oc-harness-setup 0.2.0 → 0.3.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 (115) hide show
  1. package/.docs/unwired-routing.md +14 -9
  2. package/.gitignore +14 -1
  3. package/AGENTS.md +70 -106
  4. package/README.md +27 -23
  5. package/agents/build.md +10 -12
  6. package/agents/explore.md +14 -8
  7. package/agents/general.md +7 -9
  8. package/agents/orchestrator.md +38 -0
  9. package/agents/plan.md +10 -13
  10. package/agents/reviewer.md +9 -14
  11. package/agents/vault.md +44 -35
  12. package/bin/cli.js +32 -3
  13. package/commands/build.md +2 -8
  14. package/commands/checkpoint.md +3 -1
  15. package/commands/code-simplify.md +3 -9
  16. package/commands/gauntlet.md +7 -0
  17. package/commands/handoff.md +3 -1
  18. package/commands/keeper.md +3 -3
  19. package/commands/kill.md +11 -0
  20. package/commands/plan.md +2 -13
  21. package/commands/retro.md +15 -0
  22. package/commands/review.md +1 -1
  23. package/commands/ship.md +3 -27
  24. package/commands/spec.md +3 -11
  25. package/commands/test.md +2 -9
  26. package/commands/webperf.md +7 -0
  27. package/opencode.jsonc +23 -8
  28. package/package.json +3 -3
  29. package/reference/README.md +14 -14
  30. package/reference/auto-mandate.md +11 -0
  31. package/reference/backup-convention.md +9 -0
  32. package/reference/clean-mandate.md +13 -0
  33. package/reference/editor-parity.md +7 -0
  34. package/reference/gc-scripts.md +8 -0
  35. package/reference/intent-routing.md +14 -0
  36. package/reference/lifecycle.md +15 -0
  37. package/reference/model-keeper.md +30 -10
  38. package/reference/model-test.md +11 -6
  39. package/reference/models.md +25 -14
  40. package/reference/oc-source-map.md +162 -0
  41. package/reference/owner-pin.md +31 -0
  42. package/reference/roster.md +15 -0
  43. package/reference/session-scope.md +9 -0
  44. package/reference/session-state.md +13 -0
  45. package/reference/swarm.md +32 -0
  46. package/scripts/backup-config.ps1 +42 -0
  47. package/scripts/gc-branch.ps1 +196 -0
  48. package/scripts/gc-bump.ps1 +198 -0
  49. package/scripts/gc-clean.ps1 +648 -0
  50. package/scripts/gc-commit.ps1 +143 -0
  51. package/scripts/gc-merge.ps1 +272 -0
  52. package/scripts/gc-pr.ps1 +190 -0
  53. package/scripts/gc-push.ps1 +111 -0
  54. package/scripts/gc-read.ps1 +150 -0
  55. package/scripts/gc-rebase.ps1 +162 -0
  56. package/scripts/gc-release.ps1 +225 -0
  57. package/scripts/gc-stage.ps1 +103 -0
  58. package/scripts/gc-status.ps1 +127 -0
  59. package/scripts/gc-sync.ps1 +65 -0
  60. package/scripts/gc.core.ps1 +715 -0
  61. package/scripts/gc.smoke.ps1 +779 -0
  62. package/scripts/harness-doctor.ps1 +11 -9
  63. package/scripts/interrupt-session.ps1 +65 -0
  64. package/scripts/logbook/README.md +108 -0
  65. package/scripts/logbook/logbook.test.ts +440 -0
  66. package/scripts/logbook/logbook.ts +797 -0
  67. package/scripts/pirep/README.md +147 -0
  68. package/scripts/pirep/pirep.test.ts +735 -0
  69. package/scripts/pirep/pirep.ts +836 -0
  70. package/scripts/testflight/README.md +112 -0
  71. package/scripts/testflight/testflight.test.ts +512 -0
  72. package/scripts/testflight/testflight.ts +806 -0
  73. package/skills/_shared/SOURCES.md +7 -7
  74. package/skills/_shared/references/definition-of-done.md +2 -2
  75. package/skills/_shared/references/orchestration-patterns.md +1 -2
  76. package/skills/_shared/references/security-checklist.md +2 -2
  77. package/skills/api-and-interface-design/SKILL.md +7 -360
  78. package/skills/browser-testing-with-devtools/SKILL.md +303 -0
  79. package/skills/code-simplification/SKILL.md +7 -364
  80. package/skills/creative-writing/SKILL.md +1 -1
  81. package/skills/debugging-and-error-recovery/SKILL.md +8 -309
  82. package/skills/flight-deck/SKILL.md +17 -0
  83. package/skills/frontend-ui-engineering/SKILL.md +8 -320
  84. package/skills/gauntlet/SKILL.md +21 -0
  85. package/skills/git-ceremony/SKILL.md +16 -318
  86. package/skills/grilling/SKILL.md +10 -30
  87. package/skills/observability-and-instrumentation/SKILL.md +9 -229
  88. package/skills/performance-optimization/SKILL.md +8 -488
  89. package/skills/pilot-report/SKILL.md +18 -0
  90. package/skills/planning-and-task-breakdown/SKILL.md +8 -249
  91. package/skills/security-and-hardening/SKILL.md +9 -490
  92. package/skills/source-driven-development/SKILL.md +8 -208
  93. package/skills/spec-driven-development/SKILL.md +15 -234
  94. package/skills/test-driven-development/SKILL.md +8 -388
  95. package/skills/test-flight/SKILL.md +14 -0
  96. package/skills/writing-for-agents/SKILL-MECHANICS.md +3 -3
  97. package/skills/writing-for-agents/SKILL.md +7 -1
  98. package/agents/coder.md +0 -19
  99. package/agents/documenter.md +0 -28
  100. package/agents/keeper.md +0 -22
  101. package/agents/master.md +0 -70
  102. package/agents/researcher.md +0 -21
  103. package/agents/security-auditor.md +0 -20
  104. package/agents/test-engineer.md +0 -20
  105. package/agents/web-performance-auditor.md +0 -19
  106. package/commands/council.md +0 -24
  107. package/commands/doctor.md +0 -19
  108. package/commands/ponytail-audit.md +0 -7
  109. package/commands/ponytail-debt.md +0 -14
  110. package/commands/report.md +0 -13
  111. package/scripts/harness-report.ps1 +0 -695
  112. package/scripts/panic/panic.ts +0 -240
  113. package/skills/code-review-and-quality/SKILL.md +0 -396
  114. package/skills/incremental-implementation/SKILL.md +0 -249
  115. package/skills/swarm-orchestration/SKILL.md +0 -54
