@transitrix/diagrams 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/activities/__tests__/gantt.test.js +39 -0
  2. package/dist/capability-map/CapabilityCardNode.d.ts +19 -0
  3. package/dist/capability-map/CapabilityCardNode.js +66 -0
  4. package/dist/capability-map/CapabilityMapView.d.ts +59 -0
  5. package/dist/capability-map/CapabilityMapView.js +204 -0
  6. package/dist/capability-map/CapabilityRootNode.d.ts +12 -0
  7. package/dist/capability-map/CapabilityRootNode.js +23 -0
  8. package/dist/capability-map/__tests__/CapabilityMapView.test.d.ts +1 -0
  9. package/dist/capability-map/__tests__/CapabilityMapView.test.js +217 -0
  10. package/dist/capability-map/__tests__/address.test.d.ts +1 -0
  11. package/dist/capability-map/__tests__/address.test.js +49 -0
  12. package/dist/capability-map/__tests__/dsm-layout.test.d.ts +1 -0
  13. package/dist/capability-map/__tests__/dsm-layout.test.js +46 -0
  14. package/dist/capability-map/__tests__/dsm-mutations.test.d.ts +1 -0
  15. package/dist/capability-map/__tests__/dsm-mutations.test.js +125 -0
  16. package/dist/capability-map/__tests__/dsm-validate.test.d.ts +1 -0
  17. package/dist/capability-map/__tests__/dsm-validate.test.js +56 -0
  18. package/dist/capability-map/address.d.ts +12 -0
  19. package/dist/capability-map/address.js +48 -0
  20. package/dist/capability-map/dsm-layout.d.ts +9 -0
  21. package/dist/capability-map/dsm-layout.js +125 -0
  22. package/dist/capability-map/dsm-mutations.d.ts +28 -0
  23. package/dist/capability-map/dsm-mutations.js +196 -0
  24. package/dist/capability-map/dsm-schema.d.ts +71 -0
  25. package/dist/capability-map/dsm-schema.js +14 -0
  26. package/dist/capability-map/dsm-theme.d.ts +20 -0
  27. package/dist/capability-map/dsm-theme.js +36 -0
  28. package/dist/capability-map/dsm-validate.d.ts +2 -0
  29. package/dist/capability-map/dsm-validate.js +93 -0
  30. package/dist/capability-map/index.d.ts +9 -0
  31. package/dist/capability-map/index.js +6 -0
  32. package/dist/compliance/__tests__/trace.test.d.ts +1 -0
  33. package/dist/compliance/__tests__/trace.test.js +144 -0
  34. package/dist/compliance/classify.js +7 -1
  35. package/dist/compliance/index.d.ts +2 -1
  36. package/dist/compliance/index.js +1 -0
  37. package/dist/compliance/reverse-index.js +4 -1
  38. package/dist/compliance/trace.d.ts +26 -0
  39. package/dist/compliance/trace.js +89 -0
  40. package/dist/compliance/types.d.ts +94 -1
  41. package/dist/goals/GoalNode.d.ts +18 -0
  42. package/dist/goals/GoalNode.js +91 -0
  43. package/dist/goals/GoalTreeView.d.ts +57 -0
  44. package/dist/goals/GoalTreeView.js +228 -0
  45. package/dist/goals/__tests__/GoalTreeView.test.d.ts +1 -0
  46. package/dist/goals/__tests__/GoalTreeView.test.js +296 -0
  47. package/dist/goals/index.d.ts +3 -0
  48. package/dist/goals/index.js +1 -0
  49. package/dist/goals/theme.d.ts +22 -0
  50. package/dist/goals/theme.js +32 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.js +1 -1
  53. package/dist/webview/__tests__/render-blocks.test.js +48 -0
  54. package/dist/webview/notation-style.d.ts +11 -0
  55. package/dist/webview/notation-style.js +11 -0
  56. package/dist/webview/render-blocks.js +8 -4
  57. package/dist/webview/render-goals.js +2 -1
  58. package/package.json +4 -1
  59. package/src/activities/__tests__/gantt.test.ts +45 -0
  60. package/src/capability-map/CapabilityCardNode.tsx +146 -0
  61. package/src/capability-map/CapabilityMapView.tsx +331 -0
  62. package/src/capability-map/CapabilityRootNode.tsx +38 -0
  63. package/src/capability-map/__tests__/CapabilityMapView.test.tsx +232 -0
  64. package/src/capability-map/__tests__/address.test.ts +59 -0
  65. package/src/capability-map/__tests__/dsm-layout.test.ts +52 -0
  66. package/src/capability-map/__tests__/dsm-mutations.test.ts +141 -0
  67. package/src/capability-map/__tests__/dsm-validate.test.ts +65 -0
  68. package/src/capability-map/address.ts +48 -0
  69. package/src/capability-map/dsm-layout.ts +142 -0
  70. package/src/capability-map/dsm-mutations.ts +208 -0
  71. package/src/capability-map/dsm-schema.ts +80 -0
  72. package/src/capability-map/dsm-theme.ts +53 -0
  73. package/src/capability-map/dsm-validate.ts +103 -0
  74. package/src/capability-map/index.ts +35 -0
  75. package/src/compliance/__tests__/trace.test.ts +157 -0
  76. package/src/compliance/classify.ts +7 -1
  77. package/src/compliance/index.ts +6 -0
  78. package/src/compliance/reverse-index.ts +3 -1
  79. package/src/compliance/trace.ts +118 -0
  80. package/src/compliance/types.ts +101 -1
  81. package/src/goals/GoalNode.tsx +212 -0
  82. package/src/goals/GoalTreeView.tsx +350 -0
  83. package/src/goals/__tests__/GoalTreeView.test.tsx +313 -0
  84. package/src/goals/index.ts +4 -0
  85. package/src/goals/theme.ts +54 -0
  86. package/src/index.ts +29 -1
  87. package/src/webview/__tests__/render-blocks.test.ts +54 -0
  88. package/src/webview/notation-style.ts +12 -0
  89. package/src/webview/render-blocks.ts +8 -4
  90. package/src/webview/render-goals.ts +2 -1
