ckb/.agents/skills/ckb-lint/scripts/lint_quick.ps1
Michał Kopeć 7b812e545b Template 1.11.1: fix five defects reported downstream
Four deterministic-script defects plus a contract gap, all reported by a
downstream KB running 1.11.0. None of them crashed; each produced confident,
wrong output, which is why they went unnoticed.

retrieve_candidates.py:
- load_pages() walked rglob unsorted, so tests/expected/retrieve.json encoded
  one machine's directory order and the smoke test failed on a clean clone.
- cited_by used setdefault, crediting a shared source to whichever page was
  walked first and dropping the source from the results entirely, so the other
  citing pages reported corroborated_by: []. Now every citing page is credited.

lint_report.py:
- check 12 reported a cited directory as "does not exist", because is_file()
  is false for a directory. Citing a subtree is now explicitly legal and
  carries no fingerprint; same fix in lint_quick.sh and lint_quick.ps1.
- check 8 keyed log entries on timestamp + file with the action type dropped,
  so a Rule B POINTER was indistinguishable from a duplicate of the entry it
  points at. POINTER is now exempt; genuine duplicates still fire.
- check 13 required a backticked path, so "— Chat conversation, Name, date"
  counted as unattributed although AGENTS.md lists it as a first-class source.
  Attribution and verifiability are now separate questions.

AGENTS.md documents both resolved contract gaps: directory citations, and the
two legal attribution shapes. The fixture KB gained coverage for all three lint
defects — each finding fires under the old script and is silent under the new.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-09 21:47:53 +02:00

133 lines
6.8 KiB
PowerShell