@@ -0,0 +1,648 @@
1
+ #Requires -Version 7.0
2
+ <#
3
+ .SYNOPSIS
4
+ Housekeeper sweep for the two junk roots: dry-run report by default, and
5
+ deletion only with -Force while the session is armed with `--clean`.
6
+
7
+ .DESCRIPTION
8
+ `--clean` housekeeper as a script (reference/clean-mandate.md). Default roots:
9
+
10
+ %TEMP%\opencode
11
+ %USERPROFILE%\.cache\opencode
12
+
13
+ `-Root <path>` overrides with a single sweep root (testing/sandbox use); the
14
+ github\ / github\v2 structure semantics are derived under it when present.
15
+
16
+ Phase 0 runs FIRST and unconditionally (dry-run and armed mode alike): files
17
+ matching `*.bak*` found inside %USERPROFILE%\.config\opencode are MOVED -
18
+ never deleted - into %USERPROFILE%\.opencode\config-backups\.
19
+
20
+ Junk classes (the ONLY deletions permitted):
21
+ - `*.bak*` temp config backups;
22
+ - stale cache entries under github\v2 for plugins not in the adopter's
23
+ live set (safe to re-fetch if ever re-added) - classified only when a
24
+ live set is passed via -LiveCache; without one, v2 entries are
25
+ reported, never deleted (a live cache is indistinguishable from stale
26
+ without the list);
27
+ - old-layout leftovers under github\ that are not github\v2\;
28
+ - directories left empty after those deletions.
29
+
30
+ Everything else is unclassified: reported, never deleted. Repo-local
31
+ untracked files are listed only - this tool never deletes them.
32
+
33
+ SAFETY RAILS (defence in depth, all enforced here):
34
+ - without -Force nothing is deleted anywhere;
35
+ - a deletion candidate must sit strictly under a resolved root, never be
36
+ a reparse point, never be on the keep-list, and must scan clean for
37
+ credential-shaped names and secret-shaped content - a hit is reported
38
+ by path only, contents are never printed;
39
+ - junk-class misclassification is a hard refusal: only the four classes
40
+ above are ever deleted, everything else is reported;
41
+ - if the keep-list cannot be resolved (script path, reference directory,
42
+ -KeepExtra), -Force stops with exit 2;
43
+ - the keep-list is law, PROTECT-IF-PRESENT: this script, the reference
44
+ directory, any *.tgz npm pack, the adopter's live v2 cache entries
45
+ (via -LiveCache), plus -KeepExtra. An absent keep is skipped with a
46
+ note - never a hard exit.
47
+
48
+ OUTPUT: stdout carries only the final `RESULT: <json>` line (take the LAST
49
+ one); everything else is console narration. The terse default prints the
50
+ would-delete/done table, the reported/kept summary, the keep-list line and
51
+ warnings; -Detailed adds the keep ledger, the complete reported/kept list
52
+ and the complete untracked listing.
53
+
54
+ .PARAMETER Force
55
+ Delete the classified junk. Only pass while the session is armed with
56
+ `--clean`; without it the sweep is a dry run.
57
+ .PARAMETER KeepExtra
58
+ Additional paths this run must never touch (prefix semantics: a kept path
59
+ covers everything beneath it).
60
+ .PARAMETER Root
61
+ Optional single sweep root override (default: the two roots above). For
62
+ sandboxed test runs; the github\ / github\v2 classes are derived under it.
63
+ .PARAMETER LiveCache
64
+ Name prefixes of the adopter's current plugin cache entries under
65
+ github\v2 (e.g. `owner--plugin--`). Kept as law; other `*--*--*` v2 entries
66
+ are junk only while this list is non-empty.
67
+ .PARAMETER RepoRoot
68
+ Path whose untracked files are listed (defaults to the current directory).
69
+ Listing only - never deleted by this tool.
70
+ .PARAMETER Detailed
71
+ Restore the full narration: keep ledger, complete reported/kept list,
72
+ complete untracked listing. Never affects the RESULT line, warnings or
73
+ failures.
74
+
75
+ .EXAMPLE
76
+ pwsh -File scripts\gc-clean.ps1
77
+
78
+ .EXAMPLE
79
+ # only while the session is armed with `--clean`
80
+ pwsh -File scripts\gc-clean.ps1 -Force -KeepExtra "$env:TEMP\opencode\my-scratch"
81
+
82
+ .EXAMPLE
83
+ # sandboxed test sweep against a scratch directory
84
+ pwsh -File scripts\gc-clean.ps1 -Root "$env:TEMP\opencode\sweep-sandbox" -LiveCache 'acme--plugin--' -Force
85
+ #>
86
+ param(
87
+ [switch]$Force,
88
+ [string[]]$KeepExtra = @(),
89
+ [string]$Root = '',
90
+ [string[]]$LiveCache = @(),
91
+ [string]$RepoRoot = (Get-Location).Path,
92
+ [switch]$Detailed
93
+ )
94
+ Set-StrictMode -Version Latest
95
+ $ErrorActionPreference = 'Stop'
96
+ . (Join-Path $PSScriptRoot 'gc.core.ps1')
97
+ if ($Detailed) { $script:GcQuiet = $false }
98
+
99
+ # --- constants ----------------------------------------------------------------
100
+ # live v2 cache entry name prefixes the sweep must never touch - adopter-set
101
+ # (reference/clean-mandate.md - keep-list is law; empty = no live set known)
102
+ $script:CleanLiveCachePrefixes = @($LiveCache)
103
+ # secret-scan bounds: config backups are tiny; anything bigger is refused
104
+ # (kept) rather than deleted unverified - fail-safe, never fail-fast
105
+ $script:CleanScanMaxBytes = 2MB
106
+ $script:CleanScanMaxFiles = 2000
107
+
108
+ # --- sweep state (populated before any scan) ----------------------------------
109
+ $script:CleanRoots = [System.Collections.Generic.List[string]]::new()
110
+ $script:CleanStructureDirs = [System.Collections.Generic.List[string]]::new()
111
+ $script:CleanUnitParents = [System.Collections.Generic.List[string]]::new()
112
+ $script:CleanKeepFiles = [System.Collections.Generic.List[string]]::new()
113
+ $script:CleanKeepPrefixes = [System.Collections.Generic.List[string]]::new()
114
+ $script:CleanKeepHits = [System.Collections.Generic.List[object]]::new()
115
+ $script:CleanWouldDelete = [System.Collections.Generic.List[object]]::new()
116
+ $script:CleanReported = [System.Collections.Generic.List[object]]::new()
117
+ $script:CleanUnclassified = 0
118
+
119
+ # --- helpers ------------------------------------------------------------------
120
+ function ConvertTo-CleanPath {
121
+ <# absolute path, no trailing separator; throws when unnormalisable. #>
122
+ param([Parameter(Mandatory)][string]$Path)
123
+ return ([System.IO.Path]::GetFullPath($Path)).TrimEnd([char]'\', [char]'/')
124
+ }
125
+
126
+ function Test-CleanKept {
127
+ <# keep-list is law: exact file keeps and prefix (subtree) keeps. #>
128
+ param([Parameter(Mandatory)][string]$Path)
129
+ foreach ($f in $script:CleanKeepFiles) {
130
+ if ($Path.Equals($f, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
131
+ }
132
+ foreach ($p in $script:CleanKeepPrefixes) {
133
+ if ($Path.Equals($p, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
134
+ if ($Path.StartsWith($p + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
135
+ }
136
+ return $false
137
+ }
138
+
139
+ function Test-CleanUnderRoot {
140
+ <# strictly under a resolved sweep root - nothing else can EVER be deleted. #>
141
+ param([Parameter(Mandatory)][string]$Path)
142
+ foreach ($r in $script:CleanRoots) {
143
+ if ($Path.StartsWith($r + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
144
+ }
145
+ return $false
146
+ }
147
+
148
+ function Test-CleanStructureDir {
149
+ param([Parameter(Mandatory)][string]$Path)
150
+ foreach ($s in $script:CleanStructureDirs) {
151
+ if ($Path -ieq $s) { return $true }
152
+ }
153
+ return $false
154
+ }
155
+
156
+ function Test-CleanUnitParent {
157
+ <# unclassified items are itemized at unit level only (root children and
158
+ the structured github\ / github\v2 levels); a nested file inside an
159
+ unclassified kept subtree belongs to that unit's report, not a unit. #>
160
+ param([Parameter(Mandatory)][string]$Parent)
161
+ foreach ($p in $script:CleanUnitParents) {
162
+ if ($Parent -ieq $p) { return $true }
163
+ }
164
+ return $false
165
+ }
166
+
167
+ function Test-CleanLiveCache {
168
+ param([Parameter(Mandatory)][string]$Name)
169
+ foreach ($p in $script:CleanLiveCachePrefixes) {
170
+ if ($Name.StartsWith($p, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
171
+ }
172
+ return $false
173
+ }
174
+
175
+ function Test-CleanCredentialName {
176
+ <# credential-shaped leaf names are never deleted; .env.example-style safe
177
+ names stay deletable as junk, matching the core secret gate. #>
178
+ param([Parameter(Mandatory)][string]$Name)
179
+ if ($Name -match $script:GcSecretSafeFilenameRe) { return $false }
180
+ return ($Name -match $script:GcSecretFilenameRe)
181
+ }
182
+
183
+ function Get-CleanFileVerdict {
184
+ <# $null = scanned clean; otherwise the reason the file must be KEPT.
185
+ Content is read only to prove the absence of secret shapes. #>
186
+ param([Parameter(Mandatory)][string]$File)
187
+ $len = 0L
188
+ try { $len = [System.IO.FileInfo]::new($File).Length } catch { return 'unreadable - kept' }
189
+ if ($len -gt $script:CleanScanMaxBytes) { return "larger than $([int]($script:CleanScanMaxBytes / 1KB)) KB - cannot verify secret-free, kept" }
190
+ $text = ''
191
+ try { $text = [System.IO.File]::ReadAllText($File) } catch { return 'unreadable - kept' }
192
+ foreach ($re in $script:GcSecretContentRes) {
193
+ if ($text -match $re) { return 'secret-shaped content - kept, contents not printed' }
194
+ }
195
+ return $null
196
+ }
197
+
198
+ function Get-CleanTreeVerdict {
199
+ <# $null = every contained file scanned clean; otherwise the reason the
200
+ whole tree must be KEPT (reparse points and oversized trees refuse). #>
201
+ param([Parameter(Mandatory)][string]$Dir)
202
+ $seen = 0
203
+ $stack = [System.Collections.Generic.Stack[string]]::new()
204
+ $stack.Push($Dir)
205
+ while ($stack.Count -gt 0) {
206
+ $d = $stack.Pop()
207
+ try { $entries = @([System.IO.Directory]::EnumerateFileSystemEntries($d)) } catch { return 'unreadable subtree - kept' }
208
+ foreach ($e in $entries) {
209
+ $attr = $null
210
+ try { $attr = [System.IO.File]::GetAttributes($e) } catch { }
211
+ if ($null -eq $attr) { return 'entry unreadable during scan - kept' }
212
+ if ($attr -band [System.IO.FileAttributes]::ReparsePoint) { return 'contains a reparse point - kept' }
213
+ if ($attr -band [System.IO.FileAttributes]::Directory) { $stack.Push($e); continue }
214
+ $seen++
215
+ if ($seen -gt $script:CleanScanMaxFiles) { return "more than $($script:CleanScanMaxFiles) files - cannot verify secret-free, kept" }
216
+ if (Test-CleanCredentialName ([System.IO.Path]::GetFileName($e))) { return 'credential-shaped filename inside - kept' }
217
+ $v = Get-CleanFileVerdict -File $e
218
+ if ($v) { return "$v (inside this tree)" }
219
+ }
220
+ }
221
+ return $null
222
+ }
223
+
224
+ function Get-CleanTreeSize {
225
+ <# bytes under a path (files only; reparse points skipped). #>
226
+ param([Parameter(Mandatory)][string]$Path)
227
+ [long]$sum = 0
228
+ $stack = [System.Collections.Generic.Stack[string]]::new()
229
+ $stack.Push($Path)
230
+ while ($stack.Count -gt 0) {
231
+ $d = $stack.Pop()
232
+ try { $entries = @([System.IO.Directory]::EnumerateFileSystemEntries($d)) } catch { continue }
233
+ foreach ($e in $entries) {
234
+ $attr = $null
235
+ try { $attr = [System.IO.File]::GetAttributes($e) } catch { }
236
+ if ($null -eq $attr) { continue }
237
+ if ($attr -band [System.IO.FileAttributes]::ReparsePoint) { continue }
238
+ if ($attr -band [System.IO.FileAttributes]::Directory) { $stack.Push($e); continue }
239
+ try { $sum += [System.IO.FileInfo]::new($e).Length } catch { }
240
+ }
241
+ }
242
+ return $sum
243
+ }
244
+
245
+ function Test-CleanEmptyDir {
246
+ param([Parameter(Mandatory)][string]$Path)
247
+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return $false }
248
+ try {
249
+ $en = [System.IO.Directory]::EnumerateFileSystemEntries($Path).GetEnumerator()
250
+ try { return -not $en.MoveNext() } finally { $en.Dispose() }
251
+ } catch { return $false }
252
+ }
253
+
254
+ # --- main ---------------------------------------------------------------------
255
+ try {
256
+ # --- phase 0: relocate stray *.bak* under the config dir (enforcement net) ---
257
+ # Non-destructive and UNCONDITIONAL (dry-run and armed mode alike): any
258
+ # `*.bak*` file found inside %USERPROFILE%\.config\opencode - placed there
259
+ # by any means, including manual commands - is MOVED, never deleted, into
260
+ # %USERPROFILE%\.opencode\config-backups\. `-Recurse` does not descend
261
+ # into reparse points; that stays true (no -FollowSymlink).
262
+ if ($env:USERPROFILE) {
263
+ $cfgDir = ConvertTo-CleanPath (Join-Path $env:USERPROFILE '.config\opencode')
264
+ $bakDst = ConvertTo-CleanPath (Join-Path $env:USERPROFILE '.opencode\config-backups')
265
+ if (Test-Path -LiteralPath $cfgDir -PathType Container) {
266
+ if (-not (Test-Path -LiteralPath $bakDst -PathType Container)) {
267
+ try { New-Item -ItemType Directory -Path $bakDst -Force -ErrorAction Stop | Out-Null }
268
+ catch { Write-GcWarn "phase 0: cannot create $bakDst - $($_.Exception.Message)" }
269
+ }
270
+ if (Test-Path -LiteralPath $bakDst -PathType Container) {
271
+ foreach ($f in @(Get-ChildItem -LiteralPath $cfgDir -Recurse -File -Force | Where-Object { $_.Name -like '*.bak*' })) {
272
+ $dest = Join-Path $bakDst $f.Name
273
+ $i = 1
274
+ while (Test-Path -LiteralPath $dest) {
275
+ $dest = Join-Path $bakDst ('{0}-{1}{2}' -f $f.BaseName, $i, $f.Extension)
276
+ $i++
277
+ }
278
+ try {
279
+ Move-Item -LiteralPath $f.FullName -Destination $dest -ErrorAction Stop
280
+ Write-GcNotice "moved: $($f.FullName) -> $dest"
281
+ } catch { Write-GcWarn "phase 0: move failed - $($f.FullName): $($_.Exception.Message)" }
282
+ }
283
+ }
284
+ }
285
+ } else {
286
+ Write-GcWarn 'phase 0: %USERPROFILE% is not set - config-backups relocation skipped'
287
+ }
288
+ # roots first: a root that cannot be resolved is skipped, loudly
289
+ $tempRoot = $null; $cacheRoot = $null; $cacheGithub = $null; $cacheV2 = $null
290
+ $rootProblems = [System.Collections.Generic.List[string]]::new()
291
+
292
+ if ($Root) {
293
+ try {
294
+ $tempRoot = ConvertTo-CleanPath $Root
295
+ if ([System.IO.Path]::GetPathRoot($tempRoot) -eq $tempRoot) { throw 'resolves to a volume root' }
296
+ $script:CleanRoots.Add($tempRoot)
297
+ $cacheGithub = Join-Path $tempRoot 'github'
298
+ $cacheV2 = Join-Path $cacheGithub 'v2'
299
+ } catch { $rootProblems.Add("-Root ${Root}: $($_.Exception.Message)"); $tempRoot = $null }
300
+ } else {
301
+ $tempBase = if ($env:TEMP) { $env:TEMP } else { [System.IO.Path]::GetTempPath() }
302
+ if ($tempBase) {
303
+ try {
304
+ $tempRoot = ConvertTo-CleanPath (Join-Path $tempBase 'opencode')
305
+ if ([System.IO.Path]::GetPathRoot($tempRoot) -eq $tempRoot) { throw 'resolves to a volume root' }
306
+ $script:CleanRoots.Add($tempRoot)
307
+ } catch { $rootProblems.Add("%TEMP%\opencode: $($_.Exception.Message)"); $tempRoot = $null }
308
+ } else {
309
+ $rootProblems.Add('%TEMP% and GetTempPath() are both unavailable')
310
+ }
311
+
312
+ if ($env:USERPROFILE) {
313
+ try {
314
+ $cacheRoot = ConvertTo-CleanPath (Join-Path $env:USERPROFILE '.cache\opencode')
315
+ if ([System.IO.Path]::GetPathRoot($cacheRoot) -eq $cacheRoot) { throw 'resolves to a volume root' }
316
+ $script:CleanRoots.Add($cacheRoot)
317
+ $cacheGithub = Join-Path $cacheRoot 'github'
318
+ $cacheV2 = Join-Path $cacheGithub 'v2'
319
+ } catch { $rootProblems.Add('%USERPROFILE%\.cache\opencode: ' + $_.Exception.Message); $cacheRoot = $null }
320
+ } else {
321
+ $rootProblems.Add('%USERPROFILE% is not set')
322
+ }
323
+ }
324
+
325
+ # structure dirs the empty-dir sweep must never remove (github\v2 is the
326
+ # live cache layout, not junk)
327
+ foreach ($d in @($tempRoot, $cacheRoot, $cacheGithub, $cacheV2)) {
328
+ if ($d) { $script:CleanStructureDirs.Add($d) }
329
+ }
330
+ # unit level for the unclassified report: immediate children of these dirs
331
+ foreach ($d in @($tempRoot, $cacheRoot, $cacheGithub, $cacheV2)) {
332
+ if ($d) { $script:CleanUnitParents.Add($d) }
333
+ }
334
+
335
+ # --- keep-list registration (must succeed before any deletion) ------------
336
+ $keepProblems = [System.Collections.Generic.List[string]]::new()
337
+ function Add-CleanKeep {
338
+ <# register one keep; an unnormalisable path is a recorded problem -
339
+ never silently dropped from the law. Absent keeps are registered as
340
+ prefix keeps (most conservative): PROTECT-IF-PRESENT - they are
341
+ skipped with a note, never fatal. #>
342
+ param(
343
+ [Parameter(Mandatory)][string]$Label,
344
+ [Parameter(Mandatory)][string]$Path,
345
+ [ValidateSet('prefix', 'file', 'auto')][string]$Kind = 'auto'
346
+ )
347
+ try {
348
+ $abs = ConvertTo-CleanPath $Path
349
+ if ($Kind -eq 'auto') {
350
+ if (Test-Path -LiteralPath $abs -PathType Container) { $Kind = 'prefix' }
351
+ elseif (Test-Path -LiteralPath $abs -PathType Leaf) { $Kind = 'file' }
352
+ else {
353
+ $Kind = 'prefix' # absent keeps are treated as subtrees (most conservative)
354
+ Write-GcWarn "keep not present, PROTECT-IF-PRESENT (registered as subtree): $Label ($Path)"
355
+ }
356
+ }
357
+ if ($Kind -eq 'file') { $script:CleanKeepFiles.Add($abs) } else { $script:CleanKeepPrefixes.Add($abs) }
358
+ } catch {
359
+ $keepProblems.Add("$Label ($Path): $($_.Exception.Message)")
360
+ }
361
+ }
362
+
363
+ if ($PSScriptRoot) {
364
+ Add-CleanKeep -Label 'this script' -Path (Join-Path $PSScriptRoot 'gc-clean.ps1') -Kind auto
365
+ Add-CleanKeep -Label 'reference directory' -Path (Join-Path $PSScriptRoot '..\reference') -Kind prefix
366
+ } else {
367
+ $keepProblems.Add('this script and the reference directory: script root unresolved')
368
+ }
369
+ foreach ($k in $KeepExtra) {
370
+ if (-not $k) { $keepProblems.Add('-KeepExtra: empty path ignored'); continue }
371
+ Add-CleanKeep -Label '-KeepExtra' -Path $k -Kind auto
372
+ }
373
+
374
+ # defence in depth: -Force with an unresolvable keep-list is a loud stop
375
+ if ($Force -and $keepProblems.Count -gt 0) {
376
+ foreach ($p in $keepProblems) { Write-GcFail "keep-list cannot be resolved: $p" }
377
+ Write-GcResult -Code $script:GcExitPre -Props @{ message = 'keep-list cannot be resolved - refusing to delete' }
378
+ }
379
+ foreach ($p in $keepProblems) { Write-GcWarn "keep-list incomplete: $p" }
380
+ foreach ($p in $rootProblems) { Write-GcWarn "root skipped: $p" }
381
+
382
+ # --- scan ------------------------------------------------------------------
383
+ function Add-CleanReport {
384
+ param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Reason)
385
+ $script:CleanReported.Add([pscustomobject]@{ Path = $Path; Reason = $Reason })
386
+ }
387
+
388
+ function Add-CleanJunk {
389
+ <# a pattern hit: size it, verify it is secret-free, then either queue
390
+ it for deletion or downgrade it to reported/kept. #>
391
+ param(
392
+ [Parameter(Mandatory)][string]$Path,
393
+ [Parameter(Mandatory)][ValidateSet('file', 'dir')][string]$Kind,
394
+ [Parameter(Mandatory)][string]$Class
395
+ )
396
+ $verdict = if ($Kind -eq 'file') { Get-CleanFileVerdict -File $Path } else { Get-CleanTreeVerdict -Dir $Path }
397
+ if ($verdict) {
398
+ Add-CleanReport -Path $Path -Reason "$Class candidate but $verdict"
399
+ Write-GcWarn "kept ($Class): $Path - $verdict"
400
+ return
401
+ }
402
+ [long]$size = 0
403
+ if ($Kind -eq 'file') {
404
+ try { $size = [System.IO.FileInfo]::new($Path).Length } catch { $size = 0 }
405
+ } else {
406
+ $size = Get-CleanTreeSize -Path $Path
407
+ }
408
+ $script:CleanWouldDelete.Add([pscustomobject]@{ Path = $Path; Kind = $Kind; Class = $Class; Size = $size })
409
+ }
410
+
411
+ foreach ($root in $script:CleanRoots) {
412
+ if (-not (Test-Path -LiteralPath $root -PathType Container)) {
413
+ Write-GcWarn "root missing, skipped: $root"
414
+ continue
415
+ }
416
+ $stack = [System.Collections.Generic.Stack[string]]::new()
417
+ $stack.Push($root)
418
+ while ($stack.Count -gt 0) {
419
+ $dir = $stack.Pop()
420
+ try { $entries = @([System.IO.Directory]::EnumerateFileSystemEntries($dir)) }
421
+ catch { Write-GcWarn "unreadable directory skipped: $dir - $($_.Exception.Message)"; continue }
422
+ foreach ($entry in $entries) {
423
+ $attr = $null
424
+ try { $attr = [System.IO.File]::GetAttributes($entry) } catch { }
425
+ if ($null -eq $attr) { Add-CleanReport -Path $entry -Reason 'vanished or unreadable during the scan'; continue }
426
+
427
+ $name = [System.IO.Path]::GetFileName($entry)
428
+ $parent = [System.IO.Path]::GetDirectoryName($entry)
429
+ $isDir = ($attr -band [System.IO.FileAttributes]::Directory) -ne 0
430
+
431
+ if ($attr -band [System.IO.FileAttributes]::ReparsePoint) {
432
+ Add-CleanReport -Path $entry -Reason 'reparse point - never followed or deleted'
433
+ continue
434
+ }
435
+ if (Test-CleanKept -Path $entry) {
436
+ $script:CleanKeepHits.Add([pscustomobject]@{ Path = $entry; Kind = $(if ($isDir) { 'dir' } else { 'file' }) })
437
+ continue
438
+ }
439
+ if (-not $isDir -and ($name -like '*.tgz')) {
440
+ $script:CleanKeepHits.Add([pscustomobject]@{ Path = $entry; Kind = 'tgz' })
441
+ continue
442
+ }
443
+
444
+ if ($isDir) {
445
+ if (Test-CleanStructureDir -Path $entry) { $stack.Push($entry); continue } # github / github\v2: descend
446
+ if ($cacheV2 -and ($parent -ieq $cacheV2) -and (Test-CleanLiveCache -Name $name)) {
447
+ # live cache entries are keep-list: recorded, never scanned, never touched
448
+ $script:CleanKeepHits.Add([pscustomobject]@{ Path = $entry; Kind = 'live-cache' })
449
+ continue
450
+ }
451
+ if ($cacheGithub -and ($parent -ieq $cacheGithub) -and ($name -ine 'v2')) {
452
+ Add-CleanJunk -Path $entry -Kind dir -Class 'old-layout'
453
+ continue
454
+ }
455
+ if ($cacheV2 -and ($parent -ieq $cacheV2) -and ($name -like '*--*--*') -and ($script:CleanLiveCachePrefixes.Count -gt 0) -and -not (Test-CleanLiveCache -Name $name)) {
456
+ Add-CleanJunk -Path $entry -Kind dir -Class 'stale-cache'
457
+ continue
458
+ }
459
+ if ($name -like '*.bak*') {
460
+ Add-CleanJunk -Path $entry -Kind dir -Class 'bak'
461
+ continue
462
+ }
463
+ if (Test-CleanUnitParent -Parent $parent) {
464
+ $script:CleanUnclassified++
465
+ Add-CleanReport -Path $entry -Reason 'unclassified - kept'
466
+ }
467
+ $stack.Push($entry)
468
+ continue
469
+ }
470
+
471
+ if (Test-CleanCredentialName -Name $name) {
472
+ Add-CleanReport -Path $entry -Reason 'credential-shaped filename - kept'
473
+ continue
474
+ }
475
+ if ($name -like '*.bak*') {
476
+ Add-CleanJunk -Path $entry -Kind file -Class 'bak'
477
+ continue
478
+ }
479
+ if (Test-CleanUnitParent -Parent $parent) {
480
+ $script:CleanUnclassified++
481
+ Add-CleanReport -Path $entry -Reason 'unclassified - kept'
482
+ }
483
+ }
484
+ }
485
+ }
486
+
487
+ # --- report / delete -------------------------------------------------------
488
+ $items = $script:CleanWouldDelete.Count
489
+ [long]$bytes = 0
490
+ foreach ($i in $script:CleanWouldDelete) { $bytes += $i.Size }
491
+
492
+ $deleted = [System.Collections.Generic.List[object]]::new()
493
+ $failures = [System.Collections.Generic.List[string]]::new()
494
+ $removedEmpty = [System.Collections.Generic.List[string]]::new()
495
+ [long]$freed = 0
496
+
497
+ if ($Force) {
498
+ # deletion order: files first, then classified trees, then the dirs
499
+ # those deletions left empty
500
+ foreach ($item in @($script:CleanWouldDelete | Where-Object { $_.Kind -eq 'file' } | Sort-Object -Property Path)) {
501
+ if (-not (Test-CleanUnderRoot -Path $item.Path) -or (Test-CleanKept -Path $item.Path)) {
502
+ $failures.Add("$($item.Path): refused - outside a resolved root or on the keep-list")
503
+ continue
504
+ }
505
+ if (-not (Test-Path -LiteralPath $item.Path)) { continue } # vanished since the scan: nothing to do
506
+ try { Remove-Item -LiteralPath $item.Path -Force -ErrorAction Stop; $deleted.Add($item); $freed += $item.Size }
507
+ catch { $failures.Add("$($item.Path): $($_.Exception.Message)") }
508
+ }
509
+ foreach ($item in @($script:CleanWouldDelete | Where-Object { $_.Kind -eq 'dir' } | Sort-Object -Property Path)) {
510
+ if (-not (Test-CleanUnderRoot -Path $item.Path) -or (Test-CleanKept -Path $item.Path)) {
511
+ $failures.Add("$($item.Path): refused - outside a resolved root or on the keep-list")
512
+ continue
513
+ }
514
+ if (-not (Test-Path -LiteralPath $item.Path)) { continue }
515
+ try { Remove-Item -LiteralPath $item.Path -Force -Recurse -ErrorAction Stop; $deleted.Add($item); $freed += $item.Size }
516
+ catch { $failures.Add("$($item.Path): $($_.Exception.Message)") }
517
+ }
518
+ # empty-dir sweep: only parents a deletion may have emptied, never the
519
+ # roots and never the github\ / github\v2 structure
520
+ $starts = [System.Collections.Generic.List[string]]::new()
521
+ foreach ($item in $deleted) {
522
+ $p = [System.IO.Path]::GetDirectoryName($item.Path)
523
+ if ($p) { $starts.Add($p) }
524
+ }
525
+ foreach ($start in $starts) {
526
+ $d = $start
527
+ while ($d) {
528
+ if (-not (Test-CleanUnderRoot -Path $d)) { break }
529
+ if ((Test-CleanKept -Path $d) -or (Test-CleanStructureDir -Path $d)) { break }
530
+ if (-not (Test-CleanEmptyDir -Path $d)) { break }
531
+ try { Remove-Item -LiteralPath $d -Force -ErrorAction Stop; $removedEmpty.Add($d) }
532
+ catch { $failures.Add("${d}: $($_.Exception.Message)"); break }
533
+ $d = [System.IO.Path]::GetDirectoryName($d)
534
+ }
535
+ }
536
+ }
537
+
538
+ if ($Force) {
539
+ if ($deleted.Count -gt 0) {
540
+ Write-GcNotice 'deleted:'
541
+ foreach ($i in @($deleted | Sort-Object -Property Path)) {
542
+ Write-GcNotice (" {0,12:N0} B [{1}] {2}" -f $i.Size, $i.Class, $i.Path)
543
+ }
544
+ } else {
545
+ Write-GcNotice 'deleted: nothing'
546
+ }
547
+ if ($removedEmpty.Count -gt 0) { Write-GcNotice "empty directories removed: $($removedEmpty.Count)" }
548
+ Write-GcNotice "freed $freed B across $($deleted.Count) item(s)"
549
+ } else {
550
+ if ($items -gt 0) {
551
+ Write-GcNotice 'would-delete (dry-run):'
552
+ foreach ($i in @($script:CleanWouldDelete | Sort-Object -Property Path)) {
553
+ Write-GcNotice (" {0,12:N0} B [{1}] {2}" -f $i.Size, $i.Class, $i.Path)
554
+ }
555
+ Write-GcNotice "would free $bytes B across $items item(s); -Force (only while --clean is armed) performs the deletion"
556
+ } else {
557
+ Write-GcNotice 'would-delete: none - sweep is clean'
558
+ }
559
+ }
560
+
561
+ if ($script:CleanReported.Count -gt 0) {
562
+ Write-GcNotice "reported - kept: $($script:CleanReported.Count) item(s) ($($script:CleanUnclassified) unclassified) - never deleted"
563
+ $limit = if ($Detailed) { $script:CleanReported.Count } else { [Math]::Min(20, $script:CleanReported.Count) }
564
+ $shown = 0
565
+ foreach ($r in @($script:CleanReported | Sort-Object -Property Path)) {
566
+ if ($shown -ge $limit) { break }
567
+ Write-GcNotice " reported - kept: $($r.Path) - $($r.Reason)"
568
+ $shown++
569
+ }
570
+ if ($shown -lt $script:CleanReported.Count) {
571
+ Write-GcNotice " ... $($script:CleanReported.Count - $shown) more item(s) - -Detailed lists all"
572
+ }
573
+ } else {
574
+ Write-GcNotice 'reported - kept: none'
575
+ }
576
+
577
+ if ($Detailed) {
578
+ foreach ($k in @($script:CleanKeepHits | Sort-Object -Property Path)) {
579
+ Write-GcNotice " kept [$($k.Kind)]: $($k.Path)"
580
+ }
581
+ }
582
+
583
+ # keep-list confirmation: the baseline keeps, checked after the sweep.
584
+ # PROTECT-IF-PRESENT: an absent keep is skipped with a note - never fatal.
585
+ $keepPresent = [System.Collections.Generic.List[string]]::new()
586
+ $keepAbsent = [System.Collections.Generic.List[string]]::new()
587
+ if ($PSScriptRoot) {
588
+ if (Test-Path -LiteralPath (Join-Path $PSScriptRoot 'gc-clean.ps1') -PathType Leaf) { $keepPresent.Add('this script') } else { $keepAbsent.Add('this script') }
589
+ if (Test-Path -LiteralPath (Join-Path $PSScriptRoot '..\reference') -PathType Container) { $keepPresent.Add('reference directory') } else { $keepAbsent.Add('reference directory') }
590
+ }
591
+ if ($script:CleanLiveCachePrefixes.Count -gt 0) {
592
+ $liveFound = 0
593
+ if ($cacheV2 -and (Test-Path -LiteralPath $cacheV2 -PathType Container)) {
594
+ $liveFound = @(Get-ChildItem -Force -LiteralPath $cacheV2 -Directory | Where-Object { Test-CleanLiveCache -Name $_.Name }).Count
595
+ }
596
+ if ($liveFound -ge $script:CleanLiveCachePrefixes.Count) {
597
+ $keepPresent.Add("live v2 cache entries $liveFound/$($script:CleanLiveCachePrefixes.Count)")
598
+ } else {
599
+ $keepAbsent.Add("live v2 cache entries ($liveFound/$($script:CleanLiveCachePrefixes.Count) present)")
600
+ }
601
+ }
602
+ $tgzCount = @($script:CleanKeepHits | Where-Object { $_.Kind -eq 'tgz' }).Count
603
+ if ($tgzCount -gt 0) { $keepPresent.Add("$tgzCount *.tgz pack(s)") }
604
+ if ($keepPresent.Count -gt 0) { Write-GcNotice "keep-list intact: $($keepPresent -join ', ')" }
605
+ if ($keepAbsent.Count -gt 0) { Write-GcWarn "keep-list item(s) not present - skipped, never fatal: $($keepAbsent -join ', ')" }
606
+
607
+ # repo-local untracked: listed only - this tool never deletes them
608
+ $untracked = @()
609
+ if ($RepoRoot -and (Test-Path -LiteralPath $RepoRoot)) {
610
+ $gitTop = $null
611
+ try { $gitTop = (Get-GcGit -Root $RepoRoot -Argv @('rev-parse', '--show-toplevel') | Select-Object -First 1).Trim() } catch { }
612
+ if ($gitTop) {
613
+ try { $untracked = @(Get-GcGit -Root $gitTop -Argv @('ls-files', '--others', '--exclude-standard')) }
614
+ catch { Write-GcWarn "untracked listing skipped: $($_.Exception.Message)" }
615
+ } else {
616
+ Write-GcInfo "RepoRoot is not a git work tree - no untracked listing ($RepoRoot)"
617
+ }
618
+ }
619
+ if ($untracked.Count -gt 0) {
620
+ if ($Force) {
621
+ # -Force ran: untracked files are listed dry-run only - here the
622
+ # count is awareness; the itemized listing belongs to the dry run
623
+ Write-GcNotice "repo-local untracked: $($untracked.Count) present - never deleted by this tool (dry-run listing only)"
624
+ } else {
625
+ Write-GcNotice "repo-local untracked (dry-run listing only - never deleted by this tool): $($untracked.Count)"
626
+ $show = if ($Detailed) { $untracked } else { @($untracked | Select-Object -First 10) }
627
+ foreach ($u in $show) { Write-GcNotice " [untracked] $u" }
628
+ if (-not $Detailed -and $untracked.Count -gt 10) {
629
+ Write-GcNotice " ... $($untracked.Count - 10) more (-Detailed lists all)"
630
+ }
631
+ }
632
+ }
633
+
634
+ if ($Force) {
635
+ if ($failures.Count -gt 0) {
636
+ foreach ($f in $failures) { Write-GcFail "deletion failed: $f" }
637
+ Write-GcResult -Code $script:GcExitFail -Props @{ mode = 'clean'; items = $deleted.Count; bytes = $freed; message = "$($failures.Count) deletion(s) failed" }
638
+ }
639
+ Write-GcResult -Props @{ mode = 'clean'; items = $deleted.Count; bytes = $freed }
640
+ }
641
+ Write-GcResult -Props @{ mode = 'dry-run'; items = $items; bytes = $bytes }
642
+ } catch [GcException] {
643
+ Write-GcFail $_.Exception.Message
644
+ Write-GcResult -Code $_.Exception.Code -Props @{ message = $_.Exception.Message }
645
+ } catch {
646
+ Write-GcFail "unexpected: $($_.Exception.Message)"
647
+ Write-GcResult -Code $script:GcExitFail -Props @{ message = $_.Exception.Message }
648
+ }