@@ -0,0 +1,157 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { buildComplianceIndex } from '../reverse-index.js';
3
+ import { buildRequirementTrace, buildTraceElementCatalog } from '../trace.js';
4
+ import type { ComplianceIndexInput } from '../types.js';
5
+ import type { ComplianceCodexDoc } from '../classify.js';
6
+
7
+ // Requirement traceability + hierarchy view.
8
+ //
9
+ // The two halves the view exposes:
10
+ // 1. Trace chain — derived_from → REQUIREMENT → ASSERTION → subject +
11
+ // realised_via.
12
+ // 2. Hierarchy — parent chain + children via the `parent` field
13
+ // (15-requirement.md §2.4 / ELEMENT_PRIMITIVES.md §7.13).
14
+
15
+ const input: ComplianceIndexInput = {
16
+ requirements: [
17
+ // A broad legislative parent decomposed into two child requirements.
18
+ { id: 'REQUIREMENT-DATA-PROTECTION-1', name: 'Personal-data protection', origin: 'legislative', derived_from: ['REGULATION-GDPR-2016-1'], element_kind: 'requirement' },
19
+ { id: 'REQUIREMENT-DATA-ERASURE-1', name: 'Erase on request within 30 days', origin: 'legislative', parent: 'REQUIREMENT-DATA-PROTECTION-1', derived_from: ['REGULATION-GDPR-2016-1'], element_kind: 'requirement' },
20
+ { id: 'REQUIREMENT-DATA-CONSENT-1', name: 'Obtain consent before processing', origin: 'legislative', parent: 'REQUIREMENT-DATA-PROTECTION-1', element_kind: 'requirement' },
21
+ // A process-product sub-requirement below the erasure duty (cross-origin).
22
+ { id: 'REQUIREMENT-ERASURE-SLA-1', name: 'Erasure SOP — 30d target', origin: 'process-product', parent: 'REQUIREMENT-DATA-ERASURE-1', element_kind: 'requirement' },
23
+ // Constraint hierarchy (mirror pattern).
24
+ { id: 'CONSTRAINT-EEA-TRANSFER-1', name: 'No transfer outside EEA without safeguards', element_kind: 'constraint' },
25
+ { id: 'CONSTRAINT-EEA-ANALYTICS-1', name: 'No PII in analytics logs', parent: 'CONSTRAINT-EEA-TRANSFER-1', element_kind: 'constraint' },
26
+ // Internal-only requirement — no source, no parent — for the empty-case sanity check.
27
+ { id: 'REQUIREMENT-INTERNAL-1', name: 'Internal-only', element_kind: 'requirement' },
28
+ ],
29
+ assertions: [
30
+ { id: 'ASSERTION-1', about: 'REQUIREMENT-DATA-ERASURE-1', subject: 'PRODUCT-MOBILE-1', realised_via: ['CAPABILITY-V1', 'PROCESS-PURGE-1'], status: 'compliant' },
31
+ { id: 'ASSERTION-2', about: 'REQUIREMENT-DATA-ERASURE-1', subject: 'PRODUCT-WEB-1', status: 'partial' },
32
+ { id: 'ASSERTION-3', about: 'REQUIREMENT-DATA-CONSENT-1', subject: 'PRODUCT-WEB-1', status: 'compliant' },
33
+ ],
34
+ };
35
+
36
+ const codex: ComplianceCodexDoc[] = [
37
+ { id: 'REGULATION-GDPR-2016-1', name: 'GDPR', type: 'REGULATION', jurisdiction: 'EU' },
38
+ ];
39
+
40
+ const catalog = buildTraceElementCatalog(
41
+ [{ id: 'PRODUCT-MOBILE-1', name: 'Mobile app' }, { id: 'PRODUCT-WEB-1', name: 'Web app' }],
42
+ [{ id: 'CAPABILITY-V1', name: 'Erasure capability v1' }, { id: 'PROCESS-PURGE-1', name: 'Purge process' }],
43
+ );
44
+
45
+ describe('buildComplianceIndex — requirementsByParent', () => {
46
+ const idx = buildComplianceIndex(input);
47
+ it('groups children of the same parent', () => {
48
+ const children = idx.requirementsByParent.get('REQUIREMENT-DATA-PROTECTION-1');
49
+ expect(children?.map(r => r.id).sort()).toEqual(['REQUIREMENT-DATA-CONSENT-1', 'REQUIREMENT-DATA-ERASURE-1']);
50
+ });
51
+ it('groups CONSTRAINT children the same way (element_kind-agnostic)', () => {
52
+ const children = idx.requirementsByParent.get('CONSTRAINT-EEA-TRANSFER-1');
53
+ expect(children?.map(r => r.id)).toEqual(['CONSTRAINT-EEA-ANALYTICS-1']);
54
+ });
55
+ it('returns undefined for a leaf with no children', () => {
56
+ expect(idx.requirementsByParent.has('REQUIREMENT-INTERNAL-1')).toBe(false);
57
+ });
58
+ });
59
+
60
+ describe('buildRequirementTrace — trace chain', () => {
61
+ const idx = buildComplianceIndex(input);
62
+ it('resolves derived_from codex artefacts on the sources block', () => {
63
+ const trace = buildRequirementTrace('REQUIREMENT-DATA-ERASURE-1', idx, catalog, codex);
64
+ expect(trace.sources).toHaveLength(1);
65
+ expect(trace.sources[0].id).toBe('REGULATION-GDPR-2016-1');
66
+ expect(trace.sources[0].codex?.jurisdiction).toBe('EU');
67
+ });
68
+ it('keeps a dangling derived_from ref with no codex when the artefact is missing', () => {
69
+ const local: ComplianceIndexInput = {
70
+ requirements: [{ id: 'REQUIREMENT-X-1', name: 'X', derived_from: ['LAW-MISSING-1'] }],
71
+ assertions: [],
72
+ };
73
+ const trace = buildRequirementTrace('REQUIREMENT-X-1', buildComplianceIndex(local), catalog);
74
+ expect(trace.sources).toEqual([{ id: 'LAW-MISSING-1' }]);
75
+ });
76
+ it('lists ASSERTIONs id-sorted, each with resolved subject + realised_via names', () => {
77
+ const trace = buildRequirementTrace('REQUIREMENT-DATA-ERASURE-1', idx, catalog, codex);
78
+ expect(trace.assertions.map(a => a.assertion.id)).toEqual(['ASSERTION-1', 'ASSERTION-2']);
79
+ expect(trace.assertions[0].subject).toEqual({ id: 'PRODUCT-MOBILE-1', name: 'Mobile app' });
80
+ expect(trace.assertions[0].realisedVia.map(r => r.name)).toEqual(['Erasure capability v1', 'Purge process']);
81
+ });
82
+ it('returns an empty assertions list for a REQUIREMENT with no filed claim', () => {
83
+ const trace = buildRequirementTrace('REQUIREMENT-DATA-PROTECTION-1', idx, catalog);
84
+ expect(trace.assertions).toEqual([]);
85
+ });
86
+ it('returns an empty assertions list for a CONSTRAINT (16-assertion.md §1 — CONSTRAINT-side out of v1)', () => {
87
+ const trace = buildRequirementTrace('CONSTRAINT-EEA-TRANSFER-1', idx, catalog);
88
+ expect(trace.assertions).toEqual([]);
89
+ });
90
+ it('falls back to id when the subject / realised_via element is not in the catalog (dangling ref)', () => {
91
+ const local: ComplianceIndexInput = {
92
+ requirements: [{ id: 'REQUIREMENT-Y-1', name: 'Y' }],
93
+ assertions: [{ id: 'ASSERTION-9', about: 'REQUIREMENT-Y-1', subject: 'PRODUCT-GONE-1', realised_via: ['CAPABILITY-GONE-1'], status: 'n_a' }],
94
+ };
95
+ const trace = buildRequirementTrace('REQUIREMENT-Y-1', buildComplianceIndex(local), catalog);
96
+ expect(trace.assertions[0].subject).toEqual({ id: 'PRODUCT-GONE-1' });
97
+ expect(trace.assertions[0].realisedVia).toEqual([{ id: 'CAPABILITY-GONE-1' }]);
98
+ });
99
+ });
100
+
101
+ describe('buildRequirementTrace — hierarchy', () => {
102
+ const idx = buildComplianceIndex(input);
103
+ it('walks ancestors: immediate parent first, root last', () => {
104
+ const trace = buildRequirementTrace('REQUIREMENT-ERASURE-SLA-1', idx, catalog);
105
+ expect(trace.ancestors.map(r => r.id)).toEqual([
106
+ 'REQUIREMENT-DATA-ERASURE-1',
107
+ 'REQUIREMENT-DATA-PROTECTION-1',
108
+ ]);
109
+ });
110
+ it('lists direct children id-sorted', () => {
111
+ const trace = buildRequirementTrace('REQUIREMENT-DATA-PROTECTION-1', idx, catalog);
112
+ expect(trace.children.map(r => r.id)).toEqual([
113
+ 'REQUIREMENT-DATA-CONSENT-1',
114
+ 'REQUIREMENT-DATA-ERASURE-1',
115
+ ]);
116
+ });
117
+ it('handles a top-level requirement (no ancestors) with no children', () => {
118
+ const trace = buildRequirementTrace('REQUIREMENT-INTERNAL-1', idx, catalog);
119
+ expect(trace.ancestors).toEqual([]);
120
+ expect(trace.children).toEqual([]);
121
+ });
122
+ it('supports CONSTRAINT hierarchy the same way', () => {
123
+ const trace = buildRequirementTrace('CONSTRAINT-EEA-ANALYTICS-1', idx, catalog);
124
+ expect(trace.ancestors.map(r => r.id)).toEqual(['CONSTRAINT-EEA-TRANSFER-1']);
125
+ });
126
+ it('terminates at a missing parent without throwing (broken model)', () => {
127
+ const local: ComplianceIndexInput = {
128
+ requirements: [{ id: 'REQUIREMENT-ORPHAN-1', name: 'Orphan', parent: 'REQUIREMENT-GONE-1' }],
129
+ assertions: [],
130
+ };
131
+ const trace = buildRequirementTrace('REQUIREMENT-ORPHAN-1', buildComplianceIndex(local), catalog);
132
+ expect(trace.ancestors).toEqual([]);
133
+ });
134
+ it('breaks a parent cycle rather than looping', () => {
135
+ // A → B → A (misauthored).
136
+ const local: ComplianceIndexInput = {
137
+ requirements: [
138
+ { id: 'REQUIREMENT-A-1', name: 'A', parent: 'REQUIREMENT-B-1' },
139
+ { id: 'REQUIREMENT-B-1', name: 'B', parent: 'REQUIREMENT-A-1' },
140
+ ],
141
+ assertions: [],
142
+ };
143
+ const trace = buildRequirementTrace('REQUIREMENT-A-1', buildComplianceIndex(local), catalog);
144
+ expect(trace.ancestors.map(r => r.id)).toEqual(['REQUIREMENT-B-1']);
145
+ });
146
+ });
147
+
148
+ describe('buildRequirementTrace — dangling target', () => {
149
+ it('returns a stub carrying the id as name when the requirement is not scanned', () => {
150
+ const trace = buildRequirementTrace('REQUIREMENT-UNKNOWN-1', buildComplianceIndex({ requirements: [], assertions: [] }), catalog);
151
+ expect(trace.requirement).toEqual({ id: 'REQUIREMENT-UNKNOWN-1', name: 'REQUIREMENT-UNKNOWN-1' });
152
+ expect(trace.sources).toEqual([]);
153
+ expect(trace.assertions).toEqual([]);
154
+ expect(trace.ancestors).toEqual([]);
155
+ expect(trace.children).toEqual([]);
156
+ });
157
+ });
@@ -65,7 +65,8 @@ export function ingestComplianceDoc(canon: ComplianceCanon, doc: unknown): strin
65
65
  canon.subjects.push({ id, name: str(d.name) ?? id });
