Files
solution-erp/scripts/governance-detectors.ps1

1092 lines
59 KiB
PowerShell

<#
.SYNOPSIS
governance-detectors.ps1 - Harness-11 PHAN C + B3 governance drift detectors.
.DESCRIPTION
NO-API, DETECT-and-FLAG-only grep net (Harness-11 mandate):
(1) NO-API - only Select-String + byte/file-exist measure. NEVER calls model/API.
(2) FLAG-only - prints FLAGs, NEVER edits files (auto-WRITE of rules = top hazard, forbidden).
(3) PowerShell 5.1 compatible. Run offline. ASCII-only script body (gotcha #30);
target-file content is read -Encoding UTF8 so Vietnamese count-tokens
(bay / bang / Du tru) match correctly.
(5) DETECT-only LOWERING NET, not a hard build gate. Exit code always 0.
Detectors:
C2/B3 - derived-staleness : canonical counts from STATUS.md (cross-checked vs disk),
then derived docs scanned for stale count-tokens.
C1 - broken-pointer : (a) gotcha #N refs > max-gotcha or missing "### N." anchor
(b) dangling [[wikilink]] in user-memory / agent-memory.
C3 - vocab-fork : alias-sets where >=2 variants live side-by-side.
C4 - self-line exclusion: pattern-describing files removed from every scan
(else the detector self-matches).
H24-1 - title-freshness : doc's OWN title/status anchor date vs the newest
governance milestone date. ANCHOR-SCOPED parse.
H24-2 - carry-age : [carry:<slug>] keys alive across >= M consecutive
most-recent carry-lines. M read from config, never
hardcoded. INFORM-only.
Each FLAG line:
[DETECTOR] severity | file:line | description | resolve: <un-flag condition> (C5)
.PARAMETER RepoRoot
Repo root. Default = resolved 2 levels up from this script (scripts/ -> repo root).
.EXAMPLE
powershell.exe -ExecutionPolicy Bypass -File scripts/governance-detectors.ps1
#>
param(
[string]$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
)
$ErrorActionPreference = 'Continue'
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
$script:FlagCount = 0
function Write-Flag {
param(
[ValidateSet('HIGH', 'MED', 'LOW')] [string]$Severity,
[string]$Where, # file:line
[string]$Desc,
[string]$Resolve
)
$color = switch ($Severity) { 'HIGH' { 'Red' } 'MED' { 'Yellow' } default { 'Gray' } }
Write-Host ("[DETECTOR] {0,-4} | {1} | {2} | resolve: {3}" -f $Severity, $Where, $Desc, $Resolve) -ForegroundColor $color
$script:FlagCount++
}
function Write-Section($title) {
Write-Host ''
Write-Host ("===== $title =====") -ForegroundColor Cyan
}
# Make a path repo-relative for readable FLAG output (forward slashes).
function Rel($full) {
$r = $full
if ($full.StartsWith($RepoRoot, [StringComparison]::OrdinalIgnoreCase)) {
$r = $full.Substring($RepoRoot.Length).TrimStart('\', '/')
}
return ($r -replace '\\', '/')
}
# ---------------------------------------------------------------------------
# Unicode-token builder (gotcha #30 mojibake guard).
# This .ps1 is ASCII-only on disk. PowerShell 5.1 decodes a BOM-less .ps1 with
# the system ANSI codepage (NOT UTF-8) when launched via -File, which corrupts
# any inline Vietnamese literal (e.g. "bay" -> mojibake) so it can no longer
# match correctly-decoded UTF-8 file content. We therefore build every
# Vietnamese token from Unicode code points at RUNTIME -> encoding-independent.
function U { param([int[]]$cp) -join ($cp | ForEach-Object { [char]$_ }) }
# Vietnamese tokens used by detectors:
$VN_BAY = U @(0x62, 0x1EAB, 0x79) # "bay" (gotcha synonym)
$VN_BANG = U @(0x62, 0x1EA3, 0x6E, 0x67) # "bang" (table synonym)
$VN_DUTRU_PRO = U @(0x44, 0x1EF1, 0x20, 0x74, 0x72, 0xF9, 0x20, 0x50, 0x52, 0x4F) # "Du tru PRO"
$VN_NGANSACH_PRO = U @(0x4E, 0x67, 0xE2, 0x6E, 0x20, 0x73, 0xE1, 0x63, 0x68, 0x20, 0x50, 0x52, 0x4F) # "Ngan sach PRO"
# H24-1: EM DASH U+2014 (NOT hyphen-minus U+002D). Verified byte-level against
# .claude/skills/permission-matrix/SKILL.md:16 -> bytes "e2 80 94" = U+2014.
# Same runtime code-point trick as the VN tokens: an inline em-dash would be a
# non-ASCII byte in this .ps1 and would mojibake under the ANSI codepage decode.
$EM_DASH = U @(0x2014)
# ---------------------------------------------------------------------------
# C4 - self-line exclusion (BUILT FIRST so every scan can apply it)
# These files DESCRIBE the patterns the detectors look for; without exclusion
# the detector would flag itself. Glob-style suffix/substring rules.
# ---------------------------------------------------------------------------
$ExcludeExact = @(
(Join-Path $RepoRoot 'scripts\governance-detectors.ps1'),
(Join-Path $RepoRoot 'docs\governance\harness-11-engine.md'),
(Join-Path $RepoRoot 'docs\governance\vocab-alias-map.md')
) | ForEach-Object { $_ -replace '/', '\' }
$ExcludeDirFragments = @(
'\broadcasts\inbox\',
'\broadcasts\outbox\',
'\.claude\workflows\runs\',
'\.claude\workflows\scripts\'
)
function Test-Excluded($full) {
$p = ($full -replace '/', '\')
foreach ($ex in $ExcludeExact) { if ($p -ieq $ex) { return $true } }
foreach ($frag in $ExcludeDirFragments) { if ($p -ilike "*$frag*") { return $true } }
return $false
}
# Resolve which excluded paths actually exist on disk (for the audit line).
$ExcludedActual = @()
foreach ($ex in $ExcludeExact) { if (Test-Path $ex) { $ExcludedActual += $ex } }
foreach ($frag in $ExcludeDirFragments) {
$probe = Join-Path $RepoRoot ($frag.Trim('\'))
if (Test-Path $probe) { $ExcludedActual += $probe }
}
# Gather governance MD set ONCE (docs/** + .claude/** *.md), minus excluded.
# VENDOR-SKIP (S123 review): this walks the FILESYSTEM, so it does NOT honour .gitignore.
# Measured: docs/_user-guide/node_modules/ holds 30 gitignored .md that were being scanned
# as if they were governance docs. Zero anchors in them today => zero impact so far, but
# H24-1 sets moc-phai to the MAX anchor in the corpus: ONE vendor README carrying a future
# "**Last updated:** 2027-xx-xx" would push the right edge past every real doc and silence
# the detector for good -- the exact strangle documented at the H24-1 banner below.
# The '(bin|obj|node_modules)' filter already existed further down for the code-scan; it
# was simply never applied here. Same class, one site patched, sibling missed -- which is
# the S123 lesson in miniature: patch a class, then grep every same-class site.
function Get-GovernanceMd {
$dirs = @((Join-Path $RepoRoot 'docs'), (Join-Path $RepoRoot '.claude'))
$all = @()
foreach ($d in $dirs) {
if (Test-Path $d) {
$all += Get-ChildItem -Path $d -Recurse -Filter *.md -File -ErrorAction SilentlyContinue
}
}
return $all |
Where-Object { $_.FullName -notmatch '[\\/](bin|obj|node_modules)[\\/]' } |
Where-Object { -not (Test-Excluded $_.FullName) }
}
$GovMd = Get-GovernanceMd
# ---------------------------------------------------------------------------
# Canonical values from docs/STATUS.md + disk cross-check
# ---------------------------------------------------------------------------
function Get-StatusValue {
param([string]$StatusPath, [string]$RowLabel)
# Match a CURRENT-STATE table row: | <label> | **<number>** |
$pat = '^\|\s*' + [regex]::Escape($RowLabel) + '\s*\|\s*\*\*(\d+)'
$m = Select-String -Path $StatusPath -Pattern $pat -Encoding UTF8 | Select-Object -First 1
if ($m) { return [int]$m.Matches[0].Groups[1].Value }
return $null
}
Write-Section 'C2/B3 - canonical resolve + disk cross-check'
$statusPath = Join-Path $RepoRoot 'docs\STATUS.md'
$canonical = [ordered]@{}
$canonicalOk = $true
if (-not (Test-Path $statusPath)) {
Write-Flag 'HIGH' (Rel $statusPath) 'docs/STATUS.md not found - cannot resolve canonical counts' 'create docs/STATUS.md CURRENT STATE table'
$canonicalOk = $false
}
else {
# GAP-3 (H24): canonical token -> STATUS.md CURRENT-STATE row label.
# Row labels are READ OFF DISK, not guessed: 'Menu keys' is docs/STATUS.md:19
# ("| Menu keys | **54** |"); 'Policies' does NOT exist yet -- W2 lands
# "| Policies | **216** |". A token whose row is absent must FAIL-LOUD and then
# be SKIPPED: silently resolving to $null would let the 'policy' half of GAP-3
# sit green while measuring nothing (a detector that cannot fire is worse than
# no detector -- it reads as coverage).
$canonRows = [ordered]@{
'mig' = 'Migrations'
'test' = 'Tests'
'gotcha' = 'Gotchas'
'table' = 'SQL tables'
'menu' = 'Menu keys'
'policy' = 'Policies'
}
foreach ($k in $canonRows.Keys) { $canonical[$k] = Get-StatusValue $statusPath $canonRows[$k] }
$canonShow = @()
foreach ($k in $canonRows.Keys) {
$v = $canonical[$k]
if ($null -eq $v) { $canonShow += ("{0}=MISSING" -f $k) } else { $canonShow += ("{0}={1}" -f $k, $v) }
}
Write-Host (" STATUS.md canonical: " + ($canonShow -join ' '))
foreach ($k in $canonRows.Keys) {
if ($null -eq $canonical[$k]) {
Write-Flag 'MED' (Rel $statusPath) `
("canonical row missing: no '| {0} | **<n>** |' row in CURRENT STATE -> token '{1}' UNRESOLVED and SKIPPED (scanning nothing, NOT green)" -f $canonRows[$k], $k) `
("add the '{0}' row to the docs/STATUS.md CURRENT STATE table" -f $canonRows[$k])
}
}
# ---- disk cross-check: canonical must not itself be stale ----
# mig = migration .cs files (exclude *Designer.cs / *ModelSnapshot.cs), recursive
# so it survives Migrations/ vs Persistence/Migrations/ layout differences.
$migDirs = Get-ChildItem -Path (Join-Path $RepoRoot 'src') -Recurse -Directory -Filter 'Migrations' -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\(bin|obj|node_modules)\\' }
$diskMig = 0
foreach ($md in $migDirs) {
$diskMig += (Get-ChildItem -Path $md.FullName -Filter *.cs -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -notlike '*Designer.cs' -and $_.Name -notlike '*ModelSnapshot.cs' }).Count
}
# gotcha = highest N from "### N." headings in docs/gotchas.md
$gotchasPath = Join-Path $RepoRoot 'docs\gotchas.md'
$diskGotcha = $null
if (Test-Path $gotchasPath) {
$nums = Select-String -Path $gotchasPath -Pattern '^### (\d+)\.' -Encoding UTF8 |
ForEach-Object { [int]$_.Matches[0].Groups[1].Value }
if ($nums) { $diskGotcha = ($nums | Measure-Object -Maximum).Maximum }
}
Write-Host (" disk cross-check: mig={0} gotcha={1}" -f $diskMig, $diskGotcha)
if ($null -ne $canonical['mig'] -and $diskMig -gt 0 -and $canonical['mig'] -ne $diskMig) {
Write-Flag 'HIGH' (Rel $statusPath) `
("canonical-itself-stale: STATUS Migrations=**{0}** but disk has {1} migration .cs" -f $canonical['mig'], $diskMig) `
("re-ground STATUS.md Migrations row to {0}" -f $diskMig)
$canonicalOk = $false
}
if ($null -ne $canonical['gotcha'] -and $null -ne $diskGotcha -and $canonical['gotcha'] -ne $diskGotcha) {
Write-Flag 'HIGH' (Rel $statusPath) `
("canonical-itself-stale: STATUS Gotchas=**{0}** but docs/gotchas.md max anchor is {1}" -f $canonical['gotcha'], $diskGotcha) `
("re-ground STATUS.md Gotchas row to {0}" -f $diskGotcha)
$canonicalOk = $false
}
if ($canonicalOk) {
Write-Host ' [OK] canonical matches disk (mig + gotcha) - safe baseline for derived scan' -ForegroundColor Green
}
}
# ---------------------------------------------------------------------------
# C2/B3 - derived-staleness scan
# Derived docs that summarize counts; each should match canonical OR be a pointer.
# ---------------------------------------------------------------------------
Write-Section 'C2/B3 - derived-doc staleness'
# token-regex -> canonical key. Vietnamese tokens built from code points (ASCII source).
$countPatterns = @(
@{ Rx = '(\d+)\s*migration'; Key = 'mig'; Label = 'migration' },
@{ Rx = '(\d+)\s*test'; Key = 'test'; Label = 'test' },
@{ Rx = ('(\d+)\s*(?:' + $VN_BAY + '|gotcha)'); Key = 'gotcha'; Label = 'gotcha/bay' },
@{ Rx = ('(\d+)\s*(?:' + $VN_BANG + '|table)'); Key = 'table'; Label = 'table/bang' },
# GAP-3 (H24): 'menu' + 'policy' were BLIND. Both resolve via $canonRows above;
# a token whose canonical row is missing is skipped by the $null guard below
# (already FAIL-LOUD flagged at resolve time), so 'policy' stays inert until W2.
@{ Rx = '(\d+)\s*menu'; Key = 'menu'; Label = 'menu' },
@{ Rx = '(\d+)\s*polic(?:y|ies)'; Key = 'policy'; Label = 'policy' }
)
# H18-A(b) scan-range follows the REAL rule-range (S100, Harness-18 adopt): the derived-doc
# set expands DYNAMICALLY to ALL skill SKILL.md + ALL command *.md. Rationale (real pain):
# a stale hard-count "(68)" survived ~11 sessions inside .claude/commands/session-start.md
# because commands/ sat OUTSIDE this fixed list (blind class, H1 F3 catch S99). A fixed list
# self-ages as the rule-set grows; the glob tracks the live set. Test-Excluded still applies.
$derivedDocs = @(
'CLAUDE.md',
'docs\CLAUDE.md',
'.claude\skills\README.md'
) | ForEach-Object { Join-Path $RepoRoot $_ }
$derivedDocs += @(Get-ChildItem -Path (Join-Path $RepoRoot '.claude\skills') -Recurse -Filter 'SKILL.md' -File -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
$derivedDocs += @(Get-ChildItem -Path (Join-Path $RepoRoot '.claude\commands') -Filter '*.md' -File -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName })
foreach ($doc in $derivedDocs) {
if (-not (Test-Path $doc)) { continue }
if (Test-Excluded $doc) { continue }
$lines = Get-Content -Path $doc -Encoding UTF8
for ($i = 0; $i -lt $lines.Count; $i++) {
$line = $lines[$i]
# C2 FP-reduction (R2 refinement S75): per-item table rows + frozen-historical lines are NOT state-count claims
if ($line -match '^\s*\|') { continue }
if ($line -match '(?i)(baseline|\bS\d{2}\b|\(current\b)') { continue }
foreach ($cp in $countPatterns) {
$canon = $canonical[$cp.Key]
if ($null -eq $canon) { continue }
foreach ($m in [regex]::Matches($line, $cp.Rx)) {
$pre = $line.Substring([Math]::Max(0, $m.Index - 12), [Math]::Min(12, $m.Index))
if ($pre -match '(?i)(core|\.net|react|vite|node|mig|phase|session|version)\s*$') { continue } # version/ordinal token, not a state-count
$postIdx = $m.Index + $m.Length
$post = $line.Substring($postIdx, [Math]::Min(10, $line.Length - $postIdx))
if ($cp.Key -eq 'test' -and $post -match '^\s*project') { continue } # "N test project" = project count, not test count
$n = [int]$m.Groups[1].Value
if ($n -ne $canon) {
# H18-A(a) mismatch-only CONFIDENCE band (S100): a stale TOTAL lags canonical
# by a few sessions so it lands NEAR canonical (ratio 0.5..2.0) -> MED.
# A module-local count ("6 test PeWorkflowDefinition" vs canonical 440) sits
# FAR from the total -> LOW advisory (likely a different quantity sharing the
# token word, NOT a stale claim). The old |diff|>=10 rule was BACKWARDS for
# that class (big diff = high sev = false alarm; S98 verify: 8/8 MED were FP).
# Correct restatement (n == canon) still never flags (mismatch-only base).
$ratio = if ($canon -gt 0) { [double]$n / [double]$canon } else { 0.0 }
$sev = if ($ratio -ge 0.5 -and $ratio -le 2.0) { 'MED' } else { 'LOW' }
Write-Flag $sev ("{0}:{1}" -f (Rel $doc), ($i + 1)) `
("derived-stale: writes {0} {1} but canonical={2}" -f $n, $cp.Label, $canon) `
("update to {0} OR replace with pointer '-> docs/STATUS.md'" -f $canon)
}
}
}
}
}
Write-Host ' (note: count-token grep is a soft net - module-local phrases like "4 bang Budget" / "71 test (Phase 8)" can false-positive; H18-A ratio-band demotes far-from-canonical counts to LOW = review-not-fail, near-canonical stale-totals stay MED)' -ForegroundColor DarkGray
# ---------------------------------------------------------------------------
# C1 - broken-pointer: gotcha #N refs
# ---------------------------------------------------------------------------
Write-Section 'C1 - broken gotcha-ref'
$maxGotcha = $canonical['gotcha']
$gotchasPath = Join-Path $RepoRoot 'docs\gotchas.md'
$gotchaAnchors = @{}
if (Test-Path $gotchasPath) {
Select-String -Path $gotchasPath -Pattern '^### (\d+)\.' -Encoding UTF8 |
ForEach-Object { $gotchaAnchors[[int]$_.Matches[0].Groups[1].Value] = $true }
}
if ($null -eq $maxGotcha -or $gotchaAnchors.Count -eq 0) {
Write-Host ' [skip] no canonical max-gotcha or no anchors parsed - cannot validate gotcha refs' -ForegroundColor DarkGray
}
else {
# Match "gotcha #N", "gotcha N", and bare "#N" tokens.
$refRx = '(?:gotcha[s]?\s*#?(\d+))|(?<![A-Za-z0-9])#(\d+)'
foreach ($f in $GovMd) {
$lines = Get-Content -Path $f.FullName -Encoding UTF8
for ($i = 0; $i -lt $lines.Count; $i++) {
foreach ($m in [regex]::Matches($lines[$i], $refRx)) {
$num = if ($m.Groups[1].Success) { [int]$m.Groups[1].Value } else { [int]$m.Groups[2].Value }
$isGotchaWord = $m.Groups[1].Success
# bare "#N": only treat as gotcha-ref candidate when N is in gotcha numeric range
# to avoid PR/issue/run numbers. gotcha-word form always validated.
if (-not $isGotchaWord) {
if ($num -le 0 -or $num -gt ($maxGotcha + 50)) { continue }
# bare #N with N <= maxGotcha and anchor exists -> fine, skip silently
if ($num -le $maxGotcha -and $gotchaAnchors.ContainsKey($num)) { continue }
# bare #N > maxGotcha is ambiguous (could be Run #312) -> skip to avoid noise
if ($num -gt $maxGotcha) { continue }
}
if ($num -gt $maxGotcha) {
Write-Flag 'MED' ("{0}:{1}" -f (Rel $f.FullName), ($i + 1)) `
("broken-gotcha-ref: cites #{0} but max gotcha is {1}" -f $num, $maxGotcha) `
'fix the number or add the gotcha to docs/gotchas.md'
}
elseif ($isGotchaWord -and -not $gotchaAnchors.ContainsKey($num)) {
Write-Flag 'LOW' ("{0}:{1}" -f (Rel $f.FullName), ($i + 1)) `
("broken-gotcha-ref: 'gotcha #{0}' has no '### {0}.' anchor in gotchas.md" -f $num) `
'fix ref or create the missing gotcha anchor'
}
}
}
}
}
# ---------------------------------------------------------------------------
# C1 - broken-pointer: dangling [[wikilink]] (user-memory + agent-memory)
# ---------------------------------------------------------------------------
Write-Section 'C1 - dangling wikilink'
# user-memory dir (outside repo). DERIVED from $RepoRoot, not hardcoded.
#
# FIXED S122 W5 -- the old line was:
# $userMemDir = 'C:\Users\pqhuy\.claude\projects\D--Dropbox-...-SOLUTION-ERP\memory'
# ...directly under a comment that claimed "Derive from this machine's project slug".
# The comment described the INTENT; the code hardcoded an absolute path AND a username.
# Two concrete harms, not style:
# 1) -RepoRoot <temp-tree> still read the REAL user-memory => fault-injection could not
# isolate. The C1-wikilink teeth-test (prove the detector FLAGS on injected breakage)
# was therefore unrunnable -- the one tool built to prove teeth had no teeth itself.
# 2) Hardcoded 'pqhuy' => the script silently degrades to the else-branch on any other
# machine/account, and a silent degrade reads exactly like "clean".
#
# The Claude Code project slug IS $RepoRoot with [:\/_] collapsed to '-'. Verified S122:
# D:\Dropbox\CONG_VIEC\SOLUTION\SOLUTION_ERP -> D--Dropbox-CONG-VIEC-SOLUTION-SOLUTION-ERP
# (exact match against the previously hardcoded literal; Test-Path = True)
# and a temp RepoRoot yields a different slug whose path does NOT exist => the else-branch
# fires => fault-injection isolates. That is the whole point of deriving it.
$projectSlug = $RepoRoot -replace '[:\\/_]', '-'
$userMemDir = Join-Path $env:USERPROFILE ".claude\projects\$projectSlug\memory"
$agentMemDir = Join-Path $RepoRoot '.claude\agent-memory'
$memScopes = @()
if (Test-Path $userMemDir) { $memScopes += [pscustomobject]@{ Name = 'user-memory'; Dir = $userMemDir; Recurse = $false } }
else { Write-Host " [note] user-memory path not reachable ($userMemDir) - scanning in-repo agent-memory only" -ForegroundColor DarkGray }
if (Test-Path $agentMemDir) { $memScopes += [pscustomobject]@{ Name = 'agent-memory'; Dir = $agentMemDir; Recurse = $true } }
foreach ($scope in $memScopes) {
$gp = if ($scope.Recurse) {
Get-ChildItem -Path $scope.Dir -Recurse -Filter *.md -File -ErrorAction SilentlyContinue
} else {
Get-ChildItem -Path $scope.Dir -Filter *.md -File -ErrorAction SilentlyContinue
}
# Build the set of existing target basenames in this scope.
$targets = @{}
foreach ($g in $gp) { $targets[$g.BaseName] = $true; $targets[($g.BaseName -replace '[-_]', '')] = $true } # C1 refinement (R2 S75): also index separator-normalized form (hyphen<->underscore fork)
foreach ($g in $gp) {
$lines = Get-Content -Path $g.FullName -Encoding UTF8
for ($i = 0; $i -lt $lines.Count; $i++) {
foreach ($m in [regex]::Matches($lines[$i], '\[\[([a-z0-9_-]+)\]\]')) {
$tgt = $m.Groups[1].Value
if (-not ($targets.ContainsKey($tgt) -or $targets.ContainsKey(($tgt -replace '[-_]', '')))) {
Write-Flag 'LOW' ("{0}/{1}:{2}" -f $scope.Name, $g.Name, ($i + 1)) `
("dangling-wikilink: [[{0}]] -> {0}.md not found in {1}" -f $tgt, $scope.Name) `
'fix the link target or create the file (note: hyphen vs underscore basename fork is common)'
}
}
}
}
}
# ---------------------------------------------------------------------------
# C3 - vocab-fork
# ---------------------------------------------------------------------------
Write-Section 'C3 - vocab-fork'
# Seed alias-sets (hard-coded from audit; extend over time). Vietnamese variants
# built from code points so the .ps1 stays ASCII-only (gotcha #30) yet matches
# correctly-decoded UTF-8 content.
$aliasSets = @(
@('wave-folder', 'run-trace'),
@($VN_DUTRU_PRO, $VN_NGANSACH_PRO),
@('two-tier', 'all-inherit', 'worker-tier-pin')
)
# NOTE (S126, 2026-07-16): 'worker-tier-pin' added as 3rd variant - owner-decision S124 made it
# the canonical term (vocab-alias-map.md section 3); the B1 sweep found the fork all-inherit-vs-
# worker-tier-pin LIVE in 5 governance files (patched S126) and this seed could not see it.
# NOTE (Harness-16, S93): "memory-fidelity" is INTENTIONALLY NOT seeded here. It is
# NOT a vocab-fork (one concept / two names) -- it is two DISTINCT concepts sharing a
# word: H6.7 "memoryDelta-routing-fidelity" (delta lands in the right agent-memory)
# vs Harness-16 "memory-fidelity-EVAL / MFE" (coverage/retention). The alias-map is
# RECORDED in docs/governance/harness-11-engine.md PHAN H. Seeding it would FALSE-flag
# two legitimately-different terms as a fork-to-merge -- do not add it.
# NOTE (Harness-17, S95): "coverage" is likewise INTENTIONALLY NOT seeded. It is THREE
# distinct concepts sharing a word, not a fork: (1) H2 harvest-curator "Coverage"
# (0-silent-miss of spawned subs/runs) ; (2) H16 MFE SUB "coverage" (role-floor still
# carried in the diary) ; (3) H17 A1 "HCV / harvest-coverage" (per-run said-vs-kept).
# The alias-map is RECORDED in harness-11-engine.md PHAN I. Seeding would FALSE-flag three
# legitimately-different terms as a fork-to-merge -- do not add it. Same for "audit"
# (monthly-drift-audit vs H17 spec-audit) -- disambiguated by name in-doc, not seeded.
for ($s = 0; $s -lt $aliasSets.Count; $s++) {
$variants = $aliasSets[$s]
$perVariantFiles = @{}
foreach ($v in $variants) { $perVariantFiles[$v] = New-Object System.Collections.Generic.List[string] }
foreach ($f in $GovMd) {
$content = Get-Content -Path $f.FullName -Raw -Encoding UTF8
if ($null -eq $content) { continue }
foreach ($v in $variants) {
if ($content -match [regex]::Escape($v)) {
$perVariantFiles[$v].Add((Rel $f.FullName)) | Out-Null
}
}
}
$liveVariants = @($variants | Where-Object { $perVariantFiles[$_].Count -gt 0 })
if ($liveVariants.Count -ge 2) {
$detail = ($liveVariants | ForEach-Object { "{0}={1}f" -f $_, $perVariantFiles[$_].Count }) -join ' vs '
$sample = ($liveVariants | ForEach-Object {
$first = $perVariantFiles[$_] | Select-Object -First 2
"'$_' in [$($first -join ', ')]"
}) -join ' | '
Write-Flag 'MED' 'multiple files' `
("vocab-fork: $detail live side-by-side -- $sample") `
'merge to ONE canonical term, or record an alias-map in docs/governance'
}
}
# ---------------------------------------------------------------------------
# C5 - WAL guardrail (H22 S111, reviewer-m1): .claude/WAL.md hard cap 40 lines
# (N.1 overwrite-not-append). DETECT-only nhu moi detector khac.
# ---------------------------------------------------------------------------
Write-Section 'C5 - WAL guardrail (H22)'
$walPath = Join-Path $RepoRoot '.claude\WAL.md'
if (Test-Path $walPath) {
$walLineCount = @(Get-Content $walPath).Count
if ($walLineCount -gt 40) {
Write-Flag 'MED' '.claude/WAL.md' `
("wal-overflow: {0} lines > 40-line hard cap (H22 N.1 overwrite-not-append)" -f $walLineCount) `
'trim WAL to <= 40 lines: move long notes to run-folder/work-state; keep chain+next+verify only'
} else {
Write-Host (" [OK] WAL.md = {0} lines (<= 40 hard cap)" -f $walLineCount)
}
} else {
Write-Host ' (no .claude/WAL.md - no active chain, skip)'
}
# ---------------------------------------------------------------------------
# H24-1 - title-freshness (do-tuoi-tieu-de)
# moc-phai (right edge) = newest governance milestone = MAX valid anchor date in corpus
# moc-trai (left edge) = the date carried by the doc's OWN title/status anchor
# FLAG when trai < phai. No anchor => SKIP (a doc that makes no freshness claim
# cannot make a STALE one).
#
# WHY ANCHOR-SCOPED, NOT "any date on the line" -- this is the load-bearing bit.
# Measured on disk: docs/STATUS.md:6 is a 69,870-char MEGA-LINE carrying 41
# date-shaped tokens. Most are NOT dates: owner-mark ids of the form
# RC-pqhuy1987-12-07-2026-11-43-45 get shredded by a bare \d{4}-\d{2}-\d{2} into
# GARBAGE pseudo-dates (1987-12-07 from the ...1987-12-07... slice, 2026-11-43,
# 2026-20-42 -- month 20, day 42). The line also holds a REAL future date
# (2026-08-01 = next monthly audit due). So:
# - date-max over the line -> 2026-20-42 (garbage) or 2026-08-01 (future)
# - either makes moc-phai unreachable => trai < phai never true => 0 flags forever
# => the detector silently strangles its OWN positive-control and reads green.
# Hence: capture ONLY the date bound to the anchor + strict calendar validation
# (TryParseExact rejects month-20/day-42 outright).
#
# WHY anchor_patterns IS A LIST (>=2 forms) -- also load-bearing:
# .claude/skills/*/SKILL.md carry NO "Last updated" anchor (grep "Last updated"
# in .claude/skills/ = 0 hit, verified). They use the OTHER form:
# "**Status (post Session N <em-dash> YYYY-MM-DD):**". A single "Last updated"
# regex + the "no anchor => skip" rule would drop permission-matrix/SKILL.md --
# the exact positive-control this detector exists to fire on.
# ---------------------------------------------------------------------------
Write-Section 'H24-1 - title-freshness'
$AnchorPatterns = @(
'\*\*Last updated:\*\*\s*(\d{4}-\d{2}-\d{2})',
('\*\*Status \(post Session \d+ ' + $EM_DASH + ' (\d{4}-\d{2}-\d{2})\)\:\*\*')
)
# docs/_archive/ is FROZEN-BY-DESIGN (verbatim pre-S40 snapshots kept as historical
# record). Their old anchor date is the POINT of the file, and the only "resolve"
# action -- refresh the date -- would destroy the record. A flag whose resolve is
# forbidden is permanent noise, so archives are out of THIS detector's scope.
# Scoped LOCALLY (not added to the global Test-Excluded) so C1/C3 keep scanning them
# exactly as before -- widening the global exclude would silently move other
# detectors' baselines, which is not this lane's call.
$TitleFreshSkip = @('\docs\_archive\')
# BACKTICK-GUARD (S123) -- the self-reference trap, measured not guessed.
# A doc that DEFINES the stale-anchor anti-pattern must QUOTE a stale anchor to
# explain it. That quote is byte-identical to a live anchor -- being identical is
# the POINT of a good example -- so a pattern-matcher flags the teacher.
# Measured on disk @S123: 4 H24-1 flags, 2 are this exact case:
# .claude/agents/lead-view-auditor.md:45 quotes the anchor as the EXAMPLE
# for its own class `view-stale-header`
# docs/governance/adap-reports/...harness-24...:78 quotes it while EXPLAINING that
# very false-positive <- 3rd generation
# The defect PROPAGATES BY CITATION: every doc written ABOUT the false-positive
# becomes one. Root instance = permission-matrix/SKILL.md:16 (a REAL defect, fixed W4).
#
# WHY NOT the H24-2 mechanism (charset-discriminator, :670-672): that guard works
# because the format-spec literal "[carry:<slug>]" carries a '<' that a real key can
# NEVER contain. Here there is no such character -- example and claim are byte-equal.
# A DIFFERENT discriminator is required: not the anchor's SHAPE, but its ENCLOSURE.
#
# THE RULE: an anchor sitting inside an inline-code span (`...`) is being MENTIONED,
# not USED (use/mention distinction). Count backticks left of the match; ODD => we are
# inside an open span => quoted example => keep looking. Measured 4/4 ON DISK TODAY:
# BARE -> docs/rag-setup-plan.md:4 . form-engine/SKILL.md:15 = TRUE POSITIVE, still fires
# QUOTED -> lead-view-auditor.md:45 . adap-report...:78 = FALSE POSITIVE, now skipped
#
# 4/4, NOT the "5/5" an earlier draft of this comment claimed (fixed S123 after review).
# The would-be 5th case, permission-matrix/SKILL.md:16, IS NOT ON DISK ANY MORE and does
# NOT fire -- W4/S122 "fixed" it by rewriting the anchor into "**Status (cap-nhat ...):**",
# a form that matches NEITHER $AnchorPatterns entry. So it does not even parse, let alone
# flag. Verified: both patterns return False against that line.
# -> ADJACENT HAZARD, worth naming: that file left the MEASUREMENT SET instead of getting
# fresh. H24-1 thereby lost the exact positive-control it was built around (see the
# anchor_patterns note below: pattern #2 exists BECAUSE of permission-matrix). Flag
# count fell, which reads like success -- Goodhart in its quietest form. Do NOT
# "resolve" a title-stale flag by reshaping the anchor; refresh the date or declare
# the doc frozen-historical.
# -> pattern #2 now matches ONLY form-engine/SKILL.md:15. If that one is ever reshaped
# too, pattern #2 becomes dead code that exists purely to catch quoted examples.
#
# WHY NO head-N-lines scope on top: position is a PROXY, and the backtick rule already
# separates the measured set exactly. Stacking a proxy buys zero measured precision while
# adding a NEW blind spot -- a doc that legitimately anchors below line N goes silently
# unwatched. Mark RC-pqhuy1987-20-06-2026-10-29-11 (proxy-instead-of-signal = false
# economy) applies: use the real signal, not its shadow.
#
# HONEST LIMIT (do not read this as closed): the guard reads INLINE spans only. An
# anchor quoted inside a fenced ``` block has ZERO backticks on its own line => reads
# BARE => still a false positive. Measured 0 such cases today (383 files scanned, 6 anchor
# hits, none inside a fence), so it is left unhandled rather than fixed blind. Same for
# escaped \` and ``double-tick`` spans.
# Test-Quoted -- SHARED by H24-1 (Get-AnchorDate) and H24-3 (session-label).
# Deliberately a FUNCTION, not two inline copies: the citation trap is a CLASS, and the
# S123 review caught H24-3 shipping WITHOUT this guard in the very diff that proved the
# class exists. One greppable definition is how the next detector inherits the fix instead
# of re-earning it. If you add a detector that pattern-matches prose, call this.
function Test-Quoted {
param([string]$Line, [int]$Index)
return ((([regex]::Matches($Line.Substring(0, $Index), '`')).Count % 2) -eq 1)
}
function Get-AnchorDate {
param([string]$Path)
$ls = Get-Content -Path $Path -Encoding UTF8 -ErrorAction SilentlyContinue
if ($null -eq $ls) { return $null }
for ($i = 0; $i -lt $ls.Count; $i++) {
foreach ($rx in $AnchorPatterns) {
# Matches (all), not Match (first): one line may carry a quoted example
# BEFORE a live anchor. Taking only the first match would let the example
# shadow the real claim on that line.
foreach ($m in [regex]::Matches($ls[$i], $rx)) {
if (Test-Quoted $ls[$i] $m.Index) { continue } # inside `...` => mentioned, not used
$raw = $m.Groups[1].Value
$dt = [datetime]::MinValue
$ok = [datetime]::TryParseExact($raw, 'yyyy-MM-dd',
[Globalization.CultureInfo]::InvariantCulture,
[Globalization.DateTimeStyles]::None, [ref]$dt)
if ($ok) {
return [pscustomobject]@{ Date = $dt; Raw = $raw; Line = ($i + 1) }
}
# anchor present but date not a real calendar date -> keep looking
}
}
}
return $null
}
$anchored = @()
foreach ($f in $GovMd) {
$p = ($f.FullName -replace '/', '\')
$skip = $false
foreach ($frag in $TitleFreshSkip) { if ($p -ilike "*$frag*") { $skip = $true } }
if ($skip) { continue }
$a = Get-AnchorDate $f.FullName
if ($null -ne $a) {
$anchored += [pscustomobject]@{
Rel = (Rel $f.FullName); Date = $a.Date; Raw = $a.Raw; Line = $a.Line
}
}
}
if ($anchored.Count -eq 0) {
Write-Host ' [skip] no doc carries a known title/status anchor - nothing to age-compare' -ForegroundColor DarkGray
}
else {
$newest = ($anchored | Sort-Object Date -Descending | Select-Object -First 1)
Write-Host (" anchors parsed: {0} doc(s) ; moc-phai (newest governance milestone) = {1} from {2}:{3}" -f `
$anchored.Count, $newest.Raw, $newest.Rel, $newest.Line)
foreach ($a in ($anchored | Sort-Object Date -Descending)) {
Write-Host (" anchor {0} {1}:{2}" -f $a.Raw, $a.Rel, $a.Line) -ForegroundColor DarkGray
}
foreach ($a in $anchored) {
if ($a.Date -lt $newest.Date) {
$age = [int]($newest.Date - $a.Date).TotalDays
Write-Flag 'LOW' ("{0}:{1}" -f $a.Rel, $a.Line) `
("title-stale: anchor says {0} but newest governance milestone is {1} ({2}d behind)" -f $a.Raw, $newest.Raw, $age) `
'refresh the title/status anchor date, or state explicitly that the doc is frozen-historical'
}
}
}
# ---------------------------------------------------------------------------
# H24-3 - session-label lag (do-lech-nhan-phien) [NEW S123]
#
# WHY THIS EXISTS -- H24-1 has a PROVEN false-negative, and this is it.
# docs/STATUS.md:6 read "**Last updated:** 2026-07-15 (S119 ...)" while :35 read
# "## Recently Done (S122 ...)". Measured: S119 x3 hits in the mega-line, S120/S121/
# S122 = 0 hits => the header label had fallen 3 sessions behind the content.
# H24-1 CANNOT see this: it compares DATES, and the date 2026-07-15 was the NEWEST
# in the corpus => 0 flags. The doc was simultaneously the freshest thing on disk
# and wrong about itself.
#
# NOT a one-off: the same :6-lag was caught by hand at S116, S117, S118 and again at
# S123 -- 4 recurrences. Three of those were fixed by bumping the number, which is
# why it came back a 4th time. Per the owner's own S122 finding: what stops a repeat
# is a LAW THAT CAN SEE, not a memory that must remember. So the axis changes from
# DATE (H24-1) to SESSION LABEL (here).
#
# THE RULE: within ONE file, the "(S<N>)" on the **Last updated** line must not be
# older than the newest "(S<M>)" carried by a heading. Both numbers live in the same
# file, so there is no cross-file inference and no ratio-band -- a mismatch is wrong
# BY CONSTRUCTION. Hence MED, not the LOW that H24-1's noisier date-axis earns.
# -> HONEST CORRECTION (S123 review): an earlier draft justified MED with "0 proxy".
# That was WRONG. $labelN is the FIRST regex hit, which is a PROXY for "this file's
# OWN label" -- and it breaks precisely when the file QUOTES someone else's label.
# MED survives because Test-Quoted removes that failure mode, NOT because no proxy
# was ever there. Naming the proxy is the point; pretending it is absent is how the
# next reader stops looking for it.
#
# TWO BUGS THIS DETECTOR SHIPPED AND THE S123 REVIEW CAUGHT -- both worth remembering:
# (a) NO Test-Quoted guard. The same diff that added this detector ALSO added 30 lines
# proving "every doc written ABOUT the false-positive becomes one" -- and then built
# a new prose-matcher without the guard. Generation-2 of the very trap. The canonical
# trigger would have been the S123 adap-report DESCRIBING this detector.
# => the lesson is mechanical, not moral: patch a trap CLASS, then grep every
# same-class matcher IN THAT DIFF. A lesson sitting in context does not self-fire.
# (b) GREEDY '.*' took the LAST "(S<N>" on a line, not the MAX. Isolated repro:
# "## Tong hop (S122 ...) va lich su (S110 ...)" -> regex yielded S110, max is S122
# => could print "[ok] label S115 >= newest heading S110", a false-negative stated
# as a fact about the file. Fixed by scanning ALL matches per line and taking max.
# The 6/6 fault-inject missed it because every case put ONE "(S<N>" per heading:
# N/N PASS proves the axes TOUCHED, never the axis never tried. Ask instead:
# "which axis has no case at all?" (corpus has 0 such headings today => was LATENT).
#
# Measured @S123 on the live corpus (both directions, no tuning):
# docs/STATUS.md label S119 vs max-heading S122 -> 119 < 122 => FLAG (the real defect)
# docs/HANDOFF.md label S122 vs max-heading S84 -> 122 > 84 => silent
# HANDOFF needs NO special case: its only S-heading is an archive pointer
# ("Session detail cu (S84 -> tro ve truoc)"), and a pointer to old sessions is
# exactly what a CURRENT label should outrank. The rule reads that correctly on its own.
#
# HONEST LIMIT: this catches a label that lags its OWN headings. A file whose label
# AND headings are both stale together stays silent -- consistency is not freshness.
# That gap is real and left open rather than papered over with a second proxy.
# ---------------------------------------------------------------------------
Write-Section 'H24-3 - session-label lag'
$SessLabelRx = '\*\*Last updated:\*\*[^(]*\(S(\d+)'
# Heading side is scanned in TWO steps, NOT one regex: '^#{2,}\s' decides "is this a
# heading?", then EVERY '\(S(\d+)' on that line is collected and max-ed. The old
# single-regex '^#{2,}\s+.*\(S(\d+)' looked equivalent and was not -- greedy '.*' made it
# "the LAST (S<N> on the line", which is a different question from "the newest".
$SessHeadingLineRx = '^#{2,}\s'
$SessNumRx = '\(S(\d+)'
$sessChecked = 0
foreach ($f in $GovMd) {
$p = ($f.FullName -replace '/', '\')
$skip = $false
# Same frozen-by-design carve-out as H24-1: an archive's old label IS the record.
foreach ($frag in $TitleFreshSkip) { if ($p -ilike "*$frag*") { $skip = $true } }
if ($skip) { continue }
$ls = Get-Content -Path $f.FullName -Encoding UTF8 -ErrorAction SilentlyContinue
if ($null -eq $ls) { continue }
$labelN = $null; $labelLine = 0
$maxHeadN = $null; $maxHeadLine = 0
for ($i = 0; $i -lt $ls.Count; $i++) {
# LABEL: first UNQUOTED hit wins. Matches (all) + Test-Quoted, so a line that
# quotes an example label before carrying a real one still yields the real one.
if ($null -eq $labelN) {
foreach ($lm in [regex]::Matches($ls[$i], $SessLabelRx)) {
if (Test-Quoted $ls[$i] $lm.Index) { continue }
$labelN = [int]$lm.Groups[1].Value; $labelLine = $i + 1
break
}
}
# HEADING: MAX over ALL unquoted hits ON the line (not the first, not the last).
# $SessHeadingRx anchors '^#{2,}' so it only matches at line start; iterating
# Matches() would re-scan the same line, so strip the anchor and scan the tail.
if ($ls[$i] -match $SessHeadingLineRx) {
foreach ($hm in [regex]::Matches($ls[$i], $SessNumRx)) {
if (Test-Quoted $ls[$i] $hm.Index) { continue }
$hn = [int]$hm.Groups[1].Value
if (($null -eq $maxHeadN) -or ($hn -gt $maxHeadN)) { $maxHeadN = $hn; $maxHeadLine = $i + 1 }
}
}
}
# No label, or no S-heading to compare against => this doc makes no session claim.
if (($null -eq $labelN) -or ($null -eq $maxHeadN)) { continue }
$sessChecked++
if ($labelN -lt $maxHeadN) {
Write-Flag 'MED' ("{0}:{1}" -f (Rel $f.FullName), $labelLine) `
("session-label lag: header label says S{0} but the file's own newest heading is S{1} (line {2}, {3} session(s) ahead)" -f `
$labelN, $maxHeadN, $maxHeadLine, ($maxHeadN - $labelN)) `
'bump the header label to match the newest section, OR drop the session label from the header so it cannot go stale (B1 collapse)'
}
else {
Write-Host (" [ok] {0}: label S{1} >= newest heading S{2}" -f (Rel $f.FullName), $labelN, $maxHeadN) -ForegroundColor DarkGray
}
}
if ($sessChecked -eq 0) {
Write-Host ' [skip] no doc carries BOTH a session label and an S-heading - nothing to compare' -ForegroundColor DarkGray
}
# ---------------------------------------------------------------------------
# H24-2 - carry-age (INFORM-only)
# A [carry:<slug>] key that survives >= M CONSECUTIVE most-recent carry-lines is
# "aged" -- it has outlived a full review cadence without being closed.
#
# "carry-line" (dong-carry) = a LOGIC segment, NOT a physical line. docs/HANDOFF.md
# is 12 physical lines but line 5 alone is a ~46.5K-char mega-line holding 45
# "NEXT anh" / "NEXT em" blocks (newest-first). Get-Content -TotalCount would see
# ONE line and measure nothing, so we read -Raw and split on the NEXT markers.
#
# Streak counts only over lines that HAVE carry: a session that emitted no carry
# does NOT break a chain. A key resets ONLY by being absent from a line that HAS
# carry. Only keys on the newest carry-line can hold a live streak (a key gone from
# the newest one is closed, not aged).
#
# M comes from config, NEVER hardcoded: a hardcoded cadence is exactly the
# single-source violation H24 forbids. Missing config/key => FAIL-LOUD + measure
# nothing. Scope note: this "no hardcoded cadence" rule is about the CADENCE number
# only -- pre-existing constants elsewhere in this script are other detectors'
# owner-signed numbers and are out of scope.
# ---------------------------------------------------------------------------
Write-Section 'H24-2 - carry-age (INFORM-only)'
# Canonical config path per owner-decision Q2. Probe agent-memory/ FIRST (that is
# where the live memory-budget.json actually is on disk); the bare .claude/ path is
# a fallback in case W2 lands the key at the shorter path some docs abbreviate to.
$cfgCandidates = @(
(Join-Path $RepoRoot '.claude\agent-memory\memory-budget.json'),
(Join-Path $RepoRoot '.claude\memory-budget.json')
)
$cfgPath = $null
foreach ($c in $cfgCandidates) { if ($null -eq $cfgPath) { if (Test-Path $c) { $cfgPath = $c } } }
# NOTE: named $CadenceM, NOT $M. PowerShell variable names are CASE-INSENSITIVE, so a
# bare $M is the SAME variable as the $m used by the regex-match loops below -- the
# match object silently clobbered the cadence, making ($null -eq $M) false and turning
# the fail-loud path into "Could not compare 1 to [carry:bvaau]". Keep the long name.
$CadenceM = $null
if ($null -eq $cfgPath) {
Write-Flag 'MED' '.claude/agent-memory/memory-budget.json' `
'carry-age config NOT FOUND at any candidate path - cadence unresolved, carry-age measuring NOTHING' `
'create memory-budget.json carrying h24_cadence { light_every, deep_every, jump_on_class_repeat }'
}
else {
Write-Host (" config resolved: {0}" -f (Rel $cfgPath))
$cfg = $null
try { $cfg = (Get-Content -Path $cfgPath -Raw -Encoding UTF8 | ConvertFrom-Json) }
catch { $cfg = $null }
if ($null -eq $cfg) {
Write-Flag 'MED' (Rel $cfgPath) `
'carry-age config unparseable as JSON - cadence unresolved, carry-age measuring NOTHING' `
'fix the JSON syntax'
}
elseif ($null -eq $cfg.h24_cadence) {
Write-Flag 'MED' (Rel $cfgPath) `
'h24_cadence missing - W2 chua land => carry-age cadence UNRESOLVED, measuring NOTHING (no default is assumed: a hardcoded cadence would violate H24 single-source)' `
'W2: add h24_cadence { light_every, deep_every, jump_on_class_repeat }'
}
elseif ($null -eq $cfg.h24_cadence.light_every) {
Write-Flag 'MED' (Rel $cfgPath) `
'h24_cadence present but sub-key light_every missing - carry-age uses light_every as M, measuring NOTHING' `
'W2: add h24_cadence.light_every (the light-audit cadence a carry must not outlive)'
}
else {
$CadenceM = [int]$cfg.h24_cadence.light_every
Write-Host (" M = h24_cadence.light_every = {0} (read from config, not hardcoded)" -f $CadenceM)
}
}
$handoffPath = Join-Path $RepoRoot 'docs\HANDOFF.md'
if (-not (Test-Path $handoffPath)) {
Write-Host ' (no docs/HANDOFF.md - no carry surface, skip)' -ForegroundColor DarkGray
}
else {
$raw = Get-Content -Path $handoffPath -Raw -Encoding UTF8
# "NEXT anh" / "NEXT em" are pure ASCII (no diacritics) -> safe as a literal here.
$marks = [regex]::Matches($raw, 'NEXT\s+(?:anh|em)')
$segs = @()
for ($i = 0; $i -lt $marks.Count; $i++) {
$start = $marks[$i].Index
$end = if ($i + 1 -lt $marks.Count) { $marks[$i + 1].Index } else { $raw.Length }
$segs += $raw.Substring($start, $end - $start)
}
# Key charset excludes '<' so the FORMAT-SPEC literal "[carry:<slug>]" (prose in
# HANDOFF describing the convention) is never counted as a real key -- a detector
# that flags the sentence DEFINING its own pattern is the self-reference trap.
$carryRx = '\[carry:([a-z0-9][a-z0-9._-]*)\]'
$carryLines = @()
foreach ($s in $segs) {
$ks = @()
foreach ($cm in [regex]::Matches($s, $carryRx)) { $ks += $cm.Groups[1].Value }
if ($ks.Count -gt 0) { $carryLines += , (@($ks | Select-Object -Unique)) }
}
Write-Host (" HANDOFF logic-segments (NEXT anh/em) = {0} ; of those, carry-lines = {1}" -f `
$segs.Count, $carryLines.Count)
if ($carryLines.Count -eq 0) {
Write-Host ' (0 carry-line - no [carry:<slug>] stamped yet, nothing to age)' -ForegroundColor DarkGray
}
else {
foreach ($k in $carryLines[0]) {
$n = 0
for ($i = 0; $i -lt $carryLines.Count; $i++) {
if ($carryLines[$i] -contains $k) { $n++ } else { break }
}
if ($null -eq $CadenceM) {
Write-Host (" [inform] carry '{0}' streak={1} carry-line(s) ; M unresolved -> NO aged/not-aged verdict" -f $k, $n) -ForegroundColor DarkGray
}
elseif ($n -ge $CadenceM) {
Write-Flag 'LOW' ('docs/HANDOFF.md:5') `
("gap-carry-aged [INFORM]: carry '{0}' alive across {1} consecutive carry-lines (>= M={2}) - owner may be holding it deliberately" -f $k, $n, $CadenceM) `
("close it, or re-scope it; INFORM-only - no action forced")
}
else {
Write-Host (" [ok] carry '{0}' streak={1} < M={2}" -f $k, $n, $CadenceM) -ForegroundColor DarkGray
}
}
}
}
# ---------------------------------------------------------------------------
# H25-closeout-ritual (GAP-2) : did the last 3 session-close commits each leave a
# full ritual trace? A close that skips STATUS / HANDOFF / a NEW session-log / an
# agent-memory delta is silent governance drift (the memory-loss class).
#
# WINDOW, not per-commit (T4a, measured): the ritual delta does NOT sit inside the
# closeout commit alone. The Stop-hook 'wal: flush' carries agent-memory deltas in
# EARLIER commits, and STATUS/HANDOFF are often bumped a commit or two before the
# close. Scoring the closeout commit by itself FAILs healthy data 2/3. So each close
# is scored over the UNION of every commit since the PREVIOUS close: the half-open
# range (prev-close .. this-close], via git log --name-only.
#
# The NEW-session book uses --diff-filter=A (an ADDED path): editing an old session
# log is not opening this session's log. The other three books accept any touch
# (STATUS/HANDOFF/diaries are appended, not recreated).
#
# HONEST LIMIT (surfaced, NOT silenced): a tail-close commit whose previous close is
# its own parent AND the same session batch yields a 1-commit window; that batch's
# real ritual lives in the excluded lower-bound commit, so the tail reads incomplete
# = a FALSE POSITIVE. The canonical spec baseline calls for per-session-label folding
# of same-batch closes; this build is per-commit as handed. Do NOT special-case it to
# green a report -- classify the flag and let the owner choose the grouping.
#
# git-based, so it honours -RepoRoot (fault-injection runs on a temp git tree). A
# RepoRoot that is not a git work-tree SKIPs with a reason; a probe never crashes.
# ---------------------------------------------------------------------------
Write-Section 'H25-closeout-ritual (GAP-2)'
# Subject shape of a session-close commit. Held in a variable (used by -match on git
# SUBJECTS, never on any scanned file) so no prose copy exists to self-trip a matcher.
$CloseoutSubjectRx = '^\[CLAUDE\] Docs: S\d+.*(?:closeout|session-end)'
$closeouts = @()
$gitTree = Test-Path (Join-Path $RepoRoot '.git')
if ($gitTree) {
try {
$logRaw = & git -C $RepoRoot log --format='%H|%s' --max-count=400
} catch { $logRaw = $null }
if ($logRaw) {
foreach ($ln in $logRaw) {
if ([string]::IsNullOrWhiteSpace($ln)) { continue }
$parts = $ln -split '\|', 2
if ($parts.Count -lt 2) { continue }
if ($parts[1] -match $CloseoutSubjectRx) {
$lab = if ($parts[1] -match 'S(\d+)') { 'S' + $Matches[1] } else { 'S?' }
$closeouts += [pscustomobject]@{ Hash = $parts[0]; Short = $parts[0].Substring(0, 7); Label = $lab }
}
}
}
}
if (-not $gitTree) {
Write-Host ' [skip] RepoRoot is not a git work-tree - cannot score closeouts' -ForegroundColor DarkGray
}
elseif ($closeouts.Count -eq 0) {
Write-Host ' [skip] no commit matches the closeout subject shape - nothing to score' -ForegroundColor DarkGray
}
else {
$take = [Math]::Min(3, $closeouts.Count)
Write-Host (" closeouts found: {0} ; scoring {1} most-recent (union-window per close)" -f $closeouts.Count, $take)
for ($i = 0; $i -lt $take; $i++) {
$cur = $closeouts[$i]
if ($i + 1 -ge $closeouts.Count) {
Write-Host (" [skip] {0} {1}: no earlier close to open the window (oldest close in history) - not scored, not flagged" -f $cur.Short, $cur.Label) -ForegroundColor DarkGray
continue
}
$prev = $closeouts[$i + 1]
$range = ("{0}..{1}" -f $prev.Hash, $cur.Hash)
$union = @()
try { $u = & git -C $RepoRoot log --name-only --pretty=format: $range } catch { $u = $null }
foreach ($p in $u) { if (-not [string]::IsNullOrWhiteSpace($p)) { $union += $p.Trim() } }
$newSess = @()
try { $ns = & git -C $RepoRoot log --diff-filter=A --name-only --pretty=format: $range '--' 'docs/changelog/sessions/' } catch { $ns = $null }
foreach ($p in $ns) { if (-not [string]::IsNullOrWhiteSpace($p)) { $newSess += $p.Trim() } }
$missing = @()
if (-not ($union -contains 'docs/STATUS.md')) { $missing += 'docs/STATUS.md' }
if (-not ($union -contains 'docs/HANDOFF.md')) { $missing += 'docs/HANDOFF.md' }
if ($newSess.Count -eq 0) { $missing += 'docs/changelog/sessions/*(NEW,--diff-filter=A)' }
if (@($union | Where-Object { $_ -match '^\.claude/agent-memory/' }).Count -eq 0) { $missing += '.claude/agent-memory/**' }
if ($missing.Count -eq 0) {
Write-Host (" [ok] {0} {1}: union ({2}..{3}] has all 4 ritual books" -f $cur.Short, $cur.Label, $prev.Short, $cur.Short) -ForegroundColor DarkGray
}
else {
Write-Flag 'MED' ("git:{0} ({1})" -f $cur.Short, $cur.Label) `
("closeout-ritual gap: window ({0}..{1}] missing {2} of 4 books -> {3}" -f $prev.Short, $cur.Short, $missing.Count, ($missing -join ', ')) `
'the session-close (or its window since the prior close) must touch STATUS + HANDOFF + a NEW session-log + an agent-memory diary'
}
}
}
# ---------------------------------------------------------------------------
# H25-role-notebook (GAP-3) : every role that ACTUALLY RAN must leave a diary
# (.claude/agent-memory/<role>/MEMORY.md, byte>0). A role defined-but-never-spawned
# is NOT a defect, so the check is gated on evidence-of-run and measures CONTENT not
# NAME (S122): a sub-file whose prefix is not an exact roster role is LISTED as
# UNMAPPED, never flagged (no name-guessing). A zero-byte diary IS flagged
# (anti-Goodhart: an empty notebook is not a notebook; touching a file to green the
# check must still fail). Byte size via (Get-Item).Length -- Get-Content-count is
# FORBIDDEN (a no-BOM file miscounts VN text x2-3, bug E-010/S130).
# ---------------------------------------------------------------------------
Write-Section 'H25-role-notebook (GAP-3)'
$agentsDir = Join-Path $RepoRoot '.claude\agents'
$roster = @()
if (Test-Path $agentsDir) {
$roster = @(Get-ChildItem -Path $agentsDir -Filter *.md -File -ErrorAction SilentlyContinue |
Where-Object { $_.BaseName -ne 'README' } | ForEach-Object { $_.BaseName })
}
$rosterSet = @{}
foreach ($r in $roster) { $rosterSet[$r] = $true }
if ($roster.Count -eq 0) {
Write-Host ' [skip] no .claude/agents/*.md roster - nothing to check' -ForegroundColor DarkGray
}
else {
# Evidence-of-run: scan runs/*/sub-*.md and map each filename prefix to a roster role.
# Two-step greedy parse: 'sub-<role>-<numeric-idx>.md' first, else 'sub-<rest>.md'.
$runsDir = Join-Path $RepoRoot '.claude\workflows\runs'
$ran = @{} # role -> ran (exact roster match)
$unmapped = @{} # prefix -> seen (not an exact roster role)
if (Test-Path $runsDir) {
$subs = Get-ChildItem -Path $runsDir -Recurse -Filter 'sub-*.md' -File -ErrorAction SilentlyContinue
foreach ($s in $subs) {
$cand = $null
if ($s.Name -match '^sub-(.+)-\d+\.md$') { $cand = $Matches[1] }
elseif ($s.Name -match '^sub-(.+)\.md$') { $cand = $Matches[1] }
if ($null -eq $cand) { continue }
if ($rosterSet.ContainsKey($cand)) { $ran[$cand] = $true } else { $unmapped[$cand] = $true }
}
}
# has-run(role) = a mapped sub-file OR a diary directory already on disk (any size).
$memRoot = Join-Path $RepoRoot '.claude\agent-memory'
$okCount = 0; $flagged = 0; $inert = 0
foreach ($role in ($roster | Sort-Object)) {
$diary = Join-Path (Join-Path $memRoot $role) 'MEMORY.md'
$diaryExists = Test-Path -LiteralPath $diary
$hasRun = ($ran.ContainsKey($role)) -or $diaryExists
if (-not $hasRun) {
$inert++
continue
}
$bytes = if ($diaryExists) { (Get-Item -LiteralPath $diary).Length } else { -1 }
if ($diaryExists -and $bytes -gt 0) {
$okCount++
}
else {
$why = if (-not $diaryExists) { 'MISSING' } else { '0-byte (empty notebook)' }
Write-Flag 'MED' ("agent-memory/{0}/MEMORY.md" -f $role) `
("role-notebook gap: role '{0}' has run-evidence but its diary is {1}" -f $role, $why) `
("write a non-empty agent-memory/{0}/MEMORY.md (harvest the role slice at session-end)" -f $role)
$flagged++
}
}
Write-Host (" roster={0} ; diaries-ok={1} ; flagged={2} ; inert(defined-not-run)={3}" -f $roster.Count, $okCount, $flagged, $inert)
if ($unmapped.Count -gt 0) {
$ulist = ($unmapped.Keys | Sort-Object) -join ', '
Write-Host (" UNMAPPED sub-file prefixes ({0}) [INFORM, not flagged - measure content not name, S122]:" -f $unmapped.Count) -ForegroundColor DarkGray
Write-Host (" {0}" -f $ulist) -ForegroundColor DarkGray
}
}
# ---------------------------------------------------------------------------
# Summary + C4 self-exclusion audit (RUNTIME proof)
# ---------------------------------------------------------------------------
Write-Section 'Summary'
# Confirm 0 self-match: the detector script must never appear in the scanned set.
$selfPath = (Join-Path $RepoRoot 'scripts\governance-detectors.ps1') -replace '/', '\'
$selfInScan = @($GovMd | Where-Object { ($_.FullName -replace '/', '\') -ieq $selfPath }).Count
# (governance-detectors.ps1 is .ps1 not .md so never in $GovMd; this asserts the
# invariant explicitly. Also assert none of the excluded dirs leaked in.)
$leaked = @($GovMd | Where-Object { Test-Excluded $_.FullName }).Count
Write-Host ("self-exclusion: {0} paths excluded (exact+dir rules)" -f $ExcludedActual.Count)
foreach ($e in $ExcludedActual) { Write-Host (" - excluded: {0}" -f (Rel $e)) -ForegroundColor DarkGray }
Write-Host ("self-match check: governance-detectors.ps1 in scan = {0} ; leaked excluded files in scan = {1}" -f $selfInScan, $leaked)
if ($selfInScan -eq 0 -and $leaked -eq 0) {
Write-Host ' [OK] 0 self-match (C4 satisfied)' -ForegroundColor Green
} else {
Write-Host ' [!] self-exclusion LEAK - investigate Test-Excluded rules' -ForegroundColor Red
}
Write-Host ''
Write-Host ("TOTAL FLAGS: {0}" -f $script:FlagCount) -ForegroundColor Cyan
Write-Host 'NOTE: DETECT-only lowering net. Exit 0 always (never fails build). FLAGs are advisory.' -ForegroundColor DarkGray
exit 0