agent-bios 0.9.4 → 0.9.6

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.
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env python3
2
+ """Derive the promotion manifest from the ledger (collection loop, Phase 4).
3
+
4
+ `config/promotions.json` names the personal learnings that have been PROMOTED
5
+ into the shared corpus, so the user-side migrate rule can clear the now-absorbed
6
+ personal copy (scripts/migrate-learnings.py). The manifest is DERIVED — never
7
+ hand-edited: a promoted user learning is a ledger entry with `status == placed`
8
+ AND a `learning_id` (the Phase 3 dedup key kept on merge). Session-distill
9
+ entries have no `learning_id`, so they are never in the manifest.
10
+
11
+ F3 hardening (the one silent-loss path in the safety design): the audience a
12
+ promotion belongs to (which users' bundles carry it) is derived from where the
13
+ bullet ACTUALLY landed — the placed entry's `placed_anchor`, resolved against
14
+ `config/domains.json` (the placement source of truth) — NOT the ledger's free
15
+ `domain` tag. A placed+learning_id entry with a missing or unresolvable
16
+ `placed_anchor` FAILS the build/--check, so a promotion can neither ship with a
17
+ wrong audience nor ship without actually landing in the corpus.
18
+
19
+ Manifest shape (no PII — learning_id + the derived audience):
20
+ { "version": 1, "promotions": [
21
+ { "learning_id": "<uuid>", "tier": "core|infra|domain", "domains": ["<key>", ...] } ] }
22
+ (`domains` is empty for the universal tiers core/infra.)
23
+
24
+ Release step: regenerate before a push. `--check` fails if the on-disk manifest
25
+ is stale vs the ledger (a check-parity gate). `--self-test` runs the derivation.
26
+ """
27
+ import argparse
28
+ import json
29
+ import pathlib
30
+ import sys
31
+
32
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
33
+ import pkgid # noqa: E402 (sibling module; scripts/ is a flat toolbox)
34
+
35
+ REPO = pathlib.Path(__file__).resolve().parent.parent
36
+ LEDGER = REPO / "design" / "session-distill" / "ledger.json"
37
+ DOMAINS = REPO / "config" / "domains.json"
38
+ MANIFEST = REPO / "config" / "promotions.json"
39
+ FIXTURE = REPO / "design" / "collection-loop" / "fixtures" / "ledger-promote-sample.json"
40
+ MANIFEST_VERSION = 2
41
+
42
+
43
+ class ManifestError(Exception):
44
+ pass
45
+
46
+
47
+ def resolve_audience(anchor, domains_manifest):
48
+ """(tier, [domains]) for a placed anchor, or None if it does not resolve.
49
+ Bullets match by their `anchor` field; a whole guide/hook/agent matches by
50
+ key. This is the authoritative placement audience (mirrors what assemble.py
51
+ reads to decide who gets the bullet)."""
52
+ for b in domains_manifest.get("bullets", []):
53
+ if b.get("anchor") == anchor:
54
+ return b.get("tier"), list(b.get("domains", []))
55
+ for kind in ("guides", "hooks", "agents"):
56
+ entry = domains_manifest.get(kind, {}).get(anchor)
57
+ if entry is not None:
58
+ return entry.get("tier"), list(entry.get("domains", []))
59
+ return None
60
+
61
+
62
+ def build_manifest(ledger, domains_manifest):
63
+ """Ledger + domains manifest -> the promotion manifest. Raises ManifestError
64
+ on a placed+learning_id entry whose placement can't be verified (missing or
65
+ unresolvable placed_anchor) — the F3 silent-loss guard. Sorted by
66
+ learning_id for a stable, deterministic artifact."""
67
+ promotions = []
68
+ for e in ledger.get("entries", []):
69
+ if not isinstance(e, dict):
70
+ continue
71
+ lid = e.get("learning_id")
72
+ if e.get("status") != "placed" or not (isinstance(lid, str) and lid):
73
+ continue
74
+ anchor = e.get("placed_anchor")
75
+ if not anchor:
76
+ raise ManifestError(
77
+ f"placed learning {e.get('id')!r} ({lid}) has no `placed_anchor` — "
78
+ "record where the bullet landed (a config/domains.json anchor/key) "
79
+ "before promoting")
80
+ aud = resolve_audience(anchor, domains_manifest)
81
+ if aud is None:
82
+ raise ManifestError(
83
+ f"placed_anchor {anchor!r} (learning {lid}) does not resolve in "
84
+ "config/domains.json — the promotion has no verifiable placement")
85
+ tier, domains = aud
86
+ pid = pkgid.resolve(e, "placed_package_id")
87
+ if not pkgid.is_valid(pid):
88
+ raise ManifestError(
89
+ f"placed_package_id {pid!r} (learning {lid}) is not @scope/name")
90
+ # `anchor` ships alongside the derived audience because the consumer
91
+ # (migrate-learnings) must verify the bullet is REALLY in the user's
92
+ # deployed corpus before deleting their personal copy. Audience metadata
93
+ # alone cannot answer that — it is a build-time projection that drifts.
94
+ promotions.append({"learning_id": lid.lower(), "package_id": pid,
95
+ "anchor": anchor, "tier": tier, "domains": domains})
96
+ promotions.sort(key=lambda p: p["learning_id"])
97
+ return {"version": MANIFEST_VERSION, "promotions": promotions}
98
+
99
+
100
+ def render(manifest):
101
+ return json.dumps(manifest, ensure_ascii=False, indent=2) + "\n"
102
+
103
+
104
+ def _self_test():
105
+ ledger = json.loads(FIXTURE.read_text(encoding="utf-8"))
106
+ # Fixture domains manifest the fixture's placed_anchors resolve against.
107
+ domains = {
108
+ "bullets": [
109
+ {"anchor": "universal placed rule", "tier": "core", "domains": []},
110
+ {"anchor": "builder placed rule", "tier": "domain", "domains": ["builder-base"]},
111
+ ],
112
+ "guides": {}, "hooks": {}, "agents": {},
113
+ }
114
+ m = build_manifest(ledger, domains)
115
+ by = {p["learning_id"]: p for p in m["promotions"]}
116
+ a1 = "0f8c1c2a-4d1e-4abc-9def-0000000000a1"
117
+ b2 = "0f8c1c2a-4d1e-4abc-9def-0000000000b2"
118
+
119
+ checks = [
120
+ ("only placed+learning_id promoted (cardinality > 0)", set(by) == {a1, b2}),
121
+ ("session-distill (no learning_id) excluded",
122
+ all(p["learning_id"] for p in m["promotions"])),
123
+ ("incubating excluded",
124
+ "0f8c1c2a-4d1e-4abc-9def-0000000000c1" not in by),
125
+ ("audience DERIVED from the anchor, not the ledger domain tag",
126
+ by[a1]["tier"] == "core" and by[a1]["domains"] == []
127
+ and by[b2]["tier"] == "domain" and by[b2]["domains"] == ["builder-base"]),
128
+ ("sorted + deterministic",
129
+ [p["learning_id"] for p in m["promotions"]] == sorted(by)
130
+ and render(build_manifest(ledger, domains)) == render(m)),
131
+ ]
132
+
133
+ # F3 guards: missing / unresolvable placed_anchor must FAIL.
134
+ def raises(mut):
135
+ led = json.loads(FIXTURE.read_text(encoding="utf-8"))
136
+ mut(led)
137
+ try:
138
+ build_manifest(led, domains)
139
+ return False
140
+ except ManifestError:
141
+ return True
142
+
143
+ checks.append(("missing placed_anchor fails",
144
+ raises(lambda l: l["entries"][0].pop("placed_anchor", None))))
145
+ checks.append(("unresolvable placed_anchor fails",
146
+ raises(lambda l: l["entries"][0].__setitem__("placed_anchor", "no-such-anchor"))))
147
+
148
+ # v2 identity + locator. Without these the manifest looks fine while the
149
+ # consumer that must verify placement has nothing to verify against.
150
+ checks.append(("manifest is v2", m["version"] == 2))
151
+ checks.append(("every promotion carries its anchor",
152
+ all(p.get("anchor") for p in m["promotions"])))
153
+ checks.append(("absent placed_package_id resolves to core",
154
+ all(p.get("package_id") == pkgid.CORE for p in m["promotions"])))
155
+ led2 = json.loads(FIXTURE.read_text(encoding="utf-8"))
156
+ led2["entries"][0]["placed_package_id"] = "@acme/security"
157
+ checks.append(("declared placed_package_id is carried through",
158
+ any(p["package_id"] == "@acme/security"
159
+ for p in build_manifest(led2, domains)["promotions"])))
160
+ checks.append(("malformed placed_package_id fails",
161
+ raises(lambda l: l["entries"][0].__setitem__("placed_package_id", "Acme/Sec"))))
162
+
163
+ failed = [n for n, ok in checks if not ok]
164
+ if failed:
165
+ for n in failed:
166
+ print(f"build-promotions --self-test: FAIL: {n}", file=sys.stderr)
167
+ sys.exit(1)
168
+ print(f"build-promotions --self-test: OK ({len(checks)} manifest-derivation checks)")
169
+
170
+
171
+ def _load_and_build():
172
+ ledger = json.loads(LEDGER.read_text(encoding="utf-8"))
173
+ domains = json.loads(DOMAINS.read_text(encoding="utf-8"))
174
+ try:
175
+ return render(build_manifest(ledger, domains))
176
+ except ManifestError as e:
177
+ print(f"build-promotions: {e}", file=sys.stderr)
178
+ sys.exit(1)
179
+
180
+
181
+ def main():
182
+ ap = argparse.ArgumentParser(description="Derive config/promotions.json from the ledger.")
183
+ ap.add_argument("--check", action="store_true",
184
+ help="fail if config/promotions.json is stale vs the ledger (gate)")
185
+ ap.add_argument("--self-test", action="store_true")
186
+ args = ap.parse_args()
187
+
188
+ if args.self_test:
189
+ _self_test()
190
+ return
191
+
192
+ want = _load_and_build()
193
+
194
+ if args.check:
195
+ have = MANIFEST.read_text(encoding="utf-8") if MANIFEST.is_file() else ""
196
+ if have != want:
197
+ print("build-promotions --check: config/promotions.json is STALE vs the "
198
+ "ledger — run `python3 scripts/build-promotions.py` and commit.",
199
+ file=sys.stderr)
200
+ sys.exit(1)
201
+ print("build-promotions --check: promotions.json is current with the ledger")
202
+ return
203
+
204
+ MANIFEST.write_text(want, encoding="utf-8")
205
+ n = want.count('"learning_id"')
206
+ print(f"build-promotions: wrote {MANIFEST} ({n} promotion(s))")
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env bash
2
+ # Activation canary: proves the central bundle actually LOADS in a live
3
+ # session — file presence cannot detect a declined @import approval or a
4
+ # broken entry import line, so this asks a headless session to echo the
5
+ # bundle's rev marker back.
6
+ # Exit: 0 loaded | 1 not loading (or no bundle) | 3 cannot probe (no CLI).
7
+ set -u
8
+ CLAUDE_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
9
+ BUNDLE="$CLAUDE_DIR/central/bundle.md"
10
+
11
+ [ -f "$BUNDLE" ] || { echo "CANARY FAIL: no bundle at $BUNDLE (run: agent-bios install --domains ...)"; exit 1; }
12
+ expected="$(grep -m1 '^agent-bios-bundle-rev: ' "$BUNDLE")"
13
+ [ -n "$expected" ] || { echo "CANARY FAIL: bundle has no rev marker (reassemble with a current assemble.py)"; exit 1; }
14
+ command -v claude >/dev/null 2>&1 || { echo "CANARY SKIP: claude CLI not found — cannot probe activation"; exit 3; }
15
+
16
+ probe="Somewhere in your loaded instruction context there may be a line that starts with 'agent-bios-bundle-rev:'. Reply with ONLY that line, verbatim. If no such line is in your context, reply with exactly: BUNDLE-NOT-LOADED"
17
+ out="$(cd "$HOME" && claude -p "$probe" 2>/dev/null)"
18
+
19
+ if printf '%s' "$out" | grep -qF "$expected"; then
20
+ echo "CANARY PASS: central bundle is loading ($expected)"
21
+ exit 0
22
+ fi
23
+ echo "CANARY FAIL: central bundle is NOT loading in live sessions."
24
+ echo " expected marker: $expected"
25
+ echo " probe replied: $(printf '%s' "$out" | head -c 200)"
26
+ echo " Likely causes: the CLAUDE.md import approval was declined (open a session and re-approve imports),"
27
+ echo " or the entry file lost its '@central/bundle.md' line. Diagnose with: agent-bios verify"
28
+ exit 1
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env python3
2
+ """Bijection/coverage gate: config/domains.json vs the canonical corpus.
3
+
4
+ The manifest is the sole classification authority (tagged-monolith layout);
5
+ claude/CLAUDE.md stays the sole text authority. This gate closes the
6
+ silent-drop window: a bullet reworded without a manifest update, or a
7
+ manifest entry whose anchor no longer matches, fails HERE, before landing.
8
+
9
+ Blocking checks (any violation exits 1, all violations listed):
10
+ 1. schema shape + registry legality (tiers/domains from the manifest's own
11
+ registry; domains list non-empty iff tier == "domain")
12
+ 2. bullet bijection: every manifest anchor matches exactly ONE `- ` bullet
13
+ in claude/CLAUDE.md, and every bullet is claimed by exactly ONE entry
14
+ 3. file coverage: every file in claude/guides|hooks|agents claimed exactly
15
+ once; every claimed file exists on disk
16
+ 4. router-guide co-package: a bullet referencing guides/<g>.md must have an
17
+ audience covered by that guide's audience (universal bullet -> universal
18
+ guide; domain bullet -> guide covering all its domains)
19
+ 5. hook source_guide: a hook naming its source guide must carry the same
20
+ tier + domain set as that guide
21
+ 6. non-vacuity: every subject set this gate judges is non-empty, so a green
22
+ run cannot be vacuous
23
+
24
+ Informational (non-blocking until budgets are set in the manifest): estimated
25
+ token size per package.
26
+
27
+ --self-test: runs negative controls (mutated manifests that MUST fail) and
28
+ exits 0 only if every mutation is caught. Proves the gate can fail.
29
+ """
30
+ import json
31
+ import pathlib
32
+ import re
33
+ import sys
34
+
35
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
36
+ import pkgid # noqa: E402 (sibling module; scripts/ is a flat toolbox, not a package)
37
+
38
+ REPO = pathlib.Path(__file__).resolve().parent.parent
39
+ MANIFEST = REPO / "config" / "domains.json"
40
+ MONOLITH = REPO / "claude" / "CLAUDE.md"
41
+ FILE_SECTIONS = { # manifest key -> corpus dir, glob
42
+ "guides": ("claude/guides", "*.md"),
43
+ "hooks": ("claude/hooks", "*"),
44
+ "agents": ("claude/agents", "*.md"),
45
+ }
46
+
47
+
48
+ def load_manifest(path=MANIFEST):
49
+ with open(path, encoding="utf-8") as f:
50
+ return json.load(f)
51
+
52
+
53
+ def corpus_bullets(path=MONOLITH):
54
+ text = path.read_text(encoding="utf-8")
55
+ return [ln for ln in text.splitlines() if ln.startswith("- ")]
56
+
57
+
58
+ def audience(entry, errors, ctx):
59
+ """Universal set marker, or the frozen domain set; records legality errors."""
60
+ tier = entry.get("tier")
61
+ domains = entry.get("domains", [])
62
+ if tier in ("core", "infra"):
63
+ if domains:
64
+ errors.append(f"{ctx}: tier {tier} must not list domains, got {domains}")
65
+ return "UNIVERSAL"
66
+ if tier == "env-personal":
67
+ if domains:
68
+ errors.append(f"{ctx}: env-personal must not list domains")
69
+ return "NEVER"
70
+ if tier == "domain":
71
+ if not domains:
72
+ errors.append(f"{ctx}: tier domain requires >=1 domain")
73
+ return frozenset(domains)
74
+ errors.append(f"{ctx}: illegal tier {tier!r}")
75
+ return "NEVER"
76
+
77
+
78
+ def covers(guide_aud, bullet_aud):
79
+ if guide_aud == "UNIVERSAL":
80
+ return True
81
+ if bullet_aud in ("UNIVERSAL", "NEVER"):
82
+ return False # universal bullet needs universal guide; NEVER refs nothing
83
+ return isinstance(guide_aud, frozenset) and guide_aud >= bullet_aud
84
+
85
+
86
+ def run_gate(manifest, bullets, repo=REPO):
87
+ errors = []
88
+ tiers = set(manifest.get("tiers", []))
89
+ domains_reg = set(manifest.get("domains", {}))
90
+ if not tiers or not domains_reg:
91
+ errors.append("registry: tiers/domains registry empty")
92
+
93
+ # -- 0. package identity ------------------------------------------------
94
+ # Absent means core (the reservation that keeps pre-v2 artifacts valid), but
95
+ # a PRESENT malformed id must fail rather than fall back — silently treating
96
+ # a typo as core would hand it the engine's unconditional-injection audience.
97
+ pid = pkgid.resolve(manifest)
98
+ if not pkgid.is_valid(pid):
99
+ errors.append(f"package_id: {pid!r} is not @scope/name (lowercase, hyphen-separated)")
100
+
101
+ def check_registry(entry, ctx):
102
+ if entry.get("tier") not in tiers:
103
+ errors.append(f"{ctx}: tier {entry.get('tier')!r} not in registry")
104
+ for d in entry.get("domains", []):
105
+ if d not in domains_reg:
106
+ errors.append(f"{ctx}: domain {d!r} not in registry")
107
+
108
+ # -- 2. bullet bijection ------------------------------------------------
109
+ mb = manifest.get("bullets", [])
110
+ if not bullets:
111
+ errors.append("non-vacuity: no bullets found in monolith")
112
+ if not mb:
113
+ errors.append("non-vacuity: manifest has no bullet entries")
114
+ if len(mb) != len(bullets):
115
+ errors.append(f"bijection: manifest has {len(mb)} bullet entries, monolith has {len(bullets)} bullets")
116
+ claimed = [0] * len(bullets)
117
+ seen_anchors = set()
118
+ for i, entry in enumerate(mb):
119
+ ctx = f"bullets[{i}] anchor={entry.get('anchor', '')!r:.60}"
120
+ check_registry(entry, ctx)
121
+ anchor = entry.get("anchor", "")
122
+ if not anchor:
123
+ errors.append(f"{ctx}: empty anchor")
124
+ continue
125
+ if anchor in seen_anchors:
126
+ errors.append(f"{ctx}: duplicate anchor")
127
+ seen_anchors.add(anchor)
128
+ hits = [j for j, b in enumerate(bullets) if anchor in b]
129
+ if len(hits) != 1:
130
+ errors.append(f"{ctx}: anchor matches {len(hits)} bullets (need exactly 1)")
131
+ for j in hits:
132
+ claimed[j] += 1
133
+ for j, n in enumerate(claimed):
134
+ if n != 1:
135
+ errors.append(f"bijection: bullet line {bullets[j][:70]!r} claimed {n} times (need exactly 1)")
136
+
137
+ # -- 3. file coverage ---------------------------------------------------
138
+ entries = {}
139
+ for key, (rel, glob) in FILE_SECTIONS.items():
140
+ section = manifest.get(key, {})
141
+ entries[key] = section
142
+ if not section:
143
+ errors.append(f"non-vacuity: manifest section {key!r} empty")
144
+ on_disk = {p.name for p in (repo / rel).glob(glob) if p.is_file()}
145
+ if not on_disk:
146
+ errors.append(f"non-vacuity: no files on disk under {rel}")
147
+ for name, entry in section.items():
148
+ check_registry(entry, f"{key}/{name}")
149
+ if name not in on_disk:
150
+ errors.append(f"{key}: claimed file {name} does not exist in {rel}")
151
+ for name in sorted(on_disk - set(section)):
152
+ errors.append(f"{key}: file {name} in {rel} not claimed by the manifest")
153
+
154
+ # -- 4. router-guide co-package ----------------------------------------
155
+ guide_aud = {n: audience(e, errors, f"guides/{n}") for n, e in entries["guides"].items()}
156
+ anchor_of = {id(e): e.get("anchor", "?") for e in mb}
157
+ ref_checks = 0
158
+ for entry in mb:
159
+ hits = [b for b in bullets if entry.get("anchor", "\0") in b]
160
+ if len(hits) != 1:
161
+ continue # already reported by bijection
162
+ b_aud = audience(entry, errors, f"bullet {entry.get('anchor', '')!r:.40}")
163
+ for g in re.findall(r"guides/([a-z0-9-]+\.md)", hits[0]):
164
+ ref_checks += 1
165
+ if g not in guide_aud:
166
+ errors.append(f"router: bullet {entry['anchor']!r:.40} references unclaimed guide {g}")
167
+ elif not covers(guide_aud[g], b_aud):
168
+ errors.append(
169
+ f"router: bullet {entry['anchor']!r:.40} (audience {b_aud}) references guide {g} "
170
+ f"(audience {guide_aud[g]}) — user can hold the router without the guide"
171
+ )
172
+ if ref_checks == 0:
173
+ errors.append("non-vacuity: no router->guide references were checked")
174
+
175
+ # -- 5. hook source_guide -----------------------------------------------
176
+ for name, entry in entries["hooks"].items():
177
+ src = entry.get("source_guide")
178
+ if src:
179
+ g = entries["guides"].get(src)
180
+ if g is None:
181
+ errors.append(f"hooks/{name}: source_guide {src} not in manifest guides")
182
+ elif (entry.get("tier"), sorted(entry.get("domains", []))) != (g.get("tier"), sorted(g.get("domains", []))):
183
+ errors.append(f"hooks/{name}: tier/domains differ from source guide {src}")
184
+
185
+ # -- informational token report ------------------------------------------
186
+ sizes = {}
187
+ for entry in mb:
188
+ key = entry.get("tier") if entry.get("tier") != "domain" else ",".join(entry.get("domains", ["?"])[:1])
189
+ hit = next((b for b in bullets if entry.get("anchor", "\0") in b), "")
190
+ sizes[key] = sizes.get(key, 0) + len(hit) // 4
191
+ for name, entry in entries["guides"].items():
192
+ key = entry.get("tier") if entry.get("tier") != "domain" else ",".join(entry.get("domains", ["?"])[:1])
193
+ p = repo / FILE_SECTIONS["guides"][0] / name
194
+ if p.is_file():
195
+ sizes[key] = sizes.get(key, 0) + len(p.read_text(encoding="utf-8")) // 4
196
+ return errors, sizes
197
+
198
+
199
+ def self_test(manifest, bullets):
200
+ """Negative controls: each mutation MUST make the gate fail."""
201
+ import copy
202
+
203
+ muts = []
204
+ m1 = copy.deepcopy(manifest)
205
+ m1["bullets"] = m1["bullets"][1:]
206
+ muts.append(("dropped bullet entry", m1, bullets))
207
+ m2 = copy.deepcopy(manifest)
208
+ m2["bullets"][0]["anchor"] = "zz-no-such-phrase-zz"
209
+ muts.append(("anchor matches nothing (reword drift)", m2, bullets))
210
+ m3 = copy.deepcopy(manifest)
211
+ m3["bullets"][1]["anchor"] = m3["bullets"][0]["anchor"]
212
+ muts.append(("duplicate anchor claim", m3, bullets))
213
+ m4 = copy.deepcopy(manifest)
214
+ first_guide = next(iter(m4["guides"]))
215
+ del m4["guides"][first_guide]
216
+ muts.append((f"unclaimed guide {first_guide}", m4, bullets))
217
+ b5 = bullets + ["- a brand new bullet the manifest never heard of"]
218
+ muts.append(("bullet added without manifest entry", copy.deepcopy(manifest), b5))
219
+ m6 = copy.deepcopy(manifest)
220
+ m6["package_id"] = "@Acme/Builder" # uppercase is not a legal segment
221
+ muts.append(("malformed package_id", m6, bullets))
222
+
223
+ failed = []
224
+ for name, mm, bb in muts:
225
+ errs, _ = run_gate(mm, bb)
226
+ if not errs:
227
+ failed.append(name)
228
+ print(f"self-test [{'CAUGHT' if errs else 'MISSED'}] {name}")
229
+ return failed
230
+
231
+
232
+ def main():
233
+ manifest = load_manifest()
234
+ bullets = corpus_bullets()
235
+ if "--self-test" in sys.argv:
236
+ missed = self_test(manifest, bullets)
237
+ if missed:
238
+ print(f"SELF-TEST FAIL: gate missed: {missed}")
239
+ return 1
240
+ print("SELF-TEST OK: every negative control was caught")
241
+ return 0
242
+ errors, sizes = run_gate(manifest, bullets)
243
+ for e in errors:
244
+ print(f"FAIL: {e}")
245
+ print("-- package token estimate (informational) --")
246
+ for k in sorted(sizes):
247
+ print(f" {k}: ~{sizes[k]} tokens")
248
+ if errors:
249
+ print(f"DOMAINS GATE FAIL: {len(errors)} violation(s)")
250
+ return 1
251
+ print(f"DOMAINS GATE OK: {len(bullets)} bullets bijective, all files claimed, routers co-packaged")
252
+ return 0
253
+
254
+
255
+ if __name__ == "__main__":
256
+ sys.exit(main())