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.
- package/.docs/unwired-routing.md +14 -9
- package/.gitignore +14 -1
- package/AGENTS.md +70 -106
- package/README.md +27 -23
- package/agents/build.md +10 -12
- package/agents/explore.md +14 -8
- package/agents/general.md +7 -9
- package/agents/orchestrator.md +38 -0
- package/agents/plan.md +10 -13
- package/agents/reviewer.md +9 -14
- package/agents/vault.md +44 -35
- package/bin/cli.js +32 -3
- package/commands/build.md +2 -8
- package/commands/checkpoint.md +3 -1
- package/commands/code-simplify.md +3 -9
- package/commands/gauntlet.md +7 -0
- package/commands/handoff.md +3 -1
- package/commands/keeper.md +3 -3
- package/commands/kill.md +11 -0
- package/commands/plan.md +2 -13
- package/commands/retro.md +15 -0
- package/commands/review.md +1 -1
- package/commands/ship.md +3 -27
- package/commands/spec.md +3 -11
- package/commands/test.md +2 -9
- package/commands/webperf.md +7 -0
- package/opencode.jsonc +23 -8
- package/package.json +3 -3
- package/reference/README.md +14 -14
- package/reference/auto-mandate.md +11 -0
- package/reference/backup-convention.md +9 -0
- package/reference/clean-mandate.md +13 -0
- package/reference/editor-parity.md +7 -0
- package/reference/gc-scripts.md +8 -0
- package/reference/intent-routing.md +14 -0
- package/reference/lifecycle.md +15 -0
- package/reference/model-keeper.md +30 -10
- package/reference/model-test.md +11 -6
- package/reference/models.md +25 -14
- package/reference/oc-source-map.md +162 -0
- package/reference/owner-pin.md +31 -0
- package/reference/roster.md +15 -0
- package/reference/session-scope.md +9 -0
- package/reference/session-state.md +13 -0
- package/reference/swarm.md +32 -0
- package/scripts/backup-config.ps1 +42 -0
- package/scripts/gc-branch.ps1 +196 -0
- package/scripts/gc-bump.ps1 +198 -0
- package/scripts/gc-clean.ps1 +648 -0
- package/scripts/gc-commit.ps1 +143 -0
- package/scripts/gc-merge.ps1 +272 -0
- package/scripts/gc-pr.ps1 +190 -0
- package/scripts/gc-push.ps1 +111 -0
- package/scripts/gc-read.ps1 +150 -0
- package/scripts/gc-rebase.ps1 +162 -0
- package/scripts/gc-release.ps1 +225 -0
- package/scripts/gc-stage.ps1 +103 -0
- package/scripts/gc-status.ps1 +127 -0
- package/scripts/gc-sync.ps1 +65 -0
- package/scripts/gc.core.ps1 +715 -0
- package/scripts/gc.smoke.ps1 +779 -0
- package/scripts/harness-doctor.ps1 +11 -9
- package/scripts/interrupt-session.ps1 +65 -0
- package/scripts/logbook/README.md +108 -0
- package/scripts/logbook/logbook.test.ts +440 -0
- package/scripts/logbook/logbook.ts +797 -0
- package/scripts/pirep/README.md +147 -0
- package/scripts/pirep/pirep.test.ts +735 -0
- package/scripts/pirep/pirep.ts +836 -0
- package/scripts/testflight/README.md +112 -0
- package/scripts/testflight/testflight.test.ts +512 -0
- package/scripts/testflight/testflight.ts +806 -0
- package/skills/_shared/SOURCES.md +7 -7
- package/skills/_shared/references/definition-of-done.md +2 -2
- package/skills/_shared/references/orchestration-patterns.md +1 -2
- package/skills/_shared/references/security-checklist.md +2 -2
- package/skills/api-and-interface-design/SKILL.md +7 -360
- package/skills/browser-testing-with-devtools/SKILL.md +303 -0
- package/skills/code-simplification/SKILL.md +7 -364
- package/skills/creative-writing/SKILL.md +1 -1
- package/skills/debugging-and-error-recovery/SKILL.md +8 -309
- package/skills/flight-deck/SKILL.md +17 -0
- package/skills/frontend-ui-engineering/SKILL.md +8 -320
- package/skills/gauntlet/SKILL.md +21 -0
- package/skills/git-ceremony/SKILL.md +16 -318
- package/skills/grilling/SKILL.md +10 -30
- package/skills/observability-and-instrumentation/SKILL.md +9 -229
- package/skills/performance-optimization/SKILL.md +8 -488
- package/skills/pilot-report/SKILL.md +18 -0
- package/skills/planning-and-task-breakdown/SKILL.md +8 -249
- package/skills/security-and-hardening/SKILL.md +9 -490
- package/skills/source-driven-development/SKILL.md +8 -208
- package/skills/spec-driven-development/SKILL.md +15 -234
- package/skills/test-driven-development/SKILL.md +8 -388
- package/skills/test-flight/SKILL.md +14 -0
- package/skills/writing-for-agents/SKILL-MECHANICS.md +3 -3
- package/skills/writing-for-agents/SKILL.md +7 -1
- package/agents/coder.md +0 -19
- package/agents/documenter.md +0 -28
- package/agents/keeper.md +0 -22
- package/agents/master.md +0 -70
- package/agents/researcher.md +0 -21
- package/agents/security-auditor.md +0 -20
- package/agents/test-engineer.md +0 -20
- package/agents/web-performance-auditor.md +0 -19
- package/commands/council.md +0 -24
- package/commands/doctor.md +0 -19
- package/commands/ponytail-audit.md +0 -7
- package/commands/ponytail-debt.md +0 -14
- package/commands/report.md +0 -13
- package/scripts/harness-report.ps1 +0 -695
- package/scripts/panic/panic.ts +0 -240
- package/skills/code-review-and-quality/SKILL.md +0 -396
- package/skills/incremental-implementation/SKILL.md +0 -249
- package/skills/swarm-orchestration/SKILL.md +0 -54
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
#Requires -Version 7.0
|
|
2
|
+
<#
|
|
3
|
+
.SYNOPSIS
|
|
4
|
+
Shared core for the gc-* git-ceremony scripts (scripts\gc-*.ps1).
|
|
5
|
+
|
|
6
|
+
.DESCRIPTION
|
|
7
|
+
Dot-sourced by every gc-* script. Provides logging, the pinned git runner
|
|
8
|
+
(always `git -C <root>` — never the ambient cwd, per the worktree rails in
|
|
9
|
+
git-ceremony §10), ceremony validation, default-branch resolution, the secret
|
|
10
|
+
gate, and the RESULT line contract.
|
|
11
|
+
|
|
12
|
+
EXIT-CODE CONTRACT (stable API for agent callers):
|
|
13
|
+
0 success or clean no-op
|
|
14
|
+
1 generic failure (unexpected)
|
|
15
|
+
2 agent-fixable stop — needs agent action to proceed
|
|
16
|
+
(precondition violated, push rejected, conflict stop, merge refused)
|
|
17
|
+
3 dependency missing or unusable (git, gh)
|
|
18
|
+
4 security gate blocked a stage/commit (secret scan hit)
|
|
19
|
+
|
|
20
|
+
OUTPUT CONTRACT: every script prints exactly one final stdout line
|
|
21
|
+
RESULT: <json>
|
|
22
|
+
whatever the outcome (ok, exit code, message, per-script props). Under the
|
|
23
|
+
terse default that RESULT line is the ONLY line on stdout. -Detailed routes
|
|
24
|
+
the Write-Host narration through the console instead, but across a process
|
|
25
|
+
boundary that text is still captured by the caller (2>&1 sees it), so the real
|
|
26
|
+
guarantee is: take the LAST `RESULT: ` line out of the captured output. Quote
|
|
27
|
+
it, e.g.
|
|
28
|
+
$r = pwsh -NoProfile -File scripts\gc-commit.ps1 ... | Out-String
|
|
29
|
+
Write-GcFail and Write-GcNotice always print, in either mode.
|
|
30
|
+
|
|
31
|
+
TERSE LEVER: the default is TERSE — a run prints only the RESULT line plus
|
|
32
|
+
warnings, failures, and the security/remediation guidance. -Detailed restores
|
|
33
|
+
the step narration, the ok/info lines, and the raw git/gh relay; -Quiet is
|
|
34
|
+
accepted as a no-op for compatibility and wins if passed with -Detailed. The
|
|
35
|
+
RESULT line, the exit code, warnings, failures, and the secret-gate guidance
|
|
36
|
+
are never gated by either switch.
|
|
37
|
+
|
|
38
|
+
FLOW MAP (git-ceremony section → script; see reference/gc-scripts.md):
|
|
39
|
+
§1 pull / sync gc-sync.ps1
|
|
40
|
+
§2 branch lifecycle gc-branch.ps1 (create · -Reuse switch · -Delete)
|
|
41
|
+
§3 stage + commit gc-stage.ps1 · gc-commit.ps1
|
|
42
|
+
§4 push + PR gc-push.ps1 · gc-pr.ps1
|
|
43
|
+
§6 merge + cleanup gc-merge.ps1 (-Mode squash | merge | rebase)
|
|
44
|
+
status / where-am-i gc-status.ps1
|
|
45
|
+
rebase rail gc-rebase.ps1 (-Onto · -Continue · -Abort)
|
|
46
|
+
§8 version bump gc-bump.ps1 (-Major | -Minor | -Patch | -Set)
|
|
47
|
+
§9 release gc-release.ps1 (one entry · moving `latest` pointer)
|
|
48
|
+
Deliberately NOT scripted (prose; repo rules win): §5 review comments,
|
|
49
|
+
§7 tags (off by default), §10 worktrees (YAGNI-hold).
|
|
50
|
+
|
|
51
|
+
SECRET GATE
|
|
52
|
+
gc-stage and gc-commit block on a best-effort scan for obvious secret shapes:
|
|
53
|
+
private-key blocks, AWS AKIA keys, GitHub tokens, Slack tokens, sk- API
|
|
54
|
+
tokens, and key-ish filenames (.env*, *.pem, *.p12, *.pfx, *.key, id_*,
|
|
55
|
+
credentials). .env.example/.env.sample/.env.template are explicitly allowed.
|
|
56
|
+
The gate is defence in depth, NOT a guarantee — novel shapes can slip it, and
|
|
57
|
+
the staged-diff review stays the real last gate. On a hit the offending files
|
|
58
|
+
are left UNSTAGED (working-tree content untouched) and the script exits 4.
|
|
59
|
+
There is deliberately no bypass switch — the fix is to remove the secret.
|
|
60
|
+
|
|
61
|
+
.NOTES
|
|
62
|
+
git-ceremony precedence: a repo's own documented convention always wins; this
|
|
63
|
+
script set is the fallback ceremony. If the repo dictates its own rules, do
|
|
64
|
+
not force these scripts onto it.
|
|
65
|
+
Run every gc-* script via `pwsh -File <script>`; Write-GcResult exits the
|
|
66
|
+
process with the documented code, so interactive dot-sourcing of the core is
|
|
67
|
+
intentional and unsupported for the exit path.
|
|
68
|
+
#>
|
|
69
|
+
Set-StrictMode -Version Latest
|
|
70
|
+
$ErrorActionPreference = 'Stop'
|
|
71
|
+
|
|
72
|
+
# --- exit codes (documented contract, see .SYNOPSIS) -------------------------
|
|
73
|
+
$script:GcExitOk = 0
|
|
74
|
+
$script:GcExitFail = 1
|
|
75
|
+
$script:GcExitPre = 2 # precondition / ceremony invariant violated
|
|
76
|
+
$script:GcExitDep = 3 # dependency missing or unusable (git, gh)
|
|
77
|
+
$script:GcExitSecret = 4 # security gate blocked a stage/commit
|
|
78
|
+
|
|
79
|
+
$script:GcCeremonyTypes = @('feat','fix','chore','docs','refactor','test','perf','hotfix','wt')
|
|
80
|
+
|
|
81
|
+
class GcException : System.Exception {
|
|
82
|
+
[int]$Code
|
|
83
|
+
GcException([string]$Message, [int]$Code) : base($Message) { $this.Code = $Code }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
# --- logging (console only; stdout is reserved for the RESULT line) ----------
|
|
87
|
+
# TERSE BY DEFAULT: $script:GcQuiet starts $true, so a bare invocation prints
|
|
88
|
+
# only the RESULT line. -Detailed sets it $false (restores the pre-lever
|
|
89
|
+
# chatter); -Quiet forces it $true and so wins when both are passed.
|
|
90
|
+
# ALWAYS VISIBLE, never gated: the RESULT line (stdout), Write-GcFail,
|
|
91
|
+
# Write-GcWarn (decision cues — merge/rebase/push warnings are the reason the
|
|
92
|
+
# old docs said not to quiet those verbs), and Write-GcNotice (remediation /
|
|
93
|
+
# security guidance). GATED by $script:GcQuiet: Write-GcInfo / Write-GcOk
|
|
94
|
+
# narration and the raw git/gh relay (Write-GcNote).
|
|
95
|
+
$script:GcQuiet = $true
|
|
96
|
+
function Write-GcInfo { param([string]$Message) if (-not $script:GcQuiet) { Write-Host "[gc] $Message" -ForegroundColor Cyan } }
|
|
97
|
+
function Write-GcOk { param([string]$Message) if (-not $script:GcQuiet) { Write-Host "[gc] ok: $Message" -ForegroundColor Green } }
|
|
98
|
+
function Write-GcWarn { param([string]$Message) Write-Host "[gc] warn: $Message" -ForegroundColor Yellow }
|
|
99
|
+
function Write-GcFail { param([string]$Message) Write-Host "[gc] FAIL: $Message" -ForegroundColor Red }
|
|
100
|
+
function Write-GcNotice {
|
|
101
|
+
<# ungated console print for actionable/security guidance (remediation,
|
|
102
|
+
offender handling, next steps) that must survive the terse default. #>
|
|
103
|
+
param([string]$Message)
|
|
104
|
+
Write-Host "[gc] $Message" -ForegroundColor White
|
|
105
|
+
}
|
|
106
|
+
function Write-GcNote {
|
|
107
|
+
<# gated console print for raw chatter (git/gh relay lines, diff stats);
|
|
108
|
+
the single biggest noise emitter is the git/gh output relay. #>
|
|
109
|
+
param([string]$Text, [System.Nullable[ConsoleColor]]$ForegroundColor = $null)
|
|
110
|
+
if (-not $script:GcQuiet) {
|
|
111
|
+
if ($null -ne $ForegroundColor) { Write-Host $Text -ForegroundColor $ForegroundColor }
|
|
112
|
+
else { Write-Host $Text }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
# --- pinned git runner --------------------------------------------------------
|
|
117
|
+
function Invoke-GcGit {
|
|
118
|
+
<# git pinned to the repo root; throws GcException on non-zero exit.
|
|
119
|
+
Output relays to the console only — script stdout stays reserved for the
|
|
120
|
+
RESULT line. Use Get-GcGit when you need the output. Every invocation is
|
|
121
|
+
a mutation, so it drops the cached repo state. #>
|
|
122
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string[]]$Argv)
|
|
123
|
+
Clear-GcRepoState
|
|
124
|
+
$out = & git -C $Root @Argv 2>&1
|
|
125
|
+
if ($LASTEXITCODE -ne 0) {
|
|
126
|
+
throw [GcException]::new("git $($Argv[0]) exited $($LASTEXITCODE): " + (($out | Out-String).Trim()), $script:GcExitFail)
|
|
127
|
+
}
|
|
128
|
+
foreach ($line in @($out)) { if ($line) { Write-GcNote " $line" -ForegroundColor DarkGray } }
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function Get-GcGit {
|
|
133
|
+
<# like Invoke-GcGit but returns stdout as clean string lines, for parsing.
|
|
134
|
+
Single-line native output wraps to a 1-element array (a bare string must
|
|
135
|
+
never be piped — PowerShell would enumerate its characters). #>
|
|
136
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string[]]$Argv)
|
|
137
|
+
$out = & git -C $Root @Argv 2>$null
|
|
138
|
+
if ($LASTEXITCODE -ne 0) {
|
|
139
|
+
throw [GcException]::new("git $($Argv[0]) exited $($LASTEXITCODE)", $script:GcExitFail)
|
|
140
|
+
}
|
|
141
|
+
if ($null -eq $out) { return @() }
|
|
142
|
+
return @($out)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function Resolve-GcRoot {
|
|
146
|
+
<# the repository root for a path; Pre failure (exit 2) with the fix when
|
|
147
|
+
not inside a repo — contract: precondition violations are agent-fixable. #>
|
|
148
|
+
param([string]$Path = (Get-Location).Path)
|
|
149
|
+
$top = & git -C $Path rev-parse --show-toplevel 2>$null
|
|
150
|
+
if ($LASTEXITCODE -ne 0 -or -not $top) {
|
|
151
|
+
throw [GcException]::new("not inside a git working tree: $Path — cd into a repository or pass -RepoRoot", $script:GcExitPre)
|
|
152
|
+
}
|
|
153
|
+
return (@($top)[0]).Trim()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
# --- repo state: one porcelain v2 call per mutation window --------------------
|
|
157
|
+
# The verbs used to ask separate git calls for branch (rev-parse), cleanliness
|
|
158
|
+
# (status --porcelain), staged names (diff --cached) and, in gc-status,
|
|
159
|
+
# ahead/behind (two rev-list). One `status --porcelain=v2 --branch -z` (37 ms)
|
|
160
|
+
# answers all of them; the result is cached per repo root and dropped by every
|
|
161
|
+
# mutation (Invoke-GcGit), so a verb shares one call and never reads stale state.
|
|
162
|
+
$script:GcRepoStateCache = @{}
|
|
163
|
+
function Clear-GcRepoState { $script:GcRepoStateCache = @{} }
|
|
164
|
+
|
|
165
|
+
function Get-GcRepoState {
|
|
166
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
167
|
+
if ($script:GcRepoStateCache.ContainsKey($Root)) { return $script:GcRepoStateCache[$Root] }
|
|
168
|
+
$out = & git -C $Root status --porcelain=v2 --branch -z 2>$null
|
|
169
|
+
if ($LASTEXITCODE -ne 0) {
|
|
170
|
+
throw [GcException]::new("git status exited $LASTEXITCODE (not a git working tree: $Root)", $script:GcExitFail)
|
|
171
|
+
}
|
|
172
|
+
$text = if ($null -eq $out) { '' } else { (@($out) -join "`n") }
|
|
173
|
+
$tokens = @($text.Split([char]0) | Where-Object { $_ -ne '' })
|
|
174
|
+
|
|
175
|
+
$branch = $null; $detached = $false; $unborn = $false
|
|
176
|
+
$upstream = $null; $ahead = $null; $behind = $null
|
|
177
|
+
$staged = [System.Collections.Generic.List[string]]::new()
|
|
178
|
+
$stagedDeleted = [System.Collections.Generic.List[string]]::new()
|
|
179
|
+
$untracked = 0; $unstaged = 0; $conflicts = 0; $dirty = $false
|
|
180
|
+
$unmergedSet = @('AA','DD','UU','AU','UA','DU','UD')
|
|
181
|
+
$skipNext = $false
|
|
182
|
+
|
|
183
|
+
for ($i = 0; $i -lt $tokens.Count; $i++) {
|
|
184
|
+
$t = $tokens[$i]
|
|
185
|
+
switch ($t[0]) {
|
|
186
|
+
'#' {
|
|
187
|
+
if ($t -match '^# branch\.oid (.+)$') { $unborn = ($Matches[1] -ceq '(initial)') }
|
|
188
|
+
elseif ($t -match '^# branch\.head (.+)$') {
|
|
189
|
+
if ($Matches[1] -ceq '(detached)') { $detached = $true } else { $branch = $Matches[1] }
|
|
190
|
+
}
|
|
191
|
+
elseif ($t -match '^# branch\.upstream (.+)$') { $upstream = $Matches[1] }
|
|
192
|
+
elseif ($t -match '^# branch\.ab \+(\d+) -(\d+)$') { $ahead = [int]$Matches[1]; $behind = [int]$Matches[2] }
|
|
193
|
+
}
|
|
194
|
+
'?' { $untracked++; $dirty = $true }
|
|
195
|
+
'1' {
|
|
196
|
+
# 1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path> — remainder is the path
|
|
197
|
+
$p = $t -split ' ', 9
|
|
198
|
+
$dirty = $true
|
|
199
|
+
if ($p[1][0] -cne '.') {
|
|
200
|
+
$staged.Add($p[8])
|
|
201
|
+
if ($p[1][0] -ceq 'D' -and $p[1][1] -ceq '.') { $stagedDeleted.Add($p[8]) }
|
|
202
|
+
}
|
|
203
|
+
if ($p[1][1] -cne '.') { $unstaged++ }
|
|
204
|
+
}
|
|
205
|
+
'2' {
|
|
206
|
+
# 2 <XY> ... <X><score> <path>, then the ORIGINAL path as the next
|
|
207
|
+
# NUL token — consume it, keep the new path (matches diff --cached)
|
|
208
|
+
$p = $t -split ' ', 10
|
|
209
|
+
$dirty = $true
|
|
210
|
+
if ($p[1][0] -cne '.') {
|
|
211
|
+
$staged.Add($p[9])
|
|
212
|
+
if ($p[1][0] -ceq 'D' -and $p[1][1] -ceq '.') { $stagedDeleted.Add($p[9]) }
|
|
213
|
+
}
|
|
214
|
+
if ($p[1][1] -cne '.') { $unstaged++ }
|
|
215
|
+
$skipNext = $true
|
|
216
|
+
}
|
|
217
|
+
'u' {
|
|
218
|
+
# u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>
|
|
219
|
+
$p = $t -split ' ', 11
|
|
220
|
+
$dirty = $true
|
|
221
|
+
$staged.Add($p[10]) # diff --cached --name-only lists unmerged paths
|
|
222
|
+
if ($unmergedSet -ccontains $p[1]) { $conflicts++ }
|
|
223
|
+
if ($p[1][1] -cne '.') { $unstaged++ }
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if ($skipNext) { $i++; $skipNext = $false }
|
|
227
|
+
}
|
|
228
|
+
$state = [pscustomobject]@{
|
|
229
|
+
Branch = $branch
|
|
230
|
+
Detached = $detached
|
|
231
|
+
Unborn = $unborn
|
|
232
|
+
Upstream = $upstream
|
|
233
|
+
Ahead = $ahead
|
|
234
|
+
Behind = $behind
|
|
235
|
+
Clean = (-not $dirty)
|
|
236
|
+
Staged = $staged.ToArray()
|
|
237
|
+
StagedDeleted = $stagedDeleted.ToArray()
|
|
238
|
+
Unstaged = $unstaged
|
|
239
|
+
Conflicts = $conflicts
|
|
240
|
+
Untracked = $untracked
|
|
241
|
+
}
|
|
242
|
+
$script:GcRepoStateCache[$Root] = $state
|
|
243
|
+
return $state
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function Get-GcCurrentBranch {
|
|
247
|
+
<#
|
|
248
|
+
The current branch. Two paths, identical contract and failure modes:
|
|
249
|
+
- default: from the cached repo state (shares one porcelain walk with the
|
|
250
|
+
other facts the verb needs).
|
|
251
|
+
- -Targeted: one `rev-parse --abbrev-ref HEAD`, no worktree walk. For a
|
|
252
|
+
verb that needs the branch and NOTHING else, the state walk costs tens
|
|
253
|
+
of ms and grows with the worktree size; rev-parse is flat (~36 ms).
|
|
254
|
+
#>
|
|
255
|
+
param([Parameter(Mandatory)][string]$Root, [switch]$Targeted)
|
|
256
|
+
if ($Targeted) {
|
|
257
|
+
try {
|
|
258
|
+
$b = (Get-GcGit -Root $Root -Argv @('rev-parse','--abbrev-ref','HEAD') | Select-Object -First 1).Trim()
|
|
259
|
+
} catch {
|
|
260
|
+
# rev-parse --abbrev-ref HEAD exits 128 on an unborn HEAD ('ambiguous
|
|
261
|
+
# argument HEAD'); keep the state path's failure mode.
|
|
262
|
+
throw [GcException]::new('HEAD is unborn (no commits yet)', $script:GcExitFail)
|
|
263
|
+
}
|
|
264
|
+
if ($b -ceq 'HEAD') { throw [GcException]::new('HEAD is detached — switch to a branch first', $script:GcExitPre) }
|
|
265
|
+
return $b
|
|
266
|
+
}
|
|
267
|
+
$st = Get-GcRepoState -Root $Root
|
|
268
|
+
if ($st.Detached) { throw [GcException]::new('HEAD is detached — switch to a branch first', $script:GcExitPre) }
|
|
269
|
+
if ($st.Unborn) {
|
|
270
|
+
# rev-parse --abbrev-ref HEAD fails on an unborn HEAD; keep that failure
|
|
271
|
+
# mode (generic exit) rather than reporting the unborn branch name.
|
|
272
|
+
throw [GcException]::new('HEAD is unborn (no commits yet)', $script:GcExitFail)
|
|
273
|
+
}
|
|
274
|
+
return $st.Branch
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function Test-GcRef {
|
|
278
|
+
<# $true when the ref exists. #>
|
|
279
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string]$Ref)
|
|
280
|
+
try { Get-GcGit -Root $Root -Argv @('rev-parse','--verify','--quiet',$Ref) | Out-Null; return $true }
|
|
281
|
+
catch { return $false }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function Get-GcConfig {
|
|
285
|
+
<# git config value, '' when unset (config lookup failures are not errors). #>
|
|
286
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string]$Key)
|
|
287
|
+
try { return ((Get-GcGit -Root $Root -Argv @('config',$Key) | Select-Object -First 1).Trim()) }
|
|
288
|
+
catch { return '' }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function Get-GcDefaultBranch {
|
|
292
|
+
<#
|
|
293
|
+
Resolve the default branch name, ceremony precedence (§1):
|
|
294
|
+
1. selected remote HEAD symref (origin, otherwise the sole remote)
|
|
295
|
+
2. init.defaultBranch config
|
|
296
|
+
3. an existing refs/heads/main or refs/heads/master
|
|
297
|
+
4. 'main' (name only — fine for unborn repos; creation validates later)
|
|
298
|
+
Never hits the network.
|
|
299
|
+
#>
|
|
300
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
301
|
+
$remotes = @(Get-GcGit -Root $Root -Argv @('remote') | ForEach-Object { $_.Trim() })
|
|
302
|
+
$remote = if ($remotes -contains 'origin') { 'origin' } elseif ($remotes.Count -eq 1) { $remotes[0] } else { $null }
|
|
303
|
+
if ($remote) {
|
|
304
|
+
try {
|
|
305
|
+
$sym = (Get-GcGit -Root $Root -Argv @('symbolic-ref','--quiet',"refs/remotes/$remote/HEAD") |
|
|
306
|
+
Select-Object -First 1).Trim()
|
|
307
|
+
if ($sym -match ("^refs/remotes/" + [regex]::Escape($remote) + "/(.+)$")) { return $Matches[1] }
|
|
308
|
+
} catch { } # remote HEAD unset — fall through
|
|
309
|
+
}
|
|
310
|
+
$name = Get-GcConfig -Root $Root -Key 'init.defaultBranch'
|
|
311
|
+
if (-not $name) { $name = 'main' }
|
|
312
|
+
foreach ($cand in @($name,'main','master')) {
|
|
313
|
+
if (Test-GcRef -Root $Root -Ref "refs/heads/$cand") { return $cand }
|
|
314
|
+
}
|
|
315
|
+
return $name
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function Get-GcRemote {
|
|
319
|
+
<# origin if present, else the sole remote; Pre failure otherwise. #>
|
|
320
|
+
param([Parameter(Mandatory)][string]$Root, [string]$Preferred = 'origin')
|
|
321
|
+
$r = @(Get-GcGit -Root $Root -Argv @('remote') | ForEach-Object { $_.Trim() })
|
|
322
|
+
if ($Preferred -and $r -contains $Preferred) { return $Preferred }
|
|
323
|
+
if ($r.Count -eq 1) { return $r[0] }
|
|
324
|
+
if ($r.Count -eq 0) { throw [GcException]::new('no git remote configured — gc-pr / gc-push need one', $script:GcExitPre) }
|
|
325
|
+
throw [GcException]::new("multiple remotes ($($r -join ', ')) and no origin — pass -Remote explicitly", $script:GcExitPre)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function Test-GcCleanTree {
|
|
329
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
330
|
+
return (Get-GcRepoState -Root $Root).Clean
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function Test-GcRebaseInProgress {
|
|
334
|
+
<# $true when a rebase is stopped (conflict or paused) — .git/rebase-merge
|
|
335
|
+
or .git/rebase-apply exists. Shared by gc-rebase and gc-status. #>
|
|
336
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
337
|
+
foreach ($state in @('rebase-merge','rebase-apply')) {
|
|
338
|
+
try {
|
|
339
|
+
$p = (Get-GcGit -Root $Root -Argv @('rev-parse','--git-path',$state) | Select-Object -First 1).Trim()
|
|
340
|
+
if ($p) {
|
|
341
|
+
$abs = if ([System.IO.Path]::IsPathRooted($p)) { $p } else { Join-Path $Root $p }
|
|
342
|
+
if (Test-Path -LiteralPath $abs) { return $true }
|
|
343
|
+
}
|
|
344
|
+
} catch { }
|
|
345
|
+
}
|
|
346
|
+
return $false
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function Assert-GcRefValue {
|
|
350
|
+
<# ref-shaped user input, e.g. -Onto / -Branch / base: rejects a leading
|
|
351
|
+
dash (git option injection — gc-rebase -Onto '--exec=...' executes
|
|
352
|
+
commands), edge whitespace, and characters no ref can contain.
|
|
353
|
+
Boundary: ref names are ASCII-only in this toolset ([A-Za-z0-9._/-@~^]
|
|
354
|
+
plus rev-syntax braces for @{upstream}); ':' and '*' are rejected. #>
|
|
355
|
+
param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][string]$Value)
|
|
356
|
+
$invalid = $Value -cmatch '^-' -or $Value -match '^\s' -or $Value -match '\s$' -or
|
|
357
|
+
$Value -cnotmatch '^[A-Za-z0-9._/@~^{}-]+$'
|
|
358
|
+
if ($invalid) {
|
|
359
|
+
throw [GcException]::new("$Name '$Value' is not a valid ref — no leading dash, no edge whitespace, ASCII ref characters only", $script:GcExitPre)
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function Format-GcPrBody {
|
|
364
|
+
<# the §4 PR body, exactly: What / Why (omitted when empty) / Check / Risk,
|
|
365
|
+
one line each. Pure renderer — pinned by the smoke without gh. #>
|
|
366
|
+
param([Parameter(Mandatory)][string]$What, [string]$Why, [string]$Check, [string]$Risk)
|
|
367
|
+
$bodyLines = @("What: $What")
|
|
368
|
+
if ($Why) { $bodyLines += "Why: $Why" }
|
|
369
|
+
$bodyLines += @("Check: $(if ($Check) { $Check } else { 'n/a' })", "Risk: $(if ($Risk) { $Risk } else { 'low' })")
|
|
370
|
+
return ($bodyLines -join "`n")
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function Convert-GcMergeMode {
|
|
374
|
+
<# §6 merge method → the gh flag. Pure mapping — pinned without gh. #>
|
|
375
|
+
param([Parameter(Mandatory)][ValidateSet('squash','merge','rebase')][string]$Mode)
|
|
376
|
+
return $(switch ($Mode) { 'squash' { '--squash' } 'merge' { '--merge' } 'rebase' { '--rebase' } })
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function Get-GcMergedMethod {
|
|
380
|
+
<# truthful merge-method label for an ALREADY-merged PR, read from the
|
|
381
|
+
merge commit's own subject (gh's mergeCommit field carries no message).
|
|
382
|
+
'merge' = "Merge pull request #N from …" · 'squash' = "title (#N)" ·
|
|
383
|
+
'rebase' = the original subject · 'unknown' when the commit is absent. #>
|
|
384
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string]$Sha)
|
|
385
|
+
if (-not $Sha) { return 'unknown' }
|
|
386
|
+
try {
|
|
387
|
+
$msg = (Get-GcGit -Root $Root -Argv @('log','-1','--format=%s',$Sha) | Select-Object -First 1).Trim()
|
|
388
|
+
if ($msg -match '^Merge pull request') { return 'merge' }
|
|
389
|
+
if ($msg -match '#[0-9]+\)\s*$') { return 'squash' }
|
|
390
|
+
return 'rebase'
|
|
391
|
+
} catch { return 'unknown' }
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
# --- release renderers (§9) ---------------------------------------------------
|
|
395
|
+
function Get-GcChangelogSection {
|
|
396
|
+
<#
|
|
397
|
+
§9: the release body is rendered from the changelog. Locate the section for a
|
|
398
|
+
version — a `## <version>` heading (trailing text such as a date allowed)
|
|
399
|
+
up to the next `## ` heading — and return its lines WITHOUT the heading,
|
|
400
|
+
blank-trimmed. Pre failure (exit 2) when CHANGELOG.md or the section is
|
|
401
|
+
missing: the entry body is never hand-written (one source of truth, §8).
|
|
402
|
+
#>
|
|
403
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string]$Version)
|
|
404
|
+
$abs = Join-Path $Root 'CHANGELOG.md'
|
|
405
|
+
if (-not (Test-Path -LiteralPath $abs)) {
|
|
406
|
+
throw [GcException]::new('CHANGELOG.md not found — §9 renders the release body from the changelog; add it first', $script:GcExitPre)
|
|
407
|
+
}
|
|
408
|
+
$escaped = [regex]::Escape($Version)
|
|
409
|
+
$section = [System.Collections.Generic.List[string]]::new()
|
|
410
|
+
$found = $false
|
|
411
|
+
foreach ($line in @(Get-Content -LiteralPath $abs)) {
|
|
412
|
+
if (-not $found) {
|
|
413
|
+
if ($line -match "^##\s+$escaped(\s|$)") { $found = $true }
|
|
414
|
+
continue
|
|
415
|
+
}
|
|
416
|
+
if ($line -match '^##\s') { break }
|
|
417
|
+
$section.Add($line)
|
|
418
|
+
}
|
|
419
|
+
if (-not $found) {
|
|
420
|
+
throw [GcException]::new("CHANGELOG.md has no section for version '$Version' — the release body is rendered from the changelog (§8 one source of truth); add the section first", $script:GcExitPre)
|
|
421
|
+
}
|
|
422
|
+
while ($section.Count -gt 0 -and -not $section[0].Trim()) { $section.RemoveAt(0) }
|
|
423
|
+
while ($section.Count -gt 0 -and -not $section[$section.Count - 1].Trim()) { $section.RemoveAt($section.Count - 1) }
|
|
424
|
+
$section.ToArray()
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function Format-GcReleaseBody {
|
|
428
|
+
<# §9 body: the Version line — rendered from the manifest, never hand-edited
|
|
429
|
+
— plus the changelog section verbatim. Pure renderer; pinned by the smoke
|
|
430
|
+
without gh or npm. #>
|
|
431
|
+
param([Parameter(Mandatory)][string]$Version, [string[]]$Lines)
|
|
432
|
+
$parts = [System.Collections.Generic.List[string]]::new()
|
|
433
|
+
$parts.Add("Version: $Version")
|
|
434
|
+
$parts.Add('')
|
|
435
|
+
if ($Lines) { foreach ($l in $Lines) { $parts.Add($l) } }
|
|
436
|
+
return ($parts -join "`n")
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function Get-GcStagedNames {
|
|
440
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
441
|
+
return (Get-GcRepoState -Root $Root).Staged
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function Sync-GcDefaultBranch {
|
|
445
|
+
<#
|
|
446
|
+
Ceremony §1: fetch the selected remote, then fast-forward the local default branch.
|
|
447
|
+
Never manufactures a merge. Pre failure when the tree is dirty and a
|
|
448
|
+
switch is needed, when the branch diverged, or when the default branch is
|
|
449
|
+
not a fast-forward of its remote head.
|
|
450
|
+
#>
|
|
451
|
+
param(
|
|
452
|
+
[Parameter(Mandatory)][string]$Root,
|
|
453
|
+
[Parameter(Mandatory)][string]$Default,
|
|
454
|
+
[string]$CurrentBranch
|
|
455
|
+
)
|
|
456
|
+
$remotes = @(Get-GcGit -Root $Root -Argv @('remote') | ForEach-Object { $_.Trim() })
|
|
457
|
+
if ($remotes.Count -eq 0) {
|
|
458
|
+
Write-GcInfo 'no remote — skipping fetch (local-only repo)'
|
|
459
|
+
return 'skipped-local'
|
|
460
|
+
}
|
|
461
|
+
$remote = Get-GcRemote -Root $Root
|
|
462
|
+
Invoke-GcGit -Root $Root -Argv @('fetch','--prune',$remote)
|
|
463
|
+
if (-not (Test-GcRef -Root $Root -Ref "refs/remotes/$remote/$Default")) {
|
|
464
|
+
Write-GcInfo "$remote/$Default has no remote head yet — nothing to fast-forward"
|
|
465
|
+
return 'skipped-no-remote-head'
|
|
466
|
+
}
|
|
467
|
+
$localExists = Test-GcRef -Root $Root -Ref "refs/heads/$Default"
|
|
468
|
+
if (-not $localExists) {
|
|
469
|
+
# no local default yet: switch DWIM-creates the tracking branch from
|
|
470
|
+
# <remote>/<default> — no merge involved, so always safe.
|
|
471
|
+
Invoke-GcGit -Root $Root -Argv @('switch',$Default)
|
|
472
|
+
Write-GcOk "created local $Default tracking $remote/$Default"
|
|
473
|
+
return 'created'
|
|
474
|
+
}
|
|
475
|
+
$localAhead = [int](Get-GcGit -Root $Root -Argv @('rev-list','--count',"$remote/$Default..$Default"))
|
|
476
|
+
$localBehind = [int](Get-GcGit -Root $Root -Argv @('rev-list','--count',"$Default..$remote/$Default"))
|
|
477
|
+
if ($localAhead -eq 0 -and $localBehind -eq 0) { Write-GcInfo 'default branch up to date'; return 'up-to-date' }
|
|
478
|
+
if ($localAhead -gt 0 -and $localBehind -gt 0) {
|
|
479
|
+
throw [GcException]::new("default branch diverged from $remote/$Default ($localAhead ahead / $localBehind behind) — stop; resolve by hand, never manufacture a merge here", $script:GcExitPre)
|
|
480
|
+
}
|
|
481
|
+
if ($localAhead -gt 0) {
|
|
482
|
+
Write-GcInfo "local $Default is $localAhead commit(s) ahead of $remote — keeping local"
|
|
483
|
+
return 'local-ahead'
|
|
484
|
+
}
|
|
485
|
+
# local behind: fast-forward only.
|
|
486
|
+
if (-not (Test-GcCleanTree -Root $Root)) {
|
|
487
|
+
throw [GcException]::new("$Default is $localBehind commit(s) behind $remote/$Default but the tree is dirty — commit or stash first, then re-run", $script:GcExitPre)
|
|
488
|
+
}
|
|
489
|
+
if ($CurrentBranch -ne $Default) { Invoke-GcGit -Root $Root -Argv @('switch',$Default) }
|
|
490
|
+
Invoke-GcGit -Root $Root -Argv @('merge','--ff-only',"$remote/$Default")
|
|
491
|
+
Write-GcOk "$Default fast-forwarded to $remote/$Default"
|
|
492
|
+
return 'fast-forwarded'
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
# --- ceremony validation ------------------------------------------------------
|
|
496
|
+
function Test-GcBranchName {
|
|
497
|
+
<# validates `<type>/<slug>` per git-ceremony §2; prints why on failure.
|
|
498
|
+
PowerShell -match/-contains are case-insensitive, so the ceremony checks
|
|
499
|
+
must be case-sensitive (-cmatch / -cnotcontains). #>
|
|
500
|
+
param([Parameter(Mandatory)][string]$Branch)
|
|
501
|
+
$parts = $Branch -split '/', 2
|
|
502
|
+
if ($parts.Count -ne 2) {
|
|
503
|
+
Write-GcFail "branch '$Branch' must be <type>/<slug> — e.g. feat/token-refresh"
|
|
504
|
+
return $false
|
|
505
|
+
}
|
|
506
|
+
if ($script:GcCeremonyTypes -cnotcontains $parts[0]) {
|
|
507
|
+
Write-GcFail "type '$($parts[0])' not in ceremony set: $($script:GcCeremonyTypes -join ', ')"
|
|
508
|
+
return $false
|
|
509
|
+
}
|
|
510
|
+
if ($parts[1] -cnotmatch '^[a-z0-9]+(-[a-z0-9]+){1,4}$') {
|
|
511
|
+
Write-GcFail "slug '$($parts[1])' must be 2-5 kebab-case words, lowercase letters/digits only, no author/date — e.g. login-timeout-4821"
|
|
512
|
+
return $false
|
|
513
|
+
}
|
|
514
|
+
return $true
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function Get-GcSubjectParts {
|
|
518
|
+
<#
|
|
519
|
+
Validates a full commit subject per git-ceremony §3:
|
|
520
|
+
`type(scope): imperative summary` ≤72 chars, no trailing period, lowercase
|
|
521
|
+
start. Returns type/scope/summary. Pre failure with the fix in the message.
|
|
522
|
+
#>
|
|
523
|
+
param([Parameter(Mandatory)][string]$Subject)
|
|
524
|
+
if ($Subject.Length -gt 72) {
|
|
525
|
+
throw [GcException]::new("subject is $($Subject.Length) chars — ceremony caps it at 72", $script:GcExitPre)
|
|
526
|
+
}
|
|
527
|
+
if ($Subject -cmatch '\.\s*$') {
|
|
528
|
+
throw [GcException]::new("subject must not end with a period", $script:GcExitPre)
|
|
529
|
+
}
|
|
530
|
+
if ($Subject -cnotmatch '^([a-z]+)(\(([a-z0-9-]+)\))?: (.+)$') {
|
|
531
|
+
throw [GcException]::new("subject must match: type(scope): summary — e.g. 'fix(api): cap retry backoff at 30s'", $script:GcExitPre)
|
|
532
|
+
}
|
|
533
|
+
$type = $Matches[1]
|
|
534
|
+
$scope = if ($Matches.ContainsKey(3)) { $Matches[3] } else { $null }
|
|
535
|
+
$summary = $Matches[4]
|
|
536
|
+
if ($script:GcCeremonyTypes -notcontains $type) {
|
|
537
|
+
throw [GcException]::new("type '$type' not in ceremony set: $($script:GcCeremonyTypes -join ', ')", $script:GcExitPre)
|
|
538
|
+
}
|
|
539
|
+
if ($summary -cnotmatch '^[a-z0-9]') {
|
|
540
|
+
throw [GcException]::new("summary must start lowercase (imperative: 'add', 'cap', 'fix')", $script:GcExitPre)
|
|
541
|
+
}
|
|
542
|
+
return [pscustomobject]@{ Type = $type; Scope = $scope; Summary = $summary }
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function Assert-GcIdentity {
|
|
546
|
+
<# git user.name + user.email must exist; Pre failure with the fix. #>
|
|
547
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
548
|
+
$n = Get-GcConfig -Root $Root -Key 'user.name'
|
|
549
|
+
$e = Get-GcConfig -Root $Root -Key 'user.email'
|
|
550
|
+
if (-not $n -or -not $e) {
|
|
551
|
+
throw [GcException]::new('git identity not set — run once per repo: git config user.name "You" ; git config user.email "you@host"', $script:GcExitPre)
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
# --- gh ----------------------------------------------------------------------
|
|
556
|
+
function Assert-GcGh {
|
|
557
|
+
<# gh present. Authentication is deliberately NOT probed: `gh auth status`
|
|
558
|
+
costs ~0.5 s on every gh verb and the first real call is the probe —
|
|
559
|
+
Convert-GcGhError maps its not-logged-in failure back to the dependency
|
|
560
|
+
exit, so the documented exit-3 contract is preserved without the wait. #>
|
|
561
|
+
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
|
|
562
|
+
throw [GcException]::new('gh (GitHub CLI) is not installed or not on PATH', $script:GcExitDep)
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
$script:GcGhAuthRe = 'gh auth login|not logged in|authentication required|HTTP 401'
|
|
567
|
+
|
|
568
|
+
function Convert-GcGhError {
|
|
569
|
+
<# gh's own failure message → GcException (always throws). A not-logged-in
|
|
570
|
+
failure keeps the documented dependency exit (3) and the actionable login
|
|
571
|
+
text; any other failure stays generic (1). Replaces the deleted probe. #>
|
|
572
|
+
param([Parameter(Mandatory)][string]$Verb, [Parameter(Mandatory)][int]$Code, [string]$Text)
|
|
573
|
+
if ($Text -match $script:GcGhAuthRe) {
|
|
574
|
+
throw [GcException]::new('gh is not authenticated — run `gh auth login` once, human', $script:GcExitDep)
|
|
575
|
+
}
|
|
576
|
+
throw [GcException]::new("gh $Verb exited $Code`: " + $Text.Trim(), $script:GcExitFail)
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function Invoke-GcGhCapture {
|
|
580
|
+
<# Run gh from the repo root and return its stdout, its error text and its
|
|
581
|
+
exit code, without throwing. `gh @Argv 2>&1` catches a native gh's
|
|
582
|
+
stderr, but a wrapper/script gh writing to the process error stream
|
|
583
|
+
([Console]::Error) bypasses PowerShell's 2>&1 — swapping Console.Error
|
|
584
|
+
around the call catches that too, so a failure's own message (e.g.
|
|
585
|
+
"please run: gh auth login") always reaches Convert-GcGhError. #>
|
|
586
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string[]]$Argv)
|
|
587
|
+
Push-Location $Root
|
|
588
|
+
try {
|
|
589
|
+
$prevErr = [Console]::Error
|
|
590
|
+
$errBuf = [System.IO.StringWriter]::new()
|
|
591
|
+
$out = $null; $code = 0
|
|
592
|
+
try {
|
|
593
|
+
[Console]::SetError($errBuf)
|
|
594
|
+
$out = & gh @Argv 2>&1
|
|
595
|
+
$code = $LASTEXITCODE
|
|
596
|
+
} finally { [Console]::SetError($prevErr) }
|
|
597
|
+
} finally { Pop-Location }
|
|
598
|
+
$text = if ($null -eq $out) { '' } else { (@($out) -join "`n") }
|
|
599
|
+
$err = $errBuf.ToString()
|
|
600
|
+
if ($err) { $text = if ($text) { "$text`n$err".Trim() } else { $err.Trim() } }
|
|
601
|
+
return [pscustomobject]@{ Code = $code; Text = $text }
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function Invoke-GcGh {
|
|
605
|
+
<# gh pinned to the repo root (gh has no -C); output relays to the console
|
|
606
|
+
only; throws GcException on exit != 0. Use Get-GcGhJson for parsing. #>
|
|
607
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string[]]$Argv)
|
|
608
|
+
$r = Invoke-GcGhCapture -Root $Root -Argv $Argv
|
|
609
|
+
if ($r.Code -ne 0) { Convert-GcGhError -Verb $Argv[0] -Code $r.Code -Text $r.Text }
|
|
610
|
+
foreach ($line in @($r.Text -split "`n")) { if ($line) { Write-GcNote " $line" -ForegroundColor DarkGray } }
|
|
611
|
+
return
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function Get-GcGhJson {
|
|
615
|
+
<# gh --json result as a parsed object; failure keeps gh's own message.
|
|
616
|
+
Never pipes a bare string (chars) — join first. #>
|
|
617
|
+
param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string[]]$Argv)
|
|
618
|
+
$r = Invoke-GcGhCapture -Root $Root -Argv $Argv
|
|
619
|
+
if ($r.Code -ne 0) { Convert-GcGhError -Verb $Argv[0] -Code $r.Code -Text $r.Text }
|
|
620
|
+
return ($r.Text | ConvertFrom-Json)
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
# --- secret gate --------------------------------------------------------------
|
|
624
|
+
$script:GcSecretSafeFilenameRe = '^\.env\.(example|sample|template)$'
|
|
625
|
+
$script:GcSecretFilenameRe = '\.env(\.[A-Za-z0-9_-]+)?$|\.pem$|\.p12$|\.pfx$|\.key$|^(id_rsa|id_ed25519|id_ecdsa|id_dsa|credentials)$'
|
|
626
|
+
$script:GcSecretContentRes = @(
|
|
627
|
+
'-----BEGIN (RSA |EC |OPENSSH |DSA |PGP |ENCRYPTED )?PRIVATE KEY-----',
|
|
628
|
+
'AKIA[0-9A-Z]{16}',
|
|
629
|
+
'ghp_[A-Za-z0-9]{36}',
|
|
630
|
+
'github_pat_[A-Za-z0-9_]{30,}',
|
|
631
|
+
'xox[baprs]-[A-Za-z0-9-]{10,}',
|
|
632
|
+
'sk-[A-Za-z0-9]{24,}'
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
function Get-GcSecretHits {
|
|
636
|
+
<#
|
|
637
|
+
Scans the STAGED CONTENT — the index blobs via `git show :<path>`, exactly
|
|
638
|
+
what a commit would ship — for obvious secret shapes. A worktree edit after
|
|
639
|
+
`git add` cannot smuggle a staged secret past this gate. Staged DELETIONS
|
|
640
|
+
are skipped (removing key material is the fix itself). Returns a list of
|
|
641
|
+
{ File, Why } hits — empty when clean. Callers unstage the hits and exit 4.
|
|
642
|
+
#>
|
|
643
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
644
|
+
$state = Get-GcRepoState -Root $Root
|
|
645
|
+
# staged DELETIONS are skipped: removing key material is the fix itself.
|
|
646
|
+
# StagedDeleted mirrors the old `^D\s+` filter (X=D, Y=.) exactly.
|
|
647
|
+
$deleted = @{}
|
|
648
|
+
foreach ($n in $state.StagedDeleted) { $deleted[$n] = $true }
|
|
649
|
+
$hits = @()
|
|
650
|
+
foreach ($rel in $state.Staged) {
|
|
651
|
+
if ($deleted.ContainsKey($rel)) { continue }
|
|
652
|
+
$leaf = Split-Path $rel -Leaf
|
|
653
|
+
if ($leaf -match $script:GcSecretSafeFilenameRe) { continue }
|
|
654
|
+
$why = $null
|
|
655
|
+
if ($leaf -match $script:GcSecretFilenameRe) {
|
|
656
|
+
$why = "filename looks like key material ($leaf)"
|
|
657
|
+
} else {
|
|
658
|
+
try {
|
|
659
|
+
$blob = @(Get-GcGit -Root $Root -Argv @('show',":$rel"))
|
|
660
|
+
$text = ($blob -join "`n")
|
|
661
|
+
foreach ($re in $script:GcSecretContentRes) {
|
|
662
|
+
if ($text -match $re) { $why = "staged content matches $re"; break }
|
|
663
|
+
}
|
|
664
|
+
} catch { } # no index blob / unreadable — skip the content pass
|
|
665
|
+
}
|
|
666
|
+
if ($why) { $hits += [pscustomobject]@{ File = $rel; Why = $why } }
|
|
667
|
+
}
|
|
668
|
+
return $hits
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function Stop-GcOnSecrets {
|
|
672
|
+
<#
|
|
673
|
+
Blocks a stage/commit on secret hits: unstages exactly the offending files
|
|
674
|
+
(working tree untouched), prints remediation, and exits 4.
|
|
675
|
+
#>
|
|
676
|
+
param([Parameter(Mandatory)][string]$Root)
|
|
677
|
+
$hits = Get-GcSecretHits -Root $Root
|
|
678
|
+
if (-not $hits) { return }
|
|
679
|
+
$names = @($hits | ForEach-Object { $_.File })
|
|
680
|
+
Write-GcFail "secret scan blocked: $($names -join ', ')"
|
|
681
|
+
foreach ($h in $hits) { Write-GcFail " $($h.File) — $($h.Why)" }
|
|
682
|
+
# `restore --staged` resolves HEAD; on an unborn repo (fresh init, no commits)
|
|
683
|
+
# it dies with "fatal: could not resolve 'HEAD'". Fall back to the index-only
|
|
684
|
+
# unstage for the SAME offender names — same narrow semantics, working tree
|
|
685
|
+
# untouched, exit 4 unchanged.
|
|
686
|
+
$unstaged = $false
|
|
687
|
+
try {
|
|
688
|
+
Invoke-GcGit -Root $Root -Argv (@('restore','--staged','--') + $names)
|
|
689
|
+
$unstaged = $true
|
|
690
|
+
} catch {
|
|
691
|
+
try {
|
|
692
|
+
Invoke-GcGit -Root $Root -Argv (@('rm','--cached','--quiet','--') + $names)
|
|
693
|
+
$unstaged = $true
|
|
694
|
+
} catch {
|
|
695
|
+
Write-GcFail "could not unstage the offenders: $($_.Exception.Message)"
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if ($unstaged) { Write-GcNotice 'unstaged exactly those files; working tree untouched' }
|
|
699
|
+
Write-GcNotice 'remediation: remove the secret, add a .gitignore entry if the file is never meant to be tracked, then re-run'
|
|
700
|
+
Write-GcResult -Code $script:GcExitSecret -Props @{ message = 'secret scan blocked the operation'; blocked = $names }
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
# --- result line --------------------------------------------------------------
|
|
704
|
+
function Write-GcResult {
|
|
705
|
+
<#
|
|
706
|
+
Prints the single contract stdout line and exits with the documented code.
|
|
707
|
+
stdout carries ONLY this line; everything else is Write-Host.
|
|
708
|
+
#>
|
|
709
|
+
param([int]$Code = 0, [hashtable]$Props = @{})
|
|
710
|
+
$o = [ordered]@{ ok = ($Code -eq 0); exit = $Code }
|
|
711
|
+
foreach ($k in $Props.Keys) { $o[$k] = $Props[$k] }
|
|
712
|
+
if ($Code -ne 0) { Write-Host '' }
|
|
713
|
+
Write-Output ("RESULT: " + ($o | ConvertTo-Json -Compress))
|
|
714
|
+
exit $Code
|
|
715
|
+
}
|