oc-harness-setup 0.1.0

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