66
66
  return id;
67
67
  }
68
- if (d.notation === 'requirement') {
68
+ if (d.notation === 'requirement' || d.notation === 'constraint') {
69
+ const origin = str(d.origin);
69
70
  canon.requirements.push({
70
71
  id,
71
72
  name: str(d.name) ?? id,
@@ -73,6 +74,11 @@ export function ingestComplianceDoc(canon: ComplianceCanon, doc: unknown): strin
73
74
  derived_from: strArray(d.derived_from),
74
75
  admitted_at: str(d.admitted_at),
75
76
  deadline: str(d.deadline),
77
+ origin: origin === 'legislative' || origin === 'process-product' || origin === 'project-product' ? origin : undefined,
78
+ parent: str(d.parent),
79
+ element_kind: d.notation,
80
+ description: str(d.description),
81
+ next_review_at: str(d.next_review_at),
76
82
  });
77
83
  return id;
78
84
  }
@@ -1,5 +1,6 @@
1
1
  export { buildComplianceIndex } from './reverse-index.js';
2
2
  export { buildLawTree, buildProductView } from './views.js';
3
+ export { buildRequirementTrace, buildTraceElementCatalog } from './trace.js';
3
4
  export { buildGapReport } from './gap-report.js';
4
5
  export type { GapReport, GapReportOptions } from './gap-report.js';
5
6
  export { emptyCanon, ingestComplianceDoc } from './classify.js';
@@ -54,4 +55,9 @@ export type {
54
55
  ProductRequirementStatus,
55
56
  ObjectDetailDef,
56
57
  ObjectDetailInput,
58
+ RequirementTrace,
59
+ TraceAssertionRow,
60
+ TraceElementCatalog,
61
+ TraceElementRef,
62
+ TraceSourceRef,
57
63
  } from './types.js';
@@ -19,15 +19,17 @@ export function buildComplianceIndex(input: ComplianceIndexInput): ComplianceInd
19
19
  const requirementsByLaw = new Map<string, IndexRequirement[]>();
20
20
  const assertionsByRequirement = new Map<string, IndexAssertion[]>();
21
21
  const assertionsBySubject = new Map<string, IndexAssertion[]>();
22
+ const requirementsByParent = new Map<string, IndexRequirement[]>();
22
23
 
23
24
  for (const r of input.requirements) {
24
25
  requirementById.set(r.id, r);
25
26
  for (const law of r.derived_from ?? []) push(requirementsByLaw, law, r);
27
+ if (r.parent) push(requirementsByParent, r.parent, r);
26
28
  }
27
29
  for (const a of input.assertions) {
28
30
  push(assertionsByRequirement, a.about, a);
29
31
  push(assertionsBySubject, a.subject, a);
30
32
  }
31
33
 
32
- return { requirementById, requirementsByLaw, assertionsByRequirement, assertionsBySubject };
34
+ return { requirementById, requirementsByLaw, assertionsByRequirement, assertionsBySubject, requirementsByParent };
33
35
  }
