clayers 0.1.3

Cognitive layers: structured XML specifications with version control and machine-verifiable traceability
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Agent Guidance: Workflow instructions, onboarding skill, and artifact
  review skill. Content is stored as text in llm:node elements using
  CDATA sections, extracted at adopt time by the CLI.
-->
<spec:clayers xmlns:spec="urn:clayers:spec"
       xmlns:pr="urn:clayers:prose"
       xmlns:org="urn:clayers:organization"
       xmlns:rel="urn:clayers:relation"
       xmlns:art="urn:clayers:artifact"
       xmlns:llm="urn:clayers:llm"
       spec:index="index.xml">

  <!-- Content descriptions -->

  <pr:section id="agent-workflow-instructions">
    <pr:title>Agent workflow instructions</pr:title>
    <pr:shortdesc>The spec-first development workflow injected into
    CLAUDE.md or AGENTS.md during adoption.</pr:shortdesc>
    <pr:p>This section's llm:node contains the markdown text that gets
    wrapped in HTML comment markers and appended to the project's agent
    file. It describes the six-step spec-first workflow and references
    to clayers commands for validation, coverage, connectivity, and
    drift.</pr:p>
  </pr:section>

  <pr:section id="skill-clayers-onboard">
    <pr:title>Onboard skill</pr:title>
    <pr:shortdesc>Comprehensive codebase onboarding skill for Claude Code,
    with catch-up mode for filling gaps in existing specs.</pr:shortdesc>
    <pr:p>This section's llm:node contains the full SKILL.md content for
    the clayers-onboard skill. The content includes YAML frontmatter,
    six onboarding phases, a catch-up mode for gap filling, and a
    complete reference section with XML patterns and commands.</pr:p>
  </pr:section>

  <pr:section id="skill-clayers-review-artifacts">
    <pr:title>Review artifacts skill</pr:title>
    <pr:shortdesc>Artifact review and coverage improvement skill for
    Claude Code with drift root-cause analysis.</pr:shortdesc>
    <pr:p>This section's llm:node contains the full SKILL.md content for
    the clayers-review-artifacts skill. The content includes eight review
    phases, a decision framework for map-vs-exempt choices, and guidance
    for revision comparison.</pr:p>
  </pr:section>

  <!-- Topic typing -->

  <org:reference ref="agent-workflow-instructions">
    <org:purpose>Reference text for the development workflow injected
    into agent files during adoption.</org:purpose>
  </org:reference>

  <org:reference ref="skill-clayers-onboard">
    <org:purpose>Reference content for the onboarding skill template
    generated by adopt --skills.</org:purpose>
  </org:reference>

  <org:reference ref="skill-clayers-review-artifacts">
    <org:purpose>Reference content for the artifact review skill template
    generated by adopt --skills.</org:purpose>
  </org:reference>

  <!-- Relations -->

  <rel:relation type="depends-on" from="skill-clayers-onboard" to="agent-workflow-instructions">
    <rel:note>The onboarding skill builds on the workflow instructions,
    providing detailed phase-by-phase guidance for the same process.</rel:note>
  </rel:relation>

  <rel:relation type="depends-on" from="skill-clayers-review-artifacts" to="skill-clayers-onboard">
    <rel:note>The review skill assumes onboarding has been done and
    focuses on maintaining coverage as code evolves.</rel:note>
  </rel:relation>

  <!-- Extractable content (CDATA preserves markdown formatting) -->

  <llm:node ref="agent-workflow-instructions" format="markdown"><![CDATA[
## Clayers Development Workflow

This project uses [clayers](https://github.com/inferaldata/clayers) for
structured, layered specifications with machine-verifiable traceability.

**Spec first, code second.** Before implementing, update the spec to
describe what you are building.

1. **Update the spec** in `clayers/` — add prose, terminology, relations
2. **Validate**: `clayers validate clayers/PROJECT/`
3. **Implement** the code
4. **Map spec to code** with artifact mappings, fix hashes
5. **Iterate on quality**:
   - Coverage: `clayers artifact --coverage clayers/PROJECT/`
   - Connectivity: `clayers connectivity clayers/PROJECT/`
   - Drift: `clayers artifact --drift clayers/PROJECT/`
6. **Commit** spec + code together

**Plans go in the spec.** Use the `pln:plan` layer to write implementation
plans and save them in the knowledge base (`clayers/`). Plans are versioned,
queryable, and linked to the concepts they implement.

**Looking for what to do?** Drive spec coverage to 100%. Map every spec
node to implementing code. This naturally leads to implementing everything
that was specified.

Install: `cargo install clayers`

See [clayers documentation](https://github.com/inferaldata/clayers) for
the full layer reference (prose, terminology, organization, relation,
decision, source, plan, artifact, llm, revision).
]]></llm:node>

  <llm:node ref="skill-clayers-onboard" format="markdown"><![CDATA[
---
name: clayers-onboard
description: >
  Systematically onboard this project to clayers specifications. Analyzes the
  entire codebase, creates structured specs with prose/terminology/relations/LLM
  descriptions, maps all code with artifact traceability, and iterates until
  coverage, connectivity, and drift are all clean. Also supports catch-up mode
  to fill gaps in an existing knowledge model. Use when: "onboard to clayers",
  "create specs", "clayers-onboard", "drive coverage to 100%", "catch up",
  "fill spec gaps", "missing coverage".
argument-hint: "[--resume | --phase N | --catch-up]"
allowed-tools:
  - Bash(clayers validate *)
  - Bash(clayers artifact *)
  - Bash(clayers connectivity *)
  - Bash(clayers query *)
  - Bash(clayers schema *)
---

# Clayers Onboard

Systematically create a complete clayers specification for **{{PROJECT_NAME}}**.

The goal: every meaningful code construct is described in the spec, mapped via
artifact traceability, and verified clean by the tooling. This is not a quick
sketch -- it is a thorough, exhaustive extraction that leaves no code unmapped.

## Prerequisites

Before starting, verify:

1. **clayers is installed**: run `clayers --version`
2. **Project is adopted**: `.clayers/schemas/` exists with XSD files, and
   `clayers/{{PROJECT_NAME}}/index.xml` exists. If not, run `clayers adopt .`
3. **You can read the entire codebase**: you need access to all source files

**Mode selection:**
- **Fresh onboarding** (no arguments or `--phase 1`): Start from Phase 1.
  Use when the spec is empty or nearly empty.
- **Resume** (`--resume`): Assess current state and pick up where you left
  off. Run coverage and connectivity to determine which phase to continue.
- **Catch-up** (`--catch-up`): The spec exists but has gaps. Skip Phase 1
  and go directly to the Catch-Up section below. Use when: coverage is
  insufficient, new code was added without spec updates, or a previous
  session left the knowledge model incomplete.

---

## Catch-Up Mode

**Use when**: the spec already exists but coverage is incomplete. This
happens when new code was added without corresponding spec updates, when
a previous onboarding session was interrupted, or when an LLM lost context
and left gaps in the knowledge model.

Catch-up is NOT about fixing mappings (use `/clayers-review-artifacts` for
that). Catch-up is about finding concepts that are completely absent from
the knowledge model -- code that has no spec node at all.

### Step 1: Assess current state

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
clayers artifact --coverage clayers/{{PROJECT_NAME}}/ --code-path src/
clayers connectivity clayers/{{PROJECT_NAME}}/
clayers validate clayers/{{PROJECT_NAME}}/
```

Record:
- Total nodes, mapped, exempt, unmapped
- Code coverage % per file
- Isolated nodes
- Any validation errors

### Step 2: Identify uncovered code

Focus on the "code coverage" section of the coverage output. For each file
with uncovered ranges (`NOT COVERED`), read the uncovered code and ask:

**Is there a spec node that should describe this code?**

Build a gap list organized by type:

```
MISSING SPEC NODES:
  src/auth/jwt.rs:45-120  -- JWT token validation (no spec node exists)
  src/api/handlers.rs:200-280  -- bulk import endpoint (not described)

MISSING TERMS:
  "tenant" -- used 47 times across codebase, no trm:term
  "pipeline stage" -- core concept, undefined

MISSING RELATIONS:
  auth module depends on database module (no rel:relation)

THIN SPEC NODES (exist but lack depth):
  section-api -- has 2-sentence description for a 500-line module
```

### Step 3: Scan for missing domain terminology

Compare the codebase vocabulary against existing terms:

```bash
# List existing terms
clayers query clayers/{{PROJECT_NAME}}/ '//trm:term/trm:name' --text
```

Then scan the code for domain-specific words, type names, and concepts
that appear frequently but have no corresponding term. Look in:
- Type/struct/class names
- Function names (especially public API)
- Constants and configuration keys
- Comments that define concepts
- Documentation and README files

### Step 4: Scan for missing module descriptions

```bash
# List existing spec sections
clayers query clayers/{{PROJECT_NAME}}/ '//pr:section/pr:title' --text
```

Compare against the project's directory structure. Each major module or
component should have a corresponding spec section. Look for:
- Source directories with no spec file
- Files with significant logic but no artifact mapping
- New modules added since the last onboarding

### Step 5: Check for shallow spec nodes

For each existing spec node, assess whether its description is adequate:

```bash
# List all spec nodes
clayers query clayers/{{PROJECT_NAME}}/ '//*[@id]/@id' --text
```

A spec node is "shallow" if:
- The prose is just one sentence for a complex concept
- It lacks an LLM description (`llm:node`)
- It has no relations to other nodes (isolated)
- Its artifact mapping covers 200+ lines without decomposition
- The description doesn't match what the code actually does

For each shallow node, decide:
- **Deepen**: Add more prose, sub-sections, terms, relations
- **Decompose**: Split into multiple focused nodes
- **Update**: Rewrite to match current code (it may have evolved)

### Step 6: Execute the gap fill

For each item on your gap list, apply the appropriate phase:

| Gap type | Action | Go to |
|----------|--------|-------|
| Missing term | Create `trm:term` | Phase 2 |
| Missing spec node | Create spec file/section | Phase 3 |
| Missing artifact mapping | Create `art:mapping` | Phase 4 |
| Missing relation | Add `rel:relation` | Phase 3 |
| Missing LLM description | Add `llm:node` | Phase 3 |
| Shallow node | Deepen/decompose | Phase 3 |

Work through the gap list systematically. After each batch of changes:

```bash
clayers validate clayers/{{PROJECT_NAME}}/
clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/
clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/
```

### Step 7: Verify catch-up is complete

Run the full quality suite (same as Phase 5 + Phase 6):

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
clayers connectivity clayers/{{PROJECT_NAME}}/
clayers artifact --drift clayers/{{PROJECT_NAME}}/
clayers validate clayers/{{PROJECT_NAME}}/
```

Compare against your Step 1 baseline:
- Unmapped nodes should be zero (or reduced)
- Code coverage should be higher
- Isolated nodes should be zero
- No new validation errors

If gaps remain, repeat Steps 2-6 for the remaining items.

---

## Phase 1: Codebase Discovery

**Goal**: Build a complete mental model of the project before writing any XML.

### 1.1 Inventory source directories

Scan the project tree. For each directory containing source code:
- Note its purpose (e.g., `src/auth/` = authentication logic)
- Count files and approximate lines of code
- Identify the primary language

Skip: `node_modules/`, `target/`, `.git/`, `vendor/`, build outputs.

### 1.2 Catalog modules and components

For each source directory, identify:
- **Modules/packages**: logical groupings of code (e.g., `auth`, `api`, `db`)
- **Entry points**: main functions, HTTP handlers, CLI commands, event handlers
- **Data types**: structs, classes, enums, interfaces that carry domain semantics
- **Key functions**: functions that implement core business logic
- **External boundaries**: API endpoints, database queries, file I/O, network calls

### 1.3 Extract domain concepts

Read through the code and documentation to identify:
- **Domain terms**: words with specific meaning in this project (e.g., "workspace",
  "tenant", "pipeline", "artifact")
- **Concept relationships**: which concepts depend on, refine, or reference others
- **Concept hierarchy**: parent-child relationships between concepts

### 1.4 Map dependencies

For each module/component, note:
- What it depends on (imports, calls)
- What depends on it (reverse imports)
- External dependencies (libraries, services)

### 1.5 Document your findings

Write a structured summary as notes. This will drive Phases 2-4. Organize by:

```
Module: <name>
  Purpose: <one sentence>
  Files: <list>
  Key types: <list>
  Key functions: <list>
  Domain concepts: <list>
  Depends on: <list of other modules>
```

**Success criteria**: You can describe every source directory's purpose and how
modules relate to each other.

---

## Phase 2: Terminology Extraction

**Goal**: Create `trm:term` elements for every domain concept.

### 2.1 Create a terminology file

If the spec doesn't already have terminology, create a file for it.
Register it in `clayers/{{PROJECT_NAME}}/index.xml`:

```xml
<!-- In index.xml, add: -->
<file href="terminology.xml" layer="urn:clayers:terminology"/>
```

Or add terms to existing topic files (preferred when terms are closely tied
to a specific topic).

### 2.2 Write term elements

For each domain concept from Phase 1, create a term:

```xml
<trm:term id="term-{concept-name}">
  <trm:name>{Concept Name}</trm:name>
  <trm:definition>{Precise, one-paragraph definition. State what it IS,
  not what it does. Include scope, constraints, and relationships to
  other terms. Reference other terms with trm:ref where appropriate.}</trm:definition>
</trm:term>
```

**Guidelines**:
- IDs must be unique across the entire spec. Use `term-` prefix.
- Definitions should be self-contained: a reader unfamiliar with the code
  should understand the concept from the definition alone.
- Cross-reference related terms: `<trm:ref term="term-other">other</trm:ref>`
- Group related terms in the same file.

### 2.3 Validate

After adding terms, validate:

```bash
clayers validate clayers/{{PROJECT_NAME}}/
```

Fix any errors before proceeding.

**Success criteria**: Every domain concept from Phase 1 has a `trm:term` with
a precise definition. Validation passes.

---

## Phase 3: Spec File Creation

**Goal**: Create spec files organized by topic, each containing all layers
for that topic.

### 3.1 Organize by topic, not by layer

Each spec file should cover one major topic (module, component, or concept
cluster). A single file contains prose, organization, relations, and LLM
descriptions for its topic. Do NOT create separate files per layer type.

File naming: `{topic-name}.xml` (kebab-case).

### 3.2 File template

Every spec file must have this structure:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
  {Topic title}: {Brief description of what this file covers.}
-->
<spec:clayers xmlns:spec="urn:clayers:spec"
       xmlns:pr="urn:clayers:prose"
       xmlns:trm="urn:clayers:terminology"
       xmlns:org="urn:clayers:organization"
       xmlns:rel="urn:clayers:relation"
       xmlns:art="urn:clayers:artifact"
       xmlns:llm="urn:clayers:llm"
       spec:index="index.xml">

  <!-- Vocabulary (terms specific to this topic) -->

  <trm:term id="term-{topic-specific-concept}">
    <trm:name>{Concept}</trm:name>
    <trm:definition>{Definition}</trm:definition>
  </trm:term>

  <!-- Content -->

  <pr:section id="{topic-id}">
    <pr:title>{Topic Title}</pr:title>
    <pr:shortdesc>{One-sentence summary.}</pr:shortdesc>

    <pr:p>{Detailed prose describing what this component/module does,
    how it works, its design rationale, and its role in the system.
    Use multiple paragraphs if needed.}</pr:p>

    <pr:p>{Additional paragraphs for subtopics, algorithms, data flow,
    error handling, etc.}</pr:p>
  </pr:section>

  <!-- Subsections for major parts of the topic -->

  <pr:section id="{topic-subtopic}">
    <pr:title>{Subtopic}</pr:title>
    <pr:p>{Description of this specific aspect.}</pr:p>
  </pr:section>

  <!-- Topic typing -->

  <org:concept ref="{topic-id}">
    <org:purpose>{Why this concept exists in the system.}</org:purpose>
  </org:concept>

  <!-- Use org:task for procedural/action topics -->
  <!--
  <org:task ref="{topic-id}">
    <org:purpose>{What this task accomplishes.}</org:purpose>
    <org:actor>{Who or what performs it.}</org:actor>
  </org:task>
  -->

  <!-- Use org:reference for API/config/data-structure topics -->
  <!--
  <org:reference ref="{topic-id}">
    <org:purpose>{What information this reference provides.}</org:purpose>
  </org:reference>
  -->

  <!-- Relations -->

  <rel:relation type="depends-on" from="{topic-id}" to="{other-topic-id}">
    <rel:note>{Why this dependency exists.}</rel:note>
  </rel:relation>

  <rel:relation type="refines" from="{subtopic-id}" to="{topic-id}">
    <rel:note>{How the subtopic refines the parent topic.}</rel:note>
  </rel:relation>

  <!-- Machine descriptions -->

  <llm:node ref="{topic-id}">
    {Concise description for LLM consumption. Include: what it is,
    what it does, key behaviors, relationships to other components.
    Written as plain text, not XML.}
  </llm:node>

</spec:clayers>
```

### 3.3 Register every file in index.xml

For each new spec file, add an entry to `clayers/{{PROJECT_NAME}}/index.xml`:

```xml
<file href="{filename}.xml" layer="urn:clayers:prose"/>
```

Use the primary layer as the `layer` attribute (usually `urn:clayers:prose`
for topic files).

### 3.4 Relation types

Use these relation types to connect spec nodes:

| Type | Meaning | Example |
|------|---------|---------|
| `depends-on` | A requires B to function | auth depends-on database |
| `refines` | A is a more specific version of B | jwt-auth refines auth |
| `references` | A mentions or uses B | api-handler references auth |
| `precedes` | A must happen before B | init precedes serve |
| `extends` | A adds capabilities to B | plugin extends core |

### 3.5 Validate after each file

```bash
clayers validate clayers/{{PROJECT_NAME}}/
```

Common errors:
- Duplicate IDs: rename one
- Dangling references: check spelling of `ref`, `from`, `to` attributes
- Missing index entry: add `<file>` element to index.xml

**Success criteria**: Every major module/component from Phase 1 has a spec
file with prose, organization, relations, and LLM descriptions. All files
registered in index.xml. Validation passes with zero errors.

---

## Phase 4: Artifact Mapping

**Goal**: Link every spec node to its implementing code with precise
line ranges.

### 4.1 Determine the revision name

Check `clayers/{{PROJECT_NAME}}/revision.xml` for the current revision name
(usually `draft-1`).

### 4.2 Create artifact mappings

For each spec node that describes code (sections, terms that map to
implementations), add an artifact mapping. Mappings go in the same file
as the spec node they reference.

```xml
<art:mapping id="map-{descriptive-name}">
  <art:spec-ref node="{spec-node-id}"
            revision="draft-1"
            node-hash="sha256:placeholder"/>
  <art:artifact repo="{{PROJECT_NAME}}"
            repo-revision="HEAD"
            path="{relative/path/to/file.rs}">
    <art:range hash="sha256:placeholder"
               start-line="{start}" end-line="{end}"/>
  </art:artifact>
  <art:coverage>full</art:coverage>
  <art:note>{Brief description of what the code implements.}</art:note>
</art:mapping>
```

**Guidelines**:
- `node` must reference an existing spec node ID
- `path` is relative to the repo root
- `start-line` and `end-line` define the exact code range (inclusive)
- Use multiple `<art:range>` elements for non-contiguous code regions
- `coverage` is `full` if the range covers the complete implementation,
  `partial` if it covers only part
- Use `sha256:placeholder` for hashes -- the tooling will compute real values

### 4.3 Fix hashes

After adding mappings, compute real hashes:

```bash
clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/
clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/
```

### 4.4 Check drift

Verify everything is clean:

```bash
clayers artifact --drift clayers/{{PROJECT_NAME}}/
```

All mappings should show `OK`. If any show `DRIFTED`, investigate:
- **SPEC DRIFTED**: the spec node changed after the mapping was created.
  Run `--fix-node-hash` again.
- **ARTIFACT DRIFTED**: the code changed. Update `start-line`/`end-line`
  if lines shifted, then run `--fix-artifact-hash`.
- **UNAVAILABLE**: the file path doesn't exist. Fix the `path` attribute.

### 4.5 Exempt non-code nodes

Some spec nodes are abstract concepts, design rationale, or process
descriptions that don't map to code. Mark them as exempt:

```xml
<art:exempt node="{abstract-concept-id}"/>
```

### 4.6 Validate

```bash
clayers validate clayers/{{PROJECT_NAME}}/
```

**Success criteria**: Every spec node is either mapped to code or explicitly
exempted. `--drift` shows zero drift. Validation passes.

---

## Phase 5: Quality Iteration

**Goal**: Drive all quality metrics to their targets through iterative
improvement.

This phase is a loop. Run all three checks, fix issues, repeat.

### 5.1 Coverage check

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
```

**Read the output carefully:**

- **Unmapped nodes**: spec nodes with no artifact mapping and no exemption.
  For each: either add a mapping or mark as exempt.
- **Code coverage by file**: shows which lines are covered and which are not.
  For each uncovered range: either add a spec node + mapping for that code,
  or extend an existing mapping to include it.

**Target**: zero unmapped nodes, maximize code line coverage.

To check coverage for a specific code path:
```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/ --code-path src/
```

### 5.2 Connectivity check

```bash
clayers connectivity clayers/{{PROJECT_NAME}}/
```

**Read the output carefully:**

- **Isolated nodes**: nodes with no relations. For each: add at least one
  `rel:relation` connecting it to a related node.
- **Connected components**: ideally one large component. Multiple components
  suggest missing relations between concept clusters.
- **Acyclic violations**: cycles in relation types that should be acyclic
  (like `depends-on`). Break cycles by removing or redirecting a relation.

**Target**: zero isolated nodes, one connected component, zero acyclic
violations.

### 5.3 Drift check

```bash
clayers artifact --drift clayers/{{PROJECT_NAME}}/
```

**Target**: zero drifted mappings. If any drift:
- Spec drifted: `clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/`
- Artifact drifted: update line ranges if shifted, then
  `clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/`

### 5.4 Iteration loop

Repeat 5.1-5.3 until all three checks are clean. After fixing issues in
one area, the others may need re-checking (e.g., adding a mapping for
coverage creates a new node that needs relations for connectivity).

**Success criteria**: coverage shows zero unmapped nodes, connectivity shows
zero isolated nodes and zero acyclic violations, drift shows zero drifted
mappings.

---

## Phase 6: Final Validation

**Goal**: Verify everything is consistent and complete.

Run all checks in sequence:

```bash
# 1. Structural validation
clayers validate clayers/{{PROJECT_NAME}}/

# 2. Drift detection
clayers artifact --drift clayers/{{PROJECT_NAME}}/

# 3. Coverage analysis
clayers artifact --coverage clayers/{{PROJECT_NAME}}/

# 4. Connectivity analysis
clayers connectivity clayers/{{PROJECT_NAME}}/
```

All must pass cleanly:
- Validation: `OK (no structural errors)`
- Drift: `0 drifted`
- Coverage: zero unmapped nodes
- Connectivity: zero isolated nodes, zero acyclic violations

If any check fails, return to Phase 5 and iterate.

**Success criteria**: All four checks pass. The specification is complete.

---

## Reference: Namespace Declarations

Every spec file must declare the namespaces it uses. Copy this block
as needed:

```xml
<spec:clayers xmlns:spec="urn:clayers:spec"
       xmlns:pr="urn:clayers:prose"
       xmlns:trm="urn:clayers:terminology"
       xmlns:org="urn:clayers:organization"
       xmlns:rel="urn:clayers:relation"
       xmlns:dec="urn:clayers:decision"
       xmlns:src="urn:clayers:source"
       xmlns:pln="urn:clayers:plan"
       xmlns:art="urn:clayers:artifact"
       xmlns:llm="urn:clayers:llm"
       xmlns:rev="urn:clayers:revision"
       spec:index="index.xml">
```

Only include namespaces you actually use in the file.

## Reference: Complete Element Patterns

### Term

```xml
<trm:term id="term-example">
  <trm:name>Example</trm:name>
  <trm:definition>A precise definition. References
  <trm:ref term="term-other">other term</trm:ref> inline.</trm:definition>
</trm:term>
```

### Prose section

```xml
<pr:section id="example-section">
  <pr:title>Example Section</pr:title>
  <pr:shortdesc>One sentence summary.</pr:shortdesc>
  <pr:p>Paragraph text. Use <pr:code>inline code</pr:code>,
  <pr:b>bold</pr:b>, and <pr:i>italic</pr:i> as needed.</pr:p>
  <pr:note type="info">Informational note.</pr:note>
</pr:section>
```

### Ordered and unordered lists

```xml
<pr:ol>
  <pr:li>First item</pr:li>
  <pr:li>Second item</pr:li>
</pr:ol>

<pr:ul>
  <pr:li>Bullet item</pr:li>
</pr:ul>
```

### Topic typing

```xml
<!-- For concepts (what something IS) -->
<org:concept ref="section-id">
  <org:purpose>Why this concept exists.</org:purpose>
</org:concept>

<!-- For tasks (how to DO something) -->
<org:task ref="section-id">
  <org:purpose>What this task accomplishes.</org:purpose>
  <org:actor>Who or what performs it.</org:actor>
</org:task>

<!-- For reference material (lookup information) -->
<org:reference ref="section-id">
  <org:purpose>What information this provides.</org:purpose>
</org:reference>
```

### Relation

```xml
<rel:relation type="depends-on" from="node-a" to="node-b">
  <rel:note>Why A depends on B.</rel:note>
</rel:relation>
```

Types: `depends-on`, `refines`, `references`, `precedes`, `extends`.

### Artifact mapping

```xml
<art:mapping id="map-descriptive-name">
  <art:spec-ref node="spec-node-id"
            revision="draft-1"
            node-hash="sha256:placeholder"/>
  <art:artifact repo="{{PROJECT_NAME}}"
            repo-revision="HEAD"
            path="src/module.rs">
    <art:range hash="sha256:placeholder"
               start-line="10" end-line="50"/>
  </art:artifact>
  <art:coverage>full</art:coverage>
  <art:note>What the code implements.</art:note>
</art:mapping>

<!-- For non-contiguous code: multiple ranges -->
<art:mapping id="map-split-impl">
  <art:spec-ref node="spec-node-id"
            revision="draft-1"
            node-hash="sha256:placeholder"/>
  <art:artifact repo="{{PROJECT_NAME}}"
            repo-revision="HEAD"
            path="src/module.rs">
    <art:range hash="sha256:placeholder"
               start-line="10" end-line="30"/>
    <art:range hash="sha256:placeholder"
               start-line="80" end-line="95"/>
  </art:artifact>
  <art:coverage>full</art:coverage>
</art:mapping>

<!-- Exempt abstract/design nodes from mapping -->
<art:exempt node="abstract-concept-id"/>
```

### LLM description

```xml
<llm:node ref="spec-node-id">
  Concise description for machine consumption. Include: what it is,
  what it does, key behaviors, important relationships. Plain text,
  not XML. Keep under 200 words.
</llm:node>
```

### Decision record

```xml
<dec:decision id="dec-example" status="accepted" date="2025-01-15">
  <dec:title>Use X instead of Y</dec:title>
  <dec:context ref="relevant-section-id"/>
  <dec:rationale>Why this decision was made.</dec:rationale>
  <dec:consequence>What follows from this decision.</dec:consequence>
</dec:decision>
```

## Reference: Common Pitfalls

| Mistake | Problem | Fix |
|---------|---------|-----|
| Duplicate IDs | Validation error | Ensure IDs are unique across ALL spec files |
| Missing index entry | File is ignored | Add `<file>` to index.xml |
| Wrong namespace prefix | Element not recognized | Check namespace declarations |
| `sha256:placeholder` left after fix | Drift shows unavailable | Run `--fix-node-hash` and `--fix-artifact-hash` |
| Line ranges wrong | Artifact drift | Check `start-line`/`end-line`, run `--fix-artifact-hash` |
| Organizing by layer type | Hard to maintain | Organize by topic: one file per module/component |
| Circular `depends-on` | Acyclic violation | Restructure to break the cycle |
| Overly broad mapping | Low traceability | Use precise `start-line`/`end-line` ranges |
| Missing `spec:index` attribute | File not associated with spec | Add `spec:index="index.xml"` to root element |
| Self-referential mapping | Editing spec changes artifact hash, infinite drift | **Never** map a spec XML file to itself. Exempt or map to non-spec code |

## Reference: Useful Commands

```bash
# Validate
clayers validate clayers/{{PROJECT_NAME}}/

# Coverage (spec nodes + code lines)
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
clayers artifact --coverage clayers/{{PROJECT_NAME}}/ --code-path src/

# Connectivity (graph metrics)
clayers connectivity clayers/{{PROJECT_NAME}}/

# Drift detection
clayers artifact --drift clayers/{{PROJECT_NAME}}/

# Fix hashes (after editing spec or code)
clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/
clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/

# Query the spec (XPath)
clayers query clayers/{{PROJECT_NAME}}/ '//trm:term/trm:name' --text
clayers query clayers/{{PROJECT_NAME}}/ '//art:mapping' --count
clayers query clayers/{{PROJECT_NAME}}/ '//rel:relation[@type="depends-on"]'

# List all spec node IDs
clayers query clayers/{{PROJECT_NAME}}/ '//*[@id]/@id' --text

# Find unmapped nodes
clayers query clayers/{{PROJECT_NAME}}/ '//*[@id]/@id' --text
# Compare against mapped nodes:
clayers query clayers/{{PROJECT_NAME}}/ '//art:mapping/art:spec-ref/@node' --text
```
]]></llm:node>

  <llm:node ref="skill-clayers-review-artifacts" format="markdown"><![CDATA[
---
name: clayers-review-artifacts
description: >
  Review and improve artifact mappings for end-to-end coverage between
  specification and code. Analyzes both directions (spec-to-code and
  code-to-spec), identifies gaps, improves mapping granularity, resolves
  drift with root-cause analysis, and validates exemptions. Use when:
  "review artifacts", "check coverage", "fix drift", "clayers-review-artifacts",
  "improve mapping quality", "drive coverage to 100%".
argument-hint: "[--code-path src/] [--rev abc123]"
allowed-tools:
  - Bash(clayers validate *)
  - Bash(clayers artifact *)
  - Bash(clayers connectivity *)
  - Bash(clayers query *)
---

# Clayers Review Artifacts

Review and improve artifact mappings for **{{PROJECT_NAME}}** to achieve
end-to-end traceability between specification and code.

**Goal**: Every spec node maps to code. Every code region maps to a spec
node. Coverage is precise (small ranges, focused nodes). Drift is zero.
Exemptions are justified.

---

## Before You Start

Run all quality checks to establish baseline:

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
clayers artifact --drift clayers/{{PROJECT_NAME}}/
clayers connectivity clayers/{{PROJECT_NAME}}/
clayers validate clayers/{{PROJECT_NAME}}/
```

Record the numbers: total nodes, mapped, exempt, unmapped, drifted.
These are your starting point.

If `--rev` argument was provided, also check out the previous revision
and run coverage there for comparison (see Phase 7).

---

## Phase 1: Spec-to-Code Coverage (Unmapped Nodes)

**Question**: Which spec nodes have no artifact mapping?

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
```

Look at the "unmapped nodes" section. For EACH unmapped node:

### 1.1 Determine if the node describes code

Read the node content:
```bash
clayers query clayers/{{PROJECT_NAME}}/ '//*[@id="NODE_ID"]' --text
```

Ask: **Does this node describe something implemented in code?**

| Node type | Likely maps to code? | Example |
|-----------|---------------------|---------|
| Algorithm, data structure, function | Yes | "Binary search implementation" |
| API endpoint, CLI command | Yes | "The validate command" |
| Data type, struct, enum | Yes | "ArtifactMapping struct" |
| Configuration, schema definition | Yes | "XSD schema for prose layer" |
| Design rationale, motivation | No | "Why we chose SHA-256" |
| Process description, workflow | Maybe | Depends if code implements it |
| Abstract concept, philosophy | No | "Spec-first methodology" |
| Future work, roadmap item | No | "Planned: git integration" |

### 1.2 If YES: Create an artifact mapping

Find the implementing code. Search by:
- Function/type names mentioned in the spec prose
- File paths mentioned in related mappings
- Module structure matching the concept

Create a **precise** mapping. Prefer:

| Approach | Coverage strength | Prefer? |
|----------|------------------|---------|
| Specific function (20 lines) | Precise | Yes |
| Module section (80 lines) | Moderate | OK |
| Entire file (500 lines) | Broad | Avoid |

```xml
<art:mapping id="map-{descriptive-name}">
  <art:spec-ref node="{NODE_ID}"
            revision="draft-1"
            node-hash="sha256:placeholder"/>
  <art:artifact repo="{{PROJECT_NAME}}"
            repo-revision="HEAD"
            path="{path/to/file}">
    <art:range hash="sha256:placeholder"
               start-line="{start}" end-line="{end}"/>
  </art:artifact>
  <art:coverage>full</art:coverage>
  <art:note>{What this code implements from the spec node.}</art:note>
</art:mapping>
```

If the implementation spans multiple non-contiguous ranges, use
multiple `<art:range>` elements in a single mapping.

After adding mappings:
```bash
clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/
clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/
```

### 1.3 If NO: Exempt with justification

Think carefully before exempting. Ask yourself:

- **Is this truly abstract?** Or is there code that realizes this concept?
- **Could the concept be decomposed?** Maybe the abstract part is exempt
  but a concrete sub-aspect maps to code.
- **Am I being lazy?** If the code is hard to find, that's not a reason
  to exempt.

**If unsure, ask the user.** Present the node content and your reasoning.

To exempt:
```xml
<art:exempt node="{NODE_ID}"/>
```

Always add a comment explaining WHY:
```xml
<!-- Exempt: design rationale with no implementing code -->
<art:exempt node="dec-why-sha256"/>
```

### 1.4 Validate after each batch

```bash
clayers validate clayers/{{PROJECT_NAME}}/
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
```

**Success criteria**: Zero unmapped nodes (all mapped or explicitly exempted).

---

## Phase 2: Code-to-Spec Coverage (Uncovered Code)

**Question**: Which code regions have no spec node describing them?

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/ --code-path src/
```

Look at the "code coverage" section. For EACH file with uncovered ranges:

### 2.1 Analyze uncovered ranges

For each `NOT COVERED` range, read the code:
- What does this code do?
- Is it a distinct concept, or part of an already-mapped concept?
- Is it boilerplate/generated code that doesn't need spec coverage?

### 2.2 Extend existing mapping or create new spec node

**Option A: The code implements an already-described concept.**
Extend the existing mapping by adding another `<art:range>`:

```xml
<!-- Add a range to an existing mapping -->
<art:mapping id="map-existing">
  <art:spec-ref node="existing-concept" .../>
  <art:artifact ...>
    <art:range ... start-line="10" end-line="50"/>
    <!-- NEW: additional range for uncovered code -->
    <art:range hash="sha256:placeholder"
               start-line="80" end-line="95"/>
  </art:artifact>
</art:mapping>
```

**Option B: The code implements a new concept not yet in the spec.**
Create the spec node first (spec-first!), then map it:

1. Add `<pr:section>`, `<org:concept>`, `<rel:relation>`, `<llm:node>`
2. Register in index.xml if new file
3. Create `<art:mapping>` with precise line ranges
4. Fix hashes

### 2.3 Decompose broad mappings

If a file shows 100% coverage but all from one broad mapping (e.g.,
whole-file with 500 lines), consider splitting:

1. Identify distinct logical sections within the file
2. Create separate spec nodes for each section
3. Replace the single broad mapping with multiple precise mappings
4. Each mapping covers 10-80 lines ideally

**Coverage strength targets:**

| Strength | Lines | Quality | Action |
|----------|-------|---------|--------|
| Precise | 1-30 | Excellent | Keep |
| Moderate | 31-100 | Good | Keep or split if >80 |
| Broad | 101+ | Poor | Always split |

Check current mapping strengths:
```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
```

The output shows strength per mapping (e.g., `map-id: file.rs (150 lines, Broad)`).

**Success criteria**: Maximize code line coverage. No `Broad` mappings
unless the code is genuinely monolithic.

---

## Phase 3: Drift Resolution

**Question**: Are stored hashes consistent with current content?

```bash
clayers artifact --drift clayers/{{PROJECT_NAME}}/
```

For each drifted mapping, do NOT blindly fix. Analyze first.

### 3.1 ARTIFACT DRIFTED (code changed)

The code at the mapped lines changed. Investigate:

```bash
# What changed in this file?
git log --oneline -10 -- {file_path}
git diff HEAD~5 -- {file_path}
```

**Determine the cause:**

| Cause | Action |
|-------|--------|
| Lines shifted (refactor, added code above) | Update `start-line`/`end-line`, then `--fix-artifact-hash` |
| Function renamed/moved | Find new location, update path and/or line ranges |
| Semantic change (logic rewritten) | Review spec prose, update if needed, then fix hashes |
| Function deleted | Remove mapping, possibly remove/update spec node |
| File renamed/moved | Update `path` attribute |

**To update line ranges after a shift:**

1. Find where the function actually is now:
   ```bash
   grep -n 'fn function_name' {file_path}
   ```
2. Update `start-line` and `end-line` in the mapping
3. Run `clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/`
4. Verify: `clayers artifact --drift clayers/{{PROJECT_NAME}}/`

**Pattern matching for line shifts:**
If many mappings in the same file drifted, it's likely a line shift.
Calculate the offset (new_line - old_line) and apply uniformly.

### 3.2 SPEC DRIFTED (spec node changed)

The spec prose for a mapped node changed. This means the description
evolved but the mapping hash is stale.

```bash
clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/
```

Then verify the mapping still makes sense: does the code still implement
what the spec now describes? If the spec changed significantly, the
code mapping may need updating too.

### 3.3 UNAVAILABLE (file or node missing)

The mapped artifact can't be found. Possible causes:
- File was deleted or renamed
- Path is wrong (typo, different repo layout)
- Node ID was changed

**Fix**: Find the correct path/ID or remove the mapping.

### 3.4 Post-drift validation

After fixing all drift:
```bash
clayers artifact --drift clayers/{{PROJECT_NAME}}/
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
clayers validate clayers/{{PROJECT_NAME}}/
```

**Coverage may have changed after drift fixes** (line ranges moved,
files renamed). Re-run coverage and fix any new gaps.

**Success criteria**: Zero drifted mappings.

---

## Phase 4: Exemption Audit

**Question**: Are all exemptions justified?

List current exemptions:
```bash
clayers query clayers/{{PROJECT_NAME}}/ '//art:exempt/@node' --text
```

For EACH exempted node:

1. Read the node:
   ```bash
   clayers query clayers/{{PROJECT_NAME}}/ '//*[@id="NODE_ID"]' --text
   ```

2. Ask: **Is this STILL exempt-worthy?**
   - Did someone add implementing code since the exemption?
   - Was the node refined to be more concrete?
   - Could part of it now be mapped even if the whole can't?

3. **If the exemption is no longer valid**: Remove `<art:exempt>` and
   create an artifact mapping instead.

4. **If unsure**: Ask the user. Present the node content and explain
   your reasoning for keeping or removing the exemption.

**Success criteria**: Every exemption has a clear justification. No
node is exempted just because finding its code is difficult.

---

## Phase 5: Mapping Quality Review

**Question**: Are mappings precise and well-described?

### 5.1 Check mapping strengths

```bash
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
```

For each mapping, the output shows line count and strength classification.
Target: majority of mappings should be Precise (1-30 lines) or Moderate
(31-100 lines).

### 5.2 Split broad mappings

For any mapping classified as Broad (101+ lines):

1. Read the mapped code range
2. Identify logical sub-sections (functions, blocks, types)
3. Create separate spec sub-sections for each
4. Split the single mapping into multiple precise mappings
5. Each sub-mapping gets its own `<art:note>` explaining what it covers

### 5.3 Check mapping notes

Every mapping should have a descriptive `<art:note>`. Review:
- Does the note explain WHAT the code implements?
- Would someone reading only the note understand the mapping?
- Is the note current (matches what the code actually does)?

### 5.4 Check coverage values

Each mapping has `<art:coverage>full</art:coverage>` or `partial`.
Verify:
- `full`: the mapped range completely implements the spec node
- `partial`: the mapped range only partially implements it
  - Are there other ranges that complete the implementation?
  - Should additional ranges be added?

### 5.5 Spec node granularity

If a single spec node has many mappings pointing to it, the node may
be too broad. Consider decomposing:

```bash
# How many mappings per node?
clayers query clayers/{{PROJECT_NAME}}/ '//art:mapping/art:spec-ref/@node' --text
```

Count occurrences. If one node has 10+ mappings, it probably needs
to be split into sub-sections, each with their own mappings.

**Success criteria**: No Broad mappings. Every mapping has a descriptive
note. Coverage values are accurate.

---

## Phase 6: Connectivity Cross-Check

**Question**: Are mapped nodes well-connected in the spec graph?

```bash
clayers connectivity clayers/{{PROJECT_NAME}}/
```

Newly mapped nodes sometimes lack relations. For each node you mapped
or modified:
- Does it have at least one `<rel:relation>`?
- Is it connected to the main component (not isolated)?
- Are `depends-on` / `refines` / `references` relations accurate?

Fix isolated nodes by adding relations.

**Success criteria**: Zero isolated nodes.

---

## Phase 7: Revision Comparison (Optional)

Use when `--rev` argument is provided, or when you need to understand
how coverage changed between revisions.

### 7.1 Compare coverage across revisions

```bash
# Current coverage
clayers artifact --coverage clayers/{{PROJECT_NAME}}/

# Compare with a specific revision
git stash  # Save current work
git checkout {REV}
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
git checkout -  # Return
git stash pop   # Restore work
```

### 7.2 Analyze changes

Compare the two reports:
- **New unmapped nodes**: Spec grew but mappings didn't keep up
- **New uncovered code**: Code grew but spec didn't keep up
- **Changed coverage %**: Lines shifted, mappings drifted
- **New/removed exemptions**: Review justifications

### 7.3 Trace specific drift

For mappings that drifted between revisions:

```bash
git diff {OLD_REV}..HEAD -- {artifact_path}
```

This shows exactly what changed in the code, helping you decide
whether to update line ranges or update the spec.

---

## Phase 8: Final Verification

Run the full check suite:

```bash
# 1. Structural validation
clayers validate clayers/{{PROJECT_NAME}}/

# 2. Drift detection (exit code 0 = clean)
clayers artifact --drift clayers/{{PROJECT_NAME}}/

# 3. Coverage analysis
clayers artifact --coverage clayers/{{PROJECT_NAME}}/

# 4. Connectivity
clayers connectivity clayers/{{PROJECT_NAME}}/
```

**All must be clean:**
- Validation: OK
- Drift: 0 drifted
- Coverage: 0 unmapped nodes, no Broad mappings
- Connectivity: 0 isolated nodes

Report to the user:
- Starting state (from "Before You Start")
- Ending state (current numbers)
- What was added/changed/exempted
- Any decisions that need user input

---

## Decision Framework: Map vs. Exempt

When you're unsure whether a node should be mapped or exempted, use
this framework:

### Always map (never exempt)

- Functions, methods, implementations
- Data types (structs, enums, classes)
- CLI commands and handlers
- API endpoints
- Configuration schemas
- Test suites (map to the code they test)
- Constants and type definitions

### Usually exempt (but consider carefully)

- Design decisions (`dec:decision` elements) that explain WHY
- Historical context that doesn't correspond to current code
- Methodology descriptions (how to use clayers, not clayers itself)
- Future work items not yet implemented
- Cross-cutting concerns described once but implemented everywhere

### Ask the user when

- A concept is partially implemented (map the partial part?)
- The implementing code is in a different repository
- The node describes emergent behavior (no single code location)
- You found code that seems related but aren't sure
- The boundary between abstract and concrete is unclear

**Default**: Map. Only exempt when you're confident there is truly no
implementing code. When in doubt, ask.

---

## Anti-Patterns to Avoid

| Anti-pattern | Problem | Better approach |
|-------------|---------|----------------|
| Whole-file mapping | Broad, imprecise | Split into function-level ranges |
| Copy-paste line numbers without reading | Ranges may be wrong | Always read the code at those lines |
| Exempting because code is hard to find | Hides gaps | Search harder, ask user |
| Fixing hashes without analyzing drift | Masks real changes | Understand what changed first |
| One spec node with 10 mappings | Node too broad | Decompose into sub-sections |
| Mapping to comments or blank lines | Inflates coverage | Map to actual logic |
| Skipping connectivity after changes | Isolated nodes | Always check connectivity |
| Trusting old line ranges | Code shifts happen | Verify current positions |
| Self-referential mapping (spec file maps to itself) | Spec files are both spec and artifact; editing the spec changes the artifact hash, creating infinite drift loops | Exempt the node or map to non-spec code only. **Never** map a spec XML file to itself as an artifact |

---

## Quick Reference: Commands

```bash
# Coverage (both directions)
clayers artifact --coverage clayers/{{PROJECT_NAME}}/
clayers artifact --coverage clayers/{{PROJECT_NAME}}/ --code-path src/

# Drift
clayers artifact --drift clayers/{{PROJECT_NAME}}/

# Fix hashes
clayers artifact --fix-node-hash clayers/{{PROJECT_NAME}}/
clayers artifact --fix-artifact-hash clayers/{{PROJECT_NAME}}/

# Query spec
clayers query clayers/{{PROJECT_NAME}}/ '//art:exempt/@node' --text
clayers query clayers/{{PROJECT_NAME}}/ '//art:mapping/art:spec-ref/@node' --text
clayers query clayers/{{PROJECT_NAME}}/ '//*[@id="NODE_ID"]' --text
clayers query clayers/{{PROJECT_NAME}}/ '//art:mapping' --count

# Connectivity
clayers connectivity clayers/{{PROJECT_NAME}}/

# Validate
clayers validate clayers/{{PROJECT_NAME}}/
```
]]></llm:node>

  <!-- ================================================================== -->
  <!-- Artifact mappings for agent guidance nodes                         -->
  <!-- ================================================================== -->

  <art:mapping id="map-skill-clayers-review-artifacts">
    <art:spec-ref node="skill-clayers-review-artifacts"
              revision="draft-1"
              node-hash="sha256:0ffd819f27ecb233b24c7044aad1b389b563ca5f2ae8c325d20d28f200f93397"/>
    <art:artifact repo="clayers"
              repo-revision="9191483"
              path="crates/clayers/src/adopt.rs">
      <art:range hash="sha256:3ca74ed2fe22aba6fd9b4b15bfeecde3b60331032112f47475766219962fd586"
                 start-line="240" end-line="260"/>
    </art:artifact>
    <art:coverage>partial</art:coverage>
    <art:note>plant_skills extracts and writes the review-artifacts
    skill from embedded guidance XML to .claude/skills/.</art:note>
  </art:mapping>

  <art:mapping id="map-skill-clayers-onboard">
    <art:spec-ref node="skill-clayers-onboard"
              revision="draft-1"
              node-hash="sha256:04dc79dbaf2ce25a4d11db2bd5951f7b0f583e4a81b1bcb8e4518faa74d94199"/>
    <art:artifact repo="clayers"
              repo-revision="9191483"
              path="crates/clayers/src/adopt.rs">
      <art:range hash="sha256:3ca74ed2fe22aba6fd9b4b15bfeecde3b60331032112f47475766219962fd586"
                 start-line="240" end-line="260"/>
    </art:artifact>
    <art:coverage>partial</art:coverage>
    <art:note>plant_skills extracts and writes the onboard skill from
    embedded guidance XML to .claude/skills/.</art:note>
  </art:mapping>

  <art:mapping id="map-agent-workflow-instructions">
    <art:spec-ref node="agent-workflow-instructions"
              revision="draft-1"
              node-hash="sha256:d74a83030d4d70bab6a74fb7db9ccdf85fcb9854192f8e368c71226a53348739"/>
    <art:artifact repo="clayers"
              repo-revision="9191483"
              path="crates/clayers/src/adopt.rs">
      <art:range hash="sha256:07a8c63ed59ebb54b1f4b7798d4b095cfca2224cf452a23283a8abbcb75534bb"
                 start-line="16" end-line="31"/>
      <art:range hash="sha256:bccd6c531dbdb0737897f7548411a55b1139795362745027c9089a6327504597"
                 start-line="378" end-line="422"/>
    </art:artifact>
    <art:coverage>full</art:coverage>
    <art:note>extract_from_guidance retrieves workflow content (16-31),
    amend_agent_file injects it into AGENTS.md/CLAUDE.md (378-422).</art:note>
  </art:mapping>

</spec:clayers>