-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-shared-rule-drift.ps1
More file actions
441 lines (374 loc) · 13.2 KB
/
Copy pathcheck-shared-rule-drift.ps1
File metadata and controls
441 lines (374 loc) · 13.2 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
#Requires -Version 5.1
<#
.SYNOPSIS
Compares canonical and bootstrap shared-rule blocks for drift.
.DESCRIPTION
Extracts explicitly marked shared-rule blocks from:
- skills/codebase-orient/SKILL.md
- skills/install-codebase-orient/SKILL.md
The check compares only blocks that are intended to stay synchronized.
Bootstrap-only setup text, framework probes, discovery-order structure,
output-doc examples, and other intentionally different sections are
excluded by leaving them outside the shared-rule markers.
.EXAMPLE
.\scripts\check-shared-rule-drift.ps1
#>
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Join-Path $scriptDir '..'
Set-Location $repoRoot
$canonicalPath = Join-Path $repoRoot 'skills/codebase-orient/SKILL.md'
$bootstrapPath = Join-Path $repoRoot 'skills/install-codebase-orient/SKILL.md'
$blockIds = @(
'when-to-use-this-skill',
'token-aware-use-guidance',
'normal-mode-vs-dry-run-mode',
'confidence-labels',
'docs-as-hypotheses-rule',
'ci-deployment-precision-rule',
'read-depth-heuristic',
'cheap-artifact-glob-rule',
'open-question-quality-rule',
'change-surfaces-mapping-guidance',
'no-date-only-churn-rule',
'cross-file-consistency-rule',
'orientation-completion-rule',
'orientation-report-discipline',
'project-local-specialization-rule',
'hidden-risk-reporting-rule',
'source-of-truth-drift-detection-rule'
)
$markerPattern = '<!-- shared-rule:(start|end):([a-z0-9-]+) -->'
function Get-LeadingWhitespaceWidth {
param(
[Parameter(Mandatory = $true)]
[string] $Line
)
$width = 0
foreach ($char in $Line.ToCharArray()) {
if ($char -eq ' ') {
$width++
continue
}
if ($char -eq "`t") {
$width += 4
continue
}
break
}
return $width
}
function Remove-CommonOuterIndentation {
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string[]] $Lines
)
$nonBlank = @($Lines | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
if ($nonBlank.Count -eq 0) {
return ,$Lines
}
$minIndent = ($nonBlank | ForEach-Object { Get-LeadingWhitespaceWidth -Line $_ } | Measure-Object -Minimum).Minimum
if ($minIndent -le 0) {
return ,$Lines
}
$normalized = foreach ($line in $Lines) {
if ([string]::IsNullOrWhiteSpace($line)) {
$line.TrimEnd()
continue
}
$remaining = $minIndent
$index = 0
while ($remaining -gt 0 -and $index -lt $line.Length) {
if ($line[$index] -eq ' ') {
$remaining--
$index++
continue
}
if ($line[$index] -eq "`t") {
if ($remaining -lt 4) {
break
}
$remaining -= 4
$index++
continue
}
break
}
$line.Substring($index).TrimEnd()
}
return ,$normalized
}
function Remove-CommonBlockquoteWrapper {
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string[]] $Lines
)
$nonBlank = @($Lines | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
if ($nonBlank.Count -eq 0) {
return ,$Lines
}
$allQuoted = $true
foreach ($line in $nonBlank) {
if ($line -notmatch '^\s*>\s?') {
$allQuoted = $false
break
}
}
if (-not $allQuoted) {
return ,$Lines
}
$normalized = foreach ($line in $Lines) {
$line.TrimEnd() -replace '^(\s*)>\s?', '$1'
}
return ,$normalized
}
function Normalize-HeadingDepth {
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string[]] $Lines
)
$headingLevels = @(
$Lines |
ForEach-Object {
if ($_ -match '^\s*(#{1,6})\s+') {
$Matches[1].Length
}
} |
Where-Object { $_ -is [int] }
)
$baseHeadingLevel = $null
if ($headingLevels.Count -gt 0) {
$baseHeadingLevel = ($headingLevels | Measure-Object -Minimum).Minimum
}
$normalized = foreach ($line in $Lines) {
if ($line -match '^(\s*)#{1,6}\s+(.*)$') {
$headingLevel = ($line -replace '^(\s*)(#{1,6})\s+(.*)$', '$2').Length
if ($null -eq $baseHeadingLevel) {
'{0}{1} {2}' -f $Matches[1], ('#' * $headingLevel), $Matches[2].TrimEnd()
} else {
$relativeLevel = $headingLevel - $baseHeadingLevel + 1
'{0}{1} {2}' -f $Matches[1], ('#' * $relativeLevel), $Matches[2].TrimEnd()
}
} else {
$line.TrimEnd()
}
}
return ,$normalized
}
function Trim-OuterBlankLines {
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string[]] $Lines
)
$start = 0
$end = $Lines.Count - 1
while ($start -le $end -and [string]::IsNullOrWhiteSpace($Lines[$start])) {
$start++
}
while ($end -ge $start -and [string]::IsNullOrWhiteSpace($Lines[$end])) {
$end--
}
if ($start -gt $end) {
return @('')
}
return ,($Lines[$start..$end])
}
function Get-SharedRuleBlockRecords {
param(
[Parameter(Mandatory = $true)]
[string] $Path
)
$raw = Get-Content -Raw -Encoding UTF8 $Path
$markerMatches = [regex]::Matches($raw, $markerPattern)
$records = New-Object System.Collections.Generic.List[object]
$startIds = New-Object System.Collections.Generic.List[string]
$endIds = New-Object System.Collections.Generic.List[string]
$topologyErrors = New-Object System.Collections.Generic.List[string]
$openBlock = $null
foreach ($match in $markerMatches) {
$markerType = $match.Groups[1].Value
$markerId = $match.Groups[2].Value
if ($markerType -eq 'start') {
$startIds.Add($markerId)
if ($null -ne $openBlock) {
$topologyErrors.Add(
"nested start marker in ${Path}: saw start:$markerId before closing start:$($openBlock.Id)"
)
}
$openBlock = [pscustomobject]@{
Id = $markerId
StartMarkerIndex = $match.Index
ContentStartIndex = $match.Index + $match.Length
}
continue
}
$endIds.Add($markerId)
if ($null -eq $openBlock) {
$topologyErrors.Add(
"orphan end marker in ${Path}: end:$markerId has no matching start"
)
continue
}
if ($openBlock.Id -ne $markerId) {
$topologyErrors.Add(
"mismatched end marker in ${Path}: opened start:$($openBlock.Id) but closed end:$markerId"
)
$openBlock = $null
continue
}
$rawContent = $raw.Substring($openBlock.ContentStartIndex, $match.Index - $openBlock.ContentStartIndex) -replace "`r", ''
$lines = $rawContent -split "`n"
$trimmed = Trim-OuterBlankLines -Lines $lines
$deindented = Remove-CommonOuterIndentation -Lines $trimmed
$unquoted = Remove-CommonBlockquoteWrapper -Lines $deindented
$normalizedLines = Normalize-HeadingDepth -Lines $unquoted
$records.Add([pscustomobject]@{
Id = $markerId
NormalizedContent = ($normalizedLines -join "`n")
})
$openBlock = $null
}
if ($null -ne $openBlock) {
$topologyErrors.Add(
"unclosed start marker in ${Path}: start:$($openBlock.Id) has no matching end"
)
}
if ($startIds.Count -ne $endIds.Count -or $startIds.Count -ne $records.Count) {
$topologyErrors.Add(
"marker topology mismatch in ${Path}: start markers=$($startIds.Count), end markers=$($endIds.Count), complete blocks=$($records.Count)"
)
}
return [pscustomobject]@{
Path = $Path
Records = $records
StartIds = @($startIds)
EndIds = @($endIds)
Errors = @($topologyErrors)
}
}
function Write-BlockDiff {
param(
[Parameter(Mandatory = $true)]
[string] $BlockId,
[Parameter(Mandatory = $true)]
[string] $CanonicalContent,
[Parameter(Mandatory = $true)]
[string] $BootstrapContent
)
$canonicalTemp = New-TemporaryFile
$bootstrapTemp = New-TemporaryFile
try {
Set-Content -LiteralPath $canonicalTemp -Value $CanonicalContent -Encoding UTF8
Set-Content -LiteralPath $bootstrapTemp -Value $BootstrapContent -Encoding UTF8
Write-Host "FAIL shared-rule block drift: $BlockId" -ForegroundColor Red
& git diff --no-index -- $canonicalTemp $bootstrapTemp
} finally {
Remove-Item -LiteralPath $canonicalTemp, $bootstrapTemp -ErrorAction SilentlyContinue
}
}
$canonicalResult = Get-SharedRuleBlockRecords -Path $canonicalPath
$bootstrapResult = Get-SharedRuleBlockRecords -Path $bootstrapPath
$failed = $false
foreach ($fileInfo in @(
@{ Label = 'canonical'; Result = $canonicalResult },
@{ Label = 'bootstrap'; Result = $bootstrapResult }
)) {
foreach ($validationError in $fileInfo.Result.Errors) {
Write-Host "FAIL $validationError" -ForegroundColor Red
$failed = $true
}
$startUnexpected = @($fileInfo.Result.StartIds | Where-Object { $blockIds -notcontains $_ } | Sort-Object -Unique)
if ($startUnexpected.Count -gt 0) {
Write-Host "FAIL unexpected $($fileInfo.Label) start block ids in $($fileInfo.Result.Path): $($startUnexpected -join ', ')" -ForegroundColor Red
$failed = $true
}
$endUnexpected = @($fileInfo.Result.EndIds | Where-Object { $blockIds -notcontains $_ } | Sort-Object -Unique)
if ($endUnexpected.Count -gt 0) {
Write-Host "FAIL unexpected $($fileInfo.Label) end block ids in $($fileInfo.Result.Path): $($endUnexpected -join ', ')" -ForegroundColor Red
$failed = $true
}
$ids = @($fileInfo.Result.Records | ForEach-Object { $_.Id })
$unexpected = @($ids | Where-Object { $blockIds -notcontains $_ } | Sort-Object -Unique)
if ($unexpected.Count -gt 0) {
Write-Host "FAIL unexpected $($fileInfo.Label) complete block ids in $($fileInfo.Result.Path): $($unexpected -join ', ')" -ForegroundColor Red
$failed = $true
}
$duplicates = @(
$ids |
Group-Object |
Where-Object { $_.Count -gt 1 } |
Sort-Object Name
)
if ($duplicates.Count -gt 0) {
$duplicateText = $duplicates | ForEach-Object { '{0} (x{1})' -f $_.Name, $_.Count }
Write-Host "FAIL duplicate $($fileInfo.Label) complete block ids in $($fileInfo.Result.Path): $($duplicateText -join ', ')" -ForegroundColor Red
$failed = $true
}
$startDuplicates = @(
$fileInfo.Result.StartIds |
Group-Object |
Where-Object { $_.Count -gt 1 } |
Sort-Object Name
)
if ($startDuplicates.Count -gt 0) {
$duplicateText = $startDuplicates | ForEach-Object { '{0} (x{1})' -f $_.Name, $_.Count }
Write-Host "FAIL duplicate $($fileInfo.Label) start marker ids in $($fileInfo.Result.Path): $($duplicateText -join ', ')" -ForegroundColor Red
$failed = $true
}
$endDuplicates = @(
$fileInfo.Result.EndIds |
Group-Object |
Where-Object { $_.Count -gt 1 } |
Sort-Object Name
)
if ($endDuplicates.Count -gt 0) {
$duplicateText = $endDuplicates | ForEach-Object { '{0} (x{1})' -f $_.Name, $_.Count }
Write-Host "FAIL duplicate $($fileInfo.Label) end marker ids in $($fileInfo.Result.Path): $($duplicateText -join ', ')" -ForegroundColor Red
$failed = $true
}
}
$canonicalMap = @{}
foreach ($record in $canonicalResult.Records) {
if (-not $canonicalMap.ContainsKey($record.Id)) {
$canonicalMap[$record.Id] = $record
}
}
$bootstrapMap = @{}
foreach ($record in $bootstrapResult.Records) {
if (-not $bootstrapMap.ContainsKey($record.Id)) {
$bootstrapMap[$record.Id] = $record
}
}
foreach ($blockId in $blockIds) {
if (-not $canonicalMap.ContainsKey($blockId)) {
Write-Host "FAIL missing canonical block: $blockId" -ForegroundColor Red
$failed = $true
}
if (-not $bootstrapMap.ContainsKey($blockId)) {
Write-Host "FAIL missing bootstrap block: $blockId" -ForegroundColor Red
$failed = $true
}
}
if ($failed) {
exit 1
}
foreach ($blockId in $blockIds) {
if ($canonicalMap[$blockId].NormalizedContent -ne $bootstrapMap[$blockId].NormalizedContent) {
$failed = $true
Write-BlockDiff -BlockId $blockId -CanonicalContent $canonicalMap[$blockId].NormalizedContent -BootstrapContent $bootstrapMap[$blockId].NormalizedContent
} else {
Write-Host "PASS shared-rule block: $blockId"
}
}
if ($failed) {
Write-Host ''
Write-Host 'check-shared-rule-drift: shared-rule drift found. See diff above.' -ForegroundColor Red
exit 1
}
Write-Host ''
Write-Host 'check-shared-rule-drift: all shared-rule blocks are synchronized.'