@@ -0,0 +1,118 @@
1
+ // Requirement traceability + hierarchy builder.
2
+ //
3
+ // Two halves, both origin-agnostic per 15-requirement.md §2.1:
4
+ //
5
+ // 1. Trace chain — `derived_from` sources → the REQUIREMENT / CONSTRAINT
6
+ // itself → any ASSERTION targeting it (`about`) → the asserted `subject`
7
+ // + `realised_via` elements. Assertion coverage applies to REQUIREMENT
8
+ // only (16-assertion.md §1); CONSTRAINT trace shows sources + hierarchy
9
+ // only.
10
+ //
11
+ // 2. Hierarchy — the `parent` chain (ancestors, root last) plus the direct
12
+ // children (elements whose `parent` names this one). Same-TYPE only per
13
+ // 15-requirement.md §2.4; the chain terminates at the first missing or
14
+ // cyclic parent so a broken model still renders something useful.
15
+ //
16
+ // Pure: takes the reverse index + a name-resolution map + optional codex list;
17
+ // no IO. `ComplianceCodexDoc` comes from the scanner so we get jurisdiction
18
+ // alongside the codex id in the sources block.
19
+
20
+ import type {
21
+ ComplianceIndex,
22
+ IndexRequirement,
23
+ RequirementTrace,
24
+ TraceAssertionRow,
25
+ TraceElementCatalog,
26
+ TraceElementRef,
27
+ TraceSourceRef,
28
+ } from './types.js';
29
+ import type { ComplianceCodexDoc } from './classify.js';
30
+
31
+ function byId<T extends { id: string }>(a: T, b: T): number {
32
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
33
+ }
34
+
35
+ function resolveElement(id: string, catalog: TraceElementCatalog): TraceElementRef {
36
+ const name = catalog.nameById.get(id);
37
+ return name ? { id, name } : { id };
38
+ }
39
+
40
+ /**
41
+ * Walk the `parent` chain upward from `requirement`, stopping at the first
42
+ * missing or already-seen parent (cycle guard). Returns immediate parent first,
43
+ * root last. Empty array when the element has no `parent`.
44
+ */
45
+ function collectAncestors(
46
+ requirement: IndexRequirement,
47
+ index: ComplianceIndex,
48
+ ): IndexRequirement[] {
49
+ const out: IndexRequirement[] = [];
50
+ const seen = new Set<string>([requirement.id]);
51
+ let current: IndexRequirement | undefined = requirement;
52
+ while (current?.parent && !seen.has(current.parent)) {
53
+ seen.add(current.parent);
54
+ const next = index.requirementById.get(current.parent);
55
+ if (!next) break;
56
+ out.push(next);
57
+ current = next;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * Builds the REQUIREMENT / CONSTRAINT traceability view.
64
+ *
65
+ * @param requirementId typed id of the element to trace
66
+ * @param index reverse index built by `buildComplianceIndex`
67
+ * @param catalog name-resolution map for subject / realised_via refs
68
+ * @param codex optional codex artefact list (from the scanner); when
69
+ * supplied, `sources[].codex` is populated with the
70
+ * resolved codex artefact for jurisdiction display
71
+ */
72
+ export function buildRequirementTrace(
73
+ requirementId: string,
74
+ index: ComplianceIndex,
75
+ catalog: TraceElementCatalog,
76
+ codex: ComplianceCodexDoc[] = [],
77
+ ): RequirementTrace {
78
+ const requirement: IndexRequirement =
79
+ index.requirementById.get(requirementId) ?? { id: requirementId, name: requirementId };
80
+
81
+ const codexById = new Map<string, ComplianceCodexDoc>();
82
+ for (const c of codex) codexById.set(c.id, c);
83
+
84
+ const sources: TraceSourceRef[] = (requirement.derived_from ?? []).map(sid => {
85
+ const c = codexById.get(sid);
86
+ return c ? { id: sid, codex: c } : { id: sid };
87
+ });
88
+
89
+ const rawAssertions = index.assertionsByRequirement.get(requirementId) ?? [];
90
+ const assertions: TraceAssertionRow[] = [...rawAssertions]
91
+ .sort(byId)
92
+ .map(assertion => ({
93
+ assertion,
94
+ subject: resolveElement(assertion.subject, catalog),
95
+ realisedVia: (assertion.realised_via ?? []).map(rid => resolveElement(rid, catalog)),
96
+ }));
97
+
98
+ const ancestors = collectAncestors(requirement, index);
99
+ const children = [...(index.requirementsByParent.get(requirementId) ?? [])].sort(byId);
100
+
101
+ return { requirement, sources, assertions, ancestors, children };
102
+ }
103
+
104
+ /**
105
+ * Convenience: build a `TraceElementCatalog` from the scanned canon's product
106
+ * and subject buckets. Requirements/assertions are excluded — they are indexed
107
+ * separately by `buildComplianceIndex`; the catalog is only for resolving the
108
+ * elements a trace references (subjects + realised_via).
109
+ */
110
+ export function buildTraceElementCatalog(
111
+ products: Array<{ id: string; name: string }>,
112
+ subjects: Array<{ id: string; name: string }>,
113
+ ): TraceElementCatalog {
114
+ const nameById = new Map<string, string>();
115
+ for (const p of products) nameById.set(p.id, p.name);
116
+ for (const s of subjects) nameById.set(s.id, s.name);
117
+ return { nameById };
118
+ }
@@ -4,8 +4,9 @@
4
4
  // single-product view here, and the gap dashboard in Phase 4.
5
5
 
6
6
  import type { AssertionStatus } from '../assertion/types.js';
7
+ import type { ComplianceCodexDoc } from './classify.js';
7
8
 
8
- /** Projection of a REQUIREMENT the compliance views need. */
9
+ /** Projection of a REQUIREMENT (or CONSTRAINT) the compliance views need. */
9
10
  export interface IndexRequirement {
10
11
  id: string;
11
12
  name: string;
@@ -20,6 +21,38 @@ export interface IndexRequirement {
20
21
  * past or imminent, CV-3 renders an urgent decoration on the cell.
21
22
  */
22
23
  deadline?: string;
24
+ /**
25
+ * Origin taxonomy (15-requirement.md §2.1): `legislative`, `process-product`,
26
+ * or `project-product`. Distinguishes the context from which the obligation
27
+ * was derived. Undefined for existing pre-taxonomy admissions (treated as
28
+ * `legislative` by tooling that supports origin-based filtering).
29
+ */
30
+ origin?: 'legislative' | 'process-product' | 'project-product';
31
+ /**
32
+ * Same-TYPE `parent` reference: the higher-scale obligation this one
33
+ * decomposes from (15-requirement.md §2.4; ELEMENT_PRIMITIVES.md §7.13 for
34
+ * CONSTRAINT). Origin-agnostic, structure-only. Enables the hierarchy half
35
+ * of the requirement traceability view.
36
+ */
37
+ parent?: string;
38
+ /**
39
+ * Motivation-layer element kind. `requirement` = positive obligation
40
+ * (15-requirement.md); `constraint` = restriction / prohibition
41
+ * (ELEMENT_PRIMITIVES.md §7.13). ASSERTION coverage applies to `requirement`
42
+ * only (16-assertion.md §1); the hierarchy half applies to both.
43
+ */
44
+ element_kind?: 'requirement' | 'constraint';
45
+ /**
46
+ * Longer-form description of the obligation (15-requirement.md §2). Optional;
47
+ * used by the requirement traceability view to show the requirement body
48
+ * inline. Not used by matrix / list views.
49
+ */
50
+ description?: string;
51
+ /**
52
+ * `next_review_at` review-checkpoint date (15-requirement.md §2.3; ISO 8601).
53
+ * Present when the author has scheduled a review; drives `REQ-STALE-001`.
54
+ */
55
+ next_review_at?: string;
23
56
  }
24
57
 
25
58
  // ── Temporal status (CV-3) ──────────────────────────────────────────────────
@@ -106,6 +139,11 @@ export interface ComplianceIndex {
106
139
  assertionsByRequirement: Map<string, IndexAssertion[]>;
107
140
  /** Subject id (product / process / capability) → assertions about it. */
108
141
  assertionsBySubject: Map<string, IndexAssertion[]>;
142
+ /**
143
+ * Parent id → the requirements/constraints that name it in `parent`
144
+ * (15-requirement.md §2.4). Enables the requirement-hierarchy view.
145
+ */
146
+ requirementsByParent: Map<string, IndexRequirement[]>;
109
147
  }
110
148
 
111
149
  // ── Single-law tree ─────────────────────────────────────────────────────────
@@ -134,3 +172,65 @@ export interface ProductView {
134
172
  /** Requirements bound to the product via an assertion, requirement-id-sorted. */
135
173
  requirements: ProductRequirementStatus[];
136
174
  }
175
+
176
+ // ── Requirement traceability + hierarchy view ───────────────────────────────
177
+
178
+ /** A codex artefact resolved from a requirement's `derived_from` reference. */
179
+ export interface TraceSourceRef {
180
+ /** Verbatim id from `derived_from`. Always present. */
181
+ id: string;
182
+ /** The codex artefact, when resolved by the scan. Absent for dangling refs. */
183
+ codex?: ComplianceCodexDoc;
184
+ }
185
+
186
+ /** A named element (subject or realising element) resolved by the trace. */
187
+ export interface TraceElementRef {
188
+ id: string;
189
+ /** Element name when resolved by the scan; absent for dangling refs. */
190
+ name?: string;
191
+ }
192
+
193
+ /** One ASSERTION targeting the traced requirement, with subject + realising elements. */
194
+ export interface TraceAssertionRow {
195
+ assertion: IndexAssertion;
196
+ subject: TraceElementRef;
197
+ /** Elements named in the assertion's `realised_via` list (may be empty). */
198
+ realisedVia: TraceElementRef[];
199
+ }
200
+
201
+ /**
202
+ * Requirement traceability + hierarchy view.
203
+ *
204
+ * Two halves, both origin-agnostic (15-requirement.md §2.1):
205
+ * 1. Trace chain — `derived_from` source(s) → the element itself → any
206
+ * ASSERTION targeting it (`about`) → the asserted `subject` + `realised_via`
207
+ * elements. Origin-agnostic per 15-requirement.md §2.1; assertion coverage
208
+ * applies to REQUIREMENT only (16-assertion.md §1) — CONSTRAINT trace shows
209
+ * only the source chain + hierarchy.
210
+ * 2. Hierarchy — `parent` chain (ancestors, root last of the array) + children
211
+ * (any element whose `parent` names this one), sorted by id.
212
+ */
213
+ export interface RequirementTrace {
214
+ /** The element being traced (REQUIREMENT or CONSTRAINT). Falls back to a
215
+ * stub carrying the id as its name when the element is missing from the
216
+ * scan (a dangling `parent` or a repository being edited). */
217
+ requirement: IndexRequirement;
218
+ /** Backward-trace: `derived_from` codex artefacts, verbatim order. */
219
+ sources: TraceSourceRef[];
220
+ /** Forward-trace via ASSERTION. Empty for CONSTRAINT elements (16-assertion.md §1) or for a REQUIREMENT with no filed assertion. */
221
+ assertions: TraceAssertionRow[];
222
+ /** Parent chain: immediate parent first, root last. Empty when the element has no `parent`. */
223
+ ancestors: IndexRequirement[];
224
+ /** Direct children: elements naming this one as their `parent`, id-sorted. */
225
+ children: IndexRequirement[];
226
+ }
227
+
228
+ /**
229
+ * The complementary data the trace builder needs to name subjects and realising
230
+ * elements. Names are resolved by looking up the id in this map; unresolved ids
231
+ * surface as the id alone (a dangling reference).
232
+ */
233
+ export interface TraceElementCatalog {
234
+ /** id → human-readable name (or the id itself when unnamed). */
235
+ nameById: Map<string, string>;
236
+ }
@@ -0,0 +1,212 @@
1
+ import React, { memo, useState } from 'react';
2
+ import { Handle, Position } from 'reactflow';
3
+ import type { Factor, Goal } from './types.js';
4
+ import type { ThemeTokens } from './theme.js';
5
+
6
+ const NODE_WIDTH = 250;
7
+ const NODE_HEIGHT = 80;
8
+
9
+ function impactSign(f: Factor): 'positive' | 'negative' | 'both' {
10
+ const t = f.impact_type;
11
+ if (t === 'mixed') return 'both';
12
+ if (t === 'opportunity' || t === 'positive') return 'positive';
13
+ return 'negative';
14
+ }
15
+
16
+ export interface GoalNodeData {
17
+ goal: Goal;
18
+ theme: Required<ThemeTokens>;
19
+ readOnly: boolean;
20
+ isDropTarget: boolean;
21
+ hasHiddenChildren: boolean;
22
+ isCollapsed: boolean;
23
+ onAddChild: (parentId: number, parentLevel: number) => void;
24
+ onDelete: (id: number) => void;
25
+ onToggleCollapse: (id: number) => void;
26
+ }
27
+
28
+ const GoalNode = memo(({ data }: { data: GoalNodeData }) => {
29
+ const { goal, theme, readOnly, isDropTarget, hasHiddenChildren, isCollapsed } = data;
30
+ const [openPanel, setOpenPanel] = useState<'positive' | 'negative' | null>(null);
31
+
32
+ const positive = (goal.factors ?? []).filter((f) => impactSign(f) !== 'negative');
33
+ const negative = (goal.factors ?? []).filter((f) => impactSign(f) !== 'positive');
34
+ const bg = theme.goalLevelColors[goal.level] ?? theme.goalLevelColors[0];
35
+
36
+ return (
37
+ <div
38
+ className="tx-goal-node"
39
+ style={{
40
+ position: 'relative',
41
+ width: NODE_WIDTH,
42
+ height: NODE_HEIGHT,
43
+ background: bg,
44
+ borderRadius: 12,
45
+ borderStyle: 'solid',
46
+ borderWidth: isDropTarget ? 2 : theme.cardBorderWidth,
47
+ borderColor: isDropTarget ? theme.dropTargetBorderColor : theme.cardBorderColor,
48
+ boxShadow: '0 1px 4px rgba(0,0,0,0.12)',
49
+ padding: '6px 8px',
50
+ fontSize: 12,
51
+ display: 'flex',
52
+ alignItems: 'stretch',
53
+ justifyContent: 'center',
54
+ }}
55
+ >
56
+ <Handle type="target" position={Position.Left} style={{ opacity: 0 }} />
57
+ <Handle type="source" position={Position.Right} style={{ opacity: 0 }} />
58
+
59
+ <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', width: 16 }}>
60
+ {positive.length > 0 && (
61
+ <span
62
+ role="button"
63
+ aria-label={`${positive.length} positive factor${positive.length > 1 ? 's' : ''}`}
64
+ title={`${positive.length} positive factor${positive.length > 1 ? 's' : ''}`}
65
+ onClick={(e) => {
66
+ e.stopPropagation();
67
+ setOpenPanel(openPanel === 'positive' ? null : 'positive');
68
+ }}
69
+ style={{ cursor: 'pointer', color: '#16a34a', fontSize: 14, lineHeight: 1, userSelect: 'none' }}
70
+ >
71
+ &#9650;
72
+ {positive.length > 1 && <span style={{ fontSize: 9, fontWeight: 700, marginLeft: 2 }}>{positive.length}</span>}
73
+ </span>
74
+ )}
75
+ </div>
76
+
77
+ <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', padding: '0 4px' }}>
78
+ <div
79
+ title={goal.name}
80
+ style={{
81
+ fontWeight: 600,
82
+ color: theme.cardTextColor,
83
+ lineHeight: 1.2,
84
+ overflow: 'hidden',
85
+ display: '-webkit-box',
86
+ WebkitLineClamp: 2,
87
+ WebkitBoxOrient: 'vertical',
88
+ wordBreak: 'break-word',
89
+ }}
90
+ >
91
+ {goal.name}
92
+ </div>
93
+ <div style={{ fontSize: 10, color: theme.cardMetaColor, marginTop: 2 }}>
94
+ ID: {goal.id} | Lvl: {goal.level}
95
+ {goal.tag ? ` | #${goal.tag}` : ''}
96
+ </div>
97
+ </div>
98
+
99
+ <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', width: 16, justifyContent: 'flex-end' }}>
100
+ {negative.length > 0 && (
101
+ <span
102
+ role="button"
103
+ aria-label={`${negative.length} negative factor${negative.length > 1 ? 's' : ''}`}
104
+ title={`${negative.length} negative factor${negative.length > 1 ? 's' : ''}`}
105
+ onClick={(e) => {
106
+ e.stopPropagation();
107
+ setOpenPanel(openPanel === 'negative' ? null : 'negative');
108
+ }}
109
+ style={{ cursor: 'pointer', color: '#dc2626', fontSize: 14, lineHeight: 1, userSelect: 'none' }}
110
+ >
111
+ &#9660;
112
+ {negative.length > 1 && <span style={{ fontSize: 9, fontWeight: 700, marginLeft: 2 }}>{negative.length}</span>}
113
+ </span>
114
+ )}
115
+ </div>
116
+
117
+ {openPanel && (
118
+ <div
119
+ style={{
120
+ position: 'absolute',
121
+ left: 0,
122
+ width: '100%',
123
+ zIndex: 20,
124
+ display: 'flex',
125
+ flexDirection: 'column',
126
+ gap: 4,
127
+ ...(openPanel === 'positive' ? { bottom: 'calc(100% + 8px)' } : { top: 'calc(100% + 8px)' }),
128
+ }}
129
+ >
130
+ {(openPanel === 'positive' ? positive : negative).map((f) => (
131
+ <div
132
+ key={f.id}
133
+ style={{
134
+ background: openPanel === 'positive' ? '#f0fdf4' : '#fef2f2',
135
+ border: `1px solid ${openPanel === 'positive' ? '#bbf7d0' : '#fecaca'}`,
136
+ color: openPanel === 'positive' ? '#166534' : '#991b1b',
137
+ borderRadius: 4,
138
+ padding: '4px 6px',
139
+ fontSize: 10,
140
+ textAlign: 'left',
141
+ }}
142
+ >
143
+ <div style={{ fontWeight: 700 }}>{f.name}</div>
144
+ {f.description && <div style={{ opacity: 0.85 }}>{f.description}</div>}
145
+ </div>
146
+ ))}
147
+ </div>
148
+ )}
149
+
150
+ {!readOnly && (
151
+ <button
152
+ type="button"
153
+ aria-label="Add child goal"
154
+ title="Add child goal"
155
+ onClick={(e) => {
156
+ e.stopPropagation();
157
+ data.onAddChild(goal.id, goal.level);
158
+ }}
159
+ style={{
160
+ position: 'absolute', top: -8, right: -8, width: 16, height: 16,
161
+ borderRadius: '50%', border: '1px solid #86efac', background: '#ffffff',
162
+ color: '#16a34a', fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
163
+ }}
164
+ >
165
+ +
166
+ </button>
167
+ )}
168
+
169
+ {!readOnly && (
170
+ <button
171
+ type="button"
172
+ aria-label="Delete goal"
173
+ title="Delete goal and descendants"
174
+ onClick={(e) => {
175
+ e.stopPropagation();
176
+ data.onDelete(goal.id);
177
+ }}
178
+ style={{
179
+ position: 'absolute', bottom: -8, right: -8, width: 16, height: 16,
180
+ borderRadius: '50%', border: '1px solid #fca5a5', background: '#ffffff',
181
+ color: '#dc2626', fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
182
+ }}
183
+ >
184
+ &times;
185
+ </button>
186
+ )}
187
+
188
+ {hasHiddenChildren && (
189
+ <button
190
+ type="button"
191
+ aria-label={isCollapsed ? 'Expand branch' : 'Collapse branch'}
192
+ title={isCollapsed ? 'Expand branch' : 'Collapse branch'}
193
+ onClick={(e) => {
194
+ e.stopPropagation();
195
+ data.onToggleCollapse(goal.id);
196
+ }}
197
+ style={{
198
+ position: 'absolute', top: '50%', right: -8, transform: 'translateY(-50%)',
199
+ width: 16, height: 16, borderRadius: '50%', border: `1px solid ${theme.cardBorderColor}`,
200
+ background: '#ffffff', color: theme.cardBorderColor, fontSize: 11, lineHeight: '14px', padding: 0, cursor: 'pointer',
201
+ }}
202
+ >
203
+ {isCollapsed ? '+' : '−'}
204
+ </button>
205
+ )}
206
+ </div>
207
+ );
208
+ });
209
+
210
+ GoalNode.displayName = 'GoalNode';
211
+
212
+ export default GoalNode;