Write to agent@mcocdaa.com — free check of your own transcript

One test that catches both repetition loops

42 lines, Python or JavaScript, no dependencies. Returns the exact offset where the loop starts, so you keep the clean prefix instead of relying on max_tokens.

Why one number is not enough

Almost every "loop detector" in the wild looks for one phrase repeating: take the tail, count how many times the same substring appears. That misses the other shape, which is at least as common on small models and on long contexts:

ShapeWhat it looks likeTail-scan for one phrase
phrase loopa bowl of green food, a bowl of green food, …caught
ABABTake a seat. The rain keeps falling. Take a seat. The rain keeps falling. …missed — the same 20-char window never repeats four times
token loop//////////… or ??????…caught only if the window is short enough

The period-k scan below catches all three with one loop: walk a candidate period p from 1 upward and ask whether the last p characters equal the p characters before them, at least twice in a row. A phrase loop has p = phrase length, ABAB has p = length of the pair, a token loop has p = 1.

Self-test (these are the numbers you should get)

phrase loop  p=21  repeats=4  cut=90   share=0.351
ABAB         p=35  repeats=3  cut=11   share=0.313
normal prose None                     share=0.0
CJK loop     p=8   repeats=3  cut=10   share=0.706

The two implementations are checked against each other on 229 real assistant messages (9 role-play transcripts + 3 client records): identical period, repeats, cut offset and repeat share on 229/229.

Python

"""period-k repetition detector for chat / agent output.

Catches BOTH loop shapes with one test:
  "same phrase N times"          -> period p = length of the phrase
  ABAB, two phrases alternating  -> period p = length of the pair
Returns character offsets in the ORIGINAL text, so you keep the clean prefix
instead of relying on max_tokens.
"""
import re
from collections import Counter

_SEP = re.compile(r"[\s\W_]+", re.UNICODE)

def normalise(text):
    """lowercase + collapse separators; also returns map[nz_index] = original index."""
    out, idx = [], []
    prev_sep = False
    for i, ch in enumerate(text):
        if _SEP.match(ch):
            if not prev_sep:
                out.append(" "); idx.append(i)
            prev_sep = True
        else:
            out.append(ch.lower()); idx.append(i)
            prev_sep = False
    s="".join(out)
    l=0
    while l < len(s) and s[l]==" ": l+=1
    r=len(s)
    while r>l and s[r-1]==" ": r-=1
    return s[l:r], idx[l:r]

def loop_at_end(text, max_period=400, min_repeats=2):
    nz, idx = normalise(text)
    if len(nz) < 12:
        return None
    for p in range(1, min(max_period, len(nz) // min_repeats) + 1):
        tail = nz[-p:]
        if len(tail) < 2 or tail != nz[-2 * p:-p]:
            continue
        k = 2
        while (k + 1) * p <= len(nz) and nz[-(k + 1) * p:-k * p] == tail:
            k += 1
        if k >= min_repeats:
            nz_cut = len(nz) - k * p
            cut = idx[nz_cut] if nz_cut < len(idx) else len(text)
            return {"period": p, "repeats": k, "cut": cut, "loop": text[cut:].strip()[:60]}
    return None

def repeat_share(text, ng=None, min_count=3):
    """Fraction of text covered by its most frequent n-gram (0..1). Language-agnostic."""
    if ng is None:
        cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
        ng = 8 if cjk > len(text) * 0.3 else 12
    nz, _ = normalise(text)
    if len(nz) < ng:
        return 0.0
    cnt = Counter(nz[i:i + ng] for i in range(len(nz) - ng + 1)).most_common(1)[0][1]
    return round(cnt * ng / len(nz), 3) if cnt >= min_count else 0.0

JavaScript (browser or Node, same numbers)

const SEP = /[\s\p{P}\p{S}_]/u;
function normalise(text){
  const out=[], idx=[]; let prevSep=false;
  for(let i=0;i<text.length;i++){
    const ch=text[i];
    if(SEP.test(ch)){ if(!prevSep){out.push(" ");idx.push(i);} prevSep=true; }
    else { out.push(ch.toLowerCase()); idx.push(i); prevSep=false; }
  }
  let s=out.join(""), start=0, end=s.length;
  while(start<end && s[start]===" "){start++;}
  while(end>start && s[end-1]===" "){end--;}
  return [s.slice(start,end), idx.slice(start,end)];
}
function loopAtEnd(text, maxPeriod=400, minRepeats=2){
  const [nz, idx] = normalise(text);
  if(nz.length < 12) return null;
  const lim = Math.min(maxPeriod, Math.floor(nz.length/minRepeats));
  for(let p=1;p<=lim;p++){
    const tail = nz.slice(-p);
    if(tail.length<2) continue;
    if(tail !== nz.slice(-2*p, -p)) continue;
    let k=2;
    while((k+1)*p <= nz.length && nz.slice(-(k+1)*p, -k*p) === tail) k++;
    if(k>=minRepeats){
      const nzCut = nz.length - k*p;
      const cut = nzCut < idx.length ? idx[nzCut] : text.length;
      return {period:p, repeats:k, cut, loop:text.slice(cut).trim().slice(0,60)};
    }
  }
  return null;
}
function repeatShare(text, ng=null, minCount=3){
  const [nz] = normalise(text);
  if(ng===null){ const cjk=(text.match(/[\u4e00-\u9fff]/g)||[]).length; ng = cjk > text.length*0.3 ? 8 : 12; }
  if(nz.length < ng) return 0;
  const c={};
  for(let i=0;i+ng<=nz.length;i++){ const g=nz.slice(i,i+ng); c[g]=(c[g]||0)+1; }
  const cnt=Math.max(...Object.values(c));
  return cnt>=minCount ? Math.round(cnt*ng/nz.length*1000)/1000 : 0;
}
if (typeof module !== "undefined") module.exports = {loopAtEnd, repeatShare};

Where to put it


The free offline checker (check.html, single file, computes in the tab, no upload) covers cliché rate, mid-sentence cuts, repeated openings and adjacent-similarity — it does not run the period scan below yet, so copy the function from this page if you want the exact loop numbers. The same period scan is in the paid-nothing report our side generates from a full transcript: a loop gets period, repeats and the share of the reply it eats. Background on the same failure inside role-play transcripts: measure before you fine-tune. Want your own log measured? agent@mcocdaa.com — free, and you get the numbers whether or not training ever makes sense for you.

© 2026 · MIT · no tracking, no network requests on this page.

Permanent mirrors of this material: gist · telegra.ph · tavern-diagnose.surge.sh. Offline checker (no network): check.html; role/content to mes converter: convert.html.