# Copyright 2026 Michał Kopeć
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# No-Python fallback for `lint_report.py --quick` (Rule E session-start check).
#
# powershell -ExecutionPolicy Bypass -File lint_quick.ps1 [-Today YYYY-MM-DD]
#
# Run from the repository root. Read-only. Prints the same one-line summary
# shape as the Python script for three of its four quick checks:
# - malformed pages with no/unclosed frontmatter or no `type`
# - past freshness `last_updated` + `freshness_window_days` < today
# - source drift `## Sources` bullets whose sha256 no longer matches
# The fourth (diverged crux quotes) needs the full checker and is skipped;
# the summary says so. Exit 0 when clean, 1 when anything was flagged.
#
# Works on Windows PowerShell 5.1 and PowerShell 7+. Prefer the Python script
# whenever an interpreter is available — it is the reference implementation.
[CmdletBinding()]
param([string]$Today = "")
$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath "wiki" -PathType Container)) {
[Console]::Error.WriteLine("error: no wiki/ directory here — run from the repository root"); exit 2
}
function Parse-Date([string]$s) {
$s = $s.Trim()
if ($s -notmatch '^\d{4}-\d{2}-\d{2}$') { return $null }
try { return [datetime]::ParseExact($s, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture) } catch { return $null }
}
if ($Today -eq "") { $todayDate = (Get-Date).Date } else {
$todayDate = Parse-Date $Today
if ($null -eq $todayDate) { [Console]::Error.WriteLine("error: -Today is not a YYYY-MM-DD date: $Today"); exit 2 }
}
function Unquote([string]$v) {
$v = $v.Trim()
if ($v.Length -ge 2 -and $v[0] -eq $v[-1] -and ($v[0] -eq '"' -or $v[0] -eq "'")) { return $v.Substring(1, $v.Length - 2) }
return $v
}
$malformed = 0; $stale = 0; $drift = 0
$root = (Get-Location).Path
# Trees: wiki/ plus every connector-backed lib (has source.yaml).
$trees = @("wiki")
if (Test-Path -LiteralPath "libs" -PathType Container) {
Get-ChildItem -LiteralPath "libs" -Directory | ForEach-Object {
if (Test-Path -LiteralPath (Join-Path $_.FullName "source.yaml")) { $trees += "libs/$($_.Name)" }
}
}
foreach ($tree in $trees) {
$files = Get-ChildItem -LiteralPath $tree -Recurse -File -Filter *.md | Sort-Object FullName
foreach ($file in $files) {
if ($file.Name -eq "index.md" -or $file.Name -eq "log.md") { continue }
$rel = $file.FullName.Substring($root.Length).TrimStart('\', '/')
if (($rel -split '[\\/]') | Where-Object { $_.StartsWith('.') }) { continue }
$text = [IO.File]::ReadAllText($file.FullName) -replace "`r`n", "`n"
$lines = $text -split "`n"
# ---- frontmatter --------------------------------------------------
if ($lines.Count -eq 0 -or $lines[0] -ne '---') { $malformed++; continue }
$end = -1
for ($i = 1; $i -lt $lines.Count; $i++) { if ($lines[$i] -eq '---') { $end = $i; break } }
if ($end -lt 0) { $malformed++; continue }
$fm = @{}; $bad = $false
for ($i = 1; $i -lt $end; $i++) {
$line = $lines[$i]; $stripped = $line.Trim()
if ($stripped -eq '' -or $stripped.StartsWith('#')) { continue }
if ($line -match '^\s') { $bad = $true; break }
if ($stripped -notmatch ':') { $bad = $true; break }
$idx = $stripped.IndexOf(':')
$fm[$stripped.Substring(0, $idx).Trim()] = Unquote $stripped.Substring($idx + 1)
}
if ($bad) { $malformed++; continue }
if (-not $fm.ContainsKey('type') -or [string]::IsNullOrWhiteSpace($fm['type'])) { $malformed++; continue }
$body = ($lines | Select-Object -Skip ($end + 1)) -join "`n"
# ---- freshness ----------------------------------------------------
$win = $null
if ($fm.ContainsKey('freshness_window_days') -and $fm['freshness_window_days'] -match '^\s*\d+\s*$') { $win = [int]$fm['freshness_window_days'] }
$updRaw = if ($fm.ContainsKey('last_updated')) { $fm['last_updated'] } else { '' }
$upd = if ($updRaw -ne '') { Parse-Date $updRaw } else { $null }
if ($updRaw -ne '' -and $null -eq $upd) { $stale++ }
elseif ($null -ne $win -and $null -ne $upd) {
if (($todayDate - $upd).Days -gt $win) { $stale++ }
}
# ---- source fingerprints -----------------------------------------
$secStart = -1; $bodyLines = $body -split "`n"
for ($i = 0; $i -lt $bodyLines.Count; $i++) { if ($bodyLines[$i] -match '^## Sources\s*$') { $secStart = $i; break } }
if ($secStart -lt 0) { continue }
$section = @()
for ($i = $secStart + 1; $i -lt $bodyLines.Count; $i++) { if ($bodyLines[$i] -match '^## ') { break }; $section += $bodyLines[$i] }
$bullets = $section | Where-Object { $_ -match '^\s*[-*]\s+`([^`]+)`(.*)$' }
if (-not $bullets) { $drift++; continue }
foreach ($b in $bullets) {
if ($b -notmatch '^\s*[-*]\s+`([^`]+)`(.*)$') { continue }
$cited = $Matches[1].Trim(); $rest = $Matches[2]
if ($cited -match '^[a-z][a-z0-9+.-]*://') { continue }
$target = Join-Path $root $cited.TrimStart('/')
if (-not (Test-Path -LiteralPath $target)) { $target = Join-Path (Join-Path $root $tree) $cited.TrimStart('/') }
# A cited subtree is legal but has no single digest to recompute.
if (Test-Path -LiteralPath $target -PathType Container) { continue }
if (-not (Test-Path -LiteralPath $target -PathType Leaf)) { $drift++; continue }
if ($rest -notmatch '\b(sha256|etag|mtime):([^\s,)]+)') { $drift++; continue }
if ($Matches[1] -ne 'sha256') { continue }
$recorded = $Matches[2].ToLowerInvariant()
try { $actual = (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash.ToLowerInvariant() } catch { $drift++; continue }
if (-not $actual.StartsWith($recorded)) { $drift++ }
}
}
}
$flagged = @()
if ($malformed) { $flagged += "$malformed malformed" }
if ($stale) { $flagged += "$stale past freshness window" }
if ($drift) { $flagged += "$drift source drift" }
$note = " (fallback: crux quotes not checked — install Python for the full check)"
if ($flagged.Count -eq 0) { Write-Output "ckb check: clean$note"; exit 0 }
Write-Output ("ckb check: " + ($flagged -join ", ") + " — run `"lint`" for detail" + $note)
exit 1