This commit is contained in:
eddiesoehnel committed 2026-10-14 10:45:26 -06:00
commit 4af224804a
39 files changed
+5534

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
# Scripts and validation
Python 3.10+ is required. Core scripts use the standard library. Optional full JSON Schema checks require jsonschema; absence is reported as a validation limitation. No credential or paid API setup is needed for these scripts.
| Script | Function | Writes |
|---|---|---|
| build_content_index.py | Catalog declared authoritative files and dated reports with stable IDs | content-index.json only |
| rollup.py | Preserve report bodies in a cumulative rollup, then refresh catalog | reports/seo-geo-research-rollup.md and content-index.json |
| validate_discovery.py | Metadata alignment, local links, index freshness, schemas when available | None |
| audit_repository.py | Template skill-workflow structural audit | None |
| validate_pack.py | Skill contract/JSON checks | None |
| test_rollup.py | Rollup preservation and idempotence regressions | Temporary fixtures inside script directory |
Run commands from the repository root:
```text
python -B scripts/build_content_index.py
python -B scripts/rollup.py
python -B scripts/audit_repository.py . --profile skill-workflow --json
python -B scripts/validate_discovery.py
python -B scripts/validate_pack.py
python -B scripts/test_rollup.py
python -B -m unittest discover -s tests -p "test_*.py"
```
build_content_index.py, rollup.py and validate_discovery.py accept --root PATH. Index generation validates paths, uniqueness and relationships before atomic replacement; a failure preserves the previous index. Rebuilds preserve existing publication lifecycle status and timestamps; new dated reports start as drafts. Historical archive is one file, and rollup is derived. Original template audit/schema attribution: AI-Ready Repository Template, Eddie Soehnel, MIT, local version 0.3.0.
+370
View File
@@ -0,0 +1,370 @@
#!/usr/bin/env python3
"""Read-only structural audit for an AI-ready repository."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import re
import sys
PROFILES = {
"documentation-guide": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CITATION.cff",
"docs",
},
"skill-workflow": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"AGENTS.md",
"skills.md",
"skills",
"templates",
"examples",
},
"software-automation": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CONTRIBUTING.md",
"SECURITY.md",
"AGENTS.md",
"docs",
"scripts",
"tests",
},
"dataset": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CITATION.cff",
"data",
"schemas",
"docs",
},
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repository", type=Path, help="Repository root to inspect")
parser.add_argument(
"--profile",
choices=sorted(PROFILES),
required=True,
help="Approved repository profile",
)
parser.add_argument("--json", action="store_true", help="Emit JSON")
return parser.parse_args()
def read_version_from_citation(path: Path) -> str | None:
if not path.is_file():
return None
match = re.search(
r"(?m)^version:\s*[\"']?([^\"'\s#]+)",
path.read_text(encoding="utf-8-sig"),
)
return match.group(1) if match else None
def audit_content_index(root: Path, findings: list[dict[str, str]]) -> None:
path = root / "content-index.json"
if not path.is_file():
return
try:
index = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append({"level": "error", "message": f"content-index.json is invalid: {exc}"})
return
items = index.get("items")
if not isinstance(items, list):
findings.append(
{"level": "error", "message": "content-index.json items must be an array"}
)
return
content_ids: set[str] = set()
paths: set[str] = set()
for position, item in enumerate(items):
if not isinstance(item, dict):
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} must be an object",
}
)
continue
content_id = item.get("content_id")
declared = item.get("path")
if not content_id:
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} lacks content_id",
}
)
elif content_id in content_ids:
findings.append(
{
"level": "error",
"message": f"Duplicate content_id in content-index.json: {content_id}",
}
)
else:
content_ids.add(content_id)
if not declared:
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} lacks path",
}
)
elif declared in paths:
findings.append(
{
"level": "error",
"message": f"Duplicate path in content-index.json: {declared}",
}
)
else:
paths.add(declared)
declared_path = Path(declared)
if (
declared_path.is_absolute()
or ".." in declared_path.parts
or not (root / declared_path).is_file()
):
findings.append(
{
"level": "error",
"message": f"Indexed content path does not exist or is unsafe: {declared}",
}
)
def audit(root: Path, profile: str) -> dict:
findings: list[dict[str, str]] = []
if not root.is_dir():
return {
"repository": str(root),
"profile": profile,
"passed": False,
"findings": [{"level": "error", "message": "Repository path is not a directory"}],
}
for relative in sorted(PROFILES[profile]):
if not (root / relative).exists():
findings.append({"level": "error", "message": f"Missing required path: {relative}"})
manifest_path = root / "repository.json"
manifest = None
if manifest_path.is_file():
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append({"level": "error", "message": f"repository.json is invalid: {exc}"})
else:
for key in ("schema_version", "repository_id", "title", "description", "version", "entrypoints"):
if key not in manifest:
findings.append({"level": "error", "message": f"repository.json lacks key: {key}"})
entrypoints = manifest.get("entrypoints", {})
if isinstance(entrypoints, dict):
for audience in ("human", "ai"):
declared = entrypoints.get(audience)
if not declared:
findings.append(
{"level": "error", "message": f"Missing {audience} entrypoint declaration"}
)
elif not (root / declared).exists():
findings.append(
{
"level": "error",
"message": f"Declared {audience} entrypoint does not exist: {declared}",
}
)
else:
findings.append({"level": "error", "message": "entrypoints must be an object"})
variables_path = root / "repository-variables.json"
variables = None
if variables_path.is_file():
try:
variables = json.loads(variables_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append(
{"level": "error", "message": f"repository-variables.json is invalid: {exc}"}
)
else:
for key in (
"schema_version",
"repository_profile",
"identity",
"repository",
"rights",
"skill_defaults",
"verified_by",
"verified_at",
):
if key not in variables:
findings.append(
{
"level": "error",
"message": f"repository-variables.json lacks key: {key}",
}
)
if manifest and variables:
identity = variables.get("identity", {})
variable_authors = [
item.get("name")
for item in identity.get("authors", [])
if isinstance(item, dict)
]
manifest_authors = [
item.get("name")
for item in manifest.get("authors", [])
if isinstance(item, dict)
]
comparisons = (
("authors", variable_authors, manifest_authors),
(
"publisher",
identity.get("publisher", {}).get("name"),
manifest.get("publisher", {}).get("name"),
),
(
"maintainer",
identity.get("maintainer", {}).get("name"),
manifest.get("maintenance", {}).get("maintainer"),
),
(
"repository",
variables.get("repository"),
{
key: manifest.get(key)
for key in (
"repository_id",
"name",
"title",
"canonical_url",
"organization",
)
},
),
(
"rights",
variables.get("rights"),
{
key: manifest.get("rights", {}).get(key)
for key in ("license", "license_file")
},
),
)
for label, variable_value, manifest_value in comparisons:
if variable_value != manifest_value:
findings.append(
{
"level": "error",
"message": (
f"{label} differs between repository-variables.json "
"and repository.json"
),
}
)
if variables and variables.get("repository_profile") != profile:
findings.append(
{
"level": "error",
"message": (
"repository_profile differs between repository-variables.json "
f"({variables.get('repository_profile')}) and requested audit ({profile})"
),
}
)
audit_content_index(root, findings)
version_path = root / "VERSION"
version = version_path.read_text(encoding="utf-8-sig").strip() if version_path.is_file() else None
if version and manifest and manifest.get("version") != version:
findings.append(
{
"level": "error",
"message": f"VERSION ({version}) differs from repository.json ({manifest.get('version')})",
}
)
citation_version = read_version_from_citation(root / "CITATION.cff")
if version and citation_version and citation_version != version:
findings.append(
{
"level": "error",
"message": f"VERSION ({version}) differs from CITATION.cff ({citation_version})",
}
)
readme = root / "README.md"
if readme.is_file() and not readme.read_text(encoding="utf-8-sig").strip():
findings.append({"level": "error", "message": "README.md is empty"})
return {
"repository": str(root.resolve()),
"profile": profile,
"passed": not any(item["level"] == "error" for item in findings),
"findings": findings,
}
def emit_markdown(result: dict) -> None:
print(f"# Repository Audit\n\n- Repository: `{result['repository']}`")
print(f"- Profile: `{result['profile']}`")
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
print("\n## Findings")
if not result["findings"]:
print("\n- No structural errors found.")
else:
for finding in result["findings"]:
print(f"\n- {finding['level'].upper()}: {finding['message']}")
def main() -> int:
args = parse_args()
result = audit(args.repository, args.profile)
if args.json:
print(json.dumps(result, indent=2))
else:
emit_markdown(result)
return 0 if result["passed"] else 1
if __name__ == "__main__":
sys.exit(main())
+69
View File
@@ -0,0 +1,69 @@
"""Deterministic, template-compatible file catalog; no source body duplication."""
from pathlib import Path
import argparse, json, re
FIXED = [
('seo-geo-research-skill','skills/seo-geo-research/SKILL.md','SEO / GEO research service','skill','Weekly dual-engine research contract and verification gates.',['seo','geo','aeo','agent-discovery']),
('seo-geo-research-framework','skills/seo-geo-research/references/research-framework.md','Original GEO / AI Search framework','reference','Original analytical scope for iNDX, NetworkSIG and AI discovery.',['iNDX','NetworkSIG','retrieval','provenance']),
('seo-geo-report-template','templates/report-template.md','Weekly research report template','template','Report sections, source ledger, query ledger and architectural implications.',['research-report','web-search','exa']),
('seo-geo-research-rollup','reports/seo-geo-research-rollup.md','Cumulative SEO / GEO research rollup','derived-rollup','Derived chronological collection, not independent evidence; preserves source report status.',['seo','geo','derived','historical-context'])]
def read_json(path): return json.loads(Path(path).read_text(encoding='utf-8-sig'))
def validate_index(root,index):
root=Path(root).resolve(); ids=set(); paths=set()
for item in index['items']:
cid=item['content_id']; path=item['path']; target=(root/path).resolve()
if cid in ids or path in paths: raise ValueError('Duplicate content ID or path')
if not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*',cid): raise ValueError('Unsafe content ID')
if not target.is_relative_to(root) or not target.is_file(): raise ValueError('Missing or unsafe indexed target: '+path)
if item['status'] not in ['draft','published','archived','deprecated','superseded']: raise ValueError('Invalid lifecycle status')
ids.add(cid); paths.add(path)
for item in index['items']:
if not set(item.get('related_content_ids',[])).issubset(ids): raise ValueError('Unresolved related content')
def make_index(root):
root=Path(root); manifest=read_json(root/'repository.json'); old=read_json(root/'content-index.json') if (root/'content-index.json').exists() else {}
old_items={i['path']:i for i in old.get('items',[])}; items=[]
def add(cid,path,title,kind,desc,topics,date=None,status='draft'):
previous=old_items.get(path,{})
items.append({'content_id':previous.get('content_id',cid),'title':title,'description':desc,'content_type':kind,'path':path,'canonical_url':previous.get('canonical_url'), 'published_at':previous.get('published_at'), 'updated_at':previous.get('updated_at',date),'status':previous.get('status',status),'author':'Eddie Soehnel','topics':topics,'related_content_ids':[]})
for cid,path,title,kind,desc,topics in FIXED: add(cid,path,title,kind,desc,topics,manifest['updated_at'])
for p in sorted((root/'reports').rglob('*.md')):
if 'receipts' in p.relative_to(root).parts: continue
path=p.relative_to(root).as_posix()
if p.name.startswith('GEO-AI-Search-Weekly-Research-Archive-'):
match=re.search(r'(\d{4}-\d{2}-\d{2})_to_(\d{4}-\d{2}-\d{2})',p.name)
coverage=f'{match[1]} through {match[2]}' if match else 'imported historical coverage'
cid='seo-geo-history-'+re.sub(r'[^a-z0-9]+','-',p.stem.lower()).strip('-')
add(cid,path,'Historical GEO / AI search archive','historical-archive','Imported '+coverage+'; original portable citations unavailable. Unverified historical context.', ['geo','ai-search','historical','unverified'],manifest['updated_at'],'archived')
elif re.fullmatch(r'\d{4}-\d{2}-\d{2}-geo-ai-search-intelligence(?:-[a-zA-Z0-9-]+)?\.md',p.name):
text=p.read_text(encoding='utf-8-sig'); title=next((line.lstrip('# ').strip() for line in text.splitlines() if line.startswith('# ')),p.stem)
cid='seo-geo-report-'+p.stem
add(cid,path,title,'research-report','Dated research report; consult body and local receipt for completion and coverage. Lifecycle publication status is recorded separately.', ['seo','geo','ai-search','weekly-report','web-search','exa'],p.name[:10])
sources=[i['content_id'] for i in items if i['content_type'] in ['historical-archive','research-report']]
for item in items:
if item['content_id']=='seo-geo-research-rollup': item['related_content_ids']=sources
elif item['content_type']=='research-report': item['related_content_ids']=['seo-geo-research-skill','seo-geo-report-template']
index={'$schema':'./schemas/content-index.schema.json','schema_version':'1.0','collection_id':'seo-geo-research-documents','title':'SEO / GEO research documents','description':'File-level research catalog. Historical sources are unverified; cumulative rollup is derived. Completion and publication are distinct.','updated_at':old.get('updated_at',manifest['updated_at']),'items':items}
if old and old.get('items')!=items:
from datetime import datetime
try:
from zoneinfo import ZoneInfo
today=datetime.now(ZoneInfo('America/Denver')).date().isoformat()
except Exception:
today=max([manifest['updated_at']]+[i.get('updated_at') or manifest['updated_at'] for i in items])
index['updated_at']=today
validate_index(root,index)
return index
def build(root):
root=Path(root); index=make_index(root); data=json.dumps(index,indent=2,ensure_ascii=False)+'\n'
out=root/'content-index.json'; temp=out.with_suffix('.json.tmp')
temp.write_text(data,encoding='utf-8'); temp.replace(out)
if out.read_text(encoding='utf-8')!=data: raise IOError('Index readback failed')
return index
if __name__=='__main__':
parser=argparse.ArgumentParser(); parser.add_argument('--root',default=str(Path(__file__).resolve().parents[1])); args=parser.parse_args()
print(f"Indexed {len(build(args.root)['items'])} documents")
+23
View File
@@ -0,0 +1,23 @@
from pathlib import Path
import hashlib, re, json, argparse
def build(root):
root=Path(root); reports=root/'reports'; out=reports/'seo-geo-research-rollup.md'
files=sorted(p for p in reports.rglob('*.md') if p != out and 'receipts' not in p.parts and (p.name.startswith('GEO-AI-Search-Weekly-Research-Archive-') or re.match(r'\d{4}-\d{2}-\d{2}-geo-ai-search-intelligence',p.name)))
if not files: raise ValueError('No source reports; rollup unchanged')
parts=['# SEO / GEO research rollup','Chronological source record. Imported ChatGPT claims lack portable citations and remain historical, unverified evidence. New reports preserve their own completion status and source attribution. This rollup does not independently revalidate claims.','## Source inventory']
inventory=[]
for p in files:
raw=p.read_bytes(); text=raw.decode('utf-8-sig'); dates=re.findall(r'^# (\d{4}-\d{2}-\d{2})$',text,re.M)
item={'path':p.relative_to(root).as_posix(),'sha256':hashlib.sha256(raw).hexdigest(),'weekly_sections':len(dates)}; inventory.append(item)
parts.append(f"- [{p.name}]({p.relative_to(reports).as_posix()}): SHA256 `{item['sha256']}`; imported weekly sections: {len(dates)}")
for p in files: parts.extend(['---','## Source: '+p.name,p.read_text(encoding='utf-8-sig')])
content='\n\n'.join(parts)+'\n'; temp=out.with_suffix('.md.tmp'); temp.write_text(content,encoding='utf-8'); temp.replace(out)
if out.read_text(encoding='utf-8') != content: raise IOError('Readback mismatch')
if (root/'repository.json').exists():
from build_content_index import build as refresh_index
refresh_index(root)
return inventory
if __name__=='__main__':
parser=argparse.ArgumentParser(); parser.add_argument('--root',default=str(Path(__file__).resolve().parents[1])); args=parser.parse_args(); print(json.dumps(build(args.root),indent=2))
+17
View File
@@ -0,0 +1,17 @@
import tempfile, unittest
from pathlib import Path
from rollup import build
class RollupTests(unittest.TestCase):
def test_preservation_and_idempotence(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parent) as d:
r=Path(d)/'reports'; r.mkdir(); archive=r/'GEO-AI-Search-Weekly-Research-Archive-test.md'; archive.write_text('# 2026-06-22\nOriginal claim\n',encoding='utf-8'); raw=archive.read_bytes()
report=r/'2026-10-19-geo-ai-search-intelligence.md'; report.write_text('Status: partial\n[Source](https://example.org) — Exa',encoding='utf-8')
inv=build(d); first=(r/'seo-geo-research-rollup.md').read_bytes(); build(d)
self.assertEqual(first,(r/'seo-geo-research-rollup.md').read_bytes()); self.assertEqual(raw,archive.read_bytes()); self.assertEqual(len(inv),2); self.assertIn(b'Status: partial',first)
def test_empty_keeps_existing(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parent) as d:
r=Path(d)/'reports'; r.mkdir(); out=r/'seo-geo-research-rollup.md'; out.write_text('keep')
with self.assertRaises(ValueError): build(d)
self.assertEqual(out.read_text(),'keep')
if __name__=='__main__': unittest.main()
+47
View File
@@ -0,0 +1,47 @@
"""Read-only checks; full schema validation optional and explicitly reported."""
from pathlib import Path
import argparse, json, re
from urllib.parse import unquote
from build_content_index import make_index, validate_index, read_json
def validate(root,schemas=True):
root=Path(root).resolve(); manifest=read_json(root/'repository.json'); variables=read_json(root/'repository-variables.json'); index=read_json(root/'content-index.json')
for p in root.rglob('*.json'):
if 'receipts' not in p.parts: read_json(p)
validate_index(root,index)
if index!=make_index(root): raise ValueError('Stale content index; rebuild required')
version=(root/'VERSION').read_text().strip()
if manifest['version']!=version: raise ValueError('Repository version mismatch')
citation=(root/'CITATION.cff').read_text(); author=(root/'AUTHOR.md').read_text()
if not re.search(r'^version: '+re.escape(version)+r'$',citation,re.M): raise ValueError('Citation version mismatch')
if '## '+version+' ' not in (root/'CHANGELOG.md').read_text(): raise ValueError('Missing version changelog')
for key,value in variables['repository'].items():
if manifest.get(key)!=value: raise ValueError('Repository identity mismatch: '+key)
if variables['identity']['authors']!=manifest['authors'] or variables['identity']['publisher']!=manifest['publisher']: raise ValueError('Attribution mismatch')
if variables['identity']['maintainer']['name']!=manifest['maintenance']['maintainer']: raise ValueError('Maintainer mismatch')
for key,value in variables['rights'].items():
if manifest['rights'][key]!=value: raise ValueError('Rights mismatch')
if 'Eddie Soehnel' not in author or manifest['canonical_url'] not in author or 'family-names: Soehnel' not in citation or 'MIT License' not in (root/'LICENSE').read_text(): raise ValueError('Human attribution/license mismatch')
paths=list(manifest['entrypoints'].values())+[i['path'] for i in manifest['contents']]+manifest['ai_retrieval']['read_first']+manifest['ai_retrieval']['retrieve_as_needed']
for path in paths:
if path and not (root/path).exists(): raise ValueError('Missing declared path: '+path)
for path in ['README.md','AUTHOR.md','AGENTS.md','skills.md','CONTRIBUTING.md','SECURITY.md','examples/README.md','scripts/README.md','skills/seo-geo-research/SKILL.md']:
p=root/path
for dest in re.findall(r'\[[^\]]*\]\(([^)]+)\)',p.read_text()):
dest=dest.strip('<>').split('#')[0]
if not dest or re.match(r'[a-zA-Z]+:',dest): continue
if not (p.parent/unquote(dest)).resolve().exists(): raise ValueError('Broken relative link in '+path+': '+dest)
for p in [root/'README.md',root/'AUTHOR.md',root/'repository.json',root/'repository-variables.json']:
if re.search(r'(?:ghp_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{20,}|BEGIN (?:RSA |OPENSSH )?PRIVATE KEY)',p.read_text()): raise ValueError('Possible secret in '+p.name)
schema_result='not requested'
if schemas:
try: import jsonschema
except ImportError: schema_result='UNAVAILABLE: jsonschema is not installed; core checks passed'
else:
for name,data in [('repository',manifest),('repository-variables',variables),('content-index',index)]:
schema=read_json(root/f'schemas/{name}.schema.json'); jsonschema.Draft202012Validator(schema,format_checker=jsonschema.FormatChecker()).validate(data)
schema_result='PASS: all three template JSON Schemas'
return {'status':'PASS','documents':len(index['items']),'schemas':schema_result,'checks':['JSON','attribution','version alignment','declared paths','index freshness','unique IDs and paths','relationships','changed-entrypoint relative links','obvious-secret patterns']}
if __name__=='__main__':
parser=argparse.ArgumentParser(); parser.add_argument('--root',default=str(Path(__file__).resolve().parents[1])); args=parser.parse_args(); print(json.dumps(validate(args.root),indent=2))
+10
View File
@@ -0,0 +1,10 @@
from pathlib import Path
import json
root=Path(__file__).resolve().parents[1]
required=['skills/seo-geo-research/SKILL.md','skills/seo-geo-research/references/research-framework.md','templates/report-template.md','templates/run-receipt.json','evals/contract.json','evals/routing-cases.json','scripts/rollup.py','scripts/test_rollup.py']
for name in required: assert (root/name).is_file(),name
for p in root.rglob('*.json'): json.loads(p.read_text(encoding='utf-8-sig'))
skill=(root/required[0]).read_text(encoding='utf-8')
for section in ['Contract','Requires','Ensures','Workflow','State Scope','Validation','Run Receipt','Ratchet']: assert section in skill,section
assert 'name: seo-geo-research' in skill
print('PASS: required files, JSON, skill contract sections')