-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-impact-analysis-synchronizer.mjs
More file actions
executable file
·1352 lines (1204 loc) · 41 KB
/
Copy path06-impact-analysis-synchronizer.mjs
File metadata and controls
executable file
·1352 lines (1204 loc) · 41 KB
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
#!/usr/bin/env node
/**
* Evolith Core Impact Analysis & Synchronization Agent
*
* Mandatory mechanism that executes after relevant changes in Evolith Core.
* Detects, analyzes, and synchronizes: ADRs, documentation, rules, standards,
* architecture, harness, agents, and rulesets.
*
* Usage:
* node .harness/scripts/impact-analysis-synchronizer.mjs [options]
*
* Options:
* --staged Analyze staged changes only (pre-commit hook default)
* --working-tree Analyze working tree changes (uncommitted)
* --all Analyze all changes since last commit
* --dry-run Report only, no changes applied
* --verbose Detailed output
* --report Generate report to .harness/reports/
*
* Idempotent: running with same inputs produces no changes.
* Incremental: only affected components are touched.
*/
import fs from "node:fs";
import path from "node:path";
import { execSync } from "node:child_process";
import crypto from "node:crypto";
// GT-556: root came from process.cwd(), so every glob and every git invocation below
// silently re-scoped itself to wherever the script happened to be launched from.
// The `reference/navigation/**` patterns were also dead — navigation now lives at the
// repo-root MASTER_INDEX.md plus reference/core/control-center/taxonomy.
import { REPO_ROOT } from '../lib/paths.mjs';
const root = REPO_ROOT;
// ============================================================================
// CHANGE CATEGORY DEFINITIONS
// ============================================================================
const CHANGE_CATEGORIES = {
ADR: {
patterns: [
/\/adrs\/core\/ADR-\d+\.md$/i,
/\/adrs\/nodejs\/ADR-\d+\.md$/i,
/\/adrs\/dotnet\/ADR-\d+\.md$/i,
/\/adrs\/android\/ADR-\d+\.md$/i,
/\/adrs\/.*\.es\.md$/i,
],
impactZones: ["adrs", "rulesets", "documentation", "navigation", "harness"],
severity: { create: "high", modify: "high", delete: "critical", rename: "medium" }
},
DOCS: {
patterns: [
/\/reference\/.*\.md$/i,
/\/reference\/.*\.es\.md$/i,
],
excludePatterns: [
/\/adrs\//,
/\/blueprints\//,
],
impactZones: ["documentation", "navigation", "bilingual"],
severity: { create: "medium", modify: "low", delete: "medium", rename: "low" }
},
RULES: {
patterns: [
/\/reference\/governance\/standards\/.*\.md$/i,
/\/rulesets\/.*\.rules\.json$/i,
/\/rulesets\/.*\.schema\.json$/i,
],
impactZones: ["rulesets", "harness", "documentation", "adrs"],
severity: { create: "high", modify: "high", delete: "critical", rename: "medium" }
},
ARCH: {
patterns: [
/\/reference\/architecture\/blueprints\/.*\.md$/i,
/\/reference\/architecture\/canonical-patterns\/.*\.md$/i,
],
impactZones: ["adrs", "rulesets", "documentation", "templates"],
severity: { create: "high", modify: "medium", delete: "high", rename: "medium" }
},
HARNESS: {
patterns: [
/\.harness\/.*\.mjs$/i,
/\.harness\/.*\.md$/i,
/\.harness\/.*\.json$/i,
/\.husky\/.*$/i,
],
impactZones: ["harness", "rulesets", "validators"],
severity: { create: "high", modify: "high", delete: "critical", rename: "high" }
},
SCHEMA: {
patterns: [
/rulesets\/schema\/.*\.json$/i,
/\.harness\/schemas\/.*\.json$/i,
],
impactZones: ["rulesets", "validators", "harness"],
severity: { create: "critical", modify: "critical", delete: "critical", rename: "high" }
},
TEMPLATE: {
patterns: [
/\/sdlc\/04-artifact-templates\/.*\.md$/i,
/\/sdlc\/04-artifact-templates\/.*\.es\.md$/i,
],
impactZones: ["templates", "documentation", "navigation"],
severity: { create: "high", modify: "medium", delete: "high", rename: "medium" }
},
NAVIGATION: {
patterns: [
/\/navigation\/MASTER_INDEX\.md$/i,
/\/navigation\/.*README\.md$/i,
/\/MASTER_INDEX\.md$/i,
/\/README\.md$/i,
/\/README\.es\.md$/i,
],
impactZones: ["navigation", "documentation"],
severity: { create: "low", modify: "low", delete: "medium", rename: "low" }
}
};
// ============================================================================
// IMPACT ZONE DEPENDENCY MAP
// ============================================================================
const IMPACT_DEPENDENCIES = {
adrs: {
affectedBy: ["ADR", "ARCH", "RULES"],
syncActions: ["index_update", "cross_ref_sync", "bilingual_sync"]
},
rulesets: {
affectedBy: ["RULES", "SCHEMA", "HARNESS", "ADR"],
syncActions: ["schema_update", "rule_propagation", "index_update"]
},
documentation: {
affectedBy: ["DOCS", "ADR", "ARCH", "RULES", "TEMPLATE"],
syncActions: ["bilingual_sync", "cross_ref_sync", "navigation_sync"]
},
navigation: {
affectedBy: ["DOCS", "ADR", "ARCH", "RULES", "HARNESS", "NAVIGATION", "TEMPLATE"],
syncActions: ["navigation_sync", "index_update"]
},
harness: {
affectedBy: ["HARNESS", "RULES", "SCHEMA"],
syncActions: ["validation", "rule_propagation"]
},
templates: {
affectedBy: ["TEMPLATE", "SCHEMA", "ADR"],
syncActions: ["template_validation", "bilingual_sync"]
},
validators: {
affectedBy: ["SCHEMA", "RULES", "HARNESS"],
syncActions: ["schema_update", "rule_propagation"]
},
bilingual: {
affectedBy: ["DOCS", "ADR", "TEMPLATE", "NAVIGATION"],
syncActions: ["bilingual_sync", "index_update"]
}
};
// ============================================================================
// IMPACT ZONE TO FILE PATTERNS
// ============================================================================
const IMPACT_ZONE_FILES = {
adrs: [
"reference/core/architecture/adrs/*/README.md",
"reference/core/architecture/adrs/*/README.es.md",
"reference/core/architecture/adrs/adr-matrix.md",
"reference/core/architecture/adrs/adr-matrix.es.md",
],
rulesets: [
"src/rulesets/**/*.md",
"src/rulesets/**/*.json",
],
documentation: [
"reference/**/*.md",
"reference/**/*.es.md",
],
navigation: [
"reference/core/control-center/taxonomy/**/*.md",
"MASTER_INDEX.md",
"MASTER_INDEX.es.md",
"README.md",
"README.es.md",
],
harness: [
".harness/scripts/*.mjs",
".harness/**/*.md",
".harness/**/*.json",
".harness/**/*.es.md",
],
templates: [
"reference/core/sdlc/04-artifact-templates/*.md",
"reference/core/sdlc/04-artifact-templates/*.es.md",
],
validators: [
".harness/scripts/validate-docs.mjs",
".harness/scripts/check-bilingual-parity.mjs",
".harness/scripts/bilingual-coverage.mjs",
]
};
// ============================================================================
// SYNCHRONIZATION RULES
// ============================================================================
const SYNC_RULES = {
adrs: {
onCreate: (change, ctx) => {
const syncs = [];
const adrDir = path.dirname(change.file);
const isSpanish = change.file.endsWith(".es.md");
const baseFile = isSpanish
? change.file.replace(".es.md", ".md")
: change.file;
// Update ADR index
const indexFile = path.join(adrDir, "README.md");
if (fs.existsSync(indexFile)) {
syncs.push({
type: "index_update",
target: indexFile,
action: "updated",
changeSource: change.file,
details: `Added ${path.basename(change.file)} to index`
});
}
// Update bilingual index if Spanish
if (isSpanish) {
syncs.push({
type: "bilingual_sync",
target: baseFile,
action: "validated",
changeSource: change.file,
details: "Spanish version created - EN version validated"
});
}
// Check for ADR number in filename
const adrMatch = change.file.match(/(\d+)[-\w]*\.md$/);
if (adrMatch && ctx.adrMatrix) {
syncs.push({
type: "cross_ref_sync",
target: "reference/core/architecture/adrs/adr-matrix.md",
action: "updated",
changeSource: change.file,
details: `ADR-${adrMatch[1]} registered in decision matrix`
});
}
return syncs;
},
onModify: (change, ctx) => {
const syncs = [];
const isSpanish = change.file.endsWith(".es.md");
// Validate bilingual parity
const counterpart = isSpanish
? change.file.replace(".es.md", ".md")
: change.file.replace(".md", ".es.md");
if (fs.existsSync(counterpart)) {
syncs.push({
type: "bilingual_sync",
target: counterpart,
action: "validated",
changeSource: change.file,
details: "Bilingual counterpart exists and is valid"
});
}
return syncs;
},
onDelete: (change, ctx) => {
const syncs = [];
const isSpanish = change.file.endsWith(".es.md");
const counterpart = isSpanish
? change.file.replace(".es.md", ".md")
: change.file.replace(".md", ".es.md");
if (fs.existsSync(counterpart)) {
syncs.push({
type: "bilingual_sync",
target: counterpart,
action: "requires_manual",
changeSource: change.file,
details: `Counterpart ${counterpart} exists - manual review required before deletion`
});
}
return syncs;
}
},
rulesets: {
onCreate: (change, ctx) => {
const syncs = [];
const isJson = change.file.endsWith(".json");
if (isJson) {
// Validate JSON schema syntax
try {
const content = fs.readFileSync(path.join(root, change.file), "utf8");
JSON.parse(content);
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: "JSON schema syntax validated"
});
} catch (e) {
syncs.push({
type: "schema_update",
target: change.file,
action: "failed",
changeSource: change.file,
details: `JSON parse error: ${e.message}`
});
}
}
// Update ruleset index
const rulesetDir = path.dirname(change.file);
const indexFile = path.join(rulesetDir, "README.md");
if (fs.existsSync(indexFile)) {
syncs.push({
type: "index_update",
target: indexFile,
action: "updated",
changeSource: change.file,
details: `Added ${path.basename(change.file)} to ruleset index`
});
}
return syncs;
},
onModify: (change, ctx) => {
const syncs = [];
if (change.file.endsWith(".rules.json")) {
// Validate rules JSON structure
try {
const content = fs.readFileSync(path.join(root, change.file), "utf8");
const rules = JSON.parse(content);
if (!rules.rules || !Array.isArray(rules.rules)) {
throw new Error("Missing 'rules' array in rules file");
}
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: `Rules file validated: ${rules.rules.length} rules`
});
} catch (e) {
syncs.push({
type: "schema_update",
target: change.file,
action: "failed",
changeSource: change.file,
details: `Rules validation error: ${e.message}`
});
}
}
return syncs;
}
},
harness: {
onCreate: (change, ctx) => {
const syncs = [];
// Validate JSON files
if (change.file.endsWith(".json")) {
try {
const content = fs.readFileSync(path.join(root, change.file), "utf8");
const parsed = JSON.parse(content);
// Validate schema structure if it looks like a schema
if (parsed.$schema || parsed.title || parsed.type) {
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: `Schema validated: ${parsed.title || "untitled"}`
});
} else {
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: "JSON file syntax validated"
});
}
} catch (e) {
syncs.push({
type: "schema_update",
target: change.file,
action: "failed",
changeSource: change.file,
details: `JSON parse error: ${e.message}`
});
}
}
// Validate MJS files for basic syntax
if (change.file.endsWith(".mjs")) {
try {
const content = fs.readFileSync(path.join(root, change.file), "utf8");
// Basic syntax check - look for common issues
const importCount = (content.match(/^import\s/gm) || []).length;
const exportCount = (content.match(/^export\s/gm) || []).length;
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: `Module validated: ${importCount} imports, ${exportCount} exports`
});
} catch (e) {
syncs.push({
type: "schema_update",
target: change.file,
action: "failed",
changeSource: change.file,
details: `File read error: ${e.message}`
});
}
}
// Update harness index if exists
if (change.file.includes("/scripts/") && !change.file.endsWith(".md")) {
syncs.push({
type: "index_update",
target: ".harness/scripts",
action: "updated",
changeSource: change.file,
details: `New script registered: ${path.basename(change.file)}`
});
}
return syncs;
},
onModify: (change, ctx) => {
const syncs = [];
if (change.file.endsWith(".json")) {
try {
const content = fs.readFileSync(path.join(root, change.file), "utf8");
JSON.parse(content);
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: "JSON file validated after modification"
});
} catch (e) {
syncs.push({
type: "schema_update",
target: change.file,
action: "failed",
changeSource: change.file,
details: `JSON parse error: ${e.message}`
});
}
}
// If modifying pre-commit hook, validate it
if (change.file.includes("pre-commit")) {
syncs.push({
type: "schema_update",
target: change.file,
action: "validated",
changeSource: change.file,
details: "Pre-commit hook validated"
});
}
return syncs;
}
},
documentation: {
onCreate: (change, ctx) => {
const syncs = [];
const isSpanish = change.file.endsWith(".es.md");
// Check bilingual counterpart
const counterpart = isSpanish
? change.file.replace(".es.md", ".md")
: change.file.replace(".md", ".es.md");
const counterpartExists = fs.existsSync(path.join(root, counterpart));
if (!isSpanish && !counterpartExists) {
syncs.push({
type: "bilingual_sync",
target: counterpart,
action: "skipped",
changeSource: change.file,
details: "ES counterpart not required yet - coverage will track"
});
} else if (isSpanish && !counterpartExists) {
syncs.push({
type: "bilingual_sync",
target: change.file,
action: "failed",
changeSource: counterpart,
details: "EN counterpart missing for Spanish file"
});
} else {
syncs.push({
type: "bilingual_sync",
target: counterpart,
action: "validated",
changeSource: change.file,
details: "Bilingual counterpart validated"
});
}
// Update navigation if in navigation directory
if (change.file.includes("/taxonomy/") || change.file === "MASTER_INDEX.md") {
syncs.push({
type: "navigation_sync",
target: "MASTER_INDEX.md",
action: "updated",
changeSource: change.file,
details: "MASTER_INDEX refreshed for navigation changes"
});
}
return syncs;
},
onModify: (change, ctx) => {
const syncs = [];
const isSpanish = change.file.endsWith(".es.md");
const counterpart = isSpanish
? change.file.replace(".es.md", ".md")
: change.file.replace(".md", ".es.md");
if (fs.existsSync(path.join(root, counterpart))) {
syncs.push({
type: "bilingual_sync",
target: counterpart,
action: "validated",
changeSource: change.file,
details: "Bilingual counterpart validated after modification"
});
}
return syncs;
}
},
navigation: {
onCreate: (change, ctx) => {
return [{
type: "navigation_sync",
target: change.file,
action: "updated",
changeSource: change.file,
details: "Navigation file registered"
}];
},
onModify: (change, ctx) => {
// Validate navigation links
const syncs = [];
const content = fs.readFileSync(path.join(root, change.file), "utf8");
const linkPattern = /\.\.\/[^)\s]+/g;
const links = content.match(linkPattern) || [];
for (const link of links) {
const resolved = path.resolve(path.dirname(change.file), link);
const rel = path.relative(root, resolved);
if (!fs.existsSync(rel)) {
syncs.push({
type: "navigation_sync",
target: change.file,
action: "failed",
changeSource: change.file,
details: `Broken link detected: ${link} → ${rel}`
});
}
}
if (syncs.length === 0) {
syncs.push({
type: "navigation_sync",
target: change.file,
action: "validated",
changeSource: change.file,
details: `Navigation file validated: ${links.length} links checked`
});
}
return syncs;
}
}
};
// ============================================================================
// CORE FUNCTIONS
// ============================================================================
function generateAnalysisId() {
return crypto.randomUUID();
}
function getTimestamp() {
return new Date().toISOString();
}
function getChangedFiles(scope = "staged") {
try {
let files = new Set();
if (scope === "staged" || scope === "all") {
// Staged changes
const stagedOutput = execSync("git diff --staged --name-only --diff-filter=AMD", {
encoding: "utf8",
cwd: root
});
for (const f of stagedOutput.split("\n")) {
if (f.trim()) files.add(f.trim());
}
// Staged new files (added)
const stagedNewOutput = execSync("git diff --staged --name-only --diff-filter=A", {
encoding: "utf8",
cwd: root
});
for (const f of stagedNewOutput.split("\n")) {
if (f.trim()) files.add(f.trim());
}
}
if (scope === "working-tree" || scope === "all") {
// Modified tracked files (not staged)
const modifiedOutput = execSync("git diff --name-only --diff-filter=AMD", {
encoding: "utf8",
cwd: root
});
for (const f of modifiedOutput.split("\n")) {
if (f.trim()) files.add(f.trim());
}
// Untracked new files
const untrackedOutput = execSync("git ls-files --others --exclude-standard", {
encoding: "utf8",
cwd: root
});
for (const f of untrackedOutput.split("\n")) {
if (f.trim() && !f.includes("node_modules") && !f.includes(".git")) {
files.add(f.trim());
}
}
}
return [...files];
} catch (e) {
console.warn(`Warning: Could not get git diff: ${e.message}`);
return [];
}
}
function classifyChange(file) {
for (const [category, config] of Object.entries(CHANGE_CATEGORIES)) {
if (config.excludePatterns) {
const shouldExclude = config.excludePatterns.some(p => p.test(file));
if (shouldExclude) continue;
}
if (config.patterns.some(p => p.test(file))) {
return category;
}
}
return null;
}
function getChangeType(file, scope) {
try {
let cmd;
switch (scope) {
case "staged":
cmd = `git diff --staged --name-status "${file}"`;
break;
case "working-tree":
// Check staged first, then unstaged
cmd = `git diff --staged --name-status "${file}" 2>/dev/null || git diff --name-status "${file}"`;
break;
case "all":
cmd = `git diff --name-status HEAD -- "${file}"`;
break;
default:
cmd = `git diff --staged --name-status "${file}"`;
}
const output = execSync(cmd, { encoding: "utf8", cwd: root });
const status = output.trim()[0] || "?";
const typeMap = { A: "create", M: "modify", D: "delete", R: "rename", "?": "create" };
return typeMap[status] || "create";
} catch {
// Untracked or new file - check if it exists on disk
const fullPath = path.join(root, file);
if (fs.existsSync(fullPath)) {
return "create"; // New untracked file exists on disk
}
return "modify";
}
}
function buildImpactMap(changes) {
const impactMap = {
harness: [],
agents: [],
rulesets: [],
adrs: [],
documentation: [],
templates: [],
validators: [],
navigation: [],
bilingual: []
};
for (const change of changes) {
const category = change.category;
if (!category) continue;
const config = CHANGE_CATEGORIES[category];
if (!config) continue;
for (const zone of config.impactZones) {
if (!impactMap[zone]) impactMap[zone] = [];
if (!impactMap[zone].includes(change.file)) {
impactMap[zone].push(change.file);
}
// Add cascading impacts within the same zone iteration
const dependencies = IMPACT_DEPENDENCIES[zone];
if (dependencies) {
for (const depZone of Object.keys(impactMap)) {
if (depZone === zone) continue;
const depConfig = IMPACT_DEPENDENCIES[depZone];
if (depConfig && depConfig.affectedBy.includes(category)) {
if (!impactMap[depZone].includes(change.file)) {
impactMap[depZone].push(change.file);
}
}
}
}
}
}
// Remove duplicates and empty arrays
for (const zone of Object.keys(impactMap)) {
impactMap[zone] = [...new Set(impactMap[zone])];
}
return impactMap;
}
function countAffectedComponents(impactMap) {
const allComponents = new Set();
for (const files of Object.values(impactMap)) {
for (const file of files) {
allComponents.add(file);
}
}
return allComponents.size;
}
function executeSynchronization(change, impactMap, dryRun = false) {
const syncs = [];
const zone = change.category?.toLowerCase();
const syncRule = SYNC_RULES[zone] || SYNC_RULES[change.category?.toLowerCase()];
if (syncRule) {
const ctx = { impactMap };
// Check if this is a bilingual file
const isSpanish = change.file.endsWith(".es.md");
const counterpart = isSpanish
? change.file.replace(".es.md", ".md")
: change.file.replace(".md", ".es.md");
// Add bilingual sync for any change that has a bilingual counterpart
if (fs.existsSync(path.join(root, counterpart))) {
syncs.push({
type: "bilingual_sync",
target: counterpart,
action: dryRun ? "skipped" : "validated",
changeSource: change.file,
details: `Bilingual pair ${isSpanish ? "ES→EN" : "EN→ES"} synchronized`
});
}
switch (change.changeType) {
case "create":
if (syncRule.onCreate) {
syncs.push(...syncRule.onCreate(change, ctx));
}
break;
case "modify":
if (syncRule.onModify) {
syncs.push(...syncRule.onModify(change, ctx));
}
break;
case "delete":
if (syncRule.onDelete) {
syncs.push(...syncRule.onDelete(change, ctx));
}
break;
}
} else {
// Default synchronization when no specific rule exists
syncs.push({
type: "index_update",
target: change.category,
action: dryRun ? "skipped" : "validated",
changeSource: change.file,
details: `Change ${change.changeType} in ${change.category} zone analyzed`
});
}
return syncs;
}
function checkForRisks(changes, impactMap, syncs) {
const risks = [];
for (const change of changes) {
if (change.changeType === "delete") {
const isSpanish = change.file.endsWith(".es.md");
const counterpart = isSpanish
? change.file.replace(".es.md", ".md")
: change.file.replace(".md", ".es.md");
if (fs.existsSync(path.join(root, counterpart))) {
risks.push({
risk: `Bilingual counterpart exists for deleted file`,
severity: "medium",
affectedComponent: change.file,
mitigation: `Review ${counterpart} - may need to also be updated to maintain bilingual parity`
});
}
}
if (change.category === "SCHEMA" && change.changeType === "modify") {
risks.push({
risk: `Schema modification may affect validation across multiple components`,
severity: "high",
affectedComponent: change.file,
mitigation: "Run full validation suite after schema change"
});
}
if (change.category === "HARNESS" && change.changeType === "modify") {
risks.push({
risk: `Harness modification may affect CI/CD pipeline behavior`,
severity: "high",
affectedComponent: change.file,
mitigation: "Verify all validation scripts still pass after harness change"
});
}
}
// Check for failed syncs
const failures = syncs.filter(s => s.status === "failed");
for (const failure of failures) {
risks.push({
risk: `Synchronization failure: ${failure.details}`,
severity: "high",
affectedComponent: failure.target,
mitigation: "Manual intervention required to resolve synchronization failure"
});
}
return risks;
}
function checkForManualActions(changes, syncs, risks) {
const pending = [];
const failures = syncs.filter(s => s.action === "requires_manual");
for (const f of failures) {
pending.push({
action: `Review and resolve: ${f.details}`,
reason: "Automated resolution not possible without manual review",
priority: "high",
affectedComponent: f.target
});
}
const deletesWithoutCounterpart = changes.filter(
c => c.changeType === "delete" &&
c.category === "DOCS" &&
!c.file.includes("/node_modules/")
);
if (deletesWithoutCounterpart.length > 0) {
pending.push({
action: `Review deleted files for bilingual consistency: ${deletesWithoutCounterpart.length} files`,
reason: "Files were deleted without checking bilingual counterpart status",
priority: "medium",
affectedComponent: "bilingual documentation"
});
}
// Check for ADR deletions
const adrDeletes = changes.filter(c => c.category === "ADR" && c.changeType === "delete");
if (adrDeletes.length > 0) {
pending.push({
action: `Architecture Board review required for deleted ADRs: ${adrDeletes.map(d => d.file).join(", ")}`,
reason: "ADR deletion requires Architecture Board approval as per INH-01 Core Immutability rules",
priority: "critical",
affectedComponent: "ADR Registry"
});
}
return pending;
}
function generateReport(analysis) {
const totalChanges = analysis.changes.length;
const affectedComponents = countAffectedComponents(analysis.impactMap);
const syncsApplied = analysis.synchronizations.filter(s =>
(s.action === "validated" || s.action === "updated" || s.action === "created") && s.status !== "failed"
).length;
const syncsSkipped = analysis.synchronizations.filter(s =>
s.action === "skipped" || s.status === "skipped"
).length;
const failures = analysis.synchronizations.filter(s =>
s.action === "failed" || s.status === "failed"
).length;
const risksCount = analysis.risks.length;
const manualCount = analysis.pendingManualActions.length;
let summary = `Impact Analysis completed. `;
summary += `${totalChanges} change(s) detected, `;
summary += `affecting ${affectedComponents} component(s). `;
summary += `${syncsApplied} sync(s) applied, ${syncsSkipped} skipped`;
if (failures > 0) {
summary += `, ${failures} failure(s)`;
}
if (risksCount > 0) {
summary += `, ${risksCount} risk(s)`;
}
if (manualCount > 0) {
summary += `, ${manualCount} manual action(s)`;
}
return {
summary,
changesDetected: totalChanges,
componentsAffected: affectedComponents,
synchronizationsApplied: syncsApplied,
synchronizationsSkipped: syncsSkipped,
failures,
risksIdentified: risksCount,
manualActionsRequired: manualCount
};
}
function runAnalysis(scope = "staged", dryRun = false, verbose = false) {
const startTime = Date.now();
const analysisId = generateAnalysisId();
if (verbose) {
console.log(`\n[Impact Analysis] Starting analysis ${analysisId}`);
console.log(`[Impact Analysis] Scope: ${scope}, Dry-run: ${dryRun}`);
}
// 1. Detect changes
const changedFiles = getChangedFiles(scope);
if (verbose) {
console.log(`[Impact Analysis] Detected ${changedFiles.length} changed file(s)`);
}
if (changedFiles.length === 0) {
const emptyAnalysis = {
analysisId,
timestamp: getTimestamp(),
trigger: { type: "pre_commit", source: "no changes" },
changes: [],
impactMap: {},
synchronizations: [{
type: "index_update",
target: "none",
action: "skipped",
changeSource: "none",
details: "No changes detected - analysis skipped",
status: "skipped"
}],
risks: [],
pendingManualActions: [],
report: {