This commit is contained in:
eddiesoehnel committed 2026-10-18 09:21:12 -06:00
1 parent 4eaec52904
commit df7571392e
50 files changed
+3390 -258

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# Scripts
Run commands from the repository root with Python 3.11+ and `requirements.txt` dependencies.
| Script | Purpose |
| --- | --- |
| [folder_builder.py](folder_builder.py) | Inspect/prepare source folders; seed plans; build drafts; finalize explicitly approved content; verify and search drafts/finals |
| [media_approval.py](media_approval.py) | Final approval input binding and integrity checks, called by folder_builder |
| [media_builder.py](media_builder.py) | Optional reviewed public-export pipeline and collection search |
| [check_repository.py](check_repository.py) | Native schemas, identity/version/rights, catalog, links, paths, syntax, whitespace, and targeted credential-pattern checks |
| [audit_repository.py](audit_repository.py) | Read-only software-automation profile audit adapted from the MIT AI-Ready Repository Template |
Use `python scripts/folder_builder.py --help` for commands and [the main README](../README.md) for the processing sequence. Finalize only on explicit approval of the specific reviewed draft, with `--reviewer`, `--approved-at`, and `--evidence`. Never invent those values to unblock a build.
Repository checks:
```text
python scripts/audit_repository.py . --profile software-automation --json
python scripts/check_repository.py
python -m unittest discover -s tests -v
```
Hashes detect inconsistent source/output, not malicious replacement of files plus receipts. No deterministic builder calls STT providers, inference services, public APIs, or hosting platforms.
+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())
+38 -3
View File
@@ -5,12 +5,47 @@ import re
from pathlib import Path
from urllib.parse import unquote
from jsonschema import Draft202012Validator
from jsonschema import Draft202012Validator, FormatChecker
ROOT = Path(__file__).resolve().parents[1]
SKIP = {'build', '.git', '__pycache__', '.test-work', '.venv'}
def validate_contracts(root=ROOT):
def load(name):
return json.loads((root/name).read_text(encoding='utf-8-sig'))
for document,schema in [('repository.json','repository'),('repository-variables.json','repository-variables'),('content-index.json','content-index')]:
Draft202012Validator(load('schemas/'+schema+'.schema.json'), format_checker=FormatChecker()).validate(load(document))
manifest,variables,index=load('repository.json'),load('repository-variables.json'),load('content-index.json')
assert variables['identity']['authors']==manifest['authors'], 'Author mismatch'
assert variables['identity']['publisher']==manifest['publisher'], 'Publisher mismatch'
assert variables['identity']['maintainer']['name']==manifest['maintenance']['maintainer'], 'Maintainer mismatch'
for key,value in variables['repository'].items():
assert manifest.get(key)==value, 'Repository identity mismatch: '+key
for key,value in variables['rights'].items():
assert manifest['rights'][key]==value, 'Rights mismatch: '+key
version=(root/'VERSION').read_text(encoding='utf-8-sig').strip()
assert manifest['version']==version, 'Manifest/version mismatch'
citation=(root/'CITATION.cff').read_text(encoding='utf-8')
assert re.search(r'(?m)^version:\s*[\"\x27]?'+re.escape(version)+r'[\"\x27]?\s*$',citation), 'Citation version mismatch'
assert 'license: MIT' in citation and manifest['rights']['license']=='MIT', 'Citation/license mismatch'
assert manifest['canonical_url'] in citation, 'Citation URL mismatch'
for record in manifest['authors']:
assert record['name'] in (root/'AUTHOR.md').read_text(encoding='utf-8'), 'Author notice mismatch'
assert 'Copyright (c) 2026 Eddie Soehnel' in (root/manifest['rights']['license_file']).read_text(encoding='utf-8'), 'License attribution mismatch'
ids=[item['content_id'] for item in index['items']]
paths=[item['path'] for item in index['items']]
assert len(ids)==len(set(ids)) and len(paths)==len(set(paths)), 'Duplicate content identity/path'
for item in index['items']:
target=(root/item['path']).resolve()
assert target.is_relative_to(root.resolve()) and target.is_file(), 'Missing/unsafe indexed path'
assert set(item.get('related_content_ids',[])) <= set(ids), 'Unresolved content relation'
for declared in [v for v in manifest['entrypoints'].values() if v] + [c['path'] for c in manifest['contents']] + manifest['ai_retrieval']['read_first'] + manifest['ai_retrieval']['retrieve_as_needed']:
target=(root/declared).resolve()
assert target.is_relative_to(root.resolve()) and target.exists(), 'Missing/unsafe declared path: '+declared
return {'version':version,'license':manifest['rights']['license'],'indexed_documents':len(ids)}
def check():
files = [p for p in ROOT.rglob('*') if p.is_file() and not (set(p.relative_to(ROOT).parts) & SKIP)]
count = {'json': 0, 'markdown_links': 0, 'schema_refs': 0, 'python': 0}
@@ -59,12 +94,12 @@ def check():
except Exception as error:
errors.append(f'{path.relative_to(ROOT)}: {error}')
manifest = json.loads((ROOT/'repository.json').read_text(encoding='utf-8'))
for name in list(manifest['entrypoints'].values()) + [v['path'] for v in manifest['contents']]:
for name in [v for v in manifest['entrypoints'].values() if v] + [v['path'] for v in manifest['contents']]:
if not (ROOT/name).exists():
errors.append('Missing manifest path: ' + name)
if errors:
raise ValueError('\n'.join(errors))
print(json.dumps({'valid': True, **count}, indent=2))
print(json.dumps({'valid': True, **count, **validate_contracts(ROOT)}, indent=2))
if __name__ == '__main__':
+14 -1
View File
@@ -322,6 +322,10 @@ def build(folder, intake_path, plan_path, output):
def verify(output, check_sources=True):
output = Path(output).resolve()
receipt = core.load(output/'build-receipt.json')
if receipt.get('status') == 'approved':
from media_approval import verify as verify_approved
return verify_approved(output, check_sources=check_sources)
core.require(receipt.get('status') == 'draft' and not receipt.get('human_approval'), 'Invalid draft state')
actual = {p.relative_to(output).as_posix():sha_file(p) for p in output.rglob('*')
if p.is_file() and p != output/'build-receipt.json'}
core.require(actual == receipt['files'], 'Draft output differs from receipt')
@@ -340,6 +344,7 @@ def search(output, query, limit=5):
terms = set(re.findall(r'\w+', query.casefold()))
core.require(terms, 'Empty query')
results = []
status = core.load(Path(output)/'build-receipt.json')['status']
for kind in ('chunks','qa'):
for r in core.load(Path(output)/(kind+'.json'))[kind]:
text = (r['title']+' '+r['summary']+' '+r['content']) if kind=='chunks' else r['question']+' '+r['answer']
@@ -350,7 +355,7 @@ def search(output, query, limit=5):
+ 2 * len(terms & set(re.findall(r'\w+',abstract.casefold()))))
if score:
results.append({'id':r.get('chunk_id',r.get('qa_id')),'type':kind,'score':score,
'text':text,'citations':r.get('citations',r.get('evidence')),'status':'draft'})
'text':text,'citations':r.get('citations',r.get('evidence')),'status':status})
return sorted(results,key=lambda r:(-r['score'],r['id']))[:limit]
@@ -372,12 +377,20 @@ def main():
if command=='search':
cmd.add_argument('--query',required=True)
cmd.add_argument('--limit',type=int,default=5)
cmd = sub.add_parser('finalize')
for name in ('source','output','intake','plan'):
cmd.add_argument('--'+name, type=Path, required=True)
for name in ('reviewer','approved-at','evidence'):
cmd.add_argument('--'+name, required=True)
a = p.parse_args()
try:
if a.command=='inspect': result=inspect(a.folder)[0]
elif a.command=='prepare': result=prepare(a.folder,a.output)
elif a.command=='seed': result=seed(a.folder,a.intake,a.output)
elif a.command=='build': result=build(a.folder,a.intake,a.plan,a.output)
elif a.command=='finalize':
from media_approval import finalize
result=finalize(a.source,a.output,a.intake,a.plan,a.reviewer,a.approved_at,a.evidence)
elif a.command=='verify': result=verify(a.output)
else: result=search(a.output,a.query,a.limit)
print(core.encoded(result).decode('utf-8'),end='')
+141
View File
@@ -0,0 +1,141 @@
"""Explicit local content approval, final-package integrity, and draft preservation.
This is workflow evidence, not authenticated signatures, source fact-checking,
third-party media licensing, or publication authority.
"""
from pathlib import Path
import copy
import shutil
import tempfile
from datetime import datetime
import media_builder as core
import folder_builder
def semantic_plan(plan):
return {key:value for key,value in plan.items() if key != 'review'}
def verify(output, check_sources=True):
output=Path(output).resolve()
receipt=core.load(output/'build-receipt.json')
approval=core.load(output/'approval.json')
core.require(receipt['status']=='approved' and receipt['lifecycle']=='final', 'Not a final approved package')
core.require(approval['status']=='approved' and approval['reviewer'].strip() and approval['approval_evidence'].strip(), 'Explicit approval record missing')
core.require(approval['input_sha256']==receipt['input_sha256'], 'Approval/receipt fingerprint mismatch')
actual={p.relative_to(output).as_posix():folder_builder.sha_file(p) for p in output.rglob('*')
if p.is_file() and p != output/'build-receipt.json'}
core.require(actual==receipt['files'], 'Final output differs from receipt')
for name in ('transcript.json','chunks.json','qa.json','ai-index.json'):
value=core.load(output/name)
core.validate(value, 'folder-export')
core.require(value['status']=='approved','Artifact not approved')
if check_sources:
for record in receipt['source_files'].values():
path=core.relative_file(output.parent,record['path'])
core.require(folder_builder.sha_file(path)==record['sha256'],'Original source changed')
intake=core.relative_file(output.parent,approval['inputs']['intake'])
plan=core.relative_file(output.parent,approval['inputs']['plan'])
core.require(folder_builder.sha_file(intake)==approval['intake_sha256'],'Intake changed since approval')
plan_value=core.load(plan)
core.require(core.digest(core.encoded(semantic_plan(plan_value)))==approval['plan_content_sha256'],
'Plan content changed since approval')
core.require(plan_value['review']['status']=='approved','Source plan not approved')
core.require(plan_value['review']['reviewer']==approval['reviewer'] and plan_value['review']['reviewed_at']==approval['approved_at'], 'Approval identity/time differs from source plan')
core.require(plan_value['review']['input_sha256']==receipt['input_sha256'],'Plan approval fingerprint mismatch')
media=core.load(output/'media.json')
core.require(media['human_approval'] and not media['publication_ready'], 'Approval scope mismatch')
return {'valid':True,'status':'approved','lifecycle':'final','source_files_checked':check_sources,
'source_files_unchanged':True if check_sources else None,
'reviewer':approval['reviewer'],**receipt['counts']}
def finalize(source,output,intake_path,plan_path,reviewer,approved_at,evidence):
source,output=Path(source).resolve(),Path(output).resolve()
intake_path,plan_path=Path(intake_path).resolve(),Path(plan_path).resolve()
core.require(source.parent==output.parent and output!=source,'Final must be a sibling of the reviewed draft')
core.require(not output.exists(),'Final output exists; do not overwrite it')
core.require(intake_path.parent==source.parent and plan_path.parent==source.parent,'Inputs must be beside the media sources')
core.require(reviewer.strip() and evidence.strip(),'Explicit reviewer and approval evidence required')
moment=datetime.fromisoformat(approved_at.replace('Z','+00:00'))
core.require(moment.tzinfo is not None,'Approval timestamp must include a timezone')
folder_builder.verify(source)
draft_receipt=core.load(source/'build-receipt.json')
plan=core.load(plan_path)
core.require(plan['review']['status']=='draft','Expected the reviewed draft source plan')
expected=core.digest(core.encoded({'builder_version':draft_receipt['builder_version'], 'intake':core.load(intake_path), 'plan':plan, 'source_files':draft_receipt['source_files']}))
core.require(expected==draft_receipt['input_sha256'], 'Draft inputs changed since build; rebuild and review before approval')
old_review=copy.deepcopy(plan['review'])
approval={
'schema_version':'1.0','status':'approved','lifecycle':'final',
'reviewer':reviewer,'approved_at':approved_at,'approval_evidence':evidence,
'scope':'Owner approval of the generated structured content and metadata as final, with documented limitations retained.',
'publication_ready':False,'input_sha256':draft_receipt['input_sha256'],
'inputs':{'intake':intake_path.name,'plan':plan_path.name},
'intake_sha256':folder_builder.sha_file(intake_path),
'plan_content_sha256':core.digest(core.encoded(semantic_plan(plan))),
'reviewed_draft_directory':source.name,'reviewed_draft_receipt':draft_receipt,
'notes':['The original reviewed draft remains available as history.',
'The approval timestamp records when this run recorded the user approval.',
'Approval does not claim independent fact-checking, audio/slide verification, a recording license, or deployment.',
'Unknown metadata and original source wording are retained.']}
pending=Path(tempfile.mkdtemp(prefix='.final-media-',dir=output.parent))
plan_updated=False
try:
for path in source.iterdir():
core.require(path.is_file(),'Unexpected draft subdirectory')
shutil.copyfile(path,pending/path.name)
for path in pending.glob('*.json'):
if path.name=='build-receipt.json':continue
value=core.load(path)
if value.get('profile')=='local-review':value['status']='approved'
if path.name=='media.json':
value['human_approval']=True
if value['metadata']['description']:
value['metadata']['description']=value['metadata']['description'].replace(
'This local draft preserves','This approved structured package preserves')
core.write(path,value)
page=(pending/'README.md').read_text(encoding='utf-8')
page=page.replace('**Draft for human review.** Built from the supplied recording, TXT, and VTT.',
f'**Final — approved by {reviewer} on {moment.date().isoformat()}.** '
'Built from the supplied recording, TXT, and VTT; documented limitations remain in the review record.')
page=page.replace('This local draft preserves','This approved structured package preserves')
page=page.replace('Draft credit','Approved credit')
core.write(pending/'README.md',page)
review=(pending/'review.md').read_text(encoding='utf-8')
review=review.replace('Status: **draft — not human approved or publication ready**.',
f'Status: **final and approved**. Approved by {reviewer} on {moment.date().isoformat()}.\n\n'
f'Approval evidence: “{evidence}”\n\n'
'This records approval of the generated structure with its stated limitations. '
'Publication prerequisites and source-verification notes below remain informational follow-up items.')
review=review.replace('## Please review','## Follow-up checks retained after approval')
review=review.replace('not factual accuracy or human approval.','not independent factual accuracy. Human approval is recorded separately in approval.json.')
core.write(pending/'review.md',review)
guide=(pending/'llms.txt').read_text(encoding='utf-8').replace(
'> Local draft for review; publication details may be unknown.',
'> Final, owner-approved structured content; publication details may remain unknown.')
core.write(pending/'llms.txt',guide)
core.write(pending/'approval.json',approval)
receipt={**draft_receipt,'status':'approved','lifecycle':'final','human_approval':True,
'publication_ready':False,'approval_record':'approval.json',
'files':{p.name:folder_builder.sha_file(p) for p in sorted(pending.iterdir())
if p.is_file() and p.name!='build-receipt.json'}}
core.write(pending/'build-receipt.json',receipt)
plan['review']={'status':'approved','reviewer':reviewer,'reviewed_at':approved_at,
'input_sha256':draft_receipt['input_sha256']}
core.validate(plan,'plan')
core.write(plan_path,plan)
plan_updated=True
# Validate all content/state and original hashes before exposing the final path.
verify(pending)
pending.rename(output)
return verify(output)
except Exception:
if plan_updated and not output.exists():
plan['review']=old_review
core.write(plan_path,plan)
raise
finally:
if pending.exists():shutil.rmtree(pending)
+1 -1
View File
@@ -16,7 +16,7 @@ from xml.etree import ElementTree as ET
from jsonschema import Draft202012Validator, FormatChecker
ROOT = Path(__file__).resolve().parents[1]
VERSION = "0.2.0"
VERSION = "0.3.0"
def require(condition, message):