From e294f18b635d6db4df36556549834d3aebc97e5d Mon Sep 17 00:00:00 2001 From: transitrix Date: Fri, 2 Oct 2026 23:54:44 +0400 Subject: [PATCH 01/26] feat: add requirements analysis skill --- transitrix/README.md | 1 + .../skills/requirements-analysis/README.md | 46 ++++++ .../skills/requirements-analysis/SKILL.md | 133 ++++++++++++++++++ 3 files changed, 180 insertions(+) create mode 100644 transitrix/skills/requirements-analysis/README.md create mode 100644 transitrix/skills/requirements-analysis/SKILL.md diff --git a/transitrix/README.md b/transitrix/README.md index 5e185948..e51413cd 100644 --- a/transitrix/README.md +++ b/transitrix/README.md @@ -51,6 +51,7 @@ Regenerate with `node packages/plugin-examples/src/generate.mjs`; CI (`.github/w | **Ingest** | `/transitrix:ingest` | Turns raw organisational documents — interviews, policies, org charts — into `field`-zone artefacts and typed canon candidates, then stages a human review queue | 0.6.0 | | **Repo-check** | `/transitrix:repo-check` | Read-only health check: methodology version, coverage-profile resolution, per-TYPE element counts, and integrity flags — all data-free, safe to share externally | 0.6.0 | | **Report** | `/transitrix:report` | Produces a reproducible compliance report (obligation × subject impact matrix or per-regime coverage metric) via a committed view-config artefact and the `@transitrix/cli` renderer | 0.6.0 | +| **Requirements analysis** | `/transitrix:requirements-analysis` | [Release-scoped PRODUCT/APPLICATION analysis](skills/requirements-analysis/README.md) through the supported CLI candidate; exact facts, provenance and proposed actions | 7.0.0 + declared 0.3 CLI support | | **Reg-intel** | `/transitrix:reg-intel` | Monitors regulatory sources, classifies new instruments against the organisation's obligation catalogue, and stages a review digest for human triage | 0.6.0 | | **ADR** | `/transitrix:adr` | Runs a Context/Decision/Consequences interview and lands the result as a gated Architecture Decision Record (`operations/decisions/ADR-YYYY-MM-DD-*.md`), never self-accepting and never editing an accepted record's body | 0.6.0 | | **Feedback** | `/transitrix:feedback` | Routes a methodology-directed finding away from data/model problems, runs a scrub-gated interview, and lands it as an anonymised `FB-NNNN` entry in `operations/feedback.md`; exports a ready-to-send message on request only, never transmits it itself | 2.1.0 | diff --git a/transitrix/skills/requirements-analysis/README.md b/transitrix/skills/requirements-analysis/README.md new file mode 100644 index 00000000..f56732d3 --- /dev/null +++ b/transitrix/skills/requirements-analysis/README.md @@ -0,0 +1,46 @@ +# Requirements-analysis skill + +Analyse the requirements of a PRODUCT or APPLICATION for a selected release +and date, optionally filtered by project. Invoke `/transitrix:requirements-analysis` +or give any assistant [SKILL.md](SKILL.md); the instructions use the standalone +CLI and do not depend on an editor or a particular assistant runtime. + +This is part of the existing [Transitrix plugin](../../README.md). Install or +update that plugin using its normal instructions; hosts discover +`skills/requirements-analysis/SKILL.md` alongside the other skills. There is no +separate skill package or personal installation channel. The shared plugin +version and methodology release process remain authoritative. + +## Examples + +- “Analyse APPLICATION-ALPHA-1, RELEASE-ALPHA-2, as at 2026-09-24, for + ACTION-ALPHA-1.” An internal application needs no manufactured product. +- “Analyse internal PRODUCT-ALPHA-1, RELEASE-ALPHA-2, as at 2026-09-24.” + Internal use does not turn a product into an application. +- “Analyse physical PRODUCT-ALPHA-1 at RELEASE-ALPHA-2 on 2026-09-24.” + The subject remains a product, independently of its physical form. +- “Analyse SaaS PRODUCT-ALPHA-1 at RELEASE-ALPHA-2 on 2026-09-24.” + Supporting applications are context, not implicit membership or evidence. + +These are independent synthetic selections, not an installed example catalogue. +See the [accepted four-case oracle](https://github.com/transitrix/methodology/blob/a131b1862d86f34be8feb729e1cc6ebc994c3891/notations/examples/requirement-subject-scope/README.md). +Missing essential scope prompts a question; the skill never guesses a release +or date. Omitted project means no project filter. + +## Tool and output + +The supported handoff is the built `@transitrix/cli` 2.12.0 candidate at +`bfc60f81bd0b7fe01dd9fac41ba4b1d4bc447730`, Node >=20, +`requirements-report/1` / `requirement-chain/0.3`. This is not an npm-publication +claim. CLI 2.11.0 is unsupported. See [the invocation and support checks](SKILL.md#1-resolve-scope-and-support) +before use. Missing tools or unsupported versions produce an unavailable result. + +The skill retains the exact CLI response, normalized request, invocation and +provenance as a report receipt, then separates computed facts, interpretation +and proposed actions. The receipt is a tooling artifact, not admitted model +data. Known IDs with incomplete totals remain incomplete; absent evidence never +becomes a passed verification. Recommendations do not write the model. + +For regulatory obligation matrices and compliance coverage, use the existing +[report skill](../report/README.md). It retains its own CLI and view-config +workflow unchanged. diff --git a/transitrix/skills/requirements-analysis/SKILL.md b/transitrix/skills/requirements-analysis/SKILL.md new file mode 100644 index 00000000..d27d290f --- /dev/null +++ b/transitrix/skills/requirements-analysis/SKILL.md @@ -0,0 +1,133 @@ +--- +name: requirements-analysis +description: "Analyse PRODUCT or APPLICATION requirements for an explicit release and date using the supported Transitrix scan-plus-report CLI. Return exact computed IDs, counts and diagnostics separately from interpretation and proposed actions." +when_to_use: 'User asks "analyse requirements for this application", "which product requirements lack verification", or "show release requirements gaps". For regulatory obligation matrices or compliance coverage, use the report skill instead.' +min_version: "7.0.0" +allowed-tools: Read, Write, Bash, Glob, Grep +--- + +# Requirements analysis + +Use `@transitrix/cli requirements-report` as the sole source of computed facts. +This skill is distributed in the existing [Transitrix plugin](../../README.md) +as `/transitrix:requirements-analysis`. Any assistant can read this file and +invoke the command; no editor, runtime-specific API or source import is needed. + +## 1. Resolve scope and support + +Resolve parameters from the request, then a report receipt the user explicitly +selected. Ask for missing essential scope; if no answer is available, report the +missing fields and stop. Do not guess a subject, latest release or today's date. + +| Parameter | Required choice / default | +|---|---| +| Catalogue root | Explicit root, or current directory only when it contains the intended `transitrix.yaml`. Ask if there are multiple catalogues. | +| Subject | Explicit `PRODUCT` or `APPLICATION` and exact model ID. Resolve a supplied name to an unambiguous ID with the user; never choose TYPE from internal use versus sale. | +| Release | Exact RELEASE ID belonging to the selected subject. Never substitute another release after a diagnostic. | +| As-at | Explicit valid `YYYY-MM-DD`; preserve the requested date. | +| Project | Optional ACTION(Project) ID; omission means no project filter. | +| Expected source revision | Optional full Git commit supplied by the user; otherwise no revision assertion. It does not select or check out a revision. | + +State the resolved scope and defaults before running: no project filter when +omitted, no revision assertion when omitted, JSON transport. Internal, external +and mixed use are independent of subject TYPE. A physical PRODUCT is valid; +an APPLICATION does not require creating a PRODUCT. This analysis never authors +membership, releases, vocabulary or model records. + +**Support boundary:** the caller handoff is `@transitrix/cli` **2.12.0 source +candidate**, source revision `bfc60f81bd0b7fe01dd9fac41ba4b1d4bc447730`, Node >=20, +transport `requirements-report/1`, projection `requirement-chain/0.3`, bound to +contract revision `a131b1862d86f34be8feb729e1cc6ebc994c3891`. See the +[versioned caller documentation](https://github.com/transitrix/transitrix-studio/blob/bfc60f81bd0b7fe01dd9fac41ba4b1d4bc447730/packages/cli/README.md#requirements-reports) +and [accepted scope contract](https://github.com/transitrix/methodology/blob/a131b1862d86f34be8feb729e1cc6ebc994c3891/notations/views/reports/requirement-subject-scope.md). +The methodology floor above is not a claim that 7.0.0 tools implement 0.3. + +Locate the installed executable and inspect its package documentation. If absent, +stop with “requirements analysis unavailable: supported CLI missing”. A supplied +candidate tarball can be installed in an isolated tooling directory using +`npm install --ignore-scripts /path/to/transitrix-cli-2.12.0.tgz`. Do not silently +install, upgrade or use an unpinned `npx` download. The earlier CLI 2.11.0 does not +support this command. A usage error is not evidence of interface support. +Candidate availability and npm publication are separate; do not describe the +candidate as published. For another version, obtain its declared compatible +transport/projection contract before treating its output as supported. + +## 2. Invoke and retain the receipt + +Invoke the installed binary directly, passing arguments as separate values +(quote shell values; never execute model text as commands). Example with explicit +scope; replace these synthetic IDs with the resolved selection: + +```sh +transitrix requirements-report \ + --root ./model \ + --subject-type APPLICATION --subject-id APPLICATION-ALPHA-1 \ + --release RELEASE-ALPHA-2 --project ACTION-ALPHA-1 \ + --as-at 2026-09-24 --json +``` + +For PRODUCT, change both subject TYPE and ID. Omit `--project` for an unfiltered +release report. If requested, append `--expect-source-revision `. +This is a source assertion, never a provenance override. Do not use the older +PRODUCT-only 0.2 adapter for this skill or recreate the graph from model files. + +Capture stdout, stderr and exit status separately. Preserve the complete, +unmodified JSON response and exact invocation with the analysis as its report +receipt. The response's `request` is the normalized scope/config; no new model +notation or view-config schema is needed. For a saved report, use the user's +chosen report-output location outside `canon/`, `field/` and `codex/`, avoid +replacing existing files, and save the invocation and diagnostics alongside it. +If no output location was requested, retain the response as a session artifact +and disclose its location and lifetime. Do not commit automatically. + +On rerun, use the retained request's explicit scope with an available local root +and the same compatible tool. Compare returned provenance, including the content +snapshot, instead of claiming identical input from the same Git commit alone. +A dirty working tree can differ at one revision; non-Git sources can still have +content provenance. Two scans detect observed changes, not atomic capture. + +## 3. Validate the returned envelope + +Read the entire response before summarizing. Check `schemaVersion`, `tool` +(name/version/source revision), returned request, source provenance, projection +contract version/revision and completeness against the selected interface. +Keep `source`, `projection`, `counts` and `errors` intact. Unknown versions, +missing required fields, malformed JSON, scope mismatch or inconsistent +status/exit code mean **unsupported or unavailable**, never a passed report. + +| Exit | Meaning | Required treatment | +|---|---|---| +| 0 | Complete computation | Still inspect verification failures and diagnostics; computation success is not verification success. | +| 2 | Incomplete but available | Retain known IDs, nullable totals and diagnostics. An empty known-ID list with unknown total is not zero. | +| 1 | Fatal; projection/counts null | Report the errors and unavailable result. Do not fill in totals or fall back to a previous result as current. | +| Other / no envelope | Invocation failure or unsupported interface | Preserve diagnostics and stop analysis; do not reconstruct a report. | + +Unresolved membership, invalid subject/release, missing project pairing, failed +reads and malformed data must remain visible. Absent verification definitions, +no applicable executed result, inconclusive execution and failed verification +are distinct findings. Child evidence does not verify a parent; other-release +or unqualified evidence does not verify the selected release. Do not repair +inputs or suppress diagnostics to obtain a complete result. + +## 4. Present analysis in three separate parts + +1. **Computed facts:** identify subject TYPE/ID, release, optional project, as-at, + tool/contract versions, source revision/dirty state/content snapshot and + complete/incomplete/unavailable status. Quote exact returned population, + stage, assignment and six-metric IDs/totals, with their completeness and + diagnostics. In 0.3 the retained `populations.product` key labels the + **subject population**, including APPLICATION. Do not count the ID arrays, + sum overlapping metrics, infer percentages or add a quality score. +2. **Interpretation:** explain what those specific IDs mean within this scope. + Cite returned record/edge identities and provenance for each finding; label + hypotheses and absent evidence. A complete computation can describe missing + verification; it does not certify the requirements or the business outcome. +3. **Recommended actions:** propose review of named missing sources, membership, + assignment or verification evidence, tied to the same IDs and receipt. Where + the result cannot identify an owner or cause, say so. These are proposals; + do not edit the model, create a replacement PRODUCT, transfer verification + across subjects or run an implementation workflow. + +Link the retained receipt so the reader can inspect every fact. Keep the +analysis within its catalogue audience: unlike the data-free repo-check skill, +this report contains model IDs and source details. From c1599c2f1f0ab7068a23ec824e8dd156262cbb04 Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Sat, 3 Oct 2026 19:32:17 +0400 Subject: [PATCH 02/26] fix: reconcile adoption health evidence and scanner entry points (#637) Signed-off-by: transitrix Co-authored-by: transitrix --- guides/adoption-health-profile.md | 25 +- transitrix/skills/health-profile/README.md | 70 ++- transitrix/skills/health-profile/SKILL.md | 203 +----- .../skills/health-profile/health_profile.py | 580 +++++++++--------- transitrix/skills/health-profile/scan.mjs | 350 +---------- .../tests/test_health_profile.py | 247 ++++++++ 6 files changed, 616 insertions(+), 859 deletions(-) create mode 100644 transitrix/skills/health-profile/tests/test_health_profile.py diff --git a/guides/adoption-health-profile.md b/guides/adoption-health-profile.md index c5fa1962..99fe21c5 100644 --- a/guides/adoption-health-profile.md +++ b/guides/adoption-health-profile.md @@ -8,7 +8,7 @@ license: MIT # Adoption health profile -This is a proposed review method, not a shipped command or an adoption certification. It helps an adopter identify gaps worth investigating. The repository's `repo-check` provides configuration and coverage information; it does not implement this whole profile. +This is a proposed review method, not an adoption certification. The [health-profile skill](../transitrix/skills/health-profile/README.md) ships a runnable, bounded collector for a synthetic pilot; neither it nor `repo-check` implements the whole profile. The collector reports all six indicators, marking unsupported results unavailable. It helps an adopter identify gaps worth investigating. The adopter owns the review scope, evidence and interpretation. No central telemetry, universal healthy threshold or automatic admission gate is implied. Health findings do not fail validation or CI. Compute the profile on demand; a static export is a dated snapshot, not live state. Collection and reconciliation require effort; the indicators can be incomplete or manipulated and must remain inspectable. @@ -39,4 +39,25 @@ Do not turn six measures into a single score without an explicit adopter decisio Identify a collector and its supported rules, supply the required sources and permissions, and test known valid, invalid, stale and missing-evidence cases. Publish the report's scope and collection failures alongside its results. Retain enough input identity to reproduce a calculation without exposing protected content to an unintended audience. -Until that implementation and its coverage are verified, use this as a manual review checklist and label results accordingly. Completing the checklist does not establish organisation-wide adoption, completeness or correctness. +Use the shipped collector only for its documented supported subset; use the remaining profile as a manual review checklist and label those results accordingly. Completing the checklist does not establish organisation-wide adoption, completeness or correctness. + +## Candidate metrics within this profile + +These metrics refine the existing indicators; none creates an adoption score or requires a new model field. + +| Candidate metric | Existing home | Required evidence and current collector limit | +| --- | --- | --- | +| Change acceptance time | Assertion queue operational drill-down | Actual submission and accepted-review timestamps for the stated cohort and period; exclude cancellation/administrative closure and expose held work. No workflow collector is implemented. | +| Open review age | Assertion queue operational drill-down | Actual opening timestamp, observation/effective time, review target and adopter policy. Compare age with an SLA only when one is explicitly supplied. Unavailable in the shipped subset. | +| Current validation | Validity | Executed checks bound to exact inputs and rules. The collector reuses existing atomicity checks over parsed records; full notation/schema/admission validation remains outside this subset. | +| Reference integrity | Connectedness diagnostic | Existing linter checks on the declared parsed cohort. Resolved references do not establish graph completeness; supported fields and unchecked shapes are listed in the report. | +| Requirement verification coverage | Connectedness / traceability drill-down | Declared applicable requirements and their scoped verification links/evidence/outcomes, with exclusions and unknowns. A link is not a passing verification. This collector does not compute that ratio; it never represents adoption success. | +| Review freshness | Freshness for canonical reaffirmation; queue drill-down for workflow reviews | Qualified admission date and explicit per-type decay policy for canonical records. Workflow review timestamps/policies require a separate collector and remain unavailable. | + +There is no genuinely missing seventh indicator in these candidates. Extending collection requires real sources, an explicit population and rules, and positive/negative controls. Git author time, file timestamps and invented review targets cannot stand in for those sources. + +## Reproducible collector subset + +The [scanner README](../transitrix/skills/health-profile/README.md) defines the common Python/Node entry points, dependencies, supported checks and calculations. It distinguishes parsed file classification from distinct canonical-ID inventory, and admitted inventory from an active lifecycle cohort. Reports retain effective date, observation time, revision and input hashes, rule identity, scope, numerator/denominator, exclusions and unknowns. Zero known evidence is unavailable; an empty applicable population is not applicable. + +The shipped synthetic controls exercise fresh-checkout/synchronization invariance, policy-qualified reaffirmation, absent evidence/policy, exclusions, duplicate IDs, parse failures, empty populations, and positive/negative existing atomicity/reference checks through both runnable entry points. Health findings remain informational; ordinary validator gates are unchanged. Consumer propagation and operational data collection are not established by these synthetic tests or by a source merge. diff --git a/transitrix/skills/health-profile/README.md b/transitrix/skills/health-profile/README.md index 663f2e8c..e340f755 100644 --- a/transitrix/skills/health-profile/README.md +++ b/transitrix/skills/health-profile/README.md @@ -1,46 +1,62 @@ # Health Profile Skill -Self-measurement tool for Transitrix adoption health. Runs against a repository and produces a report showing five instrumental indicators: validity, coverage, freshness, assertion-queue age/drain, and connectedness. Each indicator is sourced from two independent records; the finding is the disagreement. +An on-demand, informational snapshot of a single Transitrix catalogue. The report retains the [six-indicator profile](../../../guides/adoption-health-profile.md): denominator, validity, coverage, freshness, assertion queue and connectedness. It implements a bounded subset, with explicit unavailable/unknown results. It is not an adoption score or certification, and findings never fail a build. -The report is private to the adopter, runs in their repository, and does not gate the build (report only). +## Run -## Invoking the skill +Requires Python 3.10+ and PyYAML 6.x (`python3 -m pip install 'PyYAML>=6,<7'`). The Node entry point additionally requires Node 18+ and runs the same Python collector synchronously. Set `PYTHON` to an interpreter executable if needed (on Windows it defaults to `python`, elsewhere `python3`). Keep this directory with the repository's `tools/lint.py` to enable the existing rule checks; a copied skill without that file reports those checks unavailable. -From a Claude Code session: +From the methodology checkout: -``` -/transitrix:health-profile +```sh +python3 transitrix/skills/health-profile/health_profile.py --repo /path/to/catalogue --effective-date 2026-04-01 +node transitrix/skills/health-profile/scan.mjs --repo /path/to/catalogue --effective-date 2026-04-01 --format json --out health-report.json ``` -Or from the CLI (future, once the skill is shipped): +Both accept the same flags. `--repo` defaults to `.` and must contain `transitrix.yaml` directly; parent and nested catalogue roots are not inferred. `--effective-date` defaults to today in UTC. `--out` writes a snapshot; otherwise output goes to stdout. `--format` is `markdown` (default) or `json`. `/transitrix:health-profile` uses this same collector through the [skill procedure](SKILL.md). -``` -claude /transitrix:health-profile --repo --out -``` +Findings return exit 0. Invalid invocation, missing dependencies, invalid configuration or failure to write the report are execution errors, not health findings. JSON preserves counts, unknowns, exclusions, per-record freshness evidence and source hashes; Markdown wraps that same result without dropping evidence. Reports contain model IDs and paths; share only with the adopter's permission. + +## Supported subset + +| Indicator | Collected now | Limits | +| --- | --- | --- | +| Denominator | YAML/YML discovery, four file classes, parse/read failures, distinct parsed canonical IDs and duplicates; notation distribution | Read means parsed, not validated. No inference of an active cohort or full schema support. | +| Validity | YAML parsing and the shipped linter's existing atomicity check over unique parsed elements | Batch finding, not a per-element schema pass rate. No full CLI, admission or notation validation claim. | +| Coverage | Explicit unavailable result | No declared business-scope comparison. Notation counts are an inventory diagnostic. | +| Freshness | CONTRACT §11 decay using canonical `admitted_at`, complete recorded admission gate and explicitly configured `confidence_decay` | Unknown without evidence/policy. No mtime, Git edit-age, implicit thresholds, knowledge-object or workflow-review collector. Recorded evidence does not independently prove a review occurred. | +| Assertion queue | Explicit unavailable result | No workflow integration, timestamps, review targets or SLA assumptions. | +| Connectedness | Shipped linter's existing relation `from`/`to` and inline `parent`, `goals`, `delivers_changes`, `predecessors`, `owner_role` reference checks | Scoped batch finding only. Other relation types, full opportunity ratios, reachability, orphan age and requirement-verification coverage are unavailable. Unsupported inline value shapes remain explicit. | -## What it needs +The linter itself and its validation semantics are unchanged. These checks reuse its existing methods; broader validation still belongs to the adopter's normal validation command. Configuration is not evidence that a check ran, and two counts from this collector are not independent observations. -- A Transitrix repository (has `transitrix.yaml`) -- Python 3.7+ (for the scanner) -- Optional: `organisations//SCOPE.yaml` with file classification rules +## Population and calculation -## What it produces +Discovery visits `.yaml` and `.yml` files, excluding hidden files/trees, dependencies, symlinks and nested catalogue roots. Skipped trees are named; their contents are not counted. The four file classes are disjoint: -A markdown report with: +- **Read:** mappings under `canon/elements/` or `canon/relations/` with nonempty string `id` and `notation`. This establishes collector readability only. +- **Out of scope:** files matched by the selected `SCOPE.yaml` `exclude` regex list (matched from the start of the relative POSIX path), plus YAML symlinks. +- **Unread marker:** unsupported marked files, malformed/unreadable YAML (whose marker state may itself be unknown), or canonical files the collector cannot interpret. Read failures are also listed separately, not silently lost. +- **Foreign:** parsed files without a supported record or Transitrix marker, including ordinary configuration. -1. **Denominator** — files classified as read / out-of-scope / unread-marker / foreign -2. **Five indicators table** — each with precision (state today) and diagnosis (what changed) -3. **Actionable findings** — specific files, elements, or issues that need attention +Use `--scope /path/to/catalogue/organisations/example/SCOPE.yaml` to select an existing scope file. A sole `organisations/*/SCOPE.yaml` is selected automatically; multiple candidates require selection. Invalid exclusions stop collection. File masks are not a declared business scope. Views, Field artefacts and other marked formats remain unread-marker in this subset, even if another validator supports them. -See `SKILL.md` for full details. +The denominator reports distinct parsed IDs over parsed records (elements and relations, all lifecycle states), plus every class and duplicate path. It is a reconciliation, not a success ratio. Duplicate IDs prevent the validator batch and remain unknown for freshness. Empty populations are **not applicable**; unread or ambiguous input makes inventory partial. -## Implementation notes +Each result inherits the report context: effective date, UTC observation time, Git revision/dirty state when available, input SHA-256 hashes, selected scope/exclusions, collector rule identity/hash and executed linter version/hash. Git HEAD alone does not identify modified or untracked inputs. Collection failures and exclusions qualify every result. Comparisons require the same population, scope and rules. -**Computation home:** Skill (Claude Code agent procedure) +Validation and reference results use **one checked batch** as denominator and **one batch without findings** as numerator (0 or 1), never a record pass percentage. With no applicable elements/references, the denominator is zero and the result is not applicable. Existing linter diagnostic paths may be synthesized; the inventory records actual input paths. An excluded reference target can produce a finding in the declared scope, not proof the target is absent everywhere. -Rationale: Adopter control. The adopter runs this themselves in their own repository, at their own pace, and the output belongs to them. No central collection, no norms from us — just the facts that live in version control. +Freshness uses unique parsed canonical elements with `admission_state: active` or absent, regardless of lifecycle dates; this is an admitted inventory, **not an active-at-date cohort**. Relations and proposed/rejected elements are excluded with reasons. It requires `zone: canon`, a nonempty `admitted_by`, the standard `uniqueness`, `consistency`, `completeness` checks and every additional recorded check equal to `pass`, plus quoted `admitted_at: YYYY-MM-DD` no later than the effective date. No field is changed by collection. + +The existing manifest's `confidence_decay.defaults` and `confidence_decay.by_type.` supply `fresh_days`, `stale_days` and `floor`; per-type values override defaults. The collector requires explicit finite values with `0 <= fresh_days < stale_days` and `0 <= floor <= 1`, inventing no fallback policy. Per-record decay follows [CONTRACT §11](../../../notations/CONTRACT.md#113-freshness-decay). The reported fraction is **within fresh_days / elements with qualified date and policy**, alongside unknown count and excluded records. Zero known evidence is unavailable (or not applicable when the population is empty), never 100% fresh. This is not a composite score. + +## Reproducible synthetic pilot + +The shipped tests build temporary, synthetic catalogues and run both real entry points. They demonstrate stale evidence surviving timestamp changes, qualified reaffirmation refreshing it, and missing policy/evidence staying unknown. They also exercise scope, duplicates, empty populations, parse failures and positive/negative existing linter checks: + +```sh +python3 transitrix/skills/health-profile/tests/test_health_profile.py +``` -**Not in scope:** -- The survey layer (5–7 questions to the team) -- Diagnostic engagement -- Cross-adopter benchmarking +This supports a synthetic pilot of the subset above. Business-scope comparison, actual workflow collection, verification traceability, broader validation and consumer installation/propagation remain separate work; a successful pilot does not establish organisation-wide adoption. diff --git a/transitrix/skills/health-profile/SKILL.md b/transitrix/skills/health-profile/SKILL.md index 3930cbc7..64b02654 100644 --- a/transitrix/skills/health-profile/SKILL.md +++ b/transitrix/skills/health-profile/SKILL.md @@ -1,198 +1,35 @@ --- name: Transitrix Adoption Health Profile -description: "Measure how effectively a Transitrix adoption is working in practice. Computes five instrumental indicators (validity, coverage, freshness, assertion-queue age/drain, connectedness) over a repository's model files. Each indicator is sourced from two independent records; the measure cannot be faked without doing the work. Produces a markdown report showing the denominator (file classification), all five indicators with both readings, and the honest blind spot count." -when_to_use: 'User says "run a health check", "how is the model adoption going", "show me adoption health", "are we keeping the model current", or wants to measure whether their Transitrix adoption is actually driving work, without aspiration or self-report — just the facts that live in version control.' +description: "Collect an informational six-indicator adoption-health snapshot with explicit supported, unavailable and unknown results. Reports catalogue inventory, bounded existing linter checks and policy-qualified admission freshness; does not measure adoption success." +when_to_use: 'User asks to run a health check, inspect adoption-health evidence, or identify missing review evidence in a Transitrix catalogue.' min_version: "4.0.0" allowed-tools: Read, Bash, Glob, Grep --- # Transitrix Adoption Health Profile Skill -Measure how effectively a Transitrix adoption is working in practice — not aspiration, but what the version-controlled model actually shows. +Invoke as `/transitrix:health-profile`. Follow the [README](README.md) for the exact supported population, calculations, dependencies and CLI flags; the [profile guide](../../../guides/adoption-health-profile.md) defines the six indicators. -This directory is the **`health-profile` skill** within the `transitrix` plugin. Invoked as `/transitrix:health-profile`. +## Procedure -## What it does +1. Establish the catalogue root (`transitrix.yaml` directly inside it), effective date and intended exclusions. Do not infer business scope from folders or notation distribution. If more than one `organisations/*/SCOPE.yaml` exists, select the intended scope explicitly. +2. Verify Python 3.10+ and PyYAML 6.x are available. The Node entry point additionally needs Node 18+ and the same Python dependencies. Keep the shipped `tools/lint.py` available for its bounded checks; do not execute an arbitrary adopter-provided validator as part of this skill. +3. Run either existing entry point from the methodology checkout: -Scans a Transitrix repository's model files and produces a report showing: + ```sh + python3 transitrix/skills/health-profile/health_profile.py --repo /path/to/catalogue --effective-date 2026-04-01 + node transitrix/skills/health-profile/scan.mjs --repo /path/to/catalogue --effective-date 2026-04-01 --format json + ``` -1. **Denominator** — every file classified as read / out-of-scope / unread-marker / foreign -2. **Five instrumental indicators**, each with two readings: - - **Validity** (precision: pass %, diagnosis: failure reasons) - - **Coverage** (precision: files per notation, diagnosis: files per declared dimension) - - **Freshness** (precision: age distribution, diagnosis: stale files list) - - **Assertion Queue** (precision: oldest issue age, diagnosis: median close time) - - **Connectedness** (precision: orphan age, diagnosis: reachability % from motivations) -3. **Honest blind spot** — files we cannot read and are not skipping quietly + Pass `--scope` when selecting a scope file and `--out` only when the adopter wants a dated export. Collection never edits model files or reaffirms an element. Both commands return the same evidence and six indicator keys. +4. Read the denominator before interpreting findings: read/out-of-scope/unread-marker/foreign counts, parse failures, duplicate IDs and skipped trees. Read means parsed, never validated. Note the difference between this all-lifecycle inventory and an active-at-date cohort. +5. Report supported results with their scope, revision/input hashes, effective and observation dates, rules, numerator/denominator, unknowns and exclusions. Validity and reference checks are bounded batch checks, not a complete schema pass or graph coverage ratio. Empty denominator is not applicable, never success. +6. Explain freshness from recorded admission evidence and explicit `confidence_decay` policy. A checkout or synchronization cannot reaffirm content. Missing or invalid date/policy/gate evidence remains unknown. Recorded metadata is not independent proof a review occurred. Never substitute mtime, Git author time or default age bins. +7. Keep coverage and assertion queue unavailable until their actual sources/collectors exist. Requirement verification coverage is an unsupported traceability drill-down, not adoption success. No inferred SLA, queue drain, reachability or independent-record claim is permitted. +8. Present findings as informational investigation prompts. Do not turn results into a score, build gate, certification or automatic model mutation. Collection errors are execution failures; health findings do not fail builds. Leave ordinary validation gates intact. -## What it does not do +## Privacy and limits -- Does not fail the build or gate a pull request (report only) -- Does not store a health report as a maintained file (rendered on demand) -- Does not run a survey, diagnostic engagement, or benchmarking -- Does not collect or centralize results +Reports contain model paths and IDs and belong to the adopter. Do not send or centrally collect them without authorization. No anonymized export, survey, dashboard, benchmark or workflow integration is implemented. Retain enough input identity for reproduction without publishing private source content. -## How to run it - -``` -/transitrix:health-profile [--repo ] [--out ] -``` - -Flags, all optional: - -- `--repo ` — scan this repository (defaults to the current directory if in a Transitrix repo) -- `--out ` — write the report to a file instead of printing to stdout - -## Prerequisites - -- The target repository is a Transitrix repository (has `transitrix.yaml` at its root or in a scanned subdirectory) -- Optional: `organisations//SCOPE.yaml` exists (declares file classification rules; if absent, all files carrying Transitrix markers are treated as "read") - -## What the report shows - -### File Classification (Denominator) - -``` -Total files scanned: 42 - ✓ Read (carrying Transitrix markers, validated): 32 - - Out of scope (declared masked in SCOPE.yaml): 5 - ⚠ Unread marker (carrying Transitrix markers but not being validated): 3 [ACTIONABLE] - ~ Foreign (non-Transitrix files, neutral count): 2 -``` - -The unread-marker count is actionable: these files should either be read or have their markers removed. - -### Indicators Table - -Each indicator shows **precision** (state today) and **diagnosis** (what changed / what to look at). - -``` -| Indicator | Precision | Diagnosis | -|-----------|-----------|-----------| -| Validity | 95% pass (33/35 files) | 2 failures: FGA-001 (1 file), REL-002 (1 file) | -| Coverage | 12 notations used; PROCESS: 8 files, GOAL: 6, REQUIREMENT: 5 | Business unit coverage not aligned with declared structure | -| Freshness | 60% files edited <1mo, 25% 1-6mo, 15% >6mo | DRIVER, SCENARIO notations stale since May | -| Queue | Oldest open issue: 47 days; median close: 8 days | High drain rate; queue is live | -| Connectedness | 2 orphaned elements (no incoming motivation); 92% of active elements reachable from goals | One orphan unreachable for >180 days | -``` - -Both readings are always shown, never omitted. If the unread-marker count is large, it is displayed prominently. - -## Computation rules - -### Files are classified as: - -1. **Read** — carries Transitrix notation headers and `notation:` is in the supported set -2. **Out of scope** — listed in the adopter's `organisations//SCOPE.yaml` under `exclude:` -3. **Unread marker** — carries Transitrix notation markers but is not validated (e.g., file matches `*.ttrs.yaml` pattern but no `notation:` header, or header names an unsupported notation) -4. **Foreign** — no Transitrix markers at all - -The denominator is locked before any indicator is computed; every number reported is "of the read files" — this transparency is the only defense against rot looking respectable. - -### Validity - -- First record: linter (schema validation, required fields, enum values, reference closure) -- Second record: adopter's validation config (`notation:` headers, custom validators defined in repo) -- Finding: disagreement between the two - -Pass %; failure reasons by error code. - -### Coverage - -- First record: file scanner (count files per notation name) -- Second record: adopter's declared structure (roles, teams, scope declared in `organisations//SCOPE.yaml` or inferred from folder structure) -- Finding: coverage not aligning with declared structure - -Files per notation; files per declared dimension. - -### Freshness - -- First record: file system `mtime` (last edit date) -- Second record: adopter's refresh cycle (when was the planning cycle, what notations were revised) -- Finding: files not touched during announced revision window - -Age distribution (histogram); list of stale files (those older than adopter's declared threshold or > 1 year by default). - -### Assertion Queue - -- First record: git log over `canon/**`, `field/**` looking for embedded issues/assertions (open/resolved status in model) -- Second record: adopter's issue-resolution process (issues closed in their workflow) -- Finding: unresolved items in model or resolved items not recorded in it - -Oldest open issue age; median close time (drain rate). - -### Connectedness - -- First record: graph traversal (which elements are reachable from at least one DRIVER/GOAL/RISK/INCIDENT — motivations) -- Second record: adopter's declared role structure (who owns what, inferred or declared in SCOPE.yaml) -- Finding: orphaned elements, or elements not tied to anyone's declared responsibility - -Orphan age (oldest unreachable element); percentage of active elements reachable from motivations. - ---- - -## Step 0 — Repository pre-check - -Before running: - -```bash -# Is this a Transitrix repository? -ls transitrix.yaml || echo "Not a Transitrix repo" -``` - -If `transitrix.yaml` does not exist at the root, the skill will scan subdirectories but may report a large "foreign" file count if the repo structure is unclear. - ---- - -## Step 1 — Run the scan - -```bash -/transitrix:health-profile -``` - -Or with options: - -```bash -/transitrix:health-profile --repo /path/to/other/repo -/transitrix:health-profile --out health-report.md -``` - -The skill scans the model files, computes all five indicators, and prints a markdown report. - ---- - -## Step 2 — Read the report - -The report is structured in three sections: - -1. **Denominator and blind spots** — file classification, honest count of files we cannot read -2. **Indicators table** — all five indicators with precision and diagnosis -3. **Actionable findings** — specific files/ids where action is needed (stale files, orphans, unread markers, overdue issues) - -Focus on: - -- **Unread marker count** — are files being skipped that shouldn't be? -- **Stale file list** — when were these last touched, and why? -- **Drain rate** — is the queue growing or draining? (age, not length) -- **Orphan age** — is there one hanging around, or many transient ones? - -## Data privacy and sharing - -The report contains file paths and element IDs from the model, so it's private to the repository and organization. A `--data-free` option (future) will produce the same indicator numbers without paths, safe to share outside the organization. - ---- - -## Not in scope (deferred items from the spec) - -- **Phase detection** — which edits count as "response" to an assertion (deferred; likely an edit that closes an issue, depends on adopter workflow) -- **Anonymous survey** — the 5–7 questions to the team (deferred; shaped by field work) -- **Cross-adopter benchmarking** — norms and percentiles (deferred; requires aggregation and explicit consent) - -## Accepting the report - -You have a successful adoption-health run when: - -1. The report shows the denominator clearly, with honest unread-marker and foreign file counts. -2. All five indicators appear with both readings (precision and diagnosis). -3. Specific actionable findings are listed (stale files, orphans, overdue issues, unread markers). -4. The report did not fail your build or gate a PR (report only). +The synthetic controls are runnable using the command in the README. Passing them demonstrates the delivered subset, not operational completeness or consumer deployment. diff --git a/transitrix/skills/health-profile/health_profile.py b/transitrix/skills/health-profile/health_profile.py index c21482e2..f17fa234 100644 --- a/transitrix/skills/health-profile/health_profile.py +++ b/transitrix/skills/health-profile/health_profile.py @@ -1,334 +1,300 @@ #!/usr/bin/env python3 -""" -Transitrix Adoption Health Profile Scanner - -Measures how effectively a Transitrix adoption is working by computing five -instrumental indicators from two independent records each. Produces a markdown -report showing the denominator (file classification), all indicators with both -readings (precision and diagnosis), and actionable findings. - -Usage: - python health_profile.py [--repo ] [--out ] -""" - -import os -import sys -import json -import yaml +"""Informational, evidence-bound subset of the six-indicator health profile.""" import argparse -import subprocess +from collections import Counter, defaultdict +from datetime import date, datetime, timezone +import hashlib +import importlib.util +import json +import math +import os from pathlib import Path -from datetime import datetime, timedelta -from collections import defaultdict import re +import subprocess +import sys -def find_repo_root(start_path="."): - """Find the root of a Transitrix repository (has transitrix.yaml).""" - current = Path(start_path).resolve() - for _ in range(10): # Limit depth - if (current / "transitrix.yaml").exists(): - return current - parent = current.parent - if parent == current: - return None # Reached filesystem root - current = parent - return None - -def load_yaml(path): - """Load a YAML file, returning None if not found or invalid.""" - try: - with open(path, 'r', encoding='utf-8') as f: - return yaml.safe_load(f) - except: - return None - -def get_file_mtime_days(path): - """Get days since file was last modified.""" - try: - mtime = os.path.getmtime(path) - age_seconds = time.time() - mtime - return age_seconds / (24 * 3600) - except: - return None - -def get_git_log_date(repo_path, file_path): - """Get the date of the last git commit that touched this file.""" - try: - result = subprocess.run( - ["git", "log", "-1", "--format=%aI", file_path], - cwd=repo_path, - capture_output=True, - text=True, - timeout=5 - ) - if result.returncode == 0 and result.stdout.strip(): - # Parse ISO format date - date_str = result.stdout.strip() - dt = datetime.fromisoformat(date_str.replace('Z', '+00:00')) - age = datetime.now(dt.tzinfo) - dt - return age.days - except: - pass - return None - -class HealthProfileScanner: - """Scans a Transitrix repository and computes adoption-health indicators.""" - - # Transitrix notations and their file patterns - NOTATIONS = { - 'goals': r'\.goals\.transitrix\.yaml$', - 'dgca': r'\.dgca\.transitrix\.yaml$', - 'process': r'\.process\.transitrix\.yaml$|\.bpmn\.transitrix\.yaml$', - 'capability': r'\.capability-map\.transitrix\.yaml$', - 'scenario': r'\.scenario\.transitrix\.yaml$', - 'action': r'\.action\.transitrix\.yaml$', - 'blocks': r'\.blocks\.transitrix\.yaml$', - 'application': r'\.application-catalogue\.transitrix\.yaml$', - 'product': r'\.product-catalogue\.transitrix\.yaml$', - 'compliance': r'\.compliance-impact\.transitrix\.yaml$|\.coverage-metric\.transitrix\.yaml$', - 'elements': r'^([^/]*/)*(canon|field)/[^/]+\.(process|goal|driver|assessment|requirement|term|principle|law|regulation|internal_standard|standard|policy|application|product|release|business_object|actor|role|stakeholder)\.(yaml|yml)$', - 'relations': r'^([^/]*/)*(canon|field)/(internal/)?relations/[^/]+\.yaml$', - } - - def __init__(self, repo_path): - """Initialize scanner for a repository.""" - self.repo_path = Path(repo_path).resolve() - self.results = { - 'read': [], - 'out_of_scope': [], - 'unread_marker': [], - 'foreign': [], - } - self.indicators = {} - self.scope_config = None - - def scan(self): - """Scan the repository and classify all files.""" - # Load scope configuration if it exists - scope_files = list(self.repo_path.rglob("organisations/*/SCOPE.yaml")) - if scope_files: - self.scope_config = load_yaml(scope_files[0]) - - # Scan all YAML files - for yaml_file in self.repo_path.rglob("*.yaml"): - if yaml_file.name.startswith('.'): - continue - if any(x in str(yaml_file) for x in ['node_modules', '.git', '__pycache__']): - continue - - rel_path = yaml_file.relative_to(self.repo_path) - self._classify_file(yaml_file, rel_path) - - # Compute indicators - self._compute_indicators() - - def _classify_file(self, file_path, rel_path): - """Classify a file as read/out-of-scope/unread-marker/foreign.""" - try: - content = file_path.read_text(encoding='utf-8', errors='ignore') - except: - return +import yaml - # Check if it carries Transitrix markers - has_notation_header = 'notation:' in content - has_transitrix_markers = any( - re.search(pattern, str(rel_path)) - for pattern in self.NOTATIONS.values() - ) or has_notation_header or 'element_type:' in content +RULES = "health-profile/2" +REFERENCE_FIELDS = ("parent", "goals", "delivers_changes", "predecessors", "owner_role") - # Check if it's in scope - if self.scope_config and 'exclude' in self.scope_config: - exclude_patterns = self.scope_config['exclude'] - if any(re.match(pattern, str(rel_path)) for pattern in exclude_patterns): - self.results['out_of_scope'].append(str(rel_path)) - return - # Classify - if has_notation_header and has_transitrix_markers: - self.results['read'].append(str(rel_path)) - elif has_transitrix_markers: - self.results['unread_marker'].append(str(rel_path)) - elif not has_notation_header: - self.results['foreign'].append(str(rel_path)) - else: - self.results['read'].append(str(rel_path)) +def digest(data): + return hashlib.sha256(data).hexdigest() - def _compute_indicators(self): - """Compute the five adoption-health indicators.""" - # 1. Denominator (already done in classify_file) - # 2. Validity — linter pass rate - self._compute_validity() - # 3. Coverage — files per notation - self._compute_coverage() - # 4. Freshness — age distribution - self._compute_freshness() - # 5. Assertion Queue — age and drain rate - self._compute_queue() - # 6. Connectedness — orphan age and reachability - self._compute_connectedness() - def _compute_validity(self): - """Compute validity indicator (linter pass rate).""" - # This would require running the actual linter - # For now, report that it needs the lint.py run - self.indicators['validity'] = { - 'precision': 'Requires lint.py run against canon/', - 'diagnosis': 'No linter invoked in this run' - } +def iso_date(value): + # CONTRACT dates are quoted ISO calendar dates; do not silently coerce YAML dates. + if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value): + raise ValueError("expected a quoted YYYY-MM-DD date") + return date.fromisoformat(value) - def _compute_coverage(self): - """Compute coverage indicator (files per notation).""" - notation_counts = defaultdict(int) - for file_path in self.results['read']: - for notation_name, pattern in self.NOTATIONS.items(): - if re.search(pattern, file_path): - notation_counts[notation_name] += 1 - break - self.indicators['coverage'] = { - 'precision': f'{len(notation_counts)} notations in use: ' + - ', '.join(f'{k}:{v}' for k,v in sorted(notation_counts.items(), key=lambda x: -x[1])[:5]), - 'diagnosis': 'Notation distribution uneven; see detailed list for coverage by role/scope' - } +def result(status, population, numerator=None, denominator=None, **details): + return dict(status=status, population=population, numerator=numerator, + denominator=denominator, **details) - def _compute_freshness(self): - """Compute freshness indicator (age distribution).""" - import time - today = datetime.now() - age_bins = {'<1m': 0, '1-6m': 0, '6-12m': 0, '>12m': 0} - oldest_file = None - oldest_days = 0 +def git_read(root, *args): + try: + p = subprocess.run(["git", "-C", str(root), *args], capture_output=True, + text=True, timeout=5, check=False) + return p.stdout.strip() if p.returncode == 0 else None + except (OSError, subprocess.TimeoutExpired): + return None - for file_path in self.results['read']: - full_path = self.repo_path / file_path - try: - mtime = os.path.getmtime(full_path) - file_date = datetime.fromtimestamp(mtime) - days_old = (today - file_date).days - if days_old > oldest_days: - oldest_days = days_old - oldest_file = file_path +class HealthProfileScanner: + def __init__(self, repo_path, effective_date=None, scope=None): + self.root = Path(repo_path).resolve() + self.effective_date = iso_date(effective_date or datetime.now(timezone.utc).date().isoformat()) + self.scope = Path(scope).resolve() if scope else None + self.files = {k: [] for k in ("read", "out_of_scope", "unread_marker", "foreign")} + self.failures = [] + self.records = [] + self.hashes = {} + self.skipped = [] + + def read_yaml(self, path): + if path.is_symlink(): + raise ValueError("configuration or input must not be a symbolic link") + raw = path.read_bytes() + self.hashes[path.relative_to(self.root).as_posix()] = digest(raw) + return yaml.safe_load(raw.decode("utf-8")) - if days_old <= 30: - age_bins['<1m'] += 1 - elif days_old <= 180: - age_bins['1-6m'] += 1 - elif days_old <= 365: - age_bins['6-12m'] += 1 + def scan(self): + if not (self.root / "transitrix.yaml").is_file(): + raise ValueError("--repo must name a catalogue root containing transitrix.yaml") + manifest = self.read_yaml(self.root / "transitrix.yaml") + if not isinstance(manifest, dict): + raise ValueError("transitrix.yaml must contain a mapping") + # Multiple scope files cannot be silently collapsed into one organisation. + scopes = sorted(self.root.glob("organisations/*/SCOPE.yaml")) + if self.scope is None and len(scopes) > 1: + raise ValueError("multiple SCOPE.yaml files; select one with --scope") + if self.scope is None and scopes: + self.scope = scopes[0] + exclusions = [] + if self.scope: + if not self.scope.is_relative_to(self.root): + raise ValueError("--scope must be inside --repo") + config = self.read_yaml(self.scope) + if not isinstance(config, dict) or not isinstance(config.get("exclude", []), list): + raise ValueError("SCOPE.yaml must be a mapping with an optional exclude list") + if not all(isinstance(p, str) for p in config.get("exclude", [])): + raise ValueError("SCOPE exclude entries must be regular-expression strings") + exclusions = [re.compile(p) for p in config.get("exclude", [])] + + def walk_error(error): + self.failures.append({"path": Path(error.filename).relative_to(self.root).as_posix(), + "reason": "directory unreadable"}) + + for directory, dirs, names in os.walk(self.root, followlinks=False, onerror=walk_error): + base = Path(directory) + keep = [] + for name in sorted(dirs): + p = base / name + if (name.startswith(".") or name in ("node_modules", "__pycache__") + or p.is_symlink() or (p / "transitrix.yaml").exists()): + self.skipped.append(p.relative_to(self.root).as_posix()) else: - age_bins['>12m'] += 1 - except: - pass - - total = sum(age_bins.values()) - if total > 0: - pct = {k: int(100*v/total) for k,v in age_bins.items()} - precision = f"{pct['<1m']}% current (<1mo), {pct['1-6m']}% 1-6m, {pct['6-12m']}% 6-12m, {pct['>12m']}% >12m" - else: - precision = "No read files to measure" - - diagnosis = f"Oldest file: {oldest_file} ({oldest_days} days)" if oldest_file else "No files" - - self.indicators['freshness'] = { - 'precision': precision, - 'diagnosis': diagnosis - } - - def _compute_queue(self): - """Compute assertion queue indicator (age and drain rate).""" - # Look for issues in the model or in operations/ - self.indicators['queue'] = { - 'precision': 'Requires scanning operations/work-items/ for open items', - 'diagnosis': 'No queue scan implemented in this run' - } - - def _compute_connectedness(self): - """Compute connectedness indicator (orphan age and reachability).""" - self.indicators['connectedness'] = { - 'precision': 'Requires graph traversal of canon/ elements', - 'diagnosis': 'No graph scan implemented in this run' + keep.append(name) + dirs[:] = keep + for name in sorted(names): + p = base / name + if p.suffix not in (".yaml", ".yml") or name.startswith("."): + continue + rel = p.relative_to(self.root).as_posix() + if p.is_symlink(): + self.files["out_of_scope"].append(rel) + self.skipped.append(rel) + continue + if any(pattern.match(rel) for pattern in exclusions): + self.files["out_of_scope"].append(rel) + continue + marker = (rel.startswith(("canon/elements/", "canon/relations/", "field/")) + or ".transitrix." in name or ".ttrs." in name) + try: + data = self.read_yaml(p) + except (OSError, UnicodeError, yaml.YAMLError) as error: + self.files["unread_marker"].append(rel) + self.failures.append({"path": rel, "reason": type(error).__name__}) + continue + marker = marker or (isinstance(data, dict) and + any(k in data for k in ("notation", "element_type"))) + kind = ("element" if rel.startswith("canon/elements/") else + "relation" if rel.startswith("canon/relations/") else None) + if (kind and isinstance(data, dict) and isinstance(data.get("id"), str) + and data["id"].strip() and isinstance(data.get("notation"), str) + and data["notation"].strip()): + self.files["read"].append(rel) + self.records.append({"path": rel, "kind": kind, "data": data}) + else: + self.files["unread_marker" if marker else "foreign"].append(rel) + for paths in self.files.values(): + paths.sort() + grouped = defaultdict(list) + for record in self.records: + grouped[record["data"]["id"]].append(record) + duplicates = {key: [r["path"] for r in rows] for key, rows in grouped.items() if len(rows) > 1} + unique = [rows[0] for rows in grouped.values() if len(rows) == 1] + inventory = result("supported", "parsed canonical IDs (elements and relations), all lifecycle states", + len(grouped), len(self.records), duplicates=duplicates, + files=self.files, discovered=sum(map(len, self.files.values())), + collection_failures=self.failures, skipped_trees=self.skipped, + notation_distribution=dict(sorted(Counter(r["data"]["notation"] for r in self.records).items()))) + if not self.records: + inventory["status"] = "not_applicable" + if duplicates or self.failures or self.files["unread_marker"]: + inventory["status"] = "partial" + validity, connectedness, validator = self.validate(unique, duplicates) + revision = git_read(self.root, "rev-parse", "HEAD") + dirty = git_read(self.root, "status", "--porcelain", "--untracked-files=normal") + self.report_data = { + "context": {"rules": RULES, "collector_sha256": digest(Path(__file__).read_bytes()), + "python_version": sys.version.split()[0], "pyyaml_version": yaml.__version__, + "effective_date": self.effective_date.isoformat(), + "observed_at": datetime.now(timezone.utc).isoformat(), + "revision": revision, "working_tree_dirty": None if dirty is None else bool(dirty), + "scope": "single catalogue; canon/elements and canon/relations; all lifecycle states", + "scope_file": self.scope.relative_to(self.root).as_posix() if self.scope else None, + "exclusion_patterns": [p.pattern for p in exclusions], + "input_sha256": dict(sorted(self.hashes.items())), "validator": validator}, + "indicators": { + "denominator": inventory, + "validity": validity, + "coverage": result("unavailable", "adopter-declared subjects and required relations", + reason="No business-scope collector; notation distribution is inventory only"), + "freshness": self.freshness(unique, duplicates, manifest), + "assertion_queue": result("unavailable", "assertions with real opening/review/outcome timestamps", + reason="No workflow collector or review targets supplied; no invented SLA"), + "connectedness": connectedness, + }, } + return self.report_data + + def validate(self, records, duplicates): + # Reuse shipped rules over the explicit parsed cohort; do not run adopter code. + validator_path = Path(__file__).resolve().parents[3] / "tools" / "lint.py" + pop = "one batch of unique parsed canonical elements and relations" + unavailable = lambda why: result("unavailable", pop, reason=why) + if duplicates: + return unavailable("duplicate IDs make the batch ambiguous"), unavailable("duplicate IDs make resolution ambiguous"), None + if not validator_path.is_file(): + return unavailable("shipped tools/lint.py is absent"), unavailable("shipped tools/lint.py is absent"), None + spec = importlib.util.spec_from_file_location("health_profile_lint", validator_path) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + engine = module.TransitrixLinter(str(self.root)) + engine.elements = {r["data"]["id"]: r["data"] for r in records if r["kind"] == "element"} + engine.relations = {r["data"]["id"]: r["data"] for r in records if r["kind"] == "relation"} + binding = {"version": module.__version__, "sha256": digest(validator_path.read_bytes()), + "checks": ["_check_atomicity", "_check_referential_integrity"]} + def run_check(method, applicable, limit): + engine.errors = [] + if not applicable: + return result("not_applicable", pop, None, 0, limit=limit) + method() + errors = [{"path": e.file, "message": e.message} for e in engine.errors] + return result("findings" if errors else "supported", pop, int(not errors), 1, + unit="batch without findings / checked batch (not record pass rate)", + findings=errors, limit=limit, + unchecked_files=self.files["unread_marker"], + excluded_files=self.files["out_of_scope"]) + validity = run_check(engine._check_atomicity, bool(engine.elements), + "Parsed YAML plus existing atomicity only; no schema/admission/full-validator pass claimed") + ref_inputs = bool(engine.relations) or any(any(d.get(k) for k in REFERENCE_FIELDS) for d in engine.elements.values()) + connectedness = run_check(engine._check_referential_integrity, ref_inputs, + "Existing from/to and parent/goals/delivers_changes/predecessors/owner_role checks only; " + "no reachability, relation-opportunity ratio or requirement-verification coverage") + # Existing linter skips non-list/non-string inline values; surface that blind spot. + connectedness["unsupported_inline_shapes"] = [ + {"id": key, "field": field} for key, data in engine.elements.items() + for field in REFERENCE_FIELDS if field in data and not isinstance(data[field], (str, list))] + if connectedness["unsupported_inline_shapes"] and connectedness["status"] in ("supported", "not_applicable"): + connectedness.update(status="partial", numerator=None) + return validity, connectedness, binding + + def freshness(self, records, duplicates, manifest): + policy = manifest.get("confidence_decay") + rows = [] + excluded = [] + for record in records: + data = record["data"] + if record["kind"] != "element" or data.get("admission_state", "active") != "active": + excluded.append({"id": data["id"], "reason": "not an admitted canonical element"}) + continue + row = {"id": data["id"], "path": record["path"], "anchor": data.get("admitted_at"), "status": "unknown"} + try: + checks = data.get("gate_checks") + if (data.get("zone") != "canon" or not isinstance(data.get("admitted_by"), str) + or not data["admitted_by"].strip() or not isinstance(checks, dict) + or not {"uniqueness", "consistency", "completeness"}.issubset(checks) + or any(v != "pass" for v in checks.values())): + raise ValueError("missing or incomplete admission evidence") + anchor = iso_date(data.get("admitted_at")) + age = (self.effective_date - anchor).days + if age < 0: + raise ValueError("admission postdates effective date") + if not isinstance(policy, dict): + raise ValueError("no explicit confidence_decay policy") + defaults = policy.get("defaults", {}) + types = policy.get("by_type", {}) + override = types.get(data["notation"].upper(), {}) if isinstance(types, dict) else None + if not isinstance(defaults, dict) or not isinstance(override, dict): + raise ValueError("invalid confidence_decay policy") + rules = {**defaults, **override} + fresh, stale, floor = (rules.get(k) for k in ("fresh_days", "stale_days", "floor")) + if not all(type(v) in (int, float) and math.isfinite(v) for v in (fresh, stale, floor)): + raise ValueError("incomplete or nonnumeric confidence_decay policy") + if not (0 <= fresh < stale and 0 <= floor <= 1): + raise ValueError("invalid confidence_decay bounds") + value = 1.0 if age <= fresh else floor if age >= stale else 1 - (1 - floor) * (age - fresh) / (stale - fresh) + row.update(status="fresh" if age <= fresh else "stale" if age >= stale else "aging", + age_days=age, freshness=value, policy=rules) + except ValueError as error: + row["reason"] = str(error) + rows.append(row) + rows.extend({"id": key, "paths": paths, "status": "unknown", + "reason": "duplicate ID prevents admission evidence binding"} + for key, paths in duplicates.items()) + known = [r for r in rows if r["status"] != "unknown"] + return result("not_applicable" if not rows else "unavailable" if not known else "partial" if len(known) < len(rows) else "supported", + "unique parsed admitted canonical elements, all lifecycle states", + sum(r["status"] == "fresh" for r in known) if known else None, len(known), + unit="within declared fresh_days / elements with qualified date and explicit policy", + unknown=len(rows) - len(known), exclusions=excluded, evidence=rows, + limit="Admission metadata is recorded evidence, not independent proof the review occurred; " + "duplicate IDs stay unknown; knowledge objects and workflow reviews unsupported") def report(self): - """Generate a markdown report.""" - report = [] - report.append("# Transitrix Adoption Health Profile\n") - report.append(f"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}\n") - report.append(f"**Repository:** {self.repo_path}\n\n") - - # Denominator - report.append("## Denominator: File Classification\n") - total = sum(len(v) for v in self.results.values()) - report.append(f"**Total files scanned:** {total}\n\n") - report.append("| Classification | Count | Status |\n") - report.append("|---|---|---|\n") - report.append(f"| Read (Transitrix markers, validated) | {len(self.results['read'])} | ✓ |\n") - report.append(f"| Out of scope (declared masked) | {len(self.results['out_of_scope'])} | — |\n") - report.append(f"| Unread marker (carrying markers but not validated) | {len(self.results['unread_marker'])} | ⚠ ACTIONABLE |\n") - report.append(f"| Foreign (no Transitrix markers) | {len(self.results['foreign'])} | ~ |\n\n") - - if self.results['unread_marker']: - report.append("**Unread marker files (actionable):**\n") - for f in sorted(self.results['unread_marker'])[:10]: - report.append(f"- `{f}`\n") - if len(self.results['unread_marker']) > 10: - report.append(f"- ... and {len(self.results['unread_marker']) - 10} more\n") - report.append("\n") - - # Indicators - report.append("## Indicators\n\n") - report.append("| Indicator | Precision | Diagnosis |\n") - report.append("|---|---|---|\n") - for indicator_name in ['validity', 'coverage', 'freshness', 'queue', 'connectedness']: - if indicator_name in self.indicators: - ind = self.indicators[indicator_name] - precision = ind.get('precision', 'N/A') - diagnosis = ind.get('diagnosis', 'N/A') - report.append(f"| {indicator_name.title()} | {precision} | {diagnosis} |\n") + return "# Transitrix Adoption Health Profile\n\nInformational snapshot; no adoption score or build gate. " \ + "Unavailable and unknown are not success. Read means parsed, never validated.\n\n" + \ + "```json\n" + json.dumps(self.report_data, indent=2, default=str, ensure_ascii=False) + "\n```\n" - report.append("\n") - report.append("## Acknowledgments\n\n") - report.append("This report was generated by the Transitrix Health Profile Skill. ") - report.append("Indicators were computed from the repository's model files and are ") - report.append("private to this adopter — they are not collected or benchmarked by Transitrix. ") - report.append("The report does not fail the build; it is for informational purposes only.\n") - - return ''.join(report) def main(): - """Command-line interface for the health profile scanner.""" - parser = argparse.ArgumentParser( - description="Measure Transitrix adoption health in a repository" - ) - parser.add_argument('--repo', default='.', help='Repository path (default: current directory)') - parser.add_argument('--out', help='Write report to file instead of stdout') + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", default=".") + parser.add_argument("--out") + parser.add_argument("--scope", help="select an existing SCOPE.yaml within the catalogue") + parser.add_argument("--effective-date", help="YYYY-MM-DD; defaults to today's date") + parser.add_argument("--format", choices=("markdown", "json"), default="markdown") args = parser.parse_args() + try: + scanner = HealthProfileScanner(args.repo, args.effective_date, args.scope) + data = scanner.scan() + report = json.dumps(data, indent=2, default=str, ensure_ascii=False) + "\n" if args.format == "json" else scanner.report() + if args.out: + Path(args.out).write_text(report, encoding="utf-8") + else: + print(report, end="") + return 0 # Health findings do not gate builds; invocation/collection errors do. + except (OSError, ValueError, yaml.YAMLError, re.error) as error: + print(f"Cannot collect health profile: {error}", file=sys.stderr) + return 2 - # Find the repo root - repo_root = find_repo_root(args.repo) - if not repo_root: - print("Error: Not a Transitrix repository (no transitrix.yaml found)", file=sys.stderr) - sys.exit(1) - - print(f"Scanning repository: {repo_root}", file=sys.stderr) - - # Run the scan - scanner = HealthProfileScanner(repo_root) - scanner.scan() - - # Generate report - report_text = scanner.report() - - # Output report - if args.out: - with open(args.out, 'w', encoding='utf-8') as f: - f.write(report_text) - print(f"Report written to: {args.out}", file=sys.stderr) - else: - print(report_text) -if __name__ == '__main__': - import time - main() +if __name__ == "__main__": + sys.exit(main()) diff --git a/transitrix/skills/health-profile/scan.mjs b/transitrix/skills/health-profile/scan.mjs index 42945c9e..c0374b33 100644 --- a/transitrix/skills/health-profile/scan.mjs +++ b/transitrix/skills/health-profile/scan.mjs @@ -1,342 +1,12 @@ #!/usr/bin/env node - -/** - * Transitrix Adoption Health Profile Scanner (Node.js implementation) - * - * Scans a Transitrix repository and computes five instrumental indicators: - * - Validity (linter pass rate) - * - Coverage (files per notation) - * - Freshness (file age distribution) - * - Assertion Queue (issue age/drain rate) - * - Connectedness (orphan age, reachability) - * - * Usage: - * node scan.mjs [--repo ] [--out ] - */ - -import fs from 'fs'; -import path from 'path'; -import { fileURLToPath } from 'url'; -import { execSync } from 'child_process'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -class HealthProfileScanner { - constructor(repoPath = '.') { - this.repoPath = path.resolve(repoPath); - this.results = { - read: [], - out_of_scope: [], - unread_marker: [], - foreign: [], - }; - this.indicators = {}; - } - - /** - * Find all YAML files in the repository - */ - findYamlFiles() { - const files = []; - const walkDir = (dir) => { - try { - const entries = fs.readdirSync(dir); - for (const entry of entries) { - if (entry.startsWith('.') || entry === 'node_modules') continue; - const fullPath = path.join(dir, entry); - const stat = fs.statSync(fullPath); - if (stat.isDirectory()) { - walkDir(fullPath); - } else if (entry.endsWith('.yaml') || entry.endsWith('.yml')) { - files.push(fullPath); - } - } - } catch (e) { - // Skip inaccessible directories - } - }; - walkDir(this.repoPath); - return files; - } - - /** - * Check if a file carries Transitrix markers - */ - hasTransitrixMarkers(filePath, content) { - const relPath = path.relative(this.repoPath, filePath); - - // Check for notation header - if (content.includes('notation:')) return true; - - // Check for element_type marker - if (content.includes('element_type:')) return true; - - // Check for common Transitrix file patterns - const patterns = [ - /\.goals\.transitrix\.yaml$/, - /\.dgca\.transitrix\.yaml$/, - /\.process\.transitrix\.yaml$/, - /\.bpmn\.transitrix\.yaml$/, - /\.capability-map\.transitrix\.yaml$/, - /\.scenario\.transitrix\.yaml$/, - /\.action\.transitrix\.yaml$/, - /\.blocks\.transitrix\.yaml$/, - /\.ttrs\.yaml$/, - /(canon|field)\/(internal\/)?relations\//, - /(canon|field)\/.*\.(process|goal|driver|assessment|requirement|term|principle|codex)\.(yaml|yml)$/, - ]; - - return patterns.some(pattern => pattern.test(relPath)); - } - - /** - * Classify a single file - */ - classifyFile(filePath) { - try { - const content = fs.readFileSync(filePath, 'utf-8'); - const relPath = path.relative(this.repoPath, filePath); - - const hasMarkers = this.hasTransitrixMarkers(filePath, content); - const hasNotationHeader = content.includes('notation:'); - - if (hasMarkers && hasNotationHeader) { - this.results.read.push(relPath); - } else if (hasMarkers && !hasNotationHeader) { - this.results.unread_marker.push(relPath); - } else { - this.results.foreign.push(relPath); - } - } catch (e) { - // Skip files we can't read - } - } - - /** - * Scan the repository - */ - scan() { - console.error(`Scanning repository: ${this.repoPath}`); - const yamlFiles = this.findYamlFiles(); - console.error(`Found ${yamlFiles.length} YAML files`); - - for (const file of yamlFiles) { - this.classifyFile(file); - } - - this.computeIndicators(); - } - - /** - * Compute freshness indicator - */ - computeFreshness() { - const now = Date.now(); - const ageBins = { '<1m': 0, '1-6m': 0, '6-12m': 0, '>12m': 0 }; - let oldestFile = null; - let oldestDays = 0; - const staleFiles = []; - - for (const file of this.results.read) { - const fullPath = path.join(this.repoPath, file); - try { - const stat = fs.statSync(fullPath); - const days = Math.floor((now - stat.mtimeMs) / (1000 * 60 * 60 * 24)); - - if (days > oldestDays) { - oldestDays = days; - oldestFile = file; - } - - if (days > 365) staleFiles.push({ file, days }); - - if (days <= 30) ageBins['<1m']++; - else if (days <= 180) ageBins['1-6m']++; - else if (days <= 365) ageBins['6-12m']++; - else ageBins['>12m']++; - } catch (e) { - // Skip files we can't stat - } - } - - const total = Object.values(ageBins).reduce((a, b) => a + b, 0); - if (total > 0) { - const pct = Object.fromEntries( - Object.entries(ageBins).map(([k, v]) => [k, Math.round(100 * v / total)]) - ); - return { - precision: `${pct['<1m']}% current (<1mo), ${pct['1-6m']}% 1-6mo, ${pct['6-12m']}% 6-12mo, ${pct['>12m']}% >12mo`, - diagnosis: `Oldest file: ${oldestFile} (${oldestDays} days ago). ${staleFiles.length} files >1yr old.`, - staleFiles: staleFiles.sort((a, b) => b.days - a.days).slice(0, 5) - }; - } - - return { - precision: 'No read files to measure', - diagnosis: 'No model files found' - }; - } - - /** - * Compute coverage indicator - */ - computeCoverage() { - const notationCounts = {}; - const notationPatterns = { - 'goals': /\.goals\.transitrix\.yaml$/, - 'dgca': /\.dgca\.transitrix\.yaml$/, - 'process': /\.process\.transitrix\.yaml$|\.bpmn\.transitrix\.yaml$/, - 'capability': /\.capability-map\.transitrix\.yaml$/, - 'scenario': /\.scenario\.transitrix\.yaml$/, - 'action': /\.action\.transitrix\.yaml$/, - 'elements': /(canon|field)\/.*\.(process|goal|driver|assessment|requirement|term|principle)\.yaml$/, - 'relations': /(canon|field)\/.*\/relations\//, - }; - - for (const file of this.results.read) { - for (const [name, pattern] of Object.entries(notationPatterns)) { - if (pattern.test(file)) { - notationCounts[name] = (notationCounts[name] || 0) + 1; - break; - } - } - } - - const sorted = Object.entries(notationCounts) - .sort((a, b) => b[1] - a[1]) - .slice(0, 5) - .map(([k, v]) => `${k}:${v}`) - .join(', '); - - return { - precision: `${Object.keys(notationCounts).length} notations in use: ${sorted}`, - diagnosis: 'Coverage distribution across notations — see detailed breakdown' - }; - } - - /** - * Compute all indicators - */ - computeIndicators() { - this.indicators.validity = { - precision: 'Run tools/lint.py for authoritative linter pass rate', - diagnosis: 'Linter not invoked in this run; see lint.py for full validation' - }; - - this.indicators.coverage = this.computeCoverage(); - - this.indicators.freshness = this.computeFreshness(); - - this.indicators.queue = { - precision: 'Requires scanning operations/work-items/ or embedded assertions', - diagnosis: 'Queue age/drain rate not computed in this run' - }; - - this.indicators.connectedness = { - precision: 'Requires graph traversal of canon/ elements', - diagnosis: 'Orphan detection and reachability analysis deferred to full implementation' - }; - } - - /** - * Generate markdown report - */ - generateReport() { - const now = new Date().toISOString().split('T')[0]; - const total = Object.values(this.results).reduce((sum, arr) => sum + arr.length, 0); - - let report = `# Transitrix Adoption Health Profile\n\n`; - report += `**Generated:** ${now}\n`; - report += `**Repository:** ${this.repoPath}\n`; - report += `**Computation Home:** Skill (Claude Code agent procedure)\n\n`; - - // Denominator - report += `## Denominator: File Classification\n\n`; - report += `**Total files scanned:** ${total}\n\n`; - report += `| Classification | Count | Status |\n`; - report += `|---|---|---|\n`; - report += `| Read (Transitrix markers, validated) | ${this.results.read.length} | ✓ |\n`; - report += `| Out of scope (declared masked) | ${this.results.out_of_scope.length} | — |\n`; - report += `| Unread marker (carrying markers but not validated) | ${this.results.unread_marker.length} | ⚠ ACTIONABLE |\n`; - report += `| Foreign (no Transitrix markers) | ${this.results.foreign.length} | ~ |\n\n`; - - // Honest blind spot - if (this.results.unread_marker.length > 0) { - report += `### Actionable: Unread marker files\n\n`; - report += `These files carry Transitrix markers but are not being validated. `; - report += `Should they be read, or should their markers be removed?\n\n`; - for (const f of this.results.unread_marker.slice(0, 10)) { - report += `- \`${f}\`\n`; - } - if (this.results.unread_marker.length > 10) { - report += `- ... and ${this.results.unread_marker.length - 10} more\n`; - } - report += `\n`; - } - - // Indicators - report += `## Indicators\n\n`; - report += `| Indicator | Precision | Diagnosis |\n`; - report += `|---|---|---|\n`; - - for (const [name, data] of Object.entries(this.indicators)) { - report += `| **${name.charAt(0).toUpperCase() + name.slice(1)}** | ${data.precision} | ${data.diagnosis} |\n`; - } - - report += `\n`; - - // Stale files list - if (this.indicators.freshness.staleFiles) { - report += `## Freshness Detail: Stale Files\n\n`; - report += `Files not modified in >1 year:\n\n`; - for (const { file, days } of this.indicators.freshness.staleFiles) { - report += `- \`${file}\` (${days} days old)\n`; - } - report += `\n`; - } - - // Footer - report += `## About this report\n\n`; - report += `This profile measures adoption health by computing five instrumental indicators `; - report += `from the repository's model files. Each indicator is sourced from two independent records; `; - report += `the measure cannot be faked without doing the work.\n\n`; - report += `**Three core properties:**\n\n`; - report += `1. **The adopter measures themselves.** This report lives in the repository, runs on their schedule, `; - report += `and the data belongs to them. Transitrix does not collect it.\n`; - report += `2. **No norm from us.** Convergence is measured against the adopter's declared scope, not Transitrix norms.\n`; - report += `3. **Two records, two producers.** Every indicator shown is a reconciliation; the finding is disagreement.\n\n`; - report += `The report does not fail the build and contains no judgment — it is for the adopter's own use only.\n`; - - return report; - } -} - -// Main -const args = process.argv.slice(2); -let repoPath = '.'; -let outFile = null; - -for (let i = 0; i < args.length; i++) { - if (args[i] === '--repo' && i + 1 < args.length) { - repoPath = args[++i]; - } else if (args[i] === '--out' && i + 1 < args.length) { - outFile = args[++i]; - } -} - -try { - const scanner = new HealthProfileScanner(repoPath); - scanner.scan(); - const report = scanner.generateReport(); - - if (outFile) { - fs.writeFileSync(outFile, report, 'utf-8'); - console.error(`Report written to: ${outFile}`); - } else { - console.log(report); - } -} catch (error) { - console.error(`Error: ${error.message}`); - process.exit(1); +/** Node entry point for the shared health-profile collector (Python 3.10+, PyYAML). */ +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const collector = fileURLToPath(new URL('./health_profile.py', import.meta.url)); +const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3'); +const run = spawnSync(python, [collector, ...process.argv.slice(2)], { stdio: 'inherit' }); +if (run.error) { + console.error(`Cannot start health-profile collector: ${run.error.message}. Install Python 3.10+ and PyYAML; PYTHON may name the interpreter.`); } +process.exit(run.status ?? 2); diff --git a/transitrix/skills/health-profile/tests/test_health_profile.py b/transitrix/skills/health-profile/tests/test_health_profile.py new file mode 100644 index 00000000..202f5ecd --- /dev/null +++ b/transitrix/skills/health-profile/tests/test_health_profile.py @@ -0,0 +1,247 @@ +"""Synthetic controls over the shipped collector and both command-line entry points.""" +import copy +import importlib.util +import json +import os +import shutil +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +import yaml + +SKILL = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("health_profile", SKILL / "health_profile.py") +health = importlib.util.module_from_spec(spec) +spec.loader.exec_module(health) +POLICY = {"confidence_decay": {"defaults": {"fresh_days": 30, "stale_days": 90, "floor": 0.3}}} +ELEMENT = {"notation": "goal", "id": "GOAL-EXAMPLE-1", "zone": "canon", + "admitted_at": "2026-01-01", "admitted_by": "example-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}} + + +class HealthTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.write("transitrix.yaml", POLICY) + self.element_path = "canon/elements/goals/GOAL-EXAMPLE-1.yaml" + self.write(self.element_path, ELEMENT) + + def write(self, name, data): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(yaml.safe_dump(data), encoding="utf-8") + return path + + def scan(self, effective="2026-04-01", **kwargs): + return health.HealthProfileScanner(self.root, effective, **kwargs).scan() + + def indicator(self, name="freshness", **kwargs): + return self.scan(**kwargs)["indicators"][name] + + def test_checkout_and_synchronization_cannot_refresh(self): + before = self.indicator() + self.assertEqual(before["evidence"][0]["status"], "stale") + os.utime(self.root / self.element_path, (0, 0)) + self.assertEqual(before, self.indicator()) + os.utime(self.root / self.element_path, None) + self.assertEqual(before, self.indicator()) + + def test_gate_qualified_reaffirmation_refreshes(self): + self.assertEqual(self.indicator()["numerator"], 0) + data = copy.deepcopy(ELEMENT) + data["admitted_at"] = "2026-03-31" + self.write(self.element_path, data) + self.assertEqual(self.indicator()["numerator"], 1) + data["gate_checks"]["consistency"] = "pending_review" + self.write(self.element_path, data) + self.assertEqual(self.indicator()["unknown"], 1) + self.assertIsNone(self.indicator()["numerator"]) + + def test_missing_policy_is_unavailable(self): + self.write("transitrix.yaml", {}) + self.assertEqual(self.indicator()["status"], "unavailable") + + def test_missing_date_and_future_date_are_unknown(self): + for value in (None, "2026-04-02", "not-a-date", "2026-02-30"): + with self.subTest(value=value): + data = dict(ELEMENT, admitted_at=value) + self.write(self.element_path, data) + self.assertEqual(self.indicator()["unknown"], 1) + + def test_policy_bounds_and_type_override(self): + for invalid in ({"fresh_days": 90, "stale_days": 30, "floor": .3}, + {"fresh_days": 30}, {"fresh_days": True, "stale_days": 90, "floor": .3}): + self.write("transitrix.yaml", {"confidence_decay": {"defaults": invalid}}) + self.assertEqual(self.indicator()["status"], "unavailable") + self.write("transitrix.yaml", {"confidence_decay": {**POLICY["confidence_decay"], + "by_type": {"GOAL": {"fresh_days": 100, "stale_days": 200}}}}) + self.assertEqual(self.indicator()["evidence"][0]["status"], "fresh") + + def test_aging_uses_contract_formula(self): + row = self.indicator(effective="2026-03-02")["evidence"][0] + self.assertEqual(row["age_days"], 60) + self.assertAlmostEqual(row["freshness"], .65) + + def test_proposed_is_excluded(self): + self.write(self.element_path, dict(ELEMENT, admission_state="proposed")) + data = self.indicator() + self.assertEqual(data["status"], "not_applicable") + self.assertEqual(data["denominator"], 0) + self.assertEqual(len(data["exclusions"]), 1) + + def test_duplicate_ids_remain_visible_and_ambiguous(self): + self.write("canon/elements/duplicate.yml", ELEMENT) + data = self.scan()["indicators"] + self.assertEqual(data["denominator"]["numerator"], 1) + self.assertEqual(data["denominator"]["denominator"], 2) + self.assertIn(ELEMENT["id"], data["denominator"]["duplicates"]) + self.assertEqual(data["validity"]["status"], "unavailable") + self.assertEqual(data["freshness"]["unknown"], 1) + + def test_yaml_yml_parse_failures_and_unsupported_markers(self): + self.write("canon/elements/second.yml", dict(ELEMENT, id="GOAL-EXAMPLE-2")) + self.write("views/example.transitrix.yaml", {"notation": "unknown"}) + self.write("ordinary.yaml", {"note": "notation: is just prose"}) + (self.root / "broken.yaml").write_text("broken: [", encoding="utf-8") + data = self.indicator("denominator") + self.assertEqual(len(data["files"]["read"]), 2) + self.assertEqual(len(data["files"]["unread_marker"]), 2) + self.assertIn("ordinary.yaml", data["files"]["foreign"]) + self.assertEqual(len(data["collection_failures"]), 1) + self.assertEqual(data["discovered"], sum(map(len, data["files"].values()))) + + def test_scope_exclusion_and_multiple_scope_selection(self): + scope = self.write("organisations/example/SCOPE.yaml", {"exclude": [r"^canon/elements/"]}) + data = self.indicator("denominator") + self.assertEqual(data["files"]["out_of_scope"], [self.element_path]) + self.assertEqual(data["denominator"], 0) + self.write("organisations/second/SCOPE.yaml", {}) + with self.assertRaisesRegex(ValueError, "multiple"): + self.scan() + self.assertEqual(self.scan(scope=scope)["indicators"]["denominator"]["denominator"], 0) + + def test_invalid_scope_does_not_silently_expand_population(self): + for value in ({"exclude": "canon"}, {"exclude": [23]}, ["canon"]): + self.write("organisations/example/SCOPE.yaml", value) + with self.assertRaises(ValueError): + self.scan() + + def test_nested_catalogue_and_symlink_are_excluded(self): + self.write("nested/transitrix.yaml", {}) + self.write("nested/canon/elements/other.yaml", dict(ELEMENT, id="GOAL-OTHER-1")) + (self.root / "loop").symlink_to(self.root, target_is_directory=True) + (self.root / "linked.yaml").symlink_to(self.root / self.element_path) + data = self.indicator("denominator") + self.assertEqual(data["numerator"], 1) + self.assertEqual(data["files"]["out_of_scope"], ["linked.yaml"]) + self.assertEqual(set(data["skipped_trees"]), {"loop", "nested", "linked.yaml"}) + + def test_existing_atomicity_check_positive_negative(self): + self.assertEqual(self.indicator("validity")["numerator"], 1) + self.write(self.element_path, dict(ELEMENT, relations=[])) + result = self.indicator("validity") + self.assertEqual(result["numerator"], 0) + self.assertIn("ATOMICITY", result["findings"][0]["message"]) + + def test_existing_reference_check_positive_negative(self): + self.write("canon/relations/REL-EXAMPLE-1.yaml", {"notation": "relation", "id": "REL-EXAMPLE-1", + "from": ELEMENT["id"], "to": ELEMENT["id"]}) + self.assertEqual(self.indicator("connectedness")["numerator"], 1) + self.write(self.element_path, dict(ELEMENT, parent="GOAL-MISSING-1")) + data = self.indicator("connectedness") + self.assertEqual(data["numerator"], 0) + self.assertIn("GOAL-MISSING-1", data["findings"][0]["message"]) + + def test_unsupported_reference_shape_is_not_success(self): + self.write(self.element_path, dict(ELEMENT, parent={"id": "GOAL-OTHER-1"})) + data = self.indicator("connectedness") + self.assertEqual(data["status"], "partial") + self.assertIsNone(data["numerator"]) + + def test_empty_denominators_are_not_success(self): + self.assertEqual(self.indicator("connectedness")["status"], "not_applicable") + (self.root / self.element_path).unlink() + for key in ("denominator", "validity", "freshness", "connectedness"): + self.assertEqual(self.indicator(key)["status"], "not_applicable") + + def test_unsupported_business_and_workflow_metrics(self): + data = self.scan()["indicators"] + for key in ("coverage", "assertion_queue"): + self.assertEqual(data[key]["status"], "unavailable") + self.assertIsNone(data[key]["numerator"]) + self.assertEqual(len(data), 6) + + def test_provenance_changes_with_content_not_mtime(self): + before = self.scan()["context"] + os.utime(self.root / self.element_path, None) + self.assertEqual(before["input_sha256"], self.scan()["context"]["input_sha256"]) + self.write(self.element_path, dict(ELEMENT, admitted_at="2026-03-31")) + self.assertNotEqual(before["input_sha256"], self.scan()["context"]["input_sha256"]) + self.assertEqual(before["effective_date"], "2026-04-01") + self.assertIn("sha256", before["validator"]) + + def test_both_clis_match_and_findings_exit_zero(self): + self.write(self.element_path, dict(ELEMENT, relations=[])) + reports = [] + for command in ([sys.executable, str(SKILL / "health_profile.py")], ["node", str(SKILL / "scan.mjs")]): + run = subprocess.run([*command, "--repo", str(self.root), "--effective-date", "2026-04-01", "--format", "json"], + capture_output=True, text=True, env={**os.environ, "PYTHON": sys.executable}) + self.assertEqual(run.returncode, 0, run.stderr) + data = json.loads(run.stdout) + del data["context"]["observed_at"] + reports.append(data) + self.assertEqual(reports[0], reports[1]) + self.assertEqual(reports[0]["indicators"]["validity"]["status"], "findings") + + def test_copied_checkout_keeps_freshness(self): + with tempfile.TemporaryDirectory() as other: + target = Path(other) / "checkout" + shutil.copytree(self.root, target, copy_function=shutil.copyfile) + copied = health.HealthProfileScanner(target, "2026-04-01").scan() + self.assertEqual(copied["indicators"]["freshness"], self.indicator()) + + def test_no_reference_opportunities_is_not_applicable(self): + self.write(self.element_path, dict(ELEMENT, goals=[])) + self.assertEqual(self.indicator("connectedness")["status"], "not_applicable") + self.assertEqual(self.indicator("connectedness")["denominator"], 0) + + def test_copied_skill_without_validator_is_explicit(self): + with tempfile.TemporaryDirectory() as other: + target = Path(other) / "transitrix" / "skills" / "health-profile" + target.mkdir(parents=True) + shutil.copyfile(SKILL / "health_profile.py", target / "health_profile.py") + run = subprocess.run([sys.executable, str(target / "health_profile.py"), "--repo", str(self.root), "--format", "json"], + text=True, capture_output=True) + self.assertEqual(run.returncode, 0, run.stderr) + data = json.loads(run.stdout) + self.assertEqual(data["indicators"]["validity"]["status"], "unavailable") + self.assertEqual(data["indicators"]["connectedness"]["status"], "unavailable") + + def test_symlink_configuration_does_not_escape_catalogue(self): + with tempfile.TemporaryDirectory() as other: + outside = Path(other) / "scope.yaml" + outside.write_text("exclude: []", encoding="utf-8") + link = self.root / "scope.yaml" + link.symlink_to(outside) + with self.assertRaises(ValueError): + self.scan(scope=link) + + def test_cli_output_and_invalid_root(self): + output = self.root / "report.md" + run = subprocess.run([sys.executable, str(SKILL / "health_profile.py"), "--repo", str(self.root), "--out", str(output)], capture_output=True) + self.assertEqual(run.returncode, 0) + self.assertIn("six", health.__doc__) + self.assertIn("Informational snapshot", output.read_text()) + (self.root / "transitrix.yaml").unlink() + run = subprocess.run(["node", str(SKILL / "scan.mjs"), "--repo", str(self.root)], capture_output=True, + env={**os.environ, "PYTHON": sys.executable}) + self.assertEqual(run.returncode, 2) + + +if __name__ == "__main__": + unittest.main() From 35e9c2638b5b1ccaa65e6350adebd237c1f69fb1 Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Sat, 3 Oct 2026 19:35:04 +0400 Subject: [PATCH 03/26] Define PRODUCT and APPLICATION requirements scope (#633) * docs: propose explicit requirements subject scope Signed-off-by: transitrix * docs: define accepted requirements subject contract Signed-off-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix --- guides/requirement-chain.md | 13 +- .../requirement-subject-scope/README.md | 112 +++++++++++++ .../reports/requirement-subject-scope.md | 156 ++++++++++++++++++ 3 files changed, 278 insertions(+), 3 deletions(-) create mode 100644 notations/examples/requirement-subject-scope/README.md create mode 100644 notations/views/reports/requirement-subject-scope.md diff --git a/guides/requirement-chain.md b/guides/requirement-chain.md index 5c6da549..bb02ef64 100644 --- a/guides/requirement-chain.md +++ b/guides/requirement-chain.md @@ -18,9 +18,9 @@ The proposed `source_trace` records the deliberate citation. Keep permitted code citations in `derived_from`; do not put a driver, raw research ID or documents package ID in REQUIREMENT `derived_from`. -Model the product and the project (an ACTION with `type: Project`) before scoping -requirements. The proposed product/project membership relations name where a -requirement belongs even before any release exists. `required_for` still answers +For 0.2 product reports, model the product and the project (an ACTION with +`type: Project`) before scoping requirements. The proposed product/project +membership relations name where a requirement belongs even before any release exists. `required_for` still answers which release must carry the obligation. A requirement assigned to another release is not unassigned; a broken release link needs repair, not a clean unassigned label. No script can safely recover membership from matching names or folder placement. @@ -43,3 +43,10 @@ snapshot. Unclassified, unassigned, invalid and unresolved are different states. The six categories overlap. Neither cardinality nor a child's passing test proves a parent's completion. See the [worked example](../notations/examples/requirement-chain/README.md) for the exact expected populations and drill-downs. + +For application membership, separate subject identities and physical +products, see the [accepted requirement-chain/0.3 subject-scope contract](../notations/views/reports/requirement-subject-scope.md) +and its [synthetic subject cases](../notations/examples/requirement-subject-scope/README.md). +The 0.2 contract remains unchanged; 0.3 consumers preserve product calls through an +explicit compatibility adapter. Use the added relation kinds and PRODUCT value +only with methodology and consumer versions that declare support. diff --git a/notations/examples/requirement-subject-scope/README.md b/notations/examples/requirement-subject-scope/README.md new file mode 100644 index 00000000..572eadb6 --- /dev/null +++ b/notations/examples/requirement-subject-scope/README.md @@ -0,0 +1,112 @@ +# Requirements subject scope — synthetic oracle + +**Normalized records for the accepted `requirement-chain/0.3` contract.** These +cases accompany the [subject-scope contract](../../views/reports/requirement-subject-scope.md). +They extend the [unchanged 0.2 oracle](../requirement-chain/README.md) by explicit +substitution, not by reconstructing its records or introducing a storage format. +Analysts use the exact lists to interpret report scope. These normalized examples +specify consumer behavior; they are not directly loadable catalogue files. Tool +support for the added kinds and values must be declared by the pinned versions. + +## Four independent cases + +Each case starts with **every record, absence, window, finding, expected list and +independent control in the 0.2 oracle**, including its listed R and V records +(abbreviations expand exactly as there). Cases are separate catalogue snapshots; +IDs reused between cases never coexist. Date remains 2026-09-24. All record +admission and lifecycle defaults remain unchanged. Apply these substitutions +simultaneously to every record and expected result, including controls: + +| Case / snapshot | Alpha subject replacing PRODUCT-ALPHA-1 | Beta subject replacing PRODUCT-BETA-1 | Membership and pair kinds | +|---|---|---|---| +| Internal application / subject-app-1 | APPLICATION-ALPHA-1, `type: application`, name Internal planning application | APPLICATION-BETA-1, `type: application` | Replace `product_scope` with `application_scope`; `project_product` with `project_application`. | +| Internal product / subject-internal-1 | PRODUCT-ALPHA-1, `type: service`, name Internal records service | PRODUCT-BETA-1, `type: service` | Keep both existing kinds. | +| Physical product / subject-physical-1 | PRODUCT-ALPHA-1, `type: physical_product`, name Sample sensor | PRODUCT-BETA-1, `type: physical_product` | Keep both existing kinds; use the additive PRODUCT value from P3. | +| SaaS / subject-saas-1 | PRODUCT-ALPHA-1, `type: digital_product`, name Sample hosted planning product | PRODUCT-BETA-1, `type: digital_product` | Keep both existing kinds. | + +Names describe use, not additional authored fields. Release IDs A1–A3/B1–B2, +project IDs and all requirement/verification/source IDs stay unchanged. `of` +follows the substituted subject exactly. All memberships remain explicit. For +SaaS only, also add admitted APPLICATION-SAAS-1 (`type: application`), listed +in Alpha's `supporting_apps`, with `products: [PRODUCT-ALPHA-1]`, and +RELEASE-SAAS-1 with `of: APPLICATION-SAAS-1`, no predecessor and version `1`. +Give these records the oracle's ordinary envelope. No requirement memberships, +assignments or verifications for that application are implied. + +For synthetic REL source identity, use a stable tuple `(kind, from, to)` as the +baseline tables do. An extra duplicate is distinguished by suffix `duplicate-1`. +Materialized REL files must receive ordinary unique REL IDs and preserve that +mapping in provenance. Tuple shorthand never becomes an authored field or TYPE. + +## Exact baseline results for each case + +These expected sets apply separately to all four cases for a consumer implementing +0.3. A consumer that does not support a subject, kind or value must expose unsupported +scope rather than return these numbers or silently reinterpret the records. + +| Population | Exhaustive IDs | +|---|---| +| P | R1,R2,R3,R4,R5,R6,R7,R8,R9,R10,R11,R13,R14,R15,R18,R20 | +| L, Alpha 2, no project | R1,R2,R3,R4,R5,R6,R7,R8,R13,R14,R15,R18,R20 | +| S, Alpha project, Alpha 2 | R1,R2,R3,R4,R5,R6,R7,R8,R14,R15,R18,R20 | +| Clean unassigned | R9 | +| Other-release-only | R10 | +| Invalid assignment | R11 | +| Unresolved membership | Empty, given this complete synthetic baseline | +| Inactive | R16,R17 | +| Alpha 1, Alpha project | R1,R18 | +| Alpha 3, Alpha project | R10 | +| Beta 2, Beta project | R12 | + +| Stage in S | Exhaustive IDs | +|---|---| +| Stakeholder | R1,R6 | +| System | R2,R4,R5,R14,R15,R18 | +| Software | R3,R7,R20 | +| Unclassified | R8 | + +| Metric in contract order | Exact IDs for Alpha project / Alpha 2 | +|---|---| +| Broken references | R7,R14,R15,R20 | +| No accepted source path | R5,R8,R14,R15 | +| No valid verification definition | R1,R7,R8,R14,R15 | +| Verification without applicable executed result | R2,R5,R20 | +| Applicable failed verification | R3 | +| No effective release assignment, whole subject | R9 | + +Without project, add R13 to S/System and the third metric only. All Beta 2 / Beta +project metrics are empty. Definition/result stage IDs, the 37-node unfocused +matrix, exact focus selections and all six defective-reference slots remain the +0.2 lists unchanged. R1 inherits at depth 1; R18 selects its depth-0 attachment +while retaining both source relations. V31 pass and V32 fail coexist; V4 is +executed inconclusive; V51/V52 are contextual; R1 has no definition despite R3's +executions. These assertions apply to the application case as well as products. + +## Additional independent controls + +Each row starts afresh from its named case; inherited 0.2 controls also run after +substitution. Unmentioned results are derived by the same contract; the exact +effects below do not license ignoring diagnostics outside the selected scope. + +| Control | Expected result | +|---|---| +| Application: remove R9 application_scope | Known P = baseline P minus R9; unresolved membership = {R9}; known clean-unassigned = {}; its total null, not 0. Known S and first five sets unchanged, with affected completeness exposed. Restoring the relation restores {R9} and complete total 1. | +| Application: duplicate R1 membership, project membership and A1 assignment | P/L/S and all metric IDs unchanged; retain duplicate source identities; R1 still depth 1. Removing duplicates restores baseline provenance without changing counts. | +| Application: select Beta 2 with Alpha subject | Wrong owner; scope unavailable, all six totals null. Selecting Alpha 2 restores baseline. | +| Application: remove Alpha project's project_application to Alpha | Filtered scope unavailable. Unfiltered L remains the listed 13 IDs; no guessed project. Restoring pair restores S. | +| Application: replace R11's missing release target with B2 | Invalid assignment remains {R11}; unassigned remains {R9}; S and six sets unchanged. B2's owner is not R11's membership. Adding explicit R11 membership to Beta makes this a contextual assignment for Alpha; Alpha clean-unassigned becomes {R9,R11}, invalid becomes {}. | +| Application: give R11 an additional A2 assignment, retain missing target | S gains R11; broken gains R11; no-definition gains R11. Invalid remains {R11}, unassigned remains {R9}; no-source, no-result and fail unchanged. | +| Application: set R1 A1 attachment valid_to to query date | R1 remains in L/S on 2026-09-24; at 2026-09-25 it leaves L/S and becomes unassigned alongside R9. R1 leaves no-definition; other first-five IDs unchanged. Restore null to recover baseline. | +| Application: end R18 A2 attachment 2026-09-23 | R18 stays in S through A1 at depth 1. All six metric sets unchanged; V182 still explicitly verifies A2. Ending A1 attachment too removes R18 from S and adds R18 to unassigned. | +| Application: A2 predecessor becomes B1 | Stop before B1; R12 never enters known L. Known L = baseline L minus R1; known S = baseline S minus R1; totals affected by the invalid chain are null. R18 remains direct at depth 0. Restore A1 for complete baseline. | +| Application: R9 assignment has valid_from `not-a-date` | Known clean-unassigned excludes R9; invalid-assignment flag includes R9, window activity unresolved, diagnostic retained, unassigned total null. Do not turn malformed dates into an active or absent obligation. Removing malformed relation restores baseline. | +| Application: add valid V53 verifying R5 on A2 with pass, ordinary execution defaults | No-result becomes {R2,R20}; definition/result nodes gain V53. Changing only verified_on to A1 or removing it restores no-result {R2,R5,R20}; V53 stays contextual. | +| Application: set V32 performed_at to 2026-10-01 | Applicable fail = {}; R3 remains executed via V31; all other metric sets unchanged. Future-date finding retained. Restore 2026-09-21 to recover fail {R3}. | +| SaaS: select APPLICATION-SAAS-1 / RELEASE-SAAS-1 | Proven complete empty application membership gives P=L=S={}, all six empty, complete totals 0. Product support links do not transfer Alpha requirements. A failed membership-file read instead makes scope incomplete and totals null. | +| SaaS: add explicit application_scope R3 → APPLICATION-SAAS-1 and required_for R3 → RELEASE-SAAS-1 | Application P=L=S={R3}, stage Software={R3}. Metrics: broken={}, no-source={}, no-definition={}, no-result={R3}, fail={}, unassigned={}. V31/V32 remain product-release evidence. Parent context R2,R4,R1 and their sources is traversable, never included in S. Product baseline unchanged. | +| Previous SaaS control plus valid V301 verifying R3 on RELEASE-SAAS-1 with pass | Application no-result becomes {}; other five sets unchanged. Product fail remains {R3}; no result crosses subjects. R1 still lacks its own definition. | + +Consumers must expose known contributing IDs alongside null totals when reads, +membership or predecessor validation are incomplete. A loader returning an empty +array after an error fails these controls. Equivalent headless, matrix and release +views must compare IDs and diagnostics, not just cardinalities. diff --git a/notations/views/reports/requirement-subject-scope.md b/notations/views/reports/requirement-subject-scope.md new file mode 100644 index 00000000..22405117 --- /dev/null +++ b/notations/views/reports/requirement-subject-scope.md @@ -0,0 +1,156 @@ +--- +title: "PRODUCT and APPLICATION requirements scope" +version: "0.3" +last_updated: "2026-10-02" +status: "accepted" +--- + +# PRODUCT and APPLICATION requirements scope + +**Accepted consumer contract: `requirement-chain/0.3`.** This document defines +application scope without manufacturing a PRODUCT. It extends +[requirement-chain/0.2](requirement-chain.md), whose contract and +[worked oracle](../../examples/requirement-chain/README.md) remain unchanged. +The [subject cases](../../examples/requirement-subject-scope/README.md) specify +the exact expected IDs for this contract. Contract acceptance does not establish +support in a tool version: author the added kinds and values only when the pinned +methodology vocabulary, schema and consumer versions declare support. + +## Compatibility and accepted extensions + +The source baseline is Methodology commit +`f2f1cfba08b1377ae5c770a56e92aba702afdcdb`. The retained requirement-chain/0.2 +contract and oracle originate at `97c9d41819011ead8fe192c266cba32707eae82f`. +Source support, projection implementation, contract acceptance and publication +are separate claims. + +| Concern | Source contract at the baseline | Accepted extension / support boundary | +|---|---|---| +| Subject identity | [Primitives §§7.6–7.7](../../ELEMENT_PRIMITIVES.md) define distinct PRODUCT and APPLICATION. Neither has an internal/external usage discriminator. | Select either TYPE explicitly. Internal use, sale and software/physical form do not choose the subject TYPE. No usage field is needed. | +| Physical product | PRODUCT `type` is required: `digital_product`, `service`, `platform`, `bundle`; [Products §5](../diagrams/09-products.md) repeats it. | A standalone physical product has no general type value. P3 below supplies the additive value; do not disguise it as software or a bundle. | +| Release ownership | Primitives §7.29 already admits PRODUCT or APPLICATION in `RELEASE.of`; predecessor must have the same owner. | No endpoint widening needed. Validate exact owner identity, not merely TYPE. | +| Requirement membership | [Relations §3](../../elements/17-relations.md) admits `product_scope`: REQUIREMENT → PRODUCT. `required_for` points to RELEASE. | Independent application membership is missing. P1 adds `application_scope`: REQUIREMENT → APPLICATION. Never infer membership from release assignment. | +| Project selection | `project_scope`: REQUIREMENT → ACTION(Project); `project_product`: ACTION(Project) → PRODUCT. | Keep `project_scope`; P2 adds `project_application`: ACTION(Project) → APPLICATION. No inferred project from implementation links. | +| Product/application connection | PRODUCT `supporting_apps` and APPLICATION `products` describe support. | Context only; neither conveys requirement membership, assignment nor verification. | +| Trace graph and metrics | requirement-chain/0.2 §§5–7 define trace direction, direct verification and six metrics. | Reuse unchanged, substituting explicit subject membership for product membership. Cross-subject trace context never changes counts. | +| Obligation inheritance | Relations §3.2 and [reference query](../../../scripts/release-obligations.mjs) retain active requirements and nearest predecessor attachment. | Same-owner validation and completeness must surround the query; its scalar loader and cycle-safe walk are not a complete report validator. | +| Validation | [Contract §8](../../CONTRACT.md) specifies RELEASE-001–005 and REL endpoint/window rules; requirement-chain/0.2 §9 adds consumer obligations. | Tables are not proof of runtime support. New kinds require coordinated vocabulary, schema, endpoint validation and consumer capability changes before a consumer declares support. | + +The accepted extensions are: + +- **P1:** add only `application_scope`, REQUIREMENT → APPLICATION, using the + ordinary admitted REL envelope, one endpoint pair per record, inclusive window, + M:N membership and existing endpoint/lifecycle validation. Preserve + `product_scope` without widening its endpoints or migrating existing records. +- **P2:** add only `project_application`, ACTION with `type: Project` → APPLICATION, + on the same REL machinery. Keep PRODUCT pairing unchanged. A pair admits a + selection; it does not confer requirement membership on either endpoint. +- **P3:** add `physical_product` to the PRODUCT `type` vocabulary in the primitive, + product view and corresponding consumer schemas. It classifies a product form, + not its audience. This is an additive value; it introduces no new physical TYPE + or internal/external enum. +- **P4:** version the expanded consumer interface as `requirement-chain/0.3`. + Accept an explicit `{subject: {id, type}, release, project?, + as_at, catalogue_boundary, snapshot}`. Preserve 0.2 product calls through an + explicit adapter and reject conflicting product/subject selectors. Do not + silently advertise 0.3 from a picker change or unknown-field tolerance. + +These choices minimize changes to existing product consumers. Generalizing +`product_scope` to accept APPLICATION would contradict its published endpoint +and require a different compatibility contract. + +## Population contract + +Let `P` be the selected subject's active requirements with an active valid explicit +membership: `product_scope` for PRODUCT, `application_scope` for +APPLICATION. Keep the existing `P` output name for compatibility; label it +**subject population**. A requirement may explicitly belong to both subjects, +but the subjects remain distinct. Missing, malformed or unreadable membership +is unresolved, not evidence of exclusion, assignment, or a zero population. +Expose the catalogue's unresolved membership IDs separately; absent membership +cannot tell which subject they would belong to. + +Validate release `of == subject.id` before calculating release totals. Follow +only same-owner predecessors; stop on wrong-owner, dangling, malformed or cyclic +links with an incomplete-scope diagnostic. Never use version sorting. The release +record's lifecycle is not an extra report-date filter. Apply requirement and +relation lifecycle windows inclusively, requiring valid dates; a malformed window +cannot become an unbounded active relation. + +`L = releaseObligations(selected release, as_at) ∩ P`. Deduplicate requirements, +retain every contributing attachment identity, select the nearest surviving +attachment, and use REL ID for same-depth display ties. Ending a newer attachment +does not cancel an active ancestor attachment. Predecessors carry obligations, +never execution results. + +With no project selected, `S = L`. With project `J`, validate the appropriate +explicit project/subject pair and use `S = L ∩ project_scope(J)`. Missing pairing +makes that filtered scope unavailable. Missing project membership exposes known +IDs with incomplete filtered totals. Never infer project membership from a parent, +an ACTION ancestor, product support, or implementation work. + +For every member of `P`, inspect all modelled releases owned by that subject, +including branches, at the same date: + +| Classification | Exact condition | +|---|---| +| Assigned here | Member of `L`, whether direct or inherited. | +| Other-release-only | Effective assignment to another same-owner release, absent from `L`. | +| Clean unassigned | No effective same-owner assignment, with complete data and no active invalid assignment. | +| Invalid assignment | Active malformed/dangling `required_for`, or target release owner belongs to none of the requirement's valid explicit subject memberships. Retain any valid assignments too; this flag can overlap assigned here. | +| Contextual assignment | Assignment to a different explicitly declared subject; does not assign this subject's release. | +| Unresolved membership | Insufficient membership/catalogue data; retain known IDs and diagnostics, total unknown. | + +Retired and future requirements are outside active populations. Expired invalid +relations remain history rather than active assignment blockers. Missing input, +missing selection, wrong TYPE, invalid ownership and a proven empty set are +separate states. Known empty IDs under incomplete data have `total: null`, not 0. + +## Trace and evidence contract + +Use exactly the trace kinds and independent upstream/downstream walks from 0.2 +§5. A cross-subject requirement reached by an explicit source/decomposition edge +may appear as labelled context. Do not walk sideways through a shared ancestor. +Membership, supporting applications, release assignment, `depends_on`, project +pairing and assembly links do not expand trace traversal or add members to `S`. +The unfocused graph includes only necessary upstream context and direct +verification records, not every requirement of a related subject. + +Definitions attach directly to their `verifies` requirement. Execution requires +`verified_on` equal to the selected release, a valid definition and active valid +execution fields under 0.2 §6. Other-release and unqualified evidence remain +context. A child pass never covers its parent; no predecessor, product/application +support link or shared protocol text transfers a result. Active pass and fail +coexist; inconclusive is executed, and `not_yet_run` is not. Preserve malformed, +historical and future execution findings and their source navigation. + +## Six metrics and consumer result + +Let `V(r)` and `E(r)` retain the 0.2 definitions. No Phase 2 metric or overall +quality score is added. Each metric is a distinct requirement-ID set: + +| Metric | Population and predicate | +|---|---| +| Broken references | `r ∈ S`, with a defective reference attributed under 0.2 §7; retain reference-slot and unattributable inventories separately. | +| No accepted source path | `r ∈ S`, no valid upstream path to NEED, DRIVER, permitted codex or descriptor-bearing Field document. | +| No valid verification definition | `r ∈ S`, `V(r)` empty. | +| Verification without applicable executed result | `r ∈ S`, `V(r)` nonempty and `E(r)` empty. | +| Applicable failed verification | `r ∈ S`, at least one fail in `E(r)`. | +| No effective release assignment | Clean unassigned subset of whole `P`, across all same-owner releases, independent of project filter. | + +The result retains scope and immutable source provenance, sorted distinct +`P/L/S`, assignment/stage/metric IDs, all contributing edges and attachment +identities, context reasons, and attributable/unattributable diagnostics. Each +set carries completeness and a nullable total. Broken population inputs do not +fabricate complete metric totals. A valid empty population can have six zero +counts; an unavailable population cannot. + +Both reports, exports and a supported headless interface must consume one +projection. Focus, full/adjacent-pair mode, scrolling and navigation operate on +that graph and never recalculate populations. Cache keys include explicit subject +TYPE/ID, release, optional project, date, catalogue and content provenance. Refresh +publishes one new projection atomically; failed reads retain an explicitly stale +snapshot or unavailable state. Consumer support requires exact contract/oracle +revision binding and automated positive/negative evidence against all four subject +cases and their independent controls. A consumer must declare its supported +contract version separately from the version of this document. From b5194690631e3f597aaf939a6a0bc8ba6df379cf Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Sat, 3 Oct 2026 20:36:24 +0400 Subject: [PATCH 04/26] Document reproducible synthetic health-profile cases (#638) Signed-off-by: transitrix Co-authored-by: transitrix --- transitrix/skills/health-profile/README.md | 2 + .../skills/health-profile/examples/README.md | 154 ++++ .../examples/synthetic-pilot.json | 796 ++++++++++++++++++ .../tests/test_health_profile.py | 49 ++ 4 files changed, 1001 insertions(+) create mode 100644 transitrix/skills/health-profile/examples/README.md create mode 100644 transitrix/skills/health-profile/examples/synthetic-pilot.json diff --git a/transitrix/skills/health-profile/README.md b/transitrix/skills/health-profile/README.md index e340f755..c76d242b 100644 --- a/transitrix/skills/health-profile/README.md +++ b/transitrix/skills/health-profile/README.md @@ -53,6 +53,8 @@ The existing manifest's `confidence_decay.defaults` and `confidence_decay.by_typ ## Reproducible synthetic pilot +The [declared synthetic examples](examples/README.md) provide 21 case populations, independent expected results and commands to inspect both entry points. They distinguish scanner output from manual edge and verification semantics. + The shipped tests build temporary, synthetic catalogues and run both real entry points. They demonstrate stale evidence surviving timestamp changes, qualified reaffirmation refreshing it, and missing policy/evidence staying unknown. They also exercise scope, duplicates, empty populations, parse failures and positive/negative existing linter checks: ```sh diff --git a/transitrix/skills/health-profile/examples/README.md b/transitrix/skills/health-profile/examples/README.md new file mode 100644 index 00000000..57d1e7fc --- /dev/null +++ b/transitrix/skills/health-profile/examples/README.md @@ -0,0 +1,154 @@ +# Synthetic health-profile pilot + +These examples let a catalogue maintainer reproduce the published collector's +supported subset and see where a green batch result stops. They contain invented +records only. They are not live adoption evidence, full notation-valid model +examples, or a maintained health-report store. + +[synthetic-pilot.json](synthetic-pilot.json) declares the populations and expected +results independently of scanner output. `base_files` is a seven-record catalogue: +a root GOAL, ACTION, REQUIREMENT, APPLICATION, RELEASE, VERIFICATION and one REL. +Each case replaces complete files using `replace_files`, then removes +`remove_files`. There is no deep merge or implicit addition of records. The +manifest is foreign configuration, not a canonical record. Scope files are also +foreign configuration; their exclusions are listed separately. + +The effective date is **2026-04-01**, the collector rules are **health-profile/2**, +and the scope is one synthetic catalogue, all lifecycle states. All six elements +start with qualified admission metadata dated March 31 and an explicit 30/90-day +decay policy with floor 0.3. The REL is excluded from freshness. Every case declares +all six indicator results, numerators, denominators and file/freshness exclusions. +These are predeclared expectations, not captured reports. + +## What the expected results mean + +Validity is the existing atomicity batch check. Connectedness is the existing +reference batch check, **not typed graph validation**. Their denominator is one +checked batch and their numerator is one batch without findings or zero with +findings. No opportunity has denominator zero and status `not_applicable`. +Inventory counts distinct parsed IDs over parsed records. It does not collapse a +REL record into an element or claim that every record passed its notation schema. +Freshness counts qualified fresh elements over elements with usable admission and +policy evidence, keeping unknowns separate. + +`manual_semantics` is a hand-declared explanation, **not a collector result or new +metric contract**. It is grounded in the [field-purpose mapping](../../../../notations/field-purpose.md#relationships-and-one-count-per-edge). +The ACTION serves the GOAL (the stored edge is ACTION → GOAL); the GOAL has no +parent. Inline `goals` and its canonical `action_goal` REL represent one edge, with +REL precedence. An expired REL without an inline copy contributes no active edge. +The current scanner neither deduplicates semantic edges nor applies their windows; +it checks references in an all-lifecycle inventory. It can therefore flag an +obsolete inline target even when a REL supplies the intended semantic edge. + +For the manual verification expectation only, select `RELEASE-PILOT-1` and the +exact REQUIREMENT statement and acceptance criterion in each materialized case. +A qualifying pass requires a targeting `pass` record, the selected release, a +nonempty synthetic receipt that explicitly names the same requirement text and +release, and no conflicting outcome for that pair. This deliberately narrow pilot +predicate is **not** a schema rule, the existing requirement trace-closure rule, +or independent evidence of a real execution. The base receipt names the original +one-second criterion. Changing that criterion, omitting evidence or the tested +release, or introducing a conflicting result leaves qualifying coverage unknown. +An explicit fail is known non-passing; inconclusive, not-yet-run and missing records +are unknown. Null never means zero or success. A zero requirement population is +not applicable, not full coverage. + +The collector does **not** calculate this predicate. `verifies`, `verified_on`, +outcomes, evidence and their content binding are outside its reference checks. +Even a wrong-type verification target can produce a clean connectedness batch. +Do not turn the manual values into observed coverage. Coverage and assertion queue +remain `unavailable` with null counts in every case: there is no business-scope or +workflow collector. Missing decay policy additionally leaves freshness unavailable; +no workflow review policy or timestamps are invented. + +| Case | Parsed IDs/records | Fresh/known (unknown) | Validity; references | Manual distinction | +| --- | --- | --- | --- | --- | +| paired-edge | 7/7 | 6/6 (0) | pass; pass | One semantic edge, one evidence-qualified synthetic pass | +| inline-only | 6/6 | 6/6 (0) | pass; pass | Same edge through inline fallback | +| rel-precedence | 7/7 | 6/6 (0) | pass; finding | REL wins semantically; linter still checks inline | +| valid-root | 1/1 | 1/1 (0) | pass; N/A | Parentless root; no requirements | +| broken-target | 6/6 | 5/5 (0) | pass; finding | Target absent in complete fixture | +| excluded-target | 6/6 | 5/5 (0) | pass; finding | Target exists outside selected scope; global state unknown | +| expired-relation | 7/7 | 6/6 (0) | pass; pass | No active edge; historical REL stays in inventory | +| atomicity-finding | 7/7 | 6/6 (0) | finding; pass | Embedded relations rejected | +| verification-fail | 7/7 | 6/6 (0) | pass; pass | Known non-passing; trace closure is different | +| verification-inconclusive | 7/7 | 6/6 (0) | pass; pass | Unknown passing coverage | +| verification-not_yet_run | 7/7 | 6/6 (0) | pass; pass | No execution result | +| verification-missing | 6/6 | 5/5 (0) | pass; pass | No verification record | +| verification-conflict | 8/8 | 7/7 (0) | pass; pass | Pass/fail conflict unresolved | +| pass-without-evidence | 7/7 | 6/6 (0) | pass; pass | Edge and pass alone insufficient | +| pass-without-release | 7/7 | 6/6 (0) | pass; pass | Tested release unspecified | +| changed-requirement | 7/7 | 6/6 (0) | pass; pass | Receipt does not cover revised criterion | +| wrong-verification-type | 7/7 | 6/6 (0) | pass; pass | GOAL target is not validated by this collector | +| missing-policy | 7/7 | unavailable/0 (6) | pass; pass | Explicit unknown admission freshness | +| incomplete-admission | 7/7 | 5/5 (1) | pass; pass | Pending gate cannot establish freshness | +| empty-scope | 0/0 | N/A/0 (0) | N/A; N/A | Seven excluded records | +| empty-catalogue | 0/0 | N/A/0 (0) | N/A; N/A | No records or exclusions | + +Scope exclusion is the portable inaccessible-target control here. It does not +simulate an operating-system permission failure. A not-found diagnostic alone +cannot distinguish a globally absent target from one the collector could not +read. Inspect scope/exclusions and collection failures before interpreting it. + +## Reproduce + +Use the [documented dependencies](../README.md#run): Python 3.10+, PyYAML 6.x and +Node 18+ for both entry points. From the methodology checkout, compare every case +against both entry points with the existing regression suite: + +```sh +python3 transitrix/skills/health-profile/tests/test_health_profile.py +``` + +To inspect one case, run the following from a clean checkout of the revision being +verified. Change `paired-edge` to any case ID in the table. It materializes only a +temporary catalogue and emits a synthetic receipt to stdout; retain that output +outside the product repository if needed. The wrapper binds the source revision +and fixture hash to both actual reports, including their observation time, +collector/validator hashes, input hashes, scope, exclusions and six result sets. +A temporary catalogue has no Git history: its report `context.revision` is null; +the wrapper's `source_revision` identifies the methodology and fixture source, +not invented catalogue history. + +```sh +python3 - paired-edge <<'PY' +import hashlib, json, os, subprocess, sys, tempfile +from pathlib import Path +import yaml + +skill = Path('transitrix/skills/health-profile').resolve() +raw = (skill / 'examples/synthetic-pilot.json').read_bytes() +fixture = json.loads(raw) +case = next(c for c in fixture['cases'] if c['id'] == sys.argv[1]) +receipt = { + 'kind': fixture['kind'], 'case': case['id'], + 'source_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(), + 'source_dirty': bool(subprocess.check_output(['git', 'status', '--porcelain'], text=True)), + 'fixture_sha256': hashlib.sha256(raw).hexdigest(), + 'expected': case['expected'], + 'manual_semantics_not_observed': case['manual_semantics'], 'reports': {}, +} +with tempfile.TemporaryDirectory() as directory: + files = {**fixture['base_files'], **case['replace_files']} + for name in case['remove_files']: + del files[name] + for name, data in files.items(): + path = Path(directory) / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(yaml.safe_dump(data, sort_keys=True), encoding='utf-8') + for entry, command in [('python', [sys.executable, str(skill / 'health_profile.py')]), + ('node', ['node', str(skill / 'scan.mjs')])]: + output = subprocess.check_output( + [*command, '--repo', directory, '--effective-date', fixture['effective_date'], + '--format', 'json'], text=True, env={**os.environ, 'PYTHON': sys.executable}) + receipt['reports'][entry] = json.loads(output) +print(json.dumps(receipt, indent=2)) +PY +``` + +The regression suite compares declared counts/statuses/exclusions and entry-point +parity; it does not compute the manual semantic answers. Existing controls remain +in place for duplicate IDs, stale/reaffirmed evidence, input failures, unsupported +reference shapes, policy bounds, scope selection and copied-skill limitations. +Consumer installation, broader validators, typed/lifecycle-aware graph resolution, +requirement evidence verification and real workflow observations remain separate. diff --git a/transitrix/skills/health-profile/examples/synthetic-pilot.json b/transitrix/skills/health-profile/examples/synthetic-pilot.json new file mode 100644 index 00000000..64d1eff1 --- /dev/null +++ b/transitrix/skills/health-profile/examples/synthetic-pilot.json @@ -0,0 +1,796 @@ +{ + "kind": "synthetic-only", + "effective_date": "2026-04-01", + "profile": "health-profile/2", + "base_files": { + "transitrix.yaml": { + "confidence_decay": { + "defaults": {"fresh_days": 30, "stale_days": 90, "floor": 0.3} + } + }, + "canon/elements/GOAL-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "GOAL-PILOT-1", + "notation": "goal", + "name": "Synthetic response goal", + "level": 1 + }, + "canon/elements/ACTION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "ACTION-PILOT-1", + "notation": "action", + "name": "Synthetic response work", + "type": "Initiative", + "goals": [ + "GOAL-PILOT-1" + ] + }, + "canon/elements/REQUIREMENT-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "REQUIREMENT-PILOT-1", + "notation": "requirement", + "name": "Synthetic response obligation", + "statement": "Respond within one second", + "acceptance_criteria": [ + "Response time is at most one second" + ] + }, + "canon/elements/APPLICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "APPLICATION-PILOT-1", + "notation": "application", + "name": "Synthetic service" + }, + "canon/elements/RELEASE-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "RELEASE-PILOT-1", + "notation": "release", + "name": "Synthetic service v1", + "of": "APPLICATION-PILOT-1", + "version": "1.0.0" + }, + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "pass", + "performed_at": "2026-03-31", + "evidence": [ + {"kind": "note", "text": "Synthetic receipt: REQUIREMENT-PILOT-1 statement Respond within one second; RELEASE-PILOT-1; observed 0.5 seconds."} + ] + }, + "canon/relations/REL-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "REL-PILOT-1", + "notation": "relation", + "type": "action_goal", + "from": "ACTION-PILOT-1", + "to": "GOAL-PILOT-1" + } + }, + "cases": [ + { + "id": "paired-edge", + "purpose": "The inline and REL representations describe one semantic edge, REL taking precedence.", + "replace_files": {}, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "inline-only", + "purpose": "Inline fallback without a REL.", + "replace_files": {}, + "remove_files": [ + "canon/relations/REL-PILOT-1.yaml" + ], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 6, "denominator": 6}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "rel-precedence", + "purpose": "REL governs the semantic graph; the bounded linter still checks the obsolete inline reference.", + "replace_files": { + "canon/elements/ACTION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "ACTION-PILOT-1", + "notation": "action", + "name": "Synthetic response work", + "type": "Initiative", + "goals": [ + "GOAL-ABSENT-1" + ] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "findings", "numerator": 0, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "valid-root", + "purpose": "A root GOAL has no parent and no reference opportunity.", + "replace_files": {}, + "remove_files": [ + "canon/elements/ACTION-PILOT-1.yaml", + "canon/elements/REQUIREMENT-PILOT-1.yaml", + "canon/elements/VERIFICATION-PILOT-1.yaml", + "canon/relations/REL-PILOT-1.yaml", + "canon/elements/APPLICATION-PILOT-1.yaml", + "canon/elements/RELEASE-PILOT-1.yaml" + ], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 1, "denominator": 1}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "not_applicable", "numerator": null, "denominator": 0}, + "freshness": {"status": "supported", "numerator": 1, "denominator": 1, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [] + }, + "manual_semantics": {"active_action_goal_edges": 0, "qualified_passing_requirements": null, "requirement_population": 0} + }, + { + "id": "broken-target", + "purpose": "The GOAL file is absent in a completely readable synthetic catalogue.", + "replace_files": {}, + "remove_files": [ + "canon/elements/GOAL-PILOT-1.yaml" + ], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 6, "denominator": 6}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "findings", "numerator": 0, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 5, "denominator": 5, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 0, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "excluded-target", + "purpose": "The GOAL exists but is inaccessible to the selected scope; not globally absent.", + "replace_files": { + "organisations/pilot/SCOPE.yaml": {"exclude": ["^canon/elements/GOAL-PILOT-1.yaml$"]} + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 6, "denominator": 6}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "findings", "numerator": 0, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 5, "denominator": 5, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [ + "canon/elements/GOAL-PILOT-1.yaml" + ], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": null, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "expired-relation", + "purpose": "No inline fallback; REL ended before the effective date. Inventory still includes it.", + "replace_files": { + "canon/elements/ACTION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "ACTION-PILOT-1", + "notation": "action", + "name": "Synthetic response work", + "type": "Initiative" + }, + "canon/relations/REL-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": "2026-03-30", + "id": "REL-PILOT-1", + "notation": "relation", + "type": "action_goal", + "from": "ACTION-PILOT-1", + "to": "GOAL-PILOT-1" + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 0, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "atomicity-finding", + "purpose": "An embedded relations field violates the existing atomicity check.", + "replace_files": { + "canon/elements/GOAL-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "GOAL-PILOT-1", + "notation": "goal", + "name": "Synthetic response goal", + "level": 1, + "relations": [] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "findings", "numerator": 0, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "verification-fail", + "purpose": "Outcome does not qualify as passing coverage; trace closure is a separate predicate.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "fail", + "performed_at": "2026-03-31", + "evidence": [] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 0, "requirement_population": 1} + }, + { + "id": "verification-inconclusive", + "purpose": "Outcome does not qualify as passing coverage; trace closure is a separate predicate.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "inconclusive", + "performed_at": "2026-03-31", + "evidence": [] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "verification-not_yet_run", + "purpose": "Outcome does not qualify as passing coverage; trace closure is a separate predicate.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "not_yet_run", + "performed_at": "2026-03-31", + "evidence": [] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "verification-missing", + "purpose": "No targeting verification exists.", + "replace_files": {}, + "remove_files": [ + "canon/elements/VERIFICATION-PILOT-1.yaml" + ], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 6, "denominator": 6}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 5, "denominator": 5, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "verification-conflict", + "purpose": "Pass and fail target the same requirement and release; no resolution policy exists.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-2.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-2", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "fail", + "performed_at": "2026-03-31", + "evidence": [] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 8, "denominator": 8}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 7, "denominator": 7, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "pass-without-evidence", + "purpose": "A pass edge alone does not establish evidence-qualified coverage.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "pass", + "performed_at": "2026-03-31", + "evidence": [] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "pass-without-release", + "purpose": "An unqualified historical pass does not establish the selected release result.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "REQUIREMENT-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "pass", + "performed_at": "2026-03-31", + "evidence": [ + {"kind": "note", "text": "Synthetic receipt: REQUIREMENT-PILOT-1 statement Respond within one second; RELEASE-PILOT-1; observed 0.5 seconds."} + ] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "changed-requirement", + "purpose": "Evidence names the original requirement text, not this revised criterion.", + "replace_files": { + "canon/elements/REQUIREMENT-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "REQUIREMENT-PILOT-1", + "notation": "requirement", + "name": "Synthetic response obligation", + "statement": "Respond within half a second", + "acceptance_criteria": [ + "Response time is at most half a second" + ] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "wrong-verification-type", + "purpose": "verifies targets GOAL instead of REQUIREMENT; the bounded collector does not validate this field.", + "replace_files": { + "canon/elements/VERIFICATION-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pass", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "VERIFICATION-PILOT-1", + "notation": "verification", + "verifies": "GOAL-PILOT-1", + "verified_on": "RELEASE-PILOT-1", + "method": "test", + "protocol": "Measure synthetic response time against the one-second criterion", + "outcome": "pass", + "performed_at": "2026-03-31", + "evidence": [ + {"kind": "note", "text": "Synthetic receipt: REQUIREMENT-PILOT-1 statement Respond within one second; RELEASE-PILOT-1; observed 0.5 seconds."} + ] + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "supported", "numerator": 6, "denominator": 6, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": null, "requirement_population": 1} + }, + { + "id": "missing-policy", + "purpose": "No decay policy or workflow review policy: freshness unknown and queue unavailable.", + "replace_files": { + "transitrix.yaml": {} + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "unavailable", "numerator": null, "denominator": 0, "unknown": 6}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "incomplete-admission", + "purpose": "A pending admission check is not evidence of current freshness.", + "replace_files": { + "canon/elements/GOAL-PILOT-1.yaml": { + "zone": "canon", + "admitted_at": "2026-03-31", + "admitted_by": "synthetic-reviewer", + "gate_checks": {"uniqueness": "pass", "consistency": "pending_review", "completeness": "pass"}, + "valid_from": "2026-03-01", + "valid_to": null, + "id": "GOAL-PILOT-1", + "notation": "goal", + "name": "Synthetic response goal", + "level": 1 + } + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "supported", "numerator": 7, "denominator": 7}, + "validity": {"status": "supported", "numerator": 1, "denominator": 1}, + "connectedness": {"status": "supported", "numerator": 1, "denominator": 1}, + "freshness": {"status": "partial", "numerator": 5, "denominator": 5, "unknown": 1}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [ + "REL-PILOT-1" + ] + }, + "manual_semantics": {"active_action_goal_edges": 1, "qualified_passing_requirements": 1, "requirement_population": 1} + }, + { + "id": "empty-scope", + "purpose": "All canonical records excluded; zero denominator is not applicable.", + "replace_files": { + "organisations/pilot/SCOPE.yaml": {"exclude": ["^canon/"]} + }, + "remove_files": [], + "expected": { + "indicators": { + "denominator": {"status": "not_applicable", "numerator": 0, "denominator": 0}, + "validity": {"status": "not_applicable", "numerator": null, "denominator": 0}, + "connectedness": {"status": "not_applicable", "numerator": null, "denominator": 0}, + "freshness": {"status": "not_applicable", "numerator": null, "denominator": 0, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [ + "canon/elements/ACTION-PILOT-1.yaml", + "canon/elements/APPLICATION-PILOT-1.yaml", + "canon/elements/GOAL-PILOT-1.yaml", + "canon/elements/RELEASE-PILOT-1.yaml", + "canon/elements/REQUIREMENT-PILOT-1.yaml", + "canon/elements/VERIFICATION-PILOT-1.yaml", + "canon/relations/REL-PILOT-1.yaml" + ], + "freshness_excluded_ids": [] + }, + "manual_semantics": {"active_action_goal_edges": null, "qualified_passing_requirements": null, "requirement_population": 0} + }, + { + "id": "empty-catalogue", + "purpose": "No records and no exclusions; zero denominator is not applicable.", + "replace_files": {}, + "remove_files": [ + "canon/elements/GOAL-PILOT-1.yaml", + "canon/elements/ACTION-PILOT-1.yaml", + "canon/elements/REQUIREMENT-PILOT-1.yaml", + "canon/elements/VERIFICATION-PILOT-1.yaml", + "canon/relations/REL-PILOT-1.yaml", + "canon/elements/APPLICATION-PILOT-1.yaml", + "canon/elements/RELEASE-PILOT-1.yaml" + ], + "expected": { + "indicators": { + "denominator": {"status": "not_applicable", "numerator": 0, "denominator": 0}, + "validity": {"status": "not_applicable", "numerator": null, "denominator": 0}, + "connectedness": {"status": "not_applicable", "numerator": null, "denominator": 0}, + "freshness": {"status": "not_applicable", "numerator": null, "denominator": 0, "unknown": 0}, + "coverage": {"status": "unavailable", "numerator": null, "denominator": null}, + "assertion_queue": {"status": "unavailable", "numerator": null, "denominator": null} + }, + "out_of_scope": [], + "freshness_excluded_ids": [] + }, + "manual_semantics": {"active_action_goal_edges": 0, "qualified_passing_requirements": null, "requirement_population": 0} + } + ] +} diff --git a/transitrix/skills/health-profile/tests/test_health_profile.py b/transitrix/skills/health-profile/tests/test_health_profile.py index 202f5ecd..f5b4989e 100644 --- a/transitrix/skills/health-profile/tests/test_health_profile.py +++ b/transitrix/skills/health-profile/tests/test_health_profile.py @@ -243,5 +243,54 @@ def test_cli_output_and_invalid_root(self): self.assertEqual(run.returncode, 2) +class DeclaredPilotTests(unittest.TestCase): + """Compare consumer-authored expectations with both existing CLI entry points.""" + + def test_declared_synthetic_cases(self): + fixture = json.loads((SKILL / "examples" / "synthetic-pilot.json").read_text()) + self.assertEqual(fixture["kind"], "synthetic-only") + for case in fixture["cases"]: + with self.subTest(case=case["id"]), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + files = {**fixture["base_files"], **case["replace_files"]} + for name in case["remove_files"]: + del files[name] + for name, data in files.items(): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(yaml.safe_dump(data, sort_keys=True), encoding="utf-8") + reports = [] + for command in ([sys.executable, str(SKILL / "health_profile.py")], + ["node", str(SKILL / "scan.mjs")]): + run = subprocess.run([*command, "--repo", str(root), "--effective-date", + fixture["effective_date"], "--format", "json"], + capture_output=True, text=True, + env={**os.environ, "PYTHON": sys.executable}) + self.assertEqual(run.returncode, 0, run.stderr) + report = json.loads(run.stdout) + for indicator, fields in case["expected"]["indicators"].items(): + for field, value in fields.items(): + self.assertEqual(report["indicators"][indicator][field], value, + f"{case['id']}: {indicator}.{field}") + inventory = report["indicators"]["denominator"] + self.assertEqual(inventory["files"]["out_of_scope"], + case["expected"]["out_of_scope"]) + self.assertEqual(inventory["collection_failures"], []) + self.assertEqual(inventory["files"]["unread_marker"], []) + self.assertEqual(sorted(row["id"] for row in + report["indicators"]["freshness"]["exclusions"]), + case["expected"]["freshness_excluded_ids"]) + context = report["context"] + self.assertEqual(context["rules"], fixture["profile"]) + self.assertEqual(context["effective_date"], fixture["effective_date"]) + self.assertTrue(context["observed_at"]) + self.assertTrue(context["input_sha256"]) + self.assertTrue(context["collector_sha256"]) + self.assertTrue(context["validator"]["sha256"]) + del context["observed_at"] + reports.append(report) + self.assertEqual(reports[0], reports[1]) + + if __name__ == "__main__": unittest.main() From fe136938f2eb99e5f3a80ae2b9396da5e08ab922 Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Wed, 7 Oct 2026 02:42:10 +0400 Subject: [PATCH 05/26] fix: align skill instructions and extend shared documentation checks (#640) Signed-off-by: transitrix Co-authored-by: transitrix --- CONTRIBUTING.md | 2 +- scripts/check-notations.mjs | 113 ++++++++++------ scripts/check-notations.test.mjs | 128 +++++++++++++++++- transitrix/skills/feedback/SKILL.md | 6 +- transitrix/skills/ingest/tests/README.md | 2 +- transitrix/skills/knowledge-store/README.md | 6 +- transitrix/skills/knowledge-store/SKILL.md | 12 +- transitrix/skills/onboard/SKILL.md | 5 +- .../onboard/extraction/01_motivation.md | 4 +- .../skills/onboard/extraction/02_business.md | 4 +- .../onboard/extraction/03_application.md | 6 +- transitrix/skills/onboard/templates/AGENTS.md | 29 ++-- .../onboard/tests/test_skill_integrity.py | 2 +- .../templates/_intake.snapshots.README.md | 2 +- 14 files changed, 245 insertions(+), 76 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38616a1a..2c08d354 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,7 +66,7 @@ Add supporting material only as the skill needs it, following existing precedent | Touching | Run | |---|---| -| Any skill's `SKILL.md`/`README.md` prose | No dedicated linter for this tree — `node scripts/check-notations.mjs`'s link check is scoped to `notations/**/*.md` only, so check relative links by hand. | +| Any skill's `SKILL.md`/`README.md` prose | `node scripts/check-notations.mjs` and `node --test scripts/check-notations.test.mjs` — shared links, example IDs and layer trees, including installed onboarding guide paths and fixture-root links. | | `onboard`'s family-selection matrix or `templates/` | `node scripts/check-skill-cheatsheet.mjs` | | `onboard`'s scaffold logic | `python transitrix/skills/onboard/tests/test_skill_integrity.py` | | `knowledge-store`'s linter or pattern doc | the test(s) under `transitrix/skills/knowledge-store/tests/` | diff --git a/scripts/check-notations.mjs b/scripts/check-notations.mjs index 153e278f..6ac32abf 100644 --- a/scripts/check-notations.mjs +++ b/scripts/check-notations.mjs @@ -14,7 +14,7 @@ // Catches `.bpmn.yaml`-style drift and misfiled examples. // E2 header — each example carries a top-level `notation: ` whose // value matches its file extension. -// L1 links — every relative Markdown link in notations/**/*.md resolves to +// L1 links — relative Markdown links in notations/, method/ and skills/ resolve to // an existing file (anchors and external URLs are skipped). // T1 document sources — every `.ttrs` file is named ..ttrs, // and no file ends `.trs` (the near-miss: one keystroke away, a different @@ -56,8 +56,8 @@ // ID1 example-ID grammar — every ID-shaped token (a candidate whose TYPE // prefix is registered in IDS_AND_REFERENCES.md §3) found in a fenced // code block or a backtick span under method/**/*.md and -// notations/**/*.md satisfies §1's grammar (CAPABILITY's V/H address -// excepted, §2). A token that is itself a known rule code +// notations/**/*.md and transitrix/skills/**/*.md satisfies §1's +// grammar (CAPABILITY's V/H address excepted, §2). A token that is itself a known rule code // (vocabulary.yaml rule_codes / deferred.rule_codes — several rule-code // prefixes collide with a registered TYPE, e.g. ACTION-005, TERM-002) // is not an element ID and is excluded. IDS_AND_REFERENCES.md and @@ -65,7 +65,7 @@ // ✓/✗ comparison table documenting invalid forms as negative examples. // LAYER1 layer enumeration (extends VOC1's reach) — a contiguous group of // three or more distinct `NN_/` layer-folder tokens under -// method/**/*.md or notations/**/*.md (a directory tree, a table) is +// method/, notations/ or transitrix/skills/ Markdown (a directory tree) is // read as an attempt to enumerate the full layer set and must equal it // exactly — no fewer, no extra. A single incidental folder citation // (one element spec naming its own home folder) is not a "list" and is @@ -344,36 +344,68 @@ async function checkCatalogueBoundary(failures, warnings) { } } -// L1: relative markdown links in notations/**/*.md and method/**/*.md must resolve. -async function checkLinks(failures) { - const files = (await walk(NOTATIONS_DIR, '.md')).concat(await walk(METHOD_DIR, '.md')); - // Inline links only: no newline in the link text or the target, so we never - // splice an unrelated `[` and `](…)` across prose into a phantom link. +// Shared instruction inventory: include supporting prompts, templates and fixture docs. +export async function collectInstructionMarkdown(root = REPO_ROOT) { + return (await walk(join(root, 'notations'), '.md')).concat( + await walk(join(root, 'method'), '.md'), + await walk(join(root, 'transitrix', 'skills'), '.md')); +} + +// These guides are copied to the adopter root; Copilot is installed below .github. +// Resolve in that destination namespace, then require the backing source to exist. +// Other templates keep their source-relative links; no template directory is exempt. +const ONBOARD_GUIDES = new Map([ + ['AGENTS.md', 'AGENTS.md'], ['ANALYST.md', 'ANALYST.md'], + ['VALIDATOR.md', 'VALIDATOR.md'], ['INGEST.md', 'INGEST.md'], + ['FINDINGS.md', 'FINDINGS.md'], + ['copilot-instructions.md', '.github/copilot-instructions.md'], +]); + +export function resolveInstructionLink(abs, target, root = REPO_ROOT) { + const rel = relative(root, abs).split('\\').join('/'); + const prefix = 'transitrix/skills/onboard/templates/'; + const source = rel.startsWith(prefix) ? rel.slice(prefix.length) : null; + if (ONBOARD_GUIDES.has(source)) { + const installed = posix.normalize(posix.join(posix.dirname(ONBOARD_GUIDES.get(source)), target)); + for (const [file, destination] of ONBOARD_GUIDES) { + if (destination === installed) return join(root, prefix, file); + } + return null; // not an installed guide, even if a same-named source file exists + } + // Knowledge fixtures use site-root /knowledge links. Bind to the fixture's + // own root, never the machine root or a different fixture's knowledge tree. + const fixture = rel.match(/^(transitrix\/skills\/knowledge-store\/tests\/fixtures\/[^/]+)\//); + if (fixture && target.startsWith('/')) { + if (target.split('/').includes('..')) return null; + const fixtureRoot = resolve(root, fixture[1]); + const resolved = resolve(fixtureRoot, '.' + target); + return resolved.startsWith(fixtureRoot + '/') ? resolved : null; + } + return resolve(dirname(abs), target); +} + +export function findInstructionLinkFailures(text, abs, root = REPO_ROOT) { + const failures = []; + const rel = relative(root, abs).split('\\').join('/'); const linkRe = /\[[^\]\n]*\]\(([^)\n]+)\)/g; - for (const abs of files) { - const rel = relPosix(abs); - const text = await readFile(abs, 'utf8'); - let m; - while ((m = linkRe.exec(text)) !== null) { - let target = m[1].trim(); - // Skip external, anchor-only, mailto, and template placeholders. - if (/^(https?:|mailto:|#|<)/.test(target)) continue; - target = target.split('#')[0]; // drop anchor - if (!target) continue; // was anchor-only - if (target.includes('<') || target.includes('>')) continue; // placeholder like .yaml - // Only validate things that look like a local file/dir reference — a path - // segment (`/`) or a file extension. Bare words in parenthetical prose - // (`(factor)`, `(set_name)`) are not links. - if (!target.includes('/') && !/\.[a-z0-9]+$/i.test(target)) continue; - const resolved = resolve(dirname(abs), target); - if (!existsSync(resolved)) { - failures.push({ - check: 'L1', - message: `${rel}: broken relative link → \`${m[1]}\` (resolves to ${relPosix(resolved)}, not found).`, - }); - } + for (const m of text.matchAll(linkRe)) { + let target = m[1].trim(); + if (/^(https?:|mailto:|#|<)/.test(target)) continue; + target = target.split('#')[0]; + if (!target || target.includes('<') || target.includes('>')) continue; + if (!target.includes('/') && !/\.[a-z0-9]+$/i.test(target)) continue; + const resolved = resolveInstructionLink(abs, target, root); + if (!resolved || !existsSync(resolved)) { + failures.push({ check: 'L1', message: `${rel}: broken relative link → \`${m[1]}\` (destination not found).` }); } } + return failures; +} + +async function checkLinks(failures) { + for (const abs of await collectInstructionMarkdown()) { + failures.push(...findInstructionLinkFailures(await readFile(abs, 'utf8'), abs)); + } } // V1: concrete methodology_version pins must equal the SoT. @@ -1398,7 +1430,7 @@ const ID_TOKEN_RE = /\b[A-Z][A-Z0-9_]*(?:-[A-Za-z0-9_]+(?:\.[0-9]+)*)+\b/g; // "table cell" — this repo backtick-quotes every ID it documents). Skips a // match that is itself a placeholder by this repo's own conventions: wrapped // in `<…>` (``, ``) or immediately followed by the -// `-…` family-prefix ellipsis (`NEED-VALIDATION-COVERAGE-…`). Returns +// `-…` / `-...` family-prefix ellipsis or a shell `-*` prefix pattern. Returns // [{ token, line }] with 1-based line numbers. export function findIdCandidates(text) { const out = []; @@ -1410,8 +1442,13 @@ export function findIdCandidates(text) { const afterIdx = m.index + m[0].length; const after = segment[afterIdx]; if (before === '<' && after === '>') continue; // -style placeholder - if (after === '…' || segment.slice(afterIdx, afterIdx + 2) === '-…') continue; // family-prefix marker - out.push({ token: m[0], line }); + if (after === '…' || /^(?:-…|-\.\.\.|-\*)/.test(segment.slice(afterIdx))) continue; // family-prefix marker + // Operational snapshots append a fetch date to a codex ID. Check the + // source ID, not the filename's date, only in the declared snapshot path. + const snapshot = segment.slice(0, m.index).endsWith('_intake/snapshots/') + && /^\.(?:html|pdf|json|xml)\b/.test(segment.slice(afterIdx)) + && m[0].match(/^((?:REGULATION|STANDARD|POLICY|INTERNAL_STANDARD)-.+)-\d{4}-\d{2}-\d{2}$/); + out.push({ token: snapshot ? snapshot[1] : m[0], line }); } }; for (let i = 0; i < lines.length; i++) { @@ -1431,7 +1468,7 @@ export function findIdCandidates(text) { return out; } -async function checkIdGrammar(failures) { +export async function checkIdGrammar(failures, files = null) { let registryText; try { registryText = await readFile(IDS_AND_REFERENCES_PATH, 'utf8'); @@ -1457,7 +1494,7 @@ async function checkIdGrammar(failures) { // "no rule-code exclusions" rather than duplicating that failure here. } - const files = (await walk(NOTATIONS_DIR, '.md')).concat(await walk(METHOD_DIR, '.md')); + files ??= await collectInstructionMarkdown(); const seen = new Set(); for (const abs of files) { if (ID1_EXCLUDED_FILES.has(abs)) continue; // documents invalid forms on purpose @@ -1534,9 +1571,9 @@ export function findLayerEnumerationGroups(text) { return groups.filter(g => g.folders.size >= 3); } -async function checkLayerEnumeration(failures) { +export async function checkLayerEnumeration(failures, files = null) { const canonical = new Set(Object.values(LAYER_WORD_TO_FOLDER)); - const files = (await walk(NOTATIONS_DIR, '.md')).concat(await walk(METHOD_DIR, '.md')); + files ??= await collectInstructionMarkdown(); for (const abs of files) { const rel = relPosix(abs); const text = await readFile(abs, 'utf8'); diff --git a/scripts/check-notations.test.mjs b/scripts/check-notations.test.mjs index 0e0134d0..60283bc7 100644 --- a/scripts/check-notations.test.mjs +++ b/scripts/check-notations.test.mjs @@ -1,13 +1,20 @@ // Unit tests for the C1 class-derivation logic in check-notations.mjs. // Run: node --test scripts/check-notations.test.mjs // -// Exercises the pure functions only (no filesystem, no subprocess) — the +// Exercises pure functions and isolated instruction-path fixtures — the // integration-level guarantee (the real repo's counts match its README) is // covered by running scripts/check-notations.mjs itself in CI. import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; import { + collectInstructionMarkdown, + findInstructionLinkFailures, + checkIdGrammar, + checkLayerEnumeration, deriveClassCounts, parseStatedViewCounts, findStandardIdentifierEmissions, @@ -891,3 +898,122 @@ test('relation endpoint tables retain Project subtype and exclude driver-to-driv assert.deepEqual(vocabulary.get('source_trace').excludedPairs, rows.get('source_trace').excludedPairs); assert.throws(() => parseRelationsEnumTable(text.replace('ACTION(Project)', 'PRODUCT(Project)')), /unexpected subtype/); }); + + +// Maintainers exercise the same checker against installed instruction namespaces. +// Fixtures stay ephemeral; the published skill files are checked in place in CI. +test('skill instruction inventory includes protocols, prompts, templates and fixture docs', async () => { + const files = await collectInstructionMarkdown(); + for (const name of [ + 'feedback/SKILL.md', 'knowledge-store/README.md', + 'onboard/extraction/01_motivation.md', 'onboard/templates/AGENTS.md', + 'knowledge-store/tests/fixtures/valid/knowledge/warehouse-finance-handoff.md', + ]) assert.ok(files.includes(resolve('transitrix/skills', name)), name); +}); + +test('instruction links resolve source, installed and fixture roots and reject missing targets', () => { + const root = mkdtempSync(join(tmpdir(), 'instruction-links-')); + const put = (name, text = '') => { + const path = join(root, name); + mkdirSync(join(path, '..'), { recursive: true }); + writeFileSync(path, text); + return path; + }; + try { + const skill = put('transitrix/skills/knowledge-store/SKILL.md'); + put('patterns/knowledge-store.md'); + assert.equal(findInstructionLinkFailures('[gate](../../../patterns/knowledge-store.md#gate)', skill, root).length, 0); + assert.equal(findInstructionLinkFailures('[gate](../../../../patterns/knowledge-store.md)', skill, root).length, 1); + const agent = put('transitrix/skills/onboard/templates/AGENTS.md'); + const copilot = put('transitrix/skills/onboard/templates/copilot-instructions.md'); + assert.equal(findInstructionLinkFailures('[pointer](.github/copilot-instructions.md)', agent, root).length, 0); + assert.equal(findInstructionLinkFailures('[guide](../AGENTS.md)', copilot, root).length, 0); + assert.equal(findInstructionLinkFailures('[guide](../AGENT.md)', copilot, root).length, 1); + assert.equal(findInstructionLinkFailures('[pointer](copilot-instructions.md)', agent, root).length, 1); + rmSync(copilot); + assert.equal(findInstructionLinkFailures('[pointer](.github/copilot-instructions.md)', agent, root).length, 1); + const fixture = put('transitrix/skills/knowledge-store/tests/fixtures/valid/knowledge/a.md'); + put('transitrix/skills/knowledge-store/tests/fixtures/valid/knowledge/b.md'); + assert.equal(findInstructionLinkFailures('[object](/knowledge/b.md)', fixture, root).length, 0); + assert.equal(findInstructionLinkFailures('[object](/knowledge/missing.md)', fixture, root).length, 1); + const other = put('transitrix/skills/knowledge-store/tests/fixtures/other/knowledge/a.md'); + assert.equal(findInstructionLinkFailures('[object](/knowledge/b.md)', other, root).length, 1); + assert.equal(findInstructionLinkFailures('[escape](/../valid/knowledge/b.md)', fixture, root).length, 1); + const raw = put('transitrix/skills/ingest/tests/README.md'); + put('transitrix/skills/ingest/tests/fixtures/raw/INTERVIEW-sample.md'); + assert.equal(findInstructionLinkFailures('[raw](fixtures/raw/INTERVIEW-sample.md)', raw, root).length, 0); + assert.equal(findInstructionLinkFailures('[raw](fixtures/raw/INTERVIEW-missing.md)', raw, root).length, 1); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + +test('instruction IDs distinguish explicit placeholders, prose and snapshot source IDs', async () => { + const root = mkdtempSync(join(tmpdir(), 'instruction-ids-')); + const file = join(root, 'SKILL.md'); + try { + writeFileSync(file, [ + '``', '`REGULATION-CFR-*`', '`INTERVIEW-cfo-...`', + '```yaml', 'description: PROCESS level extraction', + 'id: CAPABILITY-V3.2', 'goal: GOAL-EXAMPLE-1', '```', + '`_intake/snapshots/REGULATION-GDPR-2016-1-2026-06-08.html`', + ].join('\n')); + const good = []; + await checkIdGrammar(good, [file]); + assert.deepEqual(good, []); + writeFileSync(file, [ + '`GOAL-NNN`', '`PROCESS-level`', '`CAPABILITY-ORDER_FULFIL-3`', + '`GOAL-EXAMPLE-01`', + '`_intake/snapshots/REGULATION-BAD-01-2026-06-08.html`', + ].join('\n')); + const bad = []; + await checkIdGrammar(bad, [file]); + assert.equal(bad.length, 5); + assert.ok(bad.some(f => f.message.includes('REGULATION-BAD-01'))); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + +test('a broken real instruction and incomplete template tree still fail shared checks', async () => { + const root = mkdtempSync(join(tmpdir(), 'instruction-regression-')); + try { + const feedback = join(root, 'SKILL.md'); + writeFileSync(feedback, readFileSync('transitrix/skills/feedback/SKILL.md', 'utf8') + .replaceAll('CAPABILITY-V3', 'CAPABILITY-ORDER_FULFIL-3')); + const ids = []; + await checkIdGrammar(ids, [feedback]); + assert.equal(ids.length, 1); + const knowledge = resolve('transitrix/skills/knowledge-store/SKILL.md'); + const links = findInstructionLinkFailures(readFileSync(knowledge, 'utf8') + .replaceAll('../../../patterns/', '../../../../patterns/'), knowledge); + assert.equal(links.length, 5); + const template = join(root, 'AGENTS.md'); + const text = readFileSync('transitrix/skills/onboard/templates/AGENTS.md', 'utf8'); + writeFileSync(template, text); + const good = []; + await checkLayerEnumeration(good, [template]); + assert.deepEqual(good, []); + writeFileSync(template, text.split('\n').filter(l => !l.includes('└── 05_implementation/')).join('\n')); + const bad = []; + await checkLayerEnumeration(bad, [template]); + assert.equal(bad.length, 1); + assert.match(bad[0].message, /05_implementation/); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + + +test('actual onboarding guides resolve after copying to their documented destinations', async () => { + const root = mkdtempSync(join(tmpdir(), 'installed-guides-')); + const files = ['AGENTS.md', 'ANALYST.md', 'VALIDATOR.md', 'INGEST.md', 'FINDINGS.md', 'copilot-instructions.md']; + try { + mkdirSync(join(root, '.github')); + for (const file of files) { + const destination = file === 'copilot-instructions.md' ? '.github/' + file : file; + writeFileSync(join(root, destination), readFileSync('transitrix/skills/onboard/templates/' + file)); + } + for (const file of files) { + const destination = join(root, file === 'copilot-instructions.md' ? '.github/' + file : file); + assert.deepEqual(findInstructionLinkFailures(readFileSync(destination, 'utf8'), destination, root), []); + } + rmSync(join(root, 'FINDINGS.md')); + const guide = join(root, 'AGENTS.md'); + assert.ok(findInstructionLinkFailures(readFileSync(guide, 'utf8'), guide, root).length > 0); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/transitrix/skills/feedback/SKILL.md b/transitrix/skills/feedback/SKILL.md index 7a080804..b9df6686 100644 --- a/transitrix/skills/feedback/SKILL.md +++ b/transitrix/skills/feedback/SKILL.md @@ -148,8 +148,8 @@ correctly. 3. **Refuse to write** (state why, then return to Step 2 to rephrase) if the composed text contains any of: - a token matching the canonical ID grammar, `-[-]` - (`notations/IDS_AND_REFERENCES.md` §1) — e.g. `GOAL-RETENTION-12`, - `CAPABILITY-ORDER_FULFIL-3` — this is an element ID, not a generic description; + (`notations/IDS_AND_REFERENCES.md` §1, with the capability V/H form in §2) — e.g. `GOAL-RETENTION-12`, + `CAPABILITY-V3` — this is an element ID, not a generic description; - a path under `canon/`, `field/`, or `codex/`; - an organisation name, a real person's name, or any other organisation-identifying detail (the same real-names / "publish pattern, not client instance" rule applied @@ -158,7 +158,7 @@ correctly. cannot be stated without one of the above, ask the user to rephrase it more generically. Loop until the text is clean or the user abandons the entry. -**Worked negative example** — an observation stated as *"our `CAPABILITY-ORDER_FULFIL-3` +**Worked negative example** — an observation stated as *"our `CAPABILITY-V3` element has no relation kind to link it to `GOAL-RETENTION-12` at Acme Corp"* is refused on all three grounds (two element IDs, one organisation name) and rewritten, with the user, as *"no relation kind connects a CAPABILITY element to a GOAL diff --git a/transitrix/skills/ingest/tests/README.md b/transitrix/skills/ingest/tests/README.md index 7cf0f623..599b7d91 100644 --- a/transitrix/skills/ingest/tests/README.md +++ b/transitrix/skills/ingest/tests/README.md @@ -20,5 +20,5 @@ The integrity test needs **PyYAML** (to parse the emitted YAML) and **Node** (th ## Fixtures -- `fixtures/raw/INTERVIEW-sample.md` — a generic fake interview (a role, not a named person), `.md` so the integrity test needs no Markitdown. +- [fixtures/raw/INTERVIEW-sample.md](fixtures/raw/INTERVIEW-sample.md) — a generic fake interview (a role, not a named person), `.md` so the integrity test needs no Markitdown. - `fixtures/extraction-result.json` — a canned stand-in for the agent's extraction result, so `emit-candidates` has an input without an LLM. It mixes a high-confidence relation (→ candidate) and a medium one (→ held-back suggestion). diff --git a/transitrix/skills/knowledge-store/README.md b/transitrix/skills/knowledge-store/README.md index 034d7486..5fa8aff5 100644 --- a/transitrix/skills/knowledge-store/README.md +++ b/transitrix/skills/knowledge-store/README.md @@ -12,7 +12,7 @@ This directory is the **`knowledge-store` skill** within the `transitrix` plugin --- -Re-curating a reissued source creates a new source record and a new knowledge object. After review, the new object and its predecessor receive reciprocal supersession pointers; the predecessor’s body and assertion metadata remain intact. See [Gate 2.1](../../../../patterns/knowledge-store.md#gate-21--supersession-not-rewriting). +Re-curating a reissued source creates a new source record and a new knowledge object. After review, the new object and its predecessor receive reciprocal supersession pointers; the predecessor’s body and assertion metadata remain intact. See [Gate 2.1](../../../patterns/knowledge-store.md#gate-21--supersession-not-rewriting). ## What it ships @@ -22,8 +22,8 @@ Re-curating a reissued source creates a new source record and a new knowledge ob - [`tests/test_knowledge_store_integrity.py`](tests/test_knowledge_store_integrity.py) — deterministic CI guard for `tools/knowledge_store_lint.py` (KS-001..017). The skill reads its OKF templates from the methodology patterns directory: -- [`patterns/knowledge-store-templates/okf-source-document.md`](../../../../patterns/knowledge-store-templates/okf-source-document.md) -- [`patterns/knowledge-store-templates/okf-knowledge-object.md`](../../../../patterns/knowledge-store-templates/okf-knowledge-object.md) +- [`patterns/knowledge-store-templates/okf-source-document.md`](../../../patterns/knowledge-store-templates/okf-source-document.md) +- [`patterns/knowledge-store-templates/okf-knowledge-object.md`](../../../patterns/knowledge-store-templates/okf-knowledge-object.md) --- diff --git a/transitrix/skills/knowledge-store/SKILL.md b/transitrix/skills/knowledge-store/SKILL.md index a9b0e10b..d4f43696 100644 --- a/transitrix/skills/knowledge-store/SKILL.md +++ b/transitrix/skills/knowledge-store/SKILL.md @@ -22,7 +22,7 @@ Processes raw source material through the OKF single-repo MVP knowledge store. A python3 tools/knowledge_store_lint.py . ``` -The linter enforces Gates 1–6 from [patterns/knowledge-store.md §Quality gates](../../../../patterns/knowledge-store.md). Errors block promotion; warnings require explicit human acknowledgment in `_intake/log.md`. See [tests/README.md](tests/README.md) for the KS-001..017 code reference. +The linter enforces Gates 1–6 from [patterns/knowledge-store.md §Quality gates](../../../patterns/knowledge-store.md). Errors block promotion; warnings require explicit human acknowledgment in `_intake/log.md`. See [tests/README.md](tests/README.md) for the KS-001..017 code reference. --- @@ -43,7 +43,7 @@ knowledge/ .md ← individual OKF knowledge objects ``` -If `_intake/` or `knowledge/` are missing, scaffold them now. Create `_intake/drafts/` if absent. Copy the initialisation content from [patterns/knowledge-store.md §Templates](../../../../patterns/knowledge-store.md). Add gitignore entries for `_intake/inbox/*` and `_intake/originals/*` (drafts MAY be committed for audit or gitignored for ephemeral runs). +If `_intake/` or `knowledge/` are missing, scaffold them now. Create `_intake/drafts/` if absent. Copy the initialisation content from [patterns/knowledge-store.md §Templates](../../../patterns/knowledge-store.md). Add gitignore entries for `_intake/inbox/*` and `_intake/originals/*` (drafts MAY be committed for audit or gitignored for ephemeral runs). --- @@ -66,7 +66,7 @@ State your assessment to the user before proceeding. ## Step 2 — Archive to processed/ -Copy the source file reference to `_intake/processed/` as an OKF source-document record using the template at [patterns/knowledge-store-templates/okf-source-document.md](../../../../patterns/knowledge-store-templates/okf-source-document.md). +Copy the source file reference to `_intake/processed/` as an OKF source-document record using the template at [patterns/knowledge-store-templates/okf-source-document.md](../../../patterns/knowledge-store-templates/okf-source-document.md). Fill in: - `title:` — document filename or stated title @@ -102,7 +102,7 @@ Append to `_intake/log.md`: ### 4a — Propose drafts (Gate 6) -Read the source document from `_intake/originals/` (or the processed record). Using the extraction prompt at [prompts/extract-okf.md](prompts/extract-okf.md), extract candidate knowledge objects and **write each to `_intake/drafts/.md`** using the template at [patterns/knowledge-store-templates/okf-knowledge-object-draft.md](../../../../patterns/knowledge-store-templates/okf-knowledge-object-draft.md). +Read the source document from `_intake/originals/` (or the processed record). Using the extraction prompt at [prompts/extract-okf.md](prompts/extract-okf.md), extract candidate knowledge objects and **write each to `_intake/drafts/.md`** using the template at [patterns/knowledge-store-templates/okf-knowledge-object-draft.md](../../../patterns/knowledge-store-templates/okf-knowledge-object-draft.md). Each draft: - has a clear, discrete idea (one concept per file) @@ -124,7 +124,7 @@ Wait for the user to approve, reject, or revise each draft. Do not promote anyth ### 4d — Dispose approved drafts -For each approved draft, copy to `knowledge/.md` using [patterns/knowledge-store-templates/okf-knowledge-object.md](../../../../patterns/knowledge-store-templates/okf-knowledge-object.md). **Remove** `review_status` and `ambiguity_note` from frontmatter. Delete the corresponding file under `_intake/drafts/`. +For each approved draft, copy to `knowledge/.md` using [patterns/knowledge-store-templates/okf-knowledge-object.md](../../../patterns/knowledge-store-templates/okf-knowledge-object.md). **Remove** `review_status` and `ambiguity_note` from frontmatter. Delete the corresponding file under `_intake/drafts/`. Never overwrite an existing knowledge-object path. For approved re-curation, create the successor and add `superseded_by` to its predecessor in the same change, updating only that predecessor’s lifecycle `timestamp` alongside the pointer. Preserve its body and all assertion metadata, including any earlier `supersedes`. Record the source revision and both object paths in the `[admit]` log entry; keep both index rows. @@ -195,7 +195,7 @@ PR body must include: Once the user reports the PR outcome, append to `_intake/log.md`: ```markdown -- [assert] PR # merged | admitted: [DRIV-NNN, GOAL-NNN, ...] | source: +- [assert] PR # merged | admitted: [, , ...] | source: ``` Or for rejected: diff --git a/transitrix/skills/onboard/SKILL.md b/transitrix/skills/onboard/SKILL.md index 9071669e..323794ed 100644 --- a/transitrix/skills/onboard/SKILL.md +++ b/transitrix/skills/onboard/SKILL.md @@ -102,7 +102,8 @@ Scaffold the canonical **zoned** Transitrix adopter shape in the user's chosen t │ ├── 02_business/ # ROLE, PROCESS, CAPABILITY, RULE, … │ │ └── rules/ # RULE-…-N.yaml (one per file) │ ├── 03_application/ # APPLICATION, INTEGRATION, … -│ └── 04_technology/ # NODE, ARTIFACT, … +│ ├── 04_technology/ # NODE, ARTIFACT, … +│ └── 05_implementation/ # ACTION, CHANGE ├── views/ # one subfolder per notation, beside canon/ │ ├── bpmn/ dgca/ goals/ capabilities/ processmap/ │ ├── actions/ blocks/ scenarios/ @@ -119,6 +120,8 @@ Use the org name from step 1 (or ask: "What's the organisation name? — lowerca The `views/` folder names are intentionally shorter than the canonical short names in places (`capabilities/`, `processmap/`) — this is the adopter-side convention. +For existing repositories, `canon/views/` remains accepted as a deprecated layout; coexistence with root `views/` produces `MIX-001` (CONTRACT §14.5). The `activities` notation/extension alias remains explicitly listed with `ACT-020` in the Action spec; author new views as `action`. The `issues` notation is retired and absent from the current catalogue; use an issue tracker or the `operations/` work register. Preserve existing data and agree a migration before changing legacy forms. + ### Drop in the canonical root files The named guides select assistant modes, not enterprise roles or access grants. Keep expertise, accessible scope, operation permissions, and per-change assignment separate. Validator supports an assigned domain expert; automated validation, expert review, and approval remain distinct. Preserve existing adopter guides and tool pointers; apply a reviewed in-place migration instead of overwriting custom policy. See the [compatible migration guide](https://github.com/transitrix/methodology/blob/main/guides/repository-mcp-enterprise.md#14-compatible-role-and-onboarding-migration). diff --git a/transitrix/skills/onboard/extraction/01_motivation.md b/transitrix/skills/onboard/extraction/01_motivation.md index 1a7b3569..1f387023 100644 --- a/transitrix/skills/onboard/extraction/01_motivation.md +++ b/transitrix/skills/onboard/extraction/01_motivation.md @@ -256,13 +256,13 @@ cross_layer_hints: - layer: 02_business fragment: | Source mentions "the customer-support intake process is being - overhauled" — the corresponding PROCESS-level extraction belongs + overhauled" — the corresponding PROCESS level extraction belongs to 02_business. derived_from: [INTERVIEW-cfo-strategy-2026-04-15-1] - layer: 03_application fragment: | Source mentions "we are migrating from SAP CRM to Salesforce" — - the APPLICATION-level extraction belongs to 03_application. + the APPLICATION level extraction belongs to 03_application. derived_from: [INTERVIEW-cfo-strategy-2026-04-15-1] ``` diff --git a/transitrix/skills/onboard/extraction/02_business.md b/transitrix/skills/onboard/extraction/02_business.md index c9caff7b..dee5ebf4 100644 --- a/transitrix/skills/onboard/extraction/02_business.md +++ b/transitrix/skills/onboard/extraction/02_business.md @@ -287,12 +287,12 @@ cross_layer_hints: - layer: 01_motivation fragment: | Source mentions "we need to triple revenue in three years" — the - corresponding GOAL-level extraction belongs to 01_motivation. + corresponding GOAL level extraction belongs to 01_motivation. derived_from: [INTERVIEW-cfo-strategy-2026-04-15-1] - layer: 03_application fragment: | Source mentions "the new CRM rollout is underway" — the - APPLICATION-level extraction belongs to 03_application. + APPLICATION level extraction belongs to 03_application. derived_from: [INTERVIEW-cfo-strategy-2026-04-15-1] ``` diff --git a/transitrix/skills/onboard/extraction/03_application.md b/transitrix/skills/onboard/extraction/03_application.md index 3e7057cb..bd5afc03 100644 --- a/transitrix/skills/onboard/extraction/03_application.md +++ b/transitrix/skills/onboard/extraction/03_application.md @@ -202,8 +202,8 @@ If the source is ambiguous (Application vs Platform, Application vs Integration) confidence: low extraction_notes: | The source mentions "we run everything on our internal data hub". - This could be APPLICATION-type: platform (a general-purpose hosting - platform) or APPLICATION-type: data_store (a primary data + This could be APPLICATION type: platform (a general-purpose hosting + platform) or APPLICATION type: data_store (a primary data repository). Emitted as platform because "run everything on" suggests hosting, but flagged for human review. ``` @@ -223,7 +223,7 @@ cross_layer_hints: - layer: 02_business fragment: | Source mentions "the payment-processing PROCESS handles this end - to end" — the corresponding PROCESS-level extraction belongs to + to end" — the corresponding PROCESS level extraction belongs to 02_business. derived_from: [INTERVIEW-cto-strategy-2026-03-22-1] ``` diff --git a/transitrix/skills/onboard/templates/AGENTS.md b/transitrix/skills/onboard/templates/AGENTS.md index d2eb1dff..e74bc148 100644 --- a/transitrix/skills/onboard/templates/AGENTS.md +++ b/transitrix/skills/onboard/templates/AGENTS.md @@ -43,7 +43,7 @@ This repository is a **text-native enterprise architecture model** authored in t What lives here: -- `canon/` — the **validated model** (the authoritative zone): `views//` (model files in the canonical Transitrix notations) and `elements/` (reusable architecture elements by ArchiMate layer `01_motivation/` … `04_technology/`). +- `canon/` — the **validated model** (the authoritative zone): `elements/` (reusable architecture elements by ArchiMate layer `01_motivation/` … `05_implementation/`). Views live separately at `views//`. - `field/` — **raw, unprocessed inputs**: interviews, surveys, observations, drafts. - `codex/` — **external constraints** (laws, regulations) and **internal authority documents** (policies, standards). - `transitrix.yaml` — the adopter manifest: which methodology version, notations, and zones this repo uses. @@ -109,15 +109,16 @@ The canonical layout an adopter inherits when scaffolded by `/transitrix:onboard │ └── copilot-instructions.md # pointer → AGENTS.md (GitHub Copilot) ├── README.md ├── canon/ # validated model — the authoritative zone -│ ├── elements/ # elements by ArchiMate layer -│ │ ├── 01_motivation/ # GOAL, CONSTRAINT, DRIVER, … -│ │ ├── 02_business/ # ROLE, PROCESS, CAPABILITY, RULE, … -│ │ ├── 03_application/ # APPLICATION, INTEGRATION, … -│ │ └── 04_technology/ # NODE, ARTIFACT, … -│ └── views/ # one subfolder per notation -│ ├── bpmn/ dgca/ goals/ capabilities/ processmap/ -│ ├── activities/ blocks/ scenarios/ -│ └── applications/ products/ issues/ process-blueprint/ +│ └── elements/ # elements by ArchiMate layer +│ ├── 01_motivation/ # GOAL, CONSTRAINT, DRIVER, … +│ ├── 02_business/ # ROLE, PROCESS, CAPABILITY, RULE, … +│ ├── 03_application/ # APPLICATION, INTEGRATION, … +│ ├── 04_technology/ # NODE, ARTIFACT, … +│ └── 05_implementation/ # ACTION, CHANGE +├── views/ # projections beside canon/ +│ ├── bpmn/ dgca/ goals/ capabilities/ processmap/ +│ ├── actions/ blocks/ scenarios/ +│ └── applications/ products/ process-blueprint/ ├── field/ # raw inputs — interviews, surveys, observations, drafts │ ├── interviews/ surveys/ observations/ drafts/ └── codex/ # external laws/regulations + internal policies/standards @@ -127,13 +128,15 @@ The canonical layout an adopter inherits when scaffolded by `/transitrix:onboard The `views/` folder names are intentionally shorter than the canonical short names in places (`capabilities/`, `processmap/`) — this is the adopter-side convention. +For existing repositories, `canon/views/` remains accepted as a deprecated layout; coexistence with root `views/` produces `MIX-001` (CONTRACT §14.5). The `activities` notation/extension alias remains explicitly listed with `ACT-020` in the Action spec; author new views as `action`. The `issues` notation is retired and absent from the current catalogue; use an issue tracker or the `operations/` work register. Preserve existing data and agree a migration before changing legacy forms. + The agent does **not** change this layout without a deliberate decision recorded in the adopter's PR. Adopter-specific top-level additions (e.g. a `decisions/` ADR folder, a `glossary/` directory) are fine; renaming or removing the canonical folders is not. ### 3.1 Zones This repo separates three kinds of knowledge, each with its own trust contract (defined in the canon, `notations/CONTRACT.md` §5): -- **`canon/`** — validated truth the organisation asserts about itself. Internally consistent and unique; the authoritative model. `elements/` and `views/` live here. +- **`canon/`** — validated truth the organisation asserts about itself. Internally consistent and unique; the authoritative model. `elements/` lives here; `views/` is a sibling projection directory. - **`field/`** — raw, unprocessed material (interviews, surveys, observations, drafts). Contradictions allowed; provenance is the point; **not** authoritative. A Canon record may *cite* a Field artefact via `derived_from:` — a citation, never a migration. - **`codex/`** — external constraints (laws, regulations, under `external//`) and internal authority documents (policies, standards, under `internal/`), *given to* the organisation rather than authored by it. @@ -161,7 +164,7 @@ The root `transitrix.yaml` pins which methodology release this repo conforms to ```yaml transitrix: 1 methodology_version: "7.0.0" -notations: [dgca, goals, activities, issues, capability-map, codex] +notations: [dgca, goals, action, capability-map, codex] zones: [canon, field, codex] ``` @@ -249,7 +252,7 @@ The agent does **not** publish externally-visible artefacts (PR descriptions, pu - **GitHub Issues on this repo.** Tasks live as issues on the adopter's repo; the agent reads them via `gh issue list -R /` and reports back via `gh issue comment`. - **Linear / Jira / Asana.** Tasks live in a project management tool; the agent reads tickets via the tool's API or pasted-in URLs; PRs link back via the tool's convention. -- **Self-hosted issues register.** Tasks live in this repo as a `.issues.transitrix.yaml` file under `views/issues/` per `notations/views/12-issues.md`. The agent reads and updates the YAML directly. +- **Repository work register.** Use `operations/` work items per `method/06-team-operations.md`. The retired `issues` notation and `notations/views/12-issues.md` are not current contracts; migrate an existing register deliberately rather than generating that format. --- diff --git a/transitrix/skills/onboard/tests/test_skill_integrity.py b/transitrix/skills/onboard/tests/test_skill_integrity.py index e9fc3475..3de4b4a5 100644 --- a/transitrix/skills/onboard/tests/test_skill_integrity.py +++ b/transitrix/skills/onboard/tests/test_skill_integrity.py @@ -191,7 +191,7 @@ def validate_goals(doc): ZONE_SKELETON = [ "canon/elements/01_motivation", "canon/elements/02_business", "canon/elements/03_application", "canon/elements/04_technology", - "views/goals", "field/interviews", "codex/external", "codex/internal", + "canon/elements/05_implementation", "views/goals", "field/interviews", "codex/external", "codex/internal", ] diff --git a/transitrix/skills/reg-intel/templates/_intake.snapshots.README.md b/transitrix/skills/reg-intel/templates/_intake.snapshots.README.md index 1c3fcec8..3c394321 100644 --- a/transitrix/skills/reg-intel/templates/_intake.snapshots.README.md +++ b/transitrix/skills/reg-intel/templates/_intake.snapshots.README.md @@ -18,7 +18,7 @@ One file per fetch, named by the codex source ID and the fetch date: ``` _intake/snapshots/-. -# e.g. REGULATION-GDPR-2016-1-2026-06-08.html +# e.g. _intake/snapshots/REGULATION-GDPR-2016-1-2026-06-08.html ``` `` follows the source format (`.html`, `.pdf`, `.json`, `.xml`). The bytes are the source body the agent fetched; `fetch-snapshot` fingerprints them as `source_hash: sha256:` and records that hash in the committed operations cache (`operations/state/reg-intel/signal-cache.json`), so a later run can tell whether the source moved even in a fresh clone / CI checkout. From aa8e8444b1c2aae8a505ea3f88ba6688c66433a4 Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Wed, 7 Oct 2026 06:59:00 +0400 Subject: [PATCH 06/26] Align skill guidance and isolate intake profiles (#641) * fix: align skill guidance and isolate intake profiles Signed-off-by: transitrix * fix: enforce durable intake profile selection Signed-off-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix --- packages/ingest-cli/README.md | 10 + packages/ingest-cli/intake-profile.mjs | 19 ++ packages/ingest-cli/package.json | 4 +- packages/ingest-cli/src/intake-profile.mjs | 106 +++++++ .../ingest-cli/src/intake-profile.test.mjs | 267 ++++++++++++++++++ packages/ingest-cli/src/intake.mjs | 3 + patterns/knowledge-store.md | 44 +++ scripts/check-notations.test.mjs | 26 +- transitrix/skills/feedback/README.md | 14 +- transitrix/skills/feedback/SKILL.md | 20 +- transitrix/skills/ingest/README.md | 9 + transitrix/skills/ingest/SKILL.md | 7 + .../skills/ingest/templates/_intake.README.md | 6 + .../ingest/tests/test_ingest_integrity.py | 57 ++-- transitrix/skills/knowledge-store/README.md | 11 +- transitrix/skills/knowledge-store/SKILL.md | 48 +++- .../knowledge-store/prompts/extract-canon.md | 2 +- transitrix/skills/onboard/README.md | 13 +- transitrix/skills/onboard/SKILL.md | 29 +- transitrix/skills/onboard/templates/AGENTS.md | 2 +- .../skills/onboard/templates/FINDINGS.md | 6 +- transitrix/skills/reg-intel/README.md | 9 + transitrix/skills/reg-intel/SKILL.md | 16 ++ .../reg-intel/templates/reg-intel-daily.sh | 3 + 24 files changed, 668 insertions(+), 63 deletions(-) create mode 100644 packages/ingest-cli/intake-profile.mjs create mode 100644 packages/ingest-cli/src/intake-profile.mjs create mode 100644 packages/ingest-cli/src/intake-profile.test.mjs diff --git a/packages/ingest-cli/README.md b/packages/ingest-cli/README.md index ea2601e4..8b5554dd 100644 --- a/packages/ingest-cli/README.md +++ b/packages/ingest-cli/README.md @@ -119,3 +119,13 @@ packages/ingest-cli/ ``` The agent-facing extraction prompts that produce the `--from ` input live with the skill, at `transitrix/skills/ingest/prompts/`. + +## Intake compatibility + +`transitrix-intake-profile check --profile ingest|knowledge-store` is a read-only +preflight for separate ingestion workspaces. `transitrix-intake-profile select` accepts the +same arguments and records the checked selection in `_intake/profile.json`. +`scaffold-intake` enforces and records `ingest` before creating any directories. +Neither command changes existing content or ignore rules. OKF checks require Git +so ignored source records cannot be silently hidden. See the +[deployment contract](../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility). diff --git a/packages/ingest-cli/intake-profile.mjs b/packages/ingest-cli/intake-profile.mjs new file mode 100644 index 00000000..99147c17 --- /dev/null +++ b/packages/ingest-cli/intake-profile.mjs @@ -0,0 +1,19 @@ +#!/usr/bin/env node +// Standalone preflight: no vocabulary or extraction dependencies. +import { checkIntakeProfile, selectIntakeProfile } from './src/intake-profile.mjs'; + +const [command, root, flag, profile, ...extra] = process.argv.slice(2); +if (command === '--help') { + console.log('transitrix-intake-profile check|select --profile ingest|knowledge-store'); +} else if (!['check', 'select'].includes(command) || !root || flag !== '--profile' || !profile || extra.length) { + console.error('Usage: transitrix-intake-profile check|select --profile ingest|knowledge-store'); + process.exitCode = 1; +} else { + try { + const operation = command === 'select' ? selectIntakeProfile : checkIntakeProfile; + console.log(JSON.stringify(await operation(root, profile), null, 2)); + } catch (error) { + console.error(error.message); + process.exitCode = 2; + } +} diff --git a/packages/ingest-cli/package.json b/packages/ingest-cli/package.json index 31fd225a..529be436 100644 --- a/packages/ingest-cli/package.json +++ b/packages/ingest-cli/package.json @@ -4,13 +4,15 @@ "description": "Deterministic CLI for the Transitrix ingest skill — scaffold intake, convert documents, emit field artefacts and canon candidates, validate, and stage a review queue. Never writes canon.", "type": "module", "bin": { - "transitrix-ingest": "./ingest.mjs" + "transitrix-ingest": "./ingest.mjs", + "transitrix-intake-profile": "./intake-profile.mjs" }, "engines": { "node": ">=20" }, "files": [ "ingest.mjs", + "intake-profile.mjs", "src/", "assets/" ], diff --git a/packages/ingest-cli/src/intake-profile.mjs b/packages/ingest-cli/src/intake-profile.mjs new file mode 100644 index 00000000..33bb8501 --- /dev/null +++ b/packages/ingest-cli/src/intake-profile.mjs @@ -0,0 +1,106 @@ +// Skill-local deployment compatibility. Read-only checks precede every setup write. +import { lstat, readdir, readFile, mkdir, writeFile } from 'node:fs/promises'; +import { join, resolve, relative } from 'node:path'; +import { spawnSync } from 'node:child_process'; + +const PROFILES = ['ingest', 'knowledge-store']; +const MARKER = '_intake/profile.json'; +const fail = message => { throw new Error(`Intake profile conflict: ${message}. Use separate workspaces; existing data was not changed.`); }; + +async function inspect(path) { + try { + const stat = await lstat(path); + if (stat.isSymbolicLink()) fail(`cannot establish ownership through symlink ${path}`); + return stat; + } catch (error) { + if (error.code === 'ENOENT') return null; + throw error; + } +} + +async function files(path) { + const stat = await inspect(path); + if (!stat) return []; + if (!stat.isDirectory()) return [path]; + const result = []; + for (const name of await readdir(path)) { + if (name === '.gitkeep' || name === '.gitignore') { + await inspect(join(path, name)); + continue; + } + result.push(...await files(join(path, name))); + } + return result; +} + +export async function checkIntakeProfile(orgRoot, profile) { + if (!PROFILES.includes(profile)) throw new Error('Choose --profile ingest or --profile knowledge-store'); + const root = resolve(orgRoot); + await inspect(root); + const intake = await inspect(join(root, '_intake')); + if (intake && !intake.isDirectory()) fail('_intake is not a directory'); + const evidence = { ingest: [], 'knowledge-store': [] }; + let declared = null; + if (await inspect(join(root, MARKER))) { + const marker = JSON.parse(await readFile(join(root, MARKER), 'utf8')); + if (marker.version !== 1 || !PROFILES.includes(marker.profile)) fail('invalid profile marker'); + declared = marker.profile; + evidence[declared].push(MARKER); + } + for (const [owner, paths] of Object.entries({ + ingest: ['_intake/processing', '_intake/snapshots', 'operations/config/scan-sources.yaml'], + 'knowledge-store': ['knowledge', '_intake/originals', '_intake/drafts', '_intake/log.md'], + })) { + for (const path of paths) if (await inspect(join(root, path))) evidence[owner].push(path); + } + for (const name of ['inbox', 'processing', 'processed', 'snapshots', 'originals', 'drafts']) { + const stat = await inspect(join(root, '_intake', name)); + if (stat && !stat.isDirectory()) fail(`_intake/${name} is not a directory`); + } + const processed = await files(join(root, '_intake/processed')); + for (const path of processed) { + const text = path.endsWith('.md') ? await readFile(path, 'utf8') : ''; + const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1] || ''; + const okf = /^(?:type|["']type["']):[ \t]*(?:"source-document"|'source-document'|source-document)[ \t]*(?:#.*)?$/m.test(frontmatter); + if (!okf && frontmatter.includes('source-document')) fail(`ambiguous source record at ${relative(root, path)}`); + evidence[okf ? 'knowledge-store' : 'ingest'].push(relative(root, path)); + } + // Unknown workspace entries must be classified by the adopter, never guessed. + if (intake) { + const known = new Set(['profile.json', '.gitkeep', '.gitignore', 'README.md', 'inbox', 'processed', 'processing', 'snapshots', 'originals', 'drafts', 'log.md']); + for (const name of await readdir(join(root, '_intake'))) { + if (!known.has(name)) fail(`unrecognised _intake/${name}`); + await inspect(join(root, '_intake', name)); + } + } + const other = profile === 'ingest' ? 'knowledge-store' : 'ingest'; + if (evidence[other].length) fail(`${profile} requested; ${other} evidence at ${evidence[other].join(', ')}`); + + // Both profiles require a marker that survives a normal commit and clone. + const markerVisibility = spawnSync('git', ['-C', root, 'check-ignore', '--no-index', '--', MARKER], { + encoding: 'utf8', + }); + if (markerVisibility.status === 0) fail(`profile marker would be ignored: ${MARKER}`); + if (markerVisibility.status !== 1) fail('cannot verify profile marker visibility; use a Git workspace and retry the check'); + + if (profile === 'knowledge-store') { + // Git evaluates nested/global ignores and negations, including tracked files. + const paths = ['_intake/processed/profile-check.md', ...processed.map(p => relative(root, p))]; + const result = spawnSync('git', ['-C', root, 'check-ignore', '--no-index', '--stdin'], { + input: paths.join('\n') + '\n', encoding: 'utf8', + }); + if (result.status === 0) fail(`OKF source records would be ignored: ${result.stdout.trim()}`); + if (result.status !== 1) fail('cannot verify OKF record visibility; use a Git workspace and retry the check'); + } + return { profile, declared, evidence: evidence[profile] }; +} + +export async function selectIntakeProfile(orgRoot, profile) { + const result = await checkIntakeProfile(orgRoot, profile); + if (!result.declared) { + await mkdir(join(resolve(orgRoot), '_intake'), { recursive: true }); + // Exclusive creation prevents replacing a concurrent or existing selection. + await writeFile(join(resolve(orgRoot), MARKER), JSON.stringify({ version: 1, profile }, null, 2) + '\n', { flag: 'wx' }); + } + return result; +} diff --git a/packages/ingest-cli/src/intake-profile.test.mjs b/packages/ingest-cli/src/intake-profile.test.mjs new file mode 100644 index 00000000..e0145194 --- /dev/null +++ b/packages/ingest-cli/src/intake-profile.test.mjs @@ -0,0 +1,267 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, symlink, chmod } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { checkIntakeProfile, selectIntakeProfile } from './intake-profile.mjs'; +import { scaffoldIntake } from './intake.mjs'; + +const cli = fileURLToPath(new URL('../ingest.mjs', import.meta.url)); +const profileCli = fileURLToPath(new URL('../intake-profile.mjs', import.meta.url)); +const repo = fileURLToPath(new URL('../../../', import.meta.url)); +const git = (root, ...args) => spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' }); +async function workspace(t) { + const root = await mkdtemp(join(tmpdir(), 'intake-profile-')); + t.after(() => rm(root, { recursive: true, force: true })); + assert.equal(git(root, 'init', '-q').status, 0); + // Isolate test ignore rules from developer machine configuration. + assert.equal(git(root, 'config', 'core.excludesFile', '/dev/null').status, 0); + return root; +} +async function put(root, path, text = '') { + await mkdir(join(root, path, '..'), { recursive: true }); + await writeFile(join(root, path), text); +} +async function snapshot(root) { + const result = {}; + async function walk(dir) { + for (const entry of await readdir(join(root, dir), { withFileTypes: true })) { + if (entry.name === '.git') continue; + const path = join(dir, entry.name); + result[path] = entry.isDirectory() ? 'directory' : (await readFile(join(root, path))).toString('base64'); + if (entry.isDirectory()) await walk(path); + } + } + await walk(''); + return result; +} +const okf = '---\ntype: source-document\nsource: original.md\n---\nSource summary\n'; + +test('empty selection is explicit, read-only check stays read-only, scaffold is idempotent', async t => { + const root = await workspace(t); + const before = await snapshot(root); + await checkIntakeProfile(root, 'ingest'); + await checkIntakeProfile(root, 'knowledge-store'); + assert.deepEqual(await snapshot(root), before); + await scaffoldIntake(root); + const after = await snapshot(root); + await scaffoldIntake(root); + assert.deepEqual(await snapshot(root), after); + assert.equal(JSON.parse(await readFile(join(root, '_intake/profile.json'))).profile, 'ingest'); + await assert.rejects(selectIntakeProfile(root, 'knowledge-store'), /profile conflict/); + assert.deepEqual(await snapshot(root), after); +}); + +test('OKF selection refuses ingest setup and preserves source and original bytes', async t => { + const root = await workspace(t); + await selectIntakeProfile(root, 'knowledge-store'); + await put(root, '_intake/processed/source.md', okf); + await put(root, '_intake/originals/source.txt', 'retained original'); + const before = await snapshot(root); + await checkIntakeProfile(root, 'knowledge-store'); + const run = spawnSync(process.execPath, [cli, 'scaffold-intake', root], { encoding: 'utf8' }); + assert.equal(run.status, 2); + assert.match(run.stderr, /separate workspaces/); + assert.deepEqual(await snapshot(root), before); +}); + +for (const [path, content, requested] of [ + ['_intake/processed/source.md', okf, 'ingest'], + ['knowledge/index.md', '# Knowledge', 'ingest'], + ['_intake/originals/source.txt', 'original', 'ingest'], + ['_intake/drafts/draft.md', 'draft', 'ingest'], + ['_intake/log.md', 'log', 'ingest'], + ['_intake/processing/candidate.yaml', 'pending', 'knowledge-store'], + ['_intake/snapshots/regulation.txt', 'raw', 'knowledge-store'], + ['operations/config/scan-sources.yaml', 'sources: []', 'knowledge-store'], + ['_intake/processed/raw.txt', 'raw', 'knowledge-store'], + ['_intake/unknown/data', 'unknown', 'ingest'], +]) test(`legacy evidence ${path} refuses ${requested} without writes`, async t => { + const root = await workspace(t); + await put(root, path, content); + const before = await snapshot(root); + await assert.rejects(selectIntakeProfile(root, requested), /profile conflict/); + assert.deepEqual(await snapshot(root), before); +}); + +test('mixed evidence refuses both profiles even with a matching marker', async t => { + const root = await workspace(t); + await selectIntakeProfile(root, 'ingest'); + await put(root, '_intake/processed/source.md', okf); + await put(root, '_intake/processing/raw.txt', 'raw'); + const before = await snapshot(root); + for (const profile of ['ingest', 'knowledge-store']) { + await assert.rejects(selectIntakeProfile(root, profile), /profile conflict/); + } + assert.deepEqual(await snapshot(root), before); +}); + +for (const [path, ignore] of [ + ['.gitignore', '_intake/processed/*\n'], + ['_intake/.gitignore', 'processed/\n'], + ['_intake/processed/.gitignore', '*.md\n'], + ['.git/info/exclude', '_intake/processed/**\n'], +]) test(`OKF refuses effective ignore rules in ${path}`, async t => { + const root = await workspace(t); + await put(root, path, ignore); + const before = await snapshot(root); + await assert.rejects(selectIntakeProfile(root, 'knowledge-store'), /profile conflict/); + assert.deepEqual(await snapshot(root), before); +}); + +test('Git negation permits OKF; ignored tracked records are still refused', async t => { + const root = await workspace(t); + await put(root, '.gitignore', '_intake/processed/*\n!_intake/processed/*.md\n'); + await put(root, '_intake/processed/source.md', okf); + assert.equal(git(root, 'add', '_intake/processed/source.md').status, 0); + await checkIntakeProfile(root, 'knowledge-store'); + await put(root, '.gitignore', '_intake/processed/source.md\n'); + await assert.rejects(checkIntakeProfile(root, 'knowledge-store'), /would be ignored/); +}); + +test('invalid marker, unknown selection, and symlink fail closed', async t => { + const root = await workspace(t); + await assert.rejects(selectIntakeProfile(root, 'unknown'), /Choose --profile/); + await put(root, '_intake/profile.json', '{broken'); + await assert.rejects(selectIntakeProfile(root, 'ingest')); + await rm(join(root, '_intake/profile.json')); + await mkdir(join(root, 'elsewhere')); + await symlink(join(root, 'elsewhere'), join(root, '_intake/processed')); + await assert.rejects(scaffoldIntake(root), /symlink/); + assert.deepEqual(await readdir(join(root, 'elsewhere')), []); +}); + +for (const profile of ['ingest', 'knowledge-store']) { + for (const tracked of [false, true]) test(`${profile} refuses an ignored ${tracked ? 'tracked' : 'new'} marker without writes`, async t => { + const root = await workspace(t); + await put(root, '_intake/inbox/source.txt', 'retain these bytes'); + if (tracked) { + await selectIntakeProfile(root, profile); + assert.equal(git(root, 'add', '_intake/profile.json').status, 0); + } + await put(root, '.gitignore', '_intake/profile.json\n'); + const before = await snapshot(root); + await assert.rejects(checkIntakeProfile(root, profile), /profile marker would be ignored/); + await assert.rejects(selectIntakeProfile(root, profile), /profile marker would be ignored/); + assert.deepEqual(await snapshot(root), before); + }); + + test(`${profile} permits an explicitly unignored marker`, async t => { + const root = await workspace(t); + await put(root, '.gitignore', '_intake/*.json\n!_intake/profile.json\n'); + await selectIntakeProfile(root, profile); + assert.equal(JSON.parse(await readFile(join(root, '_intake/profile.json'))).profile, profile); + }); + + test(`${profile} selection requires Git visibility verification`, async t => { + const root = await workspace(t); + await rm(join(root, '.git'), { recursive: true }); + await assert.rejects(selectIntakeProfile(root, profile), /Git workspace/); + assert.deepEqual(await readdir(root), []); + }); +} + +test('reg-intel daily driver refuses OKF before invoking hooks or its CLI', async t => { + const root = await workspace(t); + await selectIntakeProfile(root, 'knowledge-store'); + const bin = join(root, 'bin'); + await mkdir(bin); + const launcher = join(bin, 'transitrix-intake-profile'); + const quote = value => "'" + value.replaceAll("'", "'\\''") + "'"; + await writeFile(launcher, `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(profileCli)} \"$@\"\n`); + await chmod(launcher, 0o755); + const before = await snapshot(root); + const run = spawnSync('bash', [join(repo, 'transitrix/skills/reg-intel/templates/reg-intel-daily.sh'), root], { + encoding: 'utf8', env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + }); + assert.equal(run.status, 2); + assert.match(run.stderr, /profile conflict/); + assert.deepEqual(await snapshot(root), before); +}); + +for (const conflict of [null, 'ignored-marker', 'OKF-record']) { + test(`legacy daily driver selects before its CLI or refuses unchanged: ${conflict || 'compatible'}`, async t => { + const root = await workspace(t); + await put(root, 'operations/config/scan-sources.yaml', 'sources: []\n'); + await put(root, '_intake/inbox/raw.txt', 'retained input'); + if (conflict === 'ignored-marker') await put(root, '.gitignore', '_intake/profile.json\n'); + if (conflict === 'OKF-record') await put(root, '_intake/processed/source.md', okf); + const bin = join(root, 'bin'); + const quote = value => "'" + value.replaceAll("'", "'\\''") + "'"; + await put(root, 'bin/transitrix-intake-profile', `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(profileCli)} "$@"\n`); + // Replace npx so the real driver is exercised without network access. Every + // downstream command must observe the selection, including the first read. + await put(root, 'bin/npx', `#!/bin/sh +set -eu +cd ${quote(root)} +${quote(process.execPath)} -e 'const p = require("./_intake/profile.json"); if (p.version !== 1 || p.profile !== "ingest") process.exit(91)' +echo "$2" >> cli-calls +if [ "$2" = list-due ]; then echo '[{"id":"REGULATION-1","monitoring_needed":false}]'; fi +if [ "$2" = check-signal ]; then echo '{"proceed":false}'; fi +`); + for (const name of ['npx', 'transitrix-intake-profile']) await chmod(join(bin, name), 0o755); + const before = await snapshot(root); + const run = () => spawnSync('bash', [join(repo, 'transitrix/skills/reg-intel/templates/reg-intel-daily.sh'), root], { + encoding: 'utf8', env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + }); + const first = run(); + if (conflict) { + assert.equal(first.status, 2, first.stderr); + assert.match(first.stderr, /profile conflict/); + assert.deepEqual(await snapshot(root), before); + } else { + assert.equal(first.status, 0, first.stderr); + assert.match(await readFile(join(root, 'cli-calls'), 'utf8'), /^list-due\n/); + // Preserve even noncanonical formatting on an existing matching marker. + const marker = '{ "version": 1, "profile": "ingest" }\n'; + await put(root, '_intake/profile.json', marker); + assert.equal(run().status, 0); + assert.equal(await readFile(join(root, '_intake/profile.json'), 'utf8'), marker); + assert.equal(await readFile(join(root, '_intake/inbox/raw.txt'), 'utf8'), 'retained input'); + } + }); +} + +test('packed preflight works without a methodology checkout or vocabulary', async t => { + const root = await workspace(t); + const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; + const cache = join(root, 'cache'); + const packed = spawnSync(npm, ['pack', fileURLToPath(new URL('../', import.meta.url)), + '--pack-destination', root, '--cache', cache, '--ignore-scripts', '--json'], { encoding: 'utf8' }); + assert.equal(packed.status, 0, packed.stderr); + const archive = join(root, JSON.parse(packed.stdout)[0].filename); + const installed = spawnSync(npm, ['install', '--prefix', join(root, 'installed'), '--cache', cache, + '--ignore-scripts', '--no-audit', '--no-fund', '--offline', archive], { encoding: 'utf8' }); + assert.equal(installed.status, 0, installed.stderr); + const binary = join(root, 'installed/node_modules/@transitrix/ingest-cli/intake-profile.mjs'); + const before = await readFile(join(root, '.git/config'), 'utf8'); + for (const profile of ['ingest', 'knowledge-store']) { + const check = spawnSync(process.execPath, [binary, 'check', root, '--profile', profile], { encoding: 'utf8' }); + assert.equal(check.status, 0, check.stderr); + } + const selected = spawnSync(process.execPath, [binary, 'select', root, '--profile', 'knowledge-store'], { encoding: 'utf8' }); + assert.equal(selected.status, 0, selected.stderr); + const refused = spawnSync(process.execPath, [binary, 'select', root, '--profile', 'ingest'], { encoding: 'utf8' }); + assert.equal(refused.status, 2); + assert.match(refused.stderr, /separate workspaces/); + assert.equal(await readFile(join(root, '.git/config'), 'utf8'), before); +}); + +for (const type of ['type: source-document # retained', '"type": "source-document"', "type: 'source-document'"]) { + test(`legacy OKF scalar ${type} refuses ingest`, async t => { + const root = await workspace(t); + await put(root, '_intake/processed/source.md', `---\n${type}\n---\nSummary\n`); + await assert.rejects(scaffoldIntake(root), /profile conflict/); + assert.deepEqual(await readdir(join(root, '_intake')), ['processed']); + }); +} + +test('invalid stage shape refuses before recording selection', async t => { + const root = await workspace(t); + await put(root, '_intake/inbox', 'not a directory'); + const before = await snapshot(root); + await assert.rejects(scaffoldIntake(root), /not a directory/); + assert.deepEqual(await snapshot(root), before); +}); diff --git a/packages/ingest-cli/src/intake.mjs b/packages/ingest-cli/src/intake.mjs index 2fac4422..42878386 100644 --- a/packages/ingest-cli/src/intake.mjs +++ b/packages/ingest-cli/src/intake.mjs @@ -5,6 +5,8 @@ import { mkdir, rename, access, readFile, writeFile } from 'node:fs/promises'; import { join, dirname, resolve, basename } from 'node:path'; +import { selectIntakeProfile } from './intake-profile.mjs'; + export const INTAKE = '_intake'; export const STAGES = ['inbox', 'processing', 'processed']; @@ -22,6 +24,7 @@ async function exists(p) { // .gitignore pairs `_intake//*` with `!_intake/**/.gitkeep`. export async function scaffoldIntake(orgRoot) { const root = resolve(orgRoot); + await selectIntakeProfile(root, 'ingest'); const created = []; const existing = []; for (const stage of STAGES) { diff --git a/patterns/knowledge-store.md b/patterns/knowledge-store.md index 3c06d897..89e4b357 100644 --- a/patterns/knowledge-store.md +++ b/patterns/knowledge-store.md @@ -11,6 +11,50 @@ Transitrix includes an optional knowledge store component for organisations that need a structured curation layer between raw source material and the canonical model. The knowledge store is part of the methodology — not a separate or competing system. It uses [Google Cloud Open Knowledge Format (OKF) v0.1](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf) as its storage format, which provides interoperability with OKF-compatible tooling while keeping knowledge objects fully within the Transitrix lifecycle. +## Deployment profiles and intake compatibility + +Choose one intake profile per repository/workspace before setup: + +| Profile | Consumer | `_intake/processed/` ownership and retention | +|---|---|---| +| `ingest` | Ordinary ingest and reg-intel, together | Completed raw source files, private/gitignored | +| `knowledge-store` | OKF curation | Committed OKF `source-document` records; raw originals stay in gitignored `_intake/originals/` | + +These profiles are **not supported together in one workspace**. Use separate +workspaces if both are needed. This is a deployment boundary, not a migration or +co-installation contract. Leave existing files and retention rules untouched. + +Before setup or an ingestion run, use the shared preflight in `@transitrix/ingest-cli` +(Node 20+). Pre-1.0, install it from a methodology checkout with +`npm install -g ./packages/ingest-cli`; this package is not yet published to npm. +The `transitrix-intake-profile` binary is independent of document conversion, +extraction and vocabulary loading: + +```bash +transitrix-intake-profile check --profile knowledge-store +transitrix-intake-profile select --profile knowledge-store +``` + +Use `--profile ingest` for the ordinary ingest/reg-intel profile. `check` is +read-only; `select` repeats the check and records the explicit selection in +`_intake/profile.json` (version 1), without overwriting an existing selection. +Commit that marker with setup. It is skill-local operational metadata, not a +manifest field, coverage profile or permission grant. Re-run the check before +subsequent intake writes; the marker does not override conflicting evidence. + +Detection checks the marker, profile-specific directories, the regulatory watch +list, and processed content (OKF source-document frontmatter versus raw files). +Mixed evidence, unknown intake entries, symlinks or unreadable evidence stop setup +for adopter inspection. The OKF check also uses Git's effective ignore rules, +including nested/global rules and tracked files, to refuse hidden source records. +It requires an existing Git workspace; if absent, request authorised Git setup +before retrying. New or empty intake directories and shared `inbox/` alone do not +choose a profile. Explicit selection is required. No tool silently renames paths, +changes ignore rules, force-adds records, migrates data, or combines profiles. +A conflict is resolved by selecting a separate compatible workspace, not by +removing evidence or changing the marker. If the preflight is unavailable, stop +setup instead of reimplementing or skipping it. + ## Problem Raw source material — interview notes, meeting summaries, research documents — accumulates faster than it can be curated into the canonical model. Authors dump directly into `canon/` and quality degrades, or they leave everything in `field/` and canon never grows. There is no structured hand-off between "collected" and "validated". diff --git a/scripts/check-notations.test.mjs b/scripts/check-notations.test.mjs index 60283bc7..e3bff1b2 100644 --- a/scripts/check-notations.test.mjs +++ b/scripts/check-notations.test.mjs @@ -981,9 +981,12 @@ test('a broken real instruction and incomplete template tree still fail shared c await checkIdGrammar(ids, [feedback]); assert.equal(ids.length, 1); const knowledge = resolve('transitrix/skills/knowledge-store/SKILL.md'); - const links = findInstructionLinkFailures(readFileSync(knowledge, 'utf8') + const knowledgeText = readFileSync(knowledge, 'utf8'); + const links = findInstructionLinkFailures(knowledgeText .replaceAll('../../../patterns/', '../../../../patterns/'), knowledge); - assert.equal(links.length, 5); + const patternLinks = [...knowledgeText.matchAll(/\]\(\.\.\/\.\.\/\.\.\/patterns\//g)].length; + assert.ok(patternLinks >= 5); + assert.equal(links.length, patternLinks); const template = join(root, 'AGENTS.md'); const text = readFileSync('transitrix/skills/onboard/templates/AGENTS.md', 'utf8'); writeFileSync(template, text); @@ -1017,3 +1020,22 @@ test('actual onboarding guides resolve after copying to their documented destina assert.ok(findInstructionLinkFailures(readFileSync(guide, 'utf8'), guide, root).length > 0); } finally { rmSync(root, { recursive: true, force: true }); } }); + +test('knowledge-store placeholders cannot pass the canonical repository ID check', async () => { + const { repoCheck } = await import('../packages/ingest-cli/src/repo-check.mjs'); + const root = mkdtempSync(join(tmpdir(), 'canon-review-')); + try { + const dir = join(root, 'canon/elements/01_motivation/drivers'); + mkdirSync(dir, { recursive: true }); + const file = join(dir, 'candidate.yaml'); + const draft = 'id: DRIVER-TBD\nname: Draft pressure\nadmitted_to: pending\n'; + writeFileSync(file, draft); + const pending = await repoCheck(root); + assert.ok(pending.integrity.red_flags.some(f => f.includes('canonical grammar'))); + writeFileSync(file, draft.replace('DRIVER-TBD', 'DRIVER-1')); + const reviewed = await repoCheck(root); + assert.ok(!reviewed.integrity.red_flags.some(f => f.includes('canonical grammar'))); + // A valid ID alone is not evidence of completed admission. + assert.match(readFileSync(file, 'utf8'), /admitted_to: pending/); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/transitrix/skills/feedback/README.md b/transitrix/skills/feedback/README.md index 0c6ab4ca..911bb4d5 100644 --- a/transitrix/skills/feedback/README.md +++ b/transitrix/skills/feedback/README.md @@ -2,8 +2,8 @@ Helps a user go from "the methodology can't express this" (or "this tool made that harder than it should be") to a scrubbed, committed entry in the repo's own -`operations/feedback.md` register — the entry point to the upstream feedback channel -[`method/06-team-operations.md`](../../../method/06-team-operations.md) §3.3 specifies +`operations/feedback/feedback.md` journal (or preserved legacy `operations/feedback.md`) — the entry point to the upstream feedback channel +[`method/06-team-operations.md`](../../../method/06-team-operations.md) §3.2 specifies but ships no workflow for. This directory is the **`feedback` skill** within the `transitrix` plugin (the plugin @@ -13,9 +13,9 @@ root is [`transitrix/`](../../), which carries the shared ## Why it exists -`FINDINGS.md`'s propose → route → scrub protocol names `operations/feedback.md` as the -landing place for a methodology-directed finding (`escalate-methodology`), and -`method/06-team-operations.md` §3.3 defines the record's shape and status +`FINDINGS.md`'s propose → route → scrub protocol uses the journal selected by +[`SKILL.md` Step 0](SKILL.md#step-0--locate-or-scaffold-operationsfeedbackfeedbackmd) as the landing place for a methodology-directed finding (`escalate-methodology`), and +`method/06-team-operations.md` §3.2 defines the record's shape and status vocabularies — but neither ships a workflow for actually *authoring* an entry. A user (or an autonomous agent resolving a `FINDINGS.md` routing decision) still had to hand-write the field set, allocate the next `FB-NNNN`, and remember the anonymisation @@ -28,7 +28,9 @@ discipline themselves. This skill is that workflow. writing them here. - Not a submission mechanism — exporting an entry (on request only) renders ready-to-send text addressed to `hello@transitrix.com`; the skill never sends it, - never opens a PR or issue elsewhere, and never calls a network endpoint. + never opens a PR or issue elsewhere, and never calls an upstream submission + endpoint. An authorised push and PR in the adopter's repository deliver the + locally confirmed entry (Step 6). - Not an editor of past entries' substance — a later invocation updates `status` and `upstream` only; the original `observation`/`proposed`/`type`/`methodology_version` stay fixed once authored. diff --git a/transitrix/skills/feedback/SKILL.md b/transitrix/skills/feedback/SKILL.md index b9df6686..31ea3bea 100644 --- a/transitrix/skills/feedback/SKILL.md +++ b/transitrix/skills/feedback/SKILL.md @@ -1,6 +1,6 @@ --- name: Transitrix Feedback -description: Author an upstream methodology-directed finding as a gated, anonymised entry in the repo's own operations/feedback.md register — the input door to the upstream feedback channel method/06-team-operations.md §3.2 specifies but ships no workflow for. Routes non-methodology observations away first, runs an interview, composes and shows the scrubbed wording for confirmation before writing, allocates the next FB-NNNN, and (on request only) renders a ready-to-send message for hello@transitrix.com without ever transmitting it itself. +description: Author an upstream methodology-directed finding as a gated, anonymised entry in the repo's own feedback journal (operations/feedback/feedback.md, or preserved legacy operations/feedback.md) — the input door to the upstream feedback channel method/06-team-operations.md §3.2 specifies but ships no workflow for. Routes non-methodology observations away first, runs an interview, composes and shows the scrubbed wording for confirmation before writing, allocates the next FB-NNNN, and (on request only) renders a ready-to-send message for hello@transitrix.com without ever transmitting it upstream itself. when_to_use: User says "log this as feedback for the methodology", "this is a gap in the notation, write it up", "raise a finding upstream", "update FB-0002 to triaged", "what feedback have we filed", or an agent operating under FINDINGS.md's propose → route → scrub protocol resolves an incidental finding's routing to escalate-methodology and needs to write the resulting entry. min_version: "2.1.0" allowed-tools: Read, Write, Edit, Bash, Glob, Grep @@ -22,8 +22,7 @@ root is [`transitrix/`](../../), which carries the shared [`.claude-plugin/plugin.json`](../../.claude-plugin/plugin.json) manifest, one `skills//` directory per skill). Invoked as `/transitrix:feedback`. Written for any coding agent that can read/write files and run shell commands, not only Claude -Code — same portability discipline as the `adr` skill -([`transitrix/skills/adr`](../adr/)) — check its structure before changing this one. +Code. Mechanism this skill sequences (read before or during first use): [`method/06-team-operations.md`](../../../method/06-team-operations.md) §3.2 (the @@ -45,12 +44,11 @@ This `SKILL.md` does not restate the mechanism — it sequences it. confirmation. It refuses to write an entry carrying a canonical-grammar element ID, a `canon/`/`field/` path, or organisation-identifying detail — this is a hard refusal, not a suggestion the user can wave through. See Step 3. -3. **No network, ever, from this skill.** Writing an entry is a local commit to the - adopter's own repo (Step 5, PR — same as `adr`). Exporting an entry (Step 7) only - renders text for the user to paste into an email themselves — it never sends, - never opens an issue or PR on any other repo, and never calls a network endpoint. - The worst this skill can do unattended is leave a `proposed`-shaped local entry - sitting in a PR. +3. **Adopter-repository delivery only; no automatic upstream export.** Step 6 + permits an authorised push and PR in the adopter's own repository after the + scrub and confirmation gates. Step 7 only renders text for the user to send; + it never transmits the entry upstream, opens an issue or PR in another + repository, or calls an external submission endpoint. --- @@ -274,8 +272,8 @@ never as part of Steps 4–6): - Does **not** skip or soften the scrub gate — an entry carrying an element ID, a canon path, or organisation-identifying detail is refused, not flagged as a warning the user can override (Step 3). -- Does **not** send, transmit, or push an entry anywhere on its own, at any step — - export (Step 7) only renders text; the human sends it, if they choose to at all. +- Does **not** export entries upstream — Step 7 only renders text for the human + to send. Authorised adopter-repository push/PR delivery belongs to Step 6. - Does **not** invent a second feedback location — the journal is either a single file (`operations/feedback.md`) or a directory-based journal (`operations/feedback/feedback.md`), never both, per `method/06-team-operations.md` §3.2. If both layouts exist (migration conflict), diff --git a/transitrix/skills/ingest/README.md b/transitrix/skills/ingest/README.md index 1865b571..8a48de77 100644 --- a/transitrix/skills/ingest/README.md +++ b/transitrix/skills/ingest/README.md @@ -6,6 +6,15 @@ This directory is the **`ingest` skill** within the `transitrix` plugin (the plu > **Status — operational.** Beyond the agent-facing protocol ([`SKILL.md`](SKILL.md)), JSON schemas ([`schemas/`](schemas/)), and the `_intake/` convention ([`templates/_intake.README.md`](templates/_intake.README.md)), the deterministic CLI ([`@transitrix/ingest-cli`](../../../packages/ingest-cli/)) implements all subcommands and is covered by a no-API-key integrity test (see [Roadmap](#roadmap)). The skill's Step 0 pre-check still stops cleanly if the CLI is not installed in a given environment. +## Intake profile selection + +Choose `ingest` for the ordinary ingest/reg-intel workflow (private processed raw +files), or `knowledge-store` for OKF curation (committed source-document records, +private originals). They require separate workspaces. Setup and subsequent intake +runs must pass the shared CLI preflight; incompatible or ambiguous existing +content is refused without migration. See the [deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility) +for selection, installation and retention rules. + --- ## The one rule diff --git a/transitrix/skills/ingest/SKILL.md b/transitrix/skills/ingest/SKILL.md index 8a7402ac..644c2091 100644 --- a/transitrix/skills/ingest/SKILL.md +++ b/transitrix/skills/ingest/SKILL.md @@ -69,6 +69,13 @@ to run. Recognition and promotion never admit an element or rewrite its local ID transitrix-ingest scaffold-intake ``` +The scaffold first checks compatibility and records `ingest` in +`_intake/profile.json`; a knowledge-store workspace or mixed evidence is refused +before any write. Commit the marker with setup. On subsequent runs (including +shortcuts that skip scaffolding), run +`transitrix-intake-profile check --profile ingest` before intake +writes. See the [deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility). + Idempotent — it never overwrites existing intake content. A source file flows `inbox/ → processing/ → processed/`. `_intake/` is a **per-user, private workspace** — its contents are git-ignored and not shared with other modellers, so nothing that participates in the model lives here (an untyped object goes to the shared `canon/unresolved/`, Step 7, never to `_intake/`). `scaffold-intake` drops a `.gitkeep` in each of `inbox/` / `processing/` / `processed/` so the folder skeleton stays in version control while the working files are ignored — the adopter's `.gitignore` carries `_intake/inbox/*`, `_intake/processing/*`, `_intake/processed/*` and `!_intake/**/.gitkeep` (the onboarding skill seeds these). In v0 the `_intake/` convention is **skill-local**: it is documented here and in [`templates/_intake.README.md`](templates/_intake.README.md), not yet reserved in the methodology MANIFEST/CONTRACT. (Promotion to a reserved org-structure convention is a separate proposal once the skill stabilises.) --- diff --git a/transitrix/skills/ingest/templates/_intake.README.md b/transitrix/skills/ingest/templates/_intake.README.md index 20d9861a..6d240b61 100644 --- a/transitrix/skills/ingest/templates/_intake.README.md +++ b/transitrix/skills/ingest/templates/_intake.README.md @@ -40,3 +40,9 @@ _intake/processed/* ## Status In the current methodology version the `_intake/` convention is defined by the ingest skill (skill-local). It is not yet a reserved org-structure convention in the methodology `MANIFEST.md` / `CONTRACT.md`; that promotion is a separate decision taken once the skill stabilises. + +This workspace uses the `ingest` deployment profile: processed raw files remain +private/gitignored. OKF knowledge-store uses a separate workspace with committed +source records at the same relative path; co-installation is unsupported. Run +`transitrix-intake-profile check --profile ingest` before writes. +The committed `profile.json` records setup selection and does not override conflicts. diff --git a/transitrix/skills/ingest/tests/test_ingest_integrity.py b/transitrix/skills/ingest/tests/test_ingest_integrity.py index 81435a9d..b859ae67 100644 --- a/transitrix/skills/ingest/tests/test_ingest_integrity.py +++ b/transitrix/skills/ingest/tests/test_ingest_integrity.py @@ -155,6 +155,13 @@ def run_cli(*args): return subprocess.run(["node", CLI, *args], capture_output=True, text=True) +def scaffold_fixture(org): + # Profile selection verifies that its marker can be committed by the adopter. + subprocess.run(["git", "init", "-q", org], check=True, capture_output=True) + subprocess.run(["git", "-C", org, "config", "core.excludesFile", os.devnull], check=True) + return run_cli("scaffold-intake", org) + + def part_b_pipeline(): if not shutil.which("node"): print("SKIP Part B: `node` not found on PATH (the CLI is Node).") @@ -167,7 +174,7 @@ def part_b_pipeline(): org = os.path.join(work, "org") os.makedirs(org) - r = run_cli("scaffold-intake", org) + r = scaffold_fixture(org) check(r.returncode == 0, f"scaffold-intake failed: {r.stderr.strip()}") with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: @@ -273,7 +280,7 @@ def part_c_ig5(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -342,7 +349,7 @@ def part_d_ig1(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -402,7 +409,7 @@ def part_e_ig2(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -494,7 +501,7 @@ def part_f_ig3(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') inbox = os.path.join(org, "_intake", "inbox") @@ -548,7 +555,7 @@ def _coverage_org(manifest_body): work = tempfile.mkdtemp(prefix="ingest-cp-") org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write(manifest_body) cdir = os.path.join(org, "_intake", "processing", "candidates") @@ -639,7 +646,7 @@ def part_h_idempotent(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -737,7 +744,7 @@ def part_i_placement(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') cdir = os.path.join(org, "_intake", "processing", "candidates") @@ -805,7 +812,7 @@ def part_j_duplicate_source(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -883,7 +890,7 @@ def part_k_suggest_profile(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: core\n') @@ -914,7 +921,7 @@ def cand(name, obj): # Under `full`, nothing is out of profile → no delta proposed. org2 = os.path.join(work, "org2") os.makedirs(org2) - run_cli("scaffold-intake", org2) + scaffold_fixture(org2) with open(os.path.join(org2, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') cdir2 = os.path.join(org2, "_intake", "processing", "candidates") @@ -990,7 +997,7 @@ def part_m_id_grammar(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') fdir = os.path.join(org, "field", "interviews") @@ -1042,7 +1049,7 @@ def part_n_entity_resolution(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -1127,7 +1134,7 @@ def part_o_unresolved_extensions(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.6.0"\ncoverage_profile: full\n') @@ -1227,7 +1234,7 @@ def part_p_preset_version_currency(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "%s"\ncoverage_profile: core\n' % PRESETS_VERSION) @@ -1262,7 +1269,7 @@ def part_q_origin_classification(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.7.0"\ncoverage_profile: full\n') @@ -1344,7 +1351,7 @@ def part_r_privacy_gate(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') inbox = os.path.join(org, "_intake", "inbox") @@ -1420,7 +1427,7 @@ def part_r_privacy_gate(): # privacy-report.yaml records it and never leaks a fragment verbatim. org2 = os.path.join(work, "org2") os.makedirs(org2) - run_cli("scaffold-intake", org2) + scaffold_fixture(org2) with open(os.path.join(org2, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n' 'ingest:\n privacy_gate:\n enabled: true\n on_detection: reject\n') @@ -1449,7 +1456,7 @@ def part_r_privacy_gate(): # with NO privacy-scan record at all. org3 = os.path.join(work, "org3") os.makedirs(org3) - run_cli("scaffold-intake", org3) + scaffold_fixture(org3) with open(os.path.join(org3, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n' 'ingest:\n privacy_gate:\n enabled: false\n') @@ -1596,7 +1603,7 @@ def part_t_batch_naming(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -1670,7 +1677,7 @@ def part_u_source_idempotency_after_move(): try: org = os.path.join(work, "org") os.makedirs(org) - run_cli("scaffold-intake", org) + scaffold_fixture(org) with open(os.path.join(org, "transitrix.yaml"), "w", encoding="utf-8") as fh: fh.write('transitrix: 1\nmethodology_version: "0.5.0"\ncoverage_profile: full\n') @@ -1794,6 +1801,14 @@ def admit_codex(*extra): check(admission.returncode == 0, "Candidate admission regression: " + admission.stdout + admission.stderr) +# Exercise profile refusal, data preservation and packaged setup in this CI gate. +profiles = subprocess.run( + ["node", "--test", os.path.join(REPO_ROOT, "packages", "ingest-cli", "src", "intake-profile.test.mjs")], + capture_output=True, text=True, timeout=60, +) +check(profiles.returncode == 0, + "Intake profile compatibility: " + profiles.stdout + profiles.stderr) + if _failures: print("FAIL - Transitrix Ingest skill integrity:") for f in _failures: diff --git a/transitrix/skills/knowledge-store/README.md b/transitrix/skills/knowledge-store/README.md index 5fa8aff5..d3c50984 100644 --- a/transitrix/skills/knowledge-store/README.md +++ b/transitrix/skills/knowledge-store/README.md @@ -1,9 +1,18 @@ # Transitrix Knowledge Store Skill -The **OKF ingestion skill** for a Transitrix knowledge store. Processes raw source material through the OKF single-repo MVP pattern: assess → archive → route → extract → human review → write. All steps are performed by the agent with standard file tools — no external CLI required. +The **OKF ingestion skill** for a Transitrix knowledge store. Processes raw source material through the OKF single-repo MVP pattern: assess → archive → route → extract → human review → write. The agent extracts and curates with standard file tools. Setup first runs the shared intake-profile preflight from `@transitrix/ingest-cli`. This directory is the **`knowledge-store` skill** within the `transitrix` plugin. Invoked as `/transitrix:knowledge-store`. +## Intake profile selection + +Choose `ingest` for the ordinary ingest/reg-intel workflow (private processed raw +files), or `knowledge-store` for OKF curation (committed source-document records, +private originals). They require separate workspaces. Setup and subsequent intake +runs must pass the shared CLI preflight; incompatible or ambiguous existing +content is refused without migration. See the [deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility) +for selection, installation and retention rules. + --- ## The one rule diff --git a/transitrix/skills/knowledge-store/SKILL.md b/transitrix/skills/knowledge-store/SKILL.md index d4f43696..56750a41 100644 --- a/transitrix/skills/knowledge-store/SKILL.md +++ b/transitrix/skills/knowledge-store/SKILL.md @@ -8,7 +8,7 @@ allowed-tools: Read, Write, Edit, Bash, Glob, Grep # Transitrix Knowledge Store Skill -Processes raw source material through the OKF single-repo MVP knowledge store. All work is done by the agent using Read/Write/Edit tools — no external CLI required. A human reviews and approves before anything lands in `knowledge/` or `canon/`. +Processes raw source material through the OKF single-repo MVP knowledge store. Extraction and curation use the agent's Read/Write/Edit tools; setup requires the shared intake-profile preflight from `@transitrix/ingest-cli`. A human reviews and approves before anything lands in `knowledge/` or `canon/`. --- @@ -28,6 +28,20 @@ The linter enforces Gates 1–6 from [patterns/knowledge-store.md §Quality gate ## Step 0 — Check the MVP structure +Before any write, select the **knowledge-store** deployment profile using the +[compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility). +Run the shared CLI preflight (see that contract for local installation): + +```bash +transitrix-intake-profile check --profile knowledge-store +transitrix-intake-profile select --profile knowledge-store +``` + +Stop if unavailable or refused; do not scaffold, move sources or change ignore +rules to bypass a conflict. Ordinary ingest/reg-intel belongs in a separate +workspace. Commit `_intake/profile.json` with setup. On later runs repeat the +read-only check before any write, including when the marker already exists. + Verify the repo has the expected layout: ``` @@ -43,7 +57,7 @@ knowledge/ .md ← individual OKF knowledge objects ``` -If `_intake/` or `knowledge/` are missing, scaffold them now. Create `_intake/drafts/` if absent. Copy the initialisation content from [patterns/knowledge-store.md §Templates](../../../patterns/knowledge-store.md). Add gitignore entries for `_intake/inbox/*` and `_intake/originals/*` (drafts MAY be committed for audit or gitignored for ephemeral runs). +If `_intake/` or `knowledge/` are missing, scaffold them now. Create `_intake/drafts/` if absent. Copy the initialisation content from [patterns/knowledge-store.md §Templates](../../../patterns/knowledge-store.md). Add gitignore entries for `_intake/inbox/*` and `_intake/originals/*` (drafts MAY be committed for audit or gitignored for ephemeral runs). Never ignore `_intake/processed/`. Re-run the profile check after setup and before committing; explicitly verify each new source-record path is not ignored before writing it. --- @@ -168,11 +182,11 @@ For each object held because it **conflicts** with existing knowledge (not admit Using the extraction prompt at [prompts/extract-canon.md](prompts/extract-canon.md), identify candidate Transitrix elements (DRIVER, GOAL, CHANGE, CAPABILITY, ACTOR, ROLE, PROCESS, APPLICATION, PRODUCT, etc.) and typed relations. Be conservative on relations — only propose a relation when the source explicitly states the connection. -For each candidate, draft a YAML block in the format expected by `canon/elements//`: +Draft candidate YAML blocks in a YAML review file under `_intake/drafts/` (for example `canon-candidates.yaml`), outside `canon/`. These are extraction proposals, not valid canonical elements yet: ```yaml type: DRIVER -id: DRIV-NNN # assign the next available integer +id: -TBD # review placeholder, never an admitted ID name: "" description: "" derived_from: [] @@ -180,15 +194,31 @@ admitted_to: pending extraction_confidence: high | medium | low ``` -### 5b — Open PR - -Create a branch `knowledge-store/ingest--` and commit the candidate YAML files. Open a PR titled `[Knowledge Store] Ingest: `. +### 5b — Review IDs, validate, then open PR + +1. Present the draft candidates to the human reviewer. Keep `admitted_to: pending`; + no admission record is invented. Resolve duplicate candidates against existing + canon before reserving IDs. +2. During review, replace every `*-TBD` placeholder with a unique ID under + [IDS_AND_REFERENCES §§1–2](../../../notations/IDS_AND_REFERENCES.md), including + the CAPABILITY V/H exception. Resolve every relation endpoint to a reviewed ID. + A placeholder is never a canonical ID, filename or admitted reference. +3. Prepare reviewed candidates at the TYPE's canonical placement from + [ELEMENT_PRIMITIVES §4](../../../notations/ELEMENT_PRIMITIVES.md), not a generic + per-type path. Apply the required envelope and TYPE fields; retain provenance + and pending status until human admission under [CONTRACT §6](../../../notations/CONTRACT.md). +4. Run the adopter's canonical validators for ID uniqueness, reference consistency, + required fields and placement. Unresolved placeholders or failed checks block + the canon PR; keep those proposals in the draft YAML review file. Review flags + such as `extraction_confidence` never become admitted canon fields. + +Create a branch `knowledge-store/ingest--` and commit only the reviewed, validated candidate files for human admission. Open a PR titled `[Knowledge Store] Ingest: `. PR body must include: - Link to the processed source-document record - Table of proposed elements with type, name, and extraction_confidence - Note on any relations proposed -- Instruction: "Review, revise IDs to avoid conflicts, and merge when satisfied." +- Instruction: "Review the assigned IDs, resolved references, provenance and validation results; complete admission only when satisfied. Never merge unresolved placeholders or pending proposals as admitted canon." ### 5c — Log assertion outcome (after PR is merged or closed) @@ -210,6 +240,6 @@ Or for rejected: - Does not merge PRs. The canon gate is always a human. - Does not write to `knowledge/` before user review of drafts (Gate 6 — drafts land in `_intake/drafts/` only). -- Does not assign `extraction_confidence: high` to relations — relations are flagged `medium` or lower unless the source text is unambiguous. +- Does not assign `extraction_confidence: high` to relations — relations are always flagged `medium` or lower and require human validation. - Does not remove or rewrite existing knowledge objects. Re-curation adds a successor and lifecycle metadata under Gate 2.1. - Does not process multiple documents in the same run unless explicitly asked — one source per run keeps the log clean. diff --git a/transitrix/skills/knowledge-store/prompts/extract-canon.md b/transitrix/skills/knowledge-store/prompts/extract-canon.md index 5a8356ac..1944bc81 100644 --- a/transitrix/skills/knowledge-store/prompts/extract-canon.md +++ b/transitrix/skills/knowledge-store/prompts/extract-canon.md @@ -62,4 +62,4 @@ List all candidate elements, grouped by type. Then list all candidate relations. - Total elements and relations proposed - Elements or passages skipped and why (out of scope, too vague, existing canon ID known) -The agent will commit the candidates to a branch and open a PR — no canon file is written directly. +Save these proposals in a YAML review file under `_intake/drafts/` (for example `canon-candidates.yaml`), outside `canon/`. Follow SKILL Step 5b: the reviewer assigns unique canonical IDs and resolves relation endpoints before canonical placement and validation. Unresolved placeholders block the canon PR and can never become admitted IDs. Relations remain `medium` or lower. Human admission is still required; extraction does not write admitted canon. diff --git a/transitrix/skills/onboard/README.md b/transitrix/skills/onboard/README.md index 77ce532b..a1928a05 100644 --- a/transitrix/skills/onboard/README.md +++ b/transitrix/skills/onboard/README.md @@ -6,12 +6,21 @@ The skill itself runs in Claude Code. What it **scaffolds** for the adopter is a This directory is the **`onboard` skill** within the `transitrix` plugin (the plugin root is [`transitrix/`](../../), which carries the shared [`.claude-plugin/plugin.json`](../../.claude-plugin/plugin.json) manifest — name, version, license, keywords — consumed by Claude Code at install time, with one `skills//` directory per skill). This skill ships: -- [`SKILL.md`](SKILL.md) — the agent-facing protocol (frontmatter + the six-step flow + an embedded cheat sheet for the 14 view notations + codex zone primitives). +- [`SKILL.md`](SKILL.md) — the agent-facing protocol (frontmatter + the six-step flow + an embedded cheat sheet for the [notation catalogue](../../../notations/README.md) + codex zone primitives). - [`templates/`](templates/) — starter files in three groups: **root scaffolding** (`transitrix.yaml` manifest + assistant-neutral `AGENTS.md` + GitHub Copilot pointer), **view notations** (one `.transitrix.yaml` per view notation), and **codex zone primitives** (external + internal). - [`extraction/`](extraction/) — per-layer extraction prompts for initial Canon population from Field artefacts (motivation / business / application). The plugin is **read-only** against the methodology canon. It does not ship the canon — when the user goes deeper than the embedded cheat sheet, the plugin fetches the full spec from `github.com/transitrix/methodology` via `WebFetch`. +## Intake profile selection + +Choose `ingest` for the ordinary ingest/reg-intel workflow (private processed raw +files), or `knowledge-store` for OKF curation (committed source-document records, +private originals). They require separate workspaces. Setup and subsequent intake +runs must pass the shared CLI preflight; incompatible or ambiguous existing +content is refused without migration. See the [deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility) +for selection, installation and retention rules. + --- ## Install @@ -76,7 +85,7 @@ The scaffold also retains `ANALYST.md`, `VALIDATOR.md`, `INGEST.md`, and `FINDIN ### View notations (dropped into `views//` in Step 3) -One starter YAML per view notation, named `..transitrix.yaml` so the file extension already matches the canonical Studio recogniser. The 15 view templates are: +One starter YAML per view notation, named `..transitrix.yaml` so the file extension already matches the canonical Studio recogniser. The starter templates below cover common choices; the complete maintained list is in [`SKILL.md` §Templates](SKILL.md#templates). | Notation | Template | |---|---| diff --git a/transitrix/skills/onboard/SKILL.md b/transitrix/skills/onboard/SKILL.md index 323794ed..7a8a46d2 100644 --- a/transitrix/skills/onboard/SKILL.md +++ b/transitrix/skills/onboard/SKILL.md @@ -48,6 +48,7 @@ Do not assume. If the user picks a notation outside the family-selection table, **1 — Read the repo silently.** Before speaking to the user: +- Before intake setup or ingestion, run the profile check in Step 2, even in an existing repo. Reading or editing model files alone does not select an intake profile. - Read `transitrix.yaml` — note `methodology_version`, `notations:`, `zones:`. - List `views/` — note which notation sub-folders exist and which are non-empty. - List `canon/elements/` — note which ArchiMate layers have content. @@ -80,6 +81,22 @@ After the first change is authored and validated, continue to **Step 6** (sugges ## Step 2 — Scaffold the repo +**Before any setup write**, choose the intake profile with the adopter using the +[deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility). +Use `ingest` for raw documents → field/canon candidates and regulatory watching; +use `knowledge-store` for OKF curation. For model-only setup, leave intake +unconfigured and omit all intake ignore rules below. Existing intake evidence +must be inspected before changing setup; never silently switch profiles. + +For either intake profile, run +`transitrix-intake-profile check --profile ` +before changing files. Once the target directory is confirmed, run +`transitrix-intake-profile select` with the same arguments before scaffolding to record the +selection. Model-only setup runs neither command. Stop if the CLI is unavailable or the check refuses. +For `knowledge-store`, hand off to `/transitrix:knowledge-store` Step 0 for intake +setup; do not add the ingest ignore block or scaffold ingest directories. Model +zones may still be added separately after that profile check succeeds. + Scaffold the canonical **zoned** Transitrix adopter shape in the user's chosen target directory. The shape mirrors the worked example in the [`transitrix/acme-corp`](https://github.com/transitrix/acme-corp) reference repo and is defined for adopters in [`AGENTS.md`](https://github.com/transitrix/acme-corp/blob/main/AGENTS.md) §3. ``` @@ -192,7 +209,9 @@ State back to the user exactly which values you filled — the same transparency ### .gitignore — and the private `_intake/` workspace -Initialise `.gitignore`: +Initialise `.gitignore` without replacing existing rules. The intake block below +applies **only to the `ingest` profile** selected above; model-only and OKF setup +omit it. The knowledge-store skill owns OKF ignore rules. ``` node_modules/ @@ -214,7 +233,7 @@ _intake/processed/* !_intake/**/.gitkeep ``` -**Why `_intake/` is private and `canon/` is shared.** `_intake/` holds raw dropped files and in-flight extraction candidates — a private scratch space, not version-of-record. Model content is the opposite: it is committed and shared. This includes `canon/unresolved/` — the holding area for objects ingestion could not yet TYPE ([`notations/CONTRACT.md`](https://github.com/transitrix/methodology/blob/main/notations/CONTRACT.md) §13). An unresolved object is still real model knowledge (it may even be admitted-accurate, only its TYPE is open), so it must be committed to shared `canon/unresolved/`, **never** left in the private `_intake/`. When the ingest skill scaffolds `_intake/`, it drops the `.gitkeep` files; if a user creates the folders by hand, add an empty `.gitkeep` to each of `inbox/`, `processing/`, `processed/`. +**In the ingest profile, `_intake/` working content is private and `canon/` is shared.** `_intake/` holds raw dropped files and in-flight extraction candidates — a private scratch space, not version-of-record. Model content is the opposite: it is committed and shared. This includes `canon/unresolved/` — the holding area for objects ingestion could not yet TYPE ([`notations/CONTRACT.md`](https://github.com/transitrix/methodology/blob/main/notations/CONTRACT.md) §13). An unresolved object is still real model knowledge (it may even be admitted-accurate, only its TYPE is open), so it must be committed to shared `canon/unresolved/`, **never** left in the private `_intake/`. When the ingest skill scaffolds `_intake/`, it drops the `.gitkeep` files; if a user creates the folders by hand, add an empty `.gitkeep` to each of `inbox/`, `processing/`, `processed/`. Don't run `git init` unless the user asked for it. @@ -240,7 +259,7 @@ Take the user's chosen notation from step 1. Copy the matching template from `${ ### View notations (canon zone) -For any of the 15 view notations (DGCA / Goals / Capability map / Process map / BPMN / Action schedule / Actions tree / Nested blocks / Scenarios / Applications / Products / Process Blueprint / Action Card / Compliance Impact / Coverage Metric), the destination is `views//`. Naming convention: `..transitrix.yaml`. Ask the user for a short domain code (e.g. `strategy-2026`, `ORDER_FULFILMENT`, `CUSTOMER_ONBOARDING`). If they give a long name, suggest a kebab-case form. +For any view notation in the [maintained catalogue](../../../notations/README.md), the destination is `views//`. Naming convention: `..transitrix.yaml`. Ask the user for a short domain code (e.g. `strategy-2026`, `ORDER_FULFILMENT`, `CUSTOMER_ONBOARDING`). If they give a long name, suggest a kebab-case form. After the copy: - Open the file and read it to the user (or summarise its structure). @@ -352,7 +371,7 @@ Use the matrix below to pick a notation. Full specs at `notations/-.md | Design-facing document listing which application/technology elements realise which requirements | **SDD** | `*.sdd.transitrix.yaml` | | One flat, alphabetised name → definition lookup across the whole catalogue (TERM entries and every other TYPE's name/aliases/description alike) | **Glossary** | `*.glossary.transitrix.yaml` | -**Family rule:** the strategy-chain notations split by shape. **DGCA** uses the **flat form** — top-level arrays at the document root (`factors[]` / `goals[]` / `changes[]` / `actions[]`), cross-references upstream inside the flat arrays. **Goals tree** and **Action schedule** (both since v2.0) are **pure projections** — the view document carries only `view_config`, and each `GOAL-…` / `ACTION-…` lives as a standalone element file under `canon/elements/…`; the parent link (Goals) and predecessor / duration / cross-refs (Action) live on the element files, not in the view. In all three, hierarchy uses `parent: -…` on the child; no nested wrapper keys. +**Family rule:** **DGCA** uses flat root arrays (`factors[]` / `goals[]` / `changes[]` / `actions[]`). **Goals tree** supports inline `goal_types[]` / `goals[]` for a self-contained document and `view_config` projection after cross-document sharing; follow the [Goals source-of-truth rule](../../../notations/views/diagrams/04-goals.md#source-of-truth). **Action schedule** uses `view_config` to project standalone ACTION elements. Hierarchy uses `parent: -…` on the child; no nested wrapper keys. ### Zone primitives — not view documents @@ -370,7 +389,7 @@ Schema: `notations/elements/14-codex.md` for codex; `notations/CONTRACT.md` §5 - **BPMN** — `notation: bpmn`. One root `process:` with `pools[].lanes[].elements[]` and `flows[]`. Elements typed (`startEvent`, `task`, `exclusiveGateway`, …); flows directed. Compiles to BPMN 2.0 XML. - **DGCA** — `notation: dgca`. Flat root arrays: `factors[]`, `goals[]`, `changes[]`, `actions[]`. Typed string IDs (`DRIVER-1`, `GOAL-RET-1`, `CHANGE-1`, `ACTION-ONBOARD-1`). Cross-refs in the upstream direction: `goal.factors: [DRIVER-…]`, `change.goals: [GOAL-…]`, `action.changes: [CHANGE-…]`. Optional `driver.references_constraint: [CONSTRAINT-…]`. DGA mode (no Changes): add `view_config.layers.changes: off` — `changes[]` becomes optional, actions link via `action.goals: [GOAL-…]`. -- **Goals tree** — `notation: goals` (v2.0 pure projection). The view document carries a required `methodology_version: "3.0.0"`, a document `id: GOALS-…`, and a `view_config` (with `scope`, `goal_types[]` display vocabulary, and `display`). Element data is **not** inline — each `GOAL-…` is a standalone file at `canon/elements/01_motivation/goals/.yaml` (with its own `notation: goal` envelope, `type`, `level`, optional `parent: GOAL-…`, and admission / lifecycle fields per `ELEMENT_PRIMITIVES.md` §7.2). Root goals omit `parent`. Inline `goals[]` at document root is a `GOALS-008` error. +- **Goals tree** — `notation: goals`. Both authoring forms are valid: inline `goal_types[]` / `goals[]` for a self-contained hierarchy (the starter), or `view_config` selecting standalone GOAL elements after promotion. Promote a goal when a second document references it, retaining its ID; the canonical destination is `canon/elements/01_motivation/goals/.yaml`. Root goals omit `parent`; children reference a parent GOAL ID. See the [Goals specification](../../../notations/views/diagrams/04-goals.md#source-of-truth) for the envelope and fields; inline goals are not an error. - **Capability map** — `notation: capability-map`. Root key `capability_map:`. Capabilities use a V/H sub-grammar (`CAPABILITY-V1.2`, `CAPABILITY-H1`); each capability carries `type: domain | supporting` and lifecycle fields. Store `current_maturity`, `target_maturity`, `target_date` and `owner_role` in sidecars beside canonical capability records, never inline in the map (see `guides/modelling-capabilities.md`). - **Process landscape map** — `notation: process-map`. Top-level catalogue of `PROCESS-…` IDs grouped into `operating`, `supporting`, `management`. - **Action schedule** — `notation: action` (v2.0 pure projection). The view document carries a required `methodology_version: "3.0.0"`, a document `id: ACTION_SCHED-…`, and a `view_config` (with `scope`, `schedule.start_date` + optional working `calendar`, and `display.view: network | gantt | both`). Element data is **not** inline — each `ACTION-…` is a standalone file at `canon/elements/05_implementation/actions/.yaml` with its own `notation: action` envelope, `type` (`Initiative | Programme | Project | Task`), `duration` (renamed from the v1 `duration_days`), optional `predecessors: [ACTION-…]`, `goals: [GOAL-…]`, `delivers_changes: [CHANGE-…]`, `parent: ACTION-…`, and admission / lifecycle fields (see `elements/24-action.md`). Renders as a PSND network with critical path plus a Gantt projection. Inline `actions[]` / `activities[]` at document root is an `ACT-010` error. diff --git a/transitrix/skills/onboard/templates/AGENTS.md b/transitrix/skills/onboard/templates/AGENTS.md index e74bc148..de83df88 100644 --- a/transitrix/skills/onboard/templates/AGENTS.md +++ b/transitrix/skills/onboard/templates/AGENTS.md @@ -70,7 +70,7 @@ The canonical Transitrix methodology lives at [github.com/transitrix/methodology 1. The canon wins. Always. 2. Update the local file to conform, or open a PR proposing the change. -3. If the canon itself appears wrong or incomplete (a genuine gap, not a typo), raise an issue against `transitrix/methodology` rather than diverging silently. +3. If the canon itself appears wrong or incomplete (a genuine gap, not a typo), follow [`FINDINGS.md`](FINDINGS.md) §2: route and scrub a local feedback record. Upstream export is a separate opt-in step; do not open an upstream issue automatically. The agent reads the canon as **read-only**. It never edits methodology files from this repo, and it never copies methodology content into this repo wholesale (link to it instead). diff --git a/transitrix/skills/onboard/templates/FINDINGS.md b/transitrix/skills/onboard/templates/FINDINGS.md index c25bec8e..7dec61b2 100644 --- a/transitrix/skills/onboard/templates/FINDINGS.md +++ b/transitrix/skills/onboard/templates/FINDINGS.md @@ -27,8 +27,8 @@ Two outcomes, always: 2. **Route.** The finding goes to a human, who decides: - **Apply the fix** — author or approve the change into `canon/`, through the same gating as any other change (`AGENTS.md` §11). - **Escalate to the data owner or architect** — when the fix needs organisational judgement the raising role can't supply. - - **Escalate upstream to the methodology** — when the finding is a notation or spec limitation, not a data problem (e.g. "there is no relation kind connecting X to Y"). This lands as an entry in `operations/feedback.md` (`method/06-team-operations.md` §3.2) — the repo's own register of methodology-directed findings. Sending it beyond this repo is a separate, opt-in step (§3 below); routing here only writes the local record. -3. **Scrub (mandatory for methodology-directed findings).** An entry written into `operations/feedback.md` is stripped of adopter specifics at the moment of writing — a generic limitation only, never client model content. Same discipline as "publish pattern, not client instance" and the real-names rule, applied to this feedback channel too. This is what makes the register safe to read, quote, or forward as-is — there is nothing left to redact when the team later decides to send an entry to `hello@transitrix.com`. + - **Escalate upstream to the methodology** — when the finding is a notation or spec limitation, not a data problem (e.g. "there is no relation kind connecting X to Y"). This lands in the feedback journal selected by the [feedback skill, Step 0](https://github.com/transitrix/methodology/blob/main/transitrix/skills/feedback/SKILL.md#step-0--locate-or-scaffold-operationsfeedbackfeedbackmd): `operations/feedback/feedback.md`, or preserved legacy `operations/feedback.md` (`method/06-team-operations.md` §3.2). Refuse if both exist; do not migrate automatically. This is the repo's own register of methodology-directed findings. Sending it beyond this repo is a separate, opt-in step (§3 below); routing here only writes the local record. +3. **Scrub (mandatory for methodology-directed findings).** An entry written into that journal is stripped of adopter specifics at the moment of writing — a generic limitation only, never client model content. Same discipline as "publish pattern, not client instance" and the real-names rule, applied to this feedback channel too. This is what makes the register safe to read, quote, or forward as-is — there is nothing left to redact when the team later decides to send an entry to `hello@transitrix.com`. No role auto-applies its own proposed fill. Raising a finding is never itself a write to `canon/` — the human act of applying or escalating is what moves it. @@ -48,7 +48,7 @@ routing: apply | escalate-owner | escalate-methodology - `type` — `data-error` (canon disagrees with itself or its source), `model-suggestion` (canon is valid but could model something better), `methodology-feedback` (a canon-confirmed gap in the notation itself, not fixable by editing data). - `confidence` — the two-tier signal from §2 step 1. Not a numeric score; a role either has structural certainty or it doesn't. -- `routing` — the role's recommendation; the human makes the final call regardless. `escalate-methodology` is written into `operations/feedback.md` as a Feedback Record (`method/06-team-operations.md` §3.2) — a different, fixed field set from this raise-time shape, suited to a standalone register entry rather than an in-flow finding. +- `routing` — the role's recommendation; the human makes the final call regardless. `escalate-methodology` is written into the journal selected in §2 as a Feedback Record (`method/06-team-operations.md` §3.2) — a different, fixed field set from this raise-time shape, suited to a standalone register entry rather than an in-flow finding. This shape generalises two things that already exist in the methodology: the Ingest skill's `review-queue.schema.json` (candidates carry `extraction_confidence` and land in a human-reviewed queue) and the Validator's structured severity report (`VALIDATOR.md` §5, error/warning/pass). A role with an existing structured output surfaces a finding inline in that output rather than in a separate file — see §4. diff --git a/transitrix/skills/reg-intel/README.md b/transitrix/skills/reg-intel/README.md index d72d3575..7f9bb782 100644 --- a/transitrix/skills/reg-intel/README.md +++ b/transitrix/skills/reg-intel/README.md @@ -6,6 +6,15 @@ This directory is the **`reg-intel` skill** within the `transitrix` plugin (the > **Status — design v0.** The agent-facing protocol ([`SKILL.md`](SKILL.md)) is published; the deterministic CLI (`@transitrix/reg-intel-cli`) is the next increment. Until the CLI ships, Step 0 of the skill stops cleanly in any environment without it. +## Intake profile selection + +Choose `ingest` for the ordinary ingest/reg-intel workflow (private processed raw +files), or `knowledge-store` for OKF curation (committed source-document records, +private originals). They require separate workspaces. Setup and subsequent intake +runs must pass the shared CLI preflight; incompatible or ambiguous existing +content is refused without migration. See the [deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility) +for selection, installation and retention rules. + --- ## The two rules diff --git a/transitrix/skills/reg-intel/SKILL.md b/transitrix/skills/reg-intel/SKILL.md index 19ef0088..5c61fcee 100644 --- a/transitrix/skills/reg-intel/SKILL.md +++ b/transitrix/skills/reg-intel/SKILL.md @@ -39,6 +39,22 @@ Also confirm you are operating inside a Transitrix adopter repository (a `transi --- +### Intake compatibility preflight + +Before setup or any run, use the shared `@transitrix/ingest-cli` preflight: + +```bash +transitrix-intake-profile check --profile ingest +transitrix-intake-profile select --profile ingest +``` + +Use the [deployment compatibility contract](../../../patterns/knowledge-store.md#deployment-profiles-and-intake-compatibility) +for local installation and detection details. Stop if unavailable or refused; +never run hooks, write snapshots or update scan state after refusal. Ingest and +reg-intel may share this profile. OKF knowledge-store requires a separate +workspace. Commit the profile marker on first setup; subsequent checks are +read-only when using `transitrix-intake-profile check`. + ## Step 1 — Read the source registry The "source registry" is the centralised watch-list at **`operations/config/scan-sources.yaml`** (see [`14-codex.md`](https://raw.githubusercontent.com/transitrix/methodology/main/notations/elements/14-codex.md) §3.7), not a walk of the `codex/` directory. `list-due` reads this file to determine which sources to scan; it does not discover sources by walking the disk. For each entry in the watch-list, the scheduler then reads the codex artefact's `scan` block (`scan.last_scanned_at`, `scan.next_scan_due`, `scan_frequency`) to get the runtime state — exactly the operating state defined in §3.4–3.5. Keeping the scan history embedded in each codex YAML makes it auditable via git; the separate watch-list makes discovery explicit and allows future non-codex connector types (APIs, Confluence, etc.) to be added without requiring codex artefacts. diff --git a/transitrix/skills/reg-intel/templates/reg-intel-daily.sh b/transitrix/skills/reg-intel/templates/reg-intel-daily.sh index 87cce7b5..27c0ab4d 100644 --- a/transitrix/skills/reg-intel/templates/reg-intel-daily.sh +++ b/transitrix/skills/reg-intel/templates/reg-intel-daily.sh @@ -37,6 +37,9 @@ run_extraction() { :; } # e.g. claude -p "/transitrix:reg-intel segment+classi # ----------------------------------------------------------------------------- echo "reg-intel daily — ${RUN_ID} — org ${ORG_ROOT}" +# Check compatibility and record selection before hooks, network or scan-state writes. +# A matching marker is left unchanged; commit a new marker with the workspace setup. +transitrix-intake-profile select "$ORG_ROOT" --profile ingest due_json="$($CLI list-due "$ORG_ROOT" --as-of "$TODAY" --json)" # Iterate the due CODEX-IDs (jq optional; falls back to grep if jq is absent). From f7a3423bde62d974afabf6a81da8b1833f9d872e Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:42:42 +0400 Subject: [PATCH 07/26] Record and validate document handoff events (#630) * feat: record and validate document handoff events Signed-off-by: transitrix * Query issued documents using retained baselines and Git changes (#631) * Add read-only issued-document queries over retained evidence Signed-off-by: transitrix * Keep document review unknown when retained Git blobs are missing Signed-off-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix Co-authored-by: transitrix-foundry[bot] <326145071+transitrix-foundry[bot]@users.noreply.github.com> --- notations/packages/documents.md | 499 ++++++++---------- packages/documents-cli/README.md | 212 +++++++- packages/documents-cli/documents.mjs | 37 +- packages/documents-cli/package-lock.json | 8 + packages/documents-cli/package.json | 8 + packages/documents-cli/src/events.mjs | 101 ++++ packages/documents-cli/src/queries.mjs | 195 +++++++ packages/documents-cli/src/register.mjs | 56 ++ packages/documents-cli/src/validate.mjs | 7 +- .../tests/test_documents_integrity.py | 8 +- packages/documents-cli/tests/test_events.mjs | 179 +++++++ packages/documents-cli/tests/test_queries.mjs | 208 ++++++++ 12 files changed, 1217 insertions(+), 301 deletions(-) create mode 100644 packages/documents-cli/src/events.mjs create mode 100644 packages/documents-cli/src/queries.mjs create mode 100644 packages/documents-cli/src/register.mjs create mode 100644 packages/documents-cli/tests/test_events.mjs create mode 100644 packages/documents-cli/tests/test_queries.mjs diff --git a/notations/packages/documents.md b/notations/packages/documents.md index eca96a28..799bcc39 100644 --- a/notations/packages/documents.md +++ b/notations/packages/documents.md @@ -31,14 +31,15 @@ packages: [documents] ## 2. Object types and ID grammar -### 2.1 The two object kinds +### 2.1 Object kinds -The package's object model has exactly two kinds: +The package carries document definitions and instances, plus stored handoff events: | Kind | What it holds | |---|---| | `document-type` | A template: a name, a list of required fields (key + datatype), and versioning constraints. | | `document` | An issued instance: an id, the type it instantiates, a version, a status, a timestamp, and a `values` map keyed by field name. | +| `issuance-event` | A retained handoff act with issuer, recipient and pointers to evidence (§8). | ### 2.2 ID grammar — disjoint from core @@ -52,13 +53,14 @@ Per [`PACKAGES.md`](../PACKAGES.md) §4.1, a package identifier must never be sh |---|---| | `doct` | `document-type` | | `doc` | `document` | +| `issue` | `issuance-event` | -- `` is one of the two literal tokens above, followed immediately by a hyphen (so `doc-…` and `doct-…` never collide — the token match is exact, not a prefix test). +- `` is one of the literal tokens above, followed immediately by a hyphen (so `doc-…` and `doct-…` never collide — the token match is exact, not a prefix test). - `` is one or more lowercase alphanumeric segments separated by hyphens. - `` is a terminal positive integer ≥ 1, no leading zeros — same terminal-integer rule as the core grammar ([`IDS_AND_REFERENCES.md`](../IDS_AND_REFERENCES.md) §1). ``` -^(doct|doc)-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$ +^(doct|doc|issue)-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$ ``` **Examples:** `doct-requirements-1`, `doc-srs-v2-1`, `doct-architecture-decision-1`, `doc-meeting-notes-2`. @@ -69,9 +71,11 @@ Per [`PACKAGES.md`](../PACKAGES.md) §4.1, a package identifier must never be sh documents/ document-types/.yaml documents/.yaml + events/.yaml # retained handoff acts + evidence/ # optional retained run/baseline/token bytes ``` -One object per file, named by its id. Every file carries `package: documents` and `kind: ` — this pair is how the package's own tooling recognises its files; core tooling never reads them (§4.2 of the mechanism doc). +One object per file, named by its id. Every file carries `package: documents` and `kind: ` — this pair is how the package's own tooling recognises its files; core tooling never reads them (§4.2 of the mechanism doc). ### 2.4 `document-type` schema @@ -150,6 +154,7 @@ The package validator checks that a `canon_refs` value is grammar-valid (DOCS-00 ``` /documents/document-types/.yaml /documents/documents/.yaml +/documents/events/.yaml ``` One artefact per file, named by its canonical package id (§2.2). @@ -170,6 +175,8 @@ Run by `@transitrix/documents-cli validate ` (the reference im | `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`. | +Event-specific structural and evidence diagnostics are defined in §8. + No rule here reaches into `canon/`, `field/`, or `codex/` — package-internal integrity only, per [`PACKAGES.md`](../PACKAGES.md) §4.2. --- @@ -205,28 +212,103 @@ This package carries document identity and traceability metadata: versioning, st --- +## 8. Issuance-event register + +An `issuance-event` records an asserted handoff: **what, when, by whom, to whom**. +It does not prove that software submitted, approved or signed anything. Store one +row per act in `documents/events/.yaml`. A later handoff gets a new ID; +`transitrix-documents record` refuses to overwrite an existing row. Retain the +referenced bytes separately; the command never creates or replaces evidence. +Git history and adopter storage controls remain responsible for retention. + +| Field | Contract | +|---|---| +| `package`, `kind` | Exactly `documents`, `issuance-event`. | +| `id` | `issue--`, unique in the package. | +| `document` | Document ID using the existing `doc-…` grammar. A citation, not a new stable-identity schema. The current local document need not exist. | +| `edition` | Nonblank adopter-supplied edition label, e.g. `B`. Independent of the existing document's numeric `version`; no automatic conversion or latest-edition inference. | +| `issued_at` | Real UTC timestamp, second precision (`YYYY-MM-DDTHH:mm:ssZ`), of the asserted act. | +| `issuer`, `recipient` | Nonblank strings supplied by the recorder. No directory, signature or identity verification. | +| `run_record`, `baseline` | Pointers with exactly `uri` and `sha256`. URI is absolute, or a package-relative retained file path. | +| `resource` | Pointer with `uri` and `sha256` to the externally stored output bytes. Absolute URI required, e.g. `resource://documents/rp17/b.pdf`. | +| `issue_hash` | SHA-256 of the canonical act and pointers, as specified below. Computed by `record` if absent; a supplied mismatch fails. | +| `synthetic` | Optional boolean; use `true` for synthetic acts. | +| `timestamp` | Optional external evidence; absent by default. See below. | + +Every pointer hash is `sha256:` followed by 64 lowercase hexadecimal digits, +computed over the exact referenced bytes. A baseline pointer names retained +baseline evidence in the adopter's format; it does not copy the commit into the +row or imply the renderer created a snapshot. Absolute URIs must be parseable, +nonempty and contain no whitespace, backslash or credentials. Relative pointers +use slash-separated ASCII letters, digits, dots, underscores and hyphens; empty, +`.` and `..` segments are forbidden. The CLI reads relative files inside the +package only, refusing symlink escapes. It does not fetch absolute URIs, even +`file:` URIs. An authorized integration can supply bytes using the `inspectEvent` +loader API; URI resolvability outside the package belongs to that integration. + +Unknown event fields are errors: inventories, recipe editions and stale flags +belong in referenced evidence or derived answers, never copied into the act. +Existing `document-type` and `document` records retain their previous validation +and require no event, timestamp, migration or conversion. The event edition label +does not adopt the proposed RP-17 document/form identity or edition schema. + +**Hash contract.** Remove `issue_hash` and `timestamp`; recursively serialize the +remaining JSON value with object keys sorted by JavaScript string order, array +order retained and `JSON.stringify` scalar escaping, with no whitespace or final +newline. Hash those UTF-8 bytes. This is an integrity binding for recorded claims, +not proof of generation, submission or trusted time. `issueHash` in the CLI's +`src/events.mjs` exports the same algorithm. Retain original record and evidence +bytes; validation and reading never rewrite them. + +**Optional RFC 3161 seam.** `timestamp` contains `format: rfc3161`, `issue_hash` +(equal to the row hash), and `token_base64` and/or `reference` (a URI/hash pointer). +The token must be nonempty canonical base64. When both forms are present, its +bytes must match the reference hash. Supplied values are preserved. The validator +accepts only the envelope and association structurally: it does not parse a token's +DER, verify its message imprint, signature, certificate chain or trust policy. +An external RFC 3161 verifier must do those checks before calling it a trusted +timestamp. A synthetic token is test evidence only. No provider is contacted and +no token is minted. Output says `not-verified`, or `not-supplied` when absent. + +**Validation and evidence states.** `DOCS-EVENT`, `DOCS-POINTER`, `DOCS-HASH` and +`DOCS-TIMESTAMP` are structural errors. Duplicate IDs still fail DOCS-002. +`DOCS-EVIDENCE` is an error for conflicting bytes or contradictory run fields, +and a warning for unavailable evidence or unknown run format. Missing evidence +never becomes an invented successful observation. The read/API result is +`invalid`, `conflict`, `incomplete` or `consistent`; conflict takes precedence over +unavailable evidence. A structurally valid row may be created with unavailable +references, visibly `incomplete`. Matching hashes mean only matching supplied +bytes. The baseline format and its semantic agreement with a run are not inferred; +use the provenance checker with independently observed evidence for that comparison. +Register-wide queries are a separate interface (§10). + +Commands and a synthetic authoring example: [documents CLI](../../packages/documents-cli/README.md). + +--- + ## 9. DMS integration contract This package is upstream of document management. An adopter who keeps issued documents in a document management system (DMS) — whether commercial, open-source, or internal — integrates with this package at a defined seam. This section specifies what the module produces, what the adopter DMS provides, and what deliberate non-scope boundaries protect both sides. ### 9.1 What the module produces — the contract's goods -A rendered document run produces three artefacts: +The supported renderer emits a flat run record alongside rendered output. The +following distinguishes that output from adopter-supplied integration evidence: | Artefact | What it holds | Audience | |---|---|---| | **Run record** | Recipe identity (id, version), repository commit, model id, render timestamp, per-slot instructions and their verdicts. | DMS, integration layer, audit trails. | -| **Snapshot manifest** | The model state the render captured: list of element IDs cited in the document, rendered date, methodology version. | Traceability queries, freshness checks, retirement detection. | -| **Document identity** | Issuer, issue timestamp, document hash (content fingerprint), source reference (URI), baseline tag (git reference). | DMS registration, integrity checking, auditability. | +| **Snapshot/baseline evidence** | Supplied and retained by the adopter; not automatically emitted by the renderer. | Traceability and provenance checks. | +| **Issuance event** | Explicitly recorded act and hashed pointers (§8); not automatically emitted on render. | DMS integration and audit trails. | -**Format:** each is emitted as JSON by the reference implementation. A non-reference renderer may emit another format provided it carries the same semantic content and is documented per §9.6. +**Format:** the renderer serializes its run record as JSON. The optional register stores YAML (the creation command writes JSON, a YAML subset). No automatic snapshot or identity envelope is required or claimed. ### 9.2 What the adopter DMS provides — the contract's consumers | Consumer layer | Role | |---|---| | **Document store** | URI-addressable storage for the PDF (or other output format) — e.g. `resource://documents/srs-2026-q3/issue-1`. The URI is a reference, never dictated by the module. | -| **Metadata intake** | An endpoint or queue where the module deposits run record, snapshot manifest, and document identity on every render. | +| **Metadata intake** | Adopter-owned ingestion of retained run records, baseline evidence and explicit handoff events. The module has no delivery endpoint or webhook. | | **Query surface** | An API exposing facts the adopter needs — e.g. "which documents cite this capability", "which documents may be stale because an element changed". These queries are application-specific; the module provides the data, not the queries. | | **Retention and lifecycle** | Retention schedules, approval workflows, signature capture, records classifications, any regulatory regime the adopter runs. None of this is the module's concern. | @@ -247,107 +329,63 @@ The module carries document **identity and traceability**. It does not carry doc The module answers the question "what model was rendered into this document?" — not "who may see it" or "when must it be deleted." -### 9.4 Data exchange format — run record schema +### 9.4 Data exchange format — actual run record -The run record is the primary interchange artefact. Its structure is governed by [`document-renderer/README.md`](../../packages/document-renderer/README.md), emitted as JSON following this schema: +[`buildRunRecord`](../../packages/document-renderer/src/run-record.mjs) emits flat +fields, not the formerly illustrated nested `recipe` / `repository` / `model` +envelope. A synthetic output with no instruction slots is: ```json { - "recipe": { - "id": "product.srs", - "version": "1.0" - }, - "repository": { - "commit": "a1b2c3d4…", - "baseline_tag": "release-2026-q3" - }, - "model": { - "id": null, - "methodology_version": "5.1.0" - }, - "rendered_at": "2026-09-02T14:30:00Z", - "profile": "strict", - "slots": [ - { - "slot_id": "market-size", - "question": "How large is the addressable market?", - "inputs": ["CAP-1", "REQ-14"], - "sufficient": true, - "verdict": "sufficient", - "produced_text": "The addressable market is $5B growing at 15% CAGR.", - "attributions": ["CAP-1"] - } - ], - "suspicion": { - "computed": false, - "reason": "not-computed-by-this-pass" - } -} -``` - -**Snapshot manifest** (extracted from the run record and document, for efficiency in queries): - -```json -{ - "document_id": "doc-srs-v2-1", - "document_hash": "sha256:a1b2c3…", - "rendered_at": "2026-09-02T14:30:00Z", - "recipe_id": "product.srs", + "recipe_id": "rp17", "recipe_version": "1.0", - "baseline_commit": "a1b2c3d4…", - "methodology_version": "5.1.0", - "elements_cited": [ - "CAPABILITY-V2", - "REQUIREMENT-sched-auth-1", - "CONSTRAINT-4" - ] -} -``` - -**Document identity** (metadata bound to the issued artefact): - -```json -{ - "id": "doc-srs-v2-1", - "type": "doct-requirements-1", - "version": "2.0", - "status": "issued", - "issued_at": "2026-09-02T14:30:00Z", - "issuer": "release-automation@example.com", - "content_hash": "sha256:a1b2c3…", - "source_uri": "resource://documents/srs-2026-q3/issue-1", - "baseline_tag": "release-2026-q3" + "repository_commit": "synthetic-base-b", + "model_id": null, + "run_timestamp": "2026-07-10T09:00:00Z", + "render_date": "2026-07-10", + "profile": "strict", + "slots": [] } ``` -All timestamps are ISO 8601 UTC, second-precision. Hashes use SHA256. A non-reference renderer must emit JSON carrying these fields; schema variations are acceptable if approved by the consuming DMS. - -### 9.5 Integration example — how a DMS consumes the data - -**Scenario:** The adopter runs Studio to render a recipe, capturing the run record and snapshot manifest. A webhook delivers them to the DMS integration layer. - -``` -1. Studio renders recipe -> PDF + run record + document identity -2. Metadata integration layer receives all three -3. DMS: - - Stores the PDF at the URI named in document identity - - Ingests snapshot manifest for traceability queries - - Logs the run record for audit trail - - Marks the document as "ready for review" (its own workflow) -4. On later model change (element modified/deleted): - - Snapshot query: "which documents cite this element?" - - Result: [doc-srs-v2-1] - - DMS flags document as "stale, re-render recommended" - - Adopter decides: re-render, or retire the document -``` - -The module provides the data. The adopter DMS provides the **decision**, the **action**, and the **workflow**. +Each slot carries `slot_id`, `question`, `inputs`, `sufficient`, `verdict`, +`reason`, `produced_text`, and `attributions`. `repository_commit` and `model_id` +may be null; the builder defaults `run_timestamp` to an ISO timestamp with +milliseconds. Do not confuse that render time with the event's second-precision +handoff time. The renderer does not emit `baseline_tag`, `methodology_version`, +`elements_cited`, `suspicion` or document identity. A run's recorded attribution +is not proof of complete input closure or actual generation from a baseline. + +The event points at the exact run bytes; it copies none of those fields. The +reader recognizes a flat run by string `recipe_id`, `recipe_version` and array +`slots`. For retained compatibility it also recognizes the old illustrative +nested `recipe.id`, `recipe.version` and `slots`; no conversion is performed. +When both representations exist, disagreeing recipe identity/version or +`repository_commit` versus `repository.commit` is a conflict. Other legacy or +partial formats remain unknown/unavailable, even if their byte hash matches. +Unknown fields in run evidence are preserved; they are not inferred as supported +claims. This compatibility does not promise that a legacy renderer emitted the +old illustrative snapshot/identity objects. + +### 9.5 Integration example — explicit handoff + +1. Render the recipe; retain output and the actual flat run record. +2. Retain baseline evidence through the adopter's existing process, and keep the + output at its external URI. Compute the pointer hashes from retained bytes. +3. Record the asserted act with issuer, recipient, edition and time using §8. + Rendering alone creates no issuance event. +4. Read and validate the event. An unavailable external store remains unavailable; + an authorized adapter may supply its bytes for comparison. Subsequent handoffs + create new rows and do not rewrite the historical act or referenced evidence. + +The adopter DMS supplies storage, decisions and workflow. The package has no +automatic submission, signing or timestamp-provider integration. ### 9.6 Out-of-scope list — what the adopter DMS must guarantee - **The adopter is responsible for:** - Storing the document bytes at the URI the module names - - Verifying the content hash matches what the module emitted + - Verifying the retained bytes match their recorded hashes - Implementing access control (who may read/download) - Enforcing retention schedules and lifecycle - Capturing and verifying signatures if regulations require them @@ -367,196 +405,81 @@ The module provides the data. The adopter DMS provides the **decision**, the **a ## 10. Traceability queries — bidirectional document-model linkage -The DMS integration produces three derived queries that enable computable traceability between issued documents and the model elements they cite. These queries run on demand against run records and snapshot manifests, with no persistent storage or index beyond what those two artefacts provide (§10.5). - -### 10.1 Query 1: Documents citing an element - -**Purpose:** Given a model state (git commit) and an element ID, find all issued documents that cite that element. - -**Signature:** -``` -documents_citing_element(commit: string, element_id: string) - -> List[{document_id, document_version, rendered_at, recipe_id}] -``` - -**Inputs:** -- `commit`: Git commit hash at which to query the model state (e.g. `a1b2c3d4…`). -- `element_id`: A core element ID in grammar-valid form per [`IDS_AND_REFERENCES.md`](../IDS_AND_REFERENCES.md) §1 (e.g. `CAPABILITY-V2`, `REQUIREMENT-sched-auth-1`). - -**Output:** An array of document records, each carrying: -- `document_id`: The document's package id (`doc-…` per §2.2). -- `document_version`: SemVer version of that document instance. -- `rendered_at`: ISO 8601 UTC timestamp when the document was issued. -- `recipe_id`: The recipe that rendered this document. -- `recipe_version`: Version of the recipe. - -**Evaluation:** -1. Enumerate all run records where `repository.commit` is `commit` or an ancestor thereof (within the canonical rendering workflow's lookback window; see §10.5). -2. For each run record, inspect its `slots[].attributions[]` to identify which elements are cited. -3. For each document rendered by that run, check its snapshot manifest: if `elements_cited` contains `element_id`, include the document in the result. - -**Example:** -``` -documents_citing_element( - commit="release-2026-q3", - element_id="CAPABILITY-V2" -) --> [ - { - document_id: "doc-srs-v2-1", - document_version: "2.0", - rendered_at: "2026-09-02T14:30:00Z", - recipe_id: "product.srs", - recipe_version: "1.0" - } -] -``` - -**Called from:** Adopter dashboards, internal audit tools, downstream DMS traceability queries (e.g. "which documents cite this capability?"). - -### 10.2 Query 2: Documents affected by a model change - -**Purpose:** Given an element ID that was deleted or moved, find all issued documents that are now potentially stale because they cited the old element state. - -**Signature:** -``` -stale_documents_for_change(element_id: string, change_type: enum["deleted", "moved"]) - -> List[{document_id, document_version, last_rendered_at, stale_since}] -``` - -**Inputs:** -- `element_id`: The core element ID that changed (e.g. `REQUIREMENT-auth-1`). -- `change_type`: The nature of the change — `"deleted"` if the element no longer exists in `canon/`, or `"moved"` if it was renamed or reclassified. - -**Output:** An array of stale-document records, each carrying: -- `document_id`: The document's package id. -- `document_version`: SemVer version of the document instance. -- `last_rendered_at`: ISO 8601 UTC timestamp when the document was last issued. -- `stale_since`: ISO 8601 UTC timestamp of the commit that deleted/moved the element. -- `recommendation`: One of `"re-render"`, `"retire"`, or `"review"` (based on time elapsed since render, per DMS policy). - -**Evaluation:** -1. Query git history to find the commit where `element_id` was deleted or moved. -2. Enumerate all run records where `repository.commit` is before that deletion commit. -3. For each run record, check all documents it rendered: if the snapshot manifest's `elements_cited` contains `element_id`, the document is stale. -4. Return all stale documents, sorted by `last_rendered_at` (oldest first). - -**Example:** -``` -stale_documents_for_change( - element_id="REQUIREMENT-auth-1", - change_type="deleted" -) --> [ - { - document_id: "doc-srs-v2-1", - document_version: "2.0", - last_rendered_at: "2026-09-01T10:00:00Z", - stale_since: "2026-09-02T08:45:00Z", - recommendation: "re-render" - } -] -``` - -**Called from:** Adopter DMS on model change events, CI/CD workflows that flag stale documents, change-impact dashboards. - -### 10.3 Query 3: Document provenance and elements - -**Purpose:** Given an issued document ID, retrieve the model state it was rendered from, its render metadata, and the complete list of elements it cites. - -**Signature:** -``` -document_provenance(document_id: string) - -> { - document_version, - rendered_at, - recipe_id, - recipe_version, - baseline_commit, - methodology_version, - elements_cited: List[string], - run_record: object - } -``` - -**Inputs:** -- `document_id`: The document's package id (`doc-…` per §2.2). - -**Output:** A single document-provenance record carrying: -- `document_version`: SemVer version of the document. -- `rendered_at`: ISO 8601 UTC timestamp when rendered. -- `recipe_id`: The recipe that produced this document. -- `recipe_version`: Version of the recipe. -- `baseline_commit`: Git commit hash of the model state that was rendered. -- `baseline_tag`: Git tag or reference name if the render was tagged (e.g. `release-2026-q3`). -- `methodology_version`: The Transitrix methodology version the render used. -- `elements_cited`: Array of core element IDs in `elements_cited` from the snapshot manifest. -- `run_record`: The full run record JSON (for audit trails and detailed inspection). - -**Evaluation:** -1. Look up the snapshot manifest for `document_id` in the DMS metadata store. -2. Retrieve the corresponding run record from the same store. -3. Return the full provenance object. - -**Example:** -``` -document_provenance("doc-srs-v2-1") --> { - document_version: "2.0", - rendered_at: "2026-09-02T14:30:00Z", - recipe_id: "product.srs", - recipe_version: "1.0", - baseline_commit: "a1b2c3d4…", - baseline_tag: "release-2026-q3", - methodology_version: "7.0.0", - elements_cited: ["CAPABILITY-V2", "REQUIREMENT-sched-auth-1"], - run_record: { … } -} -``` - -**Called from:** DMS UI (document details pane), adopter integration tools, audit and compliance workflows, document versioning dashboards. - -### 10.4 Calling convention and error handling - -All three queries are **stateless and demand-computed**. They run synchronously on invocation, with no caching or warming phase. - -| Error case | Behavior | -|---|---| -| `element_id` not found in any run record | Return empty list (Query 1, 2) or `null` (Query 3). | -| `commit` not in git history | Return empty list (Query 1). | -| `document_id` not found in DMS | Return `null` (Query 3). | -| Run record or snapshot manifest corrupted | Raise `DataIntegrityError` with the affected document id. | -| Git history unavailable | Raise `GitHistoryError` — queries are offline and fail gracefully if the repository is not accessible. | - -### 10.5 Implementation location and performance - -**Where they run:** -- **Primary:** Studio's document-render workflow, after rendering completes and before metadata is handed to the DMS. -- **Secondary:** The adopter's own integration layer or DMS plugin, querying via a REST API the module exposes (see §10.6). -- **Offline:** An adopter's internal dashboard or audit tool that has read access to run records and git history but not the DMS. - -**Performance characteristics:** -- Query 1 (documents citing element): O(R × S), where R = number of run records in the lookback window, S = average snapshot size. Typical: < 500ms for 10 years of renders. -- Query 2 (stale documents): O(R × S × G), where G = git-history depth (worst case: full repo walk to find the deletion commit). Typical: < 2s for 10 years of renders. Mitigation: cache the deletion commit once found. -- Query 3 (document provenance): O(1) — direct lookup in DMS metadata store. - -**No persistent index.** Queries derive results from run records and git history on demand. This trades latency for simplicity: no index to keep in sync, no storage beyond what the DMS already holds, and every result is guaranteed current (never stale cached data). - -**Lookback window:** Queries enumerate run records back to the earliest document still in-scope under the adopter's retention policy (see §9.6). The module does not enforce a limit; it is the adopter DMS's responsibility to bound the window (e.g. "only documents from the last 7 years" or "only documents marked 'active'"). - -### 10.6 API surface — how callers invoke the queries - -Each query is a callable function in the module's integration layer, exposed as: -- **Studio plugin:** `@transitrix/documents-dms-queries` package, imported as `{ documentsForElement, staleDocuments, documentProvenance } from '@transitrix/documents-dms-queries'`. -- **REST API:** `POST /query/` on the adopter's integration endpoint, with JSON body carrying the query inputs. -- **Python CLI:** `@transitrix/documents-cli query ` (reference implementation). - -Each invocation logs (to the DMS audit trail): -- Query name -- Inputs (commit, element id, or document id) -- Timestamp -- Caller identity (if available from the calling context) -- Result count +The optional documents package exposes `queryIssuedDocuments` from +`@transitrix/documents-cli/src/queries.mjs`. It enumerates retained issuance events +(§8), loads their exact flat run records (§9.4), checks explicit baseline bindings +and reads historical Git objects. It reuses the renderer's +[`checkDocumentProvenance`](../../packages/document-renderer/PROVENANCE.md). +See the [query interface and adapter contract](../../packages/documents-cli/README.md#querying-retained-issuance-events) +for installation, baseline JSON, authorization and complete arguments. + +### 10.1 Element → issued documents + +`query: { kind: 'element', id: elementId }` examines every retained event in the +selected register. Matching events name their exact document and edition, run +and baseline pointers, recipe and observed input closure. Multiple handoffs are +returned separately. It does not infer issuance from a render or choose the latest +edition by date. Run `slots[].attributions` are reported separately from complete +input closure: a matching input need not be quoted verbatim in the output. + +### 10.2 Changed element → review of issued documents + +`query: { kind: 'review', id: elementId, target: exactCommit }` compares each +issued baseline with an explicit full target commit. Changes include **content +modifications**, additions, deletions and moves; changed element IDs are read from +both Git trees. Path dependencies include directory membership, so a retained +observer can account for dynamic selections. Moves conservatively require review. + +Within a complete independently observed closure, intersection yields +`review-needed`; nonintersection yields `no-relevant-change`. The selected element +must itself have changed for the event to appear in `matches`; the per-event review +result considers every input in its closure. Missing history, closure, retained +bytes or binding yields `unknown`. No dates, wall-clock stale-since value or +persistent stale flag is computed. A review result describes Git evidence, not +proof that an edition is invalid or permission to regenerate it. + +### 10.3 Issued document → model and elements + +`query: { kind: 'document', id: documentId }` returns **all** retained handoffs for +that document, preserving the explicitly recorded edition and release association. +It reports the repository identity, exact baseline commit, run attributions and +observed input closure. The generated-prose `model_id` is not the model repository +identity. No current checkout, latest review, edition label or timestamp substitutes +for a historical binding. A/B retention, independent unchanged reviews without C, +and explicit release/B association remain as illustrated by +[RP-17](../examples/packages/rp17.md); proposed semantic validators remain proposed. + +### 10.4 Unknown and conflict semantics + +Results contain `status`, `matches`, per-event `records` and enumeration `failures`. +Malformed/unreadable rows cannot silently become nonmatches. A missing register, +unknown document, unavailable baseline/history or absent closure returns +`incomplete`, never an empty successful result. Contradictory document, run, +baseline, output or release bindings remain `inconsistent` even if an individual +hash or review check passes. `match` and `review` retain explicit unknown states. +Matching hashes and associations never establish actual generation, so a known +review result can coexist with incomplete overall provenance. + +### 10.5 Retention and execution boundary + +Queries read an adopter-selected immutable register snapshot, retained evidence +and explicit committed Git states. They do not write source files, event rows, +run records, outputs, indexes, element inventories, stale flags or audit logs. +They enumerate the complete selected register without an implicit lookback window. +The adopter owns retention and authorization; no result claims completeness for +records outside that selected retained scope. Reads and tree comparisons occur +on demand; no performance promise or persistent cache is part of the contract. + +### 10.6 Supported surface + +The shipped surface is the asynchronous Node.js API in `@transitrix/documents-cli`, +with `@transitrix/document-renderer` installed as its optional query peer. The +record/read/validate CLI remains available (§8). There is no shipped query REST +endpoint, Studio DMS plugin, Python query command or automatic audit logging. +Adapters own authorized external byte access and independent observer evidence; +missing adapters produce unknown results, not fabricated observations. Storage, +workflow, approval, signing, scheduling and provider integration remain outside +this package. --- diff --git a/packages/documents-cli/README.md b/packages/documents-cli/README.md index ba9dfaf1..4b88dc21 100644 --- a/packages/documents-cli/README.md +++ b/packages/documents-cli/README.md @@ -1,6 +1,6 @@ # 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. +`@transitrix/documents-cli` validates the optional [documents package](../../notations/packages/documents.md). Validation reads document types, documents and issuance events, reports structural and evidence findings, and never writes model files or resolves citations against core. Explicit record/read commands manage individual handoff rows. Requires Node.js 20 or later. Install from a source checkout into your adopter repository: @@ -23,7 +23,7 @@ For an explicit package-only check: 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. +Each finding includes severity, rule and relative filename. Validation exit codes are 0 for input without errors (possibly with unavailable-evidence warnings), 1 for record errors, 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. @@ -37,3 +37,211 @@ 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. + +## Recording and reading handoffs + +A handoff is an explicit asserted act, separate from a render or a document's +status. The register adds no fields to repositories that do not use events. +Existing document records remain compatible. Commands operate on an explicitly +selected package folder; normal validator dispatch still requires declaration. + +Prepare an act YAML with the fields in [§8 of the package contract](../../notations/packages/documents.md#8-issuance-event-register). +This synthetic example uses placeholders for hashes; replace them with SHA-256 +of the exact retained bytes before recording it: + +```yaml +package: documents +kind: issuance-event +id: issue-rp17-b-1 +synthetic: true +document: doc-rp17-b-1 +edition: B +issued_at: "2026-07-10T10:00:00Z" +issuer: Synthetic Issuer +recipient: Synthetic Recipient +run_record: + uri: evidence/run-b.json + sha256: "sha256:<64 lowercase hex digits>" +baseline: + uri: evidence/baseline-b.txt + sha256: "sha256:<64 lowercase hex digits>" +resource: + uri: resource://documents/rp17/b.pdf + sha256: "sha256:<64 lowercase hex digits>" +``` + +```sh +npx --no-install transitrix-documents record ./documents ./act.yaml +npx --no-install transitrix-documents read ./documents issue-rp17-b-1 +npx --no-install transitrix-documents validate ./documents +``` + +`record` computes `issue_hash` when omitted, validates the input, and exclusively +creates `events/issue-rp17-b-1.yaml`. It refuses invalid/conflicting input and an +existing ID. It writes no evidence and never rewrites another row. `read` returns +the original row plus evidence states, without changing files. Both emit JSON. +A different handoff needs a different event ID, even for the same document/edition. +The edition label does not change the document's existing numeric version contract. + +Local run/baseline pointers resolve beneath `documents/`. Absolute URIs are never +fetched by the CLI. Unavailable pointers produce `incomplete` reports and validation +warnings, not fabricated evidence or failed structural validation. Mismatching +bytes produce `conflict` and validation errors. Unknown run formats remain +unavailable. Retain historical rows and evidence through your existing repository +and external storage controls; exclusive creation is not a retention service. + +For authorized integrations, the installed `src/events.mjs` exports `issueHash`, +`hashBytes`, `validateEvent` and `inspectEvent`. The latter accepts +`{ load: async pointer => bytesOrNull }`; the adapter owns access control and +external lookup. `src/register.mjs` exports `createEvent(folder, act)` and +`readEvent(folder, id)` with the same behavior as the CLI. These inspect a single +act, not a register-wide traceability query. + +Optional timestamp evidence has this envelope: + +```yaml +timestamp: + format: rfc3161 + issue_hash: "sha256:" + reference: + uri: evidence/external-token.tsr + sha256: "sha256:" +``` + +You may supply `token_base64` instead of, or alongside, `reference`; both must bind +the same bytes. Compute the act hash with `issueHash(act)` before requesting any +external evidence through your own process. The package never requests or creates +a token. It checks the envelope only, preserving supplied evidence and reporting +`timestamp_trust: not-verified`. A reference or base64 value is not proof of an +RFC 3161 message imprint, signature, certificate chain or trusted time. No timestamp +field is required when unused; no automatic signing or submission occurs. + +Validation exits 1 on structural or evidence-conflict findings, and 0 when structurally +valid (possibly incomplete). `read` exits 1 for an invalid/conflicting row. Invocation, +parse, write/refusal and filesystem failures exit 2. All commands keep unavailable +evidence explicit in their output. + +## Querying retained issuance events + +The supported query interface is the asynchronous JavaScript export +`queryIssuedDocuments` in `src/queries.mjs`. It enumerates the selected `events/` +register and reads actual retained runs and Git objects. There is no REST service, +Studio query plugin, Python query CLI, automatic audit write or persistent index. +Install the renderer alongside the documents package to use its provenance checker: + +```sh +npm pack /path/to/methodology/packages/document-renderer +npm install ./transitrix-document-renderer-0.0.1.tgz +``` + +The optional peer is required only for queries; validation and record/read work +without it. A missing checker returns `incomplete`, never a successful empty list. + +```js +import { queryIssuedDocuments } from '@transitrix/documents-cli/src/queries.mjs'; + +const options = { + folder: './documents', + repository: { root: '.', id: 'adopter-stable-model-id' }, + authorize: async () => policyAllowsEntireRegisterAndRepository, + load: async pointer => retainedBytesForAuthorizedPointer(pointer), + observe: async row => retainedObserverBundleFor(row), +}; +const reverse = await queryIssuedDocuments({ ...options, + query: { kind: 'document', id: 'doc-rp17-b-1' } }); +const forward = await queryIssuedDocuments({ ...options, + query: { kind: 'element', id: 'REQ-14' } }); +const review = await queryIssuedDocuments({ ...options, + query: { kind: 'review', id: 'REQ-14', target: exactTargetCommit } }); +``` + +The callbacks above belong to the adopter: they are not supplied services. +`authorize` must grant the entire register, repository, retained bytes and every +observer fact atomically. Denial or an exception returns a constant unavailable +result without reading them. `load` returns exact bytes or null and must handle +local event paths as well as evidence pointers; when omitted it uses `localLoader` +from `src/register.mjs` and never fetches external URIs. `observe` returns the +existing [provenance bundle](../document-renderer/PROVENANCE.md), including claims, +recipe bytes and **independently retained** observations for that event. Neither +callback may write, fetch unapproved resources or reconstruct supposed historical +observations from current claims. Select an immutable register snapshot for each +call. Reads are memoized only for that invocation; no cache survives it. + +### Baseline binding + +For these queries, the event's existing `baseline` pointer must resolve to UTF-8 +JSON with this supported envelope (values below are synthetic placeholders): + +```json +{ + "format": "document-baseline/1", + "repository_id": "synthetic-model", + "commit": "", + "document": "doc-rp17-b-1", + "edition": "B", + "run_sha256": "<64 lowercase hex digits>", + "output_sha256": "<64 lowercase hex digits>", + "product_id": "PRODUCT-portal-1", + "release_id": "RELEASE-portal-3.2" +} +``` + +This is an explicit retained association, not renderer-generated identity or an +edition registry. `product_id` and `release_id` are optional; if present in the +baseline, claims or observations, all three must supply agreeing values. Release +membership is checked by the provenance checker. Missing release data cannot +establish applicability to a release. The event still stores only its act and +hashed pointers, with no copied recipe version, element inventory or stale flag. +Existing arbitrary baseline bytes remain valid event evidence; their query binding +is unknown until independently supported in this envelope. Do not rewrite old +evidence or manufacture this association for a legacy record. + +The observed committed snapshot ID and commit, claim snapshot ID, baseline commit +and flat run `repository_commit` must agree. `model_id` remains the generated-prose +model; the model repository identity comes from explicit baseline/observer binding. +The query passes the register's run/output bytes to the existing checker; conflicting +adapter substitutes cannot replace them. Recipe, product/release, tools, rules, +configuration and external evidence retain that checker's semantics. + +### Closure, Git comparisons and results + +`observed.closure` must bind the exact run digest and commit with complete input +IDs. Citations alone do not prove closure. For a fixed-ID selection, these can be +core element IDs. Dynamic membership needs its material dependencies too: use +`path:canon/elements` for all changes beneath that directory, or `path:` for narrower dependencies. The observer owns this completeness +judgment. No closure is inferred for old runs, omitted records or unobserved +external changes. Review results cover the compared Git snapshots only. + +Targets are full commit IDs, never tags, HEAD, dates or "latest". Git is read +without optional locks or replacement objects, and without lazy network fetching. +Complete tree comparisons include added/modified paths and both sides of a move +or deletion; changed canonical YAML element IDs are read from both snapshots. +Moves count conservatively as review-worthy even if bytes are identical. Invalid +changed element identity, missing Git objects, unsupported tree entries, command +limits or unreadable history keep review unknown. No ancestry or time window +silently drops an older retained issuance. + +Results contain `matches` (event IDs), `records` and enumeration `failures`. +Each record retains its exact document/edition and evidence pointers, recorded +model/baseline, recipe labels, run attributions, observed closure and checker +report. Repeated handoffs remain separate events; no latest-edition selection +occurs. `match` is `yes`, `no` or `unknown`; `review` is `review-needed`, +`no-relevant-change` or `unknown`. Review considers all closure inputs; a review +query's matches additionally require the selected element itself to have changed. +A match says the element was in the observed input closure, not necessarily quoted +verbatim in the output. Run attributions are returned separately. + +Conflicts dominate aggregate status, even when a review subcheck passes. Missing +closure, binding, bytes, history or observations prevents a conclusive element +match/nonmatch and review result. Reverse lookup still returns retained claims, +marked incomplete or inconsistent. Missing/empty registers and absent document IDs +return incomplete with a reason, never an empty success. Overall provenance stays +`incomplete` even with a known review result because matching bytes and recorded +associations do not prove generation. A review-needed result is not approval, +invalidity, automatic reissuance or permission to alter retained bytes. + +The [RP-17 example](../../notations/examples/packages/rp17.md) remains applicable: +A/B editions and release/B bindings are explicit; an actual unchanged review +creates no C. These queries create neither reviews nor editions. Proposed identity, +predecessor and recurrence semantics remain proposed. diff --git a/packages/documents-cli/documents.mjs b/packages/documents-cli/documents.mjs index 68b8e776..a5b7608e 100644 --- a/packages/documents-cli/documents.mjs +++ b/packages/documents-cli/documents.mjs @@ -3,13 +3,15 @@ import { readdir, readFile, stat } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { parseDocument } from 'yaml'; import { validateRecords } from './src/validate.mjs'; +import { inspectEvent } from './src/events.mjs'; +import { createEvent, readEvent, localLoader, parseRecord } from './src/register.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']]) { + for (const [subdir, kind] of [['document-types', 'document-type'], ['documents', 'document'], ['events', 'issuance-event']]) { let entries; try { entries = await readdir(join(root, subdir), { withFileTypes: true }); } catch (error) { if (error.code === 'ENOENT') continue; throw error; } @@ -31,18 +33,37 @@ async function validate(folder) { } } findings.push(...validateRecords(records)); + for (const { file, value } of records.filter(r => r.value?.kind === 'issuance-event')) { + const report = await inspectEvent(value, { load: localLoader(root) }); + for (const e of report.evidence) { + if (e.status !== 'consistent') findings.push({ code: 'DOCS-EVIDENCE', + severity: e.status === 'conflict' ? 'error' : 'warning', file, + message: `${e.name}: ${e.status}${e.format ? ` (${e.format})` : ''}.` }); + } + if (value.timestamp) console.log(`documents timestamp ${file}: external evidence; trust not verified`); + } + const errors = findings.filter(f => f.severity === 'error').length; 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; + console.log(`documents validate: ${records.length} record(s), ${errors} error(s), ${findings.length - errors} warning(s)`); + return errors ? 1 : 0; } -const [command, folder, ...extra] = process.argv.slice(2); -if (command !== 'validate' || !folder || extra.length) { - console.error('Usage: transitrix-documents validate '); +const [command, folder, arg, ...extra] = process.argv.slice(2); +if (!folder || extra.length || !['validate', 'record', 'read'].includes(command) + || (command === 'validate' ? !!arg : !arg)) { + console.error('Usage: transitrix-documents validate | record | read '); process.exitCode = 2; } else { - try { process.exitCode = await validate(folder); } - catch (error) { + try { + if (command === 'validate') process.exitCode = await validate(folder); + else { + const result = command === 'record' + ? await createEvent(folder, parseRecord(await readFile(arg, 'utf8'))) + : await readEvent(folder, arg); + console.log(JSON.stringify(result, null, 2)); + process.exitCode = ['invalid', 'conflict'].includes(result.status) ? 1 : 0; + } + } 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 index 497eab4d..6bb30744 100644 --- a/packages/documents-cli/package-lock.json +++ b/packages/documents-cli/package-lock.json @@ -16,6 +16,14 @@ }, "engines": { "node": ">=20" + }, + "peerDependencies": { + "@transitrix/document-renderer": "0.0.1" + }, + "peerDependenciesMeta": { + "@transitrix/document-renderer": { + "optional": true + } } }, "node_modules/yaml": { diff --git a/packages/documents-cli/package.json b/packages/documents-cli/package.json index 8525ecf7..9fc8c665 100644 --- a/packages/documents-cli/package.json +++ b/packages/documents-cli/package.json @@ -20,5 +20,13 @@ "repository": "https://github.com/transitrix/methodology", "dependencies": { "yaml": "2.9.1" + }, + "peerDependencies": { + "@transitrix/document-renderer": "0.0.1" + }, + "peerDependenciesMeta": { + "@transitrix/document-renderer": { + "optional": true + } } } diff --git a/packages/documents-cli/src/events.mjs b/packages/documents-cli/src/events.mjs new file mode 100644 index 00000000..c1194012 --- /dev/null +++ b/packages/documents-cli/src/events.mjs @@ -0,0 +1,101 @@ +// Stored handoff acts and read-only evidence checks. No provider or DMS calls. +import { createHash } from 'node:crypto'; + +const map = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const text = v => typeof v === 'string' && v.trim().length > 0; +const digest = v => typeof v === 'string' && v.length === 71 && /^sha256:[a-f0-9]{64}$/.test(v); +export const hashBytes = bytes => `sha256:${createHash('sha256').update(bytes).digest('hex')}`; +const fields = new Set(['package', 'kind', 'id', 'document', 'edition', 'issued_at', 'issuer', 'recipient', + 'run_record', 'baseline', 'resource', 'issue_hash', 'timestamp', 'synthetic']); + +export function localPointer(uri) { + return typeof uri === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(uri) + && uri.split('/').every(part => part !== '' && part !== '.' && part !== '..'); +} +function absoluteURI(uri) { + if (!text(uri) || /[\s\\]/.test(uri) || /%(?![a-f0-9]{2})/i.test(uri)) return false; + try { const u = new URL(uri); return !!u.protocol && !u.username && !u.password && uri.length > u.protocol.length; } + catch { return false; } +} +const pointer = (v, external = false) => map(v) && Object.keys(v).every(k => ['uri', 'sha256'].includes(k)) + && digest(v.sha256) && (absoluteURI(v.uri) || (!external && localPointer(v.uri))); +const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` + : map(v) ? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` + : JSON.stringify(v); + +// Timestamp evidence is excluded so a provider can bind to a precomputed act hash. +export function issueHash(row) { + const { issue_hash, timestamp, ...act } = row; + return hashBytes(canonical(act)); +} + +export function validateEvent(row, file = '') { + const findings = []; + const flag = (code, message) => findings.push({ code, severity: 'error', file, message }); + if (!map(row)) { flag('DOCS-EVENT', 'Expected an issuance-event mapping.'); return findings; } + if (row.package !== 'documents' || row.kind !== 'issuance-event' + || !text(row.id) || row.id.trim() !== row.id || !/^issue-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$/.test(row.id ?? '') + || !text(row.document) || row.document.trim() !== row.document || !/^doc-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$/.test(row.document ?? '') + || !['edition', 'issuer', 'recipient'].every(k => text(row[k]))) { + flag('DOCS-EVENT', 'Required act: package, kind, issue ID, document ID, edition, issuer and recipient.'); + } + const date = typeof row.issued_at === 'string' ? new Date(row.issued_at) : null; + if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(row.issued_at ?? '') + || !Number.isFinite(date?.getTime()) || date.toISOString() !== row.issued_at.replace('Z', '.000Z')) { + flag('DOCS-EVENT', 'issued_at must be a real UTC second-precision timestamp.'); + } + if (Object.keys(row).some(k => !fields.has(k)) || ('synthetic' in row && typeof row.synthetic !== 'boolean')) { + flag('DOCS-EVENT', 'Unknown event field or non-boolean synthetic marker. Store derived facts in referenced evidence.'); + } + for (const k of ['run_record', 'baseline', 'resource']) { + if (!pointer(row[k], k === 'resource')) flag('DOCS-POINTER', `${k} requires uri and sha256; resource must be an absolute external URI.`); + } + if (!digest(row.issue_hash) || row.issue_hash !== issueHash(row)) flag('DOCS-HASH', 'issue_hash must match the canonical act and pointers.'); + if ('timestamp' in row) { + const t = row.timestamp; + const keys = ['format', 'issue_hash', 'token_base64', 'reference']; + const hasToken = map(t) && Object.hasOwn(t, 'token_base64'); + const hasRef = map(t) && Object.hasOwn(t, 'reference'); + const validToken = hasToken && text(t.token_base64) && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t.token_base64) + && Buffer.from(t.token_base64, 'base64').toString('base64') === t.token_base64; + if (!map(t) || Object.keys(t).some(k => !keys.includes(k)) || t.format !== 'rfc3161' + || t.issue_hash !== row.issue_hash || !digest(t.issue_hash) || (!hasToken && !hasRef) + || (hasToken && !validToken) || (hasRef && !pointer(t.reference)) + || (hasToken && hasRef && validToken && hashBytes(Buffer.from(t.token_base64, 'base64')) !== t.reference.sha256)) { + flag('DOCS-TIMESTAMP', 'Expected external rfc3161 evidence bound to issue_hash: canonical base64 token and/or hashed reference, with matching bytes when both are supplied.'); + } + } + return findings; +} + +// load receives a validated pointer and returns bytes or null. The CLI loads +// only retained local files; authorized adapters can supply external evidence. +export async function inspectEvent(row, { load = async () => null } = {}) { + const findings = validateEvent(row); + if (findings.length) return { status: 'invalid', findings, evidence: [], timestamp_trust: 'not-verified' }; + const evidence = []; + for (const [name, ref] of [['run_record', row.run_record], ['baseline', row.baseline], ['resource', row.resource], + ...(row.timestamp?.reference ? [['timestamp', row.timestamp.reference]] : [])]) { + let bytes; + try { bytes = await load(ref); } catch { bytes = null; } + let status = bytes instanceof Uint8Array ? hashBytes(bytes) === ref.sha256 ? 'consistent' : 'conflict' : 'unavailable'; + let format; + if (name === 'run_record' && status === 'consistent') { + let run; + try { run = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { /* unknown format */ } + const flat = map(run) && text(run.recipe_id) && text(run.recipe_version) && Array.isArray(run.slots); + const legacy = map(run?.recipe) && text(run.recipe.id) && text(run.recipe.version) && Array.isArray(run.slots); + format = flat ? 'flat' : legacy ? 'legacy-nested' : 'unknown'; + for (const [flatKey, nested, key] of [['recipe_id', 'recipe', 'id'], + ['recipe_version', 'recipe', 'version'], ['repository_commit', 'repository', 'commit']]) { + if (map(run) && Object.hasOwn(run, flatKey) && map(run[nested]) + && Object.hasOwn(run[nested], key) && run[flatKey] !== run[nested][key]) status = 'conflict'; + } + if (format === 'unknown' && status !== 'conflict') status = 'unavailable'; + } + evidence.push({ name, status, ...(format ? { format } : {}) }); + } + return { status: evidence.some(e => e.status === 'conflict') ? 'conflict' + : evidence.some(e => e.status === 'unavailable') ? 'incomplete' : 'consistent', findings, evidence, + timestamp_trust: row.timestamp ? 'not-verified' : 'not-supplied' }; +} diff --git a/packages/documents-cli/src/queries.mjs b/packages/documents-cli/src/queries.mjs new file mode 100644 index 00000000..4bf0a53b --- /dev/null +++ b/packages/documents-cli/src/queries.mjs @@ -0,0 +1,195 @@ +// Read-only register enumeration with explicit retained bindings and Git evidence. +import { readdir } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { hashBytes, inspectEvent } from './events.mjs'; +import { localLoader, parseRecord } from './register.mjs'; + +const map = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const text = v => typeof v === 'string' && v.length > 0; +const oid = v => typeof v === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v); +const hash = bytes => hashBytes(bytes).slice(7); +const unknown = reason => ({ status: 'incomplete', reason, matches: [], records: [] }); +const json = bytes => JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); +function gitInput(root, args, input) { + return execFileSync('git', ['--no-optional-locks', '-C', root, ...args], + { input, env: { ...process.env, GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1' }, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024 }); +} +const git = (root, ...args) => gitInput(root, args); +function commit(root, value) { + if (!oid(value) || git(root, 'rev-parse', '--verify', `${value}^{commit}`).trim() !== value) throw new Error('history unavailable'); + return value; +} +function tree(root, revision) { + const result = new Map(); + for (const line of git(root, 'ls-tree', '-rz', '--full-tree', revision).split('\0').filter(Boolean)) { + const tab = line.indexOf('\t'); + const meta = line.slice(0, tab), path = line.slice(tab + 1); + const [mode, kind, object] = meta.split(' '); + if (!path || kind !== 'blob' || !['100644', '100755'].includes(mode)) throw new Error('unsupported tree entry'); + result.set(path, object); + } + if (result.size) { + const objects = [...new Set(result.values())]; + const available = gitInput(root, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], `${objects.join('\n')}\n`).trim().split('\n'); + if (available.length !== objects.length || available.some((line, i) => line !== `${objects[i]} blob`)) { + throw new Error('retained blobs unavailable'); + } + } + return result; +} +// Compare complete trees, including both sides of moves and deletions. No +// rename heuristic, timestamp, shallow-log walk or current working-tree read. +function changes(root, base, target) { + const before = tree(root, base), after = tree(root, target); + const ids = new Set(); + const files = []; + for (const path of [...new Set([...before.keys(), ...after.keys()])].sort()) { + if (before.get(path) === after.get(path)) continue; + files.push({ path, kind: !before.has(path) ? 'added' : !after.has(path) ? 'deleted' : 'modified' }); + const parts = path.split('/'); + for (let i = 1; i <= parts.length; i++) ids.add(`path:${parts.slice(0, i).join('/')}`); + if (!path.startsWith('canon/elements/') || !/\.ya?ml$/.test(path)) continue; + for (const object of [before.get(path), after.get(path)].filter(Boolean)) { + const value = parseRecord(git(root, 'cat-file', 'blob', object)); + if (!text(value?.id)) throw new Error('element identity unavailable'); + ids.add(value.id); + } + } + return { ids: [...ids].sort(), files }; +} + +/** + * authorize covers the entire selected register, Git repository and observations. + * observe(row) supplies independent, retained provenance adapter observations; + * it must not manufacture closure from run citations. See ../README.md. + */ +export async function queryIssuedDocuments({ folder, repository, query, authorize, observe, + load = localLoader(folder) } = {}) { + try { if (await authorize?.() !== true) return unknown('unavailable'); } + catch { return unknown('unavailable'); } + if (!query || !['document', 'element', 'review'].includes(query.kind) + || !text(query.id) || !text(repository?.id) || !text(repository?.root)) return unknown('invalid-query'); + const retained = new Map(); + const safeLoad = async ref => { + if (!retained.has(ref.uri)) { + let bytes; + try { bytes = await load(ref); } catch { /* unavailable */ } + retained.set(ref.uri, bytes instanceof Uint8Array ? Buffer.from(bytes) : null); + } + return retained.get(ref.uri); + }; + let checker; + try { ({ checkDocumentProvenance: checker } = await import('@transitrix/document-renderer/src/provenance.mjs')); } + catch { return unknown('provenance-checker-unavailable'); } + let entries; + try { entries = await readdir(resolve(folder, 'events'), { withFileTypes: true }); } + catch { return unknown('register-unavailable'); } + const records = [], failures = [], seen = new Set(); + for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) { + if (!/\.ya?ml$/.test(entry.name)) continue; + let row; + try { + if (!entry.isFile()) throw new Error('not a record'); + row = parseRecord(await safeLoad({ uri: `events/${entry.name}` })); + if (!map(row)) throw new Error('invalid record'); + if (entry.name.replace(/\.ya?ml$/, '') !== row.id || seen.has(row.id)) { + failures.push({ file: entry.name, status: 'inconsistent', reason: 'invalid-or-duplicate-identity' }); + continue; + } + seen.add(row.id); + } catch { failures.push({ file: entry.name, status: 'incomplete', reason: 'record-unreadable-or-duplicate' }); continue; } + // Validate before filtering: malformed rows cannot silently disappear. + const event = await inspectEvent(row, { load: safeLoad }); + if (event.status === 'invalid') { failures.push({ file: entry.name, status: 'inconsistent', reason: 'invalid-event' }); continue; } + if (query.kind === 'document' && row.document !== query.id) continue; + const r = { event_id: row.id, document: row.document, edition: row.edition, + synthetic: row.synthetic === true, status: 'incomplete', review: 'unknown', match: 'unknown', + baseline: row.baseline, run_record: row.run_record, resource: row.resource, + evidence: event, findings: [] }; + records.push(r); + const conflict = reason => r.findings.push({ status: 'inconsistent', reason }); + const missing = reason => r.findings.push({ status: 'incomplete', reason }); + if (event.status === 'conflict') conflict('retained-bytes-conflict'); + if (event.status === 'incomplete') missing('retained-bytes-unavailable'); + let run, baseline, bundle; + const runBytes = await safeLoad(row.run_record), baselineBytes = await safeLoad(row.baseline); + try { run = json(runBytes); if (!map(run)) throw new Error('invalid run'); } catch { missing('run-unavailable'); } + try { baseline = json(baselineBytes); if (!map(baseline)) throw new Error('invalid baseline'); } catch { missing('baseline-unavailable'); } + try { bundle = structuredClone(await observe?.(structuredClone(row))); } catch { /* missing observation */ } + const b = map(baseline) ? baseline : {}; + const c = map(bundle?.claims) ? bundle.claims : {}, o = map(bundle?.observed) ? bundle.observed : {}; + const compare = (a, z, reason) => { + if (!text(a) || !text(z)) missing(`${reason}-unavailable`); + else if (a !== z) conflict(`${reason}-conflict`); + }; + if (b.format !== 'document-baseline/1') missing('baseline-format-unavailable'); + for (const [a, z, name] of [ + [b.document, row.document, 'document'], [b.edition, row.edition, 'edition'], + [b.repository_id, repository.id, 'repository'], [b.commit, run?.repository_commit, 'run-baseline'], + [b.run_sha256, row.run_record.sha256.slice(7), 'run-binding'], + [b.output_sha256, row.resource.sha256.slice(7), 'output-binding'], + [c.repository_id, b.repository_id, 'claimed-repository'], [o.repository_id, b.repository_id, 'observed-repository'], + [c.document_issue_id, row.document, 'claimed-document'], [o.document_issue_id, row.document, 'observed-document'], + [c.document_revision, row.edition, 'claimed-edition'], [o.document_revision, row.edition, 'observed-edition'], + [c.output_run_sha256, b.run_sha256, 'claimed-run'], [c.output_sha256, b.output_sha256, 'claimed-output'], + [o.snapshot?.commit, b.commit, 'observed-commit'], [o.snapshot?.id, b.commit, 'observed-snapshot'], + [c.snapshot_id, b.commit, 'claimed-snapshot'], + ]) compare(a, z, name); + for (const field of ['release_id', 'product_id']) { + if (field in b || field in c || field in o) { + compare(b[field], c[field], `claimed-${field}`); + compare(b[field], o[field], `observed-${field}`); + } + } + if (o.snapshot?.kind !== 'committed' || c.input_kind !== 'committed' || o.snapshot?.available !== true) missing('committed-observation-unavailable'); + if (bundle?.run instanceof Uint8Array && runBytes instanceof Uint8Array + && hash(bundle.run) !== hash(runBytes)) conflict('observer-run-conflict'); + // The register's retained bytes, never a substituted adapter run/output. + const output = await safeLoad(row.resource); + if (bundle?.output instanceof Uint8Array && output instanceof Uint8Array + && hash(bundle.output) !== hash(output)) conflict('observer-output-conflict'); + const closure = o.closure; + const bound = closure?.complete === true && closure.run_sha256 === b.run_sha256 + && closure.snapshot_id === b.commit && Array.isArray(closure.input_ids) + && closure.input_ids.every(text) && new Set(closure.input_ids).size === closure.input_ids.length; + if (!bound) missing('closure-unavailable'); + let diff; + try { + commit(repository.root, b.commit); + tree(repository.root, b.commit); // prove full retained tree availability for reverse lookup too + if (query.kind === 'review') diff = changes(repository.root, b.commit, commit(repository.root, query.target)); + } catch { missing('history-unavailable'); } + const observed = { ...o }; + delete observed.changes; // callers cannot substitute an unexecuted comparison + if (diff) observed.changes = { complete: true, repository_id: repository.id, + base_snapshot_id: b.commit, target_snapshot_id: query.target, ids: diff.ids }; + const provenance = await checker({ authorize: async () => true, + load: async () => ({ ...bundle, run: runBytes, output, observed }) }); + r.provenance = provenance; + if (provenance.status === 'inconsistent') conflict('provenance-conflict'); + r.model = { repository_id: b.repository_id ?? null, commit: b.commit ?? null, + generated_prose_model: run?.model_id ?? null, release_id: b.release_id ?? null, product_id: b.product_id ?? null }; + r.recipe = { id: run?.recipe_id ?? null, version: run?.recipe_version ?? null }; + r.elements = { inputs: bound ? [...closure.input_ids] : null, + attributions: Array.isArray(run?.slots) ? run.slots.flatMap(s => Array.isArray(s?.attributions) ? s.attributions : []) : null }; + if (diff) r.changes = diff; + const usable = r.findings.length === 0; + r.status = r.findings.some(f => f.status === 'inconsistent') ? 'inconsistent' + : !usable || provenance.status === 'incomplete' ? 'incomplete' : 'consistent'; + if (query.kind === 'document') r.match = 'yes'; + else if (usable) r.match = closure.input_ids.includes(query.id) ? 'yes' : 'no'; + if (query.kind === 'review' && usable && diff) { + const check = provenance.checks.find(x => x.id === 'changes.review'); + if (check?.status === 'consistent') r.review = check.reason === 'relevant-change-review-needed' ? 'review-needed' : 'no-relevant-change'; + // The selected element must actually change; all inputs still contribute + // to the per-document review result, without date/latest inference. + r.match = closure.input_ids.includes(query.id) && diff.ids.includes(query.id) ? 'yes' : 'no'; + } + } + const inconsistent = [...records, ...failures].some(r => r.status === 'inconsistent'); + return { status: inconsistent ? 'inconsistent' : 'incomplete', + reason: inconsistent ? 'evidence-conflict' : failures.length ? 'register-incomplete' + : records.length ? 'generation-not-proven' : 'no-retained-match', + matches: records.filter(r => r.match === 'yes').map(r => r.event_id), records, failures }; +} diff --git a/packages/documents-cli/src/register.mjs b/packages/documents-cli/src/register.mjs new file mode 100644 index 00000000..8a3b7a40 --- /dev/null +++ b/packages/documents-cli/src/register.mjs @@ -0,0 +1,56 @@ +import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises'; +import { isAbsolute, relative, resolve } from 'node:path'; +import { parseDocument } from 'yaml'; +import { inspectEvent, issueHash, localPointer } from './events.mjs'; + +export function parseRecord(bytes) { + const parsed = parseDocument(String(bytes), { uniqueKeys: true }); + if (parsed.errors.length) throw new Error(parsed.errors.map(e => e.message).join('; ')); + return parsed.toJS({ maxAliasCount: 100 }); +} + +export function localLoader(folder) { + return async ({ uri }) => { + if (!localPointer(uri)) return null; + const root = await realpath(folder); + const path = await realpath(resolve(root, uri)); + const rel = relative(root, path); + if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) return null; + return readFile(path); + }; +} + +async function exists(path) { + try { await lstat(path); return true; } + catch (error) { if (error.code === 'ENOENT') return false; throw error; } +} + +export async function createEvent(folder, supplied) { + const row = structuredClone(supplied); + if (row && typeof row === 'object' && !Array.isArray(row) && !Object.hasOwn(row, 'issue_hash')) row.issue_hash = issueHash(row); + const report = await inspectEvent(row, { load: localLoader(folder) }); + if (report.status === 'invalid' || report.status === 'conflict') throw new Error(JSON.stringify(report)); + const root = await realpath(folder); + const dir = resolve(root, 'events'); + await mkdir(dir, { recursive: true }); + if (await realpath(dir) !== dir) throw new Error('events must be a local directory, not a symlink.'); + if (await exists(resolve(dir, `${row.id}.yml`))) throw new Error('Event already exists as .yml.'); + // Exclusive creation is intentional: another act gets another ID. Nothing + // updates historical rows or writes their referenced evidence. + await writeFile(resolve(dir, `${row.id}.yaml`), `${JSON.stringify(row, null, 2)}\n`, { flag: 'wx' }); + return { row, ...report }; +} + +export async function readEvent(folder, id) { + if (!/^issue-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$/.test(id)) throw new Error('Invalid issue ID.'); + const yamlExists = await exists(resolve(folder, 'events', `${id}.yaml`)); + const ymlExists = await exists(resolve(folder, 'events', `${id}.yml`)); + if (yamlExists && ymlExists) throw new Error('Duplicate event files.'); + const bytes = await localLoader(folder)({ uri: `events/${id}.${ymlExists ? 'yml' : 'yaml'}` }); + if (!bytes) throw new Error('Event unavailable.'); + const row = parseRecord(bytes); + const report = await inspectEvent(row, { load: localLoader(folder) }); + if (row?.id !== id) report.findings.push({ code: 'INPUT', severity: 'error', file: `events/${id}.yaml`, message: 'Filename must match id.' }); + if (report.findings.length) report.status = 'invalid'; + return { row, ...report }; +} diff --git a/packages/documents-cli/src/validate.mjs b/packages/documents-cli/src/validate.mjs index b6a962bc..00c8811e 100644 --- a/packages/documents-cli/src/validate.mjs +++ b/packages/documents-cli/src/validate.mjs @@ -1,6 +1,8 @@ // 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' }; +import { validateEvent } from './events.mjs'; + +const PREFIX = { 'document-type': 'doct', document: 'doc', 'issuance-event': 'issue' }; 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-]+)*)?)?$/; @@ -24,7 +26,7 @@ export function validateRecords(records) { 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.'); + flag('INPUT', file, 'Expected a mapping with package: documents and kind: document-type, document or issuance-event.'); continue; } if (!text(obj.id) || !new RegExp(`^${PREFIX[obj.kind]}-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$`).test(obj.id)) { @@ -32,6 +34,7 @@ export function validateRecords(records) { } 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 === 'issuance-event') findings.push(...validateEvent(obj, 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'); diff --git a/packages/documents-cli/tests/test_documents_integrity.py b/packages/documents-cli/tests/test_documents_integrity.py index dc9a7e74..82f384b4 100644 --- a/packages/documents-cli/tests/test_documents_integrity.py +++ b/packages/documents-cli/tests/test_documents_integrity.py @@ -61,10 +61,12 @@ def main(): 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)) + renderer = json.loads(success("npm", "pack", "--json", "--pack-destination", temp, + cwd=ROOT / "packages/document-renderer")) root = temp / "adopter" root.mkdir() success("npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", - "--prefix", root, temp / packed[0]["filename"]) + "--prefix", root, temp / packed[0]["filename"], temp / renderer[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. @@ -155,6 +157,9 @@ def main(): print("PASS malformed YAML/schema: actionable input failure through dispatch") write(docpath, doc) + print(success("node", PACKAGE / "tests/test_events.mjs", root)) + print(success("node", PACKAGE / "tests/test_queries.mjs", root)) + canon_before = snapshot(root / "canon") shutil.rmtree(root / "documents") (root / "transitrix.yaml").write_text(manifest) @@ -172,6 +177,7 @@ def main(): silent = temp / "never-declared" shutil.copytree(root, silent) write(silent / "documents/documents/doc-invalid-1.yaml", {"package": "documents", "kind": "document", "id": "invalid"}) + write(silent / "documents/events/issue-invalid-1.yaml", {"package": "documents", "kind": "issuance-event", "id": "invalid"}) before = snapshot(silent) core_validate(silent) output = success("node", INGEST, "check-packages", silent) diff --git a/packages/documents-cli/tests/test_events.mjs b/packages/documents-cli/tests/test_events.mjs new file mode 100644 index 00000000..71c81e0e --- /dev/null +++ b/packages/documents-cli/tests/test_events.mjs @@ -0,0 +1,179 @@ +// Synthetic handoff acceptance through the packed CLI and normal dispatch. +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, writeFile, rm, symlink } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { tmpdir } from 'node:os'; +import { buildRunRecord, serializeRunRecord } from '../../document-renderer/src/run-record.mjs'; + +const root = resolve(process.argv[2]); +const folder = join(root, 'documents'); +const installed = join(root, 'node_modules/@transitrix/documents-cli'); +const cli = join(installed, 'documents.mjs'); +const { hashBytes, issueHash, inspectEvent, validateEvent } = await import(pathToFileURL(join(installed, 'src/events.mjs'))); +const { createEvent, readEvent } = await import(pathToFileURL(join(installed, 'src/register.mjs'))); +const dispatch = () => spawnSync(process.execPath, ['packages/ingest-cli/ingest.mjs', 'check-packages', root], { encoding: 'utf8' }); +const run = Buffer.from(serializeRunRecord(buildRunRecord({ + header: { recipe_id: 'rp17', recipe_version: '1.0' }, repositoryCommit: 'synthetic-base-b', + runTimestamp: '2026-07-10T09:00:00Z', renderDate: '2026-07-10', profile: 'strict', slotResults: [], +}))); +const baseline = Buffer.from('Synthetic retained baseline-b; repository commit synthetic-base-b\n'); +const output = Buffer.from('Synthetic RP-17 B output; no actual issuance or submission\n'); +await mkdir(join(folder, 'evidence')); +await writeFile(join(folder, 'evidence/run-b.json'), run); +await writeFile(join(folder, 'evidence/baseline-b.txt'), baseline); +const act = { + package: 'documents', kind: 'issuance-event', id: 'issue-rp17-b-1', synthetic: true, + document: 'doc-rp17-b-1', edition: 'B', issued_at: '2026-07-10T10:00:00Z', + issuer: 'Synthetic Issuer', recipient: 'Synthetic Recipient', + run_record: { uri: 'evidence/run-b.json', sha256: hashBytes(run) }, + baseline: { uri: 'evidence/baseline-b.txt', sha256: hashBytes(baseline) }, + resource: { uri: 'resource://documents/rp17/b.pdf', sha256: hashBytes(output) }, +}; +const temp = await mkdtemp(join(tmpdir(), 'documents-events-')); +try { + const outputPath = join(temp, 'b.pdf'); + await writeFile(outputPath, output); + const input = join(temp, 'act.yaml'); + await writeFile(input, JSON.stringify(act)); + const receipt = JSON.parse(execFileSync(process.execPath, [cli, 'record', folder, input], { encoding: 'utf8' })); + const row = receipt.row; + assert.equal(receipt.status, 'incomplete'); + assert.equal(receipt.timestamp_trust, 'not-supplied'); + assert.deepEqual(receipt.evidence.map(e => e.status), ['consistent', 'consistent', 'unavailable']); + assert.equal(receipt.evidence[0].format, 'flat'); + assert(!Object.hasOwn(row, 'timestamp')); + const read = JSON.parse(execFileSync(process.execPath, [cli, 'read', folder, row.id], { encoding: 'utf8' })); + assert.deepEqual(read.row, row); + assert.equal(dispatch().status, 0); + const historicalPath = join(folder, `events/${row.id}.yaml`); + const historicalBytes = await readFile(historicalPath); + await assert.rejects(createEvent(folder, act), /EEXIST/); + assert.deepEqual(await readFile(historicalPath), historicalBytes); + + const retained = new Map([[row.run_record.uri, run], [row.baseline.uri, baseline], [row.resource.uri, output]]); + const complete = await inspectEvent(row, { load: async ref => retained.get(ref.uri) }); + assert.equal(complete.status, 'consistent'); + // A structurally accepted synthetic token is not a trusted RFC 3161 assertion. + const token = Buffer.from('Synthetic timestamp evidence, not a DER timestamp token'); + const second = { ...act, id: 'issue-rp17-b-2', recipient: 'Synthetic Second Recipient' }; + second.issue_hash = issueHash(second); + second.timestamp = { format: 'rfc3161', issue_hash: second.issue_hash, + token_base64: token.toString('base64'), reference: { uri: 'evidence/timestamp.tsr', sha256: hashBytes(token) } }; + await writeFile(join(folder, 'evidence/timestamp.tsr'), token); + const supplied = await createEvent(folder, second); + assert.equal(supplied.timestamp_trust, 'not-verified'); + assert.deepEqual(supplied.row.timestamp, second.timestamp); + assert.deepEqual(await readFile(historicalPath), historicalBytes); + assert.deepEqual(await readFile(outputPath), output); + assert.deepEqual(await readFile(join(folder, act.run_record.uri)), run); + assert.deepEqual(await readFile(join(folder, act.baseline.uri)), baseline); + const externalToken = structuredClone(second); + delete externalToken.timestamp.token_base64; + externalToken.timestamp.reference.uri = 'https://example.invalid/synthetic.tsr'; + assert.equal((await inspectEvent(externalToken)).status, 'incomplete'); + assert.equal(validateEvent(externalToken).length, 0); + const tokenOnly = structuredClone(second); + delete tokenOnly.timestamp.reference; + assert.equal(validateEvent(tokenOnly).length, 0); + + const cases = []; + for (const key of ['document', 'edition', 'issued_at', 'issuer', 'recipient']) { + cases.push(['DOCS-EVENT', `missing ${key}`, r => { delete r[key]; }]); + } + for (const key of ['run_record', 'baseline', 'resource']) { + cases.push(['DOCS-POINTER', `missing ${key}`, r => { delete r[key]; }]); + cases.push(['DOCS-POINTER', `malformed ${key}`, r => { r[key].uri = '../escape'; }]); + cases.push(['DOCS-POINTER', `malformed ${key} hash`, r => { r[key].sha256 = 'sha256:abc'; }]); + } + for (const uri of ['https://example.invalid/bad uri', 'https://user:secret@example.invalid/file', + 'https://example.invalid/%QQ', '/absolute/local', 'evidence//run.json', 'evidence/./run.json']) { + cases.push(['DOCS-POINTER', 'malformed URI', r => { r.run_record.uri = uri; }]); + } + cases.push( + ['DOCS-EVENT', 'invalid calendar date', r => { r.issued_at = '2026-02-30T10:00:00Z'; }], + ['DOCS-EVENT', 'derived facts rejected', r => { r.elements_cited = ['GOAL-synthetic-1']; }], + ['DOCS-TIMESTAMP', 'bad token', r => { r.timestamp = { format: 'rfc3161', issue_hash: r.issue_hash, token_base64: '?' }; }], + ['DOCS-TIMESTAMP', 'conflicting association', r => { r.timestamp = { ...second.timestamp }; }], + ['DOCS-TIMESTAMP', 'conflicting token/reference', r => { r.timestamp = { ...second.timestamp, issue_hash: r.issue_hash, token_base64: Buffer.from('other').toString('base64') }; }], + ['DOCS-TIMESTAMP', 'empty evidence', r => { r.timestamp = { format: 'rfc3161', issue_hash: r.issue_hash }; }], + ['DOCS-TIMESTAMP', 'malformed reference', r => { r.timestamp = { format: 'rfc3161', issue_hash: r.issue_hash, reference: { uri: 'bad uri', sha256: hashBytes(token) } }; }], + ); + for (const [code, name, mutate] of cases) { + const bad = structuredClone(row); + mutate(bad); + bad.issue_hash = issueHash(bad); + await writeFile(historicalPath, JSON.stringify(bad)); + const result = dispatch(); + assert.equal(result.status, 1, `${name}: ${result.stdout}`); + assert(result.stdout.includes(`${code} error events/${row.id}.yaml`), `${name}: ${result.stdout}`); + } + const ymlPath = join(folder, 'events/issue-legacy-file-1.yml'); + const yml = { ...act, id: 'issue-legacy-file-1' }; + yml.issue_hash = issueHash(yml); + await writeFile(ymlPath, JSON.stringify(yml)); + assert.deepEqual((await readEvent(folder, yml.id)).row, yml); + await assert.rejects(createEvent(folder, yml), /already exists/); + await rm(ymlPath); + const reordered = Object.fromEntries(Object.entries(row).reverse()); + assert.equal(issueHash(reordered), row.issue_hash); + const invalidNew = { ...act, id: 'issue-invalid-1', issuer: '' }; + await assert.rejects(createEvent(folder, invalidNew), /DOCS-EVENT/); + await assert.rejects(readFile(join(folder, 'events/issue-invalid-1.yaml')), /ENOENT/); + await writeFile(historicalPath, historicalBytes); + const duplicatePath = join(folder, 'events/issue-duplicate-1.yaml'); + await writeFile(duplicatePath, historicalBytes); + assert.equal(dispatch().status, 1); + assert.match(dispatch().stdout, /DOCS-002 error/); + await rm(duplicatePath); + await writeFile(join(folder, 'evidence/timestamp.tsr'), 'different token'); + assert.match(dispatch().stdout, /timestamp: conflict/); + await writeFile(join(folder, 'evidence/timestamp.tsr'), token); + const tampered = { ...row, recipient: 'Synthetic Tamper' }; + await writeFile(historicalPath, JSON.stringify(tampered)); + assert.match(dispatch().stdout, /DOCS-HASH error/); + await writeFile(historicalPath, historicalBytes); + await writeFile(join(folder, act.run_record.uri), 'Changed run bytes'); + assert.equal(dispatch().status, 1); + assert.match(dispatch().stdout, /run_record: conflict/); + await writeFile(join(folder, act.run_record.uri), run); + await rm(join(folder, act.baseline.uri)); + const missing = await readEvent(folder, row.id); + assert.equal(missing.evidence.find(e => e.name === 'baseline').status, 'unavailable'); + assert.equal(dispatch().status, 0); + await writeFile(join(folder, act.baseline.uri), baseline); + + const inspectRun = async value => { + const bytes = Buffer.from(JSON.stringify(value)); + const r = structuredClone(row); + r.run_record.sha256 = hashBytes(bytes); + r.issue_hash = issueHash(r); + return inspectEvent(r, { load: async ref => ref.uri === r.run_record.uri ? bytes : retained.get(ref.uri) }); + }; + const flat = JSON.parse(run); + const legacy = { recipe: { id: flat.recipe_id, version: flat.recipe_version }, repository: { commit: flat.repository_commit }, slots: [] }; + assert.equal((await inspectRun(legacy)).evidence[0].format, 'legacy-nested'); + assert.equal((await inspectRun({})).status, 'incomplete'); + assert.equal((await inspectRun({ ...flat, ...legacy, recipe: { id: 'conflict', version: '1.0' } })).status, 'conflict'); + assert.equal((await inspectRun({ ...flat, repository: { commit: 'other' } })).status, 'conflict'); + assert.equal((await inspectRun({ ...flat, recipe: { version: 'other' } })).status, 'conflict'); + assert.equal((await inspectRun({ repository_commit: 'one', repository: { commit: 'two' } })).status, 'conflict'); + const denied = await inspectEvent(row, { load: async () => { throw new Error('unavailable'); } }); + assert.equal(denied.status, 'incomplete'); + const outside = join(temp, 'outside.json'); + await writeFile(outside, run); + await symlink(outside, join(folder, 'evidence/outside.json')); + const escaped = { ...act, id: 'issue-symlink-1', run_record: { uri: 'evidence/outside.json', sha256: hashBytes(run) } }; + const escapedReport = await createEvent(folder, escaped); + assert.equal(escapedReport.evidence[0].status, 'unavailable'); + await rm(join(folder, 'events/issue-symlink-1.yaml')); + await rm(join(folder, 'evidence/outside.json')); + assert.equal(dispatch().status, 0); + assert.deepEqual(await readFile(historicalPath), historicalBytes); + assert.deepEqual(await readFile(outputPath), output); + assert.deepEqual(await readFile(join(folder, act.run_record.uri)), run); + assert.deepEqual(await readFile(join(folder, act.baseline.uri)), baseline); + console.log(`PASS issuance: ${cases.length} dispatched invalid acts/pointers/timestamps; hash/byte conflicts fail; missing evidence explicit; legacy and unknown runs; no external fetch; history retained`); + console.log(`SYNTHETIC HANDOFF RECEIPT ${JSON.stringify({ ...receipt, supplied_bundle: complete.status, supplied_timestamp: supplied.timestamp_trust })}`); +} finally { await rm(temp, { recursive: true, force: true }); } diff --git a/packages/documents-cli/tests/test_queries.mjs b/packages/documents-cli/tests/test_queries.mjs new file mode 100644 index 00000000..07cf5570 --- /dev/null +++ b/packages/documents-cli/tests/test_queries.mjs @@ -0,0 +1,208 @@ +// Synthetic retained editions queried through the installed distribution. +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, writeFile, readdir, rm, rename } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { execFileSync } from 'node:child_process'; +import { buildRunRecord, serializeRunRecord } from '../../document-renderer/src/run-record.mjs'; +const installed = resolve(process.argv[2], 'node_modules/@transitrix/documents-cli'); +const { queryIssuedDocuments } = await import(pathToFileURL(join(installed, 'src/queries.mjs'))); +const { createEvent, localLoader } = await import(pathToFileURL(join(installed, 'src/register.mjs'))); +const { hashBytes, issueHash } = await import(pathToFileURL(join(installed, 'src/events.mjs'))); +const digest = b => hashBytes(b).slice(7); +const root = await mkdtemp(join(tmpdir(), 'documents-query-')); +const folder = join(root, 'documents'); +const git = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); +const put = async (p, bytes) => { await mkdir(join(root, p, '..'), { recursive: true }); await writeFile(join(root, p), bytes); }; +const save = message => { git('add', 'canon'); git('-c', 'user.name=Synthetic Test', '-c', 'user.email=synthetic@example.invalid', 'commit', '-qm', message); return git('rev-parse', 'HEAD'); }; +const snapshot = async dir => { + const files = {}; + async function walk(p, prefix = '') { + for (const e of await readdir(p, { withFileTypes: true })) { + const key = prefix + e.name; + if (e.isDirectory()) await walk(join(p, e.name), `${key}/`); + else files[key] = hashBytes(await readFile(join(p, e.name))); + } + } + await walk(dir); return files; +}; +try { + git('init', '-q'); + await put('canon/elements/REQ-14.yaml', 'id: REQ-14\nname: Synthetic retained content\n'); + await put('canon/elements/REQ-99.yaml', 'id: REQ-99\nname: Synthetic unrelated content\n'); + const base = save('Synthetic baseline'); + await put('canon/elements/REQ-14.yaml', 'id: REQ-14\nname: Synthetic relevant modification\n'); + const relevant = save('Synthetic relevant content'); + git('checkout', '-q', base); + await put('canon/elements/REQ-99.yaml', 'id: REQ-99\nname: Synthetic unrelated modification\n'); + const unrelated = save('Synthetic unrelated content'); + git('checkout', '-q', base); + await rename(join(root, 'canon/elements/REQ-14.yaml'), join(root, 'canon/elements/REQ-14-moved.yaml')); + const moved = save('Synthetic move'); + await rm(join(root, 'canon/elements/REQ-14-moved.yaml')); + const deleted = save('Synthetic deletion'); + git('checkout', '-q', base); + const recipe = await readFile(new URL('../../document-renderer/tests/fixtures/product.mrd.ttrs', import.meta.url)); + const run = Buffer.from(serializeRunRecord(buildRunRecord({ + header: { recipe_id: 'product.mrd', recipe_version: '1.0' }, repositoryCommit: base, + modelId: 'synthetic-prose-model', runTimestamp: '2026-07-10T09:00:00Z', renderDate: '2026-07-10', profile: 'strict', + slotResults: [{ slotId: 'synthetic', question: 'Synthetic', inputs: ['REQ-14'], sufficient: true, + verdict: 'sufficient', text: 'Synthetic', attributions: ['REQ-14'] }], + }))); + const output = Buffer.from('Synthetic retained RP-17 B; no real issuance'); + const baseline = { format: 'document-baseline/1', document: 'doc-rp17-b-1', edition: 'B', + repository_id: 'synthetic-model', commit: base, run_sha256: digest(run), output_sha256: digest(output), + product_id: 'PRODUCT-portal-1', release_id: 'RELEASE-portal-3.2' }; + await put('documents/evidence/run-b.json', run); + await put('documents/evidence/baseline-b.json', JSON.stringify(baseline)); + const act = { package: 'documents', kind: 'issuance-event', id: 'issue-rp17-b-1', synthetic: true, + document: baseline.document, edition: baseline.edition, issued_at: '2026-07-10T10:00:00Z', + issuer: 'Synthetic Issuer', recipient: 'Synthetic Recipient', + run_record: { uri: 'evidence/run-b.json', sha256: hashBytes(run) }, + baseline: { uri: 'evidence/baseline-b.json', sha256: hashBytes(Buffer.from(JSON.stringify(baseline))) }, + resource: { uri: 'resource://documents/rp17/b.pdf', sha256: hashBytes(output) } }; + await createEvent(folder, act); + await createEvent(folder, { ...act, id: 'issue-rp17-b-2', recipient: 'Synthetic Second Recipient' }); + const input = Buffer.from('Synthetic tool/rule/configuration evidence'); + const claims = { repository_id: baseline.repository_id, input_kind: 'committed', snapshot_id: base, + document_issue_id: act.document, document_revision: 'B', product_id: baseline.product_id, release_id: baseline.release_id, + output_sha256: digest(output), output_run_sha256: digest(run), recipe_sha256: digest(recipe), selection_sha256: digest(input), + tools: [{ id: 'synthetic-tool', sha256: digest(input) }], rules: [{ id: 'synthetic-rule', sha256: digest(input) }], + configuration: [{ id: 'synthetic-config', sha256: digest(input) }], external: [] }; + // This synthetic observer witnessed a fixed-ID selection over the controlled + // baseline. A dynamic query must include its membership dependencies instead. + const observed = { repository_id: baseline.repository_id, snapshot: { kind: 'committed', id: base, available: true, commit: base }, + document_issue_id: act.document, document_revision: 'B', product_id: baseline.product_id, release_id: baseline.release_id, + release_product_id: baseline.product_id, selection_sha256: digest(input), as_at: '2026-07-10', profile: 'strict', + closure: { complete: true, run_sha256: digest(run), snapshot_id: base, input_ids: ['REQ-14'] }, + tools: [{ id: 'synthetic-tool', bytes: input }], rules: [{ id: 'synthetic-rule', bytes: input }], + configuration: [{ id: 'synthetic-config', bytes: input }], external: [] }; + const bundle = { run, recipe, output, claims, observed }; + const options = { folder, repository: { root, id: baseline.repository_id }, authorize: async () => true, + load: async ref => ref.uri === act.resource.uri ? output : localLoader(folder)(ref), + observe: async () => bundle }; + const query = (q, extra = {}) => queryIssuedDocuments({ ...options, query: q, ...extra }); + const before = await snapshot(root); + const originalBundle = structuredClone(bundle); + let result = await query({ kind: 'document', id: act.document }); + assert.equal(result.status, 'incomplete'); // generation is never established + assert.deepEqual(result.matches, ['issue-rp17-b-1', 'issue-rp17-b-2']); + assert.equal(result.records[0].model.commit, base); + assert.equal(result.records[0].model.repository_id, baseline.repository_id); + assert.equal(result.records[0].model.generated_prose_model, 'synthetic-prose-model'); + assert.equal(result.records[0].model.release_id, baseline.release_id); + assert.deepEqual(result.records[0].elements.attributions, ['REQ-14']); + assert.equal(result.records[0].findings.length, 0, JSON.stringify(result)); + assert.deepEqual((await query({ kind: 'element', id: 'REQ-14' })).matches, result.matches); + assert.deepEqual((await query({ kind: 'element', id: 'REQ-99' })).records.map(r => r.match), ['no', 'no']); + for (const [name, target, expected] of [['relevant-content', relevant, 'review-needed'], ['unrelated-content', unrelated, 'no-relevant-change'], + ['move', moved, 'review-needed'], ['deletion', deleted, 'review-needed']]) { + result = await query({ kind: 'review', id: 'REQ-14', target }); + assert.deepEqual(result.records.map(r => r.review), [expected, expected], JSON.stringify(result)); + assert.equal(result.matches.length, expected === 'review-needed' ? 2 : 0); + console.log(JSON.stringify({ case: name, status: result.status, review: expected, matches: result.matches })); + } + for (const [name, mutate, conflict] of [ + ['missing-closure', b => { delete b.observed.closure; }, false], + ['partial-closure', b => { b.observed.closure.complete = false; }, false], + ['missing-binding', b => { delete b.claims.output_run_sha256; }, false], + ['wrong-document', b => { b.observed.document_issue_id = 'doc-other-1'; }, true], + ['wrong-edition', b => { b.observed.document_revision = 'A'; }, true], + ['wrong-release', b => { b.observed.release_id = 'RELEASE-portal-9'; }, true], + ['substituted-run', b => { b.run = Buffer.from('{}'); }, true], + ]) { + const b = structuredClone(bundle); mutate(b); + result = await query({ kind: 'review', id: 'REQ-14', target: relevant }, { observe: async () => b }); + assert.equal(result.status, conflict ? 'inconsistent' : 'incomplete', name); + assert(result.records.every(r => r.review === 'unknown' && r.match === 'unknown'), name); + } + result = await query({ kind: 'review', id: 'REQ-14', target: '0'.repeat(40) }); + assert(result.records.every(r => r.review === 'unknown' && r.findings.some(f => f.reason === 'history-unavailable'))); + for (const unavailable of [act.baseline.uri, act.run_record.uri, act.resource.uri]) { + result = await query({ kind: 'review', id: 'REQ-14', target: relevant }, + { load: async ref => ref.uri === unavailable ? null : options.load(ref) }); + assert.equal(result.status, 'incomplete'); + assert(result.records.every(r => r.review === 'unknown')); + } + result = await query({ kind: 'review', id: 'REQ-14', target: relevant }, + { load: async ref => ref.uri === act.baseline.uri ? Buffer.from('{}') : options.load(ref) }); + assert.equal(result.status, 'inconsistent'); + assert(result.records.every(r => r.review === 'unknown')); + let loaded = false; + result = await query({ kind: 'document', id: act.document }, { authorize: async () => false, load: async () => { loaded = true; } }); + assert.deepEqual(result, { status: 'incomplete', reason: 'unavailable', matches: [], records: [] }); + assert.equal(loaded, false); + assert.deepEqual(await snapshot(root), before, 'queries must preserve Git, records and all retained bytes'); + assert.deepEqual(structuredClone(bundle), originalBundle, 'adapter input must not mutate'); + const blob = git('rev-parse', `${base}:canon/elements/REQ-14.yaml`); + const objectPath = join(root, '.git/objects', blob.slice(0, 2), blob.slice(2)); + const objectBytes = await readFile(objectPath); + await rm(objectPath); + result = await query({ kind: 'review', id: 'REQ-14', target: base }); + assert(result.records.every(r => r.review === 'unknown' && r.findings.some(f => f.reason === 'history-unavailable'))); + await writeFile(objectPath, objectBytes); + const membership = structuredClone(bundle); + membership.observed.closure.input_ids.push('path:canon/elements'); + result = await query({ kind: 'review', id: 'REQ-14', target: unrelated }, { observe: async () => membership }); + assert(result.records.every(r => r.review === 'review-needed'), 'dynamic membership changes remain relevant'); + // Retained A is selected by its own identity; later actual reviews of A or B + // remain independent external evidence and never select or mint an edition. + const outputA = Buffer.from('Synthetic retained RP-17 A; original content'); + const baselineA = { ...baseline, document: 'doc-rp17-a-1', edition: 'A', output_sha256: digest(outputA) }; + delete baselineA.release_id; delete baselineA.product_id; + await put('documents/evidence/baseline-a.json', JSON.stringify(baselineA)); + const actA = { ...act, id: 'issue-rp17-a-1', document: baselineA.document, edition: 'A', issued_at: '2026-04-10T10:00:00Z', + baseline: { uri: 'evidence/baseline-a.json', sha256: hashBytes(Buffer.from(JSON.stringify(baselineA))) }, + resource: { uri: 'resource://documents/rp17/a.pdf', sha256: hashBytes(outputA) } }; + await createEvent(folder, actA); + const bundleA = structuredClone(bundle); + bundleA.output = outputA; + for (const data of [bundleA.claims, bundleA.observed]) { + data.document_issue_id = actA.document; data.document_revision = 'A'; + delete data.product_id; delete data.release_id; delete data.release_product_id; + } + bundleA.claims.output_sha256 = digest(outputA); + const editions = { load: async ref => ref.uri === actA.resource.uri ? outputA : options.load(ref), + observe: async row => row.document === actA.document ? bundleA : bundle }; + result = await query({ kind: 'document', id: actA.document }, editions); + assert.deepEqual(result.matches, ['issue-rp17-a-1']); + assert.equal(result.records[0].edition, 'A'); + assert.equal(result.records[0].findings.length, 0); + const retainedEditions = await snapshot(folder); + // These are synthetic external observations, not newly adopted review schema. + await put('actual-reviews.json', JSON.stringify([ + { document: 'RP-17', edition: 'A', performed: '2026-04-20', outcome: 'unchanged' }, + { document: 'RP-17', edition: 'B', performed: '2027-04-20', outcome: 'unchanged' }, + ])); + result = await query({ kind: 'document', id: act.document }, editions); + assert.deepEqual(result.matches, ['issue-rp17-b-1', 'issue-rp17-b-2']); + assert(result.records.every(r => r.edition === 'B' && r.model.release_id === baseline.release_id)); + assert.deepEqual(await snapshot(folder), retainedEditions, 'unchanged review must not rewrite A/B or create C'); + for (const malformed of ['null', '[]', '"unknown"']) { + const badBytes = Buffer.from(malformed); + const malformedAct = { ...act, baseline: { ...act.baseline, sha256: hashBytes(badBytes) } }; + malformedAct.issue_hash = issueHash(malformedAct); + result = await query({ kind: 'document', id: act.document }, { load: async ref => + ref.uri === 'events/issue-rp17-b-1.yaml' ? Buffer.from(JSON.stringify(malformedAct)) : + ref.uri === act.baseline.uri ? badBytes : options.load(ref) }); + assert.equal(result.records[0].status, 'incomplete'); + assert.equal(result.records[0].review, 'unknown'); + } + // Persisted contradictions remain conflicts even when event hashes agree. + const badBaseline = { ...baseline, edition: 'A' }; + await put('documents/evidence/baseline-b.json', JSON.stringify(badBaseline)); + const bad = { ...act, baseline: { ...act.baseline, sha256: hashBytes(Buffer.from(JSON.stringify(badBaseline))) } }; + bad.issue_hash = issueHash(bad); + await put('documents/events/issue-rp17-b-1.yaml', JSON.stringify(bad)); + result = await query({ kind: 'document', id: act.document }); + assert.equal(result.records[0].status, 'inconsistent'); + assert(result.records[0].findings.some(f => f.reason === 'edition-conflict')); + await put('documents/events/broken.yaml', 'package: ['); + result = await query({ kind: 'element', id: 'REQ-99' }); + assert(result.failures.length > 0); + assert.notEqual(result.status, 'consistent'); + await rm(join(folder, 'events'), { recursive: true }); + assert.equal((await query({ kind: 'document', id: act.document })).reason, 'register-unavailable'); + console.log('PASS packed queries: reverse/forward; controlled Git content/move/deletion; missing/conflicting evidence; read-only bytes; authorization; explicit release/B binding'); +} finally { await rm(root, { recursive: true, force: true }); } From afa898b3362d05d8f3d7758f6d281e1c84f0d7cf Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:55:13 +0400 Subject: [PATCH 08/26] fix: index aliases consistently across YAML list layouts (#642) Co-authored-by: transitrix --- packages/ingest-cli/README.md | 18 ++++++ packages/ingest-cli/src/canon.test.mjs | 83 +++++++++++++++++++++++++- packages/ingest-cli/src/yaml.mjs | 75 ++++++++++++++++------- 3 files changed, 154 insertions(+), 22 deletions(-) diff --git a/packages/ingest-cli/README.md b/packages/ingest-cli/README.md index 8b5554dd..7d2d0377 100644 --- a/packages/ingest-cli/README.md +++ b/packages/ingest-cli/README.md @@ -81,6 +81,24 @@ Package maintainers can check this boundary with `python packages/ingest-cli/tests/test_candidate_admission.py`. It uses synthetic data and the actual CLIs, including an explicit manual-promotion fixture step. +### Alias list input + +Canon alias indexing and catalogue matching accept `aliases:` followed by a block +sequence of single-line strings. The `-` markers may be flush-left or consistently +space-indented. Blank lines, comments and CRLF are supported; the next top-level +key ends the list. Plain strings, single-quoted strings (with doubled apostrophes), +and JSON-compatible double-quoted strings are accepted. Quote numbers and other +values that YAML would interpret as non-string scalars. Use `aliases: []` for an +empty list, or omit the key. + +Non-empty inline lists, nested collections, multiline values, anchors, tags, +inconsistent indentation, duplicate alias keys and malformed values are rejected. +Use the literal unquoted `aliases:` key. This small reader does not validate the +rest of the YAML document. Unsupported alias input stops commands such as +`repo-check` with exit code 2 instead of producing a partial successful report. +Alias collisions retain the existing report-only behavior: `repo-check` reports +`integrity.alias_collisions` and exits 0 after completing the report. + ## Multi-batch naming `review-queue.yaml` (and the reg-intel CLI's `review-digest.yaml`) is a **stable package filename**. The first batch for an org lands at the flat legacy path `_intake/processing/review-queue.yaml`. Batch identity is explicit: pass `--run-id ` to refresh the same batch in place (matching run_id is required). Without a matching run_id, or if no prior batch exists, a run creates its own dated **batch directory** instead — `_intake/processing/review-queue--YYYYMMDD-/review-queue.yaml`, where `` is `--scope ` (a generic word, never an org-identifying string) or defaults to `batch`. `workflow-status` discovers both the flat path and every dated directory. diff --git a/packages/ingest-cli/src/canon.test.mjs b/packages/ingest-cli/src/canon.test.mjs index b1de590d..c0fef34b 100644 --- a/packages/ingest-cli/src/canon.test.mjs +++ b/packages/ingest-cli/src/canon.test.mjs @@ -5,10 +5,16 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { buildCanonIndex } from './canon.mjs'; +// The list reader is shared by canon indexing and catalogue surface matching. +import { readTopList, dump } from './yaml.mjs'; +import { collectLocalElements } from './catalogue.mjs'; +import { spawnSync } from 'node:child_process'; +import { PRESETS_VERSION } from './coverage-presets.mjs'; +import { fileURLToPath } from 'node:url'; function tmpOrgRoot() { return mkdtempSync(join(tmpdir(), 'canon-test-')); @@ -68,3 +74,78 @@ test('buildCanonIndex: a TERM re-using its own name/alias is not a self-collisio const { collisions } = await buildCanonIndex(root); assert.deepEqual(collisions, []); }); + +for (const indent of ['', ' ', ' ']) { + for (const newline of ['\n', '\r\n']) { + test(`alias lists: indent ${indent.length}, ${JSON.stringify(newline)}`, async (t) => { + const list = (value) => [ + 'aliases: # surface forms', '# comment before first item', + `${indent}- "${value}" # comment`, '', `${indent}# comment between items`, + `${indent}- "Other"`, 'tags:', '- unrelated', 'name: Next', '', + ].join(newline); + assert.deepEqual(readTopList(list('Alpha'), 'aliases'), ['Alpha', 'Other']); + const root = tmpOrgRoot(); + t.after(() => rmSync(root, { recursive: true, force: true })); + writeElement(root, '02_business', 'actors', 'ACTOR-1', 'First', list('Alpha')); + writeElement(root, '02_business', 'actors', 'ACTOR-2', 'Second', `aliases:${newline}${indent}- Alpha${newline}`); + const index = await buildCanonIndex(root); + assert.equal(index.nameMap.get('alpha').matched_on, 'alias'); + assert.equal(index.nameMap.has('unrelated'), false); + assert.equal(index.collisions.length, 1); + assert.deepEqual((await collectLocalElements(root)).map(e => e.aliases), [['Alpha', 'Other'], ['Alpha']]); + writeElement(root, '02_business', 'actors', 'ACTOR-2', 'Second', `aliases:${newline}${indent}- Unique${newline}`); + assert.deepEqual((await buildCanonIndex(root)).collisions, []); + }); + } +} + +test('alias lists: empty, absent, quotes, comments and emitter round trip', () => { + assert.deepEqual(readTopList('tags:\n- unrelated\n', 'aliases'), []); + assert.deepEqual(readTopList('aliases: [] # empty\ntags:\n- unrelated\n', 'aliases'), []); + const aliases = ['Alpha', 'A "quote"', 'C:\\data', "Owner's name", 'A # B', 'null', '123']; + assert.deepEqual(readTopList(dump({ aliases }), 'aliases'), aliases); + assert.deepEqual(readTopList("aliases:\n- 'Owner''s name' # comment\n- Alpha#Beta\n- nullify\n", 'aliases'), ["Owner's name", 'Alpha#Beta', 'nullify']); + assert.deepEqual(readTopList('aliases:\n- 3D model\n', 'aliases'), ['3D model']); +}); + +const unsupportedAliases = [ + 'aliases : [Alpha]', '"aliases": [Alpha]', 'aliases: [Alpha]', 'aliases: Alpha', 'aliases: {}', 'aliases: null', + 'aliases:\n', 'aliases:\n- Alpha\n - Beta', 'aliases:\n\t- Alpha', + 'aliases:\n- Alpha\n- key: value', 'aliases:\n- Alpha\n- [Beta]', + 'aliases:\n- Alpha\n- |\n Beta', 'aliases:\n- Alpha\n continuation', + 'aliases:\n- Alpha\n- *ref', 'aliases:\n- &ref Alpha', 'aliases:\n- !str Alpha', + 'aliases:\n- "unclosed', "aliases:\n- 'unclosed", 'aliases:\n- "Alpha" trailing', + 'aliases:\n- "bad\\q"', 'aliases:\n-', 'aliases:\n- null', 'aliases:\n- 123', + 'aliases:\n- true', 'aliases: []\n- Alpha', 'aliases:\n- Alpha\naliases: []', +]; +for (const text of unsupportedAliases) { + test(`alias lists reject unsupported input: ${JSON.stringify(text)}`, async (t) => { + assert.throws(() => readTopList(text, 'aliases'), /Unsupported YAML list for aliases/); + const root = tmpOrgRoot(); + t.after(() => rmSync(root, { recursive: true, force: true })); + writeElement(root, '02_business', 'actors', 'ACTOR-1', 'First', `${text}\n`); + await assert.rejects(buildCanonIndex(root), /Unsupported YAML list for aliases/); + await assert.rejects(collectLocalElements(root), /Unsupported YAML list for aliases/); + }); +} + +test('repo-check CLI: layout parity, unique negative control and unsupported non-success', (t) => { + const root = tmpOrgRoot(); + t.after(() => rmSync(root, { recursive: true, force: true })); + writeFileSync(join(root, 'transitrix.yaml'), `methodology_version: "${PRESETS_VERSION}"\ncoverage_profile: core\n`); + const run = () => spawnSync(process.execPath, [fileURLToPath(new URL('../ingest.mjs', import.meta.url)), 'repo-check', root], { encoding: 'utf8' }); + for (const indent of ['', ' ']) { + for (const [alias, count] of [['Alpha', 1], ['Unique', 0]]) { + writeElement(root, '02_business', 'actors', 'ACTOR-1', 'First', `aliases:\n${indent}- Alpha\n`); + writeElement(root, '02_business', 'actors', 'ACTOR-2', 'Second', `aliases:\n${indent}- ${alias}\n`); + const result = run(); + assert.equal(result.status, 0, result.stderr); // report-only collision contract + assert.match(result.stdout, new RegExp(`alias_collisions: ${count}`)); + } + } + writeElement(root, '02_business', 'actors', 'ACTOR-2', 'Second', 'aliases: [Alpha]\n'); + const result = run(); + assert.equal(result.status, 2); + assert.equal(result.stdout, ''); + assert.match(result.stderr, /Unsupported YAML list for aliases/); +}); diff --git a/packages/ingest-cli/src/yaml.mjs b/packages/ingest-cli/src/yaml.mjs index 50a0f8da..e31ed8a1 100644 --- a/packages/ingest-cli/src/yaml.mjs +++ b/packages/ingest-cli/src/yaml.mjs @@ -66,30 +66,63 @@ export function dump(obj) { return dumpMap(obj, 0).join('\n') + '\n'; } -// Read a single top-level scalar key from manifest-style YAML text (e.g. -// `coverage_profile: full`). Returns the unquoted string, or null if the key is -// absent or its value is a block/map (not a top-level scalar). Intentionally tiny. -// Read a top-level list key from YAML text. Returns [] if absent or not a list. -// Understands the minimal block-list shapes this CLI emits and that adopter canon -// files carry — `key:\n - item\n - item`. Does NOT handle inline lists (`[a, b]`). +// Read a top-level list of single-line strings. Accept block sequences with a +// consistent space indent (including zero), plain/quoted items, and empty []. +// Missing keys return []; malformed or unsupported values throw so consumers +// cannot mistake a partial alias index for a complete one. This is not a YAML +// document validator: unrelated keys are outside this reader's scope. export function readTopList(text, key) { - if (typeof text !== 'string') return []; - // Normalise CRLF so the regex works on both Windows and Unix line endings. - const norm = text.replace(/\r\n/g, '\n'); - const re = new RegExp(`^${key}:[ \\t]*\\n((?:[ \\t]+-[^\\n]*\\n?)*)`, 'm'); - const m = norm.match(re); - if (!m) return []; - return m[1].replace(/\r/g, '').split('\n') - .map(l => l.replace(/^\s*-\s*/, '').trim()) - .filter(Boolean) - .map(v => { - if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) { - return v.slice(1, -1); - } - return v; - }); + if (typeof text !== 'string') throw new TypeError('readTopList expects YAML text'); + const lines = text.replace(/\r\n/g, '\n').split('\n'); + const fail = () => { throw new Error(`Unsupported YAML list for ${key}; use a block sequence of single-line strings or []`); }; + const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const keyPattern = new RegExp(`^(?:${escapedKey}|"${escapedKey}"|'${escapedKey}')[ \\t]*:`); + const headers = lines.flatMap((line, i) => keyPattern.test(line) ? [i] : []); + if (headers.length === 0) return []; + if (headers.length !== 1) return fail(); + const start = headers[0]; + if (!lines[start].startsWith(`${key}:`)) return fail(); + const header = lines[start].slice(key.length + 1).trim().replace(/(^|\s+)#.*$/, '').trim(); + if (header !== '' && header !== '[]') return fail(); + const values = []; + let indent; + for (let i = start + 1; i < lines.length; i++) { + const line = lines[i]; + if (/^ *($|#)/.test(line)) continue; + // Only a new top-level mapping key terminates this list. In particular, a + // flush-left sequence item belongs to the current key, not the next one. + if (/^[^\s:#][^:]*:(?:\s|$)/.test(line) && !line.startsWith('-')) break; + const item = /^( *)- +(.*)$/.exec(line); + if (header === '[]' || !item) return fail(); + if (indent === undefined) indent = item[1].length; + if (item[1].length !== indent) return fail(); + const raw = item[2].trim(); + let value; + if (raw.startsWith('"')) { + const quoted = /^"(?:[^"\\]|\\.)*"(?=\s+#|$)/.exec(raw); + if (!quoted) return fail(); + try { value = JSON.parse(quoted[0]); } catch { return fail(); } + } else if (raw.startsWith("'")) { + const quoted = /^'((?:[^']|'')*)'(?=\s+#|$)/.exec(raw); + if (!quoted) return fail(); + value = quoted[1].replace(/''/g, "'"); + } else { + value = raw.replace(/\s+#.*$/, '').trim(); + // Reject collections, block scalars, aliases, anchors, tags and implicit + // non-string scalars rather than indexing their YAML syntax as a name. + if (!value || /^[\[\]{}&*!|>@`#%"']/.test(value) || + /^[-?:](?:\s|$)/.test(value) || /:(?:\s|$)/.test(value) || + /^(?:null|~|true|false)$/i.test(value) || + /^[-+]?(?:0x[0-9a-f]+|0o[0-7]+|[0-9]+(?:\.[0-9]*)?(?:e[-+]?[0-9]+)?|\.[0-9]+(?:e[-+]?[0-9]+)?|\.(?:inf|nan))$/i.test(value)) return fail(); + } + values.push(value); + } + if (header === '' && values.length === 0) return fail(); + return values; } +// Read a single top-level scalar key from manifest-style YAML text. Returns the +// unquoted string, or null if absent. Intentionally tiny. export function readTopScalar(text, key) { if (typeof text !== 'string') return null; const re = new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, 'm'); From 49c7d525f320825b25c55fec7879e7c075fbe73b Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:53:52 +0400 Subject: [PATCH 09/26] Distinguish requirement provenance from central-admission origin (#643) * fix: distinguish requirement provenance from central origin Signed-off-by: transitrix * test: cover requirement origin discrimination Signed-off-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix --- notations/CONTRACT.md | 16 ++++++- packages/ingest-cli/src/catalogue.mjs | 47 ++++++++++++------- packages/ingest-cli/src/catalogue.test.mjs | 52 +++++++++++++++++++++ packages/ingest-cli/src/repo-check.mjs | 2 +- packages/ingest-cli/src/repo-check.test.mjs | 16 +++++++ 5 files changed, 115 insertions(+), 18 deletions(-) diff --git a/notations/CONTRACT.md b/notations/CONTRACT.md index 67603e19..b3ba68d1 100644 --- a/notations/CONTRACT.md +++ b/notations/CONTRACT.md @@ -1230,6 +1230,14 @@ A project repository's element and a central repository's element are related by Both fields are facts recorded *alongside* an element's own envelope (§3) — neither is a required field on any TYPE, and neither substitutes for `id`. **No tool ever rewrites a local `id`** in order to add or remove a binding. +**Requirement taxonomy is distinct.** The scalar `REQUIREMENT.origin` values +`legislative`, `process-product`, and `project-product` retain their meaning in +[elements/15-requirement.md](elements/15-requirement.md) §2.1 and are valid on local +requirements. They are not the central-admission map above. No field rename, +migration, or change to either authored shape is required. This distinction does +not permit central-admission maps on local REQUIREMENTs or taxonomy scalars on +other TYPEs; it does not define a combined scalar/map representation. + ### 17.2 Validation rules | Rule | Severity | Description | @@ -1238,7 +1246,13 @@ Both fields are facts recorded *alongside* an element's own envelope (§3) — n | `BIND-002` | error | `canon_id` resolves, but the resolved central element's TYPE differs from this element's own TYPE. | | `BIND-003` | error | Two or more elements in the same catalogue carry the same `canon_id` — a central element cannot be the binding target of more than one local element. A **cross-catalogue** gate, requiring a full catalogue scan. | | `BIND-004` | error | `canon_id` is present but the repository has no catalogue pin configured — a binding without a pin. | -| `BIND-005` | error | `origin` is present on an element that is not itself admitted in the central repository — `origin` records provenance for a central element, it is not a project-repository field. | +| `BIND-005` | error | Central-admission `origin` metadata is present on a local element. A recognised REQUIREMENT taxonomy scalar (§17.1) is exempt; other TYPEs and central-origin maps on REQUIREMENTs are not. The ingest checker retains this error for unrecognised or ambiguous local origins rather than assuming they are valid provenance. | + +The ingest checker's bounded reader recognises the three taxonomy values as +single-line plain, single-quoted, or double-quoted scalars, with optional trailing +comments. Duplicate keys, nested content, and unsupported YAML forms remain +ambiguous and are reported, not silently accepted. This check does not replace +`REQ-004` taxonomy validation. ### 17.3 Rendering rule diff --git a/packages/ingest-cli/src/catalogue.mjs b/packages/ingest-cli/src/catalogue.mjs index a3b807e0..31858d43 100644 --- a/packages/ingest-cli/src/catalogue.mjs +++ b/packages/ingest-cli/src/catalogue.mjs @@ -249,11 +249,27 @@ async function walkYaml(dir) { return out; } -// A block-map key's presence, independent of its value shape (`origin` is a map, -// never a scalar, so readTopScalar — which requires a same-line value — cannot see -// it at all: absent and present-as-a-block are otherwise indistinguishable to it). -function hasTopKey(text, key) { - return typeof text === 'string' && new RegExp(`^${key}:`, 'm').test(text); +// REQUIREMENT taxonomy is a scalar; central-admission origin is a map. +const REQUIREMENT_ORIGINS = new Set(['legislative', 'process-product', 'project-product']); + +// Retain the legacy presence marker for every unrecognised shape. Only a single, +// unambiguous, one-line scalar earns the taxonomy exception; duplicate keys or +// indented continuations must not hide a central-origin map or malformed value. +function readLocalOrigin(text) { + const lines = text.replace(/\r\n/g, '\n').split('\n'); + const entries = lines.flatMap((line, i) => /^(?:origin|'origin'|"origin")[ \t]*:/.test(line) ? [i] : []); + if (entries.length === 0) return false; + if (entries.length !== 1) return true; + const i = entries[0]; + const match = lines[i].match(/^origin:[ \t]+(?:([a-z-]+)|"([a-z-]+)"|'([a-z-]+)')[ \t]*(?:[ \t]#.*)?$/); + const value = match && (match[1] || match[2] || match[3]); + if (!REQUIREMENT_ORIGINS.has(value)) return true; + for (const line of lines.slice(i + 1)) { + if (!line.trim() || line.trimStart().startsWith('#')) continue; + if (/^\s/.test(line) || /^-/.test(line)) return true; + break; + } + return value; } // Read { id, type, name, aliases, description, canon_id, origin } off every admitted @@ -261,9 +277,9 @@ function hasTopKey(text, key) { // the BIND-001..005 envelope rules (CONTRACT.md §17.2) need. `type` is the catalogue // TYPE (the id's own prefix, IDS_AND_REFERENCES §1 — repo-check.mjs's // elementTypesOnDisk derives it the same way), NOT a per-TYPE subtype field some -// element schemas separately carry under their own `type:` key. `origin` is read as -// presence-only (BIND-005 only needs to know whether it is there, never its content — -// a project repository's own element should never carry it at all). `description` is +// element schemas separately carry under their own `type:` key. `origin` retains a +// recognised taxonomy scalar, false when absent, or true for any other present +// shape (including central metadata and ambiguous values). `description` is // read as a single-line scalar only — a multi-line block-scalar description reads // back as null here, same tiny-parser posture as everywhere else in this file. // canon/unresolved/ is excluded (CONTRACT.md §13 — a holding area, not admitted typed @@ -287,7 +303,7 @@ export async function collectLocalElements(orgRoot) { aliases: readTopList(text, 'aliases'), description: readTopScalar(text, 'description'), canon_id: readTopScalar(text, 'canon_id'), - origin: hasTopKey(text, 'origin'), + origin: readLocalOrigin(text), }); } return out; @@ -371,12 +387,10 @@ export function findVocabularyDivergence(localElements, catalogueElements) { // null — no pin declared (or a declared pin that failed to // load; a binding cannot be validated without a working // catalogue either way). -// origin_present — BIND-005: `origin` is present on a local element. Every -// element this function sees is, by construction, a -// *project* repository's own canon — `origin` records -// provenance for a *central* repository's admitted element, -// so its presence here is always a violation, regardless of -// pin state. +// origin_present — BIND-005: a local origin is central-admission metadata or +// cannot be distinguished from it. Only REQUIREMENT's three +// recognised taxonomy scalars are exempt, regardless of pin +// state. Legacy boolean presence markers remain supported. // Data-free posture matches findVocabularyDivergence: findings name ids (the // minimum needed to act), never a surface-form string. export function checkBindings(localElements, catalogueSlice) { @@ -390,7 +404,8 @@ export function checkBindings(localElements, catalogueSlice) { const byCanonId = new Map(); // canon_id -> [local_id...] (bound + resolved + type-matched only) for (const le of localElements || []) { - if (le.origin) origin_present.push({ local_id: le.id }); + const requirementProvenance = le.type === 'REQUIREMENT' && REQUIREMENT_ORIGINS.has(le.origin); + if (le.origin && !requirementProvenance) origin_present.push({ local_id: le.id }); if (!le.canon_id) continue; if (!catalogueSlice) { missing_pin.push({ local_id: le.id }); continue; } diff --git a/packages/ingest-cli/src/catalogue.test.mjs b/packages/ingest-cli/src/catalogue.test.mjs index e8d71100..946a9790 100644 --- a/packages/ingest-cli/src/catalogue.test.mjs +++ b/packages/ingest-cli/src/catalogue.test.mjs @@ -308,6 +308,58 @@ test('checkBindings: BIND-005 — origin present on a project repository\'s own assert.deepEqual(result.origin_present, [{ local_id: 'TERM-9' }]); }); +test('collectLocalElements: recognised REQUIREMENT taxonomy origins retain their scalar identity', async (t) => { + const root = tmpOrgRoot(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const dir = join(root, 'canon', 'elements', '01_motivation', 'requirements'); + mkdirSync(dir, { recursive: true }); + const fixtures = [ + ['REQUIREMENT-1', 'origin: legislative\n', 'legislative'], + ['REQUIREMENT-2', 'origin: "process-product" # taxonomy\n', 'process-product'], + ['REQUIREMENT-3', "origin: 'project-product'\n", 'project-product'], + ]; + for (const [id, origin, expected] of fixtures) { + writeFileSync(join(dir, `${id}.yaml`), `id: ${id}\nname: Requirement\n${origin}`, 'utf8'); + const element = (await collectLocalElements(root)).find((entry) => entry.id === id); + assert.equal(element.origin, expected); + assert.deepEqual(checkBindings([element], null).origin_present, []); + } +}); + +test('collectLocalElements: ambiguous, central and wrong-TYPE origins remain BIND-005 findings', async (t) => { + const root = tmpOrgRoot(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const requirements = join(root, 'canon', 'elements', '01_motivation', 'requirements'); + const goals = join(root, 'canon', 'elements', '01_motivation', 'goals'); + mkdirSync(requirements, { recursive: true }); + mkdirSync(goals, { recursive: true }); + const fixtures = [ + [requirements, 'REQUIREMENT-4', 'origin:\n repository: acme/model\n id: REQUIREMENT-9\n'], + [requirements, 'REQUIREMENT-5', 'origin: unknown\n'], + [requirements, 'REQUIREMENT-6', 'origin: legislative\norigin: process-product\n'], + [requirements, 'REQUIREMENT-7', 'origin: legislative\n nested: ambiguous\n'], + [goals, 'GOAL-1', 'origin: legislative\n'], + ]; + for (const [dir, id, origin] of fixtures) { + writeFileSync(join(dir, `${id}.yaml`), `id: ${id}\nname: Element\n${origin}`, 'utf8'); + } + const elements = await collectLocalElements(root); + assert.deepEqual(elements.map((entry) => [entry.id, entry.origin]).sort((a, b) => a[0].localeCompare(b[0])), [ + ['GOAL-1', 'legislative'], + ['REQUIREMENT-4', true], + ['REQUIREMENT-5', true], + ['REQUIREMENT-6', true], + ['REQUIREMENT-7', true], + ]); + assert.deepEqual(checkBindings(elements, null).origin_present, [ + { local_id: 'GOAL-1' }, + { local_id: 'REQUIREMENT-4' }, + { local_id: 'REQUIREMENT-5' }, + { local_id: 'REQUIREMENT-6' }, + { local_id: 'REQUIREMENT-7' }, + ]); +}); + test('checkBindings: an unbound element (no canon_id) with no origin reports nothing', () => { const local = [{ id: 'TERM-9', type: 'TERM', canon_id: null, origin: false }]; const result = checkBindings(local, null); diff --git a/packages/ingest-cli/src/repo-check.mjs b/packages/ingest-cli/src/repo-check.mjs index 40e2a067..518fb048 100644 --- a/packages/ingest-cli/src/repo-check.mjs +++ b/packages/ingest-cli/src/repo-check.mjs @@ -210,7 +210,7 @@ export async function repoCheck(orgRoot) { if (bindings.type_mismatch.length > 0) red_flags.push(`${bindings.type_mismatch.length} local element(s) bound to a central element of a different TYPE (BIND-002)`); if (bindings.duplicate_target.length > 0) red_flags.push(`${bindings.duplicate_target.length} central element(s) claimed as \`canon_id\` by more than one local element (BIND-003)`); if (bindings.missing_pin.length > 0) red_flags.push(`${bindings.missing_pin.length} local element(s) carry a \`canon_id\` but no catalogue pin is configured or loadable (BIND-004)`); - if (bindings.origin_present.length > 0) red_flags.push(`${bindings.origin_present.length} local element(s) carry an \`origin\` field — origin belongs only to a central repository's admitted elements (BIND-005)`); + if (bindings.origin_present.length > 0) red_flags.push(`${bindings.origin_present.length} local element(s) carry central-admission or unrecognised/ambiguous \`origin\` metadata — only REQUIREMENT taxonomy scalars are valid local origins (BIND-005)`); // Diagnostics (transitrix-hq#104 item 5): a per-file read failure is counted, never // silently absorbed into a lower zone/scanned count with no trace. Data-free — a // count, not the file path; `check-placement` / `check-stale` name the file for an diff --git a/packages/ingest-cli/src/repo-check.test.mjs b/packages/ingest-cli/src/repo-check.test.mjs index e0c1960e..6f910940 100644 --- a/packages/ingest-cli/src/repo-check.test.mjs +++ b/packages/ingest-cli/src/repo-check.test.mjs @@ -225,6 +225,22 @@ test('repoCheck: BIND-005 — an `origin` field on a project repository\'s own e assert.ok(report.integrity.red_flags.some((f) => f.includes('BIND-005'))); }); +test('repoCheck: REQUIREMENT taxonomy origin is not confused with central-admission provenance', async () => { + const root = tmpOrgRoot(); + writeFileSync(join(root, 'transitrix.yaml'), MANIFEST, 'utf8'); + const requirementsDir = join(root, 'canon', 'elements', '01_motivation', 'requirements'); + mkdirSync(requirementsDir, { recursive: true }); + writeFileSync( + join(requirementsDir, 'REQUIREMENT-1.yaml'), + 'id: REQUIREMENT-1\nname: Test Requirement\norigin: legislative\n', + 'utf8' + ); + + const report = await repoCheck(root); + assert.equal(Object.prototype.hasOwnProperty.call(report, 'bindings'), false); + assert.equal(report.integrity.red_flags.some((finding) => finding.includes('BIND-005')), false); +}); + test('repoCheck: BIND-004 — a canon_id present with no catalogue pin configured is flagged', async () => { const root = tmpOrgRoot(); writeFileSync(join(root, 'transitrix.yaml'), MANIFEST, 'utf8'); From ba9f24f65d89aebd4a00d34b604606bb80e99cb3 Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:58:56 +0400 Subject: [PATCH 10/26] Support vocabulary locations and explain incomplete diagnostics (#644) * fix: support vocabulary locations and explain incomplete diagnostics Signed-off-by: transitrix * test: preserve vocabulary bootstrap diagnostics Signed-off-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix --- packages/ingest-cli/README.md | 29 + packages/ingest-cli/cli.mjs | 730 +++++++++++++++++++ packages/ingest-cli/ingest.mjs | 746 +------------------- packages/ingest-cli/package.json | 1 + packages/ingest-cli/src/vocabulary.mjs | 9 +- packages/ingest-cli/src/vocabulary.test.mjs | 73 +- 6 files changed, 858 insertions(+), 730 deletions(-) create mode 100644 packages/ingest-cli/cli.mjs diff --git a/packages/ingest-cli/README.md b/packages/ingest-cli/README.md index 7d2d0377..9680311c 100644 --- a/packages/ingest-cli/README.md +++ b/packages/ingest-cli/README.md @@ -16,6 +16,35 @@ npm link The local install resolves the `transitrix-ingest` invocations used throughout the ingest and repo-check skills. Once the package ships to npm the equivalent shorthand becomes `npm install -g @transitrix/ingest-cli` (or `npx @transitrix/ingest-cli `) — the two forms invoke the same binary, with identical subcommands and flags. +### Vocabulary location and failed health checks + +Source-checkout and `npm link` installs default to the checkout's +`notations/vocabulary.yaml` and `notations/CURRENT_VERSION.yaml`, resolved from +the CLI module location, independently of the working directory. For a copied +package or an unpacked `npm pack` archive, set `TRANSITRIX_NOTATIONS_DIR` to an +explicit notations directory from the compatible methodology release. The package +archive does not bundle these files. The same setting works for source installs: + +```sh +TRANSITRIX_NOTATIONS_DIR=/path/to/methodology/notations transitrix-ingest repo-check /path/to/model +``` + +In PowerShell, set `$env:TRANSITRIX_NOTATIONS_DIR = 'C:\path\to\methodology\notations'` +before running `transitrix-ingest repo-check C:\path\to\model`. +A relative directory is resolved against the command's working directory. An unset +or empty variable keeps the source-checkout default. The directory selects both +files together; it is not the adopter's `transitrix.yaml` pin. Use vocabulary and +pin from the same compatible release as the CLI source. Matching pins establish +artifact version consistency, not support for arbitrary future vocabulary syntax. + +Missing or invalid vocabulary, an unreadable version pin, and version mismatches +stop the command with an explained diagnostic and exit code **2**. `repo-check` +reports **incomplete**, with **all health checks unavailable**: no partial health +report or successful dependent checks are emitted. Restore the release files or +correct the directory and rerun. There is no built-in vocabulary fallback and no +pin bypass. `--version` remains available to identify the package when vocabulary +cannot load; its package version alone does not identify a source revision. + ## The one rule The CLI **proposes**. It writes field artefacts, candidates, and a review queue into `_intake/` and `field/`. It **never** writes into `canon/`. Admission to canon stays a human gate. diff --git a/packages/ingest-cli/cli.mjs b/packages/ingest-cli/cli.mjs new file mode 100644 index 00000000..d01f6b9e --- /dev/null +++ b/packages/ingest-cli/cli.mjs @@ -0,0 +1,730 @@ +#!/usr/bin/env node +// @transitrix/ingest-cli — deterministic front-door pipeline for the Transitrix +// ingest skill. The skill's SKILL.md shells out to this CLI; it never reimplements +// the logic, so behaviour is identical under Claude and GitHub Copilot. +// +// THE ONE RULE: this CLI proposes. It writes field artefacts, candidates, and a +// review queue into _intake/ and field/, and it never writes *admitted* canon. The +// one path that writes under canon/ is the §13 holding area `canon/unresolved/`: +// emit-candidates parks objects it could not TYPE there as NON-admitted records (no +// admission record), which a human later resolves. Admitted canon stays human-gated. +// +// Exit codes: 0 = ok · 1 = usage / findings that need review · 2 = error +// +// Implemented: --version, scaffold-intake, convert, privacy-scan, admit-source (field +// + codex; field-artefact / codex-artefact remain as deprecated aliases), +// emit-candidates, validate, review-queue, adopt-adl, catalogue-pin, +// catalogue-recognize, catalogue-bind, catalogue-promote. + +import { readFile, writeFile, mkdir, access } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import { dirname, join, resolve } from 'node:path'; + +import { scaffoldIntake, findOrgRoot, stageDir, readManifestText } from './src/intake.mjs'; +import { convert, ConvertError } from './src/convert.mjs'; +import { emitFieldArtefact } from './src/field-artefact.mjs'; +import { validateCandidate, loadCandidates } from './src/validate.mjs'; +import { readCoverageProfile, parseProfileDecl } from './src/coverage.mjs'; +import { buildReviewQueue, writeReviewQueue } from './src/review-queue.mjs'; +import { resolveBatchPath } from './src/batch-path.mjs'; +import { dump, readTopScalar } from './src/yaml.mjs'; +import { buildProfileSuggestion } from './src/suggest-profile.mjs'; +import { emitCandidates } from './src/emit-candidates.mjs'; +import { emitCodexArtefact } from './src/codex-artefact.mjs'; +import { resolvePlacement, checkCanonPlacement } from './src/placement.mjs'; +import { repoCheck } from './src/repo-check.mjs'; +import { parsePackagesDecl, validatePackagesDecl, runPackageValidators } from './src/packages.mjs'; +import { checkStale } from './src/check-stale.mjs'; +import { computeWorkflowStatus, renderMarkdown, toReportObject } from './src/workflow-status.mjs'; +import { runPrivacyScan, parsePrivacyGateConfig } from './src/privacy-scan.mjs'; +import { CatalogueError, applyCataloguePin } from './src/catalogue.mjs'; +import { buildBindingProposals, applyBinding, buildPromotionProposalDoc, BindingError } from './src/binding.mjs'; +import { adoptAdl } from './src/adl-join.mjs'; +import { randomUUID } from 'node:crypto'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +// Tiny flag parser: returns { _: [positionals], flags: { name: value } }. +// `--k v` and `--k=v` are supported; a bare `--k` becomes boolean true. +function parseArgs(args) { + const out = { _: [], flags: {} }; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a.startsWith('--')) { + const eq = a.indexOf('='); + if (eq >= 0) out.flags[a.slice(2, eq)] = a.slice(eq + 1); + else if (i + 1 < args.length && !args[i + 1].startsWith('--')) out.flags[a.slice(2)] = args[++i]; + else out.flags[a.slice(2)] = true; + } else out._.push(a); + } + return out; +} + +const today = () => new Date().toISOString().slice(0, 10); + +async function version() { + const pkg = JSON.parse(await readFile(join(__dirname, 'package.json'), 'utf8')); + return pkg.version; +} + +function usage() { + return [ + 'transitrix-ingest [args]', + '', + 'Commands:', + ' scaffold-intake Create _intake/{inbox,processing,processed} (idempotent)', + ' convert Convert a document to Markdown in _intake/processing/', + ' privacy-scan Fail-closed PII/medical pre-admission gate (SKILL.md Step 2b)', + ' CLEAN|STRIPPED proceed to admit-source; REJECTED|ERROR halt the pipeline', + ' admit-source --zone field|codex Admit a converted source to the field or codex zone', + ' field: --type INTERVIEW|SURVEY|OBSERVATION|DRAFT --role R --date YYYY-MM-DD', + ' [--captured-by X] [--source-quality Q] [--slug SL] [--admitted-at A]', + ' codex: --type LAW|REGULATION|STANDARD|POLICY|INTERNAL_STANDARD|PRINCIPLE --effective-date YYYY-MM-DD', + ' (--effective-date optional for PRINCIPLE; PRINCIPLE instead requires --statement --rationale)', + ' STANDARD requires --jurisdiction and --issuing-authority (the issuing body)', + ' [--jurisdiction J] [--source-authority A] [--issuing-authority A] [--established-by A] [--slug SL] [--monitoring]', + ' [--force] admit even if an identical source (same source_hash) is already admitted', + ' field-artefact / codex-artefact Deprecated aliases of admit-source --zone field|codex', + ' emit-candidates --from [--candidates-dir ]', + ' Shape the agent extraction result into candidates', + ' validate Validate candidate *.json against the contract + coverage profile', + ' review-queue Assemble the human review queue (writes review-queue.yaml)', + ' [--out ] [--scope ]', + ' Non-destructive default: an unresolved review-queue.yaml already at the flat', + ' path is never overwritten — a concurrent batch lands under its own dated dir', + ' review-queue--YYYYMMDD-/review-queue.yaml (--scope defaults to "batch").', + ' suggest-profile Propose a coverage-profile delta for out-of-profile TYPEs (read-only; prints to stdout)', + ' adopt-adl [--repo /] L0 — join the decision-log network in one step: create', + ' operations/decisions/, wire scripts/check-adl.mjs + its CI workflow, and (with', + ' --repo) print the harvest.config.yaml line to add centrally. Idempotent.', + ' catalogue-pin / [org-root] L1 — write the catalogue: pin into transitrix.yaml.', + ' Refuses to touch the manifest if a catalogue: field is already declared.', + ' catalogue-recognize [org-root] L2 — propose bindings (unambiguous name/alias + TYPE match) against the pinned', + ' catalogue -> catalogue-bindings.proposed.yaml; nothing admitted, never overwrites an', + ' unresolved queue [--out ] [--scope ]', + ' catalogue-bind [org-root] Apply an accepted L2/L3 binding — writes canon_id into the', + ' local element file; idempotent if already bound to the same id, refuses to rebind', + ' catalogue-promote --repository / [org-root] L3 — emit a promotion proposal for the', + ' central repository\'s human admission gate -> promotions.proposed.yaml', + ' [--out ] [--scope ]', + ' repo-check [org-root] Data-free health report (version, profile, zone/TYPE counts, integrity flags); read-only', + ' check-placement [org-root] Flag admitted elements sitting outside their ELEMENT_PRIMITIVES §4 folder', + ' check-packages [org-root] Validate `packages:` declarations (PKG-001/PKG-002) and run each', + ' declared package\'s own validator entry point, if present (PACKAGES.md §4.2, §7)', + ' check-stale [org-root] List REQUIREMENT/CONSTRAINT elements whose next_review_at has passed (REQ-STALE-001)', + ' workflow-status [org-root] Report every human gate\'s phase + count (ADR/WI/canon/overdue/ingest batch); read-only', + ' [--out ] [--format md|yaml] [--data-free]', + ' resolve-placement Print a TYPE\'s §4 materialisation mode + layer + folder', + ' --version, -v Print the CLI version', + ' --help, -h Show this help', + ].join('\n'); +} + +async function cmdScaffoldIntake(args) { + const orgRoot = args[0]; + if (!orgRoot) { console.error('scaffold-intake: missing '); return 1; } + const { created, existing } = await scaffoldIntake(orgRoot); + for (const d of created) console.log(`created ${d}/`); + for (const d of existing) console.log(`exists ${d}/`); + console.log(`\n_intake/ ready under ${resolve(orgRoot)} (${created.length} created, ${existing.length} already present).`); + return 0; +} + +async function cmdConvert(args) { + const file = args[0]; + if (!file) { console.error('convert: missing '); return 1; } + const src = resolve(file); + try { await access(src); } catch { console.error(`convert: file not found: ${file}`); return 2; } + const orgRoot = await findOrgRoot(src); + if (!orgRoot) { + console.error(`convert: "${file}" is not inside an _intake/ workspace. Run \`scaffold-intake \` first and drop the file in _intake/inbox/.`); + return 2; + } + const processing = stageDir(orgRoot, 'processing'); + try { + const { out, mode } = await convert(src, processing); + console.log(`converted (${mode}) ${file} -> ${out}`); + return 0; + } catch (err) { + if (err instanceof ConvertError) { + console.error(err.message); + return err.exitCode; + } + throw err; + } +} + +async function cmdPrivacyScan(args) { + const { _ } = parseArgs(args); + const md = _[0]; + if (!md) { console.error('privacy-scan: missing '); return 1; } + const mdPath = resolve(md); + try { await access(mdPath); } catch { console.error(`privacy-scan: file not found: ${md}`); return 2; } + const orgRoot = await findOrgRoot(mdPath); + if (!orgRoot) { console.error(`privacy-scan: "${md}" is not inside an _intake/ workspace.`); return 2; } + + const config = parsePrivacyGateConfig(await readManifestText(orgRoot)); + const processingDir = stageDir(orgRoot, 'processing'); + const res = await runPrivacyScan({ mdPath, processingDir, config, runId: randomUUID() }); + + console.log(`privacy-scan ${md} -> ${res.outcome}`); + if (res.outcome === 'STRIPPED') { + console.log(` ${res.blockedFragments.filter((f) => !f.allowlist_cleared).length} fragment(s) redacted -> ${res.redactedFile}`); + console.log(' admit-source must be run on the redacted copy, not the original.'); + } + if (res.outcome === 'REJECTED') { + console.error(` ${res.blockedFragments.length} fragment(s) blocked — document not admissible; see privacy-report.yaml`); + } + if (res.outcome === 'ERROR') { + console.error(` ${res.errorDetail}`); + } + console.log(` privacy-report.yaml -> ${join(processingDir, 'privacy-report.yaml')}`); + + if (res.outcome === 'CLEAN' || res.outcome === 'STRIPPED') return 0; + if (res.outcome === 'REJECTED') return 1; + return 2; +} + +async function cmdFieldArtefact(args) { + const { _, flags } = parseArgs(args); + const md = _[0]; + if (!md) { console.error('field-artefact: missing (a converted file in _intake/processing/)'); return 1; } + const mdPath = resolve(md); + try { await access(mdPath); } catch { console.error(`field-artefact: file not found: ${md}`); return 2; } + if (!flags.type || !flags.role || !flags.date) { + console.error('field-artefact: --type, --role and --date are required'); + return 1; + } + const orgRoot = await findOrgRoot(mdPath); + if (!orgRoot) { console.error(`field-artefact: "${md}" is not inside an _intake/ workspace.`); return 2; } + + try { + const res = await emitFieldArtefact({ + orgRoot, mdPath, + type: String(flags.type).toUpperCase(), + role: flags.role, + date: flags.date, + setting: flags.setting, + capturedBy: flags['captured-by'] || '@transitrix/ingest-cli', + sourceQuality: flags['source-quality'], + slug: flags.slug, + admittedAt: flags['admitted-at'] || today(), + name: flags.name, + force: flags.force === true || flags.force === 'true', + }); + console.log(`field artefact ${res.id} -> ${res.outPath}`); + console.log(` proposed source_quality: ${res.proposedSQ} (confirm at admission)`); + if (res.rawMoved) console.log(` raw source retained: ${res.rawMoved}`); + if (res.sourceHash) console.log(` source_hash: ${res.sourceHash}`); + return 0; + } catch (err) { + if (err.duplicate) { + console.log(`field artefact skipped — ${err.message}`); + return 0; + } + console.error(`field-artefact: ${err.message}`); + return err.privacyGate ? 1 : 2; + } +} + +async function cmdCodexArtefact(args) { + const { _, flags } = parseArgs(args); + const md = _[0]; + if (!md) { console.error('codex-artefact: missing (a converted file in _intake/processing/)'); return 1; } + const mdPath = resolve(md); + try { await access(mdPath); } catch { console.error(`codex-artefact: file not found: ${md}`); return 2; } + if (!flags.type) { + console.error('codex-artefact: --type is required'); + return 1; + } + // --effective-date is required for every TYPE except PRINCIPLE (optional there, + // 14-codex.md §4.1); emitCodexArtefact enforces the per-TYPE required fields. + if (String(flags.type).toUpperCase() !== 'PRINCIPLE' && !flags['effective-date']) { + console.error('codex-artefact: --effective-date is required'); + return 1; + } + const orgRoot = await findOrgRoot(mdPath); + if (!orgRoot) { console.error(`codex-artefact: "${md}" is not inside an _intake/ workspace.`); return 2; } + + try { + const res = await emitCodexArtefact({ + orgRoot, mdPath, + type: String(flags.type).toUpperCase(), + jurisdiction: flags.jurisdiction, + effectiveDate: flags['effective-date'], + sourceAuthority: flags['source-authority'], + issuingAuthority: flags['issuing-authority'], + statement: flags.statement, + rationale: flags.rationale, + establishedBy: flags['established-by'], + admittedAt: flags['admitted-at'] || today(), + admittedBy: flags['admitted-by'] || '@transitrix/ingest-cli', + monitoring: flags.monitoring === true || flags.monitoring === 'true', + slug: flags.slug, + name: flags.name, + force: flags.force === true || flags.force === 'true', + }); + console.log(`codex artefact ${res.id} -> ${res.outPath}`); + console.log(` zone: codex (${res.scope}) — authoritative by construction; derive obligations as REQUIREMENT + ASSERTION candidates`); + if (res.snapshotFile) console.log(` snapshot retained: ${res.snapshotFile}`); + if (res.sourceHash) console.log(` source_hash: ${res.sourceHash}`); + return 0; + } catch (err) { + if (err.duplicate) { + console.log(`codex artefact skipped — ${err.message}`); + return 0; + } + console.error(`codex-artefact: ${err.message}`); + return 2; + } +} + +// Unified front door (admit-source --zone). `field-artefact` and `codex-artefact` +// remain as deprecated aliases for one release; both route through here. +async function cmdAdmitSource(args) { + const { flags } = parseArgs(args); + const zone = flags.zone || 'field'; + if (zone === 'field') return cmdFieldArtefact(args); + if (zone === 'codex') return cmdCodexArtefact(args); + console.error(`admit-source: --zone must be field|codex (got ${JSON.stringify(zone)})`); + return 1; +} + +async function resolveDir(dirArg, label) { + if (!dirArg) { console.error(`${label}: missing `); return { code: 1 }; } + const dir = resolve(dirArg); + try { await access(dir); } catch { console.error(`${label}: directory not found: ${dirArg}`); return { code: 2 }; } + const orgRoot = await findOrgRoot(dir); + if (!orgRoot) { console.error(`${label}: "${dirArg}" is not inside an _intake/ workspace.`); return { code: 2 }; } + return { dir, orgRoot, profile: await readCoverageProfile(orgRoot) }; +} + +async function cmdValidate(args) { + const { _ } = parseArgs(args); + const r = await resolveDir(_[0], 'validate'); + if (r.code) return r.code; + + if (r.profile && r.profile.warning) console.error(`WARNING: ${r.profile.warning}`); + + const loaded = await loadCandidates(r.dir); + if (loaded.length === 0) { console.log(`validate: no candidate *.json files in ${_[0]}`); return 0; } + + let needsReview = 0; + for (const { ref, candidate, parseError } of loaded) { + if (parseError || !candidate) { console.log(`FLAG ${ref}\n - does not parse: ${parseError || 'null'}`); needsReview++; continue; } + const v = validateCandidate(candidate, r.profile); + const issues = [...v.validation_flags]; + if (v.coverage_flag === 'out_of_profile') issues.push(`coverage: ${v.coverage_reason || 'out of profile'}`); + if (issues.length) { needsReview++; console.log(`FLAG ${ref}`); for (const i of issues) console.log(` - ${i}`); } + else console.log(`ok ${ref}`); + } + console.log(`\n${loaded.length} candidate(s); ${needsReview} need review.`); + return needsReview ? 1 : 0; +} + +async function cmdReviewQueue(args) { + const { _, flags } = parseArgs(args); + const r = await resolveDir(_[0], 'review-queue'); + if (r.code) return r.code; + + // Pick up relation suggestions emitted by `emit-candidates`, if present. + let suggestions = []; + const suggPath = join(stageDir(r.orgRoot, 'processing'), 'relation-suggestions.json'); + try { suggestions = JSON.parse(await readFile(suggPath, 'utf8')); } catch { /* none */ } + + // Pick up semantic links emitted by `emit-candidates`, if present. + let semanticLinks = []; + const semanticLinksPath = join(stageDir(r.orgRoot, 'processing'), 'semantic-links.json'); + try { semanticLinks = JSON.parse(await readFile(semanticLinksPath, 'utf8')); } catch { /* none */ } + + // Pick up role assignment proposals emitted by `emit-candidates`, if present. + let roleAssignmentProposals = []; + const roleAssignmentProposalsPath = join(stageDir(r.orgRoot, 'processing'), 'role-assignment-proposals.json'); + try { roleAssignmentProposals = JSON.parse(await readFile(roleAssignmentProposalsPath, 'utf8')); } catch { /* none */ } + + const runId = typeof flags['run-id'] === 'string' ? flags['run-id'] : undefined; + const queue = await buildReviewQueue({ orgRoot: r.orgRoot, candidatesDir: r.dir, profile: r.profile, suggestions, semanticLinks, roleAssignmentProposals, runId }); + const out = flags.out + ? resolve(flags.out) + : await resolveBatchPath({ processingDir: stageDir(r.orgRoot, 'processing'), filename: 'review-queue.yaml', scope: flags.scope, content: dump(queue), runId }); + await writeReviewQueue(queue, out); + const flagged = queue.candidates.filter(c => c.validation_flags.length || c.coverage_flag === 'out_of_profile').length; + if (queue.coverage_warning) console.error(`WARNING: ${queue.coverage_warning}`); + console.log(`review queue -> ${out}`); + console.log(` coverage_profile: ${queue.coverage_profile}`); + console.log(` ${queue.field_artefacts.length} field artefact(s), ${queue.candidates.length} candidate(s) (${flagged} flagged), ${queue.relation_suggestions.length} relation suggestion(s).`); + if (queue.semantic_links) console.log(` ${queue.semantic_links.length} semantic link(s) — review-only, no closed REL kind yet.`); + if (queue.role_assignment_proposals) console.log(` ${queue.role_assignment_proposals.length} role assignment proposal(s) — pending human decision.`); + if (queue.excluded_admitted.length) { + console.log(` ${queue.excluded_admitted.length} candidate(s) excluded — already admitted to canon (idempotent re-run).`); + } + console.log(' nothing admitted to canon — a human gates this queue.'); + return 0; +} + +async function cmdEmitCandidates(args) { + const { _, flags } = parseArgs(args); + const fa = _[0]; + if (!fa) { console.error('emit-candidates: missing '); return 1; } + if (!flags.from) { console.error('emit-candidates: --from is required (the agent extraction result)'); return 1; } + const fieldArtefactPath = resolve(fa); + try { await access(fieldArtefactPath); } catch { console.error(`emit-candidates: field artefact not found: ${fa}`); return 2; } + const orgRoot = await findOrgRoot(fieldArtefactPath); + if (!orgRoot) { console.error(`emit-candidates: "${fa}" is not inside an _intake/ workspace.`); return 2; } + + try { + const res = await emitCandidates({ + orgRoot, fieldArtefactPath, + resultPath: resolve(flags.from), + candidatesDir: flags['candidates-dir'] ? resolve(flags['candidates-dir']) : undefined, + ingestDate: flags['ingest-date'] || today(), + }); + console.log(`emit-candidates derived_from ${res.derivedFrom}`); + console.log(` ${res.candidates.length} candidate(s) -> ${res.dir}`); + console.log(` ${res.suggestions.length} relation suggestion(s) held back (relation-conservative) -> ${res.suggPath}`); + if (res.semanticLinks && res.semanticLinks.length) { + console.log(` ${res.semanticLinks.length} semantic link(s) (no closed REL kind yet) -> ${res.semanticLinksPath}`); + } + if (res.roleAssignmentProposals && res.roleAssignmentProposals.length) { + console.log(` ${res.roleAssignmentProposals.length} role assignment proposal(s) (person->role, decision pending) -> ${res.roleAssignmentProposalsPath}`); + } + if (res.unresolved && res.unresolved.written.length) { + console.log(` ${res.unresolved.written.length} untyped object(s) parked (non-admitted) -> ${res.unresolved.dir}`); + } + if (res.unresolved && res.unresolved.skipped) { + console.error(` WARNING: ${res.unresolved.skipped} unresolved item(s) dropped — missing required ingest_field / data (CONTRACT §13.2)`); + } + for (const w of res.warnings || []) console.error(` WARNING: ${w}`); + console.log(' candidates are pending — nothing admitted to canon.'); + return 0; + } catch (err) { + console.error(`emit-candidates: ${err.message}`); + return 2; + } +} + +// Discovery: scan candidates for out-of-profile TYPEs and PROPOSE a coverage delta. +// Read-only — prints a paste-ready suggestion to stdout, never widens the profile. +async function cmdSuggestProfile(args) { + const { _ } = parseArgs(args); + const r = await resolveDir(_[0], 'suggest-profile'); + if (r.code) return r.code; + + const loaded = await loadCandidates(r.dir); + if (loaded.length === 0) { console.error(`suggest-profile: no candidate *.json files in ${_[0]}`); return 0; } + + const decl = parseProfileDecl((await readManifestText(r.orgRoot)) || ''); + const baseName = decl.kind === 'short' ? decl.name : decl.kind === 'custom' ? decl.extends : 'full'; + const report = buildProfileSuggestion(loaded, r.profile, baseName); + process.stdout.write(dump(report)); + return 0; +} + +// Read-only "doctor": emit a short, data-free health report for an adopter repo. +async function cmdRepoCheck(args) { + const { _ } = parseArgs(args); + const orgRoot = _[0] ? resolve(_[0]) : (await findOrgRoot(process.cwd()) || process.cwd()); + const report = await repoCheck(orgRoot); + process.stdout.write(dump(report)); + return 0; +} + +// L0 — join the decision-log network in one step (method/07-decisions.md +// §9, guides/adl-adopter-setup.md Step 1, method/09-releases-and-propagation.md +// §6.6): the records folder, the vendored CI +// guard + its workflow, and (with --repo) the harvest.config.yaml line a human adds to +// the central repo. Idempotent — a file or folder already in place is left untouched. +async function cmdAdoptAdl(args) { + const { _, flags } = parseArgs(args); + const orgRoot = _[0]; + if (!orgRoot) { console.error('adopt-adl: missing '); return 1; } + + const { created, existing, centralLine } = await adoptAdl(orgRoot, { repoCoordinate: flags.repo }); + for (const d of created) console.log(`created ${d}`); + for (const d of existing) console.log(`exists ${d}`); + if (centralLine) { + console.log('\nAdd this to the central architecture repo\'s architecture/decision-log/harvest.config.yaml under `sources:`:\n'); + console.log(centralLine); + } else { + console.log('\nPass --repo / to also print the harvest.config.yaml line for the central repo.'); + } + console.log(`\nL0 ready under ${resolve(orgRoot)} (${created.length} created, ${existing.length} already present). Next: /transitrix:adr to write the first record.`); + return 0; +} + +// L1 — write the catalogue: pin into transitrix.yaml (method/09-releases-and-propagation.md +// §6.4.2, §6.6). Refuses to touch the manifest if a catalogue: field is already declared — +// a re-pin is a deliberate edit, not something this command guesses at. +async function cmdCataloguePin(args) { + const { _ } = parseArgs(args); + const [source, version, pinPath] = _; + if (!source || !version || !pinPath) { console.error('catalogue-pin: missing / '); return 1; } + const orgRoot = _[3] ? (await findOrgRoot(resolve(_[3])) || resolve(_[3])) : (await findOrgRoot(process.cwd()) || process.cwd()); + + try { + const res = await applyCataloguePin(orgRoot, { source, version, path: pinPath }); + console.log(`catalogue-pin ${res.source}@${res.version} -> ${res.path}`); + console.log(` vendor the slice at ${res.pinPath} before running catalogue-recognize/repo-check (method/09-releases-and-propagation.md §6.4.3 — fails closed).`); + return 0; + } catch (err) { + if (err instanceof CatalogueError) { console.error(err.message); return 1; } + throw err; + } +} + +// L2 — recognition: propose bindings against the pinned catalogue for every unbound +// local element with an unambiguous, same-TYPE name/alias match. Writes the review +// artefact, never admits one (method/09-releases-and-propagation.md §6.5) — a human +// accepts a proposal by running `catalogue-bind` on it. +async function cmdCatalogueRecognize(args) { + const { _, flags } = parseArgs(args); + const orgRoot = _[0] ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('catalogue-recognize: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + let doc; + try { + doc = await buildBindingProposals(orgRoot); + } catch (err) { + if (err instanceof CatalogueError) { console.error(`catalogue-recognize: ${err.message}`); return 2; } + throw err; + } + + const runId = typeof flags['run-id'] === 'string' ? flags['run-id'] : undefined; + const content = dump(doc); + const out = flags.out + ? resolve(flags.out) + : await resolveBatchPath({ processingDir: stageDir(orgRoot, 'processing'), filename: 'catalogue-bindings.proposed.yaml', scope: flags.scope, content, runId }); + await mkdir(dirname(out), { recursive: true }); + await writeFile(out, content, 'utf8'); + + console.log(`catalogue-recognize -> ${out}`); + if (!doc.pin) { console.log(' no catalogue pin declared (L0/pre-L1) — nothing to recognise against.'); return 0; } + console.log(` pin: ${doc.pin.source}@${doc.pin.version}`); + console.log(` ${doc.proposals.length} proposed binding(s) — nothing admitted; run \`catalogue-bind\` to accept one.`); + return 0; +} + +// Apply an accepted binding (L2's proposal, or L3's returned central-admission +// binding) — the one command that writes canon_id into a local element file. +// Idempotent against re-applying the same binding; refuses to silently replace a +// different one already there. +async function cmdCatalogueBind(args) { + const { _ } = parseArgs(args); + const [localId, canonId] = _; + if (!localId || !canonId) { console.error('catalogue-bind: missing '); return 1; } + const orgRoot = _[2] ? (await findOrgRoot(resolve(_[2])) || resolve(_[2])) : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('catalogue-bind: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + try { + const res = await applyBinding({ orgRoot, localId, canonId }); + if (res.outcome === 'unchanged') { + console.log(`catalogue-bind ${res.local_id} already bound to ${res.canon_id} — nothing to do.`); + } else { + console.log(`catalogue-bind ${res.local_id} -> canon_id: ${res.canon_id} (${res.path})`); + } + return 0; + } catch (err) { + if (err instanceof BindingError) { console.error(err.message); return 1; } + throw err; + } +} + +// L3 — promotion: emit a promotion proposal for a local element, consumable by the +// central repository's human admission gate. Writes a file only — no agent writes +// across a repository boundary (method/09-releases-and-propagation.md §6.5, §6.6). +async function cmdCataloguePromote(args) { + const { _, flags } = parseArgs(args); + const localId = _[0]; + if (!localId) { console.error('catalogue-promote: missing '); return 1; } + if (!flags.repository) { console.error('catalogue-promote: --repository / is required (this repository\'s own coordinate)'); return 1; } + const orgRoot = _[1] ? (await findOrgRoot(resolve(_[1])) || resolve(_[1])) : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('catalogue-promote: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + let doc; + try { + doc = await buildPromotionProposalDoc(orgRoot, localId, flags.repository); + } catch (err) { + if (err instanceof BindingError) { console.error(err.message); return 1; } + throw err; + } + + const runId = typeof flags['run-id'] === 'string' ? flags['run-id'] : undefined; + const content = dump(doc); + const out = flags.out + ? resolve(flags.out) + : await resolveBatchPath({ processingDir: stageDir(orgRoot, 'processing'), filename: 'promotions.proposed.yaml', scope: flags.scope, content, runId }); + await mkdir(dirname(out), { recursive: true }); + await writeFile(out, content, 'utf8'); + + console.log(`catalogue-promote ${localId} -> ${out}`); + if (doc.proposal.description === null) { + console.log(' WARNING: description could not be read (likely a multi-line block scalar) — fill it in by hand before handing this to the central repository.'); + } + console.log(' nothing admitted, no repository boundary crossed — carry this file to the central repository\'s own admission gate.'); + return 0; +} + +// Print the canonical §4 placement (mode + layer + folder) for a TYPE. +async function cmdResolvePlacement(args) { + const { _ } = parseArgs(args); + const type = _[0] ? String(_[0]).toUpperCase() : null; + if (!type) { console.error('resolve-placement: missing '); return 1; } + const p = resolvePlacement(type); + if (!p) { console.error(`resolve-placement: ${type} has no ELEMENT_PRIMITIVES §4 placement (not a catalogue element TYPE).`); return 1; } + console.log(`${type} mode: ${p.mode} layer: ${p.layer ?? '—'} folder: ${p.folder ?? '(inline — no catalogue folder)'}${p.promotable ? ' (promotable, §1 rule)' : ''}`); + return 0; +} + +// Validate `packages:` declarations and run each declared package's own +// validator entry point, if present. Package-agnostic (PACKAGES.md §4.2): +// this command never contains logic specific to any one package — it parses +// the declaration, checks shape/typo/compat (PKG-001/PKG-002), resolves each +// entry's declared entry point, and runs it if it exists. A repo declaring no +// packages reports that and exits 0 — every other command's output is +// unaffected by this one (§5 absence is silence). +async function cmdCheckPackages(args) { + const { _ } = parseArgs(args); + const orgRoot = _[0] + ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) + : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('check-packages: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + const text = await readManifestText(orgRoot); + const entries = parsePackagesDecl(text || ''); + if (entries.length === 0) { + console.log('check-packages no packages declared — nothing to check (PACKAGES.md §5, absence is silence).'); + return 0; + } + + const methodologyVersion = text ? readTopScalar(text, 'methodology_version') : null; + const findings = validatePackagesDecl(entries, { methodologyVersion }); + for (const f of findings) console.error(` ${f.rule} ${f.name ? `"${f.name}": ` : ''}${f.message}`); + + const validEntries = entries.filter((e) => e.kind !== 'malformed'); + const results = await runPackageValidators(orgRoot, validEntries); + for (const r of results) { + if (!r.ran) console.log(` ${r.name} validator entry point not present — skipped (absence is silence)`); + else console.log(` ${r.name} validator ${r.ok ? 'passed' : 'FAILED'}${r.output ? `\n ${r.output.split('\n').join('\n ')}` : ''}`); + } + + const ranCount = results.filter((r) => r.ran).length; + const failedCount = results.filter((r) => r.ran && !r.ok).length; + console.log(`\ncheck-packages ${entries.length} package(s) declared; ${findings.length} declaration finding(s); ${ranCount} validator(s) ran, ${failedCount} failed.`); + return (findings.length > 0 || failedCount > 0) ? 1 : 0; +} + +// List REQUIREMENT / CONSTRAINT files whose next_review_at is in the past +// (REQ-STALE-001; 15-requirement.md §2.3, §4). Read-only over canon/. +async function cmdCheckStale(args) { + const { _ } = parseArgs(args); + const orgRoot = _[0] + ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) + : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('check-stale: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + const { scanned, stale, malformed, unreadable, today } = await checkStale(orgRoot); + if (unreadable.length > 0) { + console.error(`check-stale ${unreadable.length} file(s) could not be read at all — excluded from the ${scanned} scanned above, not silently absorbed into "none stale":`); + for (const u of unreadable) console.error(` UNREADABLE ${u.file} (${u.reason})`); + } + if (stale.length === 0 && malformed.length === 0) { + console.log(`check-stale ${scanned} REQUIREMENT/CONSTRAINT file(s) scanned as of ${today} — none stale (REQ-STALE-001).`); + return unreadable.length > 0 ? 1 : 0; + } + if (stale.length > 0) { + console.error(`check-stale ${stale.length} of ${scanned} REQUIREMENT/CONSTRAINT element(s) stale as of ${today} (REQ-STALE-001):`); + for (const s of stale) console.error(` STALE ${s.id} next_review_at: ${s.next_review_at}`); + } + if (malformed.length > 0) { + console.error(`check-stale ${malformed.length} file(s) with an unparseable next_review_at (skipped — evaluation elided per 15-requirement.md §4):`); + for (const m of malformed) console.error(` UNPARSED ${m.id} next_review_at: ${JSON.stringify(m.next_review_at)}`); + } + return (stale.length > 0 || unreadable.length > 0) ? 1 : 0; +} + +// Report every human gate's phase + count in one table — ADR/WI status, canon +// element status, REQUIREMENT/CONSTRAINT review-overdue, ingest batches +// awaiting review. Read-only, always exit 0 — a report, not a gate. +async function cmdWorkflowStatus(args) { + const { _, flags } = parseArgs(args); + const orgRoot = _[0] + ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) + : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('workflow-status: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + const format = flags.format || 'md'; + if (format !== 'md' && format !== 'yaml') { + console.error(`workflow-status: --format must be md|yaml (got ${JSON.stringify(format)})`); + return 1; + } + const dataFree = flags['data-free'] === true || flags['data-free'] === 'true'; + + const model = await computeWorkflowStatus(orgRoot); + const out = format === 'yaml' ? dump(toReportObject(model, { dataFree })) : renderMarkdown(model, { dataFree }); + + if (flags.out) { + const { writeFile } = await import('node:fs/promises'); + const outPath = resolve(flags.out); + await writeFile(outPath, out, 'utf8'); + console.log(`workflow-status -> ${outPath}`); + } else { + process.stdout.write(out); + } + return 0; +} + +// Flag admitted elements sitting outside their §4 folder (read-only over canon/). +async function cmdCheckPlacement(args) { + const { _ } = parseArgs(args); + const orgRoot = _[0] + ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) + : (await findOrgRoot(process.cwd())); + if (!orgRoot) { console.error('check-placement: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } + + const { scanned, findings, unreadable } = await checkCanonPlacement(orgRoot); + if (unreadable.length > 0) { + console.error(`check-placement ${unreadable.length} file(s) could not be read at all — excluded from the ${scanned} scanned above, not silently absorbed into "all sit in their folder":`); + for (const u of unreadable) console.error(` UNREADABLE ${u.file} (${u.reason})`); + } + if (findings.length === 0) { + console.log(`check-placement ${scanned} catalogue element(s) scanned — all sit in their ELEMENT_PRIMITIVES §4 folder.`); + return unreadable.length > 0 ? 1 : 0; + } + console.error(`check-placement ${findings.length} of ${scanned} element(s) misplaced (ELEMENT_PRIMITIVES §4):`); + for (const f of findings) console.error(` FLAG ${f.id}\n - ${f.reason}`); + return 1; +} + +export async function main(argv) { + const [cmd, ...args] = argv; + + if (!cmd || cmd === '--help' || cmd === '-h') { console.log(usage()); return cmd ? 0 : 1; } + if (cmd === '--version' || cmd === '-v') { console.log(await version()); return 0; } + + switch (cmd) { + case 'scaffold-intake': return cmdScaffoldIntake(args); + case 'convert': return cmdConvert(args); + case 'privacy-scan': return cmdPrivacyScan(args); + case 'admit-source': return cmdAdmitSource(args); + case 'field-artefact': return cmdFieldArtefact(args); + case 'codex-artefact': return cmdCodexArtefact(args); + case 'emit-candidates': return cmdEmitCandidates(args); + case 'validate': return cmdValidate(args); + case 'review-queue': return cmdReviewQueue(args); + case 'suggest-profile': return cmdSuggestProfile(args); + case 'repo-check': return cmdRepoCheck(args); + case 'adopt-adl': return cmdAdoptAdl(args); + case 'catalogue-pin': return cmdCataloguePin(args); + case 'catalogue-recognize': return cmdCatalogueRecognize(args); + case 'catalogue-bind': return cmdCatalogueBind(args); + case 'catalogue-promote': return cmdCataloguePromote(args); + case 'check-placement': return cmdCheckPlacement(args); + case 'check-packages': return cmdCheckPackages(args); + case 'check-stale': return cmdCheckStale(args); + case 'workflow-status': return cmdWorkflowStatus(args); + case 'resolve-placement': return cmdResolvePlacement(args); + default: + console.error(`unknown command: ${cmd}\n\n${usage()}`); + return 1; + } +} diff --git a/packages/ingest-cli/ingest.mjs b/packages/ingest-cli/ingest.mjs index fcf08c0d..cfb0daf0 100644 --- a/packages/ingest-cli/ingest.mjs +++ b/packages/ingest-cli/ingest.mjs @@ -1,734 +1,26 @@ #!/usr/bin/env node -// @transitrix/ingest-cli — deterministic front-door pipeline for the Transitrix -// ingest skill. The skill's SKILL.md shells out to this CLI; it never reimplements -// the logic, so behaviour is identical under Claude and GitHub Copilot. -// -// THE ONE RULE: this CLI proposes. It writes field artefacts, candidates, and a -// review queue into _intake/ and field/, and it never writes *admitted* canon. The -// one path that writes under canon/ is the §13 holding area `canon/unresolved/`: -// emit-candidates parks objects it could not TYPE there as NON-admitted records (no -// admission record), which a human later resolves. Admitted canon stays human-gated. -// -// Exit codes: 0 = ok · 1 = usage / findings that need review · 2 = error -// -// Implemented: --version, scaffold-intake, convert, privacy-scan, admit-source (field -// + codex; field-artefact / codex-artefact remain as deprecated aliases), -// emit-candidates, validate, review-queue, adopt-adl, catalogue-pin, -// catalogue-recognize, catalogue-bind, catalogue-promote. - -import { readFile, writeFile, mkdir, access } from 'node:fs/promises'; -import { fileURLToPath } from 'node:url'; -import { dirname, join, resolve } from 'node:path'; - -import { scaffoldIntake, findOrgRoot, stageDir, readManifestText } from './src/intake.mjs'; -import { convert, ConvertError } from './src/convert.mjs'; -import { emitFieldArtefact } from './src/field-artefact.mjs'; -import { validateCandidate, loadCandidates } from './src/validate.mjs'; -import { readCoverageProfile, parseProfileDecl } from './src/coverage.mjs'; -import { buildReviewQueue, writeReviewQueue } from './src/review-queue.mjs'; -import { resolveBatchPath } from './src/batch-path.mjs'; -import { dump, readTopScalar } from './src/yaml.mjs'; -import { buildProfileSuggestion } from './src/suggest-profile.mjs'; -import { emitCandidates } from './src/emit-candidates.mjs'; -import { emitCodexArtefact } from './src/codex-artefact.mjs'; -import { resolvePlacement, checkCanonPlacement } from './src/placement.mjs'; -import { repoCheck } from './src/repo-check.mjs'; -import { parsePackagesDecl, validatePackagesDecl, runPackageValidators } from './src/packages.mjs'; -import { checkStale } from './src/check-stale.mjs'; -import { computeWorkflowStatus, renderMarkdown, toReportObject } from './src/workflow-status.mjs'; -import { runPrivacyScan, parsePrivacyGateConfig } from './src/privacy-scan.mjs'; -import { CatalogueError, applyCataloguePin } from './src/catalogue.mjs'; -import { buildBindingProposals, applyBinding, buildPromotionProposalDoc, BindingError } from './src/binding.mjs'; -import { adoptAdl } from './src/adl-join.mjs'; -import { randomUUID } from 'node:crypto'; - -const __dirname = dirname(fileURLToPath(import.meta.url)); - -// Tiny flag parser: returns { _: [positionals], flags: { name: value } }. -// `--k v` and `--k=v` are supported; a bare `--k` becomes boolean true. -function parseArgs(args) { - const out = { _: [], flags: {} }; - for (let i = 0; i < args.length; i++) { - const a = args[i]; - if (a.startsWith('--')) { - const eq = a.indexOf('='); - if (eq >= 0) out.flags[a.slice(2, eq)] = a.slice(eq + 1); - else if (i + 1 < args.length && !args[i + 1].startsWith('--')) out.flags[a.slice(2)] = args[++i]; - else out.flags[a.slice(2)] = true; - } else out._.push(a); - } - return out; -} - -const today = () => new Date().toISOString().slice(0, 10); - -async function version() { - const pkg = JSON.parse(await readFile(join(__dirname, 'package.json'), 'utf8')); - return pkg.version; -} - -function usage() { - return [ - 'transitrix-ingest [args]', - '', - 'Commands:', - ' scaffold-intake Create _intake/{inbox,processing,processed} (idempotent)', - ' convert Convert a document to Markdown in _intake/processing/', - ' privacy-scan Fail-closed PII/medical pre-admission gate (SKILL.md Step 2b)', - ' CLEAN|STRIPPED proceed to admit-source; REJECTED|ERROR halt the pipeline', - ' admit-source --zone field|codex Admit a converted source to the field or codex zone', - ' field: --type INTERVIEW|SURVEY|OBSERVATION|DRAFT --role R --date YYYY-MM-DD', - ' [--captured-by X] [--source-quality Q] [--slug SL] [--admitted-at A]', - ' codex: --type LAW|REGULATION|STANDARD|POLICY|INTERNAL_STANDARD|PRINCIPLE --effective-date YYYY-MM-DD', - ' (--effective-date optional for PRINCIPLE; PRINCIPLE instead requires --statement --rationale)', - ' STANDARD requires --jurisdiction and --issuing-authority (the issuing body)', - ' [--jurisdiction J] [--source-authority A] [--issuing-authority A] [--established-by A] [--slug SL] [--monitoring]', - ' [--force] admit even if an identical source (same source_hash) is already admitted', - ' field-artefact / codex-artefact Deprecated aliases of admit-source --zone field|codex', - ' emit-candidates --from [--candidates-dir ]', - ' Shape the agent extraction result into candidates', - ' validate Validate candidate *.json against the contract + coverage profile', - ' review-queue Assemble the human review queue (writes review-queue.yaml)', - ' [--out ] [--scope ]', - ' Non-destructive default: an unresolved review-queue.yaml already at the flat', - ' path is never overwritten — a concurrent batch lands under its own dated dir', - ' review-queue--YYYYMMDD-/review-queue.yaml (--scope defaults to "batch").', - ' suggest-profile Propose a coverage-profile delta for out-of-profile TYPEs (read-only; prints to stdout)', - ' adopt-adl [--repo /] L0 — join the decision-log network in one step: create', - ' operations/decisions/, wire scripts/check-adl.mjs + its CI workflow, and (with', - ' --repo) print the harvest.config.yaml line to add centrally. Idempotent.', - ' catalogue-pin / [org-root] L1 — write the catalogue: pin into transitrix.yaml.', - ' Refuses to touch the manifest if a catalogue: field is already declared.', - ' catalogue-recognize [org-root] L2 — propose bindings (unambiguous name/alias + TYPE match) against the pinned', - ' catalogue -> catalogue-bindings.proposed.yaml; nothing admitted, never overwrites an', - ' unresolved queue [--out ] [--scope ]', - ' catalogue-bind [org-root] Apply an accepted L2/L3 binding — writes canon_id into the', - ' local element file; idempotent if already bound to the same id, refuses to rebind', - ' catalogue-promote --repository / [org-root] L3 — emit a promotion proposal for the', - ' central repository\'s human admission gate -> promotions.proposed.yaml', - ' [--out ] [--scope ]', - ' repo-check [org-root] Data-free health report (version, profile, zone/TYPE counts, integrity flags); read-only', - ' check-placement [org-root] Flag admitted elements sitting outside their ELEMENT_PRIMITIVES §4 folder', - ' check-packages [org-root] Validate `packages:` declarations (PKG-001/PKG-002) and run each', - ' declared package\'s own validator entry point, if present (PACKAGES.md §4.2, §7)', - ' check-stale [org-root] List REQUIREMENT/CONSTRAINT elements whose next_review_at has passed (REQ-STALE-001)', - ' workflow-status [org-root] Report every human gate\'s phase + count (ADR/WI/canon/overdue/ingest batch); read-only', - ' [--out ] [--format md|yaml] [--data-free]', - ' resolve-placement Print a TYPE\'s §4 materialisation mode + layer + folder', - ' --version, -v Print the CLI version', - ' --help, -h Show this help', - ].join('\n'); -} - -async function cmdScaffoldIntake(args) { - const orgRoot = args[0]; - if (!orgRoot) { console.error('scaffold-intake: missing '); return 1; } - const { created, existing } = await scaffoldIntake(orgRoot); - for (const d of created) console.log(`created ${d}/`); - for (const d of existing) console.log(`exists ${d}/`); - console.log(`\n_intake/ ready under ${resolve(orgRoot)} (${created.length} created, ${existing.length} already present).`); - return 0; -} - -async function cmdConvert(args) { - const file = args[0]; - if (!file) { console.error('convert: missing '); return 1; } - const src = resolve(file); - try { await access(src); } catch { console.error(`convert: file not found: ${file}`); return 2; } - const orgRoot = await findOrgRoot(src); - if (!orgRoot) { - console.error(`convert: "${file}" is not inside an _intake/ workspace. Run \`scaffold-intake \` first and drop the file in _intake/inbox/.`); - return 2; - } - const processing = stageDir(orgRoot, 'processing'); - try { - const { out, mode } = await convert(src, processing); - console.log(`converted (${mode}) ${file} -> ${out}`); - return 0; - } catch (err) { - if (err instanceof ConvertError) { - console.error(err.message); - return err.exitCode; - } - throw err; - } -} - -async function cmdPrivacyScan(args) { - const { _ } = parseArgs(args); - const md = _[0]; - if (!md) { console.error('privacy-scan: missing '); return 1; } - const mdPath = resolve(md); - try { await access(mdPath); } catch { console.error(`privacy-scan: file not found: ${md}`); return 2; } - const orgRoot = await findOrgRoot(mdPath); - if (!orgRoot) { console.error(`privacy-scan: "${md}" is not inside an _intake/ workspace.`); return 2; } - - const config = parsePrivacyGateConfig(await readManifestText(orgRoot)); - const processingDir = stageDir(orgRoot, 'processing'); - const res = await runPrivacyScan({ mdPath, processingDir, config, runId: randomUUID() }); - - console.log(`privacy-scan ${md} -> ${res.outcome}`); - if (res.outcome === 'STRIPPED') { - console.log(` ${res.blockedFragments.filter((f) => !f.allowlist_cleared).length} fragment(s) redacted -> ${res.redactedFile}`); - console.log(' admit-source must be run on the redacted copy, not the original.'); - } - if (res.outcome === 'REJECTED') { - console.error(` ${res.blockedFragments.length} fragment(s) blocked — document not admissible; see privacy-report.yaml`); - } - if (res.outcome === 'ERROR') { - console.error(` ${res.errorDetail}`); - } - console.log(` privacy-report.yaml -> ${join(processingDir, 'privacy-report.yaml')}`); - - if (res.outcome === 'CLEAN' || res.outcome === 'STRIPPED') return 0; - if (res.outcome === 'REJECTED') return 1; - return 2; -} - -async function cmdFieldArtefact(args) { - const { _, flags } = parseArgs(args); - const md = _[0]; - if (!md) { console.error('field-artefact: missing (a converted file in _intake/processing/)'); return 1; } - const mdPath = resolve(md); - try { await access(mdPath); } catch { console.error(`field-artefact: file not found: ${md}`); return 2; } - if (!flags.type || !flags.role || !flags.date) { - console.error('field-artefact: --type, --role and --date are required'); - return 1; - } - const orgRoot = await findOrgRoot(mdPath); - if (!orgRoot) { console.error(`field-artefact: "${md}" is not inside an _intake/ workspace.`); return 2; } - - try { - const res = await emitFieldArtefact({ - orgRoot, mdPath, - type: String(flags.type).toUpperCase(), - role: flags.role, - date: flags.date, - setting: flags.setting, - capturedBy: flags['captured-by'] || '@transitrix/ingest-cli', - sourceQuality: flags['source-quality'], - slug: flags.slug, - admittedAt: flags['admitted-at'] || today(), - name: flags.name, - force: flags.force === true || flags.force === 'true', - }); - console.log(`field artefact ${res.id} -> ${res.outPath}`); - console.log(` proposed source_quality: ${res.proposedSQ} (confirm at admission)`); - if (res.rawMoved) console.log(` raw source retained: ${res.rawMoved}`); - if (res.sourceHash) console.log(` source_hash: ${res.sourceHash}`); - return 0; - } catch (err) { - if (err.duplicate) { - console.log(`field artefact skipped — ${err.message}`); - return 0; - } - console.error(`field-artefact: ${err.message}`); - return err.privacyGate ? 1 : 2; - } -} - -async function cmdCodexArtefact(args) { - const { _, flags } = parseArgs(args); - const md = _[0]; - if (!md) { console.error('codex-artefact: missing (a converted file in _intake/processing/)'); return 1; } - const mdPath = resolve(md); - try { await access(mdPath); } catch { console.error(`codex-artefact: file not found: ${md}`); return 2; } - if (!flags.type) { - console.error('codex-artefact: --type is required'); - return 1; - } - // --effective-date is required for every TYPE except PRINCIPLE (optional there, - // 14-codex.md §4.1); emitCodexArtefact enforces the per-TYPE required fields. - if (String(flags.type).toUpperCase() !== 'PRINCIPLE' && !flags['effective-date']) { - console.error('codex-artefact: --effective-date is required'); - return 1; - } - const orgRoot = await findOrgRoot(mdPath); - if (!orgRoot) { console.error(`codex-artefact: "${md}" is not inside an _intake/ workspace.`); return 2; } - - try { - const res = await emitCodexArtefact({ - orgRoot, mdPath, - type: String(flags.type).toUpperCase(), - jurisdiction: flags.jurisdiction, - effectiveDate: flags['effective-date'], - sourceAuthority: flags['source-authority'], - issuingAuthority: flags['issuing-authority'], - statement: flags.statement, - rationale: flags.rationale, - establishedBy: flags['established-by'], - admittedAt: flags['admitted-at'] || today(), - admittedBy: flags['admitted-by'] || '@transitrix/ingest-cli', - monitoring: flags.monitoring === true || flags.monitoring === 'true', - slug: flags.slug, - name: flags.name, - force: flags.force === true || flags.force === 'true', - }); - console.log(`codex artefact ${res.id} -> ${res.outPath}`); - console.log(` zone: codex (${res.scope}) — authoritative by construction; derive obligations as REQUIREMENT + ASSERTION candidates`); - if (res.snapshotFile) console.log(` snapshot retained: ${res.snapshotFile}`); - if (res.sourceHash) console.log(` source_hash: ${res.sourceHash}`); - return 0; - } catch (err) { - if (err.duplicate) { - console.log(`codex artefact skipped — ${err.message}`); - return 0; - } - console.error(`codex-artefact: ${err.message}`); - return 2; - } -} - -// Unified front door (admit-source --zone). `field-artefact` and `codex-artefact` -// remain as deprecated aliases for one release; both route through here. -async function cmdAdmitSource(args) { - const { flags } = parseArgs(args); - const zone = flags.zone || 'field'; - if (zone === 'field') return cmdFieldArtefact(args); - if (zone === 'codex') return cmdCodexArtefact(args); - console.error(`admit-source: --zone must be field|codex (got ${JSON.stringify(zone)})`); - return 1; -} - -async function resolveDir(dirArg, label) { - if (!dirArg) { console.error(`${label}: missing `); return { code: 1 }; } - const dir = resolve(dirArg); - try { await access(dir); } catch { console.error(`${label}: directory not found: ${dirArg}`); return { code: 2 }; } - const orgRoot = await findOrgRoot(dir); - if (!orgRoot) { console.error(`${label}: "${dirArg}" is not inside an _intake/ workspace.`); return { code: 2 }; } - return { dir, orgRoot, profile: await readCoverageProfile(orgRoot) }; -} - -async function cmdValidate(args) { - const { _ } = parseArgs(args); - const r = await resolveDir(_[0], 'validate'); - if (r.code) return r.code; - - if (r.profile && r.profile.warning) console.error(`WARNING: ${r.profile.warning}`); - - const loaded = await loadCandidates(r.dir); - if (loaded.length === 0) { console.log(`validate: no candidate *.json files in ${_[0]}`); return 0; } - - let needsReview = 0; - for (const { ref, candidate, parseError } of loaded) { - if (parseError || !candidate) { console.log(`FLAG ${ref}\n - does not parse: ${parseError || 'null'}`); needsReview++; continue; } - const v = validateCandidate(candidate, r.profile); - const issues = [...v.validation_flags]; - if (v.coverage_flag === 'out_of_profile') issues.push(`coverage: ${v.coverage_reason || 'out of profile'}`); - if (issues.length) { needsReview++; console.log(`FLAG ${ref}`); for (const i of issues) console.log(` - ${i}`); } - else console.log(`ok ${ref}`); - } - console.log(`\n${loaded.length} candidate(s); ${needsReview} need review.`); - return needsReview ? 1 : 0; -} - -async function cmdReviewQueue(args) { - const { _, flags } = parseArgs(args); - const r = await resolveDir(_[0], 'review-queue'); - if (r.code) return r.code; - - // Pick up relation suggestions emitted by `emit-candidates`, if present. - let suggestions = []; - const suggPath = join(stageDir(r.orgRoot, 'processing'), 'relation-suggestions.json'); - try { suggestions = JSON.parse(await readFile(suggPath, 'utf8')); } catch { /* none */ } - - // Pick up semantic links emitted by `emit-candidates`, if present. - let semanticLinks = []; - const semanticLinksPath = join(stageDir(r.orgRoot, 'processing'), 'semantic-links.json'); - try { semanticLinks = JSON.parse(await readFile(semanticLinksPath, 'utf8')); } catch { /* none */ } - - // Pick up role assignment proposals emitted by `emit-candidates`, if present. - let roleAssignmentProposals = []; - const roleAssignmentProposalsPath = join(stageDir(r.orgRoot, 'processing'), 'role-assignment-proposals.json'); - try { roleAssignmentProposals = JSON.parse(await readFile(roleAssignmentProposalsPath, 'utf8')); } catch { /* none */ } - - const runId = typeof flags['run-id'] === 'string' ? flags['run-id'] : undefined; - const queue = await buildReviewQueue({ orgRoot: r.orgRoot, candidatesDir: r.dir, profile: r.profile, suggestions, semanticLinks, roleAssignmentProposals, runId }); - const out = flags.out - ? resolve(flags.out) - : await resolveBatchPath({ processingDir: stageDir(r.orgRoot, 'processing'), filename: 'review-queue.yaml', scope: flags.scope, content: dump(queue), runId }); - await writeReviewQueue(queue, out); - const flagged = queue.candidates.filter(c => c.validation_flags.length || c.coverage_flag === 'out_of_profile').length; - if (queue.coverage_warning) console.error(`WARNING: ${queue.coverage_warning}`); - console.log(`review queue -> ${out}`); - console.log(` coverage_profile: ${queue.coverage_profile}`); - console.log(` ${queue.field_artefacts.length} field artefact(s), ${queue.candidates.length} candidate(s) (${flagged} flagged), ${queue.relation_suggestions.length} relation suggestion(s).`); - if (queue.semantic_links) console.log(` ${queue.semantic_links.length} semantic link(s) — review-only, no closed REL kind yet.`); - if (queue.role_assignment_proposals) console.log(` ${queue.role_assignment_proposals.length} role assignment proposal(s) — pending human decision.`); - if (queue.excluded_admitted.length) { - console.log(` ${queue.excluded_admitted.length} candidate(s) excluded — already admitted to canon (idempotent re-run).`); - } - console.log(' nothing admitted to canon — a human gates this queue.'); - return 0; -} - -async function cmdEmitCandidates(args) { - const { _, flags } = parseArgs(args); - const fa = _[0]; - if (!fa) { console.error('emit-candidates: missing '); return 1; } - if (!flags.from) { console.error('emit-candidates: --from is required (the agent extraction result)'); return 1; } - const fieldArtefactPath = resolve(fa); - try { await access(fieldArtefactPath); } catch { console.error(`emit-candidates: field artefact not found: ${fa}`); return 2; } - const orgRoot = await findOrgRoot(fieldArtefactPath); - if (!orgRoot) { console.error(`emit-candidates: "${fa}" is not inside an _intake/ workspace.`); return 2; } - - try { - const res = await emitCandidates({ - orgRoot, fieldArtefactPath, - resultPath: resolve(flags.from), - candidatesDir: flags['candidates-dir'] ? resolve(flags['candidates-dir']) : undefined, - ingestDate: flags['ingest-date'] || today(), - }); - console.log(`emit-candidates derived_from ${res.derivedFrom}`); - console.log(` ${res.candidates.length} candidate(s) -> ${res.dir}`); - console.log(` ${res.suggestions.length} relation suggestion(s) held back (relation-conservative) -> ${res.suggPath}`); - if (res.semanticLinks && res.semanticLinks.length) { - console.log(` ${res.semanticLinks.length} semantic link(s) (no closed REL kind yet) -> ${res.semanticLinksPath}`); - } - if (res.roleAssignmentProposals && res.roleAssignmentProposals.length) { - console.log(` ${res.roleAssignmentProposals.length} role assignment proposal(s) (person->role, decision pending) -> ${res.roleAssignmentProposalsPath}`); - } - if (res.unresolved && res.unresolved.written.length) { - console.log(` ${res.unresolved.written.length} untyped object(s) parked (non-admitted) -> ${res.unresolved.dir}`); - } - if (res.unresolved && res.unresolved.skipped) { - console.error(` WARNING: ${res.unresolved.skipped} unresolved item(s) dropped — missing required ingest_field / data (CONTRACT §13.2)`); - } - for (const w of res.warnings || []) console.error(` WARNING: ${w}`); - console.log(' candidates are pending — nothing admitted to canon.'); - return 0; - } catch (err) { - console.error(`emit-candidates: ${err.message}`); - return 2; - } -} - -// Discovery: scan candidates for out-of-profile TYPEs and PROPOSE a coverage delta. -// Read-only — prints a paste-ready suggestion to stdout, never widens the profile. -async function cmdSuggestProfile(args) { - const { _ } = parseArgs(args); - const r = await resolveDir(_[0], 'suggest-profile'); - if (r.code) return r.code; - - const loaded = await loadCandidates(r.dir); - if (loaded.length === 0) { console.error(`suggest-profile: no candidate *.json files in ${_[0]}`); return 0; } - - const decl = parseProfileDecl((await readManifestText(r.orgRoot)) || ''); - const baseName = decl.kind === 'short' ? decl.name : decl.kind === 'custom' ? decl.extends : 'full'; - const report = buildProfileSuggestion(loaded, r.profile, baseName); - process.stdout.write(dump(report)); - return 0; -} - -// Read-only "doctor": emit a short, data-free health report for an adopter repo. -async function cmdRepoCheck(args) { - const { _ } = parseArgs(args); - const orgRoot = _[0] ? resolve(_[0]) : (await findOrgRoot(process.cwd()) || process.cwd()); - const report = await repoCheck(orgRoot); - process.stdout.write(dump(report)); - return 0; -} - -// L0 — join the decision-log network in one step (method/07-decisions.md -// §9, guides/adl-adopter-setup.md Step 1, method/09-releases-and-propagation.md -// §6.6): the records folder, the vendored CI -// guard + its workflow, and (with --repo) the harvest.config.yaml line a human adds to -// the central repo. Idempotent — a file or folder already in place is left untouched. -async function cmdAdoptAdl(args) { - const { _, flags } = parseArgs(args); - const orgRoot = _[0]; - if (!orgRoot) { console.error('adopt-adl: missing '); return 1; } - - const { created, existing, centralLine } = await adoptAdl(orgRoot, { repoCoordinate: flags.repo }); - for (const d of created) console.log(`created ${d}`); - for (const d of existing) console.log(`exists ${d}`); - if (centralLine) { - console.log('\nAdd this to the central architecture repo\'s architecture/decision-log/harvest.config.yaml under `sources:`:\n'); - console.log(centralLine); +// Catch vocabulary failures during module initialization as well as command execution. +import { readFile } from 'node:fs/promises'; +import { VocabularyError } from './src/vocabulary.mjs'; + +const args = process.argv.slice(2); +try { + if (args[0] === '--version' || args[0] === '-v') { + const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8')); + console.log(pkg.version); } else { - console.log('\nPass --repo / to also print the harvest.config.yaml line for the central repo.'); - } - console.log(`\nL0 ready under ${resolve(orgRoot)} (${created.length} created, ${existing.length} already present). Next: /transitrix:adr to write the first record.`); - return 0; -} - -// L1 — write the catalogue: pin into transitrix.yaml (method/09-releases-and-propagation.md -// §6.4.2, §6.6). Refuses to touch the manifest if a catalogue: field is already declared — -// a re-pin is a deliberate edit, not something this command guesses at. -async function cmdCataloguePin(args) { - const { _ } = parseArgs(args); - const [source, version, pinPath] = _; - if (!source || !version || !pinPath) { console.error('catalogue-pin: missing / '); return 1; } - const orgRoot = _[3] ? (await findOrgRoot(resolve(_[3])) || resolve(_[3])) : (await findOrgRoot(process.cwd()) || process.cwd()); - - try { - const res = await applyCataloguePin(orgRoot, { source, version, path: pinPath }); - console.log(`catalogue-pin ${res.source}@${res.version} -> ${res.path}`); - console.log(` vendor the slice at ${res.pinPath} before running catalogue-recognize/repo-check (method/09-releases-and-propagation.md §6.4.3 — fails closed).`); - return 0; - } catch (err) { - if (err instanceof CatalogueError) { console.error(err.message); return 1; } - throw err; - } -} - -// L2 — recognition: propose bindings against the pinned catalogue for every unbound -// local element with an unambiguous, same-TYPE name/alias match. Writes the review -// artefact, never admits one (method/09-releases-and-propagation.md §6.5) — a human -// accepts a proposal by running `catalogue-bind` on it. -async function cmdCatalogueRecognize(args) { - const { _, flags } = parseArgs(args); - const orgRoot = _[0] ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('catalogue-recognize: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - let doc; - try { - doc = await buildBindingProposals(orgRoot); - } catch (err) { - if (err instanceof CatalogueError) { console.error(`catalogue-recognize: ${err.message}`); return 2; } - throw err; + const { main } = await import('./cli.mjs'); + process.exitCode = await main(args); } - - const runId = typeof flags['run-id'] === 'string' ? flags['run-id'] : undefined; - const content = dump(doc); - const out = flags.out - ? resolve(flags.out) - : await resolveBatchPath({ processingDir: stageDir(orgRoot, 'processing'), filename: 'catalogue-bindings.proposed.yaml', scope: flags.scope, content, runId }); - await mkdir(dirname(out), { recursive: true }); - await writeFile(out, content, 'utf8'); - - console.log(`catalogue-recognize -> ${out}`); - if (!doc.pin) { console.log(' no catalogue pin declared (L0/pre-L1) — nothing to recognise against.'); return 0; } - console.log(` pin: ${doc.pin.source}@${doc.pin.version}`); - console.log(` ${doc.proposals.length} proposed binding(s) — nothing admitted; run \`catalogue-bind\` to accept one.`); - return 0; -} - -// Apply an accepted binding (L2's proposal, or L3's returned central-admission -// binding) — the one command that writes canon_id into a local element file. -// Idempotent against re-applying the same binding; refuses to silently replace a -// different one already there. -async function cmdCatalogueBind(args) { - const { _ } = parseArgs(args); - const [localId, canonId] = _; - if (!localId || !canonId) { console.error('catalogue-bind: missing '); return 1; } - const orgRoot = _[2] ? (await findOrgRoot(resolve(_[2])) || resolve(_[2])) : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('catalogue-bind: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - try { - const res = await applyBinding({ orgRoot, localId, canonId }); - if (res.outcome === 'unchanged') { - console.log(`catalogue-bind ${res.local_id} already bound to ${res.canon_id} — nothing to do.`); - } else { - console.log(`catalogue-bind ${res.local_id} -> canon_id: ${res.canon_id} (${res.path})`); +} catch (error) { + if (error instanceof VocabularyError) { + if (args[0] === 'repo-check') { + console.error('repo-check: incomplete — all health checks unavailable; no checks ran.'); } - return 0; - } catch (err) { - if (err instanceof BindingError) { console.error(err.message); return 1; } - throw err; - } -} - -// L3 — promotion: emit a promotion proposal for a local element, consumable by the -// central repository's human admission gate. Writes a file only — no agent writes -// across a repository boundary (method/09-releases-and-propagation.md §6.5, §6.6). -async function cmdCataloguePromote(args) { - const { _, flags } = parseArgs(args); - const localId = _[0]; - if (!localId) { console.error('catalogue-promote: missing '); return 1; } - if (!flags.repository) { console.error('catalogue-promote: --repository / is required (this repository\'s own coordinate)'); return 1; } - const orgRoot = _[1] ? (await findOrgRoot(resolve(_[1])) || resolve(_[1])) : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('catalogue-promote: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - let doc; - try { - doc = await buildPromotionProposalDoc(orgRoot, localId, flags.repository); - } catch (err) { - if (err instanceof BindingError) { console.error(err.message); return 1; } - throw err; - } - - const runId = typeof flags['run-id'] === 'string' ? flags['run-id'] : undefined; - const content = dump(doc); - const out = flags.out - ? resolve(flags.out) - : await resolveBatchPath({ processingDir: stageDir(orgRoot, 'processing'), filename: 'promotions.proposed.yaml', scope: flags.scope, content, runId }); - await mkdir(dirname(out), { recursive: true }); - await writeFile(out, content, 'utf8'); - - console.log(`catalogue-promote ${localId} -> ${out}`); - if (doc.proposal.description === null) { - console.log(' WARNING: description could not be read (likely a multi-line block scalar) — fill it in by hand before handing this to the central repository.'); - } - console.log(' nothing admitted, no repository boundary crossed — carry this file to the central repository\'s own admission gate.'); - return 0; -} - -// Print the canonical §4 placement (mode + layer + folder) for a TYPE. -async function cmdResolvePlacement(args) { - const { _ } = parseArgs(args); - const type = _[0] ? String(_[0]).toUpperCase() : null; - if (!type) { console.error('resolve-placement: missing '); return 1; } - const p = resolvePlacement(type); - if (!p) { console.error(`resolve-placement: ${type} has no ELEMENT_PRIMITIVES §4 placement (not a catalogue element TYPE).`); return 1; } - console.log(`${type} mode: ${p.mode} layer: ${p.layer ?? '—'} folder: ${p.folder ?? '(inline — no catalogue folder)'}${p.promotable ? ' (promotable, §1 rule)' : ''}`); - return 0; -} - -// Validate `packages:` declarations and run each declared package's own -// validator entry point, if present. Package-agnostic (PACKAGES.md §4.2): -// this command never contains logic specific to any one package — it parses -// the declaration, checks shape/typo/compat (PKG-001/PKG-002), resolves each -// entry's declared entry point, and runs it if it exists. A repo declaring no -// packages reports that and exits 0 — every other command's output is -// unaffected by this one (§5 absence is silence). -async function cmdCheckPackages(args) { - const { _ } = parseArgs(args); - const orgRoot = _[0] - ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) - : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('check-packages: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - const text = await readManifestText(orgRoot); - const entries = parsePackagesDecl(text || ''); - if (entries.length === 0) { - console.log('check-packages no packages declared — nothing to check (PACKAGES.md §5, absence is silence).'); - return 0; - } - - const methodologyVersion = text ? readTopScalar(text, 'methodology_version') : null; - const findings = validatePackagesDecl(entries, { methodologyVersion }); - for (const f of findings) console.error(` ${f.rule} ${f.name ? `"${f.name}": ` : ''}${f.message}`); - - const validEntries = entries.filter((e) => e.kind !== 'malformed'); - const results = await runPackageValidators(orgRoot, validEntries); - for (const r of results) { - if (!r.ran) console.log(` ${r.name} validator entry point not present — skipped (absence is silence)`); - else console.log(` ${r.name} validator ${r.ok ? 'passed' : 'FAILED'}${r.output ? `\n ${r.output.split('\n').join('\n ')}` : ''}`); - } - - const ranCount = results.filter((r) => r.ran).length; - const failedCount = results.filter((r) => r.ran && !r.ok).length; - console.log(`\ncheck-packages ${entries.length} package(s) declared; ${findings.length} declaration finding(s); ${ranCount} validator(s) ran, ${failedCount} failed.`); - return (findings.length > 0 || failedCount > 0) ? 1 : 0; -} - -// List REQUIREMENT / CONSTRAINT files whose next_review_at is in the past -// (REQ-STALE-001; 15-requirement.md §2.3, §4). Read-only over canon/. -async function cmdCheckStale(args) { - const { _ } = parseArgs(args); - const orgRoot = _[0] - ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) - : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('check-stale: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - const { scanned, stale, malformed, unreadable, today } = await checkStale(orgRoot); - if (unreadable.length > 0) { - console.error(`check-stale ${unreadable.length} file(s) could not be read at all — excluded from the ${scanned} scanned above, not silently absorbed into "none stale":`); - for (const u of unreadable) console.error(` UNREADABLE ${u.file} (${u.reason})`); - } - if (stale.length === 0 && malformed.length === 0) { - console.log(`check-stale ${scanned} REQUIREMENT/CONSTRAINT file(s) scanned as of ${today} — none stale (REQ-STALE-001).`); - return unreadable.length > 0 ? 1 : 0; - } - if (stale.length > 0) { - console.error(`check-stale ${stale.length} of ${scanned} REQUIREMENT/CONSTRAINT element(s) stale as of ${today} (REQ-STALE-001):`); - for (const s of stale) console.error(` STALE ${s.id} next_review_at: ${s.next_review_at}`); - } - if (malformed.length > 0) { - console.error(`check-stale ${malformed.length} file(s) with an unparseable next_review_at (skipped — evaluation elided per 15-requirement.md §4):`); - for (const m of malformed) console.error(` UNPARSED ${m.id} next_review_at: ${JSON.stringify(m.next_review_at)}`); - } - return (stale.length > 0 || unreadable.length > 0) ? 1 : 0; -} - -// Report every human gate's phase + count in one table — ADR/WI status, canon -// element status, REQUIREMENT/CONSTRAINT review-overdue, ingest batches -// awaiting review. Read-only, always exit 0 — a report, not a gate. -async function cmdWorkflowStatus(args) { - const { _, flags } = parseArgs(args); - const orgRoot = _[0] - ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) - : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('workflow-status: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - const format = flags.format || 'md'; - if (format !== 'md' && format !== 'yaml') { - console.error(`workflow-status: --format must be md|yaml (got ${JSON.stringify(format)})`); - return 1; - } - const dataFree = flags['data-free'] === true || flags['data-free'] === 'true'; - - const model = await computeWorkflowStatus(orgRoot); - const out = format === 'yaml' ? dump(toReportObject(model, { dataFree })) : renderMarkdown(model, { dataFree }); - - if (flags.out) { - const { writeFile } = await import('node:fs/promises'); - const outPath = resolve(flags.out); - await writeFile(outPath, out, 'utf8'); - console.log(`workflow-status -> ${outPath}`); + console.error(error.message); + console.error('Set TRANSITRIX_NOTATIONS_DIR to a directory containing vocabulary.yaml and CURRENT_VERSION.yaml from the same compatible methodology release. Restore missing or damaged files from that release; do not bypass the version pin.'); } else { - process.stdout.write(out); + console.error(error?.stack || error); } - return 0; + process.exitCode = 2; } - -// Flag admitted elements sitting outside their §4 folder (read-only over canon/). -async function cmdCheckPlacement(args) { - const { _ } = parseArgs(args); - const orgRoot = _[0] - ? (await findOrgRoot(resolve(_[0])) || resolve(_[0])) - : (await findOrgRoot(process.cwd())); - if (!orgRoot) { console.error('check-placement: not inside a Transitrix workspace (no _intake/ found); pass .'); return 2; } - - const { scanned, findings, unreadable } = await checkCanonPlacement(orgRoot); - if (unreadable.length > 0) { - console.error(`check-placement ${unreadable.length} file(s) could not be read at all — excluded from the ${scanned} scanned above, not silently absorbed into "all sit in their folder":`); - for (const u of unreadable) console.error(` UNREADABLE ${u.file} (${u.reason})`); - } - if (findings.length === 0) { - console.log(`check-placement ${scanned} catalogue element(s) scanned — all sit in their ELEMENT_PRIMITIVES §4 folder.`); - return unreadable.length > 0 ? 1 : 0; - } - console.error(`check-placement ${findings.length} of ${scanned} element(s) misplaced (ELEMENT_PRIMITIVES §4):`); - for (const f of findings) console.error(` FLAG ${f.id}\n - ${f.reason}`); - return 1; -} - -async function main(argv) { - const [cmd, ...args] = argv; - - if (!cmd || cmd === '--help' || cmd === '-h') { console.log(usage()); return cmd ? 0 : 1; } - if (cmd === '--version' || cmd === '-v') { console.log(await version()); return 0; } - - switch (cmd) { - case 'scaffold-intake': return cmdScaffoldIntake(args); - case 'convert': return cmdConvert(args); - case 'privacy-scan': return cmdPrivacyScan(args); - case 'admit-source': return cmdAdmitSource(args); - case 'field-artefact': return cmdFieldArtefact(args); - case 'codex-artefact': return cmdCodexArtefact(args); - case 'emit-candidates': return cmdEmitCandidates(args); - case 'validate': return cmdValidate(args); - case 'review-queue': return cmdReviewQueue(args); - case 'suggest-profile': return cmdSuggestProfile(args); - case 'repo-check': return cmdRepoCheck(args); - case 'adopt-adl': return cmdAdoptAdl(args); - case 'catalogue-pin': return cmdCataloguePin(args); - case 'catalogue-recognize': return cmdCatalogueRecognize(args); - case 'catalogue-bind': return cmdCatalogueBind(args); - case 'catalogue-promote': return cmdCataloguePromote(args); - case 'check-placement': return cmdCheckPlacement(args); - case 'check-packages': return cmdCheckPackages(args); - case 'check-stale': return cmdCheckStale(args); - case 'workflow-status': return cmdWorkflowStatus(args); - case 'resolve-placement': return cmdResolvePlacement(args); - default: - console.error(`unknown command: ${cmd}\n\n${usage()}`); - return 1; - } -} - -main(process.argv.slice(2)) - .then((code) => process.exit(code)) - .catch((err) => { console.error(err && err.stack ? err.stack : err); process.exit(2); }); diff --git a/packages/ingest-cli/package.json b/packages/ingest-cli/package.json index 529be436..2a2198d0 100644 --- a/packages/ingest-cli/package.json +++ b/packages/ingest-cli/package.json @@ -12,6 +12,7 @@ }, "files": [ "ingest.mjs", + "cli.mjs", "intake-profile.mjs", "src/", "assets/" diff --git a/packages/ingest-cli/src/vocabulary.mjs b/packages/ingest-cli/src/vocabulary.mjs index 38f7172a..8ec127b9 100644 --- a/packages/ingest-cli/src/vocabulary.mjs +++ b/packages/ingest-cli/src/vocabulary.mjs @@ -30,8 +30,13 @@ import { dirname, join, resolve } from 'node:path'; const HERE = dirname(fileURLToPath(import.meta.url)); // packages/ingest-cli/src → repo root const REPO_ROOT = resolve(HERE, '..', '..', '..'); -export const VOCABULARY_PATH = join(REPO_ROOT, 'notations', 'vocabulary.yaml'); -export const VERSION_PIN_PATH = join(REPO_ROOT, 'notations', 'CURRENT_VERSION.yaml'); +// One location selects the artefact and its release pin together. Relative paths +// are resolved against the caller's working directory, never the adopter root. +const NOTATIONS_DIR = process.env.TRANSITRIX_NOTATIONS_DIR + ? resolve(process.env.TRANSITRIX_NOTATIONS_DIR) + : join(REPO_ROOT, 'notations'); +export const VOCABULARY_PATH = join(NOTATIONS_DIR, 'vocabulary.yaml'); +export const VERSION_PIN_PATH = join(NOTATIONS_DIR, 'CURRENT_VERSION.yaml'); class VocabularyError extends Error { constructor(message) { diff --git a/packages/ingest-cli/src/vocabulary.test.mjs b/packages/ingest-cli/src/vocabulary.test.mjs index ec586557..71bc8dcb 100644 --- a/packages/ingest-cli/src/vocabulary.test.mjs +++ b/packages/ingest-cli/src/vocabulary.test.mjs @@ -8,7 +8,9 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { writeFileSync, mkdtempSync } from 'node:fs'; +import { writeFileSync, mkdtempSync, mkdirSync, copyFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -20,6 +22,21 @@ import { VocabularyError, } from './vocabulary.mjs'; +const INGEST_CLI = fileURLToPath(new URL('../ingest.mjs', import.meta.url)); +const REAL_VOCABULARY = fileURLToPath(new URL('../../../notations/vocabulary.yaml', import.meta.url)); +const REAL_PIN = fileURLToPath(new URL('../../../notations/CURRENT_VERSION.yaml', import.meta.url)); + +function runCli(args, { cwd, notationsDir } = {}) { + const env = { ...process.env }; + if (notationsDir === undefined) delete env.TRANSITRIX_NOTATIONS_DIR; + else env.TRANSITRIX_NOTATIONS_DIR = notationsDir; + return spawnSync(process.execPath, [INGEST_CLI, ...args], { + cwd: cwd || process.cwd(), + env, + encoding: 'utf8', + }); +} + // A minimal but shape-valid document — small enough to hand-edit per test, // exercising every block loadVocabulary()'s validate() requires. function minimalDoc() { @@ -178,6 +195,60 @@ test('loadVocabulary — negative: a missing artefact file fails, never falls ba ); }); +// --- Executable bootstrap and consumer location contract ------------------- + +test('ingest executable: source default is module-relative, not cwd-relative', () => { + const cwd = mkdtempSync(join(tmpdir(), 'vocab-cli-cwd-')); + const result = runCli(['--help'], { cwd }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /^transitrix-ingest /); + assert.equal(result.stderr, ''); +}); + +test('ingest executable: a relative notations directory is resolved from the command cwd', () => { + const cwd = mkdtempSync(join(tmpdir(), 'vocab-cli-relative-')); + const notations = join(cwd, 'release-notations'); + mkdirSync(notations); + copyFileSync(REAL_VOCABULARY, join(notations, 'vocabulary.yaml')); + copyFileSync(REAL_PIN, join(notations, 'CURRENT_VERSION.yaml')); + const result = runCli(['--help'], { cwd, notationsDir: 'release-notations' }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /^transitrix-ingest /); +}); + +test('ingest executable: --version remains available without vocabulary files', () => { + const cwd = mkdtempSync(join(tmpdir(), 'vocab-cli-version-')); + const result = runCli(['--version'], { cwd, notationsDir: join(cwd, 'missing') }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), '0.0.1'); + assert.equal(result.stderr, ''); +}); + +test('ingest executable: missing vocabulary makes repo-check explicitly incomplete', () => { + const cwd = mkdtempSync(join(tmpdir(), 'vocab-cli-missing-')); + const result = runCli(['repo-check', cwd], { cwd, notationsDir: join(cwd, 'missing') }); + assert.equal(result.status, 2); + assert.equal(result.stdout, ''); + assert.match(result.stderr, /repo-check: incomplete — all health checks unavailable; no checks ran\./); + assert.match(result.stderr, /artefact not found/); + assert.match(result.stderr, /Set TRANSITRIX_NOTATIONS_DIR/); + assert.doesNotMatch(result.stderr, /\n\s+at /); +}); + +test('ingest executable: missing pin also fails closed with recovery guidance', () => { + const cwd = mkdtempSync(join(tmpdir(), 'vocab-cli-pin-')); + const notations = join(cwd, 'notations'); + mkdirSync(notations); + copyFileSync(REAL_VOCABULARY, join(notations, 'vocabulary.yaml')); + const result = runCli(['repo-check', cwd], { cwd, notationsDir: notations }); + assert.equal(result.status, 2); + assert.equal(result.stdout, ''); + assert.match(result.stderr, /repo-check: incomplete — all health checks unavailable; no checks ran\./); + assert.match(result.stderr, /version pin not readable/); + assert.match(result.stderr, /Set TRANSITRIX_NOTATIONS_DIR/); + assert.doesNotMatch(result.stderr, /\n\s+at /); +}); + // --- Derived views — what placement.mjs / validate.mjs actually consume ------ test('elementPlacement — positive: a live TYPE resolves its own mode/layer/folder', () => { From 8ca4eabf7666946ffb7a76eb579c31cb0ae3f327 Mon Sep 17 00:00:00 2001 From: Valerii Korobeinikov Date: Fri, 9 Oct 2026 13:53:46 +0400 Subject: [PATCH 11/26] fix: retain issued page identity and format dates in UTC (#645) Signed-off-by: transitrix Co-authored-by: transitrix --- .github/workflows/document-renderer-test.yml | 6 ++ packages/document-renderer/README.md | 21 ++++++- .../src/render-vivliostyle.mjs | 12 ++-- .../tests/test_paged_media_css.mjs | 42 +++++++++++++- .../tests/test_render_vivliostyle.mjs | 57 +++++++++++++------ 5 files changed, 114 insertions(+), 24 deletions(-) diff --git a/.github/workflows/document-renderer-test.yml b/.github/workflows/document-renderer-test.yml index 392649cb..79e6cd0a 100644 --- a/.github/workflows/document-renderer-test.yml +++ b/.github/workflows/document-renderer-test.yml @@ -67,3 +67,9 @@ jobs: - name: Run full-run end-to-end test run: node packages/document-renderer/tests/test_full_run.mjs + + - name: Run paged-media CSS tests + run: node packages/document-renderer/tests/test_paged_media_css.mjs + + - name: Run snapshot caption tests + run: node packages/document-renderer/tests/test_render_vivliostyle.mjs diff --git a/packages/document-renderer/README.md b/packages/document-renderer/README.md index d1b95a80..a1a9c66a 100644 --- a/packages/document-renderer/README.md +++ b/packages/document-renderer/README.md @@ -497,7 +497,8 @@ The package has two PDF rendering paths: - Running footers (issuer, date, identity, page number) - Landscape pages for wide diagrams - Page breaks and typography rules -- First-page suppression (no footer on title page) +- Every-page identity for issued documents, including the first portrait or landscape page +- First-page suppression retained for non-issued content (no `issued_at`) **Usage:** @@ -514,6 +515,24 @@ const html = wrapHtmlForPrintRendering('

Title

Content...

', { // Pass html to Vivliostyle or another CSS Paged Media renderer ``` +Supplying `issued_at` selects the issued-document footer behavior; a one-page +issued document receives the same issuer, issue date, identity, optional commit +and page counters as subsequent pages. Callers supply the existing identity +fields; this helper does not create or validate an issue identity. + +Issue dates (`issued_at`) and snapshot caption dates (`generated_at`) use the +`en-US` locale and **UTC**, independent of the host timezone. Supply ISO 8601 +timestamps with `Z` or an explicit numeric offset (or a date-only `YYYY-MM-DD`); +timezone-less date-time strings are not stable inputs across hosts. +Snapshot captions use only captured-at `generated_at`, never valid-at +`renderDate`, the issue date, or the wall clock. `renderDate` remains the separate +pass-1 input that selects model validity. Missing snapshot dates leave captions +unchanged; invalid dates produce `Unknown date`. Callers remain responsible for +snapshot binding before issuing a document. + +These helpers prepare HTML/CSS; their tests do not establish footer visibility, +landscape geometry, diagram embedding or reproducibility in a final PDF. + **Specification:** [`PDF_RENDERING_ENGINE.md`](./PDF_RENDERING_ENGINE.md) **Engine reference:** Vivliostyle (option 2), caller-supplied supported (option 3) **Feature matrix:** Named pages, landscape pages, break rules, running elements, counters diff --git a/packages/document-renderer/src/render-vivliostyle.mjs b/packages/document-renderer/src/render-vivliostyle.mjs index faa0fc56..29282036 100644 --- a/packages/document-renderer/src/render-vivliostyle.mjs +++ b/packages/document-renderer/src/render-vivliostyle.mjs @@ -31,7 +31,8 @@ function escapeHtml(text) { * * @param {object} metadata - Document metadata * @param {string} metadata.issuer - Who created the document - * @param {string} metadata.issued_at - ISO 8601 timestamp + * @param {string} metadata.issued_at - Issue timestamp with explicit offset; formatted in UTC. + * When present, retains the footer on every page, including the first. * @param {string} metadata.document_identity - Recipe ID or document identifier * @param {string} [metadata.repository_commit] - Git commit hash * @param {array} [metadata.views] - View specifications with width/height @@ -52,6 +53,7 @@ export function generatePagedMediaCss(metadata = {}) { year: 'numeric', month: 'short', day: 'numeric', + timeZone: 'UTC', }); } catch { // ignore invalid date @@ -98,11 +100,11 @@ export function generatePagedMediaCss(metadata = {}) { } } -@page :first { +${metadata.issued_at ? '' : `@page :first { @bottom-center { content: ""; } -} +}`} @page :left { margin-right: 20mm; @@ -238,7 +240,8 @@ ${wideViewsCss} /** * Format figure captions to include snapshot build dates. * Finds all
elements with data-snapshot-id attributes and appends - * the snapshot's generated_at timestamp to the caption. + * the snapshot's captured-at generated_at timestamp to the caption, formatted in UTC. + * Supply timestamps with explicit offsets; renderDate (valid-at) is not a fallback. * * @param {string} html - HTML content with figure elements * @param {object} snapshots - Map of snapshot IDs to snapshot objects with generated_at @@ -265,6 +268,7 @@ export function formatFigureCaptions(html, snapshots = {}) { year: 'numeric', month: 'short', day: 'numeric', + timeZone: 'UTC', }); } } catch { diff --git a/packages/document-renderer/tests/test_paged_media_css.mjs b/packages/document-renderer/tests/test_paged_media_css.mjs index 8854075e..0c0b572d 100644 --- a/packages/document-renderer/tests/test_paged_media_css.mjs +++ b/packages/document-renderer/tests/test_paged_media_css.mjs @@ -61,11 +61,47 @@ function check(condition, message) { check(!hasUnescapedAmpersand, 'No unescaped ampersands in content string'); } -// Test 5: First page omits footer +// Test 5: Issued identity survives on every page, including a one-page document. { + const metadata = { + issuer: 'Test Corp', + issued_at: '2026-09-02T00:30:00Z', + document_identity: 'SPEC-v2.0', + repository_commit: 'a1b2c3d4e5f6', + }; + for (const content of ['

One page

', '
Wide view
']) { + const html = wrapHtmlForPrintRendering(content, metadata); + const css = html.match(/'+''.join(zones)+''.join(out)+overlay+'' + try:ET.fromstring(svg) + except ET.ParseError as error:raise ValueError(f'Model text cannot be represented as SVG XML: {error}') from error + return svg + +LEGEND_LABELS={ + 'layers':'Bands: management-cycle stages', + 'context':'Muted boxes: parent/domain context', + 'labels':'System labels: direct mappings only', + 'outline':'Outline: direct mapping to ', + 'coverage':'Coverage: ', + 'shared':'Overlap: explicit shared mappings; area is not a percentage', + 'functional_overlap':'Red contour: intersection of 2+ system coverage polygons', + 'maturity':'Maturity:' +} + +MATURITY_LEGEND=[{'level':i,'name':name,'description':description} for i,(name,description) in enumerate(zip(LEVELS,[ + 'Capability absent','Ad hoc, unpredictable','Planned and tracked','Standardized practices','Measured and controlled','Continuous improvement']))] + + +def add_maturity_legend(group,width,y): + import math,xml.etree.ElementTree as ET + ns='{'+SVGNS+'}';tilewidth=min(216,width-48);columns=max(1,int((width-48+12)//(tilewidth+12))) + header=ET.SubElement(group,ns+'text',{'x':'24.0','y':f'{y+10:.1f}','font-size':'12','fill':'#475569','text-anchor':'start'}) + header.text=LEGEND_LABELS['maturity'] + for i,item in enumerate(MATURITY_LEGEND): + x=24+(i%columns)*(tilewidth+12);top=y+22+(i//columns)*52 + tile=ET.SubElement(group,ns+'g',{'class':'maturity-legend-item','data-maturity-level':str(item['level'])}) + ET.SubElement(tile,ns+'rect',{'class':f'maturity-legend-swatch caprect m{item["level"]}','x':f'{x:.1f}','y':f'{top:.1f}','width':'36','height':'26','rx':'6','fill':'#c9d5f2','stroke':'#c9d5f2','stroke-width':'3'}) + for text,tx,ty,size,fill,anchor in [(str(item['level']),x+18,top+17,'11','#0f172a','middle'),(item['name'],x+48,top+9,'11','#334155','start'),(item['description'],x+48,top+25,'10','#64748b','start')]: + ET.SubElement(tile,ns+'text',{'x':f'{tx:.1f}','y':f'{ty:.1f}','font-size':size,'fill':fill,'text-anchor':anchor}).text=text + return y+22+math.ceil(len(MATURITY_LEGEND)/columns)*52+6 + + +def update_legend(root,state,selection): + import xml.etree.ElementTree as ET + import textwrap + ns='{'+SVGNS+'}';group=root.find(ns+"g[@class='legend']") + if group is None:return + group.clear();group.set('class','legend') + bottom=float(root.get('data-content-bottom'));width=float(root.get('width')) + maturity_key=False + items=[];visible=[g for g in root.iter(ns+'g') if g.get('data-id') is not None and int(g.get('data-depth','1'))<=selection['depth']] + apps={str(a['id']):a for a in state['applications']} + if selection['legend'] and visible: + if selection['sort_layers'] and root.findall(ns+"rect[@class='layer-zone']"):items.append((LEGEND_LABELS['layers'],None)) + if selection['tag_filter'] and any(g.get('data-tag-match')=='context' for g in visible):items.append((LEGEND_LABELS['context'],None)) + if selection['system_labels'] and any(g.find(ns+"text[@class='system-label']") is not None for g in visible):items.append((LEGEND_LABELS['labels'],None)) + if selection['system_id'] and any(g.get('data-support')=='supported' for g in visible):items.append((LEGEND_LABELS['outline']+apps[selection['system_id']]['name'],'#00a6a6')) + active=[g for g in root.findall(ns+"g[@class='coverage-overlay']") if g.get('data-coverage-visible')=='yes'] + colors=json.loads(root.find(ns+'metadata').text)['coverage_colors'] + for overlay in active: + aid=overlay.get('data-coverage-system');items.append((LEGEND_LABELS['coverage']+apps[aid]['name'],colors[aid])) + if active:items.append((LEGEND_LABELS['shared'],None)) + if root.find(ns+"g[@class='functional-overlap']") is not None:items.append((LEGEND_LABELS['functional_overlap'],'#dc2626')) + if selection['maturity'] and any(g.find(ns+"text[@class='maturity-label']") is not None for g in visible):maturity_key=True + x=24.;baseline=bottom+18;rowheight=14. + for label,color in items: + label=' '.join(label.split()) + prefix=16 if color else 0 + lines=textwrap.wrap(label,width=max(4,int((width-48-prefix)/(11*.62))),break_long_words=True,break_on_hyphens=False) + itemwidth=max(len(line) for line in lines)*11*.62+prefix + if x>24 and x+itemwidth>width-24:x=24.;baseline+=rowheight+6;rowheight=14. + if color:ET.SubElement(group,ns+'rect',{'x':f'{x:.1f}','y':f'{baseline-9:.1f}','width':'10','height':'10','rx':'2','fill':color}) + node=ET.SubElement(group,ns+'text',{'x':f'{x+prefix:.1f}','y':f'{baseline:.1f}','font-size':'11','fill':'#475569','text-anchor':'start'}) + for i,line in enumerate(lines):ET.SubElement(node,ns+'tspan',{'x':f'{x+prefix:.1f}','dy':'14' if i else '0'}).text=line + rowheight=max(rowheight,14*len(lines));x+=itemwidth+18 + height=baseline+rowheight+6 if items else bottom+20 + if maturity_key:height=add_maturity_legend(group,width,baseline+rowheight+14 if items else bottom+12) + group.set('style','display:inline' if items or maturity_key else 'display:none') + root.set('height',f'{height:g}');root.set('viewBox',f'0 0 {width:g} {height:g}') + + +def coverage_shape_points(hull,shape='angled',rounded=False): + """Choose an enclosing rectangle or the original hull; round convex corners inward.""" + import math + if shape not in ('angled','rectangular'):raise ValueError('Unknown coverage shape') + points=list(hull) + if shape=='rectangular': + xmin=min(x for x,y in points);xmax=max(x for x,y in points);ymin=min(y for x,y in points);ymax=max(y for x,y in points) + points=[(xmin,ymin),(xmax,ymin),(xmax,ymax),(xmin,ymax)] + if not rounded:return points + result=[] + for i,corner in enumerate(points): + previous=points[i-1];following=points[(i+1)%len(points)] + before=math.hypot(previous[0]-corner[0],previous[1]-corner[1]);after=math.hypot(following[0]-corner[0],following[1]-corner[1]) + radius=min(10,before/2,after/2) + start=tuple(corner[k]+(previous[k]-corner[k])*radius/before for k in (0,1)) + end=tuple(corner[k]+(following[k]-corner[k])*radius/after for k in (0,1)) + for step in range(9): + t=step/8 + result.append(tuple(math.floor(((1-t)**2*start[k]+2*(1-t)*t*corner[k]+t*t*end[k])*10000+.5)/10000 for k in (0,1))) + return result + + +def apply_coverage_shape(root,shape='angled',rounded=False): + ns='{'+SVGNS+'}' + if shape not in ('angled','rectangular'):raise ValueError('Unknown coverage shape') + for group in root.findall(ns+"g[@class='coverage-overlay']"): + polygon=group.find(ns+"polygon[@class='coverage-polygon']") + original=polygon.get('data-coverage-hull',polygon.get('points')) + hull=[tuple(map(float,p.split(','))) for p in original.split()] + points=' '.join(f'{x:.4f},{y:.4f}' for x,y in coverage_shape_points(hull,shape,rounded)) + polygon.set('points',points) + group.find(ns+'defs/'+ns+'mask/'+ns+'polygon').set('points',points) + root.set('data-coverage-shape',shape);root.set('data-coverage-rounded','yes' if rounded else 'no') + + +def polygon_intersection(subject,clip): + """Intersect convex coverage hulls; touching edges have no area.""" + def cross(a,b,p):return (b[0]-a[0])*(p[1]-a[1])-(b[1]-a[1])*(p[0]-a[0]) + output=list(subject) + for a,b in zip(clip,clip[1:]+clip[:1]): + source=output;output=[] + if not source:break + previous=source[-1];dp=cross(a,b,previous) + for current in source: + dc=cross(a,b,current) + if (dc>=-1e-8)!=(dp>=-1e-8): + t=dp/(dp-dc);output.append((previous[0]+t*(current[0]-previous[0]),previous[1]+t*(current[1]-previous[1]))) + if dc>=-1e-8:output.append(current) + previous=current;dp=dc + area=abs(sum(a[0]*b[1]-b[0]*a[1] for a,b in zip(output,output[1:]+output[:1])))/2 + return output if area>1e-6 else [] + + +def update_functional_overlap(root,state,enabled): + """Outline the union of pairwise outer-hull intersections, independent of box cut-outs.""" + import xml.etree.ElementTree as ET + ns='{'+SVGNS+'}' + for old in root.findall(ns+"g[@class='functional-overlap']"):root.remove(old) + if not enabled:return [] + active=root.findall(ns+"g[@class='coverage-overlay'][@data-coverage-visible='yes']") + regions=[] + for i,left in enumerate(active): + for right in active[i+1:]: + polygons=[g.find(ns+"polygon[@class='coverage-polygon']") for g in (left,right)] + points=[[tuple(map(float,p.split(','))) for p in poly.get('points').split()] for poly in polygons] + intersection=polygon_intersection(*points) + if intersection:regions.append((sorted([left.get('data-coverage-system'),right.get('data-coverage-system')]),intersection)) + if not regions:return [] + group=ET.SubElement(root,ns+'g',{'class':'functional-overlap','pointer-events':'none'}) + defs=ET.SubElement(group,ns+'defs') + attrs={'id':'functional-overlap-edge','filterUnits':'userSpaceOnUse','x':'0','y':'0','width':root.get('width'),'height':root.get('data-content-bottom'),'color-interpolation-filters':'sRGB'} + edge=ET.SubElement(defs,ns+'filter',attrs) + for tag,attrs in [('feMorphology',{'in':'SourceAlpha','operator':'dilate','radius':'1.5','result':'outer'}),('feMorphology',{'in':'SourceAlpha','operator':'erode','radius':'1.5','result':'inner'}),('feComposite',{'in':'outer','in2':'inner','operator':'out','result':'edge'}),('feFlood',{'flood-color':'#dc2626','result':'red'}),('feComposite',{'in':'red','in2':'edge','operator':'in'})]:ET.SubElement(edge,ns+tag,attrs) + boundary=ET.SubElement(group,ns+'g',{'class':'functional-overlap-outline','filter':'url(#functional-overlap-edge)'}) + pairs=[] + for ids,points in regions: + pair=ET.SubElement(boundary,ns+'g',{'class':'functional-overlap-region','data-overlap-systems':json.dumps(ids,ensure_ascii=False,separators=(',',':'))}) + ET.SubElement(pair,ns+'polygon',{'points':' '.join(f'{x:.4f},{y:.4f}' for x,y in points),'fill':'white'}) + pairs.append(ids) + return pairs + + +def apply_view(svg,state,system='',depth=3,labels=False,show_maturity=False,legend=True,coverage=False,coverage_systems=None,functional_overlap=False,coverage_shape='angled',round_coverage=False): + import xml.etree.ElementTree as ET + ET.register_namespace('',SVGNS);root=ET.fromstring(svg) + apply_coverage_shape(root,coverage_shape,round_coverage) + apps={str(a['id']):a for a in state['applications']} + if system and system not in apps:raise ValueError('Selected system is not in selected state') + if depth not in (1,2,3):raise ValueError('Depth must be 1, 2 or 3') + root.attrib.update({'data-max-depth':str(depth),'data-system-labels':'on' if labels else 'off','data-maturity':'on' if show_maturity else 'off','data-legend':'on' if legend else 'off','data-system-selected':'yes' if system else 'no'}) + pilot=json.loads(root.find('{'+SVGNS+'}metadata').text).get('coverage_system_id') + if coverage_systems is not None: + if not isinstance(coverage_systems,(list,tuple)) or any(not isinstance(a,str) for a in coverage_systems):raise ValueError('coverage_systems must be a list of system IDs') + if len(set(coverage_systems))!=len(coverage_systems):raise ValueError('Duplicate selected coverage system') + if set(coverage_systems)-apps.keys():raise ValueError('Selected coverage system is not in selected state') + selected=sorted(coverage_systems if coverage_systems is not None else ([pilot] if pilot in apps else [] if pilot else apps)) if coverage else [] + for group in root.findall("{*}g[@class='coverage-overlay']"): + visible=group.get('data-coverage-system') in selected and int(group.get('data-coverage-depth'))==depth + group.set('data-coverage-visible','yes' if visible else 'no') + group.set('style','display:inline' if visible else 'display:none') + for g in root.iter('{'+SVGNS+'}g'): + if 'data-id' in g.attrib:g.set('data-support','supported' if system and system in json.loads(g.get('data-applications','[]')) else 'not-specified') + overlaps_enabled=bool(functional_overlap and coverage and len(selected)>=2) + overlaps=update_functional_overlap(root,state,overlaps_enabled) + selection={'coverage_shape':coverage_shape,'round_coverage':bool(round_coverage),'functional_overlap':overlaps_enabled,'functional_overlap_system_pairs':overlaps,'view_date':json.loads(root.find('{'+SVGNS+'}metadata').text).get('view_date'),'system_id':system or None,'depth':depth,'system_labels':labels,'maturity':show_maturity,'legend':legend,'sort_layers':json.loads(root.find('{'+SVGNS+'}metadata').text)['layout_mode']=='layers','show_backlog':json.loads(root.find('{'+SVGNS+'}metadata').text)['show_backlog'],'tag_filter':json.loads(root.find('{'+SVGNS+'}metadata').text)['tag_filter'],'coverage':bool(coverage),'coverage_system_id':selected[0] if len(selected)==1 else None,'coverage_system_ids':selected} + meta=root.find('{'+SVGNS+'}metadata');md=json.loads(meta.text);md['view']=selection;meta.text=json.dumps(md,ensure_ascii=False) + update_legend(root,state,selection) + textnode=next(e for e in root.iter('{'+SVGNS+'}text') if e.get('class')=='view-selection') + caption=f'Layout: {"Layers" if selection["sort_layers"] else "Classic"} · Backlog: {"on" if selection["show_backlog"] else "off"} · Tag: {selection["tag_filter"] or "All"} · System: {apps[system]["name"] if system else "All"} · Depth: {depth} · System labels: {"on" if labels else "off"} · Maturity: {"on" if show_maturity else "off"} · Legend: {"on" if legend else "off"} · Coverage: {", ".join(apps[a]["name"] for a in selected) if coverage and selected else "none" if coverage else "off"}' + import textwrap + for child in list(textnode):textnode.remove(child) + for i,line in enumerate(textwrap.wrap(caption,width=max(20,int((float(root.get('width'))-48)/7)),break_long_words=True)): + child=ET.SubElement(textnode,'{'+SVGNS+'}tspan',{'x':textnode.get('x'),'dy':'0' if i==0 else '14'});child.text=line + return ET.tostring(root,encoding='unicode') + +def prune_export(svg): + """Keep the selected visible content and reproducibility metadata, not hidden model detail.""" + import xml.etree.ElementTree as ET + ET.register_namespace('',SVGNS);root=ET.fromstring(svg) + depth=int(root.get('data-max-depth','3')) + hidden=set() + if root.get('data-system-labels')=='off':hidden.add('system-label') + if root.get('data-maturity')=='off':hidden.add('maturity-label') + if root.get('data-legend')=='off':hidden.add('legend') + def walk(parent): + for element in list(parent): + classes=set(element.get('class','').split()) + if element.get('data-coverage-visible')=='no' or (element.get('data-depth') and int(element.get('data-depth'))>depth) or classes & hidden or (element.tag=='{'+SVGNS+'}desc' and parent.get('data-id') is not None): + parent.remove(element);continue + element.attrib.pop('data-applications',None) + walk(element) + walk(root) + return ET.tostring(root,encoding='unicode') + +HTML_JS=r''' +const payload=JSON.parse(document.getElementById('model-data').textContent); +const stateInput=document.getElementById('state'),systemInput=document.getElementById('system'); +const coverageChoices=document.getElementById('coverage-systems'); +const allCoverage=new Map(payload.coverage_applications.map(a=>[String(a.id),a.name])); +Array.from(allCoverage).sort((a,b)=>a[0].localeCompare(b[0],'en')).forEach(([id,name])=>{const label=document.createElement('label'),input=document.createElement('input'),swatch=document.createElement('span'),title=document.createElement('span');input.type='checkbox';input.value=id;input.checked=payload.coverage_default_ids.includes(id);input.addEventListener('change',updateView);swatch.className='coverage-swatch';swatch.style.background=payload.coverage_colors[id];title.className='coverage-system-label';title.textContent=name;label.append(input,swatch,title);coverageChoices.append(label)}); +function selectedCoverage(){return Array.from(coverageChoices.querySelectorAll('input:checked:not(:disabled)')).map(i=>i.value).sort()} +const dateInput=document.getElementById('view-date'),dateStatus=document.getElementById('date-status'); +const timeSlider=document.getElementById('time-slider'),timeValue=document.getElementById('time-value'); +const dayNumber=value=>Math.floor(Date.parse(value+'T00:00:00Z')/86400000); +const dayDate=value=>new Date(Number(value)*86400000).toISOString().slice(0,10); +let timelineMin=payload.frames.length?dayNumber(payload.frames[0].frame_from):0; +const lastFrame=payload.frames[payload.frames.length-1]; +let timelineMax=lastFrame?(lastFrame.frame_to?dayNumber(lastFrame.frame_to)-1:Math.min(dayNumber('9999-12-31'),Math.max(dayNumber(lastFrame.frame_from),dayNumber(payload.initial_date||localToday()))+365)):0; +let pendingScrub=null,renderedState=null,renderedKey=''; +function syncSlider(){const when=dateInput.value;timeSlider.disabled=!payload.frames.length;if(!payload.frames.length){timeValue.textContent='No dated timeline';return}if(when){const day=dayNumber(when);timelineMin=Math.min(timelineMin,day);timelineMax=Math.max(timelineMax,day);timeSlider.min=String(timelineMin);timeSlider.max=String(timelineMax);timeSlider.value=String(day);timeSlider.setAttribute('aria-valuetext',when);timeValue.textContent=when}else{timeValue.textContent='Snapshot mode';timeSlider.setAttribute('aria-valuetext','Snapshot mode; move to select a date')}document.getElementById('time-first').textContent=dayDate(timelineMin);document.getElementById('time-last').textContent=dayDate(timelineMax)} +function scrubTime(){dateInput.value=dayDate(timeSlider.value);timeValue.textContent=dateInput.value;timeSlider.setAttribute('aria-valuetext',dateInput.value);if(pendingScrub===null)pendingScrub=requestAnimationFrame(()=>{pendingScrub=null;loadDate()})} +timeSlider.addEventListener('input',scrubTime);timeSlider.addEventListener('change',()=>{if(pendingScrub!==null){cancelAnimationFrame(pendingScrub);pendingScrub=null}dateInput.value=dayDate(timeSlider.value);loadDate()}); +payload.frames.forEach(frame=>{const tick=document.createElement('option');tick.value=String(dayNumber(frame.frame_from));tick.label=frame.frame_from;document.getElementById('time-events').append(tick)}); +function currentState(){const when=dateInput.value;return when?payload.frames.find(s=>s.frame_from<=when&&(!s.frame_to||whens.id===stateInput.value)} +function localToday(){const d=new Date();return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`} +function dateCaption(state){return `Date: ${dateInput.value} · Snapshot basis: ${state.snapshot_as_of||'not specified'} · ${state.kind==='target'?'Planned scenario; not an observed outcome':'Recorded snapshot basis; no implied daily observation'}`} +function wrapText(node,caption,svg){node.replaceChildren();const limit=Math.max(4,Math.floor((Number(svg.getAttribute('width'))-48)/(Number(node.getAttribute('font-size'))*.62)));const words=caption.split(/\s+/);let lines=[''];words.forEach(word=>{while(word.length>limit){if(lines[lines.length-1])lines.push('');lines[lines.length-1]=word.slice(0,limit);word=word.slice(limit);lines.push('')}if((lines[lines.length-1]+' '+word).trim().length>limit)lines.push(word);else lines[lines.length-1]=(lines[lines.length-1]+' '+word).trim()});lines.forEach((line,i)=>{const t=document.createElementNS('http://www.w3.org/2000/svg','tspan');t.setAttribute('x',node.getAttribute('x'));t.setAttribute('dy',i?String(Number(node.getAttribute('font-size'))+3):'0');t.textContent=line;node.appendChild(t)})} +function loadDate(){if(pendingScrub!==null){cancelAnimationFrame(pendingScrub);pendingScrub=null}syncSlider();const state=currentState();if(dateInput.value)stateInput.value=state?state.id:'';loadState()} +function loadState(){const state=currentState(),old=systemInput.value;systemInput.replaceChildren(new Option('All systems',''));if(state)state.applications.forEach(a=>systemInput.add(new Option(a.name,String(a.id))));systemInput.value=state&&state.applications.some(a=>String(a.id)===old)?old:'';loadLayout()} +function loadLayout(){syncSlider();const state=currentState(),when=dateInput.value;const key=['sort-layers','show-backlog','system-labels','maturity'].map(id=>document.getElementById(id).checked?'1':'0').join(':');const map=document.getElementById('map');document.getElementById('export-svg').disabled=!state;document.getElementById('print').disabled=!state;document.getElementById('date-prev').disabled=!payload.frames.some(s=>s.frame_froms.frame_from>when); +if(state){const layoutKey=key+':'+document.getElementById('tag-filter').value;if(state!==renderedState||layoutKey!==renderedKey||!map.querySelector('svg')){map.innerHTML='
'+state.layouts[layoutKey]+'
';renderedState=state;renderedKey=layoutKey}dateStatus.textContent=when?`${when} · ${state.label} · ${state.effective_from} ≤ date ${state.effective_to?'< '+state.effective_to:'(open end)'} · ${state.kind==='target'?'Planned scenario':'Snapshot-based view'}`:'Snapshot mode — no date selected. '+state.label}else{renderedState=null;renderedKey='';map.replaceChildren();const message=document.createElement('p');message.textContent=when?`No state data for date ${when}. Choose a date within a supplied period or select a snapshot.`:'Choose a date or select a snapshot.';map.append(message);dateStatus.textContent=message.textContent;document.getElementById('technical-details').replaceChildren();applyViewport()} +coverageChoices.querySelectorAll('input').forEach(i=>{const app=state&&state.applications.find(a=>String(a.id)===i.value);i.disabled=!app;i.parentElement.querySelector('.coverage-system-label').textContent=app?app.name:allCoverage.get(i.value);i.parentElement.title=i.disabled?'Not available in this state':''});document.getElementById('coverage').disabled=!state||!state.applications.length;if(!state)document.getElementById('functional-overlap').disabled=true;document.getElementById('coverage-count').textContent=`${selectedCoverage().length} selected`;if(state)updateView()} +function coverageShapePoints(hull,shape,rounded){let points=hull;if(shape==='rectangular'){const xs=hull.map(p=>p[0]),ys=hull.map(p=>p[1]),xmin=Math.min(...xs),xmax=Math.max(...xs),ymin=Math.min(...ys),ymax=Math.max(...ys);points=[[xmin,ymin],[xmax,ymin],[xmax,ymax],[xmin,ymax]]}if(!rounded)return points;const result=[];points.forEach((corner,i)=>{const previous=points[(i+points.length-1)%points.length],following=points[(i+1)%points.length],before=Math.hypot(previous[0]-corner[0],previous[1]-corner[1]),after=Math.hypot(following[0]-corner[0],following[1]-corner[1]),radius=Math.min(10,before/2,after/2),start=corner.map((v,k)=>v+(previous[k]-v)*radius/before),end=corner.map((v,k)=>v+(following[k]-v)*radius/after);for(let step=0;step<=8;step++){const t=step/8;result.push(corner.map((v,k)=>Math.round(((1-t)**2*start[k]+2*(1-t)*t*v+t*t*end[k])*10000)/10000))}});return result} +function applyCoverageShape(svg,shape,rounded){svg.querySelectorAll('.coverage-overlay').forEach(group=>{const polygon=group.querySelector('.coverage-polygon'),hull=polygon.getAttribute('data-coverage-hull').split(/\s+/).map(p=>p.split(',').map(Number)),points=coverageShapePoints(hull,shape,rounded).map(([x,y])=>`${x.toFixed(4)},${y.toFixed(4)}`).join(' ');polygon.setAttribute('points',points);group.querySelector('defs mask polygon').setAttribute('points',points)});svg.setAttribute('data-coverage-shape',shape);svg.setAttribute('data-coverage-rounded',rounded?'yes':'no')} +function polygonIntersection(subject,clip){const cross=(a,b,p)=>(b[0]-a[0])*(p[1]-a[1])-(b[1]-a[1])*(p[0]-a[0]);let output=subject;for(let i=0;i=-1e-8)!==(dp>=-1e-8)){const t=dp/(dp-dc);output.push([previous[0]+t*(current[0]-previous[0]),previous[1]+t*(current[1]-previous[1])])}if(dc>=-1e-8)output.push(current);previous=current;dp=dc}}const area=Math.abs(output.reduce((sum,a,i)=>{const b=output[(i+1)%output.length];return sum+a[0]*b[1]-b[0]*a[1]},0))/2;return area>1e-6?output:[]} +function updateFunctionalOverlap(svg,state,enabled){svg.querySelectorAll('g.functional-overlap').forEach(g=>g.remove());if(!enabled)return [];const active=Array.from(svg.querySelectorAll('.coverage-overlay[data-coverage-visible="yes"]')),regions=[];for(let i=0;ig.querySelector('.coverage-polygon')),points=polygons.map(p=>p.getAttribute('points').trim().split(/\s+/).map(p=>p.split(',').map(Number))),intersection=polygonIntersection(...points);if(intersection.length)regions.push({ids:[left,right].map(g=>g.getAttribute('data-coverage-system')).sort(),points:intersection})}if(!regions.length)return [];const ns='http://www.w3.org/2000/svg',add=(parent,tag,attrs)=>{const e=document.createElementNS(ns,tag);Object.entries(attrs).forEach(([k,v])=>e.setAttribute(k,v));parent.append(e);return e},group=add(svg,'g',{class:'functional-overlap','pointer-events':'none'}),defs=add(group,'defs',{}),edge=add(defs,'filter',{id:'functional-overlap-edge',filterUnits:'userSpaceOnUse',x:'0',y:'0',width:svg.getAttribute('width'),height:svg.getAttribute('data-content-bottom'),'color-interpolation-filters':'sRGB'});for(const [tag,attrs] of [['feMorphology',{in:'SourceAlpha',operator:'dilate',radius:'1.5',result:'outer'}],['feMorphology',{in:'SourceAlpha',operator:'erode',radius:'1.5',result:'inner'}],['feComposite',{in:'outer',in2:'inner',operator:'out',result:'edge'}],['feFlood',{'flood-color':'#dc2626',result:'red'}],['feComposite',{in:'red',in2:'edge',operator:'in'}]])add(edge,tag,attrs);const boundary=add(group,'g',{class:'functional-overlap-outline',filter:'url(#functional-overlap-edge)'});for(const {ids,points} of regions){const pair=add(boundary,'g',{class:'functional-overlap-region','data-overlap-systems':JSON.stringify(ids)});add(pair,'polygon',{points:points.map(([x,y])=>`${x.toFixed(4)},${y.toFixed(4)}`).join(' '),fill:'white'})}return regions.map(r=>r.ids)} +function addMaturityLegend(group,width,y){const ns='http://www.w3.org/2000/svg',add=(parent,tag,attrs,text)=>{const e=document.createElementNS(ns,tag);Object.entries(attrs).forEach(([k,v])=>e.setAttribute(k,v));if(text!==undefined)e.textContent=text;parent.append(e);return e},tilewidth=Math.min(216,width-48),columns=Math.max(1,Math.floor((width-48+12)/(tilewidth+12)));add(group,'text',{x:'24.0',y:(y+10).toFixed(1),'font-size':'12',fill:'#475569','text-anchor':'start'},payload.legend_labels.maturity);payload.maturity_legend.forEach((item,i)=>{const x=24+(i%columns)*(tilewidth+12),top=y+22+Math.floor(i/columns)*52,tile=add(group,'g',{class:'maturity-legend-item','data-maturity-level':String(item.level)});add(tile,'rect',{class:`maturity-legend-swatch caprect m${item.level}`,x:x.toFixed(1),y:top.toFixed(1),width:'36',height:'26',rx:'6',fill:'#c9d5f2',stroke:'#c9d5f2','stroke-width':'3'});for(const [text,tx,ty,size,fill,anchor] of [[String(item.level),x+18,top+17,'11','#0f172a','middle'],[item.name,x+48,top+9,'11','#334155','start'],[item.description,x+48,top+25,'10','#64748b','start']])add(tile,'text',{x:tx.toFixed(1),y:ty.toFixed(1),'font-size':size,fill,'text-anchor':anchor},text)});return y+22+Math.ceil(payload.maturity_legend.length/columns)*52+6} +function updateLegend(svg,state,view){const ns='http://www.w3.org/2000/svg',group=svg.querySelector('g.legend');if(!group)return;group.replaceChildren();const width=Number(svg.getAttribute('width')),bottom=Number(svg.getAttribute('data-content-bottom')),items=[],words=payload.legend_labels;const visible=Array.from(svg.querySelectorAll('g[data-id]')).filter(g=>Number(g.getAttribute('data-depth'))<=view.depth); +let maturityKey=false;if(view.legend&&visible.length){if(view.sort_layers&&svg.querySelector('.layer-zone'))items.push([words.layers,null]);if(view.tag_filter&&visible.some(g=>g.getAttribute('data-tag-match')==='context'))items.push([words.context,null]);if(view.system_labels&&visible.some(g=>Array.from(g.children).some(n=>n.classList.contains('system-label'))))items.push([words.labels,null]);if(view.system_id&&visible.some(g=>g.getAttribute('data-support')==='supported'))items.push([words.outline+state.applications.find(a=>String(a.id)===view.system_id).name,'#00a6a6']);const active=Array.from(svg.querySelectorAll('.coverage-overlay[data-coverage-visible="yes"]'));active.forEach(g=>{const id=g.getAttribute('data-coverage-system');items.push([words.coverage+state.applications.find(a=>String(a.id)===id).name,payload.coverage_colors[id]])});if(active.length)items.push([words.shared,null]);if(svg.querySelector('g.functional-overlap'))items.push([words.functional_overlap,'#dc2626']);if(view.maturity&&visible.some(g=>Array.from(g.children).some(n=>n.classList.contains('maturity-label'))))maturityKey=true} +let x=24,baseline=bottom+18,rowheight=14;for(const [label,color] of items){const prefix=color?16:0,limit=Math.max(4,Math.floor((width-48-prefix)/(11*.62)));let lines=[''];label.split(/\s+/).forEach(word=>{while(word.length>limit){if(lines[lines.length-1])lines.push('');lines[lines.length-1]=word.slice(0,limit);word=word.slice(limit);lines.push('')}if((lines[lines.length-1]+' '+word).trim().length>limit)lines.push(word);else lines[lines.length-1]=(lines[lines.length-1]+' '+word).trim()});const itemwidth=Math.max(...lines.map(line=>line.length))*11*.62+prefix;if(x>24&&x+itemwidth>width-24){x=24;baseline+=rowheight+6;rowheight=14}if(color){const rect=document.createElementNS(ns,'rect');Object.entries({x,y:baseline-9,width:10,height:10,rx:2,fill:color}).forEach(([k,v])=>rect.setAttribute(k,k==='x'||k==='y'?Number(v).toFixed(1):String(v)));group.append(rect)}const text=document.createElementNS(ns,'text');Object.entries({x:x+prefix,y:baseline,'font-size':11,fill:'#475569','text-anchor':'start'}).forEach(([k,v])=>text.setAttribute(k,k==='x'||k==='y'?Number(v).toFixed(1):String(v)));lines.forEach((line,i)=>{const span=document.createElementNS(ns,'tspan');span.setAttribute('x',(x+prefix).toFixed(1));span.setAttribute('dy',i?'14':'0');span.textContent=line;text.append(span)});group.append(text);rowheight=Math.max(rowheight,14*lines.length);x+=itemwidth+18}let height=items.length?baseline+rowheight+6:bottom+20;if(maturityKey)height=addMaturityLegend(group,width,items.length?baseline+rowheight+14:bottom+12);group.style.display=items.length||maturityKey?'inline':'none';svg.setAttribute('height',String(height));svg.setAttribute('viewBox',`0 0 ${width} ${height}`)} +function updateTechnicalNotes(md){const details=document.getElementById('technical-details');details.replaceChildren();for(const [label,value] of [['Model revision',md.model_revision],['Methodology contract',md.methodology_revision],['Reviewed baseline',md.methodology_baseline_revision],['Contract status',md.methodology_contract_status],['Adapter',md.adapter_version],['Renderer',md.renderer_version],['State',md.state_id],['View date',md.view_date],['Snapshot basis',md.snapshot_as_of],['View contract',md.view_contract],['Mapping semantics',md.mapping_semantics],['Functional overlap',md.functional_overlap_semantics]]){const term=document.createElement('dt'),description=document.createElement('dd');term.textContent=label;description.textContent=value||'Not specified';details.append(term,description)}} +let zoomScale=1,fitActive=false,viewportFrame=null; +const mapViewport=document.getElementById('map'),zoomRange=document.getElementById('zoom-range'); +function applyViewport(reset=false){const svg=mapViewport.querySelector('svg'),stage=document.getElementById('map-stage'),content=document.getElementById('map-content');for(const id of ['zoom-in','zoom-out','zoom-reset','zoom-range','fit-map'])document.getElementById(id).disabled=!svg;if(!svg||!stage)return;const width=Number(svg.getAttribute('width')),height=Number(svg.getAttribute('height'));if(fitActive)zoomScale=Math.min(1,Math.max(1,mapViewport.clientWidth-25)/width,Math.max(1,mapViewport.clientHeight-25)/height);stage.style.width=`${width*zoomScale}px`;stage.style.height=`${height*zoomScale}px`;content.style.width=`${width}px`;content.style.height=`${height}px`;content.style.transform=`scale(${zoomScale})`;const percentage=zoomScale*100;zoomRange.min=String(Math.min(1,Math.floor(percentage)));zoomRange.value=String(Math.round(percentage));zoomRange.setAttribute('aria-valuetext',`${percentage.toFixed(1)}%`);document.getElementById('zoom-value').textContent=`${Number(percentage.toFixed(1))}%`;document.getElementById('fit-map').setAttribute('aria-pressed',String(fitActive));if(reset){mapViewport.scrollLeft=0;mapViewport.scrollTop=0}} +function scheduleViewport(){if(viewportFrame===null)viewportFrame=requestAnimationFrame(()=>{viewportFrame=null;applyViewport()})} +function setZoom(scale){const stage=document.getElementById('map-stage');if(!stage)return;const centerX=(mapViewport.scrollLeft+mapViewport.clientWidth/2-stage.offsetLeft)/zoomScale,centerY=(mapViewport.scrollTop+mapViewport.clientHeight/2-stage.offsetTop)/zoomScale;fitActive=false;zoomScale=Math.max(.01,Math.min(3,scale));applyViewport();mapViewport.scrollLeft=stage.offsetLeft+centerX*zoomScale-mapViewport.clientWidth/2;mapViewport.scrollTop=stage.offsetTop+centerY*zoomScale-mapViewport.clientHeight/2} +function fitMap(){fitActive=true;applyViewport(true)} +document.getElementById('fit-map').addEventListener('click',fitMap);document.getElementById('zoom-in').addEventListener('click',()=>setZoom(zoomScale*1.25));document.getElementById('zoom-out').addEventListener('click',()=>setZoom(zoomScale/1.25));document.getElementById('zoom-reset').addEventListener('click',()=>setZoom(1));zoomRange.addEventListener('input',()=>setZoom(Number(zoomRange.value)/100));window.addEventListener('resize',scheduleViewport);if(typeof ResizeObserver!=='undefined')new ResizeObserver(scheduleViewport).observe(mapViewport); +function setDiagramOnly(on){document.getElementById('diagram-only').checked=on;document.body.classList.toggle('diagram-only',on);const toggle=document.getElementById('show-controls');toggle.textContent=on?'Show controls':'Hide controls';toggle.setAttribute('aria-expanded',String(!on));if(on){fitMap();document.getElementById('show-controls').focus()}else{applyViewport();document.getElementById('diagram-only').focus()}} +document.getElementById('diagram-only').addEventListener('change',event=>setDiagramOnly(event.target.checked));document.getElementById('show-controls').addEventListener('click',()=>setDiagramOnly(!document.body.classList.contains('diagram-only')));document.addEventListener('keydown',event=>{if(event.key==='Escape'&&document.body.classList.contains('diagram-only'))setDiagramOnly(false)}); +function updateView(){const svg=document.querySelector('#map svg'),state=currentState(),system=systemInput.value;if(!svg||!state)return;const depth=document.getElementById('depth').value;const labels=document.getElementById('system-labels').checked,maturity=document.getElementById('maturity').checked,legend=document.getElementById('legend').checked,coverage=document.getElementById('coverage').checked&&!document.getElementById('coverage').disabled;const selected=coverage?selectedCoverage():[];document.getElementById('coverage-count').textContent=`${selectedCoverage().length} selected`;svg.querySelectorAll('.coverage-overlay').forEach(g=>{const visible=selected.includes(g.getAttribute('data-coverage-system'))&&Number(g.getAttribute('data-coverage-depth'))===Number(depth);g.setAttribute('data-coverage-visible',visible?'yes':'no');g.style.display=visible?'inline':'none'}); +svg.setAttribute('data-max-depth',depth);svg.setAttribute('data-system-labels',labels?'on':'off');svg.setAttribute('data-maturity',maturity?'on':'off');svg.setAttribute('data-legend',legend?'on':'off');svg.setAttribute('data-system-selected',system?'yes':'no');svg.querySelectorAll('g[data-id]').forEach(g=>g.setAttribute('data-support',system&&JSON.parse(g.getAttribute('data-applications')).includes(system)?'supported':'not-specified')); +const coverageShape=document.getElementById('coverage-shape').value,roundCoverage=document.getElementById('round-coverage').checked;applyCoverageShape(svg,coverageShape,roundCoverage);const overlapInput=document.getElementById('functional-overlap');overlapInput.disabled=!coverage||selected.length<2;const overlapEnabled=overlapInput.checked&&!overlapInput.disabled;const overlapIds=updateFunctionalOverlap(svg,state,overlapEnabled); +const meta=svg.querySelector('metadata');const md=JSON.parse(meta.textContent);if(dateInput.value){md.as_of=dateInput.value;md.view_date=dateInput.value;const node=svg.querySelector('.date-context');if(node)wrapText(node,dateCaption(state),svg)}md.view={coverage_shape:coverageShape,round_coverage:roundCoverage,functional_overlap:overlapEnabled,functional_overlap_system_pairs:overlapIds,view_date:md.view_date,system_id:system||null,depth:Number(depth),system_labels:labels,maturity,legend,sort_layers:document.getElementById('sort-layers').checked,show_backlog:document.getElementById('show-backlog').checked,tag_filter:document.getElementById('tag-filter').value||null,coverage,coverage_system_id:selected.length===1?selected[0]:null,coverage_system_ids:selected};meta.textContent=JSON.stringify(md);updateLegend(svg,state,md.view);updateTechnicalNotes(md); +const name=system?state.applications.find(a=>String(a.id)===system).name:'All';const caption=`Layout: ${md.view.sort_layers?'Layers':'Classic'} · Backlog: ${md.view.show_backlog?'on':'off'} · Tag: ${md.view.tag_filter||'All'} · System: ${name} · Depth: ${depth} · System labels: ${labels?'on':'off'} · Maturity: ${maturity?'on':'off'} · Legend: ${legend?'on':'off'} · Coverage: ${coverage?(selected.map(id=>state.applications.find(a=>String(a.id)===id).name).join(', ')||'none'):'off'}`;const target=svg.querySelector('.view-selection');target.replaceChildren();const limit=Math.max(20,Math.floor((Number(svg.getAttribute('width'))-48)/7));const words=caption.split(/\s+/);let lines=[''];words.forEach(word=>{while(word.length>limit){if(lines[lines.length-1])lines.push('');lines[lines.length-1]=word.slice(0,limit);word=word.slice(limit);lines.push('')}if((lines[lines.length-1]+' '+word).trim().length>limit)lines.push(word);else lines[lines.length-1]=(lines[lines.length-1]+' '+word).trim()});lines.forEach((line,i)=>{const t=document.createElementNS('http://www.w3.org/2000/svg','tspan');t.setAttribute('x',target.getAttribute('x'));t.setAttribute('dy',i?'14':'0');t.textContent=line;target.appendChild(t)});applyViewport()} +stateInput.addEventListener('change',()=>{const state=payload.states.find(s=>s.id===stateInput.value);dateInput.value=state&&state.effective_from?(state.snapshot_as_of&&state.snapshot_as_of>=state.effective_from&&(!state.effective_to||state.snapshot_as_of{dateInput.value=localToday();loadDate()}); +for(const [id,next] of [['date-prev',false],['date-next',true]])document.getElementById(id).addEventListener('click',()=>{const dates=payload.frames.map(s=>s.frame_from).filter(d=>next?d>dateInput.value:ddocument.getElementById(id).addEventListener('change',loadLayout));['system','depth','legend','coverage','functional-overlap','coverage-shape','round-coverage'].forEach(id=>document.getElementById(id).addEventListener('change',updateView)); +document.getElementById('export-svg').addEventListener('click',()=>{const current=document.querySelector('#map svg');const clone=current.cloneNode(true);const depth=Number(clone.getAttribute('data-max-depth'));clone.querySelectorAll('.coverage-overlay[data-coverage-visible="no"]').forEach(g=>g.remove());clone.querySelectorAll('g[data-depth]').forEach(g=>{if(Number(g.getAttribute('data-depth'))>depth)g.remove()});if(clone.getAttribute('data-system-labels')==='off')clone.querySelectorAll('.system-label').forEach(e=>e.remove());if(clone.getAttribute('data-maturity')==='off')clone.querySelectorAll('.maturity-label').forEach(e=>e.remove());if(clone.getAttribute('data-legend')==='off')clone.querySelectorAll('.legend').forEach(e=>e.remove());clone.querySelectorAll('g[data-id]').forEach(g=>{g.removeAttribute('data-applications');Array.from(g.children).filter(e=>e.localName==='desc').forEach(e=>e.remove())});const xml=new XMLSerializer().serializeToString(clone);const url=URL.createObjectURL(new Blob([xml],{type:'image/svg+xml;charset=utf-8'}));const a=document.createElement('a');a.href=url;a.download='capability-map.svg';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1000)});document.getElementById('print').addEventListener('click',()=>window.print());dateInput.disabled=!payload.frames.length;document.getElementById('date-today').disabled=!payload.frames.length;dateInput.value=payload.frames.length?(payload.initial_date||localToday()):'';loadDate(); +''' + +def render(data, as_of=None, view_date=None): + model=normalize(data,as_of) + colors=coverage_colors(model) + if view_date and not any(s['effective_from'] for s in model['states']):raise ValueError('--date requires dated state periods') + def embed(state): + return {'id':state['id'],'label':state['label'],'kind':state['kind'], + 'snapshot_as_of':state['snapshot_as_of'].isoformat() if state.get('snapshot_as_of') else None, + 'effective_from':state['effective_from'].isoformat() if state.get('effective_from') else None, + 'effective_to':state['effective_to'].isoformat() if state.get('effective_to') else None, + 'frame_from':state['frame_from'].isoformat() if state.get('frame_from') else None, + 'frame_to':state['frame_to'].isoformat() if state.get('frame_to') else None, + 'applications':state['applications'],'layouts':{ + f'{int(layers)}:{int(backlog)}:{int(labels)}:{int(maturity)}:{tag}':build_svg(model,state,layers,backlog,labels,maturity,tag) + for layers in (False,True) for backlog in (False,True) + for labels in (False,True) for maturity in (False,True) for tag in ('',*TAGS)}} + payload={'maturity_legend':MATURITY_LEGEND,'legend_labels':LEGEND_LABELS,'coverage_colors':colors,'coverage_default_ids':[model['coverage_system_id']] if model.get('coverage_system_id') else [], + 'initial_date':(date(view_date) or model['view_date']).isoformat() if date(view_date) or model['view_date'] else None, + 'coverage_applications':[{'id':aid,'name':next(a['name'] for s in model['states'] for a in s['all_applications'] if str(a['id'])==aid)} for aid in colors], + 'states':[embed(s) for s in model['states']], 'frames':[embed(s) for s in timeline_frames(model)]} + encoded=json.dumps(payload,ensure_ascii=True).replace('<','\\u003c').replace('>','\\u003e').replace('&','\\u0026') + options=''.join(f'' for s in model['states']) + return f''' +{esc(model['title'])} +
+
Time +
+
+

+
Capability view
+ + + +
+
Systems & coverage
+
+
Coverage systems —
+
Export
+
Diagram notes

Classic DSM Report adaptation. Explicit dated snapshots and planned scenarios; no interpolation or forecast. Date gaps show no data. A missing system mapping means not specified, never unsupported. Five management layers; ESG, MDM and Support are box tags. Tag filters keep direct matches and muted parent/domain context; tags and system mappings do not inherit. Unclassified stages stay Not specified. Hiding backlog removes its column and unplaced assignments. System labels are off by default. Boxes resize to fit visible labels; Coverage polygons are off by default. Select one or more systems above; colors overlap where explicit mappings share a capability. Direct and explicit technical mappings; area is not a percentage. SVG exports this exact view.

+
100%
''' + +def render_svg(data,as_of=None,show_maturity=False,state_id=None,system='',depth=3,labels=False,legend=True,sort_layers=False,show_backlog=True,tag_filter='',coverage=False,coverage_systems=None,view_date=None,functional_overlap=False,coverage_shape='angled',round_coverage=False): + model=normalize(data,as_of);state=next((s for s in model['states'] if s['id']==state_id),None) if state_id else model['states'][0] + if state is None:raise ValueError('Unknown state ID') + requested=date(view_date) or (model['view_date'] if not state_id else None) + if requested:state=state_on(model,requested,state_id) + return prune_export(apply_view(build_svg(model,state,sort_layers,show_backlog,labels,show_maturity,tag_filter),state,system,depth,labels,show_maturity,legend,coverage,coverage_systems,functional_overlap,coverage_shape,round_coverage)) + +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('input');p.add_argument('output');p.add_argument('--as-of');p.add_argument('--date',dest='view_date',help='Select the explicit state period and evaluate lifetimes/maturity on YYYY-MM-DD');p.add_argument('--maturity',action='store_true');p.add_argument('--state');p.add_argument('--system',default='');p.add_argument('--depth',type=int,choices=(1,2,3),default=3);labels_group=p.add_mutually_exclusive_group();labels_group.add_argument('--system-labels',dest='system_labels',action='store_true');labels_group.add_argument('--no-system-labels',dest='system_labels',action='store_false');p.set_defaults(system_labels=False);p.add_argument('--no-legend',action='store_true');p.add_argument('--coverage',action='store_true',help='Show coverage polygons; defaults to legacy pilot, or all systems without one (SVG output)');p.add_argument('--coverage-system',action='append',dest='coverage_systems',help='Select a coverage system ID; repeat for multiple systems; requires --coverage (SVG output)');p.add_argument('--coverage-shape',choices=('angled','rectangular'),default='angled',help='Coverage outline form (SVG output)');p.add_argument('--round-coverage',action='store_true',help='Round coverage polygon corners (SVG output)');p.add_argument('--functional-overlap',action='store_true',help='Outline intersections of 2+ selected system coverage polygons in red (SVG output)');p.add_argument('--tag',default='',choices=('',*TAGS),help='Keep direct tag matches and parent/domain context (SVG output)');p.add_argument('--sort-layers',action='store_true',help='Group explicit management stages into horizontal bands (SVG output)');p.add_argument('--no-backlog',action='store_true',help='Omit backlog column and unplaced assignments (SVG output)');a=p.parse_args() + if a.functional_overlap and not a.coverage:p.error('--functional-overlap requires --coverage') + if a.coverage_systems and not a.coverage:p.error('--coverage-system requires --coverage') + try: + data=json.loads(pathlib.Path(a.input).read_text(encoding='utf-8'));as_of=date(a.as_of) + content=render_svg(data,as_of,a.maturity,a.state,a.system,a.depth,a.system_labels,not a.no_legend,a.sort_layers,not a.no_backlog,a.tag,a.coverage,a.coverage_systems,a.view_date,a.functional_overlap,a.coverage_shape,a.round_coverage) if pathlib.Path(a.output).suffix.lower()=='.svg' else render(data,as_of,a.view_date) + pathlib.Path(a.output).write_text(content,encoding='utf-8') + except (ValueError,KeyError,TypeError,OSError) as e:p.exit(2,f'Invalid model: {e}\n') +if __name__=='__main__':main() diff --git a/transitrix/skills/render-dsm-capabilities-html/scripts/test_package.py b/transitrix/skills/render-dsm-capabilities-html/scripts/test_package.py new file mode 100644 index 00000000..ae0e4474 --- /dev/null +++ b/transitrix/skills/render-dsm-capabilities-html/scripts/test_package.py @@ -0,0 +1,41 @@ +"""Exercise portable archive extraction, reproducibility and refusing writes.""" +import hashlib +import importlib.util +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +import zipfile + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('skill_package', ROOT / 'scripts/package.py') +package = importlib.util.module_from_spec(spec) +spec.loader.exec_module(package) + +class PortablePackage(unittest.TestCase): + def test_archive_reproducible_and_renderable_after_extraction(self): + with tempfile.TemporaryDirectory() as work: + work = Path(work) + first, second = work / 'first.zip', work / 'second.zip' + package.build(first) + package.build(second) + self.assertEqual(hashlib.sha256(first.read_bytes()).digest(), hashlib.sha256(second.read_bytes()).digest()) + with zipfile.ZipFile(first) as archive: + names = archive.namelist() + self.assertIn(ROOT.name + '/SKILL.md', names) + self.assertIn(ROOT.name + '/README.md', names) + self.assertFalse(any('__pycache__' in p or p.endswith('.pyc') for p in names)) + archive.extractall(work / 'unpacked') + folder = work / 'unpacked' / ROOT.name + subprocess.run([sys.executable, str(folder / 'scripts/render.py'), str(folder / 'assets/example.json'), str(work / 'map.svg'), '--no-backlog'], check=True, capture_output=True) + self.assertIn(' governance and cross-functional coordination ' * 5 + gs = groups(render.render_svg(data)) + self.assertGreaterEqual(float(rect(gs['sales'])['width']), 500) + self.assertGreater(float(rect(gs['risk'])['width']), float(rect(gs['risk'])['height'])) + title = gs['risk'].find("s:text[@class='horizontal-title']", NS) + self.assertGreater(len(title), 1) + last_baseline = float(title.get('y')) + 15*(len(title)-1) + # The long title wraps in the left gutter beside the intersection. + label_right=max(float(t.get('x'))+len(t.text or '')*12*.62 for t in title) + self.assertLess(label_right,float(rect(gs['sales'])['x'])) + self.assertLess(float(rect(gs['customer-risk'])['y']),last_baseline) + self.assertLess(last_baseline,float(rect(gs['risk'])['y'])+float(rect(gs['risk'])['height'])) + + def test_horizontal_labels_leave_domain_lanes_free(self): + for layers in (False,True): + gs=groups(render.render_svg(EXAMPLE,sort_layers=layers,show_backlog=False)) + first_column=float(rect(gs['sales'])['x']) + for ident in ('risk','data'): + for label in gs[ident].findall('s:text',NS): + if label.get('class')=='unassigned-label':continue + self.assertEqual(label.get('text-anchor'),'start') + size=float(label.get('font-size')) + for line in label: + self.assertLess(float(line.get('x'))+len(line.text or '')*size*.62,first_column) + for ident in ('customer-risk','checks','delivery-risk','quality'): + for label in gs[ident].findall('s:text',NS): + self.assertEqual(label.get('text-anchor'),'start') + + def test_views_preserve_geometry_and_exact_export(self): + for state in ('current', 'target'): + base = geometry(render.render_svg(EXAMPLE, state_id=state, labels=False, show_maturity=True)) + for depth in (1, 2, 3): + svg = render.render_svg(EXAMPLE, state_id=state, system='app-crm', depth=depth, labels=False, legend=False, show_maturity=True) + gs = groups(svg) + self.assertEqual(geometry(svg), {k: base[k] for k in gs}) + self.assertTrue(all(int(g.get('data-depth')) <= depth for g in gs.values())) + self.assertNotIn('data-applications=', svg) + root = ET.fromstring(svg) + self.assertFalse(root.findall(".//s:text[@class='system-label']", NS)) + self.assertFalse(root.findall(".//s:g[@class='legend']", NS)) + self.assertEqual(gs['risk'].get('data-support'), 'not-specified') + if depth >= 2: + self.assertEqual(gs['customer-risk'].get('data-support'), 'supported' if state=='target' else 'not-specified') + md = json.loads(root.find('s:metadata', NS).text) + self.assertEqual(md['state_id'], state) + self.assertEqual(md['horizon_label'], 'end of 2027' if state=='target' else '') + + def test_html_uses_same_svg_builder(self): + html = render.render(EXAMPLE) + payload = json.loads(re.search(r'', html).group(1)) + model = render.normalize(EXAMPLE, None) + for embedded, state in zip(payload['states'], model['states']): + for layers,backlog,labels,maturity in itertools.product((False,True),repeat=4): + key=':'.join(str(int(x)) for x in (layers,backlog,labels,maturity))+':' + self.assertEqual(embedded['layouts'][key],render.build_svg(model,state,layers,backlog,labels,maturity)) + +class CompactLabels(unittest.TestCase): + def test_defaults_and_empty_lines(self): + svg=render.render_svg(EXAMPLE) + root=ET.fromstring(svg) + self.assertFalse(root.findall(".//s:text[@class='system-label']",NS)) + self.assertFalse(root.findall(".//s:text[@class='maturity-label']",NS)) + self.assertFalse(json.loads(root.find('s:metadata',NS).text)['view']['system_labels']) + html=render.render(EXAMPLE) + checkbox=re.search(r']*>',html).group() + self.assertNotIn('checked',checkbox) + shown=ET.fromstring(render.render_svg(EXAMPLE,labels=True,show_maturity=True)) + for text in shown.findall('.//s:text',NS): + self.assertTrue(''.join(text.itertext()).strip()) + visible=' '.join(''.join(t.itertext()) for t in shown.findall('.//s:text',NS)) + self.assertNotIn('Systems: not specified',visible) + self.assertNotIn('Not assessed',visible) + + def test_show_systems_grows_boxes_and_restore_compacts(self): + for layers in (False,True): + hidden=render.render_svg(EXAMPLE,sort_layers=layers) + shown=render.render_svg(EXAMPLE,sort_layers=layers,labels=True) + off,on=groups(hidden),groups(shown) + for ident in ('acquire','quality'): + a,b=rect(off[ident]),rect(on[ident]) + self.assertGreater(float(b['width'])*float(b['height']),float(a['width'])*float(a['height'])) + self.assertIsNone(off[ident].find("s:text[@class='system-label']",NS)) + self.assertIsNotNone(on[ident].find("s:text[@class='system-label']",NS)) + self.assertIsNone(on['unknown-risk'].find("s:text[@class='system-label']",NS)) + self.assertEqual(hidden,render.render_svg(EXAMPLE,sort_layers=layers,labels=False)) + # Maturity is another optional line stack; hiding it leaves no slot. + mature=groups(render.render_svg(EXAMPLE,sort_layers=layers,show_maturity=True)) + self.assertGreater(float(rect(mature['quality'])['height']),float(rect(off['quality'])['height'])) + + def test_cli_system_labels_opt_in(self): + script=Path(render.__file__) + source=script.parents[1]/'assets/synthetic-regression.json' + with tempfile.TemporaryDirectory() as tmp: + for enabled in (False,True): + output=Path(tmp)/('shown.svg' if enabled else 'hidden.svg') + args=[sys.executable,str(script),str(source),str(output)] + if enabled:args.append('--system-labels') + subprocess.run(args,check=True,capture_output=True) + root=ET.fromstring(output.read_text()) + self.assertEqual(bool(root.findall(".//s:text[@class='system-label']",NS)),enabled) + +class BacklogVisibility(unittest.TestCase): + def test_hide_restore_both_layouts_and_snapshots(self): + before=copy.deepcopy(EXAMPLE) + for state,layers,depth in itertools.product(('current','target'),(False,True),(1,2,3)): + full=render.render_svg(EXAMPLE,state_id=state,sort_layers=layers,depth=depth) + hidden=render.render_svg(EXAMPLE,state_id=state,sort_layers=layers,depth=depth, + show_backlog=False,system='app-crm',labels=False) + gs=groups(hidden);root=ET.fromstring(hidden) + excluded={'backlog','idea','unknown-risk'} + self.assertEqual(set(gs),set(groups(full))-excluded) + self.assertLess(float(root.get('width')),float(ET.fromstring(full).get('width'))) + md=json.loads(root.find('s:metadata',NS).text) + self.assertFalse(md['show_backlog']);self.assertFalse(md['view']['show_backlog']) + self.assertEqual(md['view']['sort_layers'],layers) + self.assertEqual(md['view']['system_id'],'app-crm') + if depth>=2: + c,d=rect(gs['customer-risk']),rect(gs['sales']) + self.assertAlmostEqual(float(c['x'])+float(c['width'])/2,float(d['x'])+float(d['width'])/2) + self.assertEqual(full,render.render_svg(EXAMPLE,state_id=state,sort_layers=layers,depth=depth)) + self.assertEqual(EXAMPLE,before) + + def test_only_backlog_and_no_backlog(self): + for layers in (False,True): + data=copy.deepcopy(EXAMPLE);data['states']=data['states'][:1] + state=data['states'][0];state['applications']=[] + state['capabilities']=[r for r in state['capabilities'] if r['id'] in ('backlog','idea')] + hidden=render.render_svg(data,sort_layers=layers,show_backlog=False) + self.assertEqual(groups(hidden),{}) + self.assertNotIn('Unplaced / backlog',hidden) + # A placed capability called Backlog must not be hidden by name. + state['capabilities']=[dict(id='placed',name='Backlog',layout='vertical',first_level=1, + second_level=0,third_level=0,lane=0,property='Support')] + self.assertEqual(set(groups(render.render_svg(data,sort_layers=layers,show_backlog=False))),{'placed'}) + +class OrientationGeometry(unittest.TestCase): + def check_orientation(self,data): + for state,layers,backlog,depth in itertools.product(data['states'],(False,True),(False,True),(1,2,3)): + svg=render.render_svg(data,state_id=state['id'],sort_layers=layers,show_backlog=backlog,depth=depth) + byid={r['id']:r for r in state['capabilities']} + for ident,g in groups(svg).items(): + record=byid[ident];box=rect(g);w,h=float(box['width']),float(box['height']) + self.assertEqual(g.get('data-orientation'),record['layout']) + if record['layout']=='vertical': + if not record['second_level']:self.assertGreaterEqual(h+.1,1.25*w) + else:self.assertGreaterEqual(w+.1,1.6*h) + address=next(g.iter('{'+render.SVGNS+'}tspan')).text + self.assertTrue(address.startswith('v.' if record['layout']=='vertical' else 'h.')) + + def test_v_columns_h_rectangles_at_all_depths(self): + self.check_orientation(EXAMPLE) + + def test_descendant_widths_follow_parent_and_names_wrap_at_words(self): + data=json.loads((Path(__file__).resolve().parents[1]/'assets/example.json').read_text()) + for state,layers,backlog,labels,maturity,tag in itertools.product(data['states'],(False,True),(False,True),(False,True),(False,True),('',*render.TAGS)): + gs=groups(render.render_svg(data,state_id=state['id'],sort_layers=layers,show_backlog=backlog,labels=labels,show_maturity=maturity,tag_filter=tag)) + coords={(r['layout'],r['first_level'],r['second_level'],r['third_level']):r['id'] for r in state['capabilities']} + for record in state['capabilities']: + if record['layout']!='vertical' or not record['second_level'] or record['id'] not in gs:continue + parent=coords[('vertical',record['first_level'],record['second_level'] if record['third_level'] else 0,0)] + c,p=rect(gs[record['id']]),rect(gs[parent]);ratio=.9 if record['third_level'] else .8 + self.assertAlmostEqual(float(c['width']),float(p['width'])*ratio,delta=.11) + self.assertAlmostEqual(float(c['x'])+float(c['width'])/2,float(p['x'])+float(p['width'])/2,delta=.11) + # Ordinary example names must wrap between words, never as + # fragments such as "Custome" / "r" or "reconcili" / "ation". + name=gs[record['id']].findall('s:text',NS)[1] + lines=[t.text or '' for t in name.findall('s:tspan',NS)] + self.assertEqual(' '.join(lines),record['name']) + + def test_horizontal_content_expands_without_becoming_portrait(self): + data=copy.deepcopy(EXAMPLE);data['states']=data['states'][:1] + state=data['states'][0] + next(r for r in state['capabilities'] if r['id']=='customer-risk')['name']='Long horizontal capability label with explicit domain assignment ' * 8 + source=next(r for r in state['capabilities'] if r['id']=='checks') + for number in range(2,8): + child=copy.deepcopy(source);child.update(id=f'check-{number}',third_level=number) + state['capabilities'].append(child) + unplaced=copy.deepcopy(source) + unplaced.update(id='unplaced-check',name='Unplaced horizontal detail',second_level=3,third_level=1,lane=0) + state['capabilities'].append(unplaced) + before=copy.deepcopy(data) + self.check_orientation(data) + self.assertEqual(data,before) + +class LayerSorting(unittest.TestCase): + def setUp(self): + self.data=copy.deepcopy(EXAMPLE) + # Deliberately differ across hierarchy, orientation and snapshots. + properties={'sales':'Execution','acquire':'Planning','lead':'Strategic', + 'risk':'Support','customer-risk':'Learning','checks':'Execution', + 'data':'MDM','quality':'Assurance','idea':'Future category'} + for state in self.data['states']: + for record in state['capabilities']: + record.pop('property',None) + if record['id'] in properties:record['property']=properties[record['id']] + self.data['states'][1]['capabilities'][0]['property']='Strategic' + + def test_bands_explicit_values_and_lanes(self): + svg=render.render_svg(self.data,sort_layers=True) + root=ET.fromstring(svg);gs=groups(svg) + self.assertEqual(set(gs),{str(r['id']) for r in self.data['states'][0]['capabilities']}) + headings=root.findall("s:text[@class='layer-heading']",NS) + zones=root.findall("s:rect[@class='layer-zone']",NS) + self.assertEqual({''.join(h.itertext()) for h in headings},set((*render.LAYERS,'Not specified','Unknown property'))) + # Stage order restarts within each horizontal L1 context. + scopes={z.get('data-layer-scope') for z in zones} + order=[*render.LAYERS,'Not specified','Unknown property'] + for scope in scopes: + categories=[z.get('data-layer-zone') for z in zones if z.get('data-layer-scope')==scope] + self.assertEqual(categories,sorted(categories,key=order.index)) + y=[float(h.get('y')) for h in headings] + for r in self.data['states'][0]['capabilities']: + g=gs[r['id']];category=render.layer(r) + self.assertEqual(g.get('data-layer'),category) + if r['layout']=='vertical' and r['second_level']==0: + self.assertEqual(g.get('class'),'domain-column') + self.assertLess(float(rect(g)['y']),min(y)) + self.assertEqual(rect(g)['fill'],'none') + if render.layer_value(r):self.assertIn('Layer: '+render.layer_value(r),''.join(g.itertext())) + else:self.assertFalse(g.findall("s:text[@class='property-label']",NS)) + continue + if not r['second_level']:continue + # A stage label must stay inside a zone of its own category and + # domain context; a parent frame can span several cycle stages. + label_y=float(g.find('s:text',NS).get('y')) + scope='vertical-domains' if r['layout']=='vertical' else next(v['id'] for v in self.data['states'][0]['capabilities'] if v['layout']=='horizontal' and v['first_level']==r['first_level'] and not v['second_level']) + self.assertTrue(any(z.get('data-layer-zone')==category and z.get('data-layer-scope')==scope and + float(z.get('y'))=2: + expected='supported' if system=='app-crm' and state['id']=='target' else 'not-specified' + self.assertEqual(gs['customer-risk'].get('data-support'),expected) + self.assertEqual(self.data,before) + classic=render.render_svg(self.data) + self.assertIsNotNone(groups(classic)['acquire'].find("s:g[@data-id='lead']",NS)) + self.assertFalse(json.loads(ET.fromstring(classic).find('s:metadata',NS).text)['view']['sort_layers']) + + def test_source_parent_containment_in_all_views(self): + acme=json.loads((Path(__file__).resolve().parents[1]/'assets/example.json').read_text()) + for data in (self.data,acme): + for state,layers,backlog,labels,maturity,depth in itertools.product( + data['states'],(False,True),(False,True),(False,True),(False,True),(1,2,3)): + svg=render.render_svg(data,state_id=state['id'],sort_layers=layers, + show_backlog=backlog,labels=labels,show_maturity=maturity,depth=depth) + gs=groups(svg) + self.assertEqual(len(ET.fromstring(svg).findall('.//s:g[@data-id]',NS)),len(gs)) + records={str(r['id']):r for r in state['capabilities']} + coords={(r['layout'],r['first_level'],r['second_level'],r['third_level']):str(r['id']) for r in records.values()} + for ident,g in gs.items(): + r=records[ident] + if not r['second_level']:continue + parent=coords[(r['layout'],r['first_level'],r['second_level'] if r['third_level'] else 0,0)] + c,p=rect(g),rect(gs[parent]) + for axis,extent in [('x','width'),('y','height')]: + self.assertGreater(float(c[axis]),float(p[axis]),(ident,parent,layers,axis)) + self.assertLess(float(c[axis])+float(c[extent]),float(p[axis])+float(p[extent]),(ident,parent,layers,axis)) + # H branches and V-L3 must also retain DOM containment, so + # depth filters and exports cannot detach children. + if r['layout']=='horizontal' or r['third_level']: + self.assertIsNotNone(gs[parent].find(f"s:g[@data-id='{ident}']",NS)) + + def test_property_validation_and_missing(self): + for value in (42,True,[],{}): + data=copy.deepcopy(self.data);data['states'][0]['capabilities'][0]['property']=value + with self.assertRaisesRegex(ValueError,'property must be text'): + render.render_svg(data,sort_layers=True) + for value in (None,''): + data=copy.deepcopy(self.data);data['states'][0]['capabilities'][0]['property']=value + self.assertEqual(groups(render.render_svg(data,sort_layers=True))['sales'].get('data-layer'),'Not specified') + +class CycleLayersAndTags(unittest.TestCase): + def setUp(self): + self.data=copy.deepcopy(EXAMPLE) + for state in self.data['states']: + for r in state['capabilities']: + r.pop('property',None);r['layer']=None;r['tags']=[] + for ident,stage,labels in [('acquire','Planning',[]),('lead','Assurance',['MDM','Support']), + ('customer-risk','Execution',['ESG']),('checks','Assurance',['MDM'])]: + next(r for r in state['capabilities'] if r['id']==ident).update(layer=stage,tags=labels) + + def test_legacy_mapping_and_explicit_precedence_without_mutation(self): + data=copy.deepcopy(self.data);rows=data['states'][0]['capabilities'] + root=next(r for r in rows if r['id']=='sales');root.pop('layer');root['property']='MDM' + child=next(r for r in rows if r['id']=='acquire');child.update(property='Execution',layer='Planning') + before=copy.deepcopy(data);svg=render.render_svg(data,sort_layers=True);gs=groups(svg) + self.assertEqual(gs['sales'].get('data-layer'),'Not specified') + self.assertEqual(json.loads(gs['sales'].get('data-tags')),['MDM']) + self.assertEqual(gs['acquire'].get('data-layer'),'Planning') + self.assertEqual(json.loads(gs['acquire'].get('data-tags')),[]) + self.assertEqual(data,before) + self.assertFalse(ET.fromstring(svg).findall("s:rect[@data-layer-zone='MDM']",NS)) + self.assertIn('MDM',''.join(gs['sales'].find("s:text[@class='tag-label']",NS).itertext())) + + def test_filter_keeps_only_matches_ancestors_and_lane_context(self): + for state,layers,backlog,depth,tag in itertools.product(self.data['states'],(False,True),(False,True),(1,2,3),render.TAGS): + svg=render.render_svg(self.data,state_id=state['id'],sort_layers=layers,show_backlog=backlog,depth=depth,tag_filter=tag) + gs=groups(svg);expected={'MDM':{'lead','acquire','sales','checks','customer-risk','risk'}, + 'Support':{'lead','acquire','sales'},'ESG':{'customer-risk','sales','risk'}}[tag] + records={r['id']:r for r in state['capabilities']} + expected={i for i in expected if (3 if records[i]['third_level'] else 2 if records[i]['second_level'] else 1)<=depth} + self.assertEqual(set(gs),expected) + for ident,g in gs.items(): + self.assertEqual(g.get('data-tag-match'),'match' if tag in records[ident]['tags'] else 'context') + md=json.loads(ET.fromstring(svg).find('s:metadata',NS).text) + self.assertEqual(md['view']['tag_filter'],tag) + self.assertEqual(md['layer_vocabulary'],list(render.LAYERS)) + self.assertNotIn('data-applications=',svg) + # Tagging a root never makes its untagged descendants match. + next(r for r in self.data['states'][0]['capabilities'] if r['id']=='sales')['tags']=['Support'] + self.assertEqual(set(groups(render.render_svg(self.data,tag_filter='Support'))),{'lead','acquire','sales'}) + + def test_validation_positive_and_negative_and_empty_results(self): + for field,value,error in [('layer','MDM','layer'),('layer',42,'layer'),('tags','MDM','tags'), + ('tags',['other'],'tags'),('tags',[None],'tags'),('tags',['ESG','ESG'],'Duplicate')]: + data=copy.deepcopy(self.data);data['states'][0]['capabilities'][0][field]=value + with self.assertRaisesRegex(ValueError,error):render.render_svg(data) + for stage in render.LAYERS: + data=copy.deepcopy(self.data);data['states'][0]['capabilities'][0]['layer']=stage + self.assertEqual(groups(render.render_svg(data))['sales'].get('data-layer'),stage) + for state in self.data['states']: + for r in state['capabilities']:r['tags']=[] + svg=render.render_svg(self.data,sort_layers=True,tag_filter='MDM') + self.assertFalse(groups(svg));self.assertIn('No capabilities match tag MDM.',svg) + with self.assertRaisesRegex(ValueError,'Unknown tag filter'):render.render_svg(self.data,tag_filter='other') + + def test_acme_stages_tags_and_context_across_views(self): + data=json.loads((Path(__file__).resolve().parents[1]/'assets/example.json').read_text()) + self.assertEqual({r['layer'] for r in data['states'][0]['capabilities'] if r.get('layer')},set(render.LAYERS)) + for state,layers,backlog,depth,tag,labels,maturity in itertools.product(data['states'],(False,True),(False,True),(1,2,3),('',*render.TAGS),(False,True),(False,True)): + svg=render.render_svg(data,state_id=state['id'],sort_layers=layers,show_backlog=backlog,depth=depth,tag_filter=tag,labels=labels,show_maturity=maturity,legend=False) + root=ET.fromstring(svg);gs=groups(svg) + self.assertEqual(len(root.findall('.//s:g[@data-id]',NS)),len(gs)) + candidates=[r for r in state['capabilities'] if backlog or not + (r['layout']=='vertical' and not r['first_level'] or r['layout']=='horizontal' and r['second_level'] and not r['lane'])] + coords={(r['layout'],r['first_level'],r['second_level'],r['third_level']):r for r in candidates} + matches={r['id'] for r in candidates if not tag or tag in r.get('tags',[])} + expected=set(matches) + for r in candidates: + if r['id'] not in matches:continue + if r['second_level']:expected.add(coords[(r['layout'],r['first_level'],0,0)]['id']) + if r['third_level']:expected.add(coords[(r['layout'],r['first_level'],r['second_level'],0)]['id']) + if r['layout']=='horizontal' and r['second_level'] and r['lane']: + expected.add(coords[('vertical',r['lane'],0,0)]['id']) + expected={r['id'] for r in candidates if r['id'] in expected and (3 if r['third_level'] else 2 if r['second_level'] else 1)<=depth} + self.assertEqual(set(gs),expected) + for r in candidates: + if r['id'] not in gs:continue + g=gs[r['id']] + self.assertEqual(json.loads(g.get('data-tags')),r.get('tags',[])) + self.assertEqual(bool(g.find("s:text[@class='tag-label']",NS) is not None),bool(r.get('tags'))) + self.assertEqual(g.get('data-tag-match'),'match' if r['id'] in matches else 'context') + if not r['second_level']:continue + parent=coords[(r['layout'],r['first_level'],r['second_level'] if r['third_level'] else 0,0)] + c,p=rect(g),rect(gs[parent['id']]) + for axis,extent in [('x','width'),('y','height')]: + self.assertGreater(float(c[axis]),float(p[axis])) + self.assertLess(float(c[axis])+float(c[extent]),float(p[axis])+float(p[extent])) + self.assertFalse({z.get('data-layer-zone') for z in root.findall("s:rect[@class='layer-zone']",NS)}&set(render.TAGS)) + hroots=[rect(gs[r['id']]) for r in candidates if r['layout']=='horizontal' and not r['second_level'] and r['id'] in gs] + for first,second in zip(hroots,hroots[1:]): + self.assertLess(float(first['y'])+float(first['height']),float(second['y'])) + self.assertNotIn('data-applications=',svg) + + def test_all_html_tag_variants_equal_direct_builder_and_cli(self): + model=render.normalize(self.data,None);doc=render.render(self.data) + payload=json.loads(re.search(r'',doc).group(1)) + for embedded,state in zip(payload['states'],model['states']): + self.assertEqual(len(embedded['layouts']),64) + for layers,backlog,labels,maturity,tag in itertools.product((False,True),(False,True),(False,True),(False,True),('',*render.TAGS)): + key=':'.join(str(int(x)) for x in (layers,backlog,labels,maturity))+':'+tag + self.assertEqual(embedded['layouts'][key],render.build_svg(model,state,layers,backlog,labels,maturity,tag)) + with tempfile.TemporaryDirectory() as directory: + source=Path(directory)/'model.json';target=Path(directory)/'map.svg';source.write_text(json.dumps(self.data)) + result=subprocess.run([sys.executable,str(Path(render.__file__)),str(source),str(target),'--sort-layers','--tag','MDM'],capture_output=True,text=True) + self.assertEqual(result.returncode,0,result.stderr) + self.assertEqual(target.read_text(),render.render_svg(self.data,sort_layers=True,tag_filter='MDM')) + +class SystemCoverage(unittest.TestCase): + def setUp(self): + self.data=copy.deepcopy(EXAMPLE) + self.data['coverage_system_id']='app-crm' + for state in self.data['states']: + app=next(a for a in state['applications'] if a['id']=='app-crm') + app['capabilities']=['acquire'] + app['technical_capabilities']=[{'id':'tech-leads','name':'Lead intake','capabilities':['lead']}] + + def test_explicit_direct_and_technical_geometry_and_cutouts(self): + before=copy.deepcopy(self.data) + for layers,depth in itertools.product((False,True),(1,2,3)): + plain=render.render_svg(self.data,sort_layers=layers,depth=depth) + covered=render.render_svg(self.data,sort_layers=layers,depth=depth,coverage=True) + self.assertEqual(geometry(plain),geometry(covered)) + root=ET.fromstring(covered);overlays=root.findall("s:g[@class='coverage-overlay']",NS) + self.assertEqual(len(overlays),0 if depth==1 else 1) + if not overlays:continue + overlay=overlays[0] + self.assertEqual(overlay.get('data-coverage-depth'),str(depth)) + ids=json.loads(overlay.get('data-covered-capabilities')) + self.assertEqual(set(ids),{'acquire','lead'} if depth==3 else {'acquire'}) + sources=json.loads(overlay.get('data-coverage-sources')) + self.assertEqual(sources['direct_application'],['acquire']) + self.assertEqual(sources['technical_capabilities'],{'tech-leads':['lead']} if depth==3 else {}) + self.assertEqual(overlay.find("s:text[@class='coverage-system-name']",NS).text,'CRM') + polygon=overlay.find("s:polygon[@class='coverage-polygon']",NS) + points=[tuple(map(float,point.split(','))) for point in polygon.get('points').split()] + self.assertGreaterEqual(len(points),4) + self.assertLess(float(polygon.get('fill-opacity')),1) + self.assertEqual(overlay.get('pointer-events'),'none') + cutouts={r.get('data-excluded-capability') for r in overlay.findall('.//s:rect',NS)} + self.assertTrue(set(groups(covered))-set(ids)<=cutouts) + self.assertFalse(set(ids)&cutouts) + self.assertNotIn('data-applications=',covered) + self.assertEqual(self.data,before) + # Root mapping does not make unrelated children covered. + next(a for a in self.data['states'][0]['applications'] if a['id']=='app-crm')['capabilities']=['sales'] + svg=render.render_svg(self.data,coverage=True) + overlay=ET.fromstring(svg).find("s:g[@class='coverage-overlay']",NS) + ids=json.loads(overlay.get('data-covered-capabilities')) + self.assertEqual(set(ids),{'sales','lead'}) + self.assertNotIn('acquire',ids) + direct=groups(render.render_svg(self.data,coverage=True,system='app-crm')) + self.assertEqual(direct['lead'].get('data-support'),'not-specified') + self.assertEqual(direct['sales'].get('data-support'),'supported') + + def test_unlinked_box_inside_hull_is_cut_out(self): + records=[dict(id='root',name='Domain',layout='vertical',first_level=1,second_level=0,third_level=0,lane=0)] + for i in (1,2,3):records.append(dict(id=f'box-{i}',name=f'Ability {i}',layout='vertical',first_level=1,second_level=i,third_level=0,lane=0)) + data={'coverage_system_id':'system','capabilities':records,'applications':[{'id':'system','name':'System','capabilities':['box-1','box-3']}]} + svg=render.render_svg(data,coverage=True);root=ET.fromstring(svg);gs=groups(svg) + overlay=root.find("s:g[@class='coverage-overlay']",NS) + polygon=overlay.find("s:polygon[@class='coverage-polygon']",NS) + points=[tuple(map(float,p.split(','))) for p in polygon.get('points').split()] + b=rect(gs['box-2']);x=float(b['x'])+float(b['width'])/2;y=float(b['y'])+float(b['height'])/2 + self.assertTrue(all((v[0]-u[0])*(y-u[1])-(v[1]-u[1])*(x-u[0])>=-.1 for u,v in zip(points,points[1:]+points[:1]))) + hole=overlay.find(".//s:rect[@data-excluded-capability='box-2']",NS) + self.assertEqual(hole.get('fill'),'black') + self.assertLess(float(hole.get('x')),x);self.assertGreater(float(hole.get('x'))+float(hole.get('width')),x) + self.assertLess(float(hole.get('y')),y);self.assertGreater(float(hole.get('y'))+float(hole.get('height')),y) + self.assertNotIn('box-2',json.loads(overlay.get('data-covered-capabilities'))) + + def test_no_mapping_off_and_filtered_results(self): + for state in self.data['states']: + app=next(a for a in state['applications'] if a['id']=='app-crm') + app['capabilities']=[];app['technical_capabilities']=[] + root=ET.fromstring(render.render_svg(self.data,coverage=True)) + self.assertFalse(root.findall("s:g[@class='coverage-overlay']",NS)) + self.assertTrue(json.loads(root.find('s:metadata',NS).text)['view']['coverage']) + self.assertFalse(ET.fromstring(render.render_svg(self.data)).findall("s:g[@class='coverage-overlay']",NS)) + data=copy.deepcopy(EXAMPLE) + root=ET.fromstring(render.render_svg(data,coverage=True)) + self.assertEqual(json.loads(root.find('s:metadata',NS).text)['view']['coverage_system_ids'],sorted(str(a['id']) for a in data['states'][0]['applications'])) + + def test_invalid_pilot_and_technical_mappings(self): + data=copy.deepcopy(self.data);data['coverage_system_id']='missing' + with self.assertRaisesRegex(ValueError,'coverage_system_id'):render.render_svg(data) + for value in ({},[{}],[{'id':'x','name':'X','capabilities':['missing']}], + [{'id':'x','name':'X','capabilities':['lead','lead']}], + [{'id':'x','name':'X','capabilities':[]},{'id':'x','name':'X','capabilities':[]}]): + data=copy.deepcopy(self.data) + next(a for a in data['states'][0]['applications'] if a['id']=='app-crm')['technical_capabilities']=value + with self.assertRaises(ValueError):render.render_svg(data) + + def test_acme_coverage_across_filters_and_states(self): + data=json.loads((Path(__file__).resolve().parents[1]/'assets/example.json').read_text()) + for state,layers,depth,tag,backlog,labels in itertools.product(data['states'],(False,True),(1,2,3),('',*render.TAGS),(False,True),(False,True)): + svg=render.render_svg(data,state_id=state['id'],sort_layers=layers,depth=depth,tag_filter=tag,show_backlog=backlog,labels=labels,coverage=True) + gs=groups(svg);app=next(a for a in state['applications'] if a['id']==data['coverage_system_id']) + expected=(set(app['capabilities'])|{i for t in app['technical_capabilities'] for i in t['capabilities']})&gs.keys() + root=ET.fromstring(svg);overlays=root.findall("s:g[@class='coverage-overlay']",NS) + self.assertEqual(len(overlays),int(bool(expected))) + if expected: + overlay=overlays[0] + self.assertEqual(set(json.loads(overlay.get('data-covered-capabilities'))),expected) + self.assertEqual(overlay.get('data-coverage-system'),data['coverage_system_id']) + # An unlinked inventory-master-data card must be cut out in + # Current, even if its geometry is near the hull boundary. + excluded={r.get('data-excluded-capability') for r in overlay.findall('.//s:rect',NS)} + self.assertEqual(set(gs)-expected,excluded) + md=json.loads(root.find('s:metadata',NS).text) + self.assertTrue(md['view']['coverage']) + self.assertEqual(md['view']['coverage_system_id'],data['coverage_system_id']) + + +class MultiSystemCoverage(unittest.TestCase): + def setUp(self): + self.data=json.loads((Path(render.__file__).parent.parent/'assets/example.json').read_text()) + self.ids=['DEMO-APPLICATION-DATA','DEMO-APPLICATION-GOVERNANCE','DEMO-APPLICATION-WAREHOUSE'] + + def test_selection_overlap_colors_masks_and_geometry(self): + for state,layers in itertools.product(self.data['states'],(False,True)): + model=render.normalize(self.data,None);st=next(s for s in model['states'] if s['id']==state['id']) + base=render.build_svg(model,st,layers,tag_filter='MDM') + plain=render.prune_export(render.apply_view(base,st)) + for depth,selected in itertools.product((1,2,3),([],self.ids[:1],self.ids[:2],self.ids)): + svg=render.prune_export(render.apply_view(base,st,depth=depth,coverage=True,coverage_systems=selected)) + root=ET.fromstring(svg);overlays=root.findall("s:g[@class='coverage-overlay']",NS) + gs=groups(svg);md=json.loads(root.find('s:metadata',NS).text) + self.assertEqual(md['view']['coverage_system_ids'],sorted(selected)) + self.assertEqual(geometry(svg),{k:v for k,v in geometry(plain).items() if int(groups(plain)[k].get('data-depth'))<=depth}) + masks=[m.get('id') for m in root.findall('.//s:mask',NS)] + self.assertEqual(len(masks),len(set(masks))) + colors=[] + for overlay in overlays: + aid=overlay.get('data-coverage-system');self.assertIn(aid,selected) + app=next(a for a in state['applications'] if str(a['id'])==aid) + expected=(set(app.get('capabilities',[]))|{i for t in app.get('technical_capabilities',[]) for i in t['capabilities']}) & gs.keys() + self.assertEqual(set(json.loads(overlay.get('data-covered-capabilities'))),expected) + poly=overlay.find("s:polygon[@class='coverage-polygon']",NS);color=poly.get('fill');colors.append(color) + self.assertEqual(color,md['coverage_colors'][aid]) + self.assertIn(poly.get('mask')[5:-1],masks) + self.assertEqual(len(colors),len(set(colors))) + if depth==3 and len(selected)==3 and state['kind']!='historical': + self.assertEqual(len(overlays),3) + shared=set.intersection(*(set(json.loads(g.get('data-covered-capabilities'))) for g in overlays)) + self.assertIn('DEMO-CAPABILITY-H3.2.1',shared) + self.assertIn('DEMO-CAPABILITY-H3.1',shared) + + def test_invalid_and_empty_selections_and_master_switch(self): + for selected in ('bad',['missing'],[self.ids[0],self.ids[0]],[1]): + with self.assertRaises(ValueError):render.render_svg(self.data,coverage=True,coverage_systems=selected) + for on,selected in ((True,[]),(False,self.ids)): + root=ET.fromstring(render.render_svg(self.data,coverage=on,coverage_systems=selected)) + self.assertFalse(root.findall("s:g[@class='coverage-overlay']",NS)) + root=ET.fromstring(render.render_svg(self.data,coverage=True,coverage_systems=['DEMO-APPLICATION-ESG'])) + self.assertFalse(root.findall("s:g[@class='coverage-overlay']",NS)) + colors=render.coverage_colors(render.normalize(self.data,None)) + self.assertEqual(len(colors),len(set(colors.values()))) + + def test_cli_repeated_system_selection(self): + with tempfile.TemporaryDirectory() as directory: + source=Path(directory)/'model.json';target=Path(directory)/'map.svg';source.write_text(json.dumps(self.data)) + command=[sys.executable,str(Path(render.__file__)),str(source),str(target)] + failed=subprocess.run(command+['--coverage-system',self.ids[0]],capture_output=True,text=True) + self.assertNotEqual(failed.returncode,0) + good=subprocess.run(command+['--coverage','--coverage-system',self.ids[0],'--coverage-system',self.ids[1]],capture_output=True,text=True) + self.assertEqual(good.returncode,0,good.stderr) + root=ET.fromstring(target.read_text()) + self.assertEqual({g.get('data-coverage-system') for g in root.findall("s:g[@class='coverage-overlay']",NS)},set(self.ids[:2])) + + +class DateTimeline(unittest.TestCase): + def setUp(self): + self.data={'states':[{'id':'year','label':'Recorded year','kind':'current','as_of':'2026-06-15', + 'effective_from':'2026-01-01','effective_to':'2027-01-01', + 'capabilities':[ + {'id':'root','name':'Domain','layout':'vertical','first_level':1,'second_level':0,'third_level':0,'lane':0,'maturity':[{'change_date':'2026-01-01','level':1},{'change_date':'2026-03-01','level':2}]}, + {'id':'child','name':'Business ability','layout':'vertical','first_level':1,'second_level':1,'third_level':0,'lane':0,'start_date':'2026-04-01','end_date':'2026-06-30'}, + {'id':'leaf','name':'Nested ability','layout':'vertical','first_level':1,'second_level':1,'third_level':1,'lane':0,'start_date':'2026-05-01','end_date':'2026-06-30'}], + 'applications':[{'id':'app','name':'System','start_date':'2026-03-01','end_date':'2026-10-31','capabilities':['child'], + 'technical_capabilities':[{'id':'tech','name':'Technical ability','start_date':'2026-05-01','end_date':'2026-05-31','capabilities':['leaf']}]}]}]} + + def test_date_boundaries_lifetimes_maturity_and_coverage(self): + for when,expected,covered,level in [ + ('2026-01-01',{'root'},set(),'Initial'),('2026-03-31',{'root'},set(),'Managed'), + ('2026-04-01',{'root','child'},{'child'},'Managed'), + ('2026-05-15',{'root','child','leaf'},{'child','leaf'},'Managed'), + ('2026-06-01',{'root','child','leaf'},{'child'},'Managed'), + ('2026-06-30',{'root','child','leaf'},{'child'},'Managed'), + ('2026-07-01',{'root'},set(),'Managed'),('2026-12-31',{'root'},set(),'Managed')]: + for layers in (False,True): + svg=render.render_svg(self.data,view_date=when,coverage=True,show_maturity=True,sort_layers=layers) + self.assertEqual(set(groups(svg)),expected) + root=ET.fromstring(svg);md=json.loads(root.find('s:metadata',NS).text) + self.assertEqual(md['view_date'],when);self.assertEqual(md['as_of'],when) + self.assertEqual(md['view']['view_date'],when) + self.assertEqual(md['snapshot_as_of'],'2026-06-15') + overlays=root.findall("s:g[@class='coverage-overlay']",NS) + self.assertEqual(set().union(*(set(json.loads(g.get('data-covered-capabilities'))) for g in overlays)),covered) + self.assertIn(level,' '.join(root.itertext())) + for when in ('2025-12-31','2027-01-01','2029-01-01','invalid'): + with self.assertRaises(ValueError):render.render_svg(self.data,view_date=when) + + def test_period_validation_and_gaps(self): + for edits in ({'effective_to':'2026-01-01'},{'effective_from':None},{'effective_from':'bad'}): + data=copy.deepcopy(self.data);data['states'][0].update(edits) + with self.assertRaises(ValueError):render.normalize(data) + data=copy.deepcopy(self.data);second=copy.deepcopy(data['states'][0]);second.update(id='next',kind='target',effective_from='2026-12-31',effective_to='2028-01-01');data['states'].append(second) + with self.assertRaisesRegex(ValueError,'overlap'):render.normalize(data) + second['effective_from']='2027-02-01' + with self.assertRaisesRegex(ValueError,'No state data'):render.render_svg(data,view_date='2027-01-15') + svg=render.render_svg(data,view_date='2027-02-01');root=ET.fromstring(svg) + self.assertEqual(json.loads(root.find('s:metadata',NS).text)['state_kind'],'target') + self.assertIn('Planned scenario',' '.join(root.itertext())) + with self.assertRaisesRegex(ValueError,'does not apply'):render.render_svg(data,view_date='2027-02-01',state_id='year') + for path in ('app','tech'): + bad=copy.deepcopy(self.data);item=bad['states'][0]['applications'][0] + if path=='tech':item=item['technical_capabilities'][0] + item.update(start_date='2027-01-01',end_date='2026-01-01') + with self.assertRaisesRegex(ValueError,'reversed lifetime'):render.normalize(bad) + bad=copy.deepcopy(self.data);bad['states'][0]['capabilities'][0]['end_date']='2026-04-30' + with self.assertRaisesRegex(ValueError,'inactive parent'):render.timeline_frames(render.normalize(bad)) + + def test_frames_match_arbitrary_dates_without_daily_interpolation(self): + model=render.normalize(self.data);frames=render.timeline_frames(model) + self.assertEqual([s['frame_from'].isoformat() for s in frames],['2026-01-01','2026-03-01','2026-04-01','2026-05-01','2026-06-01','2026-07-01','2026-11-01']) + for frame in frames: + last=(frame['frame_to'] or render.date('2027-01-01'))-render.dt.timedelta(days=1) + actual=render.state_on(model,last) + self.assertEqual([r['id'] for r in frame['records']],[r['id'] for r in actual['records']]) + self.assertEqual(frame['applications'],actual['applications']) + self.assertEqual([render.maturity(r,frame['as_of']) for r in frame['records']],[render.maturity(r,last) for r in actual['records']]) + # Legacy snapshots still work but cannot silently stand in for a dated timeline. + with self.assertRaisesRegex(ValueError,'No state data'):render.render_svg(EXAMPLE,view_date='2026-10-23') + + def test_acme_history_current_future_and_exact_date_exports(self): + data=json.loads((Path(render.__file__).parent.parent/'assets/example.json').read_text());model=render.normalize(data) + for when,expected in [('2026-06-15','historical'),('2026-10-01','current'),('2026-10-23','current'),('2027-06-15','target')]: + st=render.state_on(model,when);self.assertEqual(st['id'],expected) + for layers in (False,True): + svg=render.render_svg(data,view_date=when,sort_layers=layers,coverage=True,coverage_systems=['DEMO-APPLICATION-DATA'],tag_filter='MDM') + self.assertIn(when,' '.join(ET.fromstring(svg).itertext())) + self.assertEqual('DEMO-CAPABILITY-H3.2.1' in groups(svg),when>='2026-10-22') + for when in ('2026-05-31','2028-01-01'): + with self.assertRaisesRegex(ValueError,'No state data'):render.render_svg(data,view_date=when) + with tempfile.TemporaryDirectory() as directory: + source=Path(directory)/'model.json';target=Path(directory)/'map.svg';source.write_text(json.dumps(data)) + command=[sys.executable,str(Path(render.__file__)),str(source),str(target),'--date','2027-06-15'] + result=subprocess.run(command,capture_output=True,text=True);self.assertEqual(result.returncode,0,result.stderr) + self.assertEqual(target.read_text(),render.render_svg(data,view_date='2027-06-15')) + + +class ContextLegend(unittest.TestCase): + def setUp(self): + self.data=copy.deepcopy(EXAMPLE);self.data['coverage_system_id']='app-crm' + + def test_default_empty_footer_and_metadata_provenance(self): + root=ET.fromstring(render.render_svg(self.data)) + legend=root.find("s:g[@class='legend']",NS) + self.assertEqual(len(legend),0) + self.assertEqual(float(root.get('height')),float(root.get('data-content-bottom'))+20) + visible=' '.join(''.join(n.itertext()) for n in root.findall('.//s:text',NS)) + for text in ('Model revision:','Methodology baseline:','Adapter:','Renderer:','View adapter only'): + self.assertNotIn(text,visible) + md=json.loads(root.find('s:metadata',NS).text) + self.assertEqual(md['renderer_version'],render.RENDERER_VERSION) + self.assertIn('not full methodology conformance',md['view_contract']) + self.assertIn('Missing mapping',md['mapping_semantics']) + + def test_enabled_mode_entries_and_legend_off(self): + for maturity,labels,coverage in itertools.product((False,True),repeat=3): + svg=render.render_svg(self.data,show_maturity=maturity,labels=labels,coverage=coverage) + root=ET.fromstring(svg);text=' '.join(root.find("s:g[@class='legend']",NS).itertext()) + self.assertEqual('Maturity:' in text,maturity) + self.assertEqual('System labels:' in text,labels) + self.assertEqual('Coverage:' in text,coverage) + self.assertNotIn('Outline:',text) + if coverage:self.assertIn('area is not a percentage',text) + hidden=ET.fromstring(render.render_svg(self.data,show_maturity=maturity,labels=labels,coverage=coverage,legend=False)) + self.assertFalse(hidden.findall("s:g[@class='legend']",NS)) + self.assertEqual(float(hidden.get('height')),float(hidden.get('data-content-bottom'))+20) + self.assertEqual(geometry(svg),geometry(ET.tostring(hidden,encoding='unicode'))) + text=' '.join(ET.fromstring(render.render_svg(self.data,system='app-crm',sort_layers=True)).find("s:g[@class='legend']",NS).itertext()) + self.assertIn('Outline:',text);self.assertIn('Bands:',text) + + def test_maturity_visual_key_samples_and_footer_bounds(self): + shown=render.render_svg(self.data,show_maturity=True) + root=ET.fromstring(shown);tiles=root.findall(".//s:g[@class='maturity-legend-item']",NS) + self.assertEqual([t.get('data-maturity-level') for t in tiles],list(map(str,range(6)))) + for i,tile in enumerate(tiles): + sample=tile.find('s:rect',NS) + self.assertIn('caprect',sample.get('class').split());self.assertIn(f'm{i}',sample.get('class').split()) + self.assertEqual(sample.get('stroke-width'),'3') + self.assertIn(render.LEVELS[i],''.join(tile.itertext())) + self.assertIn(render.MATURITY_LEGEND[i]['description'],''.join(tile.itertext())) + self.assertLess(float(sample.get('x'))+float(sample.get('width')),float(root.get('width'))) + self.assertLess(float(sample.get('y'))+float(sample.get('height')),float(root.get('height'))) + for kwargs in ({},{'show_maturity':True,'legend':False},{'show_maturity':False}): + hidden=ET.fromstring(render.render_svg(self.data,**kwargs)) + self.assertFalse(hidden.findall(".//s:g[@class='maturity-legend-item']",NS)) + hidden=render.render_svg(self.data,show_maturity=True,legend=False) + self.assertEqual(geometry(shown),geometry(hidden)) + self.assertGreater(float(root.get('height')),float(ET.fromstring(hidden).get('height'))) + + def test_unmapped_coverage_and_context_filter(self): + data=copy.deepcopy(self.data) + for state in data['states']: + next(a for a in state['applications'] if a['id']=='app-crm')['capabilities']=[] + next(r for r in state['capabilities'] if r['id']=='lead')['tags']=['MDM'] + root=ET.fromstring(render.render_svg(data,coverage=True,tag_filter='MDM')) + text=' '.join(root.find("s:g[@class='legend']",NS).itertext()) + self.assertIn('Muted boxes:',text);self.assertNotIn('Coverage:',text) + for state in data['states']: + for record in state['capabilities']: + record['tags']=[t for t in record.get('tags',[]) if t!='ESG'] + if record.get('property')=='ESG':record['property']=None + root=ET.fromstring(render.render_svg(data,coverage=True,tag_filter='ESG')) + self.assertEqual(len(root.find("s:g[@class='legend']",NS)),0) + + +class CoverageShapes(unittest.TestCase): + def test_rectangular_and_independent_rounding(self): + hull=[(0,0),(100,0),(100,50),(40,80),(0,50)] + self.assertEqual(render.coverage_shape_points(hull),hull) + rectangle=render.coverage_shape_points(hull,'rectangular') + self.assertEqual(rectangle,[(0,0),(100,0),(100,80),(0,80)]) + for shape,count in [('angled',len(hull)),('rectangular',4)]: + rounded=render.coverage_shape_points(hull,shape,True) + self.assertEqual(len(rounded),count*9) + self.assertTrue(all(0<=x<=100 and 0<=y<=80 for x,y in rounded)) + self.assertNotIn((0,0),rounded) + with self.assertRaisesRegex(ValueError,'coverage shape'):render.coverage_shape_points(hull,'circle') + + def test_native_shapes_masks_overlap_and_restore(self): + data=json.loads((Path(render.__file__).parent.parent/'assets/example.json').read_text()) + ids=['APPLICATION-CRM-1','APPLICATION-OMS-1','DEMO-APPLICATION-GOVERNANCE'] + for shape,rounded,layers,depth in itertools.product(('angled','rectangular'),(False,True),(False,True),(2,3)): + svg=render.render_svg(data,view_date='2026-10-23',show_backlog=False,coverage=True,coverage_systems=ids,functional_overlap=True,coverage_shape=shape,round_coverage=rounded,sort_layers=layers,depth=depth) + root=ET.fromstring(svg);md=json.loads(root.find('s:metadata',NS).text) + self.assertEqual(md['view']['coverage_shape'],shape);self.assertEqual(md['view']['round_coverage'],rounded) + self.assertTrue(root.findall(".//s:g[@class='functional-overlap-region']",NS)) + for g in root.findall("s:g[@class='coverage-overlay']",NS): + polygon=g.find("s:polygon[@class='coverage-polygon']",NS) + self.assertEqual(polygon.get('points'),g.find('s:defs/s:mask/s:polygon',NS).get('points')) + hull=[tuple(map(float,p.split(','))) for p in polygon.get('data-coverage-hull').split()] + expected=render.coverage_shape_points(hull,shape,rounded) + self.assertEqual(polygon.get('points'),' '.join(f'{x:.4f},{y:.4f}' for x,y in expected)) + render.apply_coverage_shape(root,'angled',False) + for g in root.findall("s:g[@class='coverage-overlay']",NS): + p=g.find("s:polygon[@class='coverage-polygon']",NS) + actual=[tuple(map(float,v.split(','))) for v in p.get('points').split()] + expected=[tuple(map(float,v.split(','))) for v in p.get('data-coverage-hull').split()] + self.assertEqual(actual,expected) + with self.assertRaisesRegex(ValueError,'coverage shape'):render.render_svg(data,coverage_shape='circle') + +class FunctionalOverlap(unittest.TestCase): + def setUp(self): + self.data=copy.deepcopy(EXAMPLE) + for state in self.data['states']: + state['applications']=[{'id':'a','name':'System A <&>','capabilities':['acquire'],'technical_capabilities':[{'id':'t1','name':'First ability','capabilities':['acquire']}]}, + {'id':'b','name':'System B','capabilities':['lead'],'technical_capabilities':[{'id':'t2','name':'Second ability','capabilities':['acquire']}]}, + {'id':'c','name':'System C','capabilities':['acquire']}] + + def test_adjacent_acme_domains_do_not_overlap_from_padding(self): + data=json.loads((Path(render.__file__).parent.parent/'assets/example.json').read_text()) + ids=['APPLICATION-CRM-1','APPLICATION-OMS-1'] + for layers,depth in itertools.product((False,True),(1,2,3)): + svg=render.render_svg(data,view_date='2026-10-23',sort_layers=layers,depth=depth,show_backlog=False,coverage=True,coverage_systems=ids,functional_overlap=True) + root=ET.fromstring(svg) + overlays=root.findall("s:g[@class='coverage-overlay']",NS) + self.assertEqual(len(overlays),2) + hulls=[[tuple(map(float,p.split(','))) for p in g.find("s:polygon[@class='coverage-polygon']",NS).get('points').split()] for g in overlays] + self.assertLess(max(x for x,y in hulls[1]),min(x for x,y in hulls[0])) + self.assertFalse(root.findall("s:g[@class='functional-overlap']",NS)) + self.assertEqual(json.loads(root.find('s:metadata',NS).text)['view']['functional_overlap_system_pairs'],[]) + + def test_convex_polygon_intersections(self): + square=[(0,0),(10,0),(10,10),(0,10)] + self.assertEqual(render.polygon_intersection(square,[(20,0),(30,0),(30,10),(20,10)]),[]) + self.assertEqual(render.polygon_intersection(square,[(10,0),(20,0),(20,10),(10,10)]),[]) + overlap=render.polygon_intersection(square,[(5,-5),(15,-5),(15,5),(5,5)]) + self.assertEqual(set(overlap),{(5,0),(10,0),(10,5),(5,5)}) + inner=[(2,2),(8,2),(8,8),(2,8)] + self.assertEqual(set(render.polygon_intersection(square,inner)),set(inner)) + + def test_polygon_regions_and_union_boundary(self): + plain=render.render_svg(self.data,coverage=True,coverage_systems=['a','b','c']) + svg=render.render_svg(self.data,coverage=True,coverage_systems=['a','b','c'],functional_overlap=True) + self.assertEqual(geometry(plain),geometry(svg)) + root=ET.fromstring(svg);regions=root.findall(".//s:g[@class='functional-overlap-region']",NS) + self.assertEqual(len(regions),3) + self.assertFalse(root.findall("s:g[@class='functional-overlap']/s:rect",NS)) + boundary=root.find(".//s:g[@class='functional-overlap-outline']",NS) + self.assertEqual(boundary.get('filter'),'url(#functional-overlap-edge)') + for pair in regions: + self.assertEqual(len(json.loads(pair.get('data-overlap-systems'))),2) + self.assertIsNone(pair.get('mask')) + self.assertFalse(pair.findall('.//*[@mask]')) + self.assertTrue(pair.find('s:polygon',NS).get('points')) + self.assertIn('Red contour:',' '.join(root.find("s:g[@class='legend']",NS).itertext())) + + def test_box_cutouts_do_not_change_the_outer_overlap_boundary(self): + svg=render.render_svg(self.data,coverage=True,coverage_systems=['a','b','c'],functional_overlap=True) + root=ET.fromstring(svg) + self.assertTrue(root.findall(".//s:rect[@class='coverage-cutout']",NS)) + boundary=root.find("s:g[@class='functional-overlap']",NS) + before=ET.tostring(boundary) + for hole in root.findall(".//s:rect[@class='coverage-cutout']",NS): + hole.set('width','10000');hole.set('height','10000') + render.update_functional_overlap(root,{},True) + self.assertEqual(ET.tostring(root.find("s:g[@class='functional-overlap']",NS)),before) + + def test_off_single_system_and_coverage_master(self): + for coverage,flag,ids in ((True,False,['a','b']),(False,True,['a','b']),(True,True,['a']),(True,True,[])): + root=ET.fromstring(render.render_svg(self.data,coverage=coverage,functional_overlap=flag,coverage_systems=ids)) + self.assertFalse(root.findall("s:g[@class='functional-overlap']",NS)) + md=json.loads(root.find('s:metadata',NS).text) + self.assertFalse(md['view']['functional_overlap']);self.assertEqual(md['view']['functional_overlap_system_pairs'],[]) + root=ET.fromstring(render.render_svg(self.data,coverage=True,coverage_systems=['a','b'],functional_overlap=True,legend=False)) + self.assertEqual(len(root.findall(".//s:g[@class='functional-overlap-region']",NS)),1) + self.assertFalse(root.findall("s:g[@class='legend']",NS)) + + def test_acme_date_depth_and_filters(self): + data=json.loads((Path(render.__file__).parent.parent/'assets/example.json').read_text());model=render.normalize(data) + ids=['DEMO-APPLICATION-DATA','DEMO-APPLICATION-GOVERNANCE','DEMO-APPLICATION-WAREHOUSE'] + for when,layers,depth,tag in itertools.product(('2026-06-15','2026-10-21','2026-10-23','2027-01-01'),(False,True),(1,2,3),('', 'MDM','ESG')): + state=render.state_on(model,when) + svg=render.render_svg(data,view_date=when,sort_layers=layers,depth=depth,tag_filter=tag,show_backlog=False,coverage=True,coverage_systems=ids,functional_overlap=True) + root=ET.fromstring(svg) + active=root.findall("s:g[@class='coverage-overlay'][@data-coverage-visible='yes']",NS) + expected=[] + for i,left in enumerate(active): + for right in active[i+1:]: + points=[[tuple(map(float,p.split(','))) for p in g.find("s:polygon[@class='coverage-polygon']",NS).get('points').split()] for g in (left,right)] + if render.polygon_intersection(*points):expected.append(sorted([left.get('data-coverage-system'),right.get('data-coverage-system')])) + regions=root.findall(".//s:g[@class='functional-overlap-region']",NS) + actual=[json.loads(n.get('data-overlap-systems')) for n in regions] + self.assertEqual(actual,expected) + self.assertEqual(json.loads(root.find('s:metadata',NS).text)['view']['functional_overlap_system_pairs'],expected) + with tempfile.TemporaryDirectory() as directory: + source=Path(directory)/'model.json';target=Path(directory)/'map.svg';source.write_text(json.dumps(data)) + command=[sys.executable,str(Path(render.__file__)),str(source),str(target),'--functional-overlap'] + bad=subprocess.run(command,capture_output=True,text=True);self.assertNotEqual(bad.returncode,0) + good=subprocess.run(command+['--coverage','--coverage-system',ids[0],'--coverage-system',ids[1]],capture_output=True,text=True) + self.assertEqual(good.returncode,0,good.stderr) + self.assertTrue(ET.fromstring(target.read_text()).findall(".//s:g[@class='functional-overlap-region']",NS)) + +if __name__ == '__main__': + unittest.main() From 275b7456ae36f71b1e270e012e59224e9bb7523d Mon Sep 17 00:00:00 2001 From: transitrix Date: Sun, 8 Nov 2026 00:20:44 +0400 Subject: [PATCH 26/26] Declare requirements analysis skill files --- publish-manifest.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/publish-manifest.json b/publish-manifest.json index d56362c5..c4132df8 100644 --- a/publish-manifest.json +++ b/publish-manifest.json @@ -861,6 +861,8 @@ "transitrix/skills/report/README.md", "transitrix/skills/report/SKILL.md", "transitrix/skills/report/scripts/report.py", + "transitrix/skills/requirements-analysis/README.md", + "transitrix/skills/requirements-analysis/SKILL.md", "transitrix/skills/status/README.md", "transitrix/skills/status/SKILL.md" ]