sa-validate
/sa-validate
Validate specification consistency through Neo4j Cypher queries. Internal validation (L1-L13): data consistency, model connectivity, requirement completeness, form-domain traceability, UC-form validation, cross-module consistency, FeatureRequest consistency, staleness closure, decision provenance, screen state machines, behavior slices, domain error taxonomy, cache & degradation policies (SA-extension connectivity). Cross-validation BA->SA (XL6-XL9): UC coverage, entity coverage, role coverage, rule coverage. Use when: validate specification, check consistency, find errors, run checks, quality
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 28.09.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
Validate specification consistency through Neo4j Cypher queries. Internal validation (L1-L13): data consistency, model connectivity, requirement completeness, form-domain traceability, UC-form validation, cross-module consistency, FeatureRequest consistency, staleness closure, decision provenance, screen state machines, behavior slices, domain error taxonomy, cache & degradation policies (SA-extension connectivity). Cross-validation BA->SA (XL6-XL9): UC coverage, entity coverage, role coverage, rule coverage. Use when: validate specification, check consistency, find errors, run checks, quality
Original author description
Validate specification consistency through Neo4j Cypher queries. Internal validation (L1-L13): data consistency, model connectivity, requirement completeness, form-domain traceability, UC-form validation, cross-module consistency, FeatureRequest consistency, staleness closure, decision provenance, screen state machines, behavior slices, domain error taxonomy, cache & degradation policies (SA-extension connectivity). Cross-validation BA->SA (XL6-XL9): UC coverage, entity coverage, role coverage, rule coverage. Use when: validate specification, check consistency, find errors, run checks, quality
How it works
- Purpose
- Neo4j Tools
- Invocation
- Workflow Overview
- Schema Reference
- Pre-flight Checks
- Severity Levels
- Validation Levels -- Internal (L1-L13)
- Validation Levels -- Cross-Layer (XL6-XL9)
- Execution Procedure
SKILL.md preview
---
name: sa-validate
model: opus
effort: high
description: |
Validate specification consistency through Neo4j Cypher queries.
Internal validation (L1-L13): data consistency, model connectivity, requirement completeness,
form-domain traceability, UC-form validation, cross-module consistency, FeatureRequest consistency,
staleness closure, decision provenance, screen state machines, behavior slices,
domain error taxonomy, cache & degradation policies (SA-extension connectivity).
Cross-validation BA->SA (XL6-XL9): UC coverage, entity coverage, role coverage, rule coverage.
Use when: validate specification, check consistency, find errors, run checks, quality gate.
---
# /nacl:sa-validate -- Specification Validation (Graph)
## Purpose
Quality gate for the entire specification. Runs Cypher queries against Neo4j to detect problems
in data consistency, model connectivity, requirement completeness, form-domain traceability,
and BA-to-SA cross-layer coverage. All checks are read-only -- validation never modifies data.
**Shared references:** `${CLAUDE_PLUGIN_ROOT}/nacl-core/SKILL.md`
---
## Neo4j Tools
| Tool | Usage |
|------|-------|
| `mcp__neo4j__read-cypher` | ALL validation queries (read-only) |
| `mcp__neo4j__get-schema` | Introspect current graph schema before running checks |
IMPORTANT: This skill uses ONLY read-cypher. Validation must NEVER write to the graph.
---
## Invocation
```
/nacl:sa-validate [level] [--scope=<scope>]
```
### Parameters
| Parameter | Values | Description |
|-----------|--------|-------------|
| `level` | `internal` | L1-L13: SA-internal consistency checks (incl. L8 staleness, L9 decision provenance, L10 screen state machines, L11 behavior slices, L12 domain error taxonomy, L13 cache & degradation policies) |
| | `ba-cross` | XL6-XL9: BA-to-SA cross-layer coverage |
| | `full` (default) | All levels: L1-L13 + XL6-XL9 |
| `--scope` | `intra-uc UC-NNN[,UC-NNN]` | Limit validation to specific UCs and their subgraph (forms, fields, requirements, entities). Used by nacl-sa-feature for incremental validation. |
| | `intra-module mod-xxx` | Limit validation to a specific module's nodes. |
When `--scope` is provided, all Cypher queries are augmented with a WHERE clause filtering to the specified UC or module subgraph. Checks outside the scope are skipped.
---
## Workflow Overview
```
LAUNCH VALIDATION
|
+----------+-----------+
| |
[level = internal] [level = ba-cross]
[level = full] [level = full]
| |
+---------+---------+ +-------+-------+
| L1: Data | | XL6: UC |
| Consistency | | Coverage |
+---------+---------+ +-------+-------+
| |
+---------+---------+ +-------+-------+
| L2: Model | | XL7: Entity |
| Connectivity | | Coverage |
+---------+---------+ +-------+-------+
| |
+---------+---------+ +-------+-------+
| L3: Requirement | | XL8: Role |
| Completeness | | Coverage |
+---------+---------+ +-------+-------+
| |
+---------+---------+ +-------+-------+
| L4: Form-Domain | | XL9: Rule |
| Traceability | | Coverage |
+---------+---------+ +-------+-------+
| |
+---------+---------+ |
| L5: UC-Form | |
| Validation | |
+---------+---------+ |
| |
+---------+---------+ |
| L6: Cross-Module | |
| Consistency | |
+---------+---------+ |
| |
+---------+---------+ |
| L7: FeatureReq | |
| Consistency | |
+---------+---------+ |
| |
+---------+---------+ |
| L8: Staleness | |
| Closure | |
+---------+---------+ |
| |
+---------+---------+ |
| L9: Decision | |
| Provenance | |
+---------+---------+ |
| |
+---------+---------+ |
| L10: Screen | |
| State Machines | |
+---------+---------+ |
| |
+---------+---------+ |
| L11: Behavior | |
| Slices | |
+---------+---------+ |
| |
+---------+---------+ |
| L12: Domain | |
| Error Taxonomy | |
+---------+---------+ |
| |
+---------+---------+ |
| L13: Cache & | |
| Degradation | |
+---------+---------+ |
| |
+----------+-----------+
|
+----------+-----------+
| GENERATE REPORT |
+----------------------+
```
---
## Schema Reference
This skill assumes the **canonical SA schema** as defined in `graph-infra/schema/sa-schema.cypher` and produced by:
- `/nacl:sa-architect` -- writes `:Module`, `:Component`, edge `(:Module)-[:CONTAINS_UC]->(:UseCase)`, `(:Module)-[:CONTAINS_ENTITY]->(:DomainEntity)`
- `/nacl:sa-domain` -- writes `:DomainEntity`, `:DomainAttribute`, `:Enumeration`, `:EnumValue` (with `.value` property)
- `/nacl:sa-uc` -- writes `:UseCase`, `:Requirement`, `:Form`, `:FormField`, `:ActivityStep`; `slices` command writes `:Slice` with edges `HAS_SLICE`, `COVERS`, `CALLS`, `VERIFIED_BY` (see `graph-infra/schema/sa-schema.cypher` § 3-ter; note the `CALLS` name is shared with `ScreenEffect→APIEndpoint` — every L11 query label-qualifies the source as `(sl:Slice)`); `errors` command writes `:DomainError`, `:ErrorPresentation` with edges `HAS_ERROR`, `MAY_RAISE`, `HANDLES`, `PRESENTED_AS`, `SHOWS` (see § 3-quater; all five names are unshared — no label-qualification hazard); `resilience` command writes `:CachePolicy`, `:DegradationRule` with edges `HAS_CACHE`, `CACHES`, `HAS_DEGRADATION`, `ON_ERROR`, `DEGRADES_TO` (see § 3-quinquies; all five names again unshared)
- `/nacl:sa-roles` -- writes `:SystemRole`
- `/nacl:sa-ui` -- writes `:Component`, `:FormField`; `state-machine` command writes `:Screen`, `:ScreenState`, `:ScreenEvent`, `:Transition`, `:ScreenEffect`, `:AnalyticsEvent` with edges `HAS_SCREEN`, `RENDERS`, `HAS_STATE`, `HAS_EVENT`, `HAS_TRANSITION`, `FROM_STATE`, `TO_STATE`, `ON_EVENT`, `TRIGGERS`, `CALLS`, `NAVIGATES_TO`, `EMITS` (see `graph-infra/schema/sa-schema.cypher` § 3-bis; note `HAS_STATE`/`TRIGGERS` names are shared with the BA layer — every L10 query is label-qualified)
- BA->SA handoff edges (canonical names): `AUTOMATES_AS`, `REALIZED_AS`, `IMPLEMENTED_BY`, `MAPPED_TO`, `TYPED_AS`, `SUGGESTS`
- Provenance (canonical names, written by `/nacl:sa-feature`, `/nacl:tl-fix`, `/nacl:sa-finalize`): `:Decision` node, edges `(:Decision)-[:JUSTIFIES]->(...)`, `(:Decision)-[:SUPERSEDES]->(:Decision)`, `(:FeatureRequest)-[:IMPLEMENTS]->(:Decision)`
- Staleness properties (set by `/nacl:sa-feature`, `/nacl:tl-fix`): `review_status`, `stale_reason`, `stale_since`, `stale_origin` — read with `coalesce(n.review_status,'current')`.
- Stereotype on automated steps: `WorkflowStep.stereotype = 'Автоматизируется'` (Russian) or `'Automated'` (English) -- both accepted.
**Non-canonical aliases are NOT supported.** If the graph uses any of these, validation will HALT in pre-flight (Step 0a) instead of producing false-positive criticals:
| Non-canonical | Canonical |
|---------------|-----------|
| `:SAModule` | `:Module` |
| `:SAEntity` | `:DomainEntity` |
| `:SARequirement` | `:Requirement` |
| `:SAActor` | `:SystemRole` |
| `:SAComponent` | `:Component` |
| edge `TRACES_TO` | use `AUTOMATES_AS` / `REALIZED_AS` / `IMPLEMENTED_BY` / `MAPPED_TO` per source-target semantics |
If your graph uses non-canonical labels, see the **Migration Cypher Appendix** at the bottom of this skill, or re-import the SA layer using canonical skills.
---
## Pre-flight Checks
### Step 0: Verify graph has data
Before running any validation, confirm that the graph contains SA-layer nodes under canonical labels.
```cypher
// Pre-flight: count canonical SA-layer nodes
MATCH (n)
WHERE n:Module OR n:UseCase OR n:DomainEntity OR n:Form OR n:Requirement OR n:SystemRole
RETURN labels(n)[0] AS label, count(n) AS count
ORDER BY label
```
**If the result is empty or all counts are 0:**
1. STOP -- validation is impossible without data in the graph.
2. Suggest the user runs `/nacl:sa-architect` or `/nacl:sa-domain` first.
3. Explain that `/nacl:sa-validate` works only with a populated Neo4j graph.
### Step 0a: Detect schema drift (CRITICAL gate)
If canonical SA labels are absent but non-canonical aliases exist (e.g. `:SAModule`, `:SAEntity`, `:SARequirement`), the validator's queries silently return zero rows and produce **false-positive CRITICAL findings** for every L2-L9 / XL6-XL9 check. This step catches that scenario explicitly.
```cypher
// Step 0a: schema-drift detection
CALL db.labels() YIELD label
WITH collect(label) AS allLabels
RETURN
[l IN allLabels WHERE l IN
['Module','DomainEntity','Requirement','SystemRole','Component']] AS canonical_present,
[l IN allLabels WHERE l IN
['SAModule','SAEntity','SARequirement','SAActor','SAComponent']] AS dialect_present,
[l IN allLabels WHERE l STARTS WITH 'SA' AND l <> 'SystemRole'] AS sa_prefixed_labels,
allLabels AS all_labels_in_graph
```
Also probe for non-canonical edge types that signal drift in BA->SA handoff:
```cypher
// Step 0a (cont.): probe non-canonical edge types
CALL db.relationshipTypes() YIELD relationshipType
WITH collect(relationshipType) AS allEdges
RETURN
[r IN allEdges WHERE r IN
['AUTOMATES_AS','REALIZED_AS','IMPLEMENTED_BY','MAPPED_TO','TYPED_AS','SUGGESTS']]
AS canonical_handoff_edges,
[r IN allEdges WHERE r IN ['TRACES_TO','REALIZES','MAPS_FROM']] AS dialect_handoff_edges
```
**Decision rule:**
| Condition | Action |
|-----------|--------|
| `canonical_present` non-empty AND `dialect_present` empty | OK -- continue to Step 0b |
| `canonical_present` empty AND `dialect_present` non-empty | **HALT** -- emit drift report below; do NOT run any L*/XL* checks |
| Both non-empty | **HALT** -- mixed schema is worse than pure dialect; emit drift report; do NOT run checks |
| `dialect_handoff_edges` non-empty AND no canonical handoff edges | **HALT** -- BA->SA layer uses non-canonical edges; emit drift report |
**Drift report template (emit verbatim, fill placeholders from query results):**
```
==============================================================================
SCHEMA DRIFT DETECTED -- VALIDATION HALTED
==============================================================================
The graph uses non-canonical labels/edges that this skill does not support.
Canonical labels found : {canonical_present}
Non-canonical labels found: {dialect_present}
All SA-prefixed labels : {sa_prefixed_labels}
Canonical handoff edges : {canonical_handoff_edges}
Non-canonical handoff edges: {dialect_handoff_edges}
The skill expects the canonical SA schema (see "Schema Reference" section above).
Running validation queries against this graph would silently miss every node and
produce false-positive CRITICAL findings.
To proceed, choose ONE:
1. Migrate the graph to canonical labels & edges.
See the "Migration Cypher Appendix" at the bottom of this skill --
copy the block, run it via mcp__neo4j__write-cypher, then re-run
/nacl:sa-validate. The migration is idempotent.
2. Re-import the SA layer using canonical skills:
/nacl:sa-architect (creates :Module + structural skeleton)
/nacl:sa-domain (creates :DomainEntity, :Enumeration)
/nacl:sa-uc (creates :UseCase, :Requirement, :Form, :FormField)
/nacl:sa-roles (creates :SystemRole)
/nacl:ba-handoff (creates BA->SA handoff edges)
DO NOT proceed with validation. Halt here, surface this report to the user,
and wait for instruction.
==============================================================================
```
### Step 0b: Pre-flight node-count report (two sections)
Once Step 0a has confirmed the graph is canonical, render a two-section node-count report. The first section is canonical labels; the second surfaces any unexpected labels that didn't trigger HALT but are still worth flagging (e.g. typos, custom labels).
```cypher
// Step 0b: canonical SA-layer node counts
// (keep in sync with the Schema Reference above: every label a producer skill
// writes and every L-level anchors on belongs here — L10 added Screen*, L11
// Slice, L12 DomainError/ErrorPresentation, L13 CachePolicy/DegradationRule,
// L8/L9 Decision. A future L14+ MUST extend this list in the same commit.)
UNWIND ['Module','UseCase','DomainEntity','DomainAttribute','Enumeration','EnumValue',
'Form','FormField','Requirement','SystemRole','Component','ActivityStep',
'FeatureRequest','Screen','ScreenState','ScreenEvent','Transition',
'ScreenEffect','AnalyticsEvent','Slice','Decision','APIEndpoint',
'DomainError','ErrorPresentation','CachePolicy','DegradationRule'] AS labelName
CALL {
WITH labelName
MATCH (n) WHERE labelName IN labels(n)
RETURN count(n) AS cnt
}
RETURN labelName AS label, cnt AS count
ORDER BY labelName
```
```cypher
// Step 0b (cont.): non-canonical labels still present in graph
// The NOT IN list = canonical SA labels + known neighbor-layer labels that are
// legitimate on a shared graph and must NOT be reported as drift:
// BA family — BusinessProcess..DataFlow, EntityState, GlossaryTerm, SystemContext
// TL family — Task, Wave, IntakeItem (written by tl-plan / tl-intake)
// legacy SA — RuntimeContract (flat-format runtime contracts)
// `cnt > 0` filters constraint-registered label tokens with zero nodes — those
// are schema residue, not findings.
CALL db.labels() YIELD label
WITH label
WHERE NOT label IN
['Module','UseCase','DomainEntity','DomainAttribute','Enumeration','EnumValue',
'Form','FormField','Requirement','SystemRole','Component','ActivityStep',
'FeatureRequest','Screen','ScreenState','ScreenEvent','Transition','ScreenEffect',
'AnalyticsEvent','Slice','Decision','APIEndpoint','DomainError','ErrorPresentation',
'CachePolicy','DegradationRule','BusinessProcess','WorkflowStep','BusinessEntity','BusinessRole',
'BusinessRule','EntityAttribute','ProcessGroup','Term','Glossary','Stakeholder',
'ExternalEntity','Document','DataFlow','EntityState','GlossaryTerm','SystemContext',
'Task','Wave','IntakeItem','RuntimeContract']
CALL {
WITH label
MATCH (n) WHERE label IN labels(n)
RETURN count(n) AS cnt
}
WITH label, cnt
WHERE cnt > 0
RETURN label, cnt AS count
ORDER BY label
```
Render in the report header as:
```
Pre-flight node counts:
Canonical SA labels:
Module : 4
DomainEntity : 15
Requirement : 29
UseCase : 24
Form : 14
...
Non-canonical labels detected (informational):
(none, or list with "<-- review" hint)
```
### Step 0c: Verify BA layer exists (for ba-cross / full)
```cypher
// Pre-flight: count BA-layer nodes
MATCH (n)
WHERE n:BusinessProcess OR n:WorkflowStep OR n:BusinessEntity OR n:BusinessRole OR n:BusinessRule
RETURN labels(n)[0] AS label, count(n) AS count
ORDER BY label
```
**If the result is empty:**
- `level=ba-cross` --> STOP, report that BA layer is not populated. User must run `/nacl:ba-import-doc` or `/nacl:ba-from-board` first.
- `level=full` --> Run only L1-L13 (internal), skip XL6-XL9 with a WARNING in the report.
### Step 0d: Verify exemption properties are populated
Before running checks, confirm that exemption properties exist in the graph. Include this table
in the report header so the user can see which properties are set and which are missing.
```cypher
// Pre-flight: exemption property coverage
MATCH (ff:FormField)
WITH count(ff) AS total,
sum(CASE WHEN ff.field_category IS NOT NULL THEN 1 ELSE 0 END) AS has_prop
RETURN 'FormField.field_category' AS property, total, has_prop, total - has_prop AS missing
UNION ALL
MATCH (uc:UseCase)
WITH count(uc) AS total,
sum(CASE WHEN uc.has_ui IS NOT NULL THEN 1 ELSE 0 END) AS has_prop
RETURN 'UseCase.has_ui' AS property, total, has_prop, total - has_prop AS missing
UNION ALL
MATCH (de:DomainEntity)
WITH count(de) AS total,
sum(CASE WHEN de.shared IS NOT NULL THEN 1 ELSE 0 END) AS has_prop
RETURN 'DomainEntity.shared' AS property, total, has_prop, total - has_prop AS missing
UNION ALL
MATCH (sr:SystemRole)
WITH count(sr) AS total,
sum(CASE WHEN sr.system_only IS NOT NULL THEN 1 ELSE 0 END) AS has_prop
RETURN 'SystemRole.system_only' AS property, total, has_prop, total - has_prop AS missing
```
If `missing` is high for any property, the exemption filters in L4-L6/XL8 will treat those nodes
as non-exempt (defaulting to the strict check). This is correct behavior -- it means the SA skills
haven't classified those nodes yet.
**Escape-valve debt (INFO).** The opt-in valves (`anchor_exempt` for L3.7, `coverage_exempt` for
L3.8, `overlap_accepted` for L13.9) default to absent, so the table above cannot show them. Report
how many nodes have pulled each valve and how many did so without the required reason, so the
debt stays visible even when the gate is green:
```cypher
// Pre-flight: escape-valve debt (INFO)
// Aggregate WITHOUT a grouping key so a valve with zero uses still returns its 0 row.
OPTIONAL MATCH (rq:Requirement) WHERE coalesce(rq.anchor_exempt, false) = true
WITH count(rq) AS exempted,
sum(CASE WHEN rq IS NOT NULL AND trim(coalesce(toString(rq.anchor_exempt_reason), '')) = '' THEN 1 ELSE 0 END) AS without_reason
RETURN 'Requirement.anchor_exempt' AS valve, exempted, without_reason
UNION ALL
OPTIONAL MATCH (s:ActivityStep) WHERE coalesce(s.coverage_exempt, false) = true
WITH count(s) AS exempted,
sum(CASE WHEN s IS NOT NULL AND trim(coalesce(toString(s.coverage_exempt_reason), '')) = '' THEN 1 ELSE 0 END) AS without_reason
RETURN 'ActivityStep.coverage_exempt' AS valve, exempted, without_reason
UNION ALL
OPTIONAL MATCH (cp:CachePolicy) WHERE coalesce(cp.overlap_accepted, false) = true
WITH count(cp) AS exempted,
sum(CASE WHEN cp IS NOT NULL AND trim(coalesce(toString(cp.overlap_accepted_reason), '')) = '' THEN 1 ELSE 0 END) AS without_reason
RETURN 'CachePolicy.overlap_accepted' AS valve, exempted, without_reason
```
`without_reason > 0` for `coverage_exempt` / `overlap_accepted` is also reported by L3.9 / L13.10.
**To backfill missing exemption properties**, use `/nacl:sa-flags`:
```
/nacl:sa-flags audit # confirm scope
/nacl:sa-flags backfill-all --detect-internal # write safe defaults
/nacl:sa-validate full # re-run validation
```
`nacl-sa-flags` is the canonical orchestrator-tier skill for setting validation-only metadata. It writes only `has_ui`, `system_only`, `shared`, `internal`, `field_category` -- no domain semantics. After `nacl-migrate-sa` it is invoked automatically; after manual graph edits or skill-version upgrades, run it explicitly.
---
## Severity Levels
Every detected problem is assigned a severity:
| Severity | Meaning | Report threshold |
|----------|---------|------------------|
| **CRITICAL** | Specification is broken; blocks downstream work | Any CRITICAL --> overall FAIL |
| **WARNING** | Inconsistency that should be fixed but is not blocking | 5+ WARNINGs --> overall WARN |
| **INFO** | Observation, optional improvement | Does not affect overall status |
**Computing the overall status is delegated** — do not roll up ~40 check results by
hand (miscounting "5+ WARNING" or missing one CRITICAL silently changes the gate
verdict). Collect every finding as `{check, severity, flags?}` and pass them to the
single-authority classifier; emit its `overall` token verbatim. It also re-applies the
property-based exemption filters (L3.7/L3.8/L4.1/L5.1/L6.1/L9.1/L10.2/L10.6/L13.9/XL8.2)
as a defense-in-depth net, so a finding whose Cypher omitted its `coalesce(...)` filter is
still dropped before it can flip the gate. Pass the exemption properties the query returns as
`flags` (L3.8: `coverage_exempt`; L13.9: `overlap_accepted_1` and `overlap_accepted_2` — the
pair is exempt only when both are true). Equivalence pinned by
`classify-findings.test.mjs`, next to the classifier script.
```bash
node ${CLAUDE_PLUGIN_ROOT}/nacl-core/scripts/classify-findings.mjs '{"findings":[{"check":"L1.1","severity":"CRITICAL"},{"check":"L4.1","severity":"CRITICAL","flags":{"field_category":"display"}}]}'
# stdout: full JSON (findings + counts + overall); stderr: the bare overall token
```
---
## Validation Levels -- Internal (L1-L13)
### Level 1: Data Consistency
**Goal:** Verify that property types, mandatory fields, and naming conventions are uniform across all SA nodes.
#### Check 1.1: Nodes missing mandatory properties
Every SA node type has mandatory properties. Find nodes that lack them.
```cypher
// L1.1 -- Severity: CRITICAL
// Nodes missing mandatory 'id' or 'name' property
MATCH (n)
WHERE (n:Module OR n:UseCase OR n:DomainEntity OR n:Form OR n:SystemRole OR n:Component)
AND (n.id IS NULL OR n.name IS NULL)
RETURN labels(n)[0] AS node_type,
coalesce(n.id, 'NO ID') AS id,
coalesce(n.name, 'NO NAME') AS name,
'Missing mandatory property: id or name' AS problem
```
#### Check 1.2: DomainAttributes missing type
Every DomainAttribute must have a data_type property.
```cypher
// L1.2 -- Severity: CRITICAL
// DomainAttributes without data_type
MATCH (de:DomainEntity)-[:HAS_ATTRIBUTE]->(da:DomainAttribute)
WHERE da.data_type IS NULL
RETURN de.name AS entity, da.name AS attribute, da.id AS attr_id,
'DomainAttribute missing data_type' AS problem
```
#### Check 1.3: Duplicate IDs within a label
IDs must be unique within each node type (enforced by constraints, but check anyway).
```cypher
// L1.3 -- Severity: CRITICAL
// Duplicate IDs across SA node types
UNWIND ['Module','UseCase','DomainEntity','DomainAttribute','Enumeration',
'Form','FormField','Requirement','SystemRole','Component'] AS labelName
CALL {
WITH labelName
MATCH (n)
WHERE labelName IN labels(n)
WITH labelName, n.id AS nodeId, count(*) AS cnt
WHERE cnt > 1
RETURN labelName AS node_type, nodeId AS id, cnt AS duplicate_count
}
RETURN node_type, id, duplicate_count
```
#### Check 1.4: Inconsistent enumeration values (duplicate or empty)
Canonical writer (`/nacl:sa-domain`) populates `EnumValue.value`. Some legacy or hand-written graphs may use `.code` or `.label` instead. To avoid false positives, this check coalesces all three property names; if none yields a non-empty string, the value is considered empty.
```cypher
// L1.4 -- Severity: WARNING
// Enumerations with duplicate or empty values (tolerant: .value | .code | .label)
MATCH (e:Enumeration)-[:HAS_VALUE]->(ev:EnumValue)
WITH e, coalesce(ev.value, ev.code, ev.label) AS val, count(*) AS cnt
WHERE cnt > 1 OR val IS NULL OR trim(val) = ''
RETURN e.name AS enumeration, e.id AS enum_id,
coalesce(val, '<EMPTY>') AS value, cnt AS occurrences,
CASE WHEN val IS NULL OR trim(val) = '' THEN 'Empty enum value'
ELSE 'Duplicate enum value' END AS problem
```
#### Check 1.5: Enumeration value-property convention (informational)
Reports which property name carries the actual enum value. Run this once during pre-flight or in the report header so the user can spot drift early.
```cypher
// L1.5 -- Severity: INFO
// Distribution of EnumValue value-property convention
MATCH (ev:EnumValue)
WITH count(ev) AS total,
sum(CASE WHEN ev.value IS NOT NULL AND trim(toString(ev.value)) <> '' THEN 1 ELSE 0 END) AS with_value,
sum(CASE WHEN ev.code IS NOT NULL AND trim(toString(ev.code)) <> '' THEN 1 ELSE 0 END) AS with_code,
sum(CASE WHEN ev.label IS NOT NULL AND trim(toString(ev.label)) <> '' THEN 1 ELSE 0 END) AS with_label
RETURN total, with_value, with_code, with_label,
CASE
WHEN with_value = total THEN 'canonical (.value)'
WHEN with_code = total THEN 'drift (.code only) -- consider migrating to .value'
WHEN with_label = total THEN 'drift (.label only) -- consider migrating to .value'
WHEN with_value > 0 AND (with_code > 0 OR with_label > 0) THEN 'mixed -- some EnumValues use .value, others use .code/.label'
WHEN total = 0 THEN 'no EnumValues in graph'
ELSE 'broken -- no EnumValue carries a recognized value property'
END AS convention
```
---
### Level 2: Model Connectivity
**Goal:** Verify that all model elements are connected -- no orphans, no broken references.
#### Check 2.1: Completely disconnected nodes (orphans)
```cypher
// L2.1 -- Severity: CRITICAL
// Nodes with zero relationships
MATCH (n)
WHERE (n:Module OR n:UseCase OR n:DomainEntity OR n:DomainAttribute OR n:Form
OR n:FormField OR n:Requirement OR n:SystemRole OR n:Enumeration OR n:Component)
AND NOT (n)--()
RETURN labels(n)[0] AS node_type, n.id AS id,
coalesce(n.name, n.description, n.value, '') AS display_name,
'Completely disconnected node (zero relationships)' AS problem
```
#### Check 2.2: DomainEntities not assigned to any Module
```cypher
// L2.2 -- Severity: WARNING
// DomainEntities without a parent Module
MATCH (de:DomainEntity)
WHERE NOT (:Module)-[:CONTAINS_ENTITY]->(de)
RETURN de.id AS entity_id, de.name AS entity_name,
'DomainEntity not assigned to any Module' AS problem
```
#### Check 2.3: UseCases not assigned to any Module
```cypher
// L2.3 -- Severity: WARNING
// UseCases without a parent Module
MATCH (uc:UseCase)
WHERE NOT (:Module)-[:CONTAINS_UC]->(uc)
RETURN uc.id AS uc_id, uc.name AS uc_name,
'UseCase not assigned to any Module' AS problem
```
#### Check 2.4: DomainAttributes not owned by any entity
```cypher
// L2.4 -- Severity: CRITICAL
// DomainAttributes floating without a parent DomainEntity
MATCH (da:DomainAttribute)
WHERE NOT (:DomainEntity)-[:HAS_ATTRIBUTE]->(da)
RETURN da.id AS attr_id, da.name AS attr_name,
'DomainAttribute not owned by any DomainEntity' AS problem
```
#### Check 2.5: FormFields not owned by any Form
```cypher
// L2.5 -- Severity: CRITICAL
// FormFields floating without a parent Form
MATCH (ff:FormField)
WHERE NOT (:Form)-[:HAS_FIELD]->(ff)
RETURN ff.id AS field_id, ff.name AS field_name,
'FormField not owned by any Form' AS problem
```
---
### Level 3: Requirement Completeness
**Goal:** Every UseCase must have requirements; every requirement must be reachable; and
every functional/validation/behavioral/interface requirement must be anchored to the
step/field/form that realizes it (`REALIZED_BY`) — NFRs and reserved classes are exempt.
#### Check 3.1: UseCases without any requirements
```cypher
// L3.1 -- Severity: CRITICAL
// UseCases with no HAS_REQUIREMENT edge
MATCH (uc:UseCase)
WHERE NOT (uc)-[:HAS_REQUIREMENT]->(:Requirement)
RETURN uc.id AS uc_id, uc.name AS uc_name,
'UseCase has no requirements' AS problem
```
#### Check 3.2: Orphaned requirements (not linked to any UseCase)
```cypher
// L3.2 -- Severity: WARNING
// Requirements not linked to any UseCase
MATCH (r:Requirement)
WHERE NOT (:UseCase)-[:HAS_REQUIREMENT]->(r)
RETURN r.id AS req_id, coalesce(r.description, r.name, '') AS description,
'Requirement not linked to any UseCase' AS problem
```
#### Check 3.3: UseCases without any ActivitySteps
A UseCase without steps is just a title -- it needs a workflow.
```cypher
// L3.3 -- Severity: WARNING
// UseCases with zero ActivitySteps
MATCH (uc:UseCase)
WHERE NOT (uc)-[:HAS_STEP]->(:ActivityStep)
RETURN uc.id AS uc_id, uc.name AS uc_name,
'UseCase has no ActivitySteps (empty workflow)' AS problem
```
#### Check 3.4: UseCases without an actor (SystemRole)
Every UseCase should have at least one actor.
```cypher
// L3.4 -- Severity: WARNING
// UseCases without ACTOR edge to a SystemRole
MATCH (uc:UseCase)
WHERE NOT (uc)-[:ACTOR]->(:SystemRole)
RETURN uc.id AS uc_id, uc.name AS uc_name,
'UseCase has no assigned actor (SystemRole)' AS problem
```
#### Check 3.5: ActivitySteps with empty/missing actor
Every ActivityStep must carry an `actor` property (`User` or `System`) so the
activity-diagram renderer can distribute steps across swimlanes. A missing actor
collapses the diagram to a single lane and hides the User/System separation.
```cypher
// L3.5 -- Severity: CRITICAL
// ActivitySteps with empty/missing actor (CRITICAL)
MATCH (uc:UseCase)-[:HAS_STEP]->(s:ActivityStep)
WHERE s.actor IS NULL OR s.actor = ''
RETURN uc.id AS uc_id,
count(s) AS empty_actor_steps,
'ActivityStep.actor empty — diagram will render single-lane' AS problem
ORDER BY empty_actor_steps DESC
```
#### Check 3.6: Non-canonical actor values on ActivityStep
The renderer expects exactly `User` or `System` (case-sensitive). Values such as
`admin`, `system`, `authenticated`, or `Admin` are silently ignored and produce
the same degraded single-lane output as a missing actor.
```cypher
// L3.6 -- Severity: WARNING
// Non-canonical actor values (WARNING)
MATCH (uc:UseCase)-[:HAS_STEP]->(s:ActivityStep)
WHERE s.actor IS NOT NULL AND s.actor <> '' AND NOT s.actor IN ['User', 'System']
RETURN uc.id AS uc_id, s.id AS step_id, s.actor AS actor_value,
'Non-canonical actor value (renderer expects User|System exactly)' AS problem
```
#### Check 3.6b: ActivityStep description is a bare number or a placeholder (data quality)
A step whose `description` is only a step number (`1`, `7a`, `2.1`) or a placeholder
(`--`, `-`, `—`, empty) carries no behavior: the activity diagram shows a numbered box,
and L3.7/L3.8 anchoring has nothing to anchor to. This is the signature of a migration that
read the wrong table column (e.g. the `Шаг` number column of a legacy
`| Шаг | Актор | Система | Данные |` Main Flow table) — cheap to detect after any
`nacl-migrate-sa` run or manual import. INFO — a count to act on (re-run the migration
with a fixed adapter, or rewrite the steps via `nacl-sa-uc`), never a gate.
```cypher
// L3.6b -- Severity: INFO
// ActivitySteps whose description is numeric-only or a placeholder, per UC
MATCH (uc:UseCase)-[:HAS_STEP]->(s:ActivityStep)
WITH uc, s, trim(coalesce(toString(s.description), '')) AS d
WHERE d IN ['', '-', '--', '---', '—', '–']
OR d =~ '[0-9]+[A-Za-zА-Яа-я]?(\\.[0-9]+)*\\.?'
RETURN uc.id AS uc_id, count(s) AS bad_descriptions,
collect(s.id)[..5] AS sample_step_ids,
'ActivityStep description is a bare step number or a placeholder (migration column defect?)' AS observation
ORDER BY bad_descriptions DESC
```
#### Check 3.7: Requirement not anchored to its implementer (REALIZED_BY)
The **outgoing-anchor invariant** for requirements. A requirement reachable only from
its UseCase (`HAS_REQUIREMENT`) floats above the artifacts that realize it, so change
propagation and coverage gates cannot reach the step or field that breaks it — the whole
premise of a *connected* spec graph. Mirrors the no-anchorless-node family (Slice L11.2,
DomainError L12.2), but unlike those it has an exemption: NFRs and reserved classes are
free-floating by design, and the rare genuinely-unanchorable functional requirement
carries `anchor_exempt=true`.
The requirement **class** is read with a normalization that tolerates every legacy
discriminator spelling — `rq_type` is canonical, but real graphs also store the class in
`req_type` (seed/domain) or in the overloaded `type` (`type:'functional'`): so the read is
`coalesce(rq.rq_type, rq.req_type, rq.type, 'unknown')`. Because `type` is overloaded, the
reserved values it also carries — `nfr`, `adr`/`question` (read by `nacl-sa-finalize`),
`assumption` — must be filtered out explicitly; they are never must-anchor.
```cypher
// L3.7 -- Severity: CRITICAL
// Must-anchor requirement (functional/validation/behavioral/interface) with no
// REALIZED_BY edge to the step/field/form that implements it.
MATCH (rq:Requirement)
WITH rq, coalesce(rq.rq_type, rq.req_type, rq.type, 'unknown') AS cls
WHERE cls IN ['functional','validation','behavioral','interface']
AND NOT coalesce(rq.type, '') IN ['nfr','adr','question','assumption'] // REQUIRED FILTER: reserved type values
AND coalesce(rq.anchor_exempt, false) = false // REQUIRED FILTER: durable escape valve
AND NOT (rq)-[:REALIZED_BY]->()
RETURN rq.id AS req_id, cls AS req_class,
coalesce(rq.description, rq.name, '') AS description,
'Requirement not anchored to its implementer (no REALIZED_BY step/field/form)' AS problem
```
#### Check 3.7b: REALIZED_BY target label disagrees with requirement class
Catches mis-anchoring — e.g. a `validation` requirement pointed at a whole `Form`
instead of the `FormField` it constrains. The contract: `functional`/`behavioral` →
`ActivityStep`; `validation` → `FormField`; `interface` → `Form` or `Screen`.
```cypher
// L3.7b -- Severity: WARNING
MATCH (rq:Requirement)-[rel:REALIZED_BY]->(t)
WITH rq, rel, t, coalesce(rq.rq_type, rq.req_type, rq.type, 'unknown') AS cls
WHERE (cls IN ['functional','behavioral'] AND NOT t:ActivityStep)
OR (cls = 'validation' AND NOT t:FormField)
OR (cls = 'interface' AND NOT (t:Form OR t:Screen))
RETURN rq.id AS req_id, cls AS req_class, labels(t) AS target_labels,
coalesce(rel.anchor_kind, '') AS anchor_kind,
'REALIZED_BY target label disagrees with requirement class' AS problem
```
#### Check 3.8: Reverse coverage — System step with no realizing requirement (opt-in)
The other direction: a `System`-actor `ActivityStep` (where business logic and rules
live) that no requirement realizes. Surfaced **only once the project has opted into
REALIZED_BY at all** (the `EXISTS {...}` arm), so un-anchored graphs pass vacuously —
the same opt-in shape as the cache-layer arm in L13. Closing it requires authoring, so
it never escalates to CRITICAL.
Not every System step realizes a rule: pure render / navigation / client plumbing
(render the list, redirect to the result page, clear `sessionStorage`) legitimately merits
no requirement, and inventing one per step to reach PASS is junk authoring. Such a step
carries `coverage_exempt=true` **plus a non-blank `coverage_exempt_reason`** — the durable
escape valve, mirroring `anchor_exempt` for L3.7. The reason is part of the contract
(L3.9 flags a blank one) and the exempted count is reported in Step 0d, so the valve can
never be pulled silently. Anything carrying a business rule, validation, persistence, an
external call, security, or money is **not** exemptible — author the requirement.
```cypher
// L3.8 -- Severity: WARNING
MATCH (uc:UseCase)-[:HAS_STEP]->(s:ActivityStep)
WHERE s.actor = 'System'
AND EXISTS { (:Requirement)-[:REALIZED_BY]->(:ActivityStep) } // opt-in: only after anchoring started
AND coalesce(s.coverage_exempt, false) = false // REQUIRED FILTER: durable escape valve
AND NOT (:Requirement)-[:REALIZED_BY]->(s)
RETURN uc.id AS uc_id, s.id AS step_id,
coalesce(s.description, '') AS step,
'System ActivityStep has no realizing requirement (reverse-coverage gap)' AS problem
```
#### Check 3.9: coverage_exempt without a reason
The L3.8 valve is only legitimate when it says why. A step flagged `coverage_exempt=true`
with a missing/blank `coverage_exempt_reason` is an unexplained hole in reverse coverage.
Not opt-in-gated: a flag without a reason is wrong whether or not anchoring has started.
```cypher
// L3.9 -- Severity: WARNING
MATCH (s:ActivityStep)
WHERE coalesce(s.coverage_exempt, false) = true
AND trim(coalesce(toString(s.coverage_exempt_reason), '')) = ''
OPTIONAL MATCH (uc:UseCase)-[:HAS_STEP]->(s)
RETURN uc.id AS uc_id, s.id AS step_id,
coalesce(s.description, '') AS step,
'coverage_exempt=true without coverage_exempt_reason (the L3.8 valve must be justified)' AS problem
```
---
### CRITICAL: Mandatory Exemption Filters
Checks L3.7, L3.8, L4–L6, L9, L10, L13.9 and XL8 contain WHERE filters that exempt nodes with specific
properties. These filters MUST be included verbatim in every query — omitting them causes
false positives that cannot be fixed by any SA skill (the data is correct, the query is wrong).
| Check | Mandatory filter | Purpose |
|-------|-----------------|---------|
| L3.7 | `AND NOT coalesce(rq.type,'') IN ['nfr','adr','question','assumption'] AND coalesce(rq.anchor_exempt,false) = false` | Exempt NFR/reserved `type` values and durably-flagged unanchorable requirements from the REALIZED_BY anchor gate (class read as `coalesce(rq.rq_type, rq.req_type, rq.type, 'unknown')`) |
| L3.8 | `AND coalesce(s.coverage_exempt, false) = false` | Exempt System steps that realize no rule (pure render / navigation / client plumbing) from the reverse-coverage check; the flag REQUIRES a non-blank `coverage_exempt_reason` (L3.9) |
| L4.1 | `AND coalesce(ff.field_category, 'input') = 'input'` | Exempt display/action fields from MAPS_TO requirement |
| L5.1 | `AND coalesce(uc.has_ui, true) = true` | Exempt backend-only UCs from form requirement |
| L5.4 | `WHERE mapped_fields = 0 AND input_fields > 0` | Exempt forms with only display/action fields |
| L6.1 | `AND coalesce(de.shared, false) = false` | Exempt intentionally shared cross-module entities |
| L7.2 | `AND fr.legacy_origin IS NULL` | Exempt FR tombstones (renamed legacy nodes preserved for traceability) |
| L7.4 | `WHERE fr.legacy_origin IS NULL` | Exempt FR tombstones (same reason as L7.2) |
| L7.6 | `AND NOT n.id STARTS WITH 'FR-LEG-'` | Exempt all tombstone namespaces from cross-label collision check |
| L9.1 | `AND coalesce(fr.decision_exempt, false) = false` | Exempt grandfathered pre-provenance FRs (rationale unrecoverable at gap-closure; see provenance-gap-closure runbook) |
| L10.2 | `AND coalesce(scr.formless, false) = false` | Exempt screens that render no Form (splash, 404) from the RENDERS requirement |
| L10.6 | `AND coalesce(st.terminal, false) = false` | Exempt intentionally terminal error states from the escape-transition requirement |
| L13.9 | `AND NOT (coalesce(cp1.overlap_accepted, false) = true AND coalesce(cp2.overlap_accepted, false) = true)` | Exempt an intentional same-storage layering of two policies on one endpoint — only when BOTH policies of the pair accept the overlap; the flag REQUIRES a non-blank `overlap_accepted_reason` (L13.10) |
| XL8.2 | `AND coalesce(sr.system_only, false) = false` | Exempt infrastructure-only roles |
L11 has **no exemption properties by design**: an anchorless Slice (L11.2) is not an exemptible
state — behavior text with no graph anchor belongs in `UseCase.acceptance_criteria`, not in a node.
L12 likewise has **no exemption properties by design**: an unraisable DomainError (L12.2) is not
an exemptible state — a failure mode observable at no API surface is an implementation detail and
belongs in Requirements / RuntimeContract notes, not in a node; an unshown ErrorPresentation is
dead text. Deliberate UI silence is modeled as a `silent`-kind presentation, not as an exemption.
L13's **structural checks (L13.0–L13.8) have no exemption properties by design**: a CachePolicy
that caches no surface (L13.2) is dead vocabulary — a caching intention with no data surface
belongs in Requirements, not in a node; a DegradationRule with neither an ON_ERROR failure mode
nor a DEGRADES_TO state is prose change propagation can never reach (the L11.2 argument
verbatim). **L13.9 has exactly one exemption** — `CachePolicy.overlap_accepted` — because it is
a heuristic overlap check, not a structural invariant: two same-storage policies on one endpoint
are usually contradictory, but an intentional layering (e.g. an in-app Cache API layer plus a
Service Worker runtime cache with distinct cache names over versioned immutable URLs, recorded
in a Decision) is not. The pair is exempt only when both policies carry `overlap_accepted=true`,
and each flag REQUIRES a non-blank `overlap_accepted_reason` (L13.10 flags a blank one).
If executing via HTTP API (curl) instead of MCP tools, copy queries CHARACTER-FOR-CHARACTER
from the code blocks below. Do NOT simplify, rephrase, or omit WHERE clauses.
---
### Level 4: Form-Domain Traceability
**Goal:** Every FormField should map to a DomainAttribute; every DomainAttribute should be reachable from at least one form (or marked internal).
#### Check 4.1: FormFields without MAPS_TO edge
```cypher
// L4.1 -- Severity: CRITICAL
// FormFields that have no MAPS_TO edge to a DomainAttribute
// Only input fields require MAPS_TO; display and action fields are exempt
MATCH (f:Form)-[:HAS_FIELD]->(ff:FormField)
WHERE NOT (ff)-[:MAPS_TO]->(:DomainAttribute)
AND coalesce(ff.field_category, 'input') = 'input' // REQUIRED FILTER: exempt display/action
RETURN f.name AS form_name, f.id AS form_id,
ff.name AS field_name, ff.id AS field_id,
ff.field_type AS field_type, ff.field_category AS field_category,
ff.label AS label,
'FormField has no MAPS_TO -> DomainAttribute binding' AS problem
```
#### Check 4.2: DomainAttributes not referenced by any FormField (orphaned attributes)
```cypher
// L4.2 -- Severity: INFO
// DomainAttributes not mapped from any FormField (may be internal-only)
MATCH (de:DomainEntity)-[:HAS_ATTRIBUTE]->(da:DomainAttribute)
WHERE NOT (:FormField)-[:MAPS_TO]->(da)
AND coalesce(da.internal, false) = false
RETURN de.name AS entity, de.id AS entity_id,
da.name AS attribute, da.id AS attr_id,
'DomainAttribute not referenced by any FormField and not marked internal' AS problem
```
#### Check 4.3: MAPS_TO pointing to non-existent attribute (dangling edge)
```cypher
// L4.3 -- Severity: CRITICAL
// FormFields with MAPS_TO edge where the target has no parent entity
MATCH (ff:FormField)-[:MAPS_TO]->(da:DomainAttribute)
WHERE NOT (:DomainEntity)-[:HAS_ATTRIBUTE]->(da)
RETURN ff.id AS field_id, ff.name AS field_name,
da.id AS attr_id, da.name AS attr_name,
'MAPS_TO target DomainAttribute has no parent DomainEntity' AS problem
```
#### Check 4.4: Type mismatch between FormField and DomainAttribute
```cypher
// L4.4 -- Severity: WARNING
// FormField field_type vs DomainAttribute data_type inconsistency
// (heuristic: TextInput should not map to Boolean, Checkbox should not map to String, etc.)
MATCH (ff:FormField)-[:MAPS_TO]->(da:DomainAttribute)
WHERE (ff.field_type = 'Checkbox' AND NOT da.data_type IN ['Boolean', 'Bool'])
OR (ff.field_type = 'NumberInput' AND NOT da.data_type IN ['Integer', 'Int', 'Float', 'Decimal', 'Number', 'Money'])
OR (ff.field_type = 'DatePicker' AND NOT da.data_type IN ['Date', 'DateTime', 'Timestamp'])
RETURN ff.id AS field_id, ff.name AS field_name, ff.field_type AS field_type,
da.id AS attr_id, da.name AS attr_name, da.data_type AS attr_type,
'Potential type mismatch between FormField and DomainAttribute' AS problem
```
---
### Level 5: UC-Form Validation
**Goal:** Every UseCase that has forms should reference them properly; forms should cover the UC's data needs.
#### Check 5.1: UseCases without any USES_FORM edge
```cypher
// L5.1 -- Severity: WARNING
// UseCases with ActivitySteps but no USES_FORM edge to any Form
// Backend-only UCs (has_ui=false) are exempt
MATCH (uc:UseCase)-[:HAS_STEP]->(:ActivityStep)
WHERE NOT (uc)-[:USES_FORM]->(:Form)
AND coalesce(uc.has_ui, true) = true // REQUIRED FILTER: exempt backend-only UCs
WITH DISTINCT uc
RETURN uc.id AS uc_id, uc.name AS uc_name,
'UseCase has steps but no linked Forms (USES_FORM)' AS problem
```
#### Check 5.2: Forms not used by any UseCase
```cypher
// L5.2 -- Severity: WARNING
// Forms that no UseCase references
MATCH (f:Form)
WHERE NOT (:UseCase)-[:USES_FORM]->(f)
RETURN f.id AS form_id, f.name AS form_name,
'Form not referenced by any UseCase (USES_FORM)' AS problem
```
#### Check 5.3: Forms with zero fields
A form without fields is structurally incomplete.
```cypher
// L5.3 -- Severity: CRITICAL
// Forms that have no FormField children
MATCH (f:Form)
WHERE NOT (f)-[:HAS_FIELD]->(:FormField)
RETURN f.id AS form_id, f.name AS form_name,
'Form has zero fields (empty form)' AS problem
```
#### Check 5.4: UC uses form but form has no mapped domain attributes
```cypher
// L5.4 -- Severity: WARNING
// UC -> Form where none of the input fields have MAPS_TO edges
// Forms with only display/action fields are exempt (no input fields to map)
MATCH (uc:UseCase)-[:USES_FORM]->(f:Form)-[:HAS_FIELD]->(ff:FormField)
WITH uc, f, count(ff) AS total_fields,
sum(CASE WHEN coalesce(ff.field_category, 'input') = 'input' THEN 1 ELSE 0 END) AS input_fields,
sum(CASE WHEN (ff)-[:MAPS_TO]->(:DomainAttribute) THEN 1 ELSE 0 END) AS mapped_fields
WHERE mapped_fields = 0 AND input_fields > 0 // REQUIRED FILTER: exempt display-only forms
RETURN uc.id AS uc_id, uc.name AS uc_name,
f.id AS form_id, f.name AS form_name,
total_fields, input_fields,
'Form used by UC has input fields but zero mapped -- no domain traceability' AS problem
```
---
### Level 6: Cross-Module Consistency
**Goal:** Shared entities, terminology, and UC numbering are consistent across modules.
#### Check 6.1: DomainEntity referenced by multiple modules with inconsistent attributes
```cypher
// L6.1 -- Severity: WARNING
// Entities belonging to multiple modules (via CONTAINS_ENTITY) -- potential shared entity conflict
// Entities marked shared=true are intentionally shared and exempt
MATCH (m:Module)-[:CONTAINS_ENTITY]->(de:DomainEntity)
WITH de, collect(m.name) AS modules, count(m) AS module_count
WHERE module_count > 1 AND coalesce(de.shared, false) = false // REQUIRED FILTER: exempt shared entities
RETURN de.id AS entity_id, de.name AS entity_name, modules,
'DomainEntity belongs to multiple modules -- verify attribute consistency' AS problem
```
#### Check 6.2: Circular UC dependencies
```cypher
// L6.2 -- Severity: CRITICAL
// Detect circular DEPENDS_ON chains (depth up to 10)
MATCH path = (uc:UseCase)-[:DEPENDS_ON*1..10]->(uc)
RETURN uc.id AS uc_id, uc.name AS uc_name,
length(path) AS cycle_length,
[n IN nodes(path) | n.id] AS cycle_path,
'Circular UC dependency detected' AS problem
LIMIT 20
```
#### Check 6.3: DomainEntities with RELATES_TO to entities in different modules
```cypher
// L6.3 -- Severity: INFO
// Cross-module entity relationships (not an error, but worth tracking)
MATCH (m1:Module)-[:CONTAINS_ENTITY]->(de1:DomainEntity)-[:RELATES_TO]->(de2:DomainEntity)<-[:CONTAINS_ENTITY]-(m2:Module)
WHERE m1 <> m2
RETURN m1.name AS module_1, de1.name AS entity_1,
m2.name AS module_2, de2.name AS entity_2,
'Cross-module entity relationship' AS observation
```
#### Check 6.4: SystemRoles with no UC actor assignments
```cypher
// L6.4 -- Severity: WARNING
// SystemRoles defined but never used as UC actor
MATCH (sr:SystemRole)
WHERE NOT (:UseCase)-[:ACTOR]->(sr)
RETURN sr.id AS role_id, sr.name AS role_name,
'SystemRole defined but not assigned as actor to any UseCase' AS problem
```
---
### Level 7: FeatureRequest Consistency
**Goal:** The FR-id namespace is consistent across three sources — `.tl/feature-requests/*.md` files, `:FeatureRequest` nodes, and any other node label that historically used FR-NNN ids (e.g. `:Task`). Without these checks, downstream skills (`nacl-tl-conductor`, `nacl-tl-plan --feature`, `nacl-tl-full --feature`) silently fall back to parsing markdown and lose graph-based scope resolution, or worse — route to the wrong node when the same id exists under multiple labels.
**Checks:**
- **L7.1** — markdown FR exists on disk but no `:FeatureRequest` node in graph (CRITICAL)
- **L7.2** — `:FeatureRequest` node has no `INCLUDES_UC` edge (CRITICAL; tombstones exempt)
- **L7.3** — `INCLUDES_UC` edge has unexpected `kind` value (WARNING)
- **L7.4** — `:FeatureRequest` references missing `:UseCase` (CRITICAL; tombstones exempt)
- **L7.5** — duplicate FR-NNN markdown files on disk (CRITICAL; filesystem check, not Cypher)
- **L7.6** — FR-NNN id reused across multiple node labels in active namespace (CRITICAL)
**How to obtain `$fileFrIds`:** before running L7.1, list FR ids from disk with a shell helper (`ls .tl/feature-requests/FR-*.md` → strip prefix/suffix to get `FR-NNN`). Pass the list as `$fileFrIds` parameter to the Cypher below.
#### Check 7.1: FR markdown without FeatureRequest node in graph
```cypher
// L7.1 -- Severity: CRITICAL
// Every FR-NNN.md on disk must have a :FeatureRequest node in Neo4j.
// Backfill via Step 6.2bis of nacl-sa-feature.
UNWIND $fileFrIds AS frId
OPTIONAL MATCH (fr:FeatureRequest {id: frId})
WITH frId, fr
WHERE fr IS NULL
RETURN frId AS missing_fr_id,
'FR markdown exists on disk but no :FeatureRequest node in graph' AS problem
```
#### Check 7.2: FeatureRequest nodes with no INCLUDES_UC
Active FeatureRequest nodes must scope at least one UseCase via INCLUDES_UC, otherwise downstream planning has nothing to consume. **Tombstones** (renamed legacy nodes preserved for historical traceability) are exempt — they keep their original edges (`GENERATES`, `REFINED_AS`, `EXTENDS`, `DERIVED_FROM`) instead of `INCLUDES_UC`. Tombstones are identified by the `legacy_origin` property, set automatically by `nacl-sa-feature` when renaming a node out of the active id-namespace.
```cypher
// L7.2 -- Severity: CRITICAL
// FeatureRequest nodes that scope zero UCs are useless for downstream planning.
// Tombstones (legacy_origin IS NOT NULL) are exempt — they use legacy edges, not INCLUDES_UC.
MATCH (fr:FeatureRequest)
WHERE NOT (fr)-[:INCLUDES_UC]->(:UseCase)
AND fr.legacy_origin IS NULL // REQUIRED FILTER: exempt tombstones
RETURN fr.id AS fr_id, fr.status AS status,
'FeatureRequest has no INCLUDES_UC -> UseCase' AS problem
```
#### Check 7.3: INCLUDES_UC edges with kind not in {new, modified}
```cypher
// L7.3 -- Severity: WARNING
// nacl-sa-feature writes kind='new'|'modified'. Other values indicate manual drift.
MATCH (fr:FeatureRequest)-[r:INCLUDES_UC]->(uc:UseCase)
WHERE NOT coalesce(r.kind, 'unknown') IN ['new', 'modified']
RETURN fr.id AS fr_id, uc.id AS uc_id, r.kind AS kind,
'INCLUDES_UC edge has unexpected kind property' AS problem
```
#### Check 7.4: FeatureRequest references missing UseCase
```cypher
// L7.4 -- Severity: CRITICAL
// Integrity check: INCLUDES_UC must point to an existing UseCase.
// (Neo4j MERGE on missing UC silently no-ops, so an FR can end up with zero UCs.)
// Tombstones (legacy_origin IS NOT NULL) are exempt -- they use legacy edges.
MATCH (fr:FeatureRequest)
WHERE fr.legacy_origin IS NULL // REQUIRED FILTER: exempt tombstones
OPTIONAL MATCH (fr)-[:INCLUDES_UC]->(uc:UseCase)
WITH fr, count(uc) AS uc_count
WHERE uc_count = 0
RETURN fr.id AS fr_id, 'FeatureRequest stored, but INCLUDES_UC matched no UseCase (likely UC ids did not exist at write time)' AS problem
```
#### Check 7.5: Duplicate FR-NNN markdown files on disk
This check is **filesystem-level** (not Cypher) — it detects two or more `.tl/feature-requests/FR-NNN-*.md` files sharing the same `FR-NNN` prefix. Such duplicates mean the FR-id was reused for two different features without renumbering, producing the same kind of confusion that `tl-conductor --feature FR-NNN` resolves to a coin-flip artifact.
**How to run** (bash, in project root):
```bash
ls .tl/feature-requests/FR-*.md 2>/dev/null \
| sed -E 's|.*/(FR-[A-Za-z0-9-]+?-[0-9]+).*\.md$|\1|' \
| sort \
| uniq -d
```
**Severity: CRITICAL**. Any output (one fr_id per line) is a violation. Resolution: rename the duplicate file to a free FR-id (use Step 6.1 allocation algorithm in `nacl-sa-feature`), then backfill its `:FeatureRequest` graph node. Don't merge the two markdowns — they describe genuinely different features.
#### Check 7.6: FR-NNN id used by multiple node labels (cross-label collision)
A single `FR-NNN` value should belong to **at most one** node label across the graph. Historically some projects used `FR-NNN` simultaneously for `:Task` (intake-pipeline ticket) and `:FeatureRequest` (refined spec). The two coexisted via different labels but caused real confusion: `tl-plan --feature FR-007` could resolve either node depending on the query. Tombstones rename their ids out of this namespace (`FR-LEG-*`, `FR-LEG-INTAKE-*`), but ad-hoc collisions still occur when an FR allocator forgets to scan all labels.
```cypher
// L7.6 -- Severity: CRITICAL
// FR-id reuse across labels in the active namespace (excluding LEG tombstones).
MATCH (n)
WHERE n.id IS NOT NULL
AND n.id =~ 'FR-([A-Za-z]+-)?[0-9]+'
AND NOT n.id STARTS WITH 'FR-LEG-'
WITH n.id AS fr_id, collect(DISTINCT labels(n)[0]) AS labels_seen
WHERE size(labels_seen) > 1
RETURN fr_id, labels_seen,
'FR-id used by multiple labels — only :FeatureRequest is canonical for active namespace' AS problem
ORDER BY fr_id
```
Resolution: rename the non-`:FeatureRequest` node into a tombstone namespace (e.g. `:Task {id: 'FR-LEG-INTAKE-007'}`) preserving all its edges via `SET n.id = ...`. Never delete — the historical lineage may be referenced by other artifacts.
---
### Level 8: Staleness Closure
**Goal:** When an upstream node changes, write-skills stamp the snapshot-bearing dependents (`Task`, `UseCase`, `Form`, `Requirement`) with a review flag. This level is the read-only gate that surfaces them; closure skills (`nacl-tl-release`, `nacl-tl-conductor`) refuse while blocking ones remain. Every flag is read with `coalesce(n.review_status,'current')`, so a graph that has never been stamped passes cleanly (every node is implicitly `current`).
**Two flags, because a change asks two different questions.** Un-built code and shipped code are not downstream of a change in the same way, and conflating them is what makes this gate unusable:
| flag | question | severity | exit |
|---|---|---|---|
| `stale` | *this task must be regenerated from the new spec* | CRITICAL (8.1) | `nacl-tl-plan` regenerates it |
| `spec_drift` | *shipped code, spec moved under it — does the code still satisfy it?* | budgeted (8.1b) | a review verdict (`nacl-tl-fix` Step 7.5b) |
Re-planning is not applicable to shipped code, so a `spec_drift` node has no `tl-plan` exit — treating it as CRITICAL makes the gate permanently red with no reachable green, which trains operators to skip it. The observed failure mode: 87 flagged tasks, 67 of them `done`, six origins, eleven days, every release in that window shipping past the gate. A gate that blocks everything blocks nothing. 8.1b keeps `spec_drift` visible and bounded instead: WARNING while the backlog is small and fresh, CRITICAL the moment it outgrows its budget — so it drains or it escalates, but never silently accrues.
This level writes nothing — it reads the flags that the producers set.
#### Check 8.1: Stale nodes not yet re-planned (project-wide)
```cypher
// L8.1 -- Severity: CRITICAL
// A node marked 'stale' is un-built work whose spec moved: it must be regenerated
// before it is developed. stale_origin/stale_since are the lineage answer
// ("why / since when"). Shipped nodes carry 'spec_drift' instead and are graded
// by 8.1b — re-planning cannot close them, so they must not block here.
MATCH (n)
WHERE coalesce(n.review_status, 'current') = 'stale'
RETURN labels(n)[0] AS node_type, n.id AS id,
coalesce(n.name, n.title, n.description) AS display,
n.stale_origin AS caused_by, n.stale_reason AS reason, n.stale_since AS since,
'Node is stale (spec moved before the work was built) and not yet re-planned' AS problem
ORDER BY n.stale_since
```
#### Check 8.1b: Spec-drift backlog on shipped work (project-wide, budgeted)
Resolve the budget from `config.yaml` `validation.spec_drift_budget`
(`max_count`, `max_age_days`; seeded by `nacl-init`, defaults 25 / 14). A project
that has not declared one uses those defaults — never treat an absent budget as
"unlimited".
```cypher
// L8.1b -- Severity: WARNING within budget, CRITICAL when exceeded
// Params: $driftMaxCount, $driftMaxAgeDays (config validation.spec_drift_budget)
// Shipped code whose spec moved under it. Each needs a review verdict, not a
// re-plan. Bounded on BOTH axes: a backlog that grows past max_count, or any
// single item older than max_age_days, escalates to CRITICAL — that is what
// stops this from becoming a permanently-red gate everyone learns to skip.
MATCH (n)
WHERE coalesce(n.review_status, 'current') = 'spec_drift'
WITH collect(n) AS drifted
WITH drifted, size(drifted) AS total,
[x IN drifted WHERE x.stale_since < datetime() - duration({days: $driftMaxAgeDays})] AS overdue
RETURN total AS drift_count,
size(overdue) AS overdue_count,
[x IN overdue | x.id] AS overdue_ids,
[x IN drifted | x.stale_origin] AS origins,
CASE WHEN total > $driftMaxCount OR size(overdue) > 0
THEN 'CRITICAL' ELSE 'WARNING' END AS severity,
CASE WHEN total > $driftMaxCount OR size(overdue) > 0
THEN 'Spec-drift backlog past budget — review the flagged shipped tasks (nacl-tl-fix Step 7.5b verdict) or record why they stand'
ELSE 'Spec-drift backlog within budget — shipped tasks awaiting a review verdict' END AS problem
```
> Report 8.1b at the severity the query returns. When it returns `CRITICAL` the overall status is `FAIL` exactly as any other CRITICAL, and the release refusal detail is `spec-drift-backlog` (condition #7). When it returns `WARNING` the release may proceed — the backlog is recorded, not hidden.
#### Check 8.2: Stale closure of a single change (scoped, `--scope=intra-uc`)
Used by `nacl-sa-feature` Phase 4 after a change, to confirm the just-modified node's dependent set was cleared. Composes with `sa_impact_closure`.
```cypher
// L8.2 -- Severity: CRITICAL (scoped)
// Params: $changedNodeId — the node that was just changed.
// Only the dependents of $changedNodeId that are still stale.
MATCH (changed {id: $changedNodeId})
MATCH (changed)-[:HAS_ATTRIBUTE|MAPS_TO|HAS_FIELD|USES_FORM|HAS_STEP|HAS_REQUIREMENT|REALIZED_BY
|ACTOR|CONTAINS_UC|CONTAINS_ENTITY|GENERATES|INCLUDES_UC
|EXPOSES|IMPLEMENTS|DEPENDS_ON*1..6]-(dep)
WHERE coalesce(dep.review_status, 'current') = 'stale'
RETURN DISTINCT dep.id AS id, labels(dep)[0] AS node_type,
dep.stale_origin AS caused_by, dep.stale_reason AS reason,
'Dependent of changed node is still stale' AS problem
```
---
### Level 9: Decision Provenance
**Goal:** Every structural change records *why* it was made, graph-natively, as a `:Decision` node linked to the artifacts it shaped — so "why was this decided, a year later" is the `sa_decisions_for_node` / `sa_timeline_of_why` query, not git archaeo
[…] pełny plik w paczce .zip
Versions
The database has no other skills named sa-validate.
Database snapshot: 13.11.2026 · package version cc8a91d1fa97 (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 91nacl-sa-validate
Validate specification consistency through Neo4j Cypher queries. Internal validation (L1-L13): data consistency, model connectivity, requirement completeness, form-domain traceability, UC-form validation, cross-module consistency, FeatureRequest consistency, staleness closure,… - 90nacl-sa-validate
Validate NaCl SA graph consistency, connectivity, requirements, form-domain traceability, UC-form coverage, cross-module rules, feature requests, staleness closure, decision provenance, screen state machines, behavior slices, domain error taxonomy, cache & degradation policies,… - 90consistency-check
Use to validate DAE artifacts for schema correctness and cross-artifact consistency. Triggers — "/engineer.consistency-check", "check consistency", "validate the artifacts", "are the specs and ACs in sync", "audit this feature". - 100cross-validate-artifacts
Cross-validate documentation and artifacts across the codebase for consistency, conflicts, and contradictions. Use when users ask to "cross-validate", "validate docs", "check documentation consistency", "audit documentation", or find conflicts/contradictions in docs. Supports… - 100repo-consistency
Checks documentation consistency across the repository. Use when user asks to "check consistency", "are the documents consistent", "is everything aligned", "verify documentation", or "/repo-consistency". - 100validate-test-coverage
Validate test coverage against acceptance criteria when the user asks to check test coverage, verify tests match requirements, audit test completeness, or cross-reference user stories with test cases