forgeproof-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,177 @@
1
+ """Rule 2 (design v1.4.5 §4a.4): a lens is tested before it is trusted.
2
+
3
+ The known-case set for the shape lens. Scout runs it on every invocation; a lens that
4
+ fails any case is not switched on (it reports BLIND(rule2-failed)). The cases are written
5
+ here, not taken from the corpus: corpus bodies come from private conversations and never
6
+ enter this repo. The seed is aura-code-corpus KNOWN-DEBT #1 (three backup scripts doing
7
+ one job, shape Jaccard 0.03-0.11); these three are new scripts of the same kind.
8
+
9
+ Each lens is a scorer ``f(a, b) -> float in [0, 1]`` plus its threshold.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ # --- the pool every case is scored against -------------------------------------------
14
+ BACKUP_TAR = """#!/bin/bash
15
+ set -eu
16
+ src="$1"; dest="$2"
17
+ stamp=$(date +%Y%m%d-%H%M%S)
18
+ tar -czf "$dest/home-$stamp.tar.gz" -C "$src" .
19
+ find "$dest" -name 'home-*.tar.gz' -mtime +14 -delete
20
+ echo "backup written: $dest/home-$stamp.tar.gz"
21
+ """
22
+
23
+ BACKUP_PY = """import shutil, sys, time, pathlib
24
+ def main():
25
+ source, target = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
26
+ name = target / time.strftime("home-%Y%m%d-%H%M%S")
27
+ archive = shutil.make_archive(str(name), "gztar", root_dir=source)
28
+ cutoff = time.time() - 14 * 86400
29
+ for old in target.glob("home-*.tar.gz"):
30
+ if old.stat().st_mtime < cutoff:
31
+ old.unlink()
32
+ print("backup written:", archive)
33
+ main()
34
+ """
35
+
36
+ BACKUP_RSYNC = """#!/bin/bash
37
+ set -eu
38
+ SRC=$1
39
+ DST=$2/snapshots/$(date +%F)
40
+ mkdir -p "$DST"
41
+ rsync -a --delete --link-dest="$2/snapshots/latest" "$SRC/" "$DST/"
42
+ ln -sfn "$DST" "$2/snapshots/latest"
43
+ """
44
+
45
+ AREA = """def area(width, height):
46
+ if width < 0 or height < 0:
47
+ raise ValueError("negative side")
48
+ return width * height
49
+ """
50
+
51
+ KMEANS = """def assign(points, centres):
52
+ labels = []
53
+ for p in points:
54
+ best, best_d = 0, float("inf")
55
+ for i, c in enumerate(centres):
56
+ d = sum((a - b) ** 2 for a, b in zip(p, c))
57
+ if d < best_d:
58
+ best, best_d = i, d
59
+ labels.append(best)
60
+ return labels
61
+ """
62
+
63
+ JSON_STATS = """import json
64
+ def summary(path):
65
+ with open(path) as fh:
66
+ rows = json.load(fh)
67
+ total = sum(r["amount"] for r in rows)
68
+ return {"rows": len(rows), "total": total, "mean": total / max(len(rows), 1)}
69
+ """
70
+
71
+ POOL = {"backup_tar": BACKUP_TAR, "backup_py": BACKUP_PY, "backup_rsync": BACKUP_RSYNC,
72
+ "area": AREA, "kmeans": KMEANS, "json_stats": JSON_STATS}
73
+
74
+ # --- queries ----------------------------------------------------------------------------
75
+ # Same look, different meaning: AREA's exact token shape, a tax computation.
76
+ TAX = """def tax(price, rate):
77
+ if price < 0 or rate < 0:
78
+ raise ValueError("negative input")
79
+ return price * rate
80
+ """
81
+
82
+ # Same meaning, same look, every name changed: a renamed copy of KMEANS. Only shape sees it;
83
+ # the keyword baseline loses most of its words.
84
+ NEAREST = """def nearest(samples, means):
85
+ out = []
86
+ for s in samples:
87
+ idx, dist = 0, float("inf")
88
+ for j, m in enumerate(means):
89
+ e = sum((u - v) ** 2 for u, v in zip(s, m))
90
+ if e < dist:
91
+ idx, dist = j, e
92
+ out.append(idx)
93
+ return out
94
+ """
95
+
96
+ # Only shape can get this right: a fork of KMEANS with a bug (ties go to the LAST centre and
97
+ # labels are 1-based). Behaviour differs, so a behaviour lens would call it unrelated; the
98
+ # copy lineage is visible only in the shape.
99
+ KMEANS_FORK = """def assign(points, centres):
100
+ labels = []
101
+ for p in points:
102
+ best, best_d = 0, float("inf")
103
+ for i, c in enumerate(centres):
104
+ d = sum((a - b) ** 2 for a, b in zip(p, c))
105
+ if d <= best_d:
106
+ best, best_d = i, d
107
+ labels.append(best + 1)
108
+ return labels
109
+ """
110
+
111
+ # Null: related to nothing in the pool.
112
+ NULL = """class Stack:
113
+ def __init__(self):
114
+ self._items = []
115
+ def push(self, x):
116
+ self._items.append(x)
117
+ def pop(self):
118
+ return self._items.pop()
119
+ """
120
+
121
+ # Keyword trap: shares the backup scripts' words but is a different job and a different shape.
122
+ KEYWORD_TRAP = """# list backup home archives by size
123
+ for f in home-*.tar.gz; do
124
+ du -h "$f"
125
+ done | sort -h
126
+ """
127
+
128
+
129
+ def _ranked(scorer, query):
130
+ return sorted(((scorer(query, body), name) for name, body in POOL.items()), key=lambda t: (-t[0], t[1]))
131
+
132
+
133
+ def evaluate(scorer, tau: float, baseline=None) -> list[str]:
134
+ """Return the failed cases (empty = the lens may be switched on)."""
135
+ fails = []
136
+ # 1. same meaning / different look: shape alone must MISS (the lens's documented limit).
137
+ for a, b in (("backup_tar", "backup_py"), ("backup_tar", "backup_rsync"), ("backup_py", "backup_rsync")):
138
+ s = scorer(POOL[a], POOL[b])
139
+ if s >= tau:
140
+ fails.append(f"same-meaning/different-look: {a}~{b} scored {s:.2f} >= {tau}; shape must miss it")
141
+ # 2. same look / different meaning: shape alone must WRONGLY match.
142
+ top_s, top_n = _ranked(scorer, TAX)[0]
143
+ if not (top_n == "area" and top_s >= tau):
144
+ fails.append(f"same-look/different-meaning: TAX ranked {top_n} at {top_s:.2f}; must match area >= {tau}")
145
+ # 3. null case: no member at or above tau.
146
+ top_s, top_n = _ranked(scorer, NULL)[0]
147
+ if top_s >= tau:
148
+ fails.append(f"null: Stack matched {top_n} at {top_s:.2f} >= {tau}")
149
+ # 4. the cases the lens must find: the renamed copy, and the buggy fork only shape can see.
150
+ for q, want, what in ((NEAREST, "kmeans", "renamed copy"), (KMEANS_FORK, "kmeans", "buggy fork (shape-only)")):
151
+ top_s, top_n = _ranked(scorer, q)[0]
152
+ if not (top_n == want and top_s >= tau):
153
+ fails.append(f"find: {what} ranked {top_n} at {top_s:.2f}; must be {want} >= {tau}")
154
+ # 5. the keyword trap must not lure the lens.
155
+ ls_s, ls_n = _ranked(scorer, KEYWORD_TRAP)[0]
156
+ if ls_s >= tau:
157
+ fails.append(f"keyword trap: the lens matched {ls_n}, a different job, at {ls_s:.2f} >= {tau}")
158
+ # 6. the keyword baseline, scored alongside, must separate worse than the lens.
159
+ if baseline is not None:
160
+ sep_l, sep_b = separation(scorer), separation(baseline)
161
+ if not sep_l > sep_b:
162
+ fails.append(f"baseline: lens separation {sep_l:.2f} does not beat the keyword baseline's {sep_b:.2f}")
163
+ if not _ranked(baseline, KEYWORD_TRAP)[0][1].startswith("backup"):
164
+ fails.append("baseline: the keyword trap did not lure the baseline; the trap tests nothing")
165
+ return fails
166
+
167
+
168
+ def separation(scorer) -> float:
169
+ """Lowest score on a pair that must match, minus the highest on a pair that must not.
170
+ Must-match: NEAREST~kmeans, KMEANS_FORK~kmeans. Must-not: every query's other members,
171
+ NULL and KEYWORD_TRAP against everything, and the three backup pairs (shape is known to
172
+ miss those, so they count as must-not for a shape-type lens)."""
173
+ pos = [scorer(NEAREST, KMEANS), scorer(KMEANS_FORK, KMEANS)]
174
+ neg = [scorer(q, b) for q in (NULL, KEYWORD_TRAP) for b in POOL.values()]
175
+ neg += [scorer(q, b) for q in (NEAREST, KMEANS_FORK) for n, b in POOL.items() if n != "kmeans"]
176
+ neg += [scorer(POOL[a], POOL[b]) for a, b in (("backup_tar", "backup_py"), ("backup_tar", "backup_rsync"), ("backup_py", "backup_rsync"))]
177
+ return min(pos) - max(neg)
@@ -0,0 +1,107 @@
1
+ # Ported from aura-code-corpus src/code_corpus/shape.py at checkout c5129d2
2
+ # (md5 0350722f31814c31085d55cce603cfd6), port-and-freeze (design §2.3). Do not edit below
3
+ # the marker line; re-port instead. tests/test_scout_slice1.py checks the body's md5.
4
+ # --- ported body below ---
5
+ """Near-duplicate shape (design §7): normalize code, shingle, MinHash + LSH, exact-Jaccard confirm."""
6
+ import hashlib
7
+ import re
8
+
9
+ TOKEN = re.compile(r'"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|\$\{?\w+\}?|\d+(?:\.\d+)?|[A-Za-z_][\w-]*|\S')
10
+ KEEP = set("""
11
+ if then else elif fi for while do done case esac in function return local export def class import from as
12
+ with try except finally raise lambda yield async await pass break continue and or not is None True False
13
+ fn let mut pub impl struct enum match use mod func go defer package var const type interface switch
14
+ echo printf cat tar gzip rsync cp mv rm mkdir find grep sed awk sort uniq head tail wc cut xargs date ssh
15
+ scp sudo systemctl launchctl crontab sqlite3 curl wget git python python3 bash sh jq tee test set exit
16
+ print open read write json os sys re path subprocess run len range dict list str int self
17
+ """.split())
18
+ P = (1 << 61) - 1
19
+
20
+
21
+ def normalize(code: str) -> list[str]:
22
+ out = []
23
+ for line in code.split("\n"):
24
+ s = line.strip()
25
+ if not s or (s.startswith("#") and not s.startswith("#!")) or s.startswith("//"):
26
+ continue
27
+ for t in TOKEN.findall(line):
28
+ if t[0] in "\"'":
29
+ out.append("S")
30
+ elif t[0] == "$":
31
+ out.append("$V")
32
+ elif t[0].isdigit():
33
+ out.append("N")
34
+ elif t[0].isalpha() or t[0] == "_":
35
+ out.append(t if t in KEEP else "ID")
36
+ else:
37
+ out.append(t)
38
+ return out
39
+
40
+
41
+ def shingles(code: str, k: int = 5) -> set[int]:
42
+ toks = normalize(code)
43
+ if len(toks) < k:
44
+ return {_h(" ".join(toks))} if toks else set()
45
+ return {_h(" ".join(toks[i:i + k])) for i in range(len(toks) - k + 1)}
46
+
47
+
48
+ def _h(s: str) -> int:
49
+ return int.from_bytes(hashlib.blake2b(s.encode(), digest_size=8).digest(), "big")
50
+
51
+
52
+ def _perms(n: int):
53
+ rng = [_h(f"perm-{i}") for i in range(2 * n)]
54
+ return [(rng[2 * i] % (P - 1) + 1, rng[2 * i + 1] % P) for i in range(n)]
55
+
56
+
57
+ class MinHasher:
58
+ def __init__(self, perms: int = 64, bands: int = 16):
59
+ self.perms, self.bands, self.rows = _perms(perms), bands, perms // bands
60
+
61
+ def signature(self, sh: set[int]) -> list[int]:
62
+ if not sh:
63
+ return [P] * len(self.perms)
64
+ return [min((a * x + b) % P for x in sh) for a, b in self.perms]
65
+
66
+ def band_keys(self, sig: list[int]):
67
+ for i in range(self.bands):
68
+ yield i, tuple(sig[i * self.rows:(i + 1) * self.rows])
69
+
70
+
71
+ def jaccard(a: set, b: set) -> float:
72
+ return len(a & b) / len(a | b) if a and b else 0.0
73
+
74
+
75
+ def clusters(items: dict[str, set[int]], tau: float, perms: int, bands: int):
76
+ """items: id -> shingle set. Returns (list of member-id lists, confirmed pair Jaccards, signatures)."""
77
+ mh = MinHasher(perms, bands)
78
+ sigs = {i: mh.signature(s) for i, s in items.items()}
79
+ buckets = {}
80
+ for i, sig in sigs.items():
81
+ for key in mh.band_keys(sig):
82
+ buckets.setdefault(key, []).append(i)
83
+ parent = {i: i for i in items}
84
+
85
+ def find(x):
86
+ while parent[x] != x:
87
+ parent[x] = parent[parent[x]]
88
+ x = parent[x]
89
+ return x
90
+ pairs, seen = {}, set()
91
+ for members in buckets.values():
92
+ if len(members) < 2 or len(members) > 500:
93
+ continue
94
+ for x in range(len(members)):
95
+ for y in range(x + 1, len(members)):
96
+ a, b = members[x], members[y]
97
+ if (a, b) in seen:
98
+ continue
99
+ seen.add((a, b))
100
+ j = jaccard(items[a], items[b])
101
+ if j >= tau:
102
+ pairs[(a, b)] = j
103
+ parent[find(a)] = find(b)
104
+ groups = {}
105
+ for i in items:
106
+ groups.setdefault(find(i), []).append(i)
107
+ return [g for g in groups.values() if len(g) > 1], pairs, sigs
@@ -0,0 +1,71 @@
1
+ """Lens 1, shape (design v1.4.5 §4a.3): "related" means the code looks alike.
2
+
3
+ Score = exact Jaccard of 5-gram shape shingles (``shape.py``, ported from the corpus).
4
+ FOUND when at least one pool member scores >= TAU, LOOKED-CLEAN when the lens ran and none
5
+ did, BLIND(reason) when it could not look. Its own ranked list with its own reason; no
6
+ combined score (§4a.4 rule 1). Bodies are compared as text only.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass, field
12
+
13
+ from . import shape, slots
14
+ from .outcomes import Outcome, blind, clean, found
15
+
16
+ NAME = "shape"
17
+ # The corpus's near-copy threshold (aura-code-corpus config.toml [cluster] tau = 0.5,
18
+ # calibrated there by `code-corpus calibrate`). The score band for trust tie-breaks is
19
+ # not set yet: [NEED: band width per lens, measured when the lens is calibrated] (§4a.4).
20
+ TAU = 0.5
21
+ MIN_TOKENS = 5 # fewer normalized tokens than one shingle: nothing to compare
22
+
23
+
24
+ @dataclass
25
+ class Hit:
26
+ item_id: str
27
+ score: float
28
+ pool: str
29
+ trust: str
30
+ lang: str = ""
31
+ kind: str = ""
32
+ slot: str = "top" # "explore" = slot 10, outside the top ranks (8b s4)
33
+
34
+
35
+ @dataclass
36
+ class LensResult:
37
+ outcome: Outcome
38
+ hits: list = field(default_factory=list) # ranked, best first: slots.TOP, then at most one explore hit
39
+ looked_at: int = 0
40
+
41
+
42
+ def score(a: str, b: str) -> float:
43
+ return shape.jaccard(shape.shingles(a), shape.shingles(b))
44
+
45
+
46
+ def keyword_score(a: str, b: str) -> float:
47
+ """The keyword baseline the lens must beat (Rule 2): Jaccard of the raw word sets."""
48
+ wa = set(re.findall(r"[A-Za-z_][A-Za-z0-9_]+", a.lower()))
49
+ wb = set(re.findall(r"[A-Za-z_][A-Za-z0-9_]+", b.lower()))
50
+ return len(wa & wb) / len(wa | wb) if wa and wb else 0.0
51
+
52
+
53
+ def rank(query: str, members: list, *, pool: str, trust: str, scorer=score,
54
+ tau: float = TAU) -> LensResult:
55
+ """members: dicts with item_id, body (and optionally lang, kind)."""
56
+ if len(shape.normalize(query)) < MIN_TOKENS:
57
+ return LensResult(blind("no-input: query has fewer tokens than one shingle"))
58
+ if not members:
59
+ return LensResult(blind(f"no-input: {pool} pool has no member in this language"))
60
+ q = shape.shingles(query) if scorer is score else None
61
+ hits = []
62
+ for m in members:
63
+ s = shape.jaccard(q, shape.shingles(m["body"])) if q is not None else scorer(query, m["body"])
64
+ hits.append(Hit(m["item_id"], round(s, 4), pool, trust, m.get("lang", ""), m.get("kind", "")))
65
+ hits.sort(key=lambda h: (-h.score, h.item_id))
66
+ top, explore = slots.split(hits, lens=NAME, query=query)
67
+ shown = top + ([explore] if explore else [])
68
+ over = [h for h in top if h.score >= tau] # the explore slot never counts (8b s4)
69
+ if over:
70
+ return LensResult(found(f"{len(over)} at or above J={tau}"), shown, len(members))
71
+ return LensResult(clean(f"best J={top[0].score} < {tau}"), shown, len(members))
@@ -0,0 +1,52 @@
1
+ """Signature extractor (design v1.4.5 §3a), Python only. Reads source as TEXT (ast), never runs it.
2
+
3
+ For each public top-level function with at least one positional argument it returns the
4
+ registry row shape: ``{"entry", "consumes": [{name, type, noun}], "produces": {type, names, noun}}``
5
+ plus ``required`` / ``total`` positional counts (the contract gate uses them). ``noun`` is always
6
+ None: §3a.3 option (a), null-by-default, no inference.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+
12
+
13
+ def _returns(fn: ast.FunctionDef) -> list[str]:
14
+ names = []
15
+ for node in ast.walk(fn):
16
+ if isinstance(node, ast.Return) and node.value is not None:
17
+ v = node.value
18
+ parts = v.elts if isinstance(v, ast.Tuple) else [v]
19
+ for p in parts:
20
+ if isinstance(p, ast.Name) and p.id not in names:
21
+ names.append(p.id)
22
+ return names
23
+
24
+
25
+ def extract(source: str) -> list[dict]:
26
+ """Raises SyntaxError for text that is not Python."""
27
+ tree = ast.parse(source)
28
+ out = []
29
+ for fn in tree.body:
30
+ if not isinstance(fn, ast.FunctionDef) or fn.name.startswith("_"):
31
+ continue
32
+ a = fn.args
33
+ pos = list(a.posonlyargs) + list(a.args)
34
+ if not pos:
35
+ continue
36
+ n_default = len(a.defaults)
37
+ out.append({
38
+ "entry": fn.name,
39
+ "consumes": [{"name": p.arg, "type": ast.unparse(p.annotation) if p.annotation else None,
40
+ "noun": None} for p in pos],
41
+ "produces": {"type": ast.unparse(fn.returns) if fn.returns else None,
42
+ "names": _returns(fn), "noun": None},
43
+ "required": len(pos) - n_default, "total": len(pos),
44
+ })
45
+ return out
46
+
47
+
48
+ def async_only(source: str) -> bool:
49
+ """True when the source's only public top-level functions are async (not supported yet)."""
50
+ tree = ast.parse(source)
51
+ fns = [n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and not n.name.startswith("_")]
52
+ return bool(fns) and all(isinstance(n, ast.AsyncFunctionDef) for n in fns)
@@ -0,0 +1,39 @@
1
+ """The one-in-ten explore slot (design §4a.5; build step 8b s4; DECISIONS-8b H10 a).
2
+
3
+ Every similarity list shows TOP ranked hits plus, in slot 10, one hit drawn from OUTSIDE the top
4
+ ranks, labelled ``explore``: a counterfactual, so the outcome ledger does not only ever learn about
5
+ what the lens already liked. The draw is seeded by the query text and the lens name, so it can be
6
+ reproduced. An explore hit never counts toward FOUND or agreement, and experience never reorders it.
7
+ A list with nothing beyond the top ranks has no explore slot.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import random
13
+
14
+ TOP = 9 # shown top ranks; slot 10 is the explore slot
15
+
16
+
17
+ def split(ranked: list, *, lens: str, query: str) -> tuple:
18
+ """(top hits, explore hit or None) from a fully ranked list (best first). Marks the slots."""
19
+ top, rest = list(ranked[:TOP]), list(ranked[TOP:])
20
+ for h in top:
21
+ _mark(h, "top")
22
+ return top, pick(rest, lens=lens, query=query)
23
+
24
+
25
+ def pick(rest: list, *, lens: str, query: str):
26
+ """The explore hit: one of ``rest`` (hits outside the top ranks), seeded, marked; None if empty."""
27
+ if not rest:
28
+ return None
29
+ seed = hashlib.sha256(f"{lens}\0{query}".encode("utf-8", "surrogatepass")).digest()
30
+ h = rest[random.Random(int.from_bytes(seed[:8], "big")).randrange(len(rest))]
31
+ _mark(h, "explore")
32
+ return h
33
+
34
+
35
+ def _mark(h, slot):
36
+ if isinstance(h, dict):
37
+ h["slot"] = slot
38
+ else:
39
+ h.slot = slot