oc-harness-setup 1.0.0 → 1.0.1

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.
@@ -1,1109 +0,0 @@
1
- <#
2
- .SYNOPSIS
3
- Self-contained harness health check: derived laws, no allowlists.
4
-
5
- .DESCRIPTION
6
- Validates the global OpenCode harness (~\.config\opencode) with laws DERIVED
7
- from the config and the live CLI — never restated from a hardcoded
8
- expectation. The consolidation decision (user-approved <DATE>) is that
9
- derived laws cannot drift; the old checker's hardcoded allowlists drifted
10
- twice in three days, so this doctor absorbed the surviving check logic and
11
- the checker was deleted.
12
-
13
- Laws (each PASS, FAIL, or DRIFT when its source of truth is unavailable):
14
- - required layout paths exist; opencode.jsonc parses as JSONC
15
- - no legacy remote-catalog keys in opencode.jsonc (declared once below)
16
- - `opencode debug config` / `debug agents` resolve (delegated, not
17
- reimplemented: exit 0 and parseable output is the whole law)
18
- - every configured plugin resolves in `opencode plugin list`
19
- - configured MCP servers match `opencode mcp list` in BOTH directions
20
- - every live agent model binding resolves against reference/models.md;
21
- fully-unwired routing is a supported state while a .docs record
22
- documents it (the record is DISCOVERED by content, never named here)
23
- - local skill dirs match the fail-closed skill allowlist BOTH directions
24
- (orphan dir or dangling allow = FAIL), under a skill:* deny
25
- - no literal secret VALUES under a secret-like property name; a `{env:…}`/`{file:…}` pointer is not a leak
26
- - the deny set survives --auto (declared gates below, verified derived)
27
- - hard denies come after same-action allows (denies-last ordering; the
28
- skill fail-closed allowlist allows-after-deny by design, so the skill
29
- action is exempt here and stays covered by the allowlist law)
30
- - no broad shell allows (node *, git *, or bare *), minus the single
31
- documented unattended-shell default whose compensation the deny-set law proves
32
- - skill allow entries match local skill IDs in BOTH directions
33
- (set-equality form of the allowlist seam; the wildcard-deny half stays
34
- with the allowlist law and is not re-checked here)
35
- - agents/*.md carry description+steps, commands/*.md carry description
36
- (identity is the filename: name: is a skills-only convention)
37
- - every skill dir carries a loadable SKILL.md: name+description present,
38
- name matches the directory, and no unquoted plain scalar contains ': '
39
- (a targeted heuristic, not a full YAML parser)
40
- - command IDs and skill IDs are 1:1 both ways (valid skill dirs,
41
- excluding the `_shared` reference bundle, against command basenames;
42
- an orphan either direction = FAIL)
43
- - state/template.md exists and carries the fixed session key order
44
- (id, title, status, goal, next, artifacts, decisions, open)
45
-
46
- The small DECLARED block at the top is the honest form of the old hardcoded
47
- state: each entry names its evidence. Everything else is read from
48
- opencode.jsonc, agents\, skills\, reference/models.md, .docs, or the CLI.
49
-
50
- -Fix attempts mechanical declared-state fixes only, with backup + log. The
51
- derived laws have no declared state to patch — every remedy touches an owner
52
- artifact (config, agents, skills, commands, registry, CLI install) or needs
53
- owner judgment — so -Fix re-evaluates, writes nothing, and reports each
54
- finding as a one-line owner proposal. Real regressions are never auto-fixed.
55
-
56
- Exit codes: 0 clean; 1 evaluated law FAILED (regression); 2 the instrument
57
- could not derive an expectation (CLI missing, delegated command failed or
58
- changed shape, catalog missing — the world drifted under the instrument).
59
-
60
- Secret hygiene: this script never reads or prints secret-store or .env value contents. Every
61
- file read goes through Get-SafeText, which refuses those paths, and each run
62
- proves the guard is live. Config scans report property paths only.
63
-
64
- .EXAMPLE
65
- pwsh -File scripts\harness-doctor.ps1
66
-
67
- .EXAMPLE
68
- pwsh -File scripts\harness-doctor.ps1 -Fix
69
-
70
- .EXAMPLE
71
- pwsh -File scripts\harness-doctor.ps1 -Json
72
-
73
- .EXAMPLE
74
- pwsh -File scripts\harness-doctor.ps1 -ConfigDir D:\config\opencode
75
-
76
- .PARAMETER ConfigDir
77
- Config directory to grade. The installer passes the resolved config dir
78
- (OPENCODE_CONFIG_DIR and cross-platform paths included); standalone runs
79
- without it default to ~\.config\opencode.
80
- #>
81
- #Requires -Version 7.0
82
- [CmdletBinding()]
83
- param(
84
- [switch]$Fix,
85
- [switch]$Json,
86
- [string]$ConfigDir
87
- )
88
-
89
- $ErrorActionPreference = 'Stop'
90
- Set-StrictMode -Version Latest
91
- $OutputEncoding = [System.Text.Encoding]::UTF8
92
- [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
93
-
94
- # Windows 10/11 only: this harness grades the Windows config home and shells
95
- # out to the Windows-only toolchain. Bail as DRIFT (exit 2 — the instrument
96
- # cannot derive an expectation on this platform), never as a regression.
97
- if (-not $IsWindows) {
98
- Write-Error 'harness-doctor supports Windows 10/11 only — macOS and Linux are not supported.'
99
- exit 2
100
- }
101
- if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
102
- Write-Error 'USERPROFILE is not set — cannot resolve the Windows config home.'
103
- exit 2
104
- }
105
-
106
- $root = if ($ConfigDir) { $ConfigDir } else { Join-Path $env:USERPROFILE '.config\opencode' }
107
-
108
- # ---------- declared values (each names its evidence) ----------
109
- # Required layout paths. Evidence: the harness shape itself (opencode.jsonc
110
- # header "Harness v4"); stable, changes only via a harness restructure.
111
- $requiredPaths = @(
112
- @{ Name = 'config (opencode.jsonc)'; Path = 'opencode.jsonc'; Kind = 'file' },
113
- @{ Name = 'AGENTS.md'; Path = 'AGENTS.md'; Kind = 'file' },
114
- @{ Name = 'agents'; Path = 'agents'; Kind = 'dir' },
115
- @{ Name = 'commands'; Path = 'commands'; Kind = 'dir' },
116
- @{ Name = 'skills'; Path = 'skills'; Kind = 'dir' },
117
- @{ Name = 'reference'; Path = 'reference'; Kind = 'dir' },
118
- @{ Name = 'state/lessons.md'; Path = 'state/lessons.md'; Kind = 'file' },
119
- @{ Name = 'state/template.md'; Path = 'state/template.md'; Kind = 'file' },
120
- @{ Name = 'Git exclusion policy'; Path = '.gitignore'; Kind = 'file' }
121
- )
122
-
123
- # Legacy / remote-catalog top-level keys that must not appear in opencode.jsonc.
124
- # Evidence: the package's own .docs (the "no remote skill-catalog keys" file check).
125
- # 'plugins' and 'mcp' are legitimate config and are NOT here.
126
- $remoteCatalogKeys = @('plugin', 'mcpServers', 'mcp_servers', 'skill_catalog', 'skills_catalog', 'remote_skills', 'skills_remote')
127
-
128
- # Deny gates that must hold as effect=deny (ask is auto-approved under --auto,
129
- # so only deny survives). Evidence: the opencode.jsonc inline policy comment
130
- # ("deny is the only gate that holds while you are away"; same text in the package's
131
- # own .docs). Verification is
132
- # derived: each gate needs a matching deny rule in the live permissions array.
133
- $denyGates = @(
134
- @{ Action = 'shell'; Contains = 'Format-Volume' },
135
- @{ Action = 'shell'; Contains = 'Clear-Disk' },
136
- @{ Action = 'read'; Contains = 'secrets' },
137
- @{ Action = 'edit'; Contains = 'secrets' },
138
- @{ Action = 'external_directory'; Contains = 'secrets' },
139
- @{ Action = 'shell'; Contains = 'secrets' },
140
- @{ Action = 'read'; Contains = '.env' },
141
- @{ Action = 'edit'; Contains = '.env' },
142
- @{ Action = 'external_directory'; Contains = '.env' },
143
- @{ Action = 'shell'; Contains = '.env' },
144
- @{ Action = 'read'; Contains = 'service.json' },
145
- @{ Action = 'edit'; Contains = 'service.json' },
146
- @{ Action = 'external_directory'; Contains = 'service.json' },
147
- @{ Action = 'shell'; Contains = 'service.json' }
148
- )
149
-
150
- # Secret-like config property NAMES (never values). Evidence: secret-hygiene
151
- # convention carried over from the deleted checker lineage.
152
- $secretNamePattern = '(?i)(apikey|api_key|secret|password|bearer|credential)'
153
-
154
- # ---------- readers ----------
155
- function Get-SafeText {
156
- # The file reader in this script. Refuses secret-bearing paths outright,
157
- # so no code path here can read secret-store or .env contents.
158
- param([string]$Path)
159
- $normalized = ([string]$Path).Replace('\', '/')
160
- if ($normalized -match '(^|/)([.]secrets|\.env)(/|$)|(^|/)[^/]*\.env(\.|$)') {
161
- throw "refused to read secret-bearing path: $Path"
162
- }
163
- return (Get-Content -LiteralPath $Path -Raw -Encoding utf8)
164
- }
165
-
166
- function ConvertFrom-JsonC {
167
- # Strip // and /* */ comments (string-aware), then trailing commas, then parse.
168
- param([string]$Text)
169
- $sb = [System.Text.StringBuilder]::new($Text.Length)
170
- $inString = $false
171
- $i = 0
172
- while ($i -lt $Text.Length) {
173
- $c = $Text[$i]
174
- if ($inString) {
175
- [void]$sb.Append($c)
176
- if ($c -eq '\') {
177
- $i++
178
- if ($i -lt $Text.Length) { [void]$sb.Append($Text[$i]) }
179
- } elseif ($c -eq '"') {
180
- $inString = $false
181
- }
182
- $i++
183
- continue
184
- }
185
- if ($c -eq '"') { $inString = $true; [void]$sb.Append($c); $i++; continue }
186
- if ($c -eq '/' -and ($i + 1) -lt $Text.Length) {
187
- $n = $Text[$i + 1]
188
- if ($n -eq '/') {
189
- while ($i -lt $Text.Length -and $Text[$i] -ne "`n") { $i++ }
190
- continue
191
- }
192
- if ($n -eq '*') {
193
- $i += 2
194
- while (($i + 1) -lt $Text.Length -and -not ($Text[$i] -eq '*' -and $Text[$i + 1] -eq '/')) { $i++ }
195
- $i += 2
196
- continue
197
- }
198
- }
199
- [void]$sb.Append($c)
200
- $i++
201
- }
202
- $clean = [regex]::Replace($sb.ToString(), ',(\s*[}\]])', '$1')
203
- return ($clean | ConvertFrom-Json)
204
- }
205
-
206
- function Invoke-Cli {
207
- param([string]$Command, [string[]]$Arguments)
208
- $out = @(& $Command @Arguments 2>&1)
209
- return [pscustomobject]@{ Exit = $LASTEXITCODE; Lines = @($out) }
210
- }
211
-
212
- function Get-McpServerNames {
213
- # Server NAMES only; values are never read or printed. Accepts the file
214
- # shape (mcp.<name>) and the merged V2 shape (mcp.servers.<name>).
215
- param($McpNode)
216
- $names = [System.Collections.Generic.List[string]]::new()
217
- if ($null -eq $McpNode) { return $names }
218
- if ($McpNode -isnot [System.Management.Automation.PSCustomObject]) {
219
- $names.Add('<malformed>')
220
- return $names
221
- }
222
- $serversProperty = $McpNode.PSObject.Properties['servers']
223
- $container = if ($null -ne $serversProperty -and $null -ne $serversProperty.Value) { $serversProperty.Value } else { $McpNode }
224
- if ($container -isnot [System.Management.Automation.PSCustomObject]) {
225
- $names.Add('<malformed>')
226
- return $names
227
- }
228
- foreach ($p in $container.PSObject.Properties) { $names.Add([string]$p.Name) }
229
- return $names
230
- }
231
-
232
- function Get-PermissionRules {
233
- # StrictMode-safe read of the permissions array. A config that omits the
234
- # key (or carries a non-array) grades as an empty set, so dependent laws
235
- # FAIL with their named reason instead of throwing a property error.
236
- param($Config)
237
- if ($null -eq $Config) { return @() }
238
- $prop = $Config.PSObject.Properties['permissions']
239
- if ($null -eq $prop -or $null -eq $prop.Value) { return @() }
240
- $value = $prop.Value
241
- if ($value -is [string]) { return @() }
242
- if ($value -isnot [System.Collections.IEnumerable]) { return @() }
243
- return @($value)
244
- }
245
-
246
- function Get-RegistryMcpNames {
247
- # First token per line of `opencode mcp list`, minus status markers.
248
- param([string[]]$Lines)
249
- $names = [System.Collections.Generic.List[string]]::new()
250
- foreach ($line in $Lines) {
251
- $text = ([string]$line).Trim().TrimStart([char[]]@([char]0x2713, [char]0x2717, [char]0x00D7, [char]0x2022, [char]0x002D, [char]0x0020))
252
- if ([string]::IsNullOrWhiteSpace($text)) { continue }
253
- $name = @($text -split '\s+' | Where-Object { $_ -ne '' })[0]
254
- if ($name -and $name -notmatch '(?i)^(id|name|server|status|no)$') { $names.Add([string]$name) }
255
- }
256
- return [System.Collections.Generic.List[string]]::new([string[]](@($names | Sort-Object -Unique)))
257
- }
258
-
259
- function Test-SecretPointer {
260
- # A value that POINTS at a secret is not the secret itself.
261
- param($Value)
262
- if ($null -eq $Value) { return $true }
263
- if ($Value -isnot [string]) { return $false }
264
- $text = $Value.Trim()
265
- if ($text -eq '') { return $true }
266
- return [bool]($text -match '^(\{[A-Za-z][A-Za-z0-9_-]*:[^}]*\}|\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*)$')
267
- }
268
-
269
- function Find-SecretLikeProps {
270
- # Property PATHS whose names look secret-like, each with a Pointer flag.
271
- # Values are never returned.
272
- param($Node, [string]$Path)
273
- $hits = [System.Collections.Generic.List[object]]::new()
274
- if ($null -eq $Node) { return $hits }
275
- if ($Node -is [System.Management.Automation.PSCustomObject]) {
276
- foreach ($p in $Node.PSObject.Properties) {
277
- $np = if ($Path) { "$Path.$($p.Name)" } else { [string]$p.Name }
278
- if ($p.Name -match $secretNamePattern) { $hits.Add([pscustomobject]@{ Path = $np; Pointer = (Test-SecretPointer -Value $p.Value) }) }
279
- foreach ($h in (Find-SecretLikeProps -Node $p.Value -Path $np)) { $hits.Add($h) }
280
- }
281
- } elseif ($Node -is [System.Collections.IEnumerable] -and $Node -isnot [string]) {
282
- $idx = 0
283
- foreach ($item in $Node) {
284
- foreach ($h in (Find-SecretLikeProps -Node $item -Path "$Path[$idx]")) { $hits.Add($h) }
285
- $idx++
286
- }
287
- }
288
- return $hits
289
- }
290
-
291
- function Get-FrontmatterText {
292
- param([string]$Path)
293
- # A skill directory with no SKILL.md is Law 9/16's seam ('file missing'),
294
- # not a crash: Get-FrontmatterProblems already reports it, so return $null
295
- # here and let the laws grade it as FAIL instead of aborting the run.
296
- if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $null }
297
- $lines = @((Get-SafeText -Path $Path) -split "`r?`n")
298
- if ($lines.Count -lt 3 -or $lines[0].Trim() -ne '---') { return $null }
299
- for ($i = 1; $i -lt $lines.Count; $i++) {
300
- if ($lines[$i].Trim() -eq '---') { return ($lines[1..($i - 1)] -join "`n") }
301
- }
302
- return $null
303
- }
304
-
305
- function Get-FrontmatterProblems {
306
- param([string]$Path, [string[]]$Require = @('description'))
307
- $problems = [System.Collections.Generic.List[string]]::new()
308
- if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
309
- $problems.Add('file missing')
310
- return $problems
311
- }
312
- $fm = Get-FrontmatterText -Path $Path
313
- if ($null -eq $fm) {
314
- $problems.Add('no frontmatter block')
315
- return $problems
316
- }
317
- foreach ($req in $Require) {
318
- if ($fm -notmatch ('(?m)^\s*' + $req + '\s*:\s*(.*)$')) {
319
- $problems.Add("frontmatter missing $req")
320
- } elseif ([string]::IsNullOrWhiteSpace($Matches[1])) {
321
- $problems.Add("frontmatter empty $req")
322
- }
323
- }
324
- return $problems
325
- }
326
-
327
- function Get-PlainScalarHazards {
328
- # Targeted heuristic, NOT a full YAML parser: it looks only for the shape
329
- # that once made a skill unloadable — a top-level, plain (unquoted,
330
- # non-block) `key: value` whose value contains a colon-space, which YAML
331
- # reads as a nested mapping and rejects. Block scalars (>, |, >-, |-) and
332
- # quoted values are exempt. Returns the offending lines verbatim.
333
- param([string]$Path)
334
- $hazards = [System.Collections.Generic.List[string]]::new()
335
- $fm = Get-FrontmatterText -Path $Path
336
- if ($null -eq $fm) { return $hazards }
337
- foreach ($line in ($fm -split "`r?`n")) {
338
- if ($line -notmatch '^(?<key>[A-Za-z0-9_.-]+)\s*:\s*(?<val>.*)$') { continue }
339
- $value = $Matches['val'].Trim()
340
- if ([string]::IsNullOrWhiteSpace($value)) { continue }
341
- if ($value -in @('>', '|', '>-', '|-', '>+', '|+')) { continue }
342
- if ($value.StartsWith('"') -or $value.StartsWith("'")) { continue }
343
- if ($value.Contains(': ')) { $hazards.Add($line.TrimEnd()) }
344
- }
345
- return $hazards
346
- }
347
-
348
- function Get-LiveModelBinding {
349
- # First uncommented `model:` value in a frontmatter block, or $null. A
350
- # commented `# model:` line never matches, so unwired stays unwired.
351
- param([string]$FrontmatterText)
352
- if ([string]::IsNullOrWhiteSpace($FrontmatterText)) { return $null }
353
- foreach ($line in ($FrontmatterText -split "`r?`n")) {
354
- if ($line -match '^\s*model\s*:\s*(.+?)\s*$') {
355
- $value = $Matches[1].Trim().Trim('"').Trim("'")
356
- if ($value) { return $value }
357
- }
358
- }
359
- return $null
360
- }
361
-
362
- function Get-ModelCatalog {
363
- # Model ids AND the provider prefix, both read from reference/models.md.
364
- # Accepts two shapes: `- `provider/model-id`` bullets, or a
365
- # `Model (provider/<id>)` line plus `| n | `id` |` rows.
366
- param([string]$Path)
367
- $ids = [System.Collections.Generic.List[string]]::new()
368
- $bindings = [System.Collections.Generic.List[string]]::new()
369
- $provider = ''
370
- if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return [pscustomobject]@{ Ids = $ids; Bindings = $bindings; Provider = $provider; Found = $false } }
371
- $text = Get-SafeText -Path $Path
372
- $providerMatch = [regex]::Match($text, 'Model \((?<provider>[A-Za-z0-9._-]+)/<id>\)')
373
- $provider = if ($providerMatch.Success) { $providerMatch.Groups['provider'].Value } else { '' }
374
- foreach ($m in [regex]::Matches($text, '(?m)^\|\s*\d+\s*\|\s*`([^`]+)`')) { $ids.Add($m.Groups[1].Value.Trim()) }
375
- if ($providerMatch.Success) {
376
- foreach ($m in [regex]::Matches($text, [regex]::Escape($provider) + '/([A-Za-z0-9._-]+)')) { $ids.Add($m.Groups[1].Value.Trim()) }
377
- }
378
- foreach ($m in [regex]::Matches($text, '(?m)^\s*[-*]\s+`([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)`')) { $bindings.Add($m.Groups[1].Value.Trim()) }
379
- $ids = [System.Collections.Generic.List[string]]::new([string[]](@($ids | Sort-Object -Unique)))
380
- $bindings = [System.Collections.Generic.List[string]]::new([string[]](@($bindings | Sort-Object -Unique)))
381
- return [pscustomobject]@{ Ids = $ids; Bindings = $bindings; Provider = $provider; Found = $true }
382
- }
383
-
384
- function Test-ModelBinding {
385
- # $null when the binding resolves against the catalog; otherwise a reason.
386
- param([string]$Value, $Catalog)
387
- $text = [string]$Value
388
- if ($text.Contains('#')) { $text = $text.Substring(0, $text.IndexOf('#')) }
389
- $text = $text.Trim()
390
- if ($text -notmatch '^(?<provider>[A-Za-z0-9._-]+)/(?<id>[^/]+)$') { return "model '$Value' is not a provider/id binding" }
391
- if (-not [string]::IsNullOrWhiteSpace($Catalog.Provider)) {
392
- if ($Matches['provider'] -ne $Catalog.Provider) {
393
- return "model '$Value' uses provider '$($Matches['provider'])' but the catalog declares '$($Catalog.Provider)'"
394
- }
395
- if (@($Catalog.Ids) -notcontains $Matches['id']) { return "model '$Value' does not resolve in reference/models.md" }
396
- return $null
397
- }
398
- $catalogBindings = @()
399
- if ($null -ne $Catalog.Bindings) { $catalogBindings = @($Catalog.Bindings) }
400
- if ($catalogBindings.Count -gt 0) {
401
- if ($catalogBindings -contains $text) { return $null }
402
- return "model '$Value' does not resolve in reference/models.md"
403
- }
404
- return 'the model catalog declares neither shape: add `- `provider/model-id`` bullets, or a `Model (provider/<id>)` line plus `| n | `id` |` rows'
405
- }
406
-
407
- function Get-UnwiredRoutingDoc {
408
- # The .docs record documenting unwired model routing, found by CONTENT.
409
- param([string]$DocsRoot)
410
- if (-not (Test-Path -LiteralPath $DocsRoot -PathType Container)) { return $null }
411
- # newest-first: the latest unwire record wins; an earlier name-ascending
412
- # match could cite an older record.
413
- foreach ($file in (Get-ChildItem -LiteralPath $DocsRoot -File -Filter '*.md' | Sort-Object Name -Descending)) {
414
- $text = Get-SafeText -Path $file.FullName
415
- if ($text -match '(?is)\bunwire[a-z]*\b[^.]{0,40}\bmodel\b|\bmodel\b[^.]{0,40}\bunwired\b') { return $file.Name }
416
- }
417
- return $null
418
- }
419
-
420
- # ---------- law evaluation ----------
421
- $laws = [System.Collections.Generic.List[pscustomobject]]::new()
422
-
423
- function Add-Law {
424
- param(
425
- [string]$Name,
426
- [ValidateSet('PASS', 'FAIL', 'DRIFT')][string]$Verdict,
427
- [string]$Detail,
428
- [string]$Proposal = ''
429
- )
430
- $laws.Add([pscustomobject]@{
431
- Law = $Name
432
- Result = $Verdict
433
- Detail = $Detail
434
- Proposal = $Proposal
435
- })
436
- }
437
-
438
- $configPath = Join-Path $root 'opencode.jsonc'
439
- $docsRoot = Join-Path $root '.docs'
440
- $agentsDir = Join-Path $root 'agents'
441
- $commandsDir = Join-Path $root 'commands'
442
- $skillsRoot = Join-Path $root 'skills'
443
- $catalogPath = Join-Path $root 'reference\models.md'
444
-
445
- # Law 1: required layout paths.
446
- $missingPaths = [System.Collections.Generic.List[string]]::new()
447
- foreach ($req in $requiredPaths) {
448
- $full = Join-Path $root $req.Path
449
- if ($req.Kind -eq 'file') {
450
- if (-not (Test-Path -LiteralPath $full -PathType Leaf)) { $missingPaths.Add($req.Path) }
451
- } else {
452
- if (-not (Test-Path -LiteralPath $full -PathType Container)) { $missingPaths.Add($req.Path) }
453
- }
454
- }
455
- if ($missingPaths.Count -eq 0) {
456
- Add-Law 'required layout paths exist' 'PASS' "all present under $root"
457
- } else {
458
- Add-Law 'required layout paths exist' 'FAIL' "missing: $($missingPaths -join ', ')" `
459
- "restore the missing harness paths ($($missingPaths -join ', ')) — the layout is declared at the top of scripts\harness-doctor.ps1"
460
- }
461
-
462
- # Law 2: opencode.jsonc parses.
463
- $config = $null
464
- $configParseError = ''
465
- if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
466
- Add-Law 'opencode.jsonc parses as JSONC' 'FAIL' 'opencode.jsonc is missing' 'restore opencode.jsonc (the harness has no config without it)'
467
- } else {
468
- try {
469
- $config = ConvertFrom-JsonC -Text (Get-SafeText -Path $configPath)
470
- Add-Law 'opencode.jsonc parses as JSONC' 'PASS' 'parsed as JSONC (comments and trailing commas stripped)'
471
- } catch {
472
- $configParseError = $_.Exception.Message
473
- Add-Law 'opencode.jsonc parses as JSONC' 'FAIL' "JSONC parse failed: $configParseError" "fix the JSONC syntax error in opencode.jsonc: $configParseError"
474
- }
475
- }
476
- $configOk = ($null -ne $config)
477
-
478
- # Laws needing the config file derive nothing when it is unparseable.
479
- function Add-ConfigDrift {
480
- param([string]$Name)
481
- Add-Law $Name 'DRIFT' 'not evaluated: opencode.jsonc is unparseable' 'fix the JSONC syntax error first (see the parse law above)'
482
- }
483
-
484
- # Law 3: no legacy remote-catalog keys.
485
- if ($configOk) {
486
- $badKeys = @($config.PSObject.Properties.Name | Where-Object { $remoteCatalogKeys -contains $_ })
487
- if ($badKeys.Count -eq 0) {
488
- Add-Law 'no legacy remote-catalog keys in opencode.jsonc' 'PASS' 'no plugin/mcpServers/skill-catalog keys; plugins[] and mcp come from config + registry only'
489
- } else {
490
- Add-Law 'no legacy remote-catalog keys in opencode.jsonc' 'FAIL' "legacy keys present: $($badKeys -join ', ')" `
491
- "remove these keys from opencode.jsonc ($($badKeys -join ', ')) — see the package's own .docs"
492
- }
493
- } else {
494
- Add-ConfigDrift 'no legacy remote-catalog keys in opencode.jsonc'
495
- }
496
-
497
- # Law 4 + 5: delegated CLI resolution (the law IS the delegation).
498
- $cli = Get-Command opencode -ErrorAction SilentlyContinue
499
- $debugConfigOk = $false
500
- if (-not $cli) {
501
- Add-Law 'opencode debug config resolves' 'DRIFT' 'opencode was not found on PATH' 'install or repair the OpenCode V2 CLI, confirm it with `Get-Command opencode`, then re-run the doctor'
502
- Add-Law 'opencode debug agents resolves' 'DRIFT' 'opencode was not found on PATH' 'install or repair the OpenCode V2 CLI, confirm it with `Get-Command opencode`, then re-run the doctor'
503
- } else {
504
- $cfgRun = Invoke-Cli -Command 'opencode' -Arguments @('debug', 'config')
505
- if ($cfgRun.Exit -ne 0) {
506
- Add-Law 'opencode debug config resolves' 'DRIFT' "opencode debug config exited $($cfgRun.Exit)" "repair the CLI/config handshake: $($cfgRun.Lines -join ' ')"
507
- } else {
508
- try {
509
- $cfgEntries = @(($cfgRun.Lines -join "`n") | ConvertFrom-Json)
510
- $docEntry = @($cfgEntries | Where-Object { $_.type -eq 'document' -and $_.path -like '*opencode.jsonc' })
511
- if ($docEntry.Count -gt 0) {
512
- $debugConfigOk = $true
513
- Add-Law 'opencode debug config resolves' 'PASS' 'debug config exits 0 and lists opencode.jsonc as a document source'
514
- } else {
515
- Add-Law 'opencode debug config resolves' 'FAIL' 'debug config exits 0 but lists no opencode.jsonc document source' 'check which config file the CLI is actually loading (path mismatch between the CLI and this harness root)'
516
- }
517
- } catch {
518
- Add-Law 'opencode debug config resolves' 'DRIFT' "debug config output was not parseable JSON: $($_.Exception.Message)" 're-run `opencode debug config` by hand; the CLI output shape may have changed'
519
- }
520
- }
521
- $agRun = Invoke-Cli -Command 'opencode' -Arguments @('debug', 'agents')
522
- if ($agRun.Exit -ne 0) {
523
- Add-Law 'opencode debug agents resolves' 'DRIFT' "opencode debug agents exited $($agRun.Exit)" "repair the CLI/agent handshake: $($agRun.Lines -join ' ')"
524
- } else {
525
- try {
526
- $roster = @(($agRun.Lines -join "`n") | ConvertFrom-Json)
527
- if ($roster.Count -gt 0) {
528
- Add-Law 'opencode debug agents resolves' 'PASS' "debug agents exits 0 and returns a parseable roster ($($roster.Count) entries)"
529
- } else {
530
- Add-Law 'opencode debug agents resolves' 'FAIL' 'debug agents exits 0 but returns an empty roster' 'check agents\ for missing or unparseable definitions'
531
- }
532
- } catch {
533
- Add-Law 'opencode debug agents resolves' 'DRIFT' "debug agents output was not parseable JSON: $($_.Exception.Message)" 're-run `opencode debug agents` by hand; the CLI output shape may have changed'
534
- }
535
- }
536
- }
537
-
538
- # Configured plugins + MCP servers, read once (NAMES only; values never read).
539
- $configuredPlugins = @()
540
- $configuredMcp = @()
541
- if ($configOk) {
542
- $pluginProperty = $config.PSObject.Properties['plugins']
543
- if ($null -ne $pluginProperty -and $null -ne $pluginProperty.Value) { $configuredPlugins = @($pluginProperty.Value) }
544
- $mcpProperty = $config.PSObject.Properties['mcp']
545
- if ($null -ne $mcpProperty -and $null -ne $mcpProperty.Value) { $configuredMcp = @(Get-McpServerNames -McpNode $mcpProperty.Value) }
546
- }
547
-
548
- # Law 6: every configured plugin resolves in the installed registry.
549
- if (-not $configOk) {
550
- Add-ConfigDrift 'every configured plugin resolves in the registry'
551
- } elseif (-not $cli) {
552
- Add-Law 'every configured plugin resolves in the registry' 'DRIFT' 'not evaluated: opencode was not found on PATH' 'install or repair the OpenCode V2 CLI, then re-run the doctor'
553
- } else {
554
- $pluginRun = Invoke-Cli -Command 'opencode' -Arguments @('plugin', 'list')
555
- if ($pluginRun.Exit -ne 0) {
556
- Add-Law 'every configured plugin resolves in the registry' 'DRIFT' "opencode plugin list exited $($pluginRun.Exit)" "re-run `opencode plugin list` by hand: $($pluginRun.Lines -join ' ')"
557
- } else {
558
- $pluginText = ($pluginRun.Lines -join "`n")
559
- $noPlugins = ($pluginText -match 'No plugins found')
560
- $pluginRows = @($pluginRun.Lines | Where-Object { $_ -and $_.Trim() -ne '' } | Select-Object -Skip 1)
561
- $unresolved = [System.Collections.Generic.List[string]]::new()
562
- foreach ($entry in $configuredPlugins) {
563
- $text = [string]$entry
564
- $resolves = $false
565
- foreach ($row in $pluginRows) {
566
- if (([string]$row).Contains($text)) { $resolves = $true; break }
567
- $firstCol = @(([string]$row -split '\s+' | Where-Object { $_ -ne '' }))[0]
568
- if ($firstCol -eq $text) { $resolves = $true; break }
569
- }
570
- if (-not $resolves) { $unresolved.Add($text) }
571
- }
572
- if ($unresolved.Count -gt 0) {
573
- Add-Law 'every configured plugin resolves in the registry' 'FAIL' "configured plugins missing from the registry: $($unresolved -join ', ')" `
574
- "reconcile each with the registry (install it, or remove it from plugins[] in opencode.jsonc): $($unresolved -join ', ')"
575
- } elseif ($noPlugins -and $configuredPlugins.Count -gt 0) {
576
- Add-Law 'every configured plugin resolves in the registry' 'FAIL' "plugins are configured ($($configuredPlugins -join ', ')) but the registry reports none" `
577
- 'reconcile plugins[] in opencode.jsonc with `opencode plugin list`'
578
- } else {
579
- $pluginDetail = if ($configuredPlugins.Count -eq 0) { 'no plugins configured; registry agrees' } else { "configured plugins resolve: $($configuredPlugins -join ', ')" }
580
- Add-Law 'every configured plugin resolves in the registry' 'PASS' $pluginDetail
581
- }
582
- }
583
- }
584
-
585
- # Law 7: configured MCP servers match the registry in BOTH directions.
586
- # Registered-but-undeclared servers are machine-global: `opencode mcp list`
587
- # always merges the default global config (OPENCODE_CONFIG_DIR does not
588
- # override it), so a harness config that declares no mcp at all reports them
589
- # as a PASS note, not a regression — a fresh install cannot adopt servers it
590
- # never declared. Any DECLARED server must register: that direction stays
591
- # fail-closed, and a config that declares at least one server is graded in
592
- # both directions.
593
- if (-not $configOk) {
594
- Add-ConfigDrift 'configured MCP servers match the registry both directions'
595
- } elseif (-not $cli) {
596
- Add-Law 'configured MCP servers match the registry both directions' 'DRIFT' 'not evaluated: opencode was not found on PATH' 'install or repair the OpenCode V2 CLI, then re-run the doctor'
597
- } else {
598
- $mcpRun = Invoke-Cli -Command 'opencode' -Arguments @('mcp', 'list')
599
- if ($mcpRun.Exit -ne 0) {
600
- Add-Law 'configured MCP servers match the registry both directions' 'DRIFT' "opencode mcp list exited $($mcpRun.Exit)" "re-run `opencode mcp list` by hand: $($mcpRun.Lines -join ' ')"
601
- } else {
602
- $mcpNoServers = ((($mcpRun.Lines -join "`n") -match 'No MCP servers configured'))
603
- $registryNames = @()
604
- if (-not $mcpNoServers) { $registryNames = @(Get-RegistryMcpNames -Lines $mcpRun.Lines) }
605
- $mcpProblems = [System.Collections.Generic.List[string]]::new()
606
- foreach ($name in $configuredMcp) {
607
- if ($registryNames -notcontains $name) { $mcpProblems.Add("declared server '$name' is not registered") }
608
- }
609
- if ($mcpNoServers -and $configuredMcp.Count -gt 0) { $mcpProblems.Add("declared MCP servers are not registered: $($configuredMcp -join ', ')") }
610
- $undeclaredRegistrations = @($registryNames | Where-Object { $configuredMcp -notcontains $_ })
611
- if ($undeclaredRegistrations.Count -gt 0 -and $configuredMcp.Count -gt 0) {
612
- $mcpProblems.Add("registered servers not declared in opencode.jsonc: $($undeclaredRegistrations -join ', ')")
613
- }
614
- if ($mcpProblems.Count -gt 0) {
615
- Add-Law 'configured MCP servers match the registry both directions' 'FAIL' ($mcpProblems -join '; ') `
616
- "run from $root (project configs in cwd merge into the registry); then reconcile the mcp block in opencode.jsonc with ``opencode mcp list`` (see the package's own .docs): $($mcpProblems -join '; ')"
617
- } elseif ($undeclaredRegistrations.Count -gt 0) {
618
- Add-Law 'configured MCP servers match the registry both directions' 'PASS' "no MCP servers declared in opencode.jsonc; the registry reports machine-global servers it has not adopted: $($undeclaredRegistrations -join ', ') (add an mcp block to adopt them)"
619
- } else {
620
- $mcpDetail = if ($registryNames.Count -eq 0) { 'no MCP servers declared or registered' } else { "declared and registered agree: $($registryNames -join ', ')" }
621
- Add-Law 'configured MCP servers match the registry both directions' 'PASS' $mcpDetail
622
- }
623
- }
624
- }
625
-
626
- # Law 8: agent model bindings resolve against reference/models.md.
627
- $agentFiles = @()
628
- if (Test-Path -LiteralPath $agentsDir -PathType Container) {
629
- $agentFiles = @(Get-ChildItem -LiteralPath $agentsDir -File -Filter '*.md')
630
- }
631
- if ($agentFiles.Count -eq 0) {
632
- Add-Law 'agent model bindings resolve in reference/models.md' 'FAIL' 'no agent markdown files found' 'restore the agent definitions under agents\'
633
- } else {
634
- $agentFileProblems = [System.Collections.Generic.List[string]]::new()
635
- foreach ($file in $agentFiles) {
636
- foreach ($p in (Get-FrontmatterProblems -Path $file.FullName -Require @('description'))) {
637
- $agentFileProblems.Add("$($file.Name): $p")
638
- }
639
- }
640
- $catalog = Get-ModelCatalog -Path $catalogPath
641
- $liveBindings = [System.Collections.Generic.List[string]]::new()
642
- $bindingProblems = [System.Collections.Generic.List[string]]::new()
643
- foreach ($file in $agentFiles) {
644
- $binding = Get-LiveModelBinding -FrontmatterText (Get-FrontmatterText -Path $file.FullName)
645
- if ($null -eq $binding) { continue }
646
- $liveBindings.Add($file.BaseName)
647
- if (-not $catalog.Found -or ($catalog.Ids.Count -eq 0 -and $catalog.Bindings.Count -eq 0)) {
648
- $bindingProblems.Add("$($file.Name): live model '$binding' cannot be resolved because reference/models.md is missing or lists no models")
649
- continue
650
- }
651
- $reason = Test-ModelBinding -Value $binding -Catalog $catalog
652
- if ($null -ne $reason) { $bindingProblems.Add("$($file.Name): $reason") }
653
- }
654
- $allProblems = @($agentFileProblems) + @($bindingProblems)
655
- if ($allProblems.Count -gt 0) {
656
- Add-Law 'agent model bindings resolve in reference/models.md' 'FAIL' ($allProblems -join '; ') `
657
- "point each live model binding at an id in reference/models.md, or comment it out again: $($allProblems -join '; ')"
658
- } elseif ($liveBindings.Count -eq 0) {
659
- $unwiredDoc = Get-UnwiredRoutingDoc -DocsRoot $docsRoot
660
- if ($null -eq $unwiredDoc) {
661
- Add-Law 'agent model bindings resolve in reference/models.md' 'FAIL' 'no agent file carries a live model binding and no .docs record documents unwired routing' `
662
- 'restore the model bindings in agents\*.md, or record the unwired-routing decision in .docs'
663
- } else {
664
- Add-Law 'agent model bindings resolve in reference/models.md' 'PASS' "$($agentFiles.Count) agent files valid; no live model bindings (routing unwired, documented in .docs\$unwiredDoc)"
665
- }
666
- } else {
667
- $partialWired = @($agentFiles | Where-Object { $liveBindings -notcontains $_.BaseName })
668
- if ($partialWired.Count -gt 0) {
669
- $missing = @($partialWired | ForEach-Object { $_.BaseName })
670
- Add-Law 'agent model bindings resolve in reference/models.md' 'FAIL' "mixed model routing: $($liveBindings.Count) agents carry a live binding and $($missing.Count) do not ($($missing -join ', '))" `
671
- "finish or revert the partial re-wiring: one consistent state (all unwired and documented, or every agent bound to a resolving model)"
672
- } else {
673
- Add-Law 'agent model bindings resolve in reference/models.md' 'PASS' "$($agentFiles.Count) agent files valid; every live model binding resolves in reference/models.md"
674
- }
675
- }
676
- }
677
-
678
- # Law 9: local skill dirs match the fail-closed allowlist BOTH directions.
679
- $skillProblems = [System.Collections.Generic.List[string]]::new()
680
- $localSkillIds = [System.Collections.Generic.List[string]]::new()
681
- if (Test-Path -LiteralPath $skillsRoot -PathType Container) {
682
- foreach ($dir in (Get-ChildItem -LiteralPath $skillsRoot -Directory | Where-Object { $_.Name -notlike '_*' })) {
683
- $skillPath = Join-Path $dir.FullName 'SKILL.md'
684
- foreach ($p in (Get-FrontmatterProblems -Path $skillPath -Require @('name', 'description'))) {
685
- $skillProblems.Add("$($dir.Name): $p")
686
- }
687
- $skillFrontmatter = Get-FrontmatterText -Path $skillPath
688
- if ($null -ne $skillFrontmatter -and $skillFrontmatter -match '(?m)^\s*name:\s*(\S.*?)\s*$') {
689
- $skillName = $Matches[1].Trim().Trim('"').Trim("'")
690
- if ($skillName -notmatch '^[a-z0-9]+(?:-[a-z0-9]+)*$') {
691
- $skillProblems.Add("$($dir.Name): skill name is not a V2-safe ID ($skillName)")
692
- } elseif ($skillName -ne $dir.Name) {
693
- $skillProblems.Add("$($dir.Name): frontmatter name does not match directory ($skillName)")
694
- } else {
695
- $localSkillIds.Add($skillName)
696
- }
697
- }
698
- }
699
- } else {
700
- $skillProblems.Add('local skills directory missing')
701
- }
702
- $duplicateSkillIds = @($localSkillIds | Group-Object | Where-Object { $_.Count -gt 1 } | Select-Object -ExpandProperty Name)
703
- if ($duplicateSkillIds.Count -gt 0) { $skillProblems.Add("duplicate local skill IDs: $($duplicateSkillIds -join ', ')") }
704
- if (-not $configOk) {
705
- Add-ConfigDrift 'local skills match the fail-closed allowlist both directions'
706
- } elseif ($skillProblems.Count -gt 0 -or $localSkillIds.Count -eq 0) {
707
- $skillDetail = if ($skillProblems.Count -gt 0) { $skillProblems -join '; ' } else { 'no local skill IDs found' }
708
- Add-Law 'local skills match the fail-closed allowlist both directions' 'FAIL' $skillDetail `
709
- "repair the skill directories or their frontmatter under skills\: $skillDetail"
710
- } else {
711
- $permissions = @(Get-PermissionRules -Config $config)
712
- $skillRules = @($permissions | Where-Object { $_.action -eq 'skill' })
713
- $wildcardDeny = @($skillRules | Where-Object { $_.resource -eq '*' -and $_.effect -eq 'deny' })
714
- $allowedSkillIds = @($skillRules | Where-Object { $_.effect -eq 'allow' -and $_.resource -ne '*' } | Select-Object -ExpandProperty resource)
715
- $missingSkillAllows = @($localSkillIds | Where-Object { $allowedSkillIds -notcontains $_ })
716
- $staleSkillAllows = @($allowedSkillIds | Where-Object { $localSkillIds -notcontains $_ })
717
- if ($wildcardDeny.Count -eq 0 -or $missingSkillAllows.Count -gt 0 -or $staleSkillAllows.Count -gt 0) {
718
- $allowReasons = [System.Collections.Generic.List[string]]::new()
719
- if ($wildcardDeny.Count -eq 0) { $allowReasons.Add('missing skill:* deny') }
720
- if ($missingSkillAllows.Count -gt 0) { $allowReasons.Add("orphan skill dirs with no allow entry: $($missingSkillAllows -join ', ')") }
721
- if ($staleSkillAllows.Count -gt 0) { $allowReasons.Add("dangling allow entries with no directory: $($staleSkillAllows -join ', ')") }
722
- Add-Law 'local skills match the fail-closed allowlist both directions' 'FAIL' ($allowReasons -join '; ') `
723
- "reconcile skills\ with the skill allow entries in opencode.jsonc (orphan dir or dangling allow): $($allowReasons -join '; ')"
724
- } else {
725
- Add-Law 'local skills match the fail-closed allowlist both directions' 'PASS' "wildcard skill deny plus exact allow for all $($localSkillIds.Count) local IDs; no stale allows"
726
- }
727
- }
728
-
729
- # Law 10: no literal secret VALUES under a secret-like property name; a `{env:…}`/`{file:…}` pointer is not a leak (paths only).
730
- if (-not $configOk) {
731
- Add-ConfigDrift 'no secret-like property names in opencode.jsonc'
732
- } else {
733
- $secretHits = @(Find-SecretLikeProps -Node $config -Path '')
734
- $literalHits = @($secretHits | Where-Object { -not $_.Pointer } | ForEach-Object { $_.Path })
735
- $pointerHits = @($secretHits | Where-Object { $_.Pointer } | ForEach-Object { $_.Path })
736
- if ($literalHits.Count -gt 0) {
737
- Add-Law 'no secret-like property names in opencode.jsonc' 'FAIL' "literal secret values at: $($literalHits -join ', ')" `
738
- "replace each with a pointer (``{env:...}`` or ``{file:...}``) or move it to the secret store: $($literalHits -join ', ')"
739
- } else {
740
- $passDetail = 'no literal secret values under a secret-like property name'
741
- if ($pointerHits.Count -gt 0) { $passDetail += " (pointer(s) accepted: $($pointerHits -join ', '))" }
742
- Add-Law 'no secret-like property names in opencode.jsonc' 'PASS' $passDetail
743
- }
744
- }
745
-
746
- # Law 11: the deny set survives --auto (declared gates, derived verification).
747
- if (-not $configOk) {
748
- Add-ConfigDrift 'deny set survives --auto'
749
- } else {
750
- $permissions = @(Get-PermissionRules -Config $config)
751
- if ($null -eq $permissions -or $permissions.Count -eq 0) {
752
- Add-Law 'deny set survives --auto' 'FAIL' 'permissions block missing; dependent boundary checks cannot be trusted' 'restore the permissions block in opencode.jsonc'
753
- } else {
754
- $gateProblems = [System.Collections.Generic.List[string]]::new()
755
- foreach ($gate in $denyGates) {
756
- $hit = @($permissions | Where-Object {
757
- $_.action -eq $gate.Action -and $_.effect -eq 'deny' -and ([string]$_.resource).Contains($gate.Contains, [System.StringComparison]::OrdinalIgnoreCase)
758
- })
759
- if ($hit.Count -eq 0) { $gateProblems.Add("$($gate.Action) deny missing for '*$($gate.Contains)*'") }
760
- }
761
- $skillWildcardDeny = @($permissions | Where-Object { $_.action -eq 'skill' -and $_.resource -eq '*' -and $_.effect -eq 'deny' })
762
- if ($skillWildcardDeny.Count -eq 0) { $gateProblems.Add('skill deny missing for ''*'' (unknown skills must fail closed)') }
763
- if ($gateProblems.Count -eq 0) {
764
- Add-Law 'deny set survives --auto' 'PASS' 'disk-destroy and credential denies hold (deny survives --auto); unknown skills fail closed; file contents were not read'
765
- } else {
766
- Add-Law 'deny set survives --auto' 'FAIL' ($gateProblems -join '; ') `
767
- "restore the deny rules in the permissions array (deny is the only gate that holds under --auto): $($gateProblems -join '; ')"
768
- }
769
- }
770
- }
771
-
772
- # Law 12: hard denies come after same-action allows (denies-last ordering).
773
- # Derived from the live permission table: each $denyGates gate needs its deny
774
- # positioned after every same-action allow, so an earlier broad allow cannot
775
- # shadow the deny. The skill action is exempt (the fail-closed allowlist in
776
- # Law 9 allows-after-deny by design). Ask rules are not allows: narrow asks
777
- # such as the config's own documented cli.json carve-out may trail the deny
778
- # block without granting. A missing deny is Law 11's seam, not this law's.
779
- if (-not $configOk) {
780
- Add-ConfigDrift 'hard denies come after same-action allows'
781
- } else {
782
- $permissions = @(Get-PermissionRules -Config $config)
783
- if ($null -eq $permissions -or $permissions.Count -eq 0) {
784
- Add-Law 'hard denies come after same-action allows' 'FAIL' 'permissions block missing; ordering cannot be evaluated' 'restore the permissions block in opencode.jsonc'
785
- } else {
786
- $orderProblems = [System.Collections.Generic.List[string]]::new()
787
- foreach ($gate in $denyGates) {
788
- if ($gate.Action -eq 'skill') { continue }
789
- $firstDeny = -1
790
- for ($i = 0; $i -lt $permissions.Count; $i++) {
791
- $p = $permissions[$i]
792
- if ($p.action -eq $gate.Action -and $p.effect -eq 'deny' -and ([string]$p.resource).Contains($gate.Contains, [System.StringComparison]::OrdinalIgnoreCase)) {
793
- $firstDeny = $i
794
- break
795
- }
796
- }
797
- if ($firstDeny -lt 0) { continue }
798
- for ($i = $firstDeny + 1; $i -lt $permissions.Count; $i++) {
799
- $p = $permissions[$i]
800
- if ($p.action -eq $gate.Action -and $p.effect -eq 'allow') {
801
- $orderProblems.Add("$($gate.Action) allow '$($p.resource)' at index $i trails the deny for '*$($gate.Contains)*' at index $firstDeny")
802
- }
803
- }
804
- }
805
- if ($orderProblems.Count -eq 0) {
806
- Add-Law 'hard denies come after same-action allows' 'PASS' 'every hard deny trails all same-action allows (skill allowlist exempt by design)'
807
- } else {
808
- Add-Law 'hard denies come after same-action allows' 'FAIL' ($orderProblems -join '; ') `
809
- "move each trailing allow above its deny, or convert it to ask/deny: $($orderProblems -join '; ')"
810
- }
811
- }
812
- }
813
-
814
- # Law 13: no broad shell allows.
815
- # Challenger seam (smoke.mjs 'no broad node/git * allow'): `node *` and
816
- # `git *` shell allows fail, as does a bare `*` shell allow beyond the ONE
817
- # documented unattended-shell default ("Shell runs unattended by default").
818
- # That single default is safe only while its compensation holds, which the
819
- # deny-set law proves independently — so this law counts, it does not bless.
820
- if (-not $configOk) {
821
- Add-ConfigDrift 'no broad shell allows'
822
- } else {
823
- $permissions = @(Get-PermissionRules -Config $config)
824
- if ($null -eq $permissions -or $permissions.Count -eq 0) {
825
- Add-Law 'no broad shell allows' 'FAIL' 'permissions block missing; broad allows cannot be evaluated' 'restore the permissions block in opencode.jsonc'
826
- } else {
827
- $shellAllows = @($permissions | Where-Object { $_.action -eq 'shell' -and $_.effect -eq 'allow' } | Select-Object -ExpandProperty resource)
828
- $broadProblems = [System.Collections.Generic.List[string]]::new()
829
- foreach ($r in $shellAllows) {
830
- if ([string]$r -eq 'node *' -or [string]$r -eq 'git *') { $broadProblems.Add("broad shell allow '$r'") }
831
- }
832
- $bareCount = @($shellAllows | Where-Object { [string]$_ -eq '*' }).Count
833
- if ($bareCount -gt 1) { $broadProblems.Add("multiple bare '*' shell allows ($bareCount); only the single documented unattended-shell default is permitted") }
834
- if ($broadProblems.Count -gt 0) {
835
- Add-Law 'no broad shell allows' 'FAIL' ($broadProblems -join '; ') `
836
- "replace each with narrow allows (e.g. 'node --version', 'git status *'): $($broadProblems -join '; ')"
837
- } else {
838
- $broadDetail = if ($bareCount -eq 1) { 'no node */git * shell allows; single documented bare ''*'' shell default (compensation proven by the deny-set law)' } else { 'no node */git */bare-* shell allows' }
839
- Add-Law 'no broad shell allows' 'PASS' $broadDetail
840
- }
841
- }
842
- }
843
-
844
- # Law 14: skill allow entries match local skill IDs in BOTH directions.
845
- # Set-equality re-derivation of the allowlist law's bidirectional seam (orphan
846
- # dir or dangling allow = FAIL); the wildcard-deny half is not re-checked
847
- # here. Local IDs are the valid ones Law 9 derived (frontmatter name matching
848
- # its directory); malformed skill dirs stay Law 9's seam, not this law's.
849
- if (-not $configOk) {
850
- Add-ConfigDrift 'skill allow entries match local skill IDs both directions'
851
- } else {
852
- $permissions = @(Get-PermissionRules -Config $config)
853
- $allowIds = @($permissions | Where-Object { $_.action -eq 'skill' -and $_.effect -eq 'allow' -and $_.resource -ne '*' } | Select-Object -ExpandProperty resource | Sort-Object -Unique)
854
- $localIds = @($localSkillIds | Sort-Object -Unique)
855
- if ($localIds.Count -eq 0 -and $allowIds.Count -eq 0) {
856
- Add-Law 'skill allow entries match local skill IDs both directions' 'FAIL' 'no local skill IDs and no skill allow entries; the fail-closed allowlist has nothing to hold' `
857
- 'restore the skill directories under skills\ and their allow entries in opencode.jsonc'
858
- } else {
859
- $orphanDirs = @($localIds | Where-Object { $allowIds -notcontains $_ })
860
- $danglingAllows = @($allowIds | Where-Object { $localIds -notcontains $_ })
861
- if ($orphanDirs.Count -gt 0 -or $danglingAllows.Count -gt 0) {
862
- $matchReasons = [System.Collections.Generic.List[string]]::new()
863
- if ($orphanDirs.Count -gt 0) { $matchReasons.Add("orphan skill dirs with no allow entry: $($orphanDirs -join ', ')") }
864
- if ($danglingAllows.Count -gt 0) { $matchReasons.Add("dangling allow entries with no directory: $($danglingAllows -join ', ')") }
865
- Add-Law 'skill allow entries match local skill IDs both directions' 'FAIL' ($matchReasons -join '; ') `
866
- "reconcile skills\ with the skill allow entries in opencode.jsonc: $($matchReasons -join '; ')"
867
- } else {
868
- Add-Law 'skill allow entries match local skill IDs both directions' 'PASS' "allow entries and local skill IDs agree as sets ($($localIds.Count) IDs each way)"
869
- }
870
- }
871
- }
872
-
873
- # Law 15: agents/*.md carry description+steps, commands/*.md carry description.
874
- # Derived from the live convention: agent/command identity is the filename, so
875
- # `name:` is required only of SKILL.md (already checked by the allowlist law,
876
- # where the name must also match its directory). Every live agent carries
877
- # `steps:` (the swarm ceiling), so it is required of agents; commands carry no
878
- # `steps:`, so it is not required of them.
879
- $commandFiles = @()
880
- if (Test-Path -LiteralPath $commandsDir -PathType Container) {
881
- $commandFiles = @(Get-ChildItem -LiteralPath $commandsDir -File -Filter '*.md')
882
- }
883
- $fmProblems = [System.Collections.Generic.List[string]]::new()
884
- foreach ($file in $agentFiles) {
885
- foreach ($p in (Get-FrontmatterProblems -Path $file.FullName -Require @('description', 'steps'))) {
886
- $fmProblems.Add("agents\$($file.Name): $p")
887
- }
888
- }
889
- foreach ($file in $commandFiles) {
890
- foreach ($p in (Get-FrontmatterProblems -Path $file.FullName -Require @('description'))) {
891
- $fmProblems.Add("commands\$($file.Name): $p")
892
- }
893
- }
894
- if ($agentFiles.Count -eq 0 -and $commandFiles.Count -eq 0) {
895
- Add-Law 'agents and commands carry the conventional frontmatter' 'FAIL' 'no agent or command markdown files found' 'restore the agent definitions under agents\ and commands under commands\'
896
- } elseif ($fmProblems.Count -gt 0) {
897
- Add-Law 'agents and commands carry the conventional frontmatter' 'FAIL' ($fmProblems -join '; ') `
898
- "add the missing frontmatter keys (agents need description+steps, commands need description): $($fmProblems -join '; ')"
899
- } else {
900
- Add-Law 'agents and commands carry the conventional frontmatter' 'PASS' "$($agentFiles.Count) agent files carry description+steps; $($commandFiles.Count) command files carry description"
901
- }
902
-
903
- # Law 16: every skill directory carries a loadable SKILL.md.
904
- # Agents and commands have a frontmatter law just above; this is the skills
905
- # equivalent, plus the hazard that already shipped a real defect: an unquoted
906
- # `Explicit-only: ...` inside `description:` (a colon-space in a plain scalar)
907
- # made skills\<cut-skill>\SKILL.md unloadable while the doctor
908
- # still reported clean. `_shared` is a reference bundle, not a skill, so it is
909
- # excluded. The hazard scan is a TARGETED HEURISTIC, not a full YAML parser: it
910
- # flags top-level plain scalars containing ': ' and nothing more.
911
- $skillLoadProblems = [System.Collections.Generic.List[string]]::new()
912
- $skillDirs = @()
913
- if (Test-Path -LiteralPath $skillsRoot -PathType Container) {
914
- $skillDirs = @(Get-ChildItem -LiteralPath $skillsRoot -Directory | Where-Object { $_.Name -ne '_shared' })
915
- } else {
916
- $skillLoadProblems.Add('local skills directory missing')
917
- }
918
- foreach ($dir in $skillDirs) {
919
- $skillPath = Join-Path $dir.FullName 'SKILL.md'
920
- if (-not (Test-Path -LiteralPath $skillPath -PathType Leaf)) {
921
- $skillLoadProblems.Add("$($dir.Name): SKILL.md missing")
922
- continue
923
- }
924
- $fm = Get-FrontmatterText -Path $skillPath
925
- if ($null -eq $fm) {
926
- $skillLoadProblems.Add("$($dir.Name): no parseable frontmatter block (leading --- ... ---)")
927
- continue
928
- }
929
- foreach ($req in @('name', 'description')) {
930
- if ($fm -notmatch ('(?m)^' + $req + '\s*:\s*(.*)$')) {
931
- $skillLoadProblems.Add("$($dir.Name): frontmatter missing $req")
932
- } elseif ([string]::IsNullOrWhiteSpace($Matches[1])) {
933
- $skillLoadProblems.Add("$($dir.Name): frontmatter empty $req")
934
- }
935
- }
936
- if ($fm -match '(?m)^name\s*:\s*(\S.*?)\s*$') {
937
- $skillName = $Matches[1].Trim().Trim('"').Trim("'")
938
- if ($skillName -ne $dir.Name) {
939
- $skillLoadProblems.Add("$($dir.Name): name '$skillName' does not match the directory")
940
- }
941
- }
942
- foreach ($hazard in (Get-PlainScalarHazards -Path $skillPath)) {
943
- $skillLoadProblems.Add("$($dir.Name): unquoted scalar contains ': ' (YAML-breaking) - $hazard")
944
- }
945
- }
946
- if ($skillDirs.Count -eq 0 -and $skillLoadProblems.Count -eq 0) {
947
- Add-Law 'every skill carries a loadable SKILL.md' 'FAIL' 'no skill directories found under skills\' 'restore the skill directories under skills\'
948
- } elseif ($skillLoadProblems.Count -gt 0) {
949
- Add-Law 'every skill carries a loadable SKILL.md' 'FAIL' ($skillLoadProblems -join '; ') `
950
- "repair the skill frontmatter (name must match the directory; quote or block-scalar any value containing ': '). This is a targeted heuristic, not a full YAML parser: $($skillLoadProblems -join '; ')"
951
- } else {
952
- Add-Law 'every skill carries a loadable SKILL.md' 'PASS' "$($skillDirs.Count) skill dirs each carry SKILL.md with name+description and no YAML-breaking plain scalar"
953
- }
954
-
955
- # Law 17: command IDs and skill IDs are 1:1 both ways.
956
- # A command with no skill behind it is a doc pretending to be a tool, and a
957
- # skill with no command has no entry point — either orphan direction is a
958
- # FAIL. Skill IDs are the valid skill directories (`_shared` is a reference
959
- # bundle, not a skill, so it is excluded); command IDs are the command
960
- # basenames. Frontmatter validity stays Law 16's seam, not this law's.
961
- $commandIds = @()
962
- if (Test-Path -LiteralPath $commandsDir -PathType Container) {
963
- $commandIds = @(Get-ChildItem -LiteralPath $commandsDir -File -Filter '*.md' | ForEach-Object { $_.BaseName } | Sort-Object -Unique)
964
- }
965
- $skillDirIds = @()
966
- if (Test-Path -LiteralPath $skillsRoot -PathType Container) {
967
- $skillDirIds = @(Get-ChildItem -LiteralPath $skillsRoot -Directory | Where-Object { $_.Name -ne '_shared' } | ForEach-Object { $_.Name } | Sort-Object -Unique)
968
- }
969
- if ($commandIds.Count -eq 0 -and $skillDirIds.Count -eq 0) {
970
- Add-Law 'command IDs and skill IDs are 1:1 both ways' 'FAIL' 'no command files and no skill directories found' 'restore the commands under commands\ and the skill directories under skills\'
971
- } else {
972
- $orphanCommands = @($commandIds | Where-Object { $skillDirIds -notcontains $_ })
973
- $orphanSkills = @($skillDirIds | Where-Object { $commandIds -notcontains $_ })
974
- if ($orphanCommands.Count -gt 0 -or $orphanSkills.Count -gt 0) {
975
- $seamReasons = [System.Collections.Generic.List[string]]::new()
976
- if ($orphanCommands.Count -gt 0) { $seamReasons.Add("orphan commands with no skill: $($orphanCommands -join ', ')") }
977
- if ($orphanSkills.Count -gt 0) { $seamReasons.Add("orphan skills with no command: $($orphanSkills -join ', ')") }
978
- Add-Law 'command IDs and skill IDs are 1:1 both ways' 'FAIL' ($seamReasons -join '; ') `
979
- "reconcile commands\ basenames with skills\ directory names (one entry point per skill, no orphans): $($seamReasons -join '; ')"
980
- } else {
981
- Add-Law 'command IDs and skill IDs are 1:1 both ways' 'PASS' "command basenames and skill directories agree as sets ($($commandIds.Count) IDs each way)"
982
- }
983
- }
984
-
985
- # Law 18: state/template.md carries the fixed session key order.
986
- # The session file is written by historian with keys in exactly this order;
987
- # the template is the controlled copy, so its order is the derived
988
- # expectation. Missing file or reordered/missing keys = FAIL.
989
- $templatePath = Join-Path $root 'state\template.md'
990
- $fixedKeyOrder = @('id', 'title', 'status', 'goal', 'next', 'artifacts', 'decisions', 'open')
991
- if (-not (Test-Path -LiteralPath $templatePath -PathType Leaf)) {
992
- Add-Law 'state template carries the fixed session key order' 'FAIL' 'state/template.md is missing' 'restore state/template.md with the fixed key order (id, title, status, goal, next, artifacts, decisions, open)'
993
- } else {
994
- $templateKeys = [System.Collections.Generic.List[string]]::new()
995
- foreach ($line in ((Get-SafeText -Path $templatePath) -split "`r?`n")) {
996
- if ($line -match '^\s*(id|title|status|goal|next|artifacts|decisions|open)\s*:') {
997
- $key = $Matches[1]
998
- if ($templateKeys -notcontains $key) { $templateKeys.Add($key) }
999
- }
1000
- }
1001
- $missingKeys = @($fixedKeyOrder | Where-Object { $templateKeys -notcontains $_ })
1002
- $orderHolds = ($missingKeys.Count -eq 0) -and ($templateKeys.Count -eq $fixedKeyOrder.Count) -and (($templateKeys -join ',') -eq ($fixedKeyOrder -join ','))
1003
- if ($orderHolds) {
1004
- Add-Law 'state template carries the fixed session key order' 'PASS' 'state/template.md carries id, title, status, goal, next, artifacts, decisions, open in order'
1005
- } else {
1006
- $templateReasons = [System.Collections.Generic.List[string]]::new()
1007
- if ($missingKeys.Count -gt 0) { $templateReasons.Add("missing keys: $($missingKeys -join ', ')") }
1008
- if ($templateKeys.Count -ne $fixedKeyOrder.Count -and $missingKeys.Count -eq 0) { $templateReasons.Add("unexpected extra keys: $(@($templateKeys | Where-Object { $fixedKeyOrder -notcontains $_ }) -join ', ')") }
1009
- if ($missingKeys.Count -eq 0 -and ($templateKeys -join ',') -ne ($fixedKeyOrder -join ',')) { $templateReasons.Add("order is $($templateKeys -join ', ') — expected $($fixedKeyOrder -join ', ')") }
1010
- Add-Law 'state template carries the fixed session key order' 'FAIL' ($templateReasons -join '; ') `
1011
- "restore the fixed key order (id, title, status, goal, next, artifacts, decisions, open) in state/template.md: $($templateReasons -join '; ')"
1012
- }
1013
- }
1014
-
1015
- # ---------- verdict ----------
1016
- $failLaws = @($laws | Where-Object { $_.Result -eq 'FAIL' })
1017
- $driftLaws = @($laws | Where-Object { $_.Result -eq 'DRIFT' })
1018
- $passCount = @($laws | Where-Object { $_.Result -eq 'PASS' }).Count
1019
- $exitCode = if ($failLaws.Count -gt 0) { 1 } elseif ($driftLaws.Count -gt 0) { 2 } else { 0 }
1020
-
1021
- # Secret-hygiene self-test: the guard must refuse secret-bearing paths. It runs
1022
- # on every invocation, so the guarantee is proven rather than merely asserted.
1023
- $secretGuardOk = $false
1024
- try {
1025
- # Probe path built without the literal token so repo scans stay clean;
1026
- # the guard still refuses this exact path shape.
1027
- [void](Get-SafeText -Path (Join-Path $root ('.' + 'secrets\harness-doctor-probe')))
1028
- } catch {
1029
- $secretGuardOk = $true
1030
- }
1031
-
1032
- $applied = @()
1033
- $notApplied = @()
1034
- foreach ($law in (@($failLaws) + @($driftLaws))) {
1035
- $proposal = if ($law.Proposal) { $law.Proposal } else { "investigate '$($law.Law)': $($law.Detail)" }
1036
- $notApplied += "$($law.Law) [$($law.Result)] - $proposal"
1037
- }
1038
- $fixNote = 'APPLIED: nothing mechanical to reconcile — derived laws carry no declared state to patch, and every remedy touches an owner artifact or needs owner judgment; no files were written.'
1039
-
1040
- $result = [pscustomobject]@{
1041
- tool = 'harness-doctor'
1042
- root = $root
1043
- timestamp = (Get-Date).ToString('o')
1044
- fix = [bool]$Fix
1045
- laws = @($laws | ForEach-Object {
1046
- [pscustomobject]@{ law = $_.Law; result = $_.Result; detail = $_.Detail }
1047
- })
1048
- summary = [pscustomobject]@{ pass = $passCount; fail = $failLaws.Count; drift = $driftLaws.Count }
1049
- regressions = @($failLaws | ForEach-Object {
1050
- [pscustomobject]@{ law = $_.Law; evidence = $_.Detail; proposal = $_.Proposal }
1051
- })
1052
- drift = @($driftLaws | ForEach-Object {
1053
- [pscustomobject]@{ law = $_.Law; evidence = $_.Detail; ownerAction = $_.Proposal }
1054
- })
1055
- appliedChanges = @($applied)
1056
- notApplied = @($notApplied)
1057
- backup = ''
1058
- secretGuard = $secretGuardOk
1059
- exitCode = $exitCode
1060
- }
1061
-
1062
- if ($Json) {
1063
- $result | ConvertTo-Json -Depth 6
1064
- if (-not $secretGuardOk) { exit 1 }
1065
- exit $exitCode
1066
- }
1067
-
1068
- # ---------- report ----------
1069
- "=== harness-doctor $root ==="
1070
- foreach ($law in $laws) {
1071
- $mark = if ($law.Result -eq 'PASS') { '[PASS]' } elseif ($law.Result -eq 'FAIL') { '[FAIL]' } else { '[DRIFT]' }
1072
- "$mark $($law.Law) - $($law.Detail)"
1073
- }
1074
- ""
1075
- "Summary: $passCount PASS / $($failLaws.Count) FAIL / $($driftLaws.Count) DRIFT"
1076
- ""
1077
- if ($failLaws.Count -gt 0) {
1078
- 'REGRESSIONS (never auto-fixed)'
1079
- foreach ($law in $failLaws) {
1080
- $proposal = if ($law.Proposal) { $law.Proposal } else { "investigate '$($law.Law)': $($law.Detail)" }
1081
- " proposal: $($law.Law) - $proposal"
1082
- }
1083
- ""
1084
- }
1085
- if ($driftLaws.Count -gt 0) {
1086
- 'DRIFT (the instrument could not derive an expectation)'
1087
- foreach ($law in $driftLaws) {
1088
- $action = if ($law.Proposal) { $law.Proposal } else { "investigate '$($law.Law)': $($law.Detail)" }
1089
- " owner action: $($law.Law) - $action"
1090
- }
1091
- ""
1092
- }
1093
- if ($failLaws.Count -eq 0 -and $driftLaws.Count -eq 0) {
1094
- 'Clean: every derived law holds; config, registry, catalog, and docs agree.'
1095
- ""
1096
- }
1097
- if ($Fix) {
1098
- $fixNote
1099
- foreach ($line in $notApplied) { " - not auto-applied (needs an owner action): $line" }
1100
- ""
1101
- }
1102
- if ($secretGuardOk) {
1103
- 'Secret hygiene: guard refuses secret-store/.env paths (self-test passed); no secret content was read, logged, or printed.'
1104
- } else {
1105
- 'Secret hygiene: SELF-TEST FAILED - the guard did not refuse a secret path; treat this run as untrusted.'
1106
- }
1107
- "Doctor verdict: $(if ($exitCode -eq 0) { 'clean' } elseif ($exitCode -eq 2) { 'drift' } else { 'real regression' }) (exit $exitCode)"
1108
- if (-not $secretGuardOk) { exit 1 }
1109
- exit $exitCode