2525import argparse
2626import datetime as _dt
2727import json
28+ import math
2829import re
2930import sys
3031from pathlib import Path
@@ -598,13 +599,63 @@ def emit_formalise(res: dict):
598599# deferred follow-up (still open) rather than the shipped task itself.
599600_FOLLOWUP_WORDS = ("follow" , "restore" , "parked" , "remain" , "blocked" , "later" ,
600601 "next step" , "next-step" , "deferred" )
602+ # Wording that makes a reference line an assertion the work is DONE, rather than
603+ # a passing mention. `jax-substructure-simulator.md` opens "the 4
604+ # `jax_substructure/` prompts shipped to `main`" — that sentence resolves four
605+ # prompts, and is the difference between a citation and a completion claim.
606+ _SHIPPED_WORDS = ("shipped" , "delivered" , "merged" , "completed" , "closed out" ,
607+ "close-out" , "landed" , "is done" , "now on main" )
608+ #: A rare identifier says far more than a shared English word. Backticked
609+ #: snake_case / CamelCase with at least two segments — `chunk_size`,
610+ #: `_validate_convolve_over_sample_size`, `RectangularAdaptDensity`.
611+ _IDENT_RE = re .compile (
612+ r"`([A-Za-z_][A-Za-z0-9_]*(?:_[A-Za-z0-9_]+)+"
613+ r"|[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]+)+)`" )
614+ #: An identifier in this many records or more is vocabulary, not evidence.
615+ _IDENT_COMMON_DF = 6
616+ #: Ditto for stem tokens: `jax` is in ~100 records and links nothing.
617+ _TOKEN_COMMON_DF = 12
618+ _W_SHIPPED = 7.0 # a record asserting the work is done — on its own
619+ # enough to qualify: `jax-substructure-simulator.md`
620+ # saying "the 4 prompts shipped to main" resolved four
621+ # prompts in one sentence, and nothing else flagged them.
622+ _W_IDENT = 2.0 # per shared rare identifier beyond the first
623+ _SUSPECT_THRESHOLD = 7.0
624+ _HIGH_THRESHOLD = 12.0
625+ # Tuned on the 2026-08-09 labelled set (PyAutoMind f25e154e, 148 prompts, five
626+ # findings independently confirmed against upstream source). Result:
627+ #
628+ # BEFORE 96 of 148 flagged (65%) — 52 "high" — biggest find NOT flagged
629+ # AFTER 31 of 148 flagged (21%) — 9 "high" — biggest find at rank 2
630+ #
631+ # Of the five findings, this ranker catches the two it can: the k x s series
632+ # (rare-token fan-out, rank 2) and the nufft chunking prompt (shared rare
633+ # identifiers). The other three are NOT ranker failures and must not be chased
634+ # by lowering the bar:
635+ #
636+ # * the test-mode umbrella states its own exit condition, which is what
637+ # PyAutoMind's `Closes-when:` header key grades — a different tool;
638+ # * the split-guard prompt had NO completion record at all (its evidence sat
639+ # inside a sibling PROMPT), so nothing Mind-local could see it;
640+ # * the latent prompt left no Mind trace whatsoever — the fix shipped upstream
641+ # without a record. Only reading the target repo finds that shape.
642+ #
643+ # Every attempt to force those three in cost precision without gaining truth:
644+ # a loose `<work-type>/<target>/` series match pulled the umbrella in at 31%
645+ # flagged, but also FALSELY flagged test_mode_bypass_ordered_assertion_ties off
646+ # references to four unrelated sibling prompts — a prompt the sweep confirmed is
647+ # NOT shipped, and exactly the mis-grade this tool must never make.
601648
602649
603650def _tokens (s : str ) -> set :
604651 return {w for w in re .findall (r"[a-z0-9]+" , s .lower ())
605652 if len (w ) > 2 and w not in _STOPWORDS }
606653
607654
655+ def _idents (text : str ) -> set :
656+ return set (_IDENT_RE .findall (text ))
657+
658+
608659def reconcile (mind : Path , prefix : str = "" ) -> dict :
609660 """Rank backlog prompts that look already-shipped, for a human to retire.
610661
@@ -624,14 +675,31 @@ def reconcile(mind: Path, prefix: str = "") -> dict:
624675 # reference lines + `## <slug>` topic headers now live inside the dated
625676 # records (the monolithic complete.md ledger was retired — issue #81)
626677 comp_lines : list = []
678+ comp_bodies : dict = {}
627679 for p in comp_files :
628- comp_lines .extend (
629- p .read_text (encoding = "utf-8" , errors = "replace" ).splitlines ())
680+ body = p .read_text (encoding = "utf-8" , errors = "replace" )
681+ comp_bodies [p .name ] = body
682+ comp_lines .extend (body .splitlines ())
683+
684+ # Document frequency over the records: how ORDINARY a token/identifier is.
685+ # Without this every prompt matches on `jax`, `test`, `workspace` and the
686+ # ranking is noise — the 2026-08-09 measurement flagged 96 of 148.
687+ token_df : dict = {}
688+ ident_df : dict = {}
689+ for name , body in comp_bodies .items ():
690+ for w in _tokens (name .replace ("-" , " " ).replace (".md" , "" )) | _tokens (body ):
691+ token_df [w ] = token_df .get (w , 0 ) + 1
692+ for i in _idents (body ):
693+ ident_df [i ] = ident_df .get (i , 0 ) + 1
630694 headers = [(ln [3 :].strip (), _tokens (ln [3 :].replace ("-" , " " )))
631695 for ln in comp_lines
632696 if ln .startswith ("## " ) and ln [3 :].strip () != "Original prompt" ]
633697 headers += [(f"complete/{ p .relative_to (comp_dir )} " ,
634698 _tokens (p .stem .replace ("_" , " " ))) for p in comp_files ]
699+ # Record STEMS specifically: a rare token appearing in several record stems
700+ # is a phased series, which is a far stronger claim than one in their prose.
701+ header_stems = [_tokens (p .stem .replace ("-" , " " )) for p in comp_files ]
702+ n_records = max (len (comp_files ), 1 )
635703 active = mind / "active"
636704 issued_names = ({p .name for p in active .glob ("*.md" )}
637705 if active .is_dir () else set ())
@@ -646,47 +714,107 @@ def reconcile(mind: Path, prefix: str = "") -> dict:
646714 findings = []
647715 score = 0.0
648716
717+ # 1. A record line that NAMES this prompt and CLAIMS it is done. A bare
718+ # mention is not evidence — measured on the 2026-08-09 labelled set,
719+ # treating any reference as high confidence produced 52 of 148 highs
720+ # and buried the true positives.
721+ # A record may resolve a whole FOLDER of prompts at once —
722+ # `jax-substructure-simulator.md` opens "the 4 `jax_substructure/`
723+ # prompts shipped to `main`", which retires four files in one sentence.
724+ # But `<work-type>/<target>/` is also just a path prefix that every
725+ # sibling reference contains, so matching it bare made a prompt "named"
726+ # by any mention of its neighbours (measured: it falsely flagged
727+ # test_mode_bypass_ordered_assertion_ties off references to four
728+ # unrelated bug/autofit/ prompts). Require the line to be talking about
729+ # the folder's prompts as a group.
730+ series = f"{ r ['work_type' ]} /{ r .get ('target' , '' )} /"
649731 for ln in comp_lines :
650- if base in ln or sans_wt in ln :
651- kind = ("referenced-followup"
652- if any (w in ln .lower () for w in _FOLLOWUP_WORDS )
653- else "referenced" )
654- findings .append ((kind , ln .strip ()))
732+ low = ln .lower ()
733+ named = base in ln or sans_wt in ln
734+ if not named and series in ln and "prompt" in low :
735+ named = True
736+ if not named :
737+ continue
738+ if any (w in low for w in _FOLLOWUP_WORDS ):
739+ findings .append (("referenced-followup" , ln .strip ()))
740+ elif any (w in low for w in _SHIPPED_WORDS ):
741+ findings .append (("record-says-shipped" , ln .strip ()))
742+ score += _W_SHIPPED
743+ else :
744+ # Evidence, not score. A record merely NAMING a prompt was the
745+ # single biggest source of noise in the 2026-08-09 measurement:
746+ # it alone produced 52 of 148 "high" verdicts and buried every
747+ # true positive among them.
748+ findings .append (("referenced" , ln .strip ()))
655749
656750 if base in issued_names :
657751 findings .append (("issued-duplicate" , f"active/{ base } already exists" ))
752+ score += _W_SHIPPED
658753 if base in comp_names :
659754 findings .append (("complete-duplicate" ,
660755 f"{ base } already in the complete/ archive" ))
661-
756+ score += _W_SHIPPED
757+
758+ # 2. Rare stem tokens, IDF-weighted, with a fan-out bonus. Raw Jaccard
759+ # missed the biggest find of the 2026-08-09 sweep:
760+ # `oversampling_kxs_coupling` against `kxs-core` scores 0.25, under
761+ # any workable threshold. The real signal is that ONE very rare token
762+ # (`kxs`, in 7 of 947 records) appears in SIX record stems — a series
763+ # that shipped in phases. Requiring two shared tokens, the obvious
764+ # first try, scores that case exactly 0.
662765 sig = _tokens (base .replace ("_" , " " )) | _tokens (r ["title" ])
663- best = (0.0 , "" , set ())
664- for h , ht in headers :
665- if not sig or not ht :
766+ tok_score , evidence , best_fan = 0.0 , [], 0
767+ for w in sig :
768+ d = token_df .get (w , 0 )
769+ if not (0 < d <= _TOKEN_COMMON_DF ):
770+ continue
771+ fan = sum (1 for st in header_stems if w in st )
772+ if not fan :
666773 continue
667- shared = sig & ht
668- j = len (shared ) / len (sig | ht )
669- if (j , len (shared )) > (best [0 ], len (best [2 ])):
670- best = (j , h , shared )
671- if best [0 ] >= 0.40 or len (best [2 ]) >= 3 :
672- score = best [0 ]
673- findings .append (("topic-overlap" ,
674- f"completion record '{ best [1 ]} ' "
675- f"(shared: { ', ' .join (sorted (best [2 ]))} )" ))
676-
677- if r ["status" ] not in ("-" , "formalised" ):
774+ best_fan = max (best_fan , fan )
775+ tok_score += math .log (n_records / d ) * (2.0 if fan >= 3 else 1.0 )
776+ evidence .append (f"{ w } ({ d } records" +
777+ (f", { fan } in the stem" if fan >= 3 else "" ) + ")" )
778+ if tok_score :
779+ score += tok_score
780+ findings .append (("rare-topic-overlap" ,
781+ "rare tokens shared with the records: "
782+ + ", " .join (sorted (evidence ))))
783+
784+ # 3. Rare identifiers the prompt names, appearing in a record body. This
785+ # is what a human grader actually reads — `interferometer-jax-jit.md`
786+ # naming `chunk_size` resolves the nufft prompt in one sentence.
787+ # census() deliberately does not carry the prompt body (it is serialised
788+ # into the dashboard JSON); read it here instead.
789+ try :
790+ prompt_text = (mind / path ).read_text (encoding = "utf-8" , errors = "replace" )
791+ except OSError :
792+ prompt_text = ""
793+ pid = {i for i in _idents (prompt_text )
794+ if 0 < ident_df .get (i , 0 ) <= _IDENT_COMMON_DF }
795+ if pid :
796+ hits = {}
797+ for p , body in comp_bodies .items ():
798+ shared = {i for i in pid if i in body }
799+ if len (shared ) >= 2 :
800+ hits [p ] = shared
801+ if hits :
802+ top = max (hits , key = lambda p : len (hits [p ]))
803+ n = len (hits [top ])
804+ score += _W_IDENT * (n - 1 ) # 2 shared is weak, 7 is decisive
805+ findings .append (("shared-identifiers" ,
806+ f"record '{ top } ' names { n } of this prompt's "
807+ f"identifiers: { ', ' .join (sorted (hits [top ])[:5 ])} " ))
808+
809+ # `Status:` alone is not evidence — it fired on every hand-set draft. Kept
810+ # as context on prompts something else already flagged, never as a reason.
811+ if score > 0 and r ["status" ] not in ("-" , "formalised" ):
678812 findings .append (("stale-status" ,
679813 f"Status: { r ['status' ]} — hand-set; verify against "
680814 "shipped state" ))
681815
682- if findings :
683- kinds = {k for k , _ in findings }
684- if kinds & {"issued-duplicate" , "complete-duplicate" , "referenced" }:
685- conf = "high"
686- elif "topic-overlap" in kinds :
687- conf = "medium"
688- else :
689- conf = "low" # follow-up reference / stale status only
816+ if score >= _SUSPECT_THRESHOLD :
817+ conf = "high" if score >= _HIGH_THRESHOLD else "medium"
690818 suspects .append ({
691819 "path" : path , "title" : r ["title" ], "confidence" : conf ,
692820 "overlap_score" : round (score , 2 ),
0 commit comments