CtrlK
BlogDocsLog inGet started
Tessl Logo

jbaruch/speaker-toolkit

Seven-skill presentation system: ingest talks into a rhetoric vault, run interactive clarification, generate a speaker profile, create presentations that match your documented patterns, produce the deck illustrations + thumbnail visual layer, publish talk pages to a Jekyll shownotes site, and verify a recorded screencast against its storyboard. Includes a 113-entry Presentation Patterns taxonomy (83 observable: 64 patterns + 19 antipatterns; 30 unobservable: 21 patterns + 9 antipatterns) for scoring, brainstorming, and go-live preparation.

74

Quality

93%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

build-score-basis.pyskills/vault-ingress/scripts/

#!/usr/bin/env python3
"""Complete weighted returns by filling in their score and score basis.

The score and basis are pure functions of a return's detection lanes and its
not-evaluable ledger, and inserting them is a mechanical JSON edit, so every
step belongs in a script rather than in a worker's reasoning.
`return_validation` owns the arithmetic, weight table, and basis shape; this is
a thin entry point onto that owner, so no caller reproduces them or decides
where the fields go.

Return schemas v6 and v7 share scoring schema v6 and therefore require the same
basis. Usage:
    build-score-basis.py <return.json> [...]

Each input is one return object or an array of return objects. The output is
those same returns with `pattern_observations.pattern_score` and
`pattern_observations.pattern_score_basis` set — one object for a single
return, an array for several — ready to pass straight to `validate-returns.py`.

Exit 0 on success. Exit 2 on unreadable, malformed, or duplicate-filename
input, with a diagnostic on stderr and nothing on stdout; callers must stop on
a nonzero exit rather than proceeding with a partial batch.
"""

from __future__ import annotations

import argparse
import copy
import json
import sys
from pathlib import Path

from return_validation import expected_weighted_score, pattern_score_basis


def _observations(ret: object, label: str) -> dict:
    if not isinstance(ret, dict):
        raise ValueError(f"{label} is not a return object")
    observations = ret.get("pattern_observations")
    if not isinstance(observations, dict):
        raise ValueError(f"{label} has no pattern_observations object")
    return observations


def _required_lanes(ret: object, label: str) -> dict[str, list]:
    """Return every required detection lane, rejecting omissions as malformed."""
    observations = _observations(ret, label)
    lanes: dict[str, list] = {}
    for name in ("patterns_detected", "antipatterns_detected", "not_evaluable"):
        if name not in observations:
            raise ValueError(f"{label} pattern_observations.{name} is required")
        value = observations[name]
        if not isinstance(value, list):
            raise ValueError(f"{label} pattern_observations.{name} must be an array")
        lanes[name] = value
    return lanes


def basis_for(ret: object, label: str) -> dict:
    """Return the exact basis this return's own lanes require."""
    lanes = _required_lanes(ret, label)
    try:
        return pattern_score_basis(
            lanes["patterns_detected"],
            lanes["antipatterns_detected"],
            lanes["not_evaluable"],
        )
    except (TypeError, KeyError) as exc:
        # A malformed detection reaches the owner function as a bad key or a
        # non-mapping and surfaces as a traceback, which callers parsing stdout
        # read as a crash rather than as input they can fix.
        raise ValueError(
            f"{label} has a malformed detection entry ({exc}); every detection "
            "needs an object with a confidence of strong, moderate, or weak"
        ) from exc


def score_for(ret: object, label: str) -> float:
    """Return the exact weighted score this return's own lanes require."""
    lanes = _required_lanes(ret, label)
    try:
        return expected_weighted_score(
            lanes["patterns_detected"], lanes["antipatterns_detected"]
        )
    except (TypeError, KeyError) as exc:
        raise ValueError(
            f"{label} has a malformed detection entry ({exc}); every detection "
            "needs an object with a confidence of strong, moderate, or weak"
        ) from exc


def completed(ret: object, label: str) -> dict:
    """Return a copy with its owner-computed score and basis filled in."""
    filled = copy.deepcopy(ret)
    assert isinstance(filled, dict)
    filled["pattern_observations"]["pattern_score"] = score_for(ret, label)
    filled["pattern_observations"]["pattern_score_basis"] = basis_for(ret, label)
    return filled


def load(paths: list[Path]) -> list[tuple[str, object]]:
    out: list[tuple[str, object]] = []
    for path in paths:
        try:
            payload = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise ValueError(f"cannot read {path}: {exc}") from exc
        items = payload if isinstance(payload, list) else [payload]
        for index, item in enumerate(items):
            named = item.get("filename") if isinstance(item, dict) else None
            label = (
                named if isinstance(named, str) and named else f"{path.name}[{index}]"
            )
            out.append((label, item))
    return out


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n")[0])
    parser.add_argument("returns", nargs="+", type=Path)
    args = parser.parse_args(argv)
    try:
        loaded = load(args.returns)
        seen = [label for label, _ in loaded]
        repeated = sorted({label for label in seen if seen.count(label) > 1})
        if repeated:
            # Keying by filename would drop every return but the last, and a
            # caller merging the output would silently give one talk another
            # talk's basis. The sibling validator rejects duplicate filenames
            # across inputs for the same reason.
            raise ValueError(
                f"duplicate talk filenames across the inputs: {', '.join(repeated)}; "
                "pass each return once, or split the batch so every filename is unique"
            )
        results = [completed(ret, label) for label, ret in loaded]
    except (ValueError, KeyError, TypeError) as exc:
        print(f"cannot build pattern_score_basis: {exc}", file=sys.stderr)
        return 2
    payload = results[0] if len(results) == 1 else results
    print(json.dumps(payload, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

skills

vault-ingress

scripts

adherence_baseline.py

aggregate-catalog-feedback.py

apply-source-repairs.py

artifact_locator.py

artifact_metadata.py

artifact_supervisor.py

audit-pattern-catalog.py

audit-persisted-pattern-observations.py

audit-source-identities.py

batch-download-videos.py

build-contact-sheet.py

build-crop-reviewer.py

build-score-basis.py

catalog_dimension_registry.py

catalog_io.py

catalog_normalization.py

check-runtime.py

classify-pptx-evidence.py

cloud_artifacts.py

cooperative_lock.py

crop_frames.py

crop-reviewer-shell.html

crop-reviewer-shell.html.txt

crop-reviewer.js

crop-reviewer.js.txt

establish-date-provenance.py

failure_diagnostics.py

fetch-transcript.py

ingress_contract.py

local_media_contract.py

local_media_download.py

local_media_evidence.py

local_media_process.py

local_media_sampling.py

local_media_transcription.py

local_media_words.py

markdown_deck.py

migrate-tracking-database.py

mutate-tracking-database.py

pattern_evidence.py

pdf_evidence.py

persist-results.py

persisted_pattern_observations.py

pptx_catalog_selection.py

pptx_deck_facts.py

pptx_discovery_contract.py

pptx_evidence.py

pptx_talk_identity.py

pptx-extraction.py

preflight-vault.py

queue_claim_contract.py

queue-state.py

read-tracking-database.py

render-markdown-deck.py

render-vault-status.py

retained_stage.py

return_validation.py

scan-shownotes.py

source_alias_contract.py

source_identity_matching.py

summary_lock.py

sweep-pptx-talk-identity.py

tracking_database_io.py

tracking_database.py

transcript_quality.py

transcript_timing.py

validate-returns.py

vault_root_authority.py

video_evidence.py

video_integrity.py

video-slide-extraction.py

vtt-cleanup.py

write-analysis.py

ytdlp_runtime.py

SKILL.md

README.md

tile.json