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
14 changes: 10 additions & 4 deletions notations/examples/packages/documents/README.md
Original file line number Diff line number Diff line change
@@ -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 <adopter-root>` 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
Expand Down
6 changes: 3 additions & 3 deletions notations/packages/documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"). 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. |
Expand Down Expand Up @@ -167,7 +167,7 @@ Run by `@transitrix/documents-cli validate <documents-folder>` (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.
Expand All @@ -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).

---

Expand Down
39 changes: 39 additions & 0 deletions packages/documents-cli/README.md
Original file line number Diff line number Diff line change
@@ -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.
50 changes: 50 additions & 0 deletions packages/documents-cli/documents.mjs
Original file line number Diff line number Diff line change
@@ -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 <documents-folder>');
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;
}
}
37 changes: 37 additions & 0 deletions packages/documents-cli/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions packages/documents-cli/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
73 changes: 73 additions & 0 deletions packages/documents-cli/src/validate.mjs
Original file line number Diff line number Diff line change
@@ -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]}-<lowercase-slug>-<positive-integer> 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;
}
Loading
Loading