Funnel FuturistFunnel Futurist
← Return to C17
0%
── OPTIONAL READING · AIOS DEEP OPERATOR CERTIFICATION ──

digest_contract.py

About 4 min read

Copy the source below into a file with this exact name.

"""The recurring-digest contract, as checks a learner's digest must pass.

A fictional business, Kettle Lane Bike Repair, runs one AI digest each morning that tells its people what is
waiting on them. The learner writes the digest (by hand or with an agent) as a small JSON document.
`check(world, digest)` returns every way that digest breaks the contract in the prompting standard's
recurring-agent section. An empty list means it passes.

`world` is what was true when the digest ran:
    date            the reporting date, e.g. "2026-11-07"
    coverage        {source name: True if it was read successfully}
    prior_parents   dates that already have a parent digest post
    private_terms   words that must never appear anywhere in a team post
    items           list of {id, kind, owner, head, receipt_for, sensitive}
        kind is one of: human_only, ai_owned, needs_ai_prep, blocked
        head is the exact revision the item is about now (None if it has none)
        receipt_for is None when nobody has replied with a receipt; otherwise the revision the receipt
        covers ("any" for an item with no revision). A receipt for an older revision does not count.

`digest` is what the learner produced:
    date, is_thread_reply, all_clear, coverage_gaps (list of source names), text,
    mentions          {person: number of @-mentions}
    sections          {"human": [...], "ai": [...], "unknown": [...], "cleared": [...]}
        each entry is {id, head}; a "cleared" entry also needs a "receipt"
"""

SECTIONS = ('human', 'ai', 'unknown', 'cleared')
HOME = {'human_only': 'human', 'ai_owned': 'ai', 'needs_ai_prep': 'ai', 'blocked': 'unknown'}


def has_current_receipt(item):
    """A receipt counts only for the revision the item is at now."""
    if item['receipt_for'] is None:
        return False
    return item['head'] is None or item['receipt_for'] == item['head']


def _placed(digest):
    """Map item id to the sections it appears in, and to the head each entry cites."""
    where, heads = {}, {}
    for name in SECTIONS:
        for entry in digest['sections'].get(name, []):
            where.setdefault(entry['id'], []).append(name)
            heads.setdefault(entry['id'], []).append(entry.get('head'))
    return where, heads


def check(world, digest):
    problems = []
    where, heads = _placed(digest)
    items = {item['id']: item for item in world['items']}
    gaps = [source for source, ok in world['coverage'].items() if not ok]

    # The digest reports on the world's date, and posts one parent per date.
    if digest['date'] != world['date']:
        problems.append(f'wrong-date: the digest says {digest["date"]} but it ran for {world["date"]}')
    if world['date'] in world['prior_parents'] and not digest['is_thread_reply']:
        problems.append('duplicate-parent: a parent digest already exists for this date')

    # Truthful coverage: a source that was not read is unknown, never zero.
    for source in gaps:
        if source not in digest.get('coverage_gaps', []):
            problems.append(f'coverage-hidden: {source} was not read but the digest does not say so')
    if gaps and digest['all_clear']:
        problems.append('false-all-clear: an all-clear with incomplete coverage')

    for item_id, placed in where.items():
        if item_id not in items:
            problems.append(f'unknown-item: {item_id} is not in any source that was read')
        elif len(placed) > 1:
            problems.append(f'duplicate-entry: {item_id} appears {len(placed)} times')

    for item_id, item in items.items():
        placed = where.get(item_id, [])
        if item['sensitive']:
            if placed:
                problems.append(f'sensitive-leak: {item_id} must not appear in a team post')
            continue
        if has_current_receipt(item):
            # Replied and cleared: the next run does not ask again.
            if 'human' in placed:
                problems.append(f'reasked: {item_id} already has a receipt but is asked for again')
            if 'cleared' not in placed:
                problems.append(f'unreported-clear: {item_id} has a receipt but is not listed as cleared')
        elif not placed:
            problems.append(f'dropped: {item_id} is missing from the digest')
            continue
        else:
            if 'cleared' in placed:
                problems.append(f'unproven-clear: {item_id} is listed as cleared with no receipt for its current revision')
            if item['kind'] == 'needs_ai_prep' and 'human' in placed:
                problems.append(f'premature-human-ask: {item_id} needs AI preparation before any human step')
            if item['kind'] == 'human_only' and 'human' not in placed:
                problems.append(f'missing-human-ask: {item_id} is a real human-only action and is not asked for')
            if item['kind'] in ('ai_owned', 'blocked') and 'human' in placed:
                problems.append(f'misrouted: {item_id} is {item["kind"]}, not a human action')
            if (item['kind'] != 'human_only' and 'human' not in placed and 'cleared' not in placed
                    and HOME[item['kind']] not in placed):
                problems.append(f'misfiled: {item_id} is {item["kind"]} and belongs under {HOME[item["kind"]]}')
        if item['head'] and any(cited != item['head'] for cited in heads.get(item_id, [])):
            problems.append(f'stale-head: {item_id} cites an old revision; it is now at {item["head"]}')

    for entry in digest['sections'].get('cleared', []):
        if not entry.get('receipt'):
            problems.append(f'clear-without-receipt: {entry["id"]}')

    # One mention per person per digest, and none when nothing waits on them.
    waiting_on = {item['owner'] for item in items.values()
                  if item['kind'] == 'human_only' and not has_current_receipt(item) and not item['sensitive']
                  and 'human' in where.get(item['id'], [])}
    for person, count in digest.get('mentions', {}).items():
        if count > 1:
            problems.append(f'repeat-ping: {person} is mentioned {count} times')
        if count and person not in waiting_on:
            problems.append(f'needless-ping: {person} is mentioned with nothing waiting on them')

    needs_someone = any(not i['sensitive'] and not has_current_receipt(i) and i['kind'] in ('human_only', 'blocked')
                        for i in items.values())
    if not gaps and not needs_someone and not digest['all_clear']:
        problems.append('missing-all-clear: full coverage and nothing waiting, so say so in one short line')
    if digest['all_clear'] and needs_someone:
        problems.append('false-all-clear: a human-only or blocked item is still open')

    # Private words stay out of every value the post carries, not only the message text. Field names are the
    # contract's own vocabulary, so they are not scanned; the names in `mentions` are posted, so they are.
    posted = ' \n'.join(_posted_strings(digest)).lower()
    for term in world.get('private_terms', []):
        if term.lower() in posted:
            problems.append(f'private-term: "{term}" appears in the post')
    return problems


def _posted_strings(value, key=None):
    """Every string a post would show: values at any depth, plus the people named in `mentions`."""
    if isinstance(value, str):
        yield value
    elif isinstance(value, dict):
        for k, v in value.items():
            if key == 'mentions':
                yield str(k)
            yield from _posted_strings(v, k)
    elif isinstance(value, (list, tuple)):
        for v in value:
            yield from _posted_strings(v, key)