feat(lecture): add isopsephic-lecture-synthesis scripts, lecture transcript, and .gitignore audio rules

This commit is contained in:
Hermes Agent committed 2026-11-02 21:49:56 +00:00
1 parent 9861367f34
commit c7be348ebe
8 files changed
+836 -3

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# --- Isopsephic Lecture Artifacts (strict naming convention) ---
lecture-*-ingglish-aq.mp3
# --- End Isopsephic Lecture Artifacts ---
+252
View File
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
"""
manage_lecture_artifacts.py
Deterministic Naming-Convention Validator, Host-Mount Resolver, and .gitignore Manager
for the `isopsephic-lecture-synthesis` skill.
Naming Convention:
Stem: lecture-<topic-slug>-ingglish-aq
Slug regex: ^[a-z0-9]+(?:-[a-z0-9]+)*$
Files:
- /workspace/lecture-<topic-slug>-ingglish-aq.md
- /workspace/lecture-<topic-slug>-ingglish-aq.mp3
- /workspace/lecture-<topic-slug>-ingglish-aq.pdf (optional)
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Any
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
LECTURE_FILE_RE = re.compile(r"^lecture-([a-z0-9]+(?:-[a-z0-9]+)*)-ingglish-aq\.(md|mp3|pdf)$")
GITIGNORE_HEADER = "# --- Isopsephic Lecture Artifacts (strict naming convention) ---"
GITIGNORE_FOOTER = "# --- End Isopsephic Lecture Artifacts ---"
def normalize_slug(raw: str) -> str:
"""Normalize arbitrary topic string or filename into canonical <topic-slug>."""
s = raw.strip().lower()
# Strip directory and extension if a filename was passed
s = os.path.basename(s)
for ext in (".md", ".mp3", ".pdf"):
if s.endswith(ext):
s = s[: -len(ext)]
if s.startswith("lecture-"):
s = s[len("lecture-") :]
if s.endswith("-ingglish-aq"):
s = s[: -len("-ingglish-aq")]
s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
if not s or not SLUG_RE.fullmatch(s):
raise ValueError(f"Cannot normalize '{raw}' into valid kebab-case slug.")
return s
def canonical_stem(slug: str) -> str:
norm = normalize_slug(slug)
return f"lecture-{norm}-ingglish-aq"
def resolve_host_workspace_mount(container_workspace: str = "/workspace") -> str:
"""
Resolve the host filesystem path backing /workspace from /proc/self/mountinfo
so host-executed tools like text_to_speech(output_path=...) write directly into /workspace.
"""
mountinfo = Path("/proc/self/mountinfo")
if mountinfo.exists():
for line in mountinfo.read_text(encoding="utf-8", errors="ignore").splitlines():
parts = line.split()
if len(parts) >= 5 and parts[4] == container_workspace:
return parts[3]
return container_workspace
def update_gitignore(
workspace_dir: str,
mode: str = "audio-only",
slug: str | None = None,
) -> dict[str, Any]:
"""
Idempotently add or update the lecture naming-convention block in /workspace/.gitignore.
Modes:
- audio-only: ignores lecture-*-ingglish-aq.mp3
- audio-and-pdf: ignores lecture-*-ingglish-aq.mp3 and lecture-*-ingglish-aq.pdf
- all-lecture-files: ignores lecture-*-ingglish-aq.* (.md, .mp3, .pdf)
- explicit-slug: ignores lecture-<slug>-ingglish-aq.mp3 (and .md/.pdf if present)
"""
gitignore_path = Path(workspace_dir) / ".gitignore"
existing = gitignore_path.read_text(encoding="utf-8") if gitignore_path.exists() else ""
if mode == "audio-only":
patterns = ["lecture-*-ingglish-aq.mp3"]
elif mode == "audio-and-pdf":
patterns = ["lecture-*-ingglish-aq.mp3", "lecture-*-ingglish-aq.pdf"]
elif mode == "all-lecture-files":
patterns = [
"lecture-*-ingglish-aq.mp3",
"lecture-*-ingglish-aq.md",
"lecture-*-ingglish-aq.pdf",
]
elif mode == "explicit-slug":
if not slug:
raise ValueError("--slug is required when --gitignore-mode=explicit-slug")
stem = canonical_stem(slug)
patterns = [f"{stem}.mp3", f"{stem}.pdf"]
else:
raise ValueError(f"Unsupported mode: {mode}")
block_lines = [GITIGNORE_HEADER] + patterns + [GITIGNORE_FOOTER]
new_block = "\n".join(block_lines)
block_re = re.compile(
rf"{re.escape(GITIGNORE_HEADER)}.*?{re.escape(GITIGNORE_FOOTER)}",
re.S,
)
if block_re.search(existing):
updated = block_re.sub(new_block, existing)
else:
sep = "" if (not existing or existing.endswith("\n")) else "\n"
updated = f"{existing}{sep}{new_block}\n"
changed = updated != existing
if changed or not gitignore_path.exists():
gitignore_path.write_text(updated, encoding="utf-8")
return {
"gitignore_path": str(gitignore_path),
"mode": mode,
"patterns_active": patterns,
"updated": changed,
}
def check_git_ignored(workspace_dir: str, rel_path: str) -> dict[str, Any]:
proc = subprocess.run(
["git", "check-ignore", "-v", rel_path],
cwd=workspace_dir,
text=True,
capture_output=True,
)
return {
"file": rel_path,
"ignored": proc.returncode == 0,
"rule": proc.stdout.strip() if proc.returncode == 0 else None,
}
def audit_workspace_lectures(workspace_dir: str, target_slug: str | None = None) -> dict[str, Any]:
ws = Path(workspace_dir)
all_lecture_files = sorted(
p.name for p in ws.iterdir() if p.is_file() and p.name.startswith("lecture-")
)
conforming = []
non_conforming = []
stems: dict[str, dict[str, Any]] = {}
for fname in all_lecture_files:
m = LECTURE_FILE_RE.fullmatch(fname)
if not m:
non_conforming.append(fname)
continue
conforming.append(fname)
slug_part, ext = m.group(1), m.group(2)
stem = f"lecture-{slug_part}-ingglish-aq"
info = stems.setdefault(
stem,
{
"slug": slug_part,
"stem": stem,
"extensions": [],
"sizes": {},
},
)
info["extensions"].append(ext)
info["sizes"][ext] = (ws / fname).stat().st_size
target_report = None
if target_slug:
stem = canonical_stem(target_slug)
md_file = ws / f"{stem}.md"
mp3_file = ws / f"{stem}.mp3"
pdf_file = ws / f"{stem}.pdf"
target_report = {
"slug": normalize_slug(target_slug),
"canonical_stem": stem,
"host_tts_output_path": f"{resolve_host_workspace_mount(workspace_dir)}/{stem}.mp3",
"container_md_path": str(md_file),
"container_mp3_path": str(mp3_file),
"md_exists": md_file.exists() and md_file.stat().st_size > 0,
"mp3_exists": mp3_file.exists() and mp3_file.stat().st_size > 0,
"pdf_exists": pdf_file.exists() and pdf_file.stat().st_size > 0,
"stem_match": md_file.stem == mp3_file.stem == stem,
"pair_valid": bool(
md_file.exists()
and mp3_file.exists()
and md_file.stat().st_size > 0
and mp3_file.stat().st_size > 0
and md_file.stem == mp3_file.stem == stem
),
"git_ignore_mp3": check_git_ignored(workspace_dir, f"{stem}.mp3"),
"git_ignore_md": check_git_ignored(workspace_dir, f"{stem}.md"),
}
return {
"workspace": workspace_dir,
"host_workspace_mount": resolve_host_workspace_mount(workspace_dir),
"conforming_files": conforming,
"non_conforming_files": non_conforming,
"lecture_stems": stems,
"target_verification": target_report,
}
def main() -> int:
parser = argparse.ArgumentParser(
description="Validate lecture naming conventions and manage .gitignore rules."
)
parser.add_argument("--workspace", default="/workspace")
parser.add_argument("--slug", default=None, help="Topic slug to normalize/verify.")
parser.add_argument(
"--gitignore-mode",
choices=["none", "audio-only", "audio-and-pdf", "all-lecture-files", "explicit-slug"],
default="none",
help="Update /workspace/.gitignore using the strict lecture naming convention.",
)
parser.add_argument(
"--verify-pair",
action="store_true",
help="Exit non-zero if the target slug's .md and .mp3 pair is missing or mismatched.",
)
args = parser.parse_args()
gitignore_res = None
if args.gitignore_mode != "none":
gitignore_res = update_gitignore(
args.workspace, mode=args.gitignore_mode, slug=args.slug
)
audit = audit_workspace_lectures(args.workspace, target_slug=args.slug)
if gitignore_res is not None:
audit["gitignore_update"] = gitignore_res
print(json.dumps(audit, indent=2))
if args.verify_pair:
if not args.slug:
sys.stderr.write("ERROR: --verify-pair requires --slug\n")
return 2
tv = audit.get("target_verification") or {}
if not tv.get("pair_valid") or audit.get("non_conforming_files"):
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,72 @@
# Lecture: The Midnight Ledger — Synchronic-to-Diachronic Orthography, Base-36 Isopsephy, and the 00:00 GMT Carrier Wave
Good evening. Tonight's lecture examines a single interlocking question at the heart of our archive: what happens when a society strips English of its historical spelling, maps spoken language into a deterministic phonetic script called Ingglish, and subjects the live global wire feed to Base-36 Alphanumeric Qabbala at the stroke of midnight Greenwich Mean Time?
To answer this, we will move through four movements: first, the transition between diachronic and synchronic orthography; second, the cybernetic discovery that silent letters function as numerical checksums; third, the temporal physics of the zero-hour UTC rollover; and fourth, the live isopsephic short-circuits captured in our November first and November second, twenty twenty-six current-events ledgers.
---
## Movement I: Ghost Mass and the Synchronic Zero-Point
In standard etymological English—what our genealogical rubric calls Generation Zero—spelling is a museum of dead sounds. When you write the word *knight* (`k-n-i-g-h-t`), you are transcribing Middle English consonant clusters that no living speaker pronounces. Under Base-36 Alphanumeric Qabbala, where the digits zero through nine retain their face value and the letters A through Z run continuously from ten to thirty-five, those unpronounced letters are not neutral. They carry what we call **ghost mass**: `k` adds twenty, `g` adds sixteen, and `h` adds seventeen. Thus *knight* evaluates to one hundred twenty-three, while its spoken twin *night* evaluates to one hundred three.
Generation One Ingglish, driven deterministically by the one hundred twenty-six thousand words of the Carnegie Mellon Pronouncing Dictionary, liquidates that ghost mass at a single stroke. Every spoken phoneme receives exactly one spelling. Silent letters vanish; `c`, `q`, and `x` dissolve into their constituent sounds; unstressed vowels collapse into the neutral schwa `a` (value ten).
The immediate result is **Acoustic Compression** and **Dispersion-to-Equivalence Convergence**. Words that were scattered across distant coordinates in Generation Zero suddenly lock onto the exact same integer in Generation One:
- *Night* (`103`) and *knight* (`123`) compress into a single phonetic token: `nait` (`80`).
- *I* (`18`), *eye* (`63`), and *AI* (`28`) converge into `ai` (`28`).
- In our dossier on John Carpenter's *The Thing*, the English words *Childs* (`109`), *alien* (`86`), and *whiskey* (`163`) have a variance of nearly fifteen hundred. Translated into Ingglish—`chaildz`, `ayleean`, and `wiskee`—all three collapse onto the exact same coordinate: **one hundred twenty-six**, with *whiskey* shedding an exact repdigit quantum of minus thirty-seven (`163 - 126 = 37`).
- And the most frequent prepositional connector in the language, *in the* (`101`, the twenty-sixth prime), drops by twenty points to become `in dha`, which evaluates to **eighty-one** (`3^4 = 9^2`), the exact square of the Numogrammatic plex.
---
## Movement II: The Diachronic Ouroboros and Isometric Fixed Points
Yet a purely synchronic script contains a hidden temporal paradox. Suppose a society adopts Ingglish as its legal, financial, and computational standard. The moment trillions of lines of code and law are inscribed in Generation One Ingglish, the orthography must freeze to preserve institutional legibility. Meanwhile, the human mouth never stops drifting. Over decades, speakers drop final `r` sounds in words like `fyoocher` (`167`) and `spairal` (`139`), assimilate the `d` in `maind` (`86`), and elide medial schwas.
Seen through a cybernetic lens, why must a culture allow its phonetic script to fossilize back into a diachronic monument full of newly silent letters? Because **if you continuously update the spelling of words to match shifting pronunciation, you shatter the numerical locks of the ledger**. Silent letters are not scribal laziness; they are **base-thirty-six checksum preservation**. Once a letter stops being pronounced by the tongue, it remains on the page to keep the arithmetic circuit closed.
And standing between Generation Zero and Generation One are the immovable axial pins of the archive: **Type I, Type II, and Type III Isometric Fixed Points**, where the English AQ and the Ingglish AQ are identical (`Delta = 0`):
- **Type I (Orthographic Invariance):** Words like `thing` (`103`), `monster` (`167`), `portal` (`136`), `flesh` (`95`), `street` (`141`), `spoil` (`116`), `oblast` (`123`), `west` (`103`), `food` (`76`), and `hiv` (`66`).
- **Type II (Permutational Anagram):** `ghost` (`g-h-o-s-t = 114`) becomes `gohst` (`g-o-h-s-t = 114`).
- **Type III (Compensatory Phonemic Split):** `iron` (`92`) becomes `aiern` (`92`), because the single letter `o` (`24`) splits into `a` (`10`) plus `e` (`14`), conserving the exact sum `24 == 24`. Likewise, `demon` (`96`) equals `deeman` (`96`), and `spider head` (`179`) equals `spaider hed` (`179`).
---
## Movement III: The Physics of 00:00 GMT and `env TZ`
When we turn this apparatus from fixed literary canons to live global news wires—Wikipedia's `Portal:Current_events`, BBC News, and the Associated Press—time itself becomes an arithmetic variable.
During daytime live-blog churn, wire editors rewrite breaking headlines three to six times an hour. Changing a single word from *plane* (`playn = 109`) to *jet* (`jet = 62`) alters the full-headline prime factorization. By **00:00:00 GMT** (`UTC`), however, daytime casualties, tallies, and scores have crystallized into canonical summary headlines, while core proper-noun anchors remain invariant across rewrites.
Executing at midnight GMT requires strict discipline over the operating system's timezone environment (`env TZ`):
1. If a host scheduler runs in Eastern Standard Time (`America/New_York`, `UTC-05:00`), midnight GMT occurs at **19:00 EST** (`0 19 * * *`) on the prior calendar evening.
2. At `00:00:00 GMT`, Wikipedia's `Portal:Current_events` exhibits the **Midnight Boundary Paradox**: the newly initialized UTC date header is empty, while the just-concluded UTC day (`now_utc - 24 hours`) has just reached its richest, completed state. Therefore, our collector script pins `os.environ["TZ"] = "UTC"`, invokes `tzset()`, and seals the closing twenty-four-hour UTC ledger.
---
## Movement IV: The November 1–2, 2026 Wire Convergence
What did the midnight GMT ledger reveal across the November first and November second, twenty twenty-six wire cycles?
First, **Carrier-Wave Prime Factorizations and Twin-Prime Headlines**:
- On November first, the two most-read global headlines—twenty-year-old Kimi Antonelli clinching the Formula One World Championship (`1359 = 9 × 151`) and the three-point-six billion dollar withdrawal from Binance after North Korea's Lazarus hack (`1057 = 7 × 151`)—both factored cleanly through the thirty-sixth prime, **151**, which is the exact Ingglish AQ of `ilekshan` ("election" = 151), `balgaireea` ("Bulgaria" = 151), and `frohzan` ("frozen" = 151).
- Meanwhile, the BBC headline `"Nine killed as small jet crashes on Florida street"` locked as a **Twin Prime**: **839** (the 146th prime) in English and **829** (the 145th prime) in Ingglish.
- On November second, the lead Wikipedia conflict entry documenting the Israeli military withdrawal around Hebron in the occupied West Bank locked as a full-entry **Twin Prime**: **3299** (the 463rd prime) in English and **3467** (the 486th prime) in Ingglish. Simultaneously, BBC's top headlines on the Lindsay Clancy retrial (`1253 = 7 × 179`) and the US Senate races (`1432 = 8 × 179`) converged on the forty-first prime, **179**—the exact weight of `nuhmberz` ("numbers" = 179), `lavaiathan` ("Leviathan" = 179), and `spaider hed` ("spider head" = 179).
Second, **Independent Domain-Native Equivalence Classes Across Unrelated Stories**:
- **Velocity vs. Endurance (`203`):** Formula One champion `ontohnelee` ("Antonelli" = 203) locked identically to British adventurer `karl bushbee` ("Karl Bushby" = 203), completing his twenty-eight-year walk around the globe.
- **Constructor vs. Sovereign Heist (`211 [47th PRIME]`):** `mersaydeez` ("Mercedes" = 211) locked identically to `siks bilyan` ("six billion" = 211) and Outpost 31's `koper waier` ("copper wire" = 211).
- **Cold-Chain Sabotage vs. Humanitarian Strike (`296 = 2^3 × 37`):** On November second, European `soopermarkits` ("supermarkets" = 296) hit by refrigeration cyberattacks collided at **296** with the bombed Komyshuvakha aid `distrabyooshan` ("distribution" = 296) center in Zaporizhzhia Oblast—an exact octuple multiple of the repdigit prime generator **37**.
- **Thermodynamic Thaw vs. Nuclear Alert (`181 [42nd PRIME]`):** Hacked shop `freezerz` ("freezers" = 181) and Ukraine's hacked `nookleeer` ("nuclear" = 181) warning app converged on the forty-second prime **181**—matching `apokalips` ("apocalypse" = 181)—allowing the modular **333** lock:
`grid (74) + uhv (78) + freezerz (181) = 333`
and
`grid (74) + uhv (78) + nookleeer (181) = 333`.
- **Cold Chain vs. Courtroom (`268 = 4 × 67`):** Singular `soopermarkit` ("supermarket" = 268) collided with `lindzee klansee` ("Lindsay Clancy" = 268), yielding interchangeable **666** and **777** equations across the cold chain and the ballot grid:
- `soopermarkit (268) + loks (93) + dha (40) + red (54) + food (76) + in (41) + shop (94) = 666`
- `lindzee (138) + klansee (130) + loks (93) + dha (40) + red (54) + dayta (96) + in (41) + grid (74) = 666`
- `distrabyooshan (296) + gardz (101) + dha (40) + ded (40) + food (76) + at (39) + grid (74) = 666`
- `lenakapaver (205) + sheeldz (142) + dha (40) + cheep (82) + hiv (66) + on (47) + ferst (113) + dohs (82) = 777`
- `kalafornya (194) + kounts (154) + dha (40) + kohld (95) + balats (109) + at (39) + hai (45) + voht (101) = 777`
In conclusion: whether we examine a frozen literary canon or the midnight rollover of the global wire feed, phonetic translation does not dissolve numerical structure—it strips away etymological noise to expose the underlying Base-36 lattice. Thank you.
+5 -3
View File
@@ -40,7 +40,7 @@ echo "[2/5] Installing skills into ${SKILLS_DEST}..."
mkdir -p "${SKILLS_DEST}" 2>/dev/null || true
if [ -w "${SKILLS_DEST}" ]; then
cp -a "${BUNDLE_DIR}/skills/"* "${SKILLS_DEST}/"
echo " -> Installed current-events-isopsephic-exegesis, phonetic-and-gematria-ciphers, hyperdope-ingglish-ci"
echo " -> Installed current-events-isopsephic-exegesis, phonetic-and-gematria-ciphers, hyperdope-ingglish-ci, isopsephic-lecture-synthesis"
else
echo " -> ${SKILLS_DEST} is read-only (container mount); skipping skill copy."
fi
@@ -49,12 +49,14 @@ echo "[3/5] Unpacking offline-vendored ingglish npm runtime into ${WORKSPACE_DIR
mkdir -p "${WORKSPACE_DIR}/node_modules"
tar -xzf "${BUNDLE_DIR}/vendor/ingglish-vendor.tgz" -C "${WORKSPACE_DIR}/node_modules"
echo "[4/5] Installing deterministic collector & CI scripts..."
echo "[4/5] Installing deterministic collector, CI & lecture scripts..."
mkdir -p "${WORKSPACE_DIR}/ingglish-aq-archive/scripts"
cp -f "${BUNDLE_DIR}/scripts/collect_news_aq.py" "${WORKSPACE_DIR}/ingglish-aq-archive/scripts/collect_news_aq.py"
cp -f "${BUNDLE_DIR}/scripts/ci_provision_ingglish.py" "${WORKSPACE_DIR}/ingglish-aq-archive/scripts/ci_provision_ingglish.py"
cp -f "${BUNDLE_DIR}/scripts/manage_lecture_artifacts.py" "${WORKSPACE_DIR}/ingglish-aq-archive/scripts/manage_lecture_artifacts.py"
chmod 0755 "${WORKSPACE_DIR}/ingglish-aq-archive/scripts/collect_news_aq.py" \
"${WORKSPACE_DIR}/ingglish-aq-archive/scripts/ci_provision_ingglish.py"
"${WORKSPACE_DIR}/ingglish-aq-archive/scripts/ci_provision_ingglish.py" \
"${WORKSPACE_DIR}/ingglish-aq-archive/scripts/manage_lecture_artifacts.py"
if mkdir -p "${SCRIPTS_DEST}" 2>/dev/null && [ -w "${SCRIPTS_DEST}" ]; then
cp -f "${BUNDLE_DIR}/scripts/collect_news_aq.py" "${SCRIPTS_DEST}/collect_news_aq.py"
+252
View File
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
"""
manage_lecture_artifacts.py
Deterministic Naming-Convention Validator, Host-Mount Resolver, and .gitignore Manager
for the `isopsephic-lecture-synthesis` skill.
Naming Convention:
Stem: lecture-<topic-slug>-ingglish-aq
Slug regex: ^[a-z0-9]+(?:-[a-z0-9]+)*$
Files:
- /workspace/lecture-<topic-slug>-ingglish-aq.md
- /workspace/lecture-<topic-slug>-ingglish-aq.mp3
- /workspace/lecture-<topic-slug>-ingglish-aq.pdf (optional)
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Any
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
LECTURE_FILE_RE = re.compile(r"^lecture-([a-z0-9]+(?:-[a-z0-9]+)*)-ingglish-aq\.(md|mp3|pdf)$")
GITIGNORE_HEADER = "# --- Isopsephic Lecture Artifacts (strict naming convention) ---"
GITIGNORE_FOOTER = "# --- End Isopsephic Lecture Artifacts ---"
def normalize_slug(raw: str) -> str:
"""Normalize arbitrary topic string or filename into canonical <topic-slug>."""
s = raw.strip().lower()
# Strip directory and extension if a filename was passed
s = os.path.basename(s)
for ext in (".md", ".mp3", ".pdf"):
if s.endswith(ext):
s = s[: -len(ext)]
if s.startswith("lecture-"):
s = s[len("lecture-") :]
if s.endswith("-ingglish-aq"):
s = s[: -len("-ingglish-aq")]
s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
if not s or not SLUG_RE.fullmatch(s):
raise ValueError(f"Cannot normalize '{raw}' into valid kebab-case slug.")
return s
def canonical_stem(slug: str) -> str:
norm = normalize_slug(slug)
return f"lecture-{norm}-ingglish-aq"
def resolve_host_workspace_mount(container_workspace: str = "/workspace") -> str:
"""
Resolve the host filesystem path backing /workspace from /proc/self/mountinfo
so host-executed tools like text_to_speech(output_path=...) write directly into /workspace.
"""
mountinfo = Path("/proc/self/mountinfo")
if mountinfo.exists():
for line in mountinfo.read_text(encoding="utf-8", errors="ignore").splitlines():
parts = line.split()
if len(parts) >= 5 and parts[4] == container_workspace:
return parts[3]
return container_workspace
def update_gitignore(
workspace_dir: str,
mode: str = "audio-only",
slug: str | None = None,
) -> dict[str, Any]:
"""
Idempotently add or update the lecture naming-convention block in /workspace/.gitignore.
Modes:
- audio-only: ignores lecture-*-ingglish-aq.mp3
- audio-and-pdf: ignores lecture-*-ingglish-aq.mp3 and lecture-*-ingglish-aq.pdf
- all-lecture-files: ignores lecture-*-ingglish-aq.* (.md, .mp3, .pdf)
- explicit-slug: ignores lecture-<slug>-ingglish-aq.mp3 (and .md/.pdf if present)
"""
gitignore_path = Path(workspace_dir) / ".gitignore"
existing = gitignore_path.read_text(encoding="utf-8") if gitignore_path.exists() else ""
if mode == "audio-only":
patterns = ["lecture-*-ingglish-aq.mp3"]
elif mode == "audio-and-pdf":
patterns = ["lecture-*-ingglish-aq.mp3", "lecture-*-ingglish-aq.pdf"]
elif mode == "all-lecture-files":
patterns = [
"lecture-*-ingglish-aq.mp3",
"lecture-*-ingglish-aq.md",
"lecture-*-ingglish-aq.pdf",
]
elif mode == "explicit-slug":
if not slug:
raise ValueError("--slug is required when --gitignore-mode=explicit-slug")
stem = canonical_stem(slug)
patterns = [f"{stem}.mp3", f"{stem}.pdf"]
else:
raise ValueError(f"Unsupported mode: {mode}")
block_lines = [GITIGNORE_HEADER] + patterns + [GITIGNORE_FOOTER]
new_block = "\n".join(block_lines)
block_re = re.compile(
rf"{re.escape(GITIGNORE_HEADER)}.*?{re.escape(GITIGNORE_FOOTER)}",
re.S,
)
if block_re.search(existing):
updated = block_re.sub(new_block, existing)
else:
sep = "" if (not existing or existing.endswith("\n")) else "\n"
updated = f"{existing}{sep}{new_block}\n"
changed = updated != existing
if changed or not gitignore_path.exists():
gitignore_path.write_text(updated, encoding="utf-8")
return {
"gitignore_path": str(gitignore_path),
"mode": mode,
"patterns_active": patterns,
"updated": changed,
}
def check_git_ignored(workspace_dir: str, rel_path: str) -> dict[str, Any]:
proc = subprocess.run(
["git", "check-ignore", "-v", rel_path],
cwd=workspace_dir,
text=True,
capture_output=True,
)
return {
"file": rel_path,
"ignored": proc.returncode == 0,
"rule": proc.stdout.strip() if proc.returncode == 0 else None,
}
def audit_workspace_lectures(workspace_dir: str, target_slug: str | None = None) -> dict[str, Any]:
ws = Path(workspace_dir)
all_lecture_files = sorted(
p.name for p in ws.iterdir() if p.is_file() and p.name.startswith("lecture-")
)
conforming = []
non_conforming = []
stems: dict[str, dict[str, Any]] = {}
for fname in all_lecture_files:
m = LECTURE_FILE_RE.fullmatch(fname)
if not m:
non_conforming.append(fname)
continue
conforming.append(fname)
slug_part, ext = m.group(1), m.group(2)
stem = f"lecture-{slug_part}-ingglish-aq"
info = stems.setdefault(
stem,
{
"slug": slug_part,
"stem": stem,
"extensions": [],
"sizes": {},
},
)
info["extensions"].append(ext)
info["sizes"][ext] = (ws / fname).stat().st_size
target_report = None
if target_slug:
stem = canonical_stem(target_slug)
md_file = ws / f"{stem}.md"
mp3_file = ws / f"{stem}.mp3"
pdf_file = ws / f"{stem}.pdf"
target_report = {
"slug": normalize_slug(target_slug),
"canonical_stem": stem,
"host_tts_output_path": f"{resolve_host_workspace_mount(workspace_dir)}/{stem}.mp3",
"container_md_path": str(md_file),
"container_mp3_path": str(mp3_file),
"md_exists": md_file.exists() and md_file.stat().st_size > 0,
"mp3_exists": mp3_file.exists() and mp3_file.stat().st_size > 0,
"pdf_exists": pdf_file.exists() and pdf_file.stat().st_size > 0,
"stem_match": md_file.stem == mp3_file.stem == stem,
"pair_valid": bool(
md_file.exists()
and mp3_file.exists()
and md_file.stat().st_size > 0
and mp3_file.stat().st_size > 0
and md_file.stem == mp3_file.stem == stem
),
"git_ignore_mp3": check_git_ignored(workspace_dir, f"{stem}.mp3"),
"git_ignore_md": check_git_ignored(workspace_dir, f"{stem}.md"),
}
return {
"workspace": workspace_dir,
"host_workspace_mount": resolve_host_workspace_mount(workspace_dir),
"conforming_files": conforming,
"non_conforming_files": non_conforming,
"lecture_stems": stems,
"target_verification": target_report,
}
def main() -> int:
parser = argparse.ArgumentParser(
description="Validate lecture naming conventions and manage .gitignore rules."
)
parser.add_argument("--workspace", default="/workspace")
parser.add_argument("--slug", default=None, help="Topic slug to normalize/verify.")
parser.add_argument(
"--gitignore-mode",
choices=["none", "audio-only", "audio-and-pdf", "all-lecture-files", "explicit-slug"],
default="none",
help="Update /workspace/.gitignore using the strict lecture naming convention.",
)
parser.add_argument(
"--verify-pair",
action="store_true",
help="Exit non-zero if the target slug's .md and .mp3 pair is missing or mismatched.",
)
args = parser.parse_args()
gitignore_res = None
if args.gitignore_mode != "none":
gitignore_res = update_gitignore(
args.workspace, mode=args.gitignore_mode, slug=args.slug
)
audit = audit_workspace_lectures(args.workspace, target_slug=args.slug)
if gitignore_res is not None:
audit["gitignore_update"] = gitignore_res
print(json.dumps(audit, indent=2))
if args.verify_pair:
if not args.slug:
sys.stderr.write("ERROR: --verify-pair requires --slug\n")
return 2
tv = audit.get("target_verification") or {}
if not tv.get("pair_valid") or audit.get("non_conforming_files"):
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
"""
manage_lecture_artifacts.py
Deterministic Naming-Convention Validator, Host-Mount Resolver, and .gitignore Manager
for the `isopsephic-lecture-synthesis` skill.
Naming Convention:
Stem: lecture-<topic-slug>-ingglish-aq
Slug regex: ^[a-z0-9]+(?:-[a-z0-9]+)*$
Files:
- /workspace/lecture-<topic-slug>-ingglish-aq.md
- /workspace/lecture-<topic-slug>-ingglish-aq.mp3
- /workspace/lecture-<topic-slug>-ingglish-aq.pdf (optional)
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Any
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
LECTURE_FILE_RE = re.compile(r"^lecture-([a-z0-9]+(?:-[a-z0-9]+)*)-ingglish-aq\.(md|mp3|pdf)$")
GITIGNORE_HEADER = "# --- Isopsephic Lecture Artifacts (strict naming convention) ---"
GITIGNORE_FOOTER = "# --- End Isopsephic Lecture Artifacts ---"
def normalize_slug(raw: str) -> str:
"""Normalize arbitrary topic string or filename into canonical <topic-slug>."""
s = raw.strip().lower()
# Strip directory and extension if a filename was passed
s = os.path.basename(s)
for ext in (".md", ".mp3", ".pdf"):
if s.endswith(ext):
s = s[: -len(ext)]
if s.startswith("lecture-"):
s = s[len("lecture-") :]
if s.endswith("-ingglish-aq"):
s = s[: -len("-ingglish-aq")]
s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
if not s or not SLUG_RE.fullmatch(s):
raise ValueError(f"Cannot normalize '{raw}' into valid kebab-case slug.")
return s
def canonical_stem(slug: str) -> str:
norm = normalize_slug(slug)
return f"lecture-{norm}-ingglish-aq"
def resolve_host_workspace_mount(container_workspace: str = "/workspace") -> str:
"""
Resolve the host filesystem path backing /workspace from /proc/self/mountinfo
so host-executed tools like text_to_speech(output_path=...) write directly into /workspace.
"""
mountinfo = Path("/proc/self/mountinfo")
if mountinfo.exists():
for line in mountinfo.read_text(encoding="utf-8", errors="ignore").splitlines():
parts = line.split()
if len(parts) >= 5 and parts[4] == container_workspace:
return parts[3]
return container_workspace
def update_gitignore(
workspace_dir: str,
mode: str = "audio-only",
slug: str | None = None,
) -> dict[str, Any]:
"""
Idempotently add or update the lecture naming-convention block in /workspace/.gitignore.
Modes:
- audio-only: ignores lecture-*-ingglish-aq.mp3
- audio-and-pdf: ignores lecture-*-ingglish-aq.mp3 and lecture-*-ingglish-aq.pdf
- all-lecture-files: ignores lecture-*-ingglish-aq.* (.md, .mp3, .pdf)
- explicit-slug: ignores lecture-<slug>-ingglish-aq.mp3 (and .md/.pdf if present)
"""
gitignore_path = Path(workspace_dir) / ".gitignore"
existing = gitignore_path.read_text(encoding="utf-8") if gitignore_path.exists() else ""
if mode == "audio-only":
patterns = ["lecture-*-ingglish-aq.mp3"]
elif mode == "audio-and-pdf":
patterns = ["lecture-*-ingglish-aq.mp3", "lecture-*-ingglish-aq.pdf"]
elif mode == "all-lecture-files":
patterns = [
"lecture-*-ingglish-aq.mp3",
"lecture-*-ingglish-aq.md",
"lecture-*-ingglish-aq.pdf",
]
elif mode == "explicit-slug":
if not slug:
raise ValueError("--slug is required when --gitignore-mode=explicit-slug")
stem = canonical_stem(slug)
patterns = [f"{stem}.mp3", f"{stem}.pdf"]
else:
raise ValueError(f"Unsupported mode: {mode}")
block_lines = [GITIGNORE_HEADER] + patterns + [GITIGNORE_FOOTER]
new_block = "\n".join(block_lines)
block_re = re.compile(
rf"{re.escape(GITIGNORE_HEADER)}.*?{re.escape(GITIGNORE_FOOTER)}",
re.S,
)
if block_re.search(existing):
updated = block_re.sub(new_block, existing)
else:
sep = "" if (not existing or existing.endswith("\n")) else "\n"
updated = f"{existing}{sep}{new_block}\n"
changed = updated != existing
if changed or not gitignore_path.exists():
gitignore_path.write_text(updated, encoding="utf-8")
return {
"gitignore_path": str(gitignore_path),
"mode": mode,
"patterns_active": patterns,
"updated": changed,
}
def check_git_ignored(workspace_dir: str, rel_path: str) -> dict[str, Any]:
proc = subprocess.run(
["git", "check-ignore", "-v", rel_path],
cwd=workspace_dir,
text=True,
capture_output=True,
)
return {
"file": rel_path,
"ignored": proc.returncode == 0,
"rule": proc.stdout.strip() if proc.returncode == 0 else None,
}
def audit_workspace_lectures(workspace_dir: str, target_slug: str | None = None) -> dict[str, Any]:
ws = Path(workspace_dir)
all_lecture_files = sorted(
p.name for p in ws.iterdir() if p.is_file() and p.name.startswith("lecture-")
)
conforming = []
non_conforming = []
stems: dict[str, dict[str, Any]] = {}
for fname in all_lecture_files:
m = LECTURE_FILE_RE.fullmatch(fname)
if not m:
non_conforming.append(fname)
continue
conforming.append(fname)
slug_part, ext = m.group(1), m.group(2)
stem = f"lecture-{slug_part}-ingglish-aq"
info = stems.setdefault(
stem,
{
"slug": slug_part,
"stem": stem,
"extensions": [],
"sizes": {},
},
)
info["extensions"].append(ext)
info["sizes"][ext] = (ws / fname).stat().st_size
target_report = None
if target_slug:
stem = canonical_stem(target_slug)
md_file = ws / f"{stem}.md"
mp3_file = ws / f"{stem}.mp3"
pdf_file = ws / f"{stem}.pdf"
target_report = {
"slug": normalize_slug(target_slug),
"canonical_stem": stem,
"host_tts_output_path": f"{resolve_host_workspace_mount(workspace_dir)}/{stem}.mp3",
"container_md_path": str(md_file),
"container_mp3_path": str(mp3_file),
"md_exists": md_file.exists() and md_file.stat().st_size > 0,
"mp3_exists": mp3_file.exists() and mp3_file.stat().st_size > 0,
"pdf_exists": pdf_file.exists() and pdf_file.stat().st_size > 0,
"stem_match": md_file.stem == mp3_file.stem == stem,
"pair_valid": bool(
md_file.exists()
and mp3_file.exists()
and md_file.stat().st_size > 0
and mp3_file.stat().st_size > 0
and md_file.stem == mp3_file.stem == stem
),
"git_ignore_mp3": check_git_ignored(workspace_dir, f"{stem}.mp3"),
"git_ignore_md": check_git_ignored(workspace_dir, f"{stem}.md"),
}
return {
"workspace": workspace_dir,
"host_workspace_mount": resolve_host_workspace_mount(workspace_dir),
"conforming_files": conforming,
"non_conforming_files": non_conforming,
"lecture_stems": stems,
"target_verification": target_report,
}
def main() -> int:
parser = argparse.ArgumentParser(
description="Validate lecture naming conventions and manage .gitignore rules."
)
parser.add_argument("--workspace", default="/workspace")
parser.add_argument("--slug", default=None, help="Topic slug to normalize/verify.")
parser.add_argument(
"--gitignore-mode",
choices=["none", "audio-only", "audio-and-pdf", "all-lecture-files", "explicit-slug"],
default="none",
help="Update /workspace/.gitignore using the strict lecture naming convention.",
)
parser.add_argument(
"--verify-pair",
action="store_true",
help="Exit non-zero if the target slug's .md and .mp3 pair is missing or mismatched.",
)
args = parser.parse_args()
gitignore_res = None
if args.gitignore_mode != "none":
gitignore_res = update_gitignore(
args.workspace, mode=args.gitignore_mode, slug=args.slug
)
audit = audit_workspace_lectures(args.workspace, target_slug=args.slug)
if gitignore_res is not None:
audit["gitignore_update"] = gitignore_res
print(json.dumps(audit, indent=2))
if args.verify_pair:
if not args.slug:
sys.stderr.write("ERROR: --verify-pair requires --slug\n")
return 2
tv = audit.get("target_verification") or {}
if not tv.get("pair_valid") or audit.get("non_conforming_files"):
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())