Skip to content

Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.

feat(brain): substance gate + orphan prune + adapter breadth (pre-deepen)

AgriciDaniel31008f2ac5fb
diff --git a/claude_blog_brain/cli.py b/claude_blog_brain/cli.py
index 7e53405..1f2c93e 100644
--- a/claude_blog_brain/cli.py
+++ b/claude_blog_brain/cli.py
@@ -56,6 +56,38 @@ def main(argv: list[str] | None = None) -> int:
p_blog_pipeline = sub.add_parser("blog-pipeline")
p_blog_pipeline.add_argument("--input", required=True)
p_blog_pipeline.add_argument("--out-dir", required=True)
+ p_cluster_ingest = sub.add_parser("cluster-ingest")
+ p_cluster_ingest.add_argument("input")
+ p_cluster_ingest.add_argument("-o", "--output", default="")
+ p_cluster_ingest.add_argument("--json", action="store_true")
+ p_cluster_synth = sub.add_parser("cluster-synthesize")
+ p_cluster_synth.add_argument("input")
+ p_cluster_synth.add_argument("-o", "--output", default="")
+ p_cluster_synth.add_argument("-l", "--ledger", default="")
+ p_cluster_synth.add_argument("--json", action="store_true")
+ p_cluster_report = sub.add_parser("cluster-report")
+ p_cluster_report.add_argument("input")
+ p_cluster_report.add_argument("-o", "--output", default="")
+ p_cluster_report.add_argument("--json", action="store_true")
+ p_cluster_pipeline = sub.add_parser("cluster-pipeline")
+ p_cluster_pipeline.add_argument("--input", required=True)
+ p_cluster_pipeline.add_argument("--out-dir", required=True)
+ p_geo_ingest = sub.add_parser("geo-ingest")
+ p_geo_ingest.add_argument("input")
+ p_geo_ingest.add_argument("-o", "--output", default="")
+ p_geo_ingest.add_argument("--json", action="store_true")
+ p_geo_synth = sub.add_parser("geo-synthesize")
+ p_geo_synth.add_argument("input")
+ p_geo_synth.add_argument("-o", "--output", default="")
+ p_geo_synth.add_argument("-l", "--ledger", default="")
+ p_geo_synth.add_argument("--json", action="store_true")
+ p_geo_report = sub.add_parser("geo-report")
+ p_geo_report.add_argument("input")
+ p_geo_report.add_argument("-o", "--output", default="")
+ p_geo_report.add_argument("--json", action="store_true")
+ p_geo_pipeline = sub.add_parser("geo-pipeline")
+ p_geo_pipeline.add_argument("--input", required=True)
+ p_geo_pipeline.add_argument("--out-dir", required=True)
p_demo = sub.add_parser("demo")
p_demo.add_argument("--out", default="")
p_demo.add_argument("--force", action="store_true")
@@ -105,6 +137,56 @@ def main(argv: list[str] | None = None) -> int:
return run_script("render_blog_report.py", call)
if args.command == "blog-pipeline":
return run_blog_pipeline(args.input, args.out_dir)
+ if args.command == "cluster-ingest":
+ call = [args.input]
+ if args.output:
+ call += ["-o", args.output]
+ if args.json:
+ call.append("--json")
+ return run_script("ingest_topic_cluster_input.py", call)
+ if args.command == "cluster-synthesize":
+ call = [args.input]
+ if args.ledger:
+ call += ["-l", args.ledger]
+ if args.output:
+ call += ["-o", args.output]
+ if args.json:
+ call.append("--json")
+ return run_script("synthesize_topic_cluster.py", call)
+ if args.command == "cluster-report":
+ call = [args.input]
+ if args.output:
+ call += ["-o", args.output]
+ if args.json:
+ call.append("--json")
+ return run_script("render_topic_cluster_report.py", call)
+ if args.command == "cluster-pipeline":
+ return run_cluster_pipeline(args.input, args.out_dir)
+ if args.command == "geo-ingest":
+ call = [args.input]
+ if args.output:
+ call += ["-o", args.output]
+ if args.json:
+ call.append("--json")
+ return run_script("ingest_geo_citation_audit.py", call)
+ if args.command == "geo-synthesize":
+ call = [args.input]
+ if args.ledger:
+ call += ["-l", args.ledger]
+ if args.output:
+ call += ["-o", args.output]
+ if args.json:
+ call.append("--json")
+ return run_script("synthesize_geo_citation_readiness.py", call)
+ if args.command == "geo-report":
+ call = [args.input]
+ if args.output:
+ call += ["-o", args.output]
+ if args.json:
+ call.append("--json")
+ return run_script("render_geo_citation_report.py", call)
+ if args.command == "geo-pipeline":
+ return run_geo_pipeline(args.input, args.out_dir)
if args.command == "demo":
call = []
if args.out:
@@ -140,5 +222,51 @@ def run_blog_pipeline(input_path: str, out_dir: str) -> int:
return 0
+def run_cluster_pipeline(input_path: str, out_dir: str) -> int:
+ out = Path(out_dir).expanduser().resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ ingested = out / "ingested-topic-cluster.json"
+ plan = out / "topic-cluster-plan.json"
+ report = out / "topic-cluster-internal-link-matrix.md"
+ steps = [
+ ("ingest_topic_cluster_input.py", [input_path, "-o", str(ingested)]),
+ ("synthesize_topic_cluster.py", [str(ingested), "-o", str(plan)]),
+ ("render_topic_cluster_report.py", [str(plan), "-o", str(report)]),
+ ]
+ for script, call in steps:
+ proc = run_script_checked(script, call)
+ if proc.returncode:
+ if proc.stdout:
+ print(proc.stdout, end="")
+ if proc.stderr:
+ print(proc.stderr, end="", file=sys.stderr)
+ return proc.returncode
+ print(report)
+ return 0
+
+
+def run_geo_pipeline(input_path: str, out_dir: str) -> int:
+ out = Path(out_dir).expanduser().resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ ingested = out / "ingested-geo-citation-audit.json"
+ plan = out / "geo-citation-readiness.json"
+ report = out / "geo-citation-readiness-report.md"
+ steps = [
+ ("ingest_geo_citation_audit.py", [input_path, "-o", str(ingested)]),
+ ("synthesize_geo_citation_readiness.py", [str(ingested), "-o", str(plan)]),
+ ("render_geo_citation_report.py", [str(plan), "-o", str(report)]),
+ ]
+ for script, call in steps:
+ proc = run_script_checked(script, call)
+ if proc.returncode:
+ if proc.stdout:
+ print(proc.stdout, end="")
+ if proc.stderr:
+ print(proc.stderr, end="", file=sys.stderr)
+ return proc.returncode
+ print(report)
+ return 0
+
+
if __name__ == "__main__":
raise SystemExit(main())
diff --git a/references/adapter-manifest.json b/references/adapter-manifest.json
index f582c6c..51f7c23 100644
--- a/references/adapter-manifest.json
+++ b/references/adapter-manifest.json
@@ -4,11 +4,13 @@
"domain": "blog content creation, optimization, and management dual-optimized for Google rankings (E-E-A-T, the 2026 core updates) and AI citations (GEO/AEO), spanning writing, rewriting and freshness, SERP-informed briefs and outlines, editorial calendars and strategy, semantic topic clusters, schema and internal linking, multilingual publishing, the FLOW framework, factchecking, personas, distribution, and the blog delivery contract, grounded in the claude-blog skill",
"generic_only": false,
"last_verified": "2026-07-09",
- "release_note": "The first blog JSON adapter path is implemented and CLI-wired. Top-level generic_only remains true as a central maturity gate until orchestrator verification reconciles adapter evidence, raw provenance, demo verification, audit, and release gates.",
+ "release_note": "Blog post, topic cluster, and GEO citation audit JSON adapter paths are implemented, CLI-wired, and covered by subprocess tests. Top-level generic_only remains false; central maturity and status labels are not changed here.",
"raw_input_types": [
"blog-post input JSON using schemas/blog-post-input.schema.json",
"Markdown body supplied through blog-post input JSON",
- "HTML body supplied through blog-post input JSON"
+ "HTML body supplied through blog-post input JSON",
+ "topic-cluster plan JSON using schemas/topic-cluster-input.schema.json",
+ "GEO citation audit JSON using schemas/geo-citation-audit-input.schema.json"
],
"rules": {
"domain_adapted_requires": [
@@ -32,6 +34,30 @@
"HTTP(S) URL patterns",
"ISO date or date-time patterns"
]
+ },
+ {
+ "name": "topic-cluster-input",
+ "path": "schemas/topic-cluster-input.schema.json",
+ "status": "implemented",
+ "planned": false,
+ "enforces": [
+ "required cluster_name, primary_topic, locale, hub, and spokes",
+ "at least two spoke pages",
+ "HTTP(S) URLs for hub, spokes, and existing links",
+ "locale pattern and unique spoke IDs"
+ ]
+ },
+ {
+ "name": "geo-citation-audit-input",
+ "path": "schemas/geo-citation-audit-input.schema.json",
+ "status": "implemented",
+ "planned": false,
+ "enforces": [
+ "required audit_name, URL, title, locale, target queries, passages, and page signals",
+ "at least one target query and one passage",
+ "HTTP(S) URLs for page and passage citations",
+ "boolean page signals and ISO citation dates"
+ ]
}
],
"importers": [
@@ -42,6 +68,22 @@
"status": "implemented",
"planned": false,
"output_schema": "claude-blog-brain.ingested-blog-post.v1"
+ },
+ {
+ "name": "ingest_topic_cluster_input",
+ "path": "scripts/ingest_topic_cluster_input.py",
+ "cli": "claude-blog-brain cluster-ingest",
+ "status": "implemented",
+ "planned": false,
+ "output_schema": "claude-blog-brain.ingested-topic-cluster.v1"
+ },
+ {
+ "name": "ingest_geo_citation_audit",
+ "path": "scripts/ingest_geo_citation_audit.py",
+ "cli": "claude-blog-brain geo-ingest",
+ "status": "implemented",
+ "planned": false,
+ "output_schema": "claude-blog-brain.ingested-geo-citation-audit.v1"
}
],
"synthesis_modules": [
@@ -52,6 +94,22 @@
"status": "implemented",
"planned": false,
"output_schema": "claude-blog-brain.blog-optimization-plan.v1"
+ },
+ {
+ "name": "synthesize_topic_cluster",
+ "path": "scripts/synthesize_topic_cluster.py",
+ "cli": "claude-blog-brain cluster-synthesize",
+ "status": "implemented",
+ "planned": false,
+ "output_schema": "claude-blog-brain.topic-cluster-plan.v1"
+ },
+ {
+ "name": "synthesize_geo_citation_readiness",
+ "path": "scripts/synthesize_geo_citation_readiness.py",
+ "cli": "claude-blog-brain geo-synthesize",
+ "status": "implemented",
+ "planned": false,
+ "output_schema": "claude-blog-brain.geo-citation-readiness.v1"
}
],
"report_renderers": [
@@ -62,6 +120,22 @@
"status": "implemented",
"planned": false,
"output_format": "markdown"
+ },
+ {
+ "name": "render_topic_cluster_report",
+ "path": "scripts/render_topic_cluster_report.py",
+ "cli": "claude-blog-brain cluster-report",
+ "status": "implemented",
+ "planned": false,
+ "output_format": "markdown"
+ },
+ {
+ "name": "render_geo_citation_report",
+ "path": "scripts/render_geo_citation_report.py",
+ "cli": "claude-blog-brain geo-report",
+ "status": "implemented",
+ "planned": false,
+ "output_format": "markdown"
}
],
"fixtures": [
@@ -70,6 +144,18 @@
"path": "tests/fixtures/sample-blog-post.json",
"status": "implemented",
"planned": false
+ },
+ {
+ "name": "sample-topic-cluster-plan",
+ "path": "tests/fixtures/sample-topic-cluster-plan.json",
+ "status": "implemented",
+ "planned": false
+ },
+ {
+ "name": "sample-geo-citation-audit",
+ "path": "tests/fixtures/sample-geo-citation-audit.json",
+ "status": "implemented",
+ "planned": false
}
],
"tests": [
@@ -114,6 +200,42 @@
"path": "tests/test_blog_adapters.py",
"status": "implemented",
"planned": false
+ },
+ {
+ "name": "topic_cluster_valid_deterministic_output_and_citation_coverage",
+ "path": "tests/test_domain_adapters.py",
+ "status": "implemented",
+ "planned": false
+ },
+ {
+ "name": "topic_cluster_malformed_input_json_error_envelope",
+ "path": "tests/test_domain_adapters.py",
+ "status": "implemented",
+ "planned": false
+ },
+ {
+ "name": "geo_valid_deterministic_output_and_citation_coverage",
+ "path": "tests/test_domain_adapters.py",
+ "status": "implemented",
+ "planned": false
+ },
+ {
+ "name": "geo_malformed_input_json_error_envelope",
+ "path": "tests/test_domain_adapters.py",
+ "status": "implemented",
+ "planned": false
+ },
+ {
+ "name": "package_cli_new_adapter_subcommands",
+ "path": "tests/test_domain_adapters.py",
+ "status": "implemented",
+ "planned": false
+ },
+ {
+ "name": "package_cli_new_pipelines",
+ "path": "tests/test_domain_adapters.py",
+ "status": "implemented",
+ "planned": false
}
]
}
diff --git a/references/adapter-plan.md b/references/adapter-plan.md
index 0bfd08b..b6e7046 100644
--- a/references/adapter-plan.md
+++ b/references/adapter-plan.md
@@ -4,17 +4,21 @@ Status: market-ready. Domain code adapters are implemented, CLI-wired, and test-
## Current Adapter Honesty
-`references/adapter-manifest.json` sets `generic_only` to false because the blog
-domain importer, synthesis module, and report renderer are implemented, CLI-wired,
-and covered by tests. The orchestrator has reconciled maturity to market-ready. The adapter evidence now covers the importer, synthesis module,
-renderer, fixture, package CLI, malformed-input envelopes, deterministic output,
-and output-file assertions for the supported blog JSON input type.
+`references/adapter-manifest.json` sets `generic_only` to false because domain
+importers, synthesis modules, and report renderers are implemented, CLI-wired,
+and covered by tests. The orchestrator has reconciled maturity to market-ready.
+The adapter evidence now covers importers, synthesis modules, renderers,
+fixtures, package CLI, malformed-input envelopes, deterministic output,
+output-file assertions, and citation coverage for blog post, topic cluster, and
+GEO citation audit JSON input types.
## Raw Input Types
- Blog post audit input using `schemas/blog-post-input.schema.json`.
- Markdown blog post with YAML frontmatter.
- HTML blog post with canonical URL and extracted metadata.
+- Topic cluster plan input using `schemas/topic-cluster-input.schema.json`.
+- GEO citation audit input using `schemas/geo-citation-audit-input.schema.json`.
- claude-blog quality report JSON from `scripts/analyze_blog.py`.
- Blog delivery contract output from `scripts/blog_preflight.py`.
- Google algorithm update ledger from `data/google-updates.json`.
@@ -27,6 +31,19 @@ and output-file assertions for the supported blog JSON input type.
- Scope: title, URL, Markdown or HTML body, frontmatter, target keyword, locale, author, dates, source block, and optional audit findings.
- Enforced facts: HTTP(S) URL patterns, ISO date or date-time strings, required
title, URL, target keyword, locale, and at least one body field.
+- Name: `topic-cluster-input`.
+- Path: `schemas/topic-cluster-input.schema.json`.
+- Scope: hub page, spoke pages, existing links, locale, audience, objective,
+ entity terms, and source-ledger IDs for a topic cluster plan.
+- Enforced facts: required cluster name, primary topic, locale, hub, at least two
+ spokes, HTTP(S) URLs, unique spoke IDs, and locale pattern.
+- Name: `geo-citation-audit-input`.
+- Path: `schemas/geo-citation-audit-input.schema.json`.
+- Scope: page URL, target queries, passage-level citation evidence, entity
+ fields, page signals, and llms.txt strategy for GEO citation readiness review.
+- Enforced facts: required audit name, URL, title, locale, target queries,
+ passages, page signals, HTTP(S) citation URLs, ISO citation dates, and boolean
+ page signal values.
## Implemented Importer
@@ -35,6 +52,16 @@ and output-file assertions for the supported blog JSON input type.
- Output schema: `claude-blog-brain.ingested-blog-post.v1`.
- Output facts: normalized headings, sections, links, source counts,
provenance hashes, date metadata, author signals, and schema hints.
+- `ingest_topic_cluster_input`, path `scripts/ingest_topic_cluster_input.py`.
+- CLI path: `claude-blog-brain cluster-ingest`.
+- Output schema: `claude-blog-brain.ingested-topic-cluster.v1`.
+- Output facts: normalized hub and spoke pages, existing link graph, duplicate
+ keyword groups, orphan spoke IDs, entity terms, source IDs, and provenance hash.
+- `ingest_geo_citation_audit`, path `scripts/ingest_geo_citation_audit.py`.
+- CLI path: `claude-blog-brain geo-ingest`.
+- Output schema: `claude-blog-brain.ingested-geo-citation-audit.v1`.
+- Output facts: normalized target queries, passages, passage word counts,
+ extractability flags, citation counts, entities, page signals, and provenance hash.
## Implemented Synthesis Module
@@ -44,6 +71,18 @@ and output-file assertions for the supported blog JSON input type.
- Output facts: five-category blog scorecard, intent and entity coverage,
GEO and AI citation readiness checks, schema recommendations, prioritized
recommendations, delivery contract, and source citations.
+- `synthesize_topic_cluster`, path `scripts/synthesize_topic_cluster.py`.
+- CLI path: `claude-blog-brain cluster-synthesize`.
+- Output schema: `claude-blog-brain.topic-cluster-plan.v1`.
+- Output facts: cluster scorecard, hub and spoke internal-link matrix, spoke
+ support links, prioritized recommendations, rollback notes, and source citations.
+- `synthesize_geo_citation_readiness`, path
+ `scripts/synthesize_geo_citation_readiness.py`.
+- CLI path: `claude-blog-brain geo-synthesize`.
+- Output schema: `claude-blog-brain.geo-citation-readiness.v1`.
+- Output facts: readiness score, passage extractability, visible citation
+ support, entity clarity, schema and crawl eligibility, measurement readiness,
+ llms.txt caveat, no-guarantee guardrail, rollback notes, and source citations.
## Implemented Renderer
@@ -52,12 +91,24 @@ and output-file assertions for the supported blog JSON input type.
- Output format: Markdown report with scorecard, delivery verdict, prioritized
recommendations, GEO and AI citation readiness, schema recommendations, and
source citations.
+- `render_topic_cluster_report`, path `scripts/render_topic_cluster_report.py`.
+- CLI path: `claude-blog-brain cluster-report`.
+- Output format: Markdown report with cluster scorecard, internal-link matrix,
+ prioritized recommendations, rollback notes, and source citations.
+- `render_geo_citation_report`, path `scripts/render_geo_citation_report.py`.
+- CLI path: `claude-blog-brain geo-report`.
+- Output format: Markdown report with readiness metrics, checks,
+ recommendations, rollback notes, and source citations.
## Implemented Fixture
- `sample-blog-post`, path `tests/fixtures/sample-blog-post.json`.
+- `sample-topic-cluster-plan`, path
+ `tests/fixtures/sample-topic-cluster-plan.json`.
+- `sample-geo-citation-audit`, path
+ `tests/fixtures/sample-geo-citation-audit.json`.
- Later fixtures may cover blog audits, Google update ledgers, and claude-blog
- reference packs after the first input type is release-verified.
+ reference packs after these input types are release-verified.
## Implemented Tests
@@ -71,6 +122,16 @@ and output-file assertions for the supported blog JSON input type.
- `invalid_date_and_url_rejection`, path `tests/test_blog_adapters.py`.
- `package_cli_blog_subcommands`, path `tests/test_blog_adapters.py`.
- `package_cli_blog_pipeline`, path `tests/test_blog_adapters.py`.
+- `topic_cluster_valid_deterministic_output_and_citation_coverage`, path
+ `tests/test_domain_adapters.py`.
+- `topic_cluster_malformed_input_json_error_envelope`, path
+ `tests/test_domain_adapters.py`.
+- `geo_valid_deterministic_output_and_citation_coverage`, path
+ `tests/test_domain_adapters.py`.
+- `geo_malformed_input_json_error_envelope`, path
+ `tests/test_domain_adapters.py`.
+- `package_cli_new_adapter_subcommands`, path `tests/test_domain_adapters.py`.
+- `package_cli_new_pipelines`, path `tests/test_domain_adapters.py`.
## Safety Requirements
diff --git a/schemas/geo-citation-audit-input.schema.json b/schemas/geo-citation-audit-input.schema.json
new file mode 100644
index 0000000..b3a785e
--- /dev/null
+++ b/schemas/geo-citation-audit-input.schema.json
@@ -0,0 +1,63 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "https://github.com/AgriciDaniel/claude-blog-brain/schemas/geo-citation-audit-input.schema.json",
+ "title": "GEO Citation Audit Input",
+ "description": "A passage-level AI citation readiness audit consumed by Claude Blog Brain GEO adapters.",
+ "type": "object",
+ "required": ["audit_name", "url", "title", "locale", "target_queries", "passages", "page_signals"],
+ "properties": {
+ "audit_name": {"type": "string", "minLength": 1},
+ "url": {"type": "string", "format": "uri", "pattern": "^https?://"},
+ "title": {"type": "string", "minLength": 1},
+ "locale": {"type": "string", "pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"},
+ "target_queries": {
+ "type": "array",
+ "minItems": 1,
+ "items": {"type": "string", "minLength": 1}
+ },
+ "passages": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "required": ["id", "heading", "text"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {"type": "string", "minLength": 1},
+ "heading": {"type": "string", "minLength": 1},
+ "text": {"type": "string", "minLength": 1},
+ "entities": {"type": "array", "items": {"type": "string"}},
+ "citations": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["title", "url", "retrieved"],
+ "additionalProperties": false,
+ "properties": {
+ "title": {"type": "string", "minLength": 1},
+ "url": {"type": "string", "format": "uri", "pattern": "^https?://"},
+ "published": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
+ "retrieved": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"}
+ }
+ }
+ }
+ }
+ }
+ },
+ "page_signals": {
+ "type": "object",
+ "required": ["has_article_schema", "indexable", "preview_allowed", "has_visible_author", "has_modified_date"],
+ "additionalProperties": false,
+ "properties": {
+ "has_article_schema": {"type": "boolean"},
+ "indexable": {"type": "boolean"},
+ "preview_allowed": {"type": "boolean"},
+ "has_visible_author": {"type": "boolean"},
+ "has_modified_date": {"type": "boolean"}
+ }
+ },
+ "llms_txt_strategy": {"type": "string", "enum": ["none", "present", "planned", "unknown"]},
+ "source_ids": {"type": "array", "items": {"type": "string"}}
+ },
+ "additionalProperties": false
+}
diff --git a/schemas/topic-cluster-input.schema.json b/schemas/topic-cluster-input.schema.json
new file mode 100644
index 0000000..44a938c
--- /dev/null
+++ b/schemas/topic-cluster-input.schema.json
@@ -0,0 +1,60 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "https://github.com/AgriciDaniel/claude-blog-brain/schemas/topic-cluster-input.schema.json",
+ "title": "Topic Cluster Plan Input",
+ "description": "A hub and spoke topic cluster plan consumed by Claude Blog Brain cluster adapters.",
+ "type": "object",
+ "required": ["cluster_name", "primary_topic", "locale", "hub", "spokes"],
+ "properties": {
+ "cluster_name": {"type": "string", "minLength": 1},
+ "primary_topic": {"type": "string", "minLength": 1},
+ "locale": {"type": "string", "pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"},
+ "audience": {"type": "string"},
+ "objective": {"type": "string"},
+ "hub": {
+ "type": "object",
+ "required": ["title", "url", "target_keyword"],
+ "additionalProperties": false,
+ "properties": {
+ "title": {"type": "string", "minLength": 1},
+ "url": {"type": "string", "format": "uri", "pattern": "^https?://"},
+ "target_keyword": {"type": "string", "minLength": 1}
+ }
+ },
+ "spokes": {
+ "type": "array",
+ "minItems": 2,
+ "items": {
+ "type": "object",
+ "required": ["id", "title", "url", "target_keyword", "intent"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {"type": "string", "minLength": 1},
+ "title": {"type": "string", "minLength": 1},
+ "url": {"type": "string", "format": "uri", "pattern": "^https?://"},
+ "target_keyword": {"type": "string", "minLength": 1},
+ "intent": {"type": "string", "minLength": 1},
+ "stage": {"type": "string"},
+ "priority": {"type": "string", "enum": ["critical", "high", "medium", "low"]},
+ "source_ids": {"type": "array", "items": {"type": "string"}}
+ }
+ }
+ },
+ "existing_links": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["from_url", "to_url"],
+ "additionalProperties": false,
+ "properties": {
+ "from_url": {"type": "string", "format": "uri", "pattern": "^https?://"},
+ "to_url": {"type": "string", "format": "uri", "pattern": "^https?://"},
+ "anchor": {"type": "string"}
+ }
+ }
+ },
+ "entity_terms": {"type": "array", "items": {"type": "string"}},
+ "source_ids": {"type": "array", "items": {"type": "string"}}
+ },
+ "additionalProperties": false
+}
diff --git a/scripts/audit_brain.py b/scripts/audit_brain.py
index 9c57d97..dc469a1 100755
--- a/scripts/audit_brain.py
+++ b/scripts/audit_brain.py
@@ -3,11 +3,13 @@
from __future__ import annotations
import argparse
+import hashlib
import json
import re
import subprocess
import sys
import tempfile
+from collections import Counter, defaultdict
from datetime import date
from pathlib import Path
from typing import Any
@@ -99,6 +101,17 @@ MATURITY_SCORE_CAP = {
MATURITY_ORDER = ["scaffolded", "researched", "domain-adapted", "demo-verified", "market-ready"]
CONFIDENCE_VALUES = {"high", "medium", "low"}
EXEC_TIMEOUT_SECONDS = 180
+SHINGLE_SIZE = 8
+NEAR_DUPLICATE_THRESHOLD = 0.82
+SKELETON_REUSE_THRESHOLD = 3
+ANCHOR_REUSE_THRESHOLD = 2
+TABLE_OR_PROCEDURE_THRESHOLD = 0.90
+SPECIFIC_CITATION_THRESHOLD = 1.00
+GENERIC_BUNDLE_REUSE_THRESHOLD = 3
+DENSITY_WORD_THRESHOLD = 120
+URL_RE = re.compile(r"https?://[^\s<>\]\"')]+")
+WORD_RE = re.compile(r"[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)?")
+FRONTMATTER_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*(?:\n|\Z)", re.S)
def main(argv: list[str] | None = None) -> int:
@@ -152,6 +165,9 @@ def audit_repo(*, run_verification: bool = False) -> dict[str, Any]:
citation_ok, citation_score, citation_notes, citation_critical = check_citations()
add_category(categories, "source_citation", citation_ok, citation_score, citation_notes)
critical.extend(citation_critical)
+ wiki_ok, wiki_score, wiki_notes, wiki_critical, wiki_details = check_wiki_substance(REPO)
+ add_category(categories, "wiki_substance", wiki_ok, wiki_score, wiki_notes, wiki_details)
+ critical.extend(wiki_critical)
add_category(categories, "demo_determinism", *check_demo_contract())
add_category(categories, "tests", *check_tests_contract())
verification_ok, verification_score, verification_notes, verification_critical = check_release_verification(run_verification=run_verification)
@@ -180,8 +196,18 @@ def audit_repo(*, run_verification: bool = False) -> dict[str, Any]:
}
-def add_category(categories: dict[str, dict[str, Any]], name: str, ok: bool, score: int, notes: list[str]) -> None:
- categories[name] = {"ok": ok, "score": max(0, min(100, score)), "notes": notes}
+def add_category(
+ categories: dict[str, dict[str, Any]],
+ name: str,
+ ok: bool,
+ score: int,
+ notes: list[str],
+ details: dict[str, Any] | None = None,
+) -> None:
+ category = {"ok": ok, "score": max(0, min(100, score)), "notes": notes}
+ if details is not None:
+ category["details"] = details
+ categories[name] = category
def check_product_clarity() -> tuple[bool, int, list[str]]:
@@ -412,6 +438,386 @@ def check_citations() -> tuple[bool, int, list[str], list[str]]:
return not critical, max(0, 100 - 15 * len(critical)), notes, critical
+def check_wiki_substance(repo_root: Path = REPO) -> tuple[bool, int, list[str], list[str], dict[str, Any]]:
+ wiki_root = repo_root / "wiki"
+ notes: list[str] = []
+ critical: list[str] = []
+ if not wiki_root.exists():
+ details = empty_wiki_substance_details()
+ notes.append("missing wiki directory")
+ return False, 0, notes, critical, details
+
+ source_ids, url_to_source_id = load_source_index(repo_root)
+ source_id_pattern = compile_source_id_pattern(source_ids)
+ spoke_notes = load_spoke_notes(repo_root, wiki_root, source_id_pattern, url_to_source_id)
+ if not spoke_notes:
+ details = empty_wiki_substance_details()
+ notes.append("no type: spoke notes found in wiki")
+ return False, 0, notes, critical, details
+
+ near_pairs = find_near_duplicate_pairs(spoke_notes)
+ skeleton = largest_reuse_group(spoke_notes, "skeleton")
+ anchor = largest_anchor_reuse(spoke_notes)
+ table_or_procedure_failures = [
+ note["rel_path"] for note in spoke_notes if not note["has_table_or_procedure"]
+ ]
+
+ bundle_counts: Counter[frozenset[str]] = Counter(
+ note["source_bundle"] for note in spoke_notes if len(note["source_bundle"]) >= 2
+ )
+ generic_bundle, generic_bundle_count = largest_bundle(bundle_counts)
+ generic_bundle_reused = {
+ bundle for bundle, count in bundle_counts.items() if count > GENERIC_BUNDLE_REUSE_THRESHOLD
+ }
+ citation_failures = [
+ note["rel_path"]
+ for note in spoke_notes
+ if not note["source_bundle"] or note["source_bundle"] in generic_bundle_reused
+ ]
+
+ shared_lines = shared_body_lines(spoke_notes)
+ density_failures = []
+ density_values: dict[str, int] = {}
+ for note in spoke_notes:
+ count = note_specific_word_count(note["body_lines"], shared_lines)
+ density_values[note["rel_path"]] = count
+ if count < DENSITY_WORD_THRESHOLD:
+ density_failures.append({"path": note["rel_path"], "note_specific_words": count})
+
+ table_or_procedure_coverage = 1.0 - (len(table_or_procedure_failures) / len(spoke_notes))
+ specific_citation_coverage = 1.0 - (len(citation_failures) / len(spoke_notes))
+ density_floor = min(density_values.values()) if density_values else 0
+ max_skeleton_reuse = skeleton["count"] if skeleton else 0
+ max_anchor_reuse = anchor["count"] if anchor else 0
+
+ metrics = {
+ "spoke_count": len(spoke_notes),
+ "near_duplicate_pairs": len(near_pairs),
+ "max_skeleton_reuse": max_skeleton_reuse,
+ "max_anchor_reuse": max_anchor_reuse,
+ "table_or_procedure_coverage": round(table_or_procedure_coverage, 4),
+ "specific_citation_coverage": round(specific_citation_coverage, 4),
+ "generic_bundle_reuse": generic_bundle_count,
+ "density_floor": density_floor,
+ "density_floor_below_count": len(density_failures),
+ }
+ offenders = {
+ "near_duplicate_pairs": near_pairs,
+ "max_skeleton_reuse": skeleton if max_skeleton_reuse > SKELETON_REUSE_THRESHOLD else {},
+ "max_anchor_reuse": anchor if max_anchor_reuse > ANCHOR_REUSE_THRESHOLD else {},
+ "table_or_procedure_coverage": table_or_procedure_failures,
+ "specific_citation_coverage": citation_failures,
+ "generic_bundle_reuse": {
+ "count": generic_bundle_count,
+ "source_ids": sorted(generic_bundle),
+ "paths": [
+ note["rel_path"] for note in spoke_notes if note["source_bundle"] == generic_bundle
+ ] if generic_bundle_count > GENERIC_BUNDLE_REUSE_THRESHOLD else [],
+ },
+ "density_floor": density_failures,
+ }
+ details = {"metrics": metrics, "offenders": offenders}
+
+ if near_pairs:
+ first = near_pairs[0]["paths"]
+ critical.append(f"wiki_substance near_duplicate_pairs={len(near_pairs)}: {first[0]} <-> {first[1]}")
+ notes.append(f"near duplicate spoke pairs: {len(near_pairs)}")
+ if max_skeleton_reuse > SKELETON_REUSE_THRESHOLD:
+ notes.append(f"H2/H3 skeleton reused by {max_skeleton_reuse} spoke notes")
+ if max_anchor_reuse > ANCHOR_REUSE_THRESHOLD:
+ notes.append(f"anchor line reused by {max_anchor_reuse} spoke notes")
+ if table_or_procedure_coverage < TABLE_OR_PROCEDURE_THRESHOLD:
+ notes.append(f"table/procedure coverage {table_or_procedure_coverage:.2f} below 0.90")
+ if specific_citation_coverage < SPECIFIC_CITATION_THRESHOLD:
+ notes.append(f"specific citation coverage {specific_citation_coverage:.2f} below 1.00")
+ if generic_bundle_count > GENERIC_BUNDLE_REUSE_THRESHOLD:
+ notes.append(f"generic source bundle reused by {generic_bundle_count} spoke notes")
+ if density_failures:
+ notes.append(f"{len(density_failures)} spoke notes below {DENSITY_WORD_THRESHOLD} note-specific words")
+
+ ok = (
+ len(near_pairs) == 0
+ and max_skeleton_reuse <= SKELETON_REUSE_THRESHOLD
+ and max_anchor_reuse <= ANCHOR_REUSE_THRESHOLD
+ and table_or_procedure_coverage >= TABLE_OR_PROCEDURE_THRESHOLD
+ and specific_citation_coverage >= SPECIFIC_CITATION_THRESHOLD
+ and generic_bundle_count <= GENERIC_BUNDLE_REUSE_THRESHOLD
+ and not density_failures
+ )
+ return ok, score_wiki_substance(metrics, len(spoke_notes)), notes, critical, details
+
+
+def empty_wiki_substance_details() -> dict[str, Any]:
+ return {
+ "metrics": {
+ "spoke_count": 0,
+ "near_duplicate_pairs": 0,
+ "max_skeleton_reuse": 0,
+ "max_anchor_reuse": 0,
+ "table_or_procedure_coverage": 0.0,
+ "specific_citation_coverage": 0.0,
+ "generic_bundle_reuse": 0,
+ "density_floor": 0,
+ "density_floor_below_count": 0,
+ },
+ "offenders": {
+ "near_duplicate_pairs": [],
+ "max_skeleton_reuse": {},
+ "max_anchor_reuse": {},
+ "table_or_procedure_coverage": [],
+ "specific_citation_coverage": [],
+ "generic_bundle_reuse": {"count": 0, "source_ids": [], "paths": []},
+ "density_floor": [],
+ },
+ }
+
+
+def load_source_index(repo_root: Path) -> tuple[set[str], dict[str, str]]:
+ data, _errors = load_json_object(repo_root / "references" / "source-ledger.json")
+ source_ids: set[str] = set()
+ url_to_source_id: dict[str, str] = {}
+ sources = data.get("sources") if isinstance(data, dict) else None
+ if not isinstance(sources, list):
+ return source_ids, url_to_source_id
+ for source in sources:
+ if not isinstance(source, dict):
+ continue
+ source_id = clean_string(source.get("id")) or clean_string(source.get("source_id"))
+ if not source_id:
+ continue
+ source_ids.add(source_id)
+ url = canonical_source_url(clean_string(source.get("url")))
+ if url:
+ url_to_source_id[url] = source_id
+ return source_ids, url_to_source_id
+
+
+def compile_source_id_pattern(source_ids: set[str]) -> re.Pattern[str] | None:
+ if not source_ids:
+ return None
+ alternatives = "|".join(re.escape(source_id) for source_id in sorted(source_ids, key=len, reverse=True))
+ return re.compile(r"(?<![A-Za-z0-9_-])(" + alternatives + r")(?![A-Za-z0-9_-])")
+
+
+def load_spoke_notes(
+ repo_root: Path,
+ wiki_root: Path,
+ source_id_pattern: re.Pattern[str] | None,
+ url_to_source_id: dict[str, str],
+) -> list[dict[str, Any]]:
+ spoke_notes: list[dict[str, Any]] = []
+ for path in sorted(wiki_root.rglob("*.md")):
+ if path.name == "_index.md":
+ continue
+ text = path.read_text(encoding="utf-8", errors="replace")
+ frontmatter, body = split_frontmatter(text)
+ if frontmatter_type(frontmatter) != "spoke":
+ continue
+ body_lines = [collapse_whitespace(line) for line in body.splitlines()]
+ normalized = normalize_body(body)
+ tokens = normalized.split()
+ source_bundle = frozenset(extract_source_ids(text, source_id_pattern, url_to_source_id))
+ spoke_notes.append(
+ {
+ "path": path,
+ "rel_path": display_path(path, repo_root),
+ "body": body,
+ "body_lines": body_lines,
+ "normalized_body": normalized,
+ "tokens": tokens,
+ "shingles": make_shingles(tokens),
+ "skeleton": heading_skeleton(body),
+ "has_table_or_procedure": has_table_or_procedure(body),
+ "source_bundle": source_bundle,
+ }
+ )
+ return spoke_notes
+
+
+def split_frontmatter(text: str) -> tuple[str, str]:
+ match = FRONTMATTER_RE.match(text)
+ if not match:
+ return "", text
+ return match.group(1), text[match.end():]
+
+
+def frontmatter_type(frontmatter: str) -> str:
+ match = re.search(r"(?m)^type:\s*[\"']?([^\"'\n#]+)[\"']?", frontmatter)
+ return match.group(1).strip().lower() if match else ""
+
+
+def normalize_body(body: str) -> str:
+ return collapse_whitespace(body.lower())
+
+
+def collapse_whitespace(value: str) -> str:
+ return re.sub(r"\s+", " ", value).strip()
+
+
+def make_shingles(tokens: list[str], size: int = SHINGLE_SIZE) -> frozenset[int]:
+ if not tokens:
+ return frozenset()
+ if len(tokens) < size:
+ return frozenset({stable_shingle_hash(tokens)})
+ return frozenset(stable_shingle_hash(tokens[index:index + size]) for index in range(len(tokens) - size + 1))
+
+
+def stable_shingle_hash(tokens: list[str]) -> int:
+ digest = hashlib.blake2b(" ".join(tokens).encode("utf-8"), digest_size=8).digest()
+ return int.from_bytes(digest, "big")
+
+
+def heading_skeleton(body: str) -> tuple[str, ...]:
+ headings = []
+ for line in body.splitlines():
+ match = re.match(r"^\s{0,3}(#{2,3})\s+(.+?)\s*$", line)
+ if match:
+ headings.append(match.group(1) + " " + collapse_whitespace(match.group(2)).lower())
+ return tuple(headings)
+
+
+def has_table_or_procedure(body: str) -> bool:
+ lines = body.splitlines()
+ for index, line in enumerate(lines[:-1]):
+ if "|" in line and re.match(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$", lines[index + 1]):
+ return True
+ step_count = 0
+ for line in lines:
+ if re.match(r"^\s*(?:\d+[\.)]|step\s+\d+\b)\s+", line, re.I):
+ step_count += 1
+ if step_count >= 3:
+ return True
+ return False
+
+
+def extract_source_ids(
+ text: str,
+ source_id_pattern: re.Pattern[str] | None,
+ url_to_source_id: dict[str, str],
+) -> set[str]:
+ found: set[str] = set()
+ if source_id_pattern:
+ found.update(source_id_pattern.findall(text))
+ for match in URL_RE.finditer(text):
+ source_id = url_to_source_id.get(canonical_source_url(match.group(0)))
+ if source_id:
+ found.add(source_id)
+ return found
+
+
+def canonical_source_url(value: str) -> str:
+ if not value:
+ return ""
+ cleaned = value.strip().strip("<>\"'").rstrip(".,;:")
+ parsed = urlparse(cleaned)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ return ""
+ parsed = parsed._replace(netloc=parsed.netloc.lower(), fragment="")
+ return parsed.geturl().rstrip("/")
+
+
+def find_near_duplicate_pairs(spoke_notes: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ inverted: dict[int, list[int]] = defaultdict(list)
+ for index, note in enumerate(spoke_notes):
+ for shingle in note["shingles"]:
+ inverted[shingle].append(index)
+
+ intersections: Counter[tuple[int, int]] = Counter()
+ for indexes in inverted.values():
+ if len(indexes) < 2:
+ continue
+ for left_pos, left in enumerate(indexes):
+ for right in indexes[left_pos + 1:]:
+ intersections[(left, right)] += 1
+
+ pairs = []
+ for (left, right), intersection in intersections.items():
+ left_shingles = spoke_notes[left]["shingles"]
+ right_shingles = spoke_notes[right]["shingles"]
+ union = len(left_shingles) + len(right_shingles) - intersection
+ similarity = 1.0 if union == 0 else intersection / union
+ if similarity >= NEAR_DUPLICATE_THRESHOLD:
+ pairs.append(
+ {
+ "paths": [spoke_notes[left]["rel_path"], spoke_notes[right]["rel_path"]],
+ "similarity": round(similarity, 4),
+ }
+ )
+ return sorted(pairs, key=lambda item: (-item["similarity"], item["paths"]))
+
+
+def largest_reuse_group(spoke_notes: list[dict[str, Any]], key: str) -> dict[str, Any]:
+ groups: dict[Any, list[str]] = defaultdict(list)
+ for note in spoke_notes:
+ groups[note[key]].append(note["rel_path"])
+ candidates = list(groups.items())
+ if not candidates:
+ return {}
+ value, paths = max(candidates, key=lambda item: (len(item[1]), sorted(item[1])[0]))
+ return {"count": len(paths), "value": list(value), "paths": sorted(paths)}
+
+
+def largest_anchor_reuse(spoke_notes: list[dict[str, Any]]) -> dict[str, Any]:
+ anchors: dict[str, list[str]] = defaultdict(list)
+ for note in spoke_notes:
+ seen_in_note = set()
+ for line in note["body_lines"]:
+ if line and len(WORD_RE.findall(line)) >= 12:
+ seen_in_note.add(line)
+ for line in seen_in_note:
+ anchors[line].append(note["rel_path"])
+ candidates = list(anchors.items())
+ if not candidates:
+ return {}
+ line, paths = max(candidates, key=lambda item: (len(item[1]), item[0]))
+ return {"count": len(paths), "line": line, "paths": sorted(paths)}
+
+
+def largest_bundle(bundle_counts: Counter[frozenset[str]]) -> tuple[frozenset[str], int]:
+ if not bundle_counts:
+ return frozenset(), 0
+ bundle, count = max(bundle_counts.items(), key=lambda item: (item[1], len(item[0]), sorted(item[0])))
+ return bundle, count
+
+
+def shared_body_lines(spoke_notes: list[dict[str, Any]]) -> set[str]:
+ counts: Counter[str] = Counter()
+ for note in spoke_notes:
+ counts.update({line for line in note["body_lines"] if line})
+ return {line for line, count in counts.items() if count > 1}
+
+
+def note_specific_word_count(body_lines: list[str], shared_lines: set[str]) -> int:
+ specific_lines = [line for line in body_lines if line and line not in shared_lines]
+ return len(WORD_RE.findall("\n".join(specific_lines)))
+
+
+def score_wiki_substance(metrics: dict[str, Any], spoke_count: int) -> int:
+ if spoke_count <= 0:
+ return 0
+ score = 100.0
+ if metrics["max_skeleton_reuse"] > SKELETON_REUSE_THRESHOLD:
+ overage = metrics["max_skeleton_reuse"] - SKELETON_REUSE_THRESHOLD
+ score -= 10.0 * min(1.0, overage / max(1, spoke_count - SKELETON_REUSE_THRESHOLD))
+ if metrics["max_anchor_reuse"] > ANCHOR_REUSE_THRESHOLD:
+ overage = metrics["max_anchor_reuse"] - ANCHOR_REUSE_THRESHOLD
+ score -= 10.0 * min(1.0, overage / max(1, spoke_count - ANCHOR_REUSE_THRESHOLD))
+ if metrics["generic_bundle_reuse"] > GENERIC_BUNDLE_REUSE_THRESHOLD:
+ overage = metrics["generic_bundle_reuse"] - GENERIC_BUNDLE_REUSE_THRESHOLD
+ score -= 10.0 * min(1.0, overage / max(1, spoke_count - GENERIC_BUNDLE_REUSE_THRESHOLD))
+ if metrics["table_or_procedure_coverage"] < TABLE_OR_PROCEDURE_THRESHOLD:
+ shortfall = TABLE_OR_PROCEDURE_THRESHOLD - metrics["table_or_procedure_coverage"]
+ score -= 15.0 * min(1.0, shortfall / TABLE_OR_PROCEDURE_THRESHOLD)
+ if metrics["specific_citation_coverage"] < SPECIFIC_CITATION_THRESHOLD:
+ shortfall = SPECIFIC_CITATION_THRESHOLD - metrics["specific_citation_coverage"]
+ score -= 20.0 * min(1.0, shortfall / SPECIFIC_CITATION_THRESHOLD)
+ if metrics["density_floor_below_count"]:
+ score -= 15.0 * min(1.0, metrics["density_floor_below_count"] / spoke_count)
+ if metrics["near_duplicate_pairs"] > 0:
+ score = min(score, 40.0)
+ return round(max(0.0, min(100.0, score)))
+
+
def check_demo_contract() -> tuple[bool, int, list[str]]:
required = ["examples/sample-vault/CODEX.md", "examples/sample-vault/.raw/.manifest.json", "examples/sample-vault/wiki/hot.md", "examples/sample-vault/wiki/reports/Weekly Report.md"]
ok, score, notes = check_paths(required)
@@ -519,14 +925,14 @@ def determine_status(categories: dict[str, dict[str, Any]], score: int, critical
return "researched"
if not categories["demo_determinism"]["ok"] or not categories["tests"]["ok"]:
return "domain-adapted"
- if critical or score < 90 or any(not categories[name]["ok"] for name in ["packaging", "installability", "docs", "source_citation", "obsidian_vault_quality", "release_verification"]):
+ if critical or score < 90 or any(not categories[name]["ok"] for name in ["packaging", "installability", "docs", "source_citation", "wiki_substance", "obsidian_vault_quality", "release_verification"]):
return "demo-verified"
return "market-ready"
def load_json_object(path: Path) -> tuple[dict[str, Any], list[str]]:
if not path.exists():
- return {}, [f"missing {path.relative_to(REPO).as_posix()}"]
+ return {}, [f"missing {display_path(path, REPO)}"]
try:
data = json.loads(path.read_text(encoding="utf-8"))
except ValueError as exc:
@@ -536,6 +942,13 @@ def load_json_object(path: Path) -> tuple[dict[str, Any], list[str]]:
return data, []
+def display_path(path: Path, root: Path) -> str:
+ try:
+ return path.relative_to(root).as_posix()
+ except ValueError:
+ return path.as_posix()
+
+
def contains_any(text: str, terms: set[str]) -> bool:
lowered = text.lower()
return any(term in lowered for term in terms)
diff --git a/scripts/ingest_geo_citation_audit.py b/scripts/ingest_geo_citation_audit.py
new file mode 100644
index 0000000..19a87b9
--- /dev/null
+++ b/scripts/ingest_geo_citation_audit.py
@@ -0,0 +1,343 @@
+#!/usr/bin/env python3
+"""Domain importer: normalize a GEO citation audit input JSON.
+
+The adapter reads ``schemas/geo-citation-audit-input.schema.json`` shaped data,
+validates passage, citation, and page signal fields, and emits a deterministic
+record for AI citation readiness synthesis.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import sys
+from datetime import date
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlparse
+
+
+REPO = Path(__file__).resolve().parents[1]
+SCHEMA_PATH = REPO / "schemas" / "geo-citation-audit-input.schema.json"
+LOCALE_RE = re.compile(r"^[a-z]{2,3}(-[A-Z]{2})?$")
+WORD_RE = re.compile(r"[A-Za-z0-9]+(?:'[A-Za-z0-9]+)?")
+ROOT_KEYS = {
+ "audit_name",
+ "url",
+ "title",
+ "locale",
+ "target_queries",
+ "passages",
+ "page_signals",
+ "llms_txt_strategy",
+ "source_ids",
+}
+
+
+class ValidationError(ValueError):
+ """Raised when a GEO citation audit input cannot be normalized."""
+
+ def __init__(self, errors: list[str]) -> None:
+ self.errors = errors
+ super().__init__("; ".join(errors))
+
+
+def clean_output_text(value: str) -> str:
+ cleaned = value.replace("\u2014", "-").replace("\u2013", "-").replace("\u2212", "-")
+ while "--" in cleaned:
+ cleaned = cleaned.replace("--", "-")
+ return cleaned
+
+
+def clean_structure(value: Any) -> Any:
+ if isinstance(value, str):
+ return clean_output_text(value).strip()
+ if isinstance(value, list):
+ return [clean_structure(item) for item in value]
+ if isinstance(value, dict):
+ return {str(key): clean_structure(item) for key, item in value.items()}
+ return value
+
+
+def read_json(path: str | Path) -> dict[str, Any]:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValidationError([f"invalid JSON at line {exc.lineno}, column {exc.colno}"]) from exc
+ if not isinstance(data, dict):
+ raise ValidationError(["input root must be an object"])
+ return clean_structure(data)
+
+
+def load_schema_id() -> str:
+ try:
+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
+ except OSError:
+ return ""
+ if isinstance(schema, dict):
+ return str(schema.get("$id", ""))
+ return ""
+
+
+def validate_input(data: dict[str, Any]) -> None:
+ errors: list[str] = []
+ for key in ("audit_name", "url", "title", "locale", "target_queries", "passages", "page_signals"):
+ if key not in data:
+ errors.append(f"missing required key: {key}")
+ unexpected = sorted(set(data) - ROOT_KEYS)
+ if unexpected:
+ errors.append("unexpected keys: " + ", ".join(unexpected))
+ for key in ("audit_name", "url", "title", "locale", "llms_txt_strategy"):
+ if key in data and not is_string(data.get(key)):
+ errors.append(f"{key} must be a string")
+ if is_nonempty_string(data.get("url")) and not is_http_url(data["url"]):
+ errors.append("url must be an HTTP(S) URL")
+ if is_string(data.get("locale")) and not LOCALE_RE.match(data["locale"]):
+ errors.append("locale must match language or language-region")
+ if data.get("llms_txt_strategy") not in {"none", "present", "planned", "unknown", None}:
+ errors.append("llms_txt_strategy is invalid")
+ validate_string_list(data.get("target_queries"), errors, "target_queries", min_items=1)
+ validate_passages(data.get("passages"), errors)
+ validate_page_signals(data.get("page_signals"), errors)
+ validate_string_list(data.get("source_ids", []), errors, "source_ids")
+ if errors:
+ raise ValidationError(dedupe(errors))
+
+
+def validate_passages(value: Any, errors: list[str]) -> None:
+ if not isinstance(value, list):
+ errors.append("passages must be an array")
+ return
+ if not value:
+ errors.append("passages must include at least one passage")
+ seen_ids: set[str] = set()
+ for index, item in enumerate(value, start=1):
+ if not isinstance(item, dict):
+ errors.append(f"passages #{index} must be an object")
+ continue
+ unexpected = sorted(set(item) - {"id", "heading", "text", "entities", "citations"})
+ if unexpected:
+ errors.append(f"passages #{index} unexpected keys: " + ", ".join(unexpected))
+ for key in ("id", "heading", "text"):
+ if not is_nonempty_string(item.get(key)):
+ errors.append(f"passages #{index}.{key} must be a nonempty string")
+ if is_nonempty_string(item.get("id")):
+ if item["id"] in seen_ids:
+ errors.append(f"passages #{index}.id must be unique")
+ seen_ids.add(item["id"])
+ validate_string_list(item.get("entities", []), errors, f"passages #{index}.entities")
+ validate_citations(item.get("citations", []), errors, f"passages #{index}.citations")
+
+
+def validate_citations(value: Any, errors: list[str], path: str) -> None:
+ if not isinstance(value, list):
+ errors.append(f"{path} must be an array")
+ return
+ for index, item in enumerate(value, start=1):
+ if not isinstance(item, dict):
+ errors.append(f"{path} #{index} must be an object")
+ continue
+ unexpected = sorted(set(item) - {"title", "url", "published", "retrieved"})
+ if unexpected:
+ errors.append(f"{path} #{index} unexpected keys: " + ", ".join(unexpected))
+ for key in ("title", "url", "retrieved"):
+ if not is_nonempty_string(item.get(key)):
+ errors.append(f"{path} #{index}.{key} must be a nonempty string")
+ if is_nonempty_string(item.get("url")) and not is_http_url(item["url"]):
+ errors.append(f"{path} #{index}.url must be an HTTP(S) URL")
+ for key in ("published", "retrieved"):
+ if key in item and is_string(item.get(key)) and item[key] and not is_iso_date(item[key]):
+ errors.append(f"{path} #{index}.{key} must be an ISO date")
+
+
+def validate_page_signals(value: Any, errors: list[str]) -> None:
+ if not isinstance(value, dict):
+ errors.append("page_signals must be an object")
+ return
+ expected = {"has_article_schema", "indexable", "preview_allowed", "has_visible_author", "has_modified_date"}
+ unexpected = sorted(set(value) - expected)
+ if unexpected:
+ errors.append("page_signals unexpected keys: " + ", ".join(unexpected))
+ for key in sorted(expected):
+ if key not in value:
+ errors.append(f"page_signals.{key} is required")
+ elif not isinstance(value[key], bool):
+ errors.append(f"page_signals.{key} must be a boolean")
+
+
+def validate_string_list(value: Any, errors: list[str], path: str, min_items: int = 0) -> None:
+ if not isinstance(value, list) or not all(isinstance(item, str) and item.strip() for item in value):
+ errors.append(f"{path} must be an array of nonempty strings")
+ return
+ if len(value) < min_items:
+ errors.append(f"{path} must include at least {min_items} item")
+
+
+def is_string(value: Any) -> bool:
+ return isinstance(value, str)
+
+
+def is_nonempty_string(value: Any) -> bool:
+ return isinstance(value, str) and bool(value.strip())
+
+
+def is_http_url(value: str) -> bool:
+ parsed = urlparse(value)
+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
+
+
+def is_iso_date(value: str) -> bool:
+ try:
+ date.fromisoformat(value)
+ except ValueError:
+ return False
+ return True
+
+
+def dedupe(errors: list[str]) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for error in errors:
+ if error not in seen:
+ result.append(error)
+ seen.add(error)
+ return result
+
+
+def normalize_text(value: Any) -> str:
+ return " ".join(str(value).split())
+
+
+def normalize_url(value: str) -> str:
+ parsed = urlparse(value.strip())
+ path = parsed.path.rstrip("/") or "/"
+ return parsed._replace(path=path, fragment="").geturl()
+
+
+def normalize_terms(values: list[str]) -> list[str]:
+ terms: list[str] = []
+ seen: set[str] = set()
+ for value in values:
+ cleaned = normalize_text(value)
+ key = cleaned.lower()
+ if cleaned and key not in seen:
+ terms.append(cleaned)
+ seen.add(key)
+ return terms
+
+
+def count_words(value: str) -> int:
+ return len(WORD_RE.findall(value))
+
+
+def normalize_citations(items: list[dict[str, Any]]) -> list[dict[str, str]]:
+ normalized: list[dict[str, str]] = []
+ for item in items:
+ normalized.append(
+ {
+ "title": normalize_text(item["title"]),
+ "url": normalize_url(item["url"]),
+ "published": normalize_text(item.get("published", "")),
+ "retrieved": normalize_text(item["retrieved"]),
+ }
+ )
+ return sorted(normalized, key=lambda item: (item["title"].lower(), item["url"]))
+
+
+def normalize_passage(item: dict[str, Any]) -> dict[str, Any]:
+ text = normalize_text(item["text"])
+ word_count = count_words(text)
+ citations = normalize_citations(item.get("citations", []) or [])
+ return {
+ "id": normalize_text(item["id"]),
+ "heading": normalize_text(item["heading"]),
+ "text": text,
+ "word_count": word_count,
+ "extractable": 12 <= word_count <= 80 and text.endswith((".", "?", "!")),
+ "entities": normalize_terms(item.get("entities", []) or []),
+ "citations": citations,
+ "citation_count": len(citations),
+ }
+
+
+def normalize_geo_audit(data: dict[str, Any], *, source_name: str, raw_bytes: bytes) -> dict[str, Any]:
+ validate_input(data)
+ passages = sorted([normalize_passage(item) for item in data["passages"]], key=lambda item: item["id"])
+ signals = data["page_signals"]
+ all_entities = normalize_terms([entity for passage in passages for entity in passage["entities"]])
+ return {
+ "schema": "claude-blog-brain.ingested-geo-citation-audit.v1",
+ "adapter": "ingest_geo_citation_audit",
+ "input": {
+ "audit_name": normalize_text(data["audit_name"]),
+ "url": normalize_url(data["url"]),
+ "title": normalize_text(data["title"]),
+ "locale": normalize_text(data["locale"]),
+ "target_queries": normalize_terms(data["target_queries"]),
+ "llms_txt_strategy": normalize_text(data.get("llms_txt_strategy", "unknown") or "unknown"),
+ },
+ "provenance": {
+ "input_name": Path(source_name).name,
+ "input_sha256": hashlib.sha256(raw_bytes).hexdigest(),
+ "schema_path": "schemas/geo-citation-audit-input.schema.json",
+ "schema_id": load_schema_id(),
+ "passage_count": len(passages),
+ },
+ "page_signals": {
+ "has_article_schema": bool(signals["has_article_schema"]),
+ "indexable": bool(signals["indexable"]),
+ "preview_allowed": bool(signals["preview_allowed"]),
+ "has_visible_author": bool(signals["has_visible_author"]),
+ "has_modified_date": bool(signals["has_modified_date"]),
+ },
+ "passages": passages,
+ "entities": all_entities,
+ "source_ids": normalize_terms(data.get("source_ids", []) or []),
+ "signals": {
+ "passage_count": len(passages),
+ "extractable_passage_count": sum(1 for passage in passages if passage["extractable"]),
+ "cited_passage_count": sum(1 for passage in passages if passage["citation_count"] > 0),
+ "entity_count": len(all_entities),
+ "target_query_count": len(data["target_queries"]),
+ },
+ }
+
+
+def load_geo_citation_audit(path: str | Path) -> dict[str, Any]:
+ source = Path(path)
+ raw = source.read_bytes()
+ return normalize_geo_audit(read_json(source), source_name=source.name, raw_bytes=raw)
+
+
+def write_json(payload: dict[str, Any], output: str | Path | None = None) -> None:
+ text = json.dumps(clean_structure(payload), indent=2, sort_keys=True) + "\n"
+ if output:
+ Path(output).write_text(text, encoding="utf-8")
+ else:
+ print(text, end="")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Normalize a GEO citation audit input JSON.")
+ parser.add_argument("input")
+ parser.add_argument("-o", "--output", default="")
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable status when writing to a file.")
+ args = parser.parse_args(argv)
+ try:
+ payload = load_geo_citation_audit(args.input)
+ write_json(payload, args.output or None)
+ if args.output and args.json:
+ write_json({"ok": True, "output": str(args.output)}, None)
+ except (OSError, ValidationError) as exc:
+ errors = exc.errors if isinstance(exc, ValidationError) else [clean_output_text(str(exc))]
+ if args.json:
+ write_json({"ok": False, "errors": errors}, None)
+ else:
+ print(clean_output_text("error: " + "; ".join(errors)), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ingest_topic_cluster_input.py b/scripts/ingest_topic_cluster_input.py
new file mode 100644
index 0000000..3605b6a
--- /dev/null
+++ b/scripts/ingest_topic_cluster_input.py
@@ -0,0 +1,353 @@
+#!/usr/bin/env python3
+"""Domain importer: normalize a topic cluster plan input JSON.
+
+The adapter reads ``schemas/topic-cluster-input.schema.json`` shaped data,
+validates the hub, spoke, and existing-link fields used by the cluster pipeline,
+and emits a deterministic JSON record for internal-link matrix synthesis.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlparse
+
+
+REPO = Path(__file__).resolve().parents[1]
+SCHEMA_PATH = REPO / "schemas" / "topic-cluster-input.schema.json"
+LOCALE_RE = re.compile(r"^[a-z]{2,3}(-[A-Z]{2})?$")
+WORD_RE = re.compile(r"[A-Za-z0-9]+")
+ROOT_KEYS = {
+ "cluster_name",
+ "primary_topic",
+ "locale",
+ "audience",
+ "objective",
+ "hub",
+ "spokes",
+ "existing_links",
+ "entity_terms",
+ "source_ids",
+}
+
+
+class ValidationError(ValueError):
+ """Raised when a topic cluster input cannot be normalized."""
+
+ def __init__(self, errors: list[str]) -> None:
+ self.errors = errors
+ super().__init__("; ".join(errors))
+
+
+def clean_output_text(value: str) -> str:
+ cleaned = value.replace("\u2014", "-").replace("\u2013", "-").replace("\u2212", "-")
+ while "--" in cleaned:
+ cleaned = cleaned.replace("--", "-")
+ return cleaned
+
+
+def clean_structure(value: Any) -> Any:
+ if isinstance(value, str):
+ return clean_output_text(value).strip()
+ if isinstance(value, list):
+ return [clean_structure(item) for item in value]
+ if isinstance(value, dict):
+ return {str(key): clean_structure(item) for key, item in value.items()}
+ return value
+
+
+def read_json(path: str | Path) -> dict[str, Any]:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValidationError([f"invalid JSON at line {exc.lineno}, column {exc.colno}"]) from exc
+ if not isinstance(data, dict):
+ raise ValidationError(["input root must be an object"])
+ return clean_structure(data)
+
+
+def load_schema_id() -> str:
+ try:
+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
+ except OSError:
+ return ""
+ if isinstance(schema, dict):
+ return str(schema.get("$id", ""))
+ return ""
+
+
+def validate_input(data: dict[str, Any]) -> None:
+ errors: list[str] = []
+ for key in ("cluster_name", "primary_topic", "locale", "hub", "spokes"):
+ if key not in data:
+ errors.append(f"missing required key: {key}")
+ unexpected = sorted(set(data) - ROOT_KEYS)
+ if unexpected:
+ errors.append("unexpected keys: " + ", ".join(unexpected))
+ for key in ("cluster_name", "primary_topic", "locale", "audience", "objective"):
+ if key in data and not is_string(data.get(key)):
+ errors.append(f"{key} must be a string")
+ if is_string(data.get("locale")) and not LOCALE_RE.match(data["locale"]):
+ errors.append("locale must match language or language-region")
+ validate_hub(data.get("hub"), errors)
+ validate_spokes(data.get("spokes"), errors)
+ validate_existing_links(data.get("existing_links", []), errors)
+ validate_string_list(data.get("entity_terms", []), errors, "entity_terms")
+ validate_string_list(data.get("source_ids", []), errors, "source_ids")
+ if errors:
+ raise ValidationError(dedupe(errors))
+
+
+def validate_hub(value: Any, errors: list[str]) -> None:
+ if not isinstance(value, dict):
+ errors.append("hub must be an object")
+ return
+ unexpected = sorted(set(value) - {"title", "url", "target_keyword"})
+ if unexpected:
+ errors.append("hub unexpected keys: " + ", ".join(unexpected))
+ for key in ("title", "url", "target_keyword"):
+ if not is_nonempty_string(value.get(key)):
+ errors.append(f"hub.{key} must be a nonempty string")
+ if is_nonempty_string(value.get("url")) and not is_http_url(value["url"]):
+ errors.append("hub.url must be an HTTP(S) URL")
+
+
+def validate_spokes(value: Any, errors: list[str]) -> None:
+ if not isinstance(value, list):
+ errors.append("spokes must be an array")
+ return
+ if len(value) < 2:
+ errors.append("spokes must include at least two pages")
+ seen_ids: set[str] = set()
+ for index, item in enumerate(value, start=1):
+ if not isinstance(item, dict):
+ errors.append(f"spokes #{index} must be an object")
+ continue
+ unexpected = sorted(set(item) - {"id", "title", "url", "target_keyword", "intent", "stage", "priority", "source_ids"})
+ if unexpected:
+ errors.append(f"spokes #{index} unexpected keys: " + ", ".join(unexpected))
+ for key in ("id", "title", "url", "target_keyword", "intent"):
+ if not is_nonempty_string(item.get(key)):
+ errors.append(f"spokes #{index}.{key} must be a nonempty string")
+ if is_nonempty_string(item.get("id")):
+ if item["id"] in seen_ids:
+ errors.append(f"spokes #{index}.id must be unique")
+ seen_ids.add(item["id"])
+ if is_nonempty_string(item.get("url")) and not is_http_url(item["url"]):
+ errors.append(f"spokes #{index}.url must be an HTTP(S) URL")
+ if "stage" in item and not is_string(item.get("stage")):
+ errors.append(f"spokes #{index}.stage must be a string")
+ if item.get("priority") not in {"critical", "high", "medium", "low", None}:
+ errors.append(f"spokes #{index}.priority is invalid")
+ validate_string_list(item.get("source_ids", []), errors, f"spokes #{index}.source_ids")
+
+
+def validate_existing_links(value: Any, errors: list[str]) -> None:
+ if not isinstance(value, list):
+ errors.append("existing_links must be an array")
+ return
+ for index, item in enumerate(value, start=1):
+ if not isinstance(item, dict):
+ errors.append(f"existing_links #{index} must be an object")
+ continue
+ unexpected = sorted(set(item) - {"from_url", "to_url", "anchor"})
+ if unexpected:
+ errors.append(f"existing_links #{index} unexpected keys: " + ", ".join(unexpected))
+ for key in ("from_url", "to_url"):
+ if not is_nonempty_string(item.get(key)):
+ errors.append(f"existing_links #{index}.{key} must be a nonempty string")
+ elif not is_http_url(item[key]):
+ errors.append(f"existing_links #{index}.{key} must be an HTTP(S) URL")
+ if "anchor" in item and not is_string(item.get("anchor")):
+ errors.append(f"existing_links #{index}.anchor must be a string")
+
+
+def validate_string_list(value: Any, errors: list[str], path: str) -> None:
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
+ errors.append(f"{path} must be an array of strings")
+
+
+def is_string(value: Any) -> bool:
+ return isinstance(value, str)
+
+
+def is_nonempty_string(value: Any) -> bool:
+ return isinstance(value, str) and bool(value.strip())
+
+
+def is_http_url(value: str) -> bool:
+ parsed = urlparse(value)
+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
+
+
+def dedupe(errors: list[str]) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for error in errors:
+ if error not in seen:
+ result.append(error)
+ seen.add(error)
+ return result
+
+
+def normalize_url(value: str) -> str:
+ parsed = urlparse(value.strip())
+ path = parsed.path.rstrip("/") or "/"
+ return parsed._replace(path=path, fragment="").geturl()
+
+
+def normalize_text(value: Any) -> str:
+ return " ".join(str(value).split())
+
+
+def normalize_terms(values: list[str]) -> list[str]:
+ terms: list[str] = []
+ seen: set[str] = set()
+ for value in values:
+ cleaned = normalize_text(value)
+ key = cleaned.lower()
+ if cleaned and key not in seen:
+ terms.append(cleaned)
+ seen.add(key)
+ return terms
+
+
+def normalize_page(page_id: str, page: dict[str, Any], role: str) -> dict[str, Any]:
+ return {
+ "id": page_id,
+ "role": role,
+ "title": normalize_text(page["title"]),
+ "url": normalize_url(page["url"]),
+ "target_keyword": normalize_text(page["target_keyword"]),
+ "intent": normalize_text(page.get("intent", "")),
+ "stage": normalize_text(page.get("stage", "")),
+ "priority": page.get("priority", "medium") or "medium",
+ "source_ids": normalize_terms(page.get("source_ids", []) or []),
+ }
+
+
+def normalize_links(links: list[dict[str, Any]]) -> list[dict[str, str]]:
+ normalized: list[dict[str, str]] = []
+ seen: set[tuple[str, str, str]] = set()
+ for link in links:
+ item = {
+ "from_url": normalize_url(link["from_url"]),
+ "to_url": normalize_url(link["to_url"]),
+ "anchor": normalize_text(link.get("anchor", "")),
+ }
+ key = (item["from_url"], item["to_url"], item["anchor"].lower())
+ if key not in seen:
+ normalized.append(item)
+ seen.add(key)
+ return sorted(normalized, key=lambda item: (item["from_url"], item["to_url"], item["anchor"].lower()))
+
+
+def duplicate_keywords(pages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ groups: dict[str, list[str]] = {}
+ for page in pages:
+ key = " ".join(token.lower() for token in WORD_RE.findall(page["target_keyword"]))
+ groups.setdefault(key, []).append(page["id"])
+ return [
+ {"target_keyword": key, "page_ids": ids}
+ for key, ids in sorted(groups.items())
+ if key and len(ids) > 1
+ ]
+
+
+def link_signals(hub: dict[str, Any], spokes: list[dict[str, Any]], links: list[dict[str, str]]) -> dict[str, Any]:
+ hub_url = hub["url"]
+ edges = {(link["from_url"], link["to_url"]) for link in links}
+ orphan_spokes = [
+ spoke["id"]
+ for spoke in spokes
+ if (hub_url, spoke["url"]) not in edges and (spoke["url"], hub_url) not in edges
+ ]
+ return {
+ "spoke_count": len(spokes),
+ "existing_link_count": len(links),
+ "hub_outbound_count": sum(1 for link in links if link["from_url"] == hub_url),
+ "hub_inbound_count": sum(1 for link in links if link["to_url"] == hub_url),
+ "orphan_spoke_ids": orphan_spokes,
+ "duplicate_target_keywords": duplicate_keywords([hub, *spokes]),
+ }
+
+
+def normalize_topic_cluster(data: dict[str, Any], *, source_name: str, raw_bytes: bytes) -> dict[str, Any]:
+ validate_input(data)
+ hub = normalize_page("hub", data["hub"], "hub")
+ spokes = sorted(
+ [normalize_page(item["id"], item, "spoke") for item in data["spokes"]],
+ key=lambda item: item["id"],
+ )
+ links = normalize_links(data.get("existing_links", []) or [])
+ entity_terms = normalize_terms(data.get("entity_terms", []) or [])
+ source_ids = normalize_terms(data.get("source_ids", []) or [])
+ for page in spokes:
+ source_ids = normalize_terms([*source_ids, *page.get("source_ids", [])])
+ return {
+ "schema": "claude-blog-brain.ingested-topic-cluster.v1",
+ "adapter": "ingest_topic_cluster_input",
+ "input": {
+ "cluster_name": normalize_text(data["cluster_name"]),
+ "primary_topic": normalize_text(data["primary_topic"]),
+ "locale": normalize_text(data["locale"]),
+ "audience": normalize_text(data.get("audience", "")),
+ "objective": normalize_text(data.get("objective", "")),
+ },
+ "provenance": {
+ "input_name": Path(source_name).name,
+ "input_sha256": hashlib.sha256(raw_bytes).hexdigest(),
+ "schema_path": "schemas/topic-cluster-input.schema.json",
+ "schema_id": load_schema_id(),
+ "page_count": len(spokes) + 1,
+ },
+ "hub": hub,
+ "spokes": spokes,
+ "existing_links": links,
+ "entity_terms": entity_terms,
+ "source_ids": source_ids,
+ "signals": link_signals(hub, spokes, links),
+ }
+
+
+def load_topic_cluster_input(path: str | Path) -> dict[str, Any]:
+ source = Path(path)
+ raw = source.read_bytes()
+ return normalize_topic_cluster(read_json(source), source_name=source.name, raw_bytes=raw)
+
+
+def write_json(payload: dict[str, Any], output: str | Path | None = None) -> None:
+ text = json.dumps(clean_structure(payload), indent=2, sort_keys=True) + "\n"
+ if output:
+ Path(output).write_text(text, encoding="utf-8")
+ else:
+ print(text, end="")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Normalize a topic cluster plan input JSON.")
+ parser.add_argument("input")
+ parser.add_argument("-o", "--output", default="")
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable status when writing to a file.")
+ args = parser.parse_args(argv)
+ try:
+ payload = load_topic_cluster_input(args.input)
+ write_json(payload, args.output or None)
+ if args.output and args.json:
+ write_json({"ok": True, "output": str(args.output)}, None)
+ except (OSError, ValidationError) as exc:
+ errors = exc.errors if isinstance(exc, ValidationError) else [clean_output_text(str(exc))]
+ if args.json:
+ write_json({"ok": False, "errors": errors}, None)
+ else:
+ print(clean_output_text("error: " + "; ".join(errors)), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/render_geo_citation_report.py b/scripts/render_geo_citation_report.py
new file mode 100644
index 0000000..6a6b038
--- /dev/null
+++ b/scripts/render_geo_citation_report.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Domain renderer: turn GEO citation readiness JSON into Markdown.
+
+The report includes readiness metrics, passage-level checks, prioritized
+recommendations, rollback notes, and source citations.
+"""
+from __future__ import annotations
+
+import argparse
+import html
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+from ingest_geo_citation_audit import clean_output_text, clean_structure, write_json
+
+
+def load_plan(path: str | Path) -> dict[str, Any]:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"invalid JSON at line {exc.lineno}, column {exc.colno}") from exc
+ if not isinstance(data, dict):
+ raise ValueError("GEO citation readiness root must be an object")
+ if data.get("schema") != "claude-blog-brain.geo-citation-readiness.v1":
+ raise ValueError("GEO citation readiness schema is not supported")
+ return clean_structure(data)
+
+
+def render_markdown(plan: dict[str, Any]) -> str:
+ input_data = plan.get("input", {})
+ metrics = plan.get("metrics", {})
+ lines: list[str] = [
+ f"# GEO Citation Readiness Report: {text(input_data.get('audit_name', 'Audit'))}",
+ "",
+ f"URL: {text(input_data.get('url', ''))}",
+ f"Title: {text(input_data.get('title', ''))}",
+ f"Locale: {text(input_data.get('locale', ''))}",
+ f"Readiness score: {text(plan.get('readiness_score', 'n/a'))}",
+ "",
+ "## Metrics",
+ "",
+ f"- Extractable passages: {metrics.get('extractable_passage_count', 0)} of {metrics.get('passage_count', 0)}",
+ f"- Cited passages: {metrics.get('cited_passage_count', 0)} of {metrics.get('passage_count', 0)}",
+ f"- Covered query terms: {metrics.get('covered_query_term_count', 0)} of {metrics.get('target_query_term_count', 0)}",
+ f"- Entity count: {metrics.get('entity_count', 0)}",
+ "",
+ "## Readiness Checks",
+ "",
+ "<table>",
+ "<thead><tr><th>Check</th><th>Score</th><th>Status</th><th>Finding</th><th>Sources</th></tr></thead>",
+ "<tbody>",
+ ]
+ for item in plan.get("checks", []):
+ lines.append(
+ "<tr>"
+ f"<td>{html.escape(text(item.get('name', '')))}</td>"
+ f"<td>{html.escape(text(item.get('score', '')))}</td>"
+ f"<td>{html.escape(text(item.get('status', '')))}</td>"
+ f"<td>{html.escape(text(item.get('finding', '')))}</td>"
+ f"<td>{html.escape(format_sources(item.get('source_ids', [])))}</td>"
+ "</tr>"
+ )
+ lines.extend(["</tbody>", "</table>", "", "## Recommendations", ""])
+ for item in plan.get("recommendations", []):
+ lines.append(
+ f"- **{text(item.get('priority', 'medium')).title()}** "
+ f"{text(item.get('recommendation', ''))} "
+ f"Sources: {format_sources(item.get('source_ids', []))}. "
+ f"Rollback: {text(item.get('rollback_note', 'Review if source guidance changes.'))}"
+ )
+ lines.extend(["", "## Source Citations", ""])
+ for source in plan.get("source_citations", []):
+ lines.append(
+ f"- `{text(source.get('id', 'source'))}`: "
+ f"{text(source.get('title', 'Untitled'))}. "
+ f"Published: {text(source.get('published', 'n/a'))}. "
+ f"Retrieved: {text(source.get('retrieved', 'n/a'))}. "
+ f"{text(source.get('url', ''))}"
+ )
+ report = "\n".join(lines).rstrip() + "\n"
+ return assert_clean_output(report)
+
+
+def text(value: Any) -> str:
+ return clean_output_text(str(value))
+
+
+def format_sources(source_ids: list[str]) -> str:
+ if not source_ids:
+ return "none"
+ return ", ".join(f"`{text(source_id)}`" for source_id in source_ids)
+
+
+def assert_clean_output(value: str) -> str:
+ cleaned = clean_output_text(value)
+ if "\u2014" in cleaned or "\u2013" in cleaned or "--" in cleaned:
+ raise ValueError("rendered report contains a disallowed dash sequence")
+ return cleaned
+
+
+def write_markdown(markdown: str, output: str | Path | None) -> None:
+ if output:
+ Path(output).write_text(markdown, encoding="utf-8")
+ else:
+ print(markdown, end="")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Render a GEO citation readiness Markdown report.")
+ parser.add_argument("input")
+ parser.add_argument("-o", "--output", default="")
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable status when writing to a file.")
+ args = parser.parse_args(argv)
+ try:
+ report = render_markdown(load_plan(args.input))
+ write_markdown(report, args.output or None)
+ if args.output and args.json:
+ write_json({"ok": True, "output": str(args.output)}, None)
+ except (OSError, ValueError) as exc:
+ if args.json:
+ write_json({"ok": False, "errors": [clean_output_text(str(exc))]}, None)
+ else:
+ print(clean_output_text(f"error: {exc}"), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/render_topic_cluster_report.py b/scripts/render_topic_cluster_report.py
new file mode 100644
index 0000000..abd0585
--- /dev/null
+++ b/scripts/render_topic_cluster_report.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""Domain renderer: turn a topic cluster plan JSON into Markdown.
+
+The report includes a cluster scorecard, internal-link matrix, prioritized
+recommendations, rollback notes, and source citations.
+"""
+from __future__ import annotations
+
+import argparse
+import html
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+from ingest_topic_cluster_input import clean_output_text, clean_structure, write_json
+
+
+def load_plan(path: str | Path) -> dict[str, Any]:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"invalid JSON at line {exc.lineno}, column {exc.colno}") from exc
+ if not isinstance(data, dict):
+ raise ValueError("topic cluster plan root must be an object")
+ if data.get("schema") != "claude-blog-brain.topic-cluster-plan.v1":
+ raise ValueError("topic cluster plan schema is not supported")
+ return clean_structure(data)
+
+
+def render_markdown(plan: dict[str, Any]) -> str:
+ input_data = plan.get("input", {})
+ lines: list[str] = [
+ f"# Topic Cluster Internal Link Matrix: {text(input_data.get('cluster_name', 'Cluster'))}",
+ "",
+ f"Primary topic: {text(input_data.get('primary_topic', ''))}",
+ f"Locale: {text(input_data.get('locale', ''))}",
+ f"Audience: {text(input_data.get('audience', ''))}",
+ "",
+ "## Cluster Scorecard",
+ "",
+ "<table>",
+ "<thead><tr><th>Check</th><th>Score</th><th>Finding</th><th>Sources</th></tr></thead>",
+ "<tbody>",
+ ]
+ for item in plan.get("cluster_quality", []):
+ lines.append(
+ "<tr>"
+ f"<td>{html.escape(text(item.get('name', '')))}</td>"
+ f"<td>{html.escape(text(item.get('score', '')))}</td>"
+ f"<td>{html.escape(text(item.get('finding', '')))}</td>"
+ f"<td>{html.escape(format_sources(item.get('source_ids', [])))}</td>"
+ "</tr>"
+ )
+ lines.extend(
+ [
+ "</tbody>",
+ "</table>",
+ "",
+ "## Internal Link Matrix",
+ "",
+ "<table>",
+ "<thead><tr><th>From</th><th>To</th><th>Anchor</th><th>Relationship</th><th>Status</th><th>Priority</th><th>Sources</th></tr></thead>",
+ "<tbody>",
+ ]
+ )
+ for row in plan.get("internal_link_matrix", []):
+ lines.append(
+ "<tr>"
+ f"<td>{html.escape(text(row.get('from_title', '')))}</td>"
+ f"<td>{html.escape(text(row.get('to_title', '')))}</td>"
+ f"<td>{html.escape(text(row.get('anchor', '')))}</td>"
+ f"<td>{html.escape(text(row.get('relationship', '')))}</td>"
+ f"<td>{html.escape(text(row.get('status', '')))}</td>"
+ f"<td>{html.escape(text(row.get('priority', '')))}</td>"
+ f"<td>{html.escape(format_sources(row.get('source_ids', [])))}</td>"
+ "</tr>"
+ )
+ lines.extend(["</tbody>", "</table>", "", "## Recommendations", ""])
+ for item in plan.get("recommendations", []):
+ lines.append(
+ f"- **{text(item.get('priority', 'medium')).title()}** "
+ f"{text(item.get('recommendation', ''))} "
+ f"Sources: {format_sources(item.get('source_ids', []))}. "
+ f"Rollback: {text(item.get('rollback_note', 'Review before publishing.'))}"
+ )
+ lines.extend(["", "## Source Citations", ""])
+ for source in plan.get("source_citations", []):
+ lines.append(
+ f"- `{text(source.get('id', 'source'))}`: "
+ f"{text(source.get('title', 'Untitled'))}. "
+ f"Published: {text(source.get('published', 'n/a'))}. "
+ f"Retrieved: {text(source.get('retrieved', 'n/a'))}. "
+ f"{text(source.get('url', ''))}"
+ )
+ report = "\n".join(lines).rstrip() + "\n"
+ return assert_clean_output(report)
+
+
+def text(value: Any) -> str:
+ return clean_output_text(str(value))
+
+
+def format_sources(source_ids: list[str]) -> str:
+ if not source_ids:
+ return "none"
+ return ", ".join(f"`{text(source_id)}`" for source_id in source_ids)
+
+
+def assert_clean_output(value: str) -> str:
+ cleaned = clean_output_text(value)
+ if "\u2014" in cleaned or "\u2013" in cleaned or "--" in cleaned:
+ raise ValueError("rendered report contains a disallowed dash sequence")
+ return cleaned
+
+
+def write_markdown(markdown: str, output: str | Path | None) -> None:
+ if output:
+ Path(output).write_text(markdown, encoding="utf-8")
+ else:
+ print(markdown, end="")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Render a topic cluster internal-link matrix report.")
+ parser.add_argument("input")
+ parser.add_argument("-o", "--output", default="")
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable status when writing to a file.")
+ args = parser.parse_args(argv)
+ try:
+ report = render_markdown(load_plan(args.input))
+ write_markdown(report, args.output or None)
+ if args.output and args.json:
+ write_json({"ok": True, "output": str(args.output)}, None)
+ except (OSError, ValueError) as exc:
+ if args.json:
+ write_json({"ok": False, "errors": [clean_output_text(str(exc))]}, None)
+ else:
+ print(clean_output_text(f"error: {exc}"), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/synthesize_geo_citation_readiness.py b/scripts/synthesize_geo_citation_readiness.py
new file mode 100644
index 0000000..089d682
--- /dev/null
+++ b/scripts/synthesize_geo_citation_readiness.py
@@ -0,0 +1,335 @@
+#!/usr/bin/env python3
+"""Domain synthesis: convert an ingested GEO audit into citation readiness JSON.
+
+The adapter emits deterministic readiness checks, prioritized recommendations,
+and source citations from ``references/source-ledger.json``.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from ingest_geo_citation_audit import ValidationError, clean_output_text, clean_structure, write_json
+
+
+REPO = Path(__file__).resolve().parents[1]
+DEFAULT_LEDGER = REPO / "references" / "source-ledger.json"
+STOPWORDS = {"a", "an", "and", "are", "for", "from", "how", "in", "of", "on", "or", "the", "to", "with"}
+PRIORITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3}
+
+
+class SourceError(ValueError):
+ """Raised when a GEO readiness plan references an unknown source ID."""
+
+
+def load_ingested(path: str | Path) -> dict[str, Any]:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValidationError([f"invalid JSON at line {exc.lineno}, column {exc.colno}"]) from exc
+ if not isinstance(data, dict):
+ raise ValidationError(["ingested GEO audit root must be an object"])
+ cleaned = clean_structure(data)
+ validate_ingested(cleaned)
+ return cleaned
+
+
+def validate_ingested(record: dict[str, Any]) -> None:
+ errors: list[str] = []
+ if record.get("schema") != "claude-blog-brain.ingested-geo-citation-audit.v1":
+ errors.append("ingested GEO audit schema is not supported")
+ for key in ("adapter", "input", "provenance", "page_signals", "passages", "signals"):
+ if key not in record:
+ errors.append(f"ingested GEO audit missing key: {key}")
+ if isinstance(record.get("input"), dict):
+ for key in ("audit_name", "url", "title", "locale"):
+ require_string(record["input"], key, errors, f"input.{key}")
+ if not isinstance(record["input"].get("target_queries"), list):
+ errors.append("input.target_queries must be a list")
+ else:
+ errors.append("input must be an object")
+ if not isinstance(record.get("passages"), list) or not record.get("passages"):
+ errors.append("passages must be a nonempty list")
+ if isinstance(record.get("page_signals"), dict):
+ for key in ("has_article_schema", "indexable", "preview_allowed", "has_visible_author", "has_modified_date"):
+ if not isinstance(record["page_signals"].get(key), bool):
+ errors.append(f"page_signals.{key} must be a boolean")
+ else:
+ errors.append("page_signals must be an object")
+ if errors:
+ raise ValidationError(dedupe(errors))
+
+
+def require_string(data: dict[str, Any], key: str, errors: list[str], path: str) -> None:
+ if not isinstance(data.get(key), str) or not data.get(key, "").strip():
+ errors.append(f"{path} must be a nonempty string")
+
+
+def dedupe(errors: list[str]) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for error in errors:
+ if error not in seen:
+ result.append(error)
+ seen.add(error)
+ return result
+
+
+def load_source_index(path: str | Path = DEFAULT_LEDGER) -> dict[str, dict[str, Any]]:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ sources = data.get("sources", [])
+ if not isinstance(sources, list):
+ raise SourceError("source ledger sources must be a list")
+ return {source["id"]: source for source in sources if isinstance(source, dict) and "id" in source}
+
+
+def synthesize(record: dict[str, Any], *, ledger_path: str | Path = DEFAULT_LEDGER) -> dict[str, Any]:
+ record = clean_structure(record)
+ validate_ingested(record)
+ source_index = load_source_index(ledger_path)
+ metrics = build_metrics(record)
+ checks = build_checks(record, metrics)
+ recommendations = build_recommendations(record, checks)
+ source_ids = collect_source_ids(checks, recommendations)
+ citations = source_citations(source_ids, source_index)
+ plan = {
+ "schema": "claude-blog-brain.geo-citation-readiness.v1",
+ "adapter": "synthesize_geo_citation_readiness",
+ "input": record["input"],
+ "provenance": record["provenance"],
+ "metrics": metrics,
+ "readiness_score": round(sum(item["score"] for item in checks) / len(checks)),
+ "checks": checks,
+ "recommendations": recommendations,
+ "source_citations": citations,
+ }
+ return clean_structure(plan)
+
+
+def build_metrics(record: dict[str, Any]) -> dict[str, Any]:
+ passages = record["passages"]
+ passage_count = max(1, len(passages))
+ extractable = sum(1 for passage in passages if passage.get("extractable"))
+ cited = sum(1 for passage in passages if int(passage.get("citation_count", 0)) > 0)
+ query_terms = [term for query in record["input"].get("target_queries", []) for term in meaningful_terms(query)]
+ body_terms = text_term_set(" ".join(passage.get("text", "") for passage in passages))
+ entity_terms = text_term_set(" ".join(record.get("entities", [])))
+ covered_terms = sorted({term for term in query_terms if term in body_terms or term in entity_terms})
+ return {
+ "passage_count": len(passages),
+ "extractable_passage_count": extractable,
+ "extractable_passage_ratio": round(extractable / passage_count, 2),
+ "cited_passage_count": cited,
+ "cited_passage_ratio": round(cited / passage_count, 2),
+ "target_query_term_count": len(set(query_terms)),
+ "covered_query_term_count": len(covered_terms),
+ "covered_query_terms": covered_terms,
+ "entity_count": len(record.get("entities", [])),
+ }
+
+
+def meaningful_terms(value: str) -> list[str]:
+ return [term for term in re.findall(r"[a-z0-9]+", value.lower()) if len(term) > 2 and term not in STOPWORDS]
+
+
+def text_term_set(value: str) -> set[str]:
+ terms: set[str] = set()
+ for term in meaningful_terms(value):
+ terms.add(term)
+ if len(term) > 3 and term.endswith("s"):
+ terms.add(term[:-1])
+ return terms
+
+
+def build_checks(record: dict[str, Any], metrics: dict[str, Any]) -> list[dict[str, Any]]:
+ signals = record["page_signals"]
+ entity_score = 100 if metrics["target_query_term_count"] and metrics["covered_query_term_count"] >= metrics["target_query_term_count"] else 65
+ crawl_ok = signals["indexable"] and signals["preview_allowed"]
+ return [
+ check(
+ "Passage extractability",
+ round(metrics["extractable_passage_ratio"] * 100),
+ f"{metrics['extractable_passage_count']} of {metrics['passage_count']} passages are compact, answer-shaped, and punctuation-closed.",
+ "Rewrite weak passages as concise answer blocks under descriptive headings.",
+ ["ziptie-aio-source-selection", "g-ai-features"],
+ ),
+ check(
+ "Visible citation support",
+ round(metrics["cited_passage_ratio"] * 100),
+ f"{metrics['cited_passage_count']} of {metrics['passage_count']} passages include visible source citations.",
+ "Attach dated, visible citations to extractable factual claims.",
+ ["ziptie-aio-source-selection", "g-helpful-content"],
+ ),
+ check(
+ "Entity clarity",
+ entity_score,
+ f"{metrics['covered_query_term_count']} of {metrics['target_query_term_count']} target query terms are represented in passages or entity fields.",
+ "Clarify product, topic, and audience entities in headings, answer blocks, and evidence context.",
+ ["ziptie-aio-source-selection", "g-nlp"],
+ ),
+ check(
+ "Schema and crawl eligibility",
+ 100 if signals["has_article_schema"] and crawl_ok else 55,
+ "Article schema, indexability, and preview controls are all ready." if signals["has_article_schema"] and crawl_ok else "Article schema, indexability, or preview controls need review.",
+ "Use standard crawl and preview controls with Article or BlogPosting schema where it matches visible page content.",
+ ["g-ai-features", "g-intro-sd"],
+ ),
+ check(
+ "Measurement readiness",
+ 80 if signals["has_modified_date"] else 60,
+ "Modified date is present for review tracking." if signals["has_modified_date"] else "Modified date is missing from the supplied page signals.",
+ "Monitor AI Overview and AI Mode impressions in Search Console where that reporting is available.",
+ ["g-genai-reports"],
+ ),
+ ]
+
+
+def check(name: str, score: int, finding: str, recommendation_text: str, source_ids: list[str]) -> dict[str, Any]:
+ return {
+ "name": name,
+ "score": max(0, min(100, score)),
+ "status": status_for_score(score),
+ "finding": finding,
+ "recommendation": recommendation_text,
+ "source_ids": source_ids,
+ }
+
+
+def status_for_score(score: int) -> str:
+ if score >= 85:
+ return "pass"
+ if score >= 70:
+ return "watch"
+ if score >= 50:
+ return "revise"
+ return "hold"
+
+
+def build_recommendations(record: dict[str, Any], checks: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ recs: list[dict[str, Any]] = []
+ for item in checks:
+ if item["status"] in {"hold", "revise"}:
+ recs.append(
+ recommendation(
+ "geo-" + slugify(item["name"]),
+ "high" if item["status"] == "hold" else "medium",
+ item["recommendation"],
+ item["source_ids"],
+ )
+ )
+ strategy = record["input"].get("llms_txt_strategy", "unknown")
+ if strategy in {"present", "planned"}:
+ recs.append(
+ recommendation(
+ "geo-llms-txt-caveat",
+ "high",
+ "Do not treat llms.txt as a Google Search, AI Overview, or AI Mode visibility tactic.",
+ ["g-ai-opt-guide"],
+ )
+ )
+ recs.append(
+ recommendation(
+ "geo-separate-ai-mode",
+ "medium",
+ "Track AI Mode separately from classic organic results and AI Overviews because it is a distinct citation surface.",
+ ["blog-aimode", "semrush-ai-mode-comparison"],
+ )
+ )
+ recs.append(
+ recommendation(
+ "geo-no-guarantee",
+ "medium",
+ "Treat citation readiness as evidence hygiene, not as a promise of AI Overview, AI Mode, or assistant citation.",
+ ["g-update-2026-06-05-guidance-on-third-party-seo-tools-services-and-advice", "g-ai-opt-guide"],
+ )
+ )
+ unique: dict[str, dict[str, Any]] = {}
+ for item in recs:
+ unique.setdefault(item["id"], item)
+ return sorted(unique.values(), key=lambda item: (PRIORITY_ORDER[item["priority"]], item["id"]))
+
+
+def recommendation(rec_id: str, priority: str, text: str, source_ids: list[str]) -> dict[str, Any]:
+ return {
+ "id": rec_id,
+ "priority": priority,
+ "recommendation": text,
+ "source_ids": source_ids,
+ "rollback_note": "Revert the recommendation if source guidance changes or the page evidence no longer matches.",
+ }
+
+
+def slugify(value: str) -> str:
+ return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
+
+
+def collect_source_ids(*sections: Any) -> list[str]:
+ found: list[str] = []
+ seen: set[str] = set()
+
+ def visit(value: Any) -> None:
+ if isinstance(value, dict):
+ if isinstance(value.get("source_ids"), list):
+ for source_id in value["source_ids"]:
+ if source_id not in seen:
+ found.append(source_id)
+ seen.add(source_id)
+ for item in value.values():
+ visit(item)
+ elif isinstance(value, list):
+ for item in value:
+ visit(item)
+
+ for section in sections:
+ visit(section)
+ return found
+
+
+def source_citations(source_ids: list[str], source_index: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
+ missing = [source_id for source_id in source_ids if source_id not in source_index]
+ if missing:
+ raise SourceError("unknown source IDs: " + ", ".join(missing))
+ citations: list[dict[str, Any]] = []
+ for source_id in source_ids:
+ source = source_index[source_id]
+ citations.append(
+ {
+ "id": source_id,
+ "title": source.get("title", ""),
+ "url": source.get("url", ""),
+ "published": source.get("published", source.get("last_updated", "")),
+ "retrieved": source.get("retrieved", ""),
+ "confidence": source.get("confidence", ""),
+ }
+ )
+ return citations
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Synthesize a GEO citation readiness JSON report.")
+ parser.add_argument("input")
+ parser.add_argument("-l", "--ledger", default=str(DEFAULT_LEDGER))
+ parser.add_argument("-o", "--output", default="")
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable status when writing to a file.")
+ args = parser.parse_args(argv)
+ try:
+ payload = synthesize(load_ingested(args.input), ledger_path=args.ledger)
+ write_json(payload, args.output or None)
+ if args.output and args.json:
+ write_json({"ok": True, "output": str(args.output)}, None)
+ except (OSError, ValidationError, SourceError, json.JSONDecodeError) as exc:
+ errors = exc.errors if isinstance(exc, ValidationError) else [clean_output_text(str(exc))]
+ if args.json:
+ write_json({"ok": False, "errors": errors}, None)
+ else:
+ print(clean_output_text("error: " + "; ".join(errors)), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/synthesize_topic_cluster.py b/scripts/synthesize_topic_cluster.py
new file mode 100644
index 0000000..a6c7eb1
--- /dev/null
+++ b/scripts/synthesize_topic_cluster.py
@@ -0,0 +1,370 @@
+#!/usr/bin/env python3
+"""Domain synthesis: convert an ingested topic cluster into a link matrix plan.
+
+The adapter emits deterministic JSON with a hub and spoke internal-link matrix,
+cluster quality signals, prioritized recommendations, and source citations from
+``references/source-ledger.json``.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from ingest_topic_cluster_input import ValidationError, clean_output_text, clean_structure, write_json
+
+
+REPO = Path(__file__).resolve().parents[1]
+DEFAULT_LEDGER = REPO / "references" / "source-ledger.json"
+STOPWORDS = {
+ "a",
+ "an",
+ "and",
+ "are",
+ "for",
+ "from",
+ "how",
+ "in",
+ "into",
+ "of",
+ "on",
+ "or",
+ "the",
+ "to",
+ "with",
+}
+PRIORITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3}
+
+
+class SourceError(ValueError):
+ """Raised when a topic cluster plan references an unknown source ID."""
+
+
+def load_ingested(path: str | Path) -> dict[str, Any]:
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValidationError([f"invalid JSON at line {exc.lineno}, column {exc.colno}"]) from exc
+ if not isinstance(data, dict):
+ raise ValidationError(["ingested topic cluster root must be an object"])
+ cleaned = clean_structure(data)
+ validate_ingested(cleaned)
+ return cleaned
+
+
+def validate_ingested(record: dict[str, Any]) -> None:
+ errors: list[str] = []
+ if record.get("schema") != "claude-blog-brain.ingested-topic-cluster.v1":
+ errors.append("ingested topic cluster schema is not supported")
+ for key in ("adapter", "input", "provenance", "hub", "spokes", "existing_links", "signals"):
+ if key not in record:
+ errors.append(f"ingested topic cluster missing key: {key}")
+ if isinstance(record.get("input"), dict):
+ for key in ("cluster_name", "primary_topic", "locale"):
+ require_string(record["input"], key, errors, f"input.{key}")
+ else:
+ errors.append("input must be an object")
+ if isinstance(record.get("hub"), dict):
+ validate_page(record["hub"], errors, "hub")
+ else:
+ errors.append("hub must be an object")
+ if isinstance(record.get("spokes"), list):
+ if len(record["spokes"]) < 2:
+ errors.append("spokes must include at least two pages")
+ for index, spoke in enumerate(record["spokes"], start=1):
+ validate_page(spoke, errors, f"spokes #{index}")
+ else:
+ errors.append("spokes must be a list")
+ if not isinstance(record.get("existing_links"), list):
+ errors.append("existing_links must be a list")
+ if errors:
+ raise ValidationError(dedupe(errors))
+
+
+def validate_page(page: Any, errors: list[str], path: str) -> None:
+ if not isinstance(page, dict):
+ errors.append(f"{path} must be an object")
+ return
+ for key in ("id", "role", "title", "url", "target_keyword"):
+ require_string(page, key, errors, f"{path}.{key}")
+
+
+def require_string(data: dict[str, Any], key: str, errors: list[str], path: str) -> None:
+ if not isinstance(data.get(key), str) or not data.get(key, "").strip():
+ errors.append(f"{path} must be a nonempty string")
+
+
+def dedupe(errors: list[str]) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for error in errors:
+ if error not in seen:
+ result.append(error)
+ seen.add(error)
+ return result
+
+
+def load_source_index(path: str | Path = DEFAULT_LEDGER) -> dict[str, dict[str, Any]]:
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ sources = data.get("sources", [])
+ if not isinstance(sources, list):
+ raise SourceError("source ledger sources must be a list")
+ return {source["id"]: source for source in sources if isinstance(source, dict) and "id" in source}
+
+
+def synthesize(record: dict[str, Any], *, ledger_path: str | Path = DEFAULT_LEDGER) -> dict[str, Any]:
+ record = clean_structure(record)
+ validate_ingested(record)
+ source_index = load_source_index(ledger_path)
+ matrix = build_link_matrix(record)
+ recommendations = build_recommendations(record, matrix)
+ scorecard = build_scorecard(record, matrix)
+ source_ids = collect_source_ids(matrix, recommendations, scorecard)
+ citations = source_citations(source_ids, source_index)
+ plan = {
+ "schema": "claude-blog-brain.topic-cluster-plan.v1",
+ "adapter": "synthesize_topic_cluster",
+ "input": record["input"],
+ "provenance": record["provenance"],
+ "cluster_quality": scorecard,
+ "internal_link_matrix": matrix,
+ "recommendations": recommendations,
+ "source_citations": citations,
+ }
+ return clean_structure(plan)
+
+
+def build_link_matrix(record: dict[str, Any]) -> list[dict[str, Any]]:
+ hub = record["hub"]
+ spokes = record["spokes"]
+ existing = {(link.get("from_url", ""), link.get("to_url", "")) for link in record.get("existing_links", [])}
+ rows: list[dict[str, Any]] = []
+ for spoke in spokes:
+ rows.append(matrix_row(hub, spoke, spoke["target_keyword"], "hub to spoke", (hub["url"], spoke["url"]) in existing))
+ rows.append(matrix_row(spoke, hub, record["input"]["primary_topic"], "spoke to hub", (spoke["url"], hub["url"]) in existing))
+ for source in spokes:
+ for target in spokes:
+ if source["id"] == target["id"]:
+ continue
+ overlap = shared_term_count(source, target)
+ if overlap >= 2:
+ rows.append(
+ matrix_row(
+ source,
+ target,
+ target["target_keyword"],
+ f"spoke support overlap {overlap}",
+ (source["url"], target["url"]) in existing,
+ priority="medium",
+ )
+ )
+ unique: dict[tuple[str, str, str], dict[str, Any]] = {}
+ for row in rows:
+ key = (row["from_url"], row["to_url"], row["relationship"])
+ unique.setdefault(key, row)
+ return sorted(unique.values(), key=lambda item: (item["from_id"], item["to_id"], item["relationship"]))
+
+
+def matrix_row(
+ source: dict[str, Any],
+ target: dict[str, Any],
+ anchor: str,
+ relationship: str,
+ exists: bool,
+ *,
+ priority: str = "high",
+) -> dict[str, Any]:
+ return {
+ "from_id": source["id"],
+ "from_title": source["title"],
+ "from_url": source["url"],
+ "to_id": target["id"],
+ "to_title": target["title"],
+ "to_url": target["url"],
+ "anchor": anchor,
+ "relationship": relationship,
+ "status": "present" if exists else "missing",
+ "priority": "low" if exists else priority,
+ "source_ids": ["dfs-labs", "g-helpful-content"],
+ }
+
+
+def shared_term_count(left: dict[str, Any], right: dict[str, Any]) -> int:
+ left_terms = terms_for_page(left)
+ right_terms = terms_for_page(right)
+ return len(left_terms & right_terms)
+
+
+def terms_for_page(page: dict[str, Any]) -> set[str]:
+ value = " ".join(str(page.get(key, "")) for key in ("title", "target_keyword", "intent", "stage"))
+ return {token for token in re.findall(r"[a-z0-9]+", value.lower()) if len(token) > 2 and token not in STOPWORDS}
+
+
+def build_recommendations(record: dict[str, Any], matrix: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ recs: list[dict[str, Any]] = []
+ missing_hub = [row for row in matrix if row["relationship"] == "hub to spoke" and row["status"] == "missing"]
+ missing_spoke = [row for row in matrix if row["relationship"] == "spoke to hub" and row["status"] == "missing"]
+ if missing_hub:
+ recs.append(
+ recommendation(
+ "cluster-add-hub-to-spoke-links",
+ "high",
+ "Add hub links to every spoke so the cluster page routes readers into each specific intent path.",
+ ["dfs-labs", "g-helpful-content"],
+ )
+ )
+ if missing_spoke:
+ recs.append(
+ recommendation(
+ "cluster-add-spoke-to-hub-links",
+ "high",
+ "Add spoke links back to the hub so each specific article reinforces the primary topic page.",
+ ["dfs-labs", "g-helpful-content"],
+ )
+ )
+ duplicates = record.get("signals", {}).get("duplicate_target_keywords", [])
+ if duplicates:
+ recs.append(
+ recommendation(
+ "cluster-resolve-duplicate-intent",
+ "high",
+ "Separate duplicate target keywords by intent, consolidate overlapping pages, or assign one canonical hub path.",
+ ["dfs-labs", "g-helpful-content"],
+ )
+ )
+ if not record.get("entity_terms"):
+ recs.append(
+ recommendation(
+ "cluster-add-entity-map",
+ "medium",
+ "Add tracked entity terms so the cluster can be reviewed for topical coverage beyond exact keywords.",
+ ["g-nlp", "g-helpful-content"],
+ )
+ )
+ if any(row["status"] == "missing" and row["relationship"].startswith("spoke support") for row in matrix):
+ recs.append(
+ recommendation(
+ "cluster-add-supporting-spoke-links",
+ "medium",
+ "Add supporting links between overlapping spokes when the link helps readers continue the same task.",
+ ["dfs-labs", "g-helpful-content"],
+ )
+ )
+ recs.append(
+ recommendation(
+ "cluster-measure-query-overlap",
+ "medium",
+ "Measure query and page performance by URL before treating the cluster map as validated.",
+ ["g-gsc-api", "dfs-labs"],
+ )
+ )
+ return sorted(recs, key=lambda item: (PRIORITY_ORDER[item["priority"]], item["id"]))
+
+
+def recommendation(rec_id: str, priority: str, text: str, source_ids: list[str]) -> dict[str, Any]:
+ return {
+ "id": rec_id,
+ "priority": priority,
+ "recommendation": text,
+ "source_ids": source_ids,
+ "rollback_note": "Remove or revise the link if it does not help readers continue the task.",
+ }
+
+
+def build_scorecard(record: dict[str, Any], matrix: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ missing = sum(1 for row in matrix if row["status"] == "missing")
+ total = max(1, len(matrix))
+ coverage = round(((total - missing) / total) * 100)
+ orphan_count = len(record.get("signals", {}).get("orphan_spoke_ids", []))
+ duplicate_count = len(record.get("signals", {}).get("duplicate_target_keywords", []))
+ return [
+ {
+ "name": "Internal link coverage",
+ "score": coverage,
+ "finding": f"{total - missing} of {total} recommended links are already present.",
+ "source_ids": ["dfs-labs", "g-helpful-content"],
+ },
+ {
+ "name": "Orphan spoke risk",
+ "score": max(0, 100 - orphan_count * 25),
+ "finding": f"{orphan_count} spokes have no hub relationship in the supplied links.",
+ "source_ids": ["g-helpful-content"],
+ },
+ {
+ "name": "Intent separation",
+ "score": 100 if duplicate_count == 0 else 60,
+ "finding": f"{duplicate_count} duplicate target keyword groups were detected.",
+ "source_ids": ["dfs-labs", "g-helpful-content"],
+ },
+ ]
+
+
+def collect_source_ids(*sections: Any) -> list[str]:
+ found: list[str] = []
+ seen: set[str] = set()
+
+ def visit(value: Any) -> None:
+ if isinstance(value, dict):
+ if isinstance(value.get("source_ids"), list):
+ for source_id in value["source_ids"]:
+ if source_id not in seen:
+ found.append(source_id)
+ seen.add(source_id)
+ for item in value.values():
+ visit(item)
+ elif isinstance(value, list):
+ for item in value:
+ visit(item)
+
+ for section in sections:
+ visit(section)
+ return found
+
+
+def source_citations(source_ids: list[str], source_index: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
+ missing = [source_id for source_id in source_ids if source_id not in source_index]
+ if missing:
+ raise SourceError("unknown source IDs: " + ", ".join(missing))
+ citations: list[dict[str, Any]] = []
+ for source_id in source_ids:
+ source = source_index[source_id]
+ citations.append(
+ {
+ "id": source_id,
+ "title": source.get("title", ""),
+ "url": source.get("url", ""),
+ "published": source.get("published", source.get("last_updated", "")),
+ "retrieved": source.get("retrieved", ""),
+ "confidence": source.get("confidence", ""),
+ }
+ )
+ return citations
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Synthesize a topic cluster internal-link matrix JSON.")
+ parser.add_argument("input")
+ parser.add_argument("-l", "--ledger", default=str(DEFAULT_LEDGER))
+ parser.add_argument("-o", "--output", default="")
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable status when writing to a file.")
+ args = parser.parse_args(argv)
+ try:
+ payload = synthesize(load_ingested(args.input), ledger_path=args.ledger)
+ write_json(payload, args.output or None)
+ if args.output and args.json:
+ write_json({"ok": True, "output": str(args.output)}, None)
+ except (OSError, ValidationError, SourceError, json.JSONDecodeError) as exc:
+ errors = exc.errors if isinstance(exc, ValidationError) else [clean_output_text(str(exc))]
+ if args.json:
+ write_json({"ok": False, "errors": errors}, None)
+ else:
+ print(clean_output_text("error: " + "; ".join(errors)), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/fixtures/sample-geo-citation-audit.json b/tests/fixtures/sample-geo-citation-audit.json
new file mode 100644
index 0000000..652d8b9
--- /dev/null
+++ b/tests/fixtures/sample-geo-citation-audit.json
@@ -0,0 +1,56 @@
+{
+ "audit_name": "AI citation readiness audit",
+ "url": "https://example.com/blog/ai-citation-ready-blog-strategy",
+ "title": "AI Citation Ready Blog Strategy",
+ "locale": "en-US",
+ "target_queries": [
+ "how to make a blog citation ready for AI search",
+ "AI citation ready blog"
+ ],
+ "passages": [
+ {
+ "id": "answer-block",
+ "heading": "What makes a blog citation ready for AI search?",
+ "text": "A citation ready blog page gives readers a direct answer, names the entities involved, and places dated source context close to the claim.",
+ "entities": ["AI search", "source context", "blog page"],
+ "citations": [
+ {
+ "title": "AI features and your website",
+ "url": "https://developers.google.com/search/docs/appearance/ai-features",
+ "published": "2025-12-10",
+ "retrieved": "2026-07-09"
+ }
+ ]
+ },
+ {
+ "id": "source-evidence",
+ "heading": "Where should source evidence appear?",
+ "text": "Editors should place visible source labels near factual claims, especially when the passage may be extracted independently by AI search systems.",
+ "entities": ["source labels", "factual claims", "AI search systems"],
+ "citations": [
+ {
+ "title": "Google AI Overviews source selection",
+ "url": "https://ziptie.dev/blog/google-ai-overviews-source-selection/",
+ "published": "2026-03-25",
+ "retrieved": "2026-07-08"
+ }
+ ]
+ },
+ {
+ "id": "measurement-boundary",
+ "heading": "Can citation readiness guarantee visibility?",
+ "text": "No. Citation readiness improves evidence hygiene and makes passages easier to evaluate, but it does not guarantee AI Overview, AI Mode, ChatGPT, Perplexity, Gemini, or Copilot citation.",
+ "entities": ["AI Overview", "AI Mode", "evidence hygiene"],
+ "citations": []
+ }
+ ],
+ "page_signals": {
+ "has_article_schema": false,
+ "indexable": true,
+ "preview_allowed": true,
+ "has_visible_author": true,
+ "has_modified_date": false
+ },
+ "llms_txt_strategy": "planned",
+ "source_ids": ["g-ai-features", "ziptie-aio-source-selection", "g-ai-opt-guide", "g-genai-reports"]
+}
diff --git a/tests/fixtures/sample-topic-cluster-plan.json b/tests/fixtures/sample-topic-cluster-plan.json
new file mode 100644
index 0000000..0a83453
--- /dev/null
+++ b/tests/fixtures/sample-topic-cluster-plan.json
@@ -0,0 +1,58 @@
+{
+ "cluster_name": "AI citation ready blog cluster",
+ "primary_topic": "AI citation ready blog strategy",
+ "locale": "en-US",
+ "audience": "SEO editors and blog operators",
+ "objective": "Plan a source-cited cluster that helps editors improve AI citation readiness without promising rankings.",
+ "hub": {
+ "title": "AI Citation Ready Blog Strategy",
+ "url": "https://example.com/blog/ai-citation-ready-blog-strategy",
+ "target_keyword": "AI citation ready blog strategy"
+ },
+ "spokes": [
+ {
+ "id": "answer-passages",
+ "title": "How to Write Answer Passages for AI Search",
+ "url": "https://example.com/blog/answer-passages-ai-search",
+ "target_keyword": "AI citation ready answer passages",
+ "intent": "Teach editors to structure self-contained answer blocks",
+ "stage": "optimize",
+ "priority": "high",
+ "source_ids": ["ziptie-aio-source-selection"]
+ },
+ {
+ "id": "source-ledger",
+ "title": "How to Maintain a Blog Source Ledger",
+ "url": "https://example.com/blog/blog-source-ledger",
+ "target_keyword": "blog source ledger",
+ "intent": "Show how to record dated source evidence for claims",
+ "stage": "govern",
+ "priority": "high",
+ "source_ids": ["g-helpful-content"]
+ },
+ {
+ "id": "measurement",
+ "title": "How to Measure AI Citation Visibility",
+ "url": "https://example.com/blog/measure-ai-citation-visibility",
+ "target_keyword": "AI citation measurement",
+ "intent": "Explain AI Overview and AI Mode measurement boundaries",
+ "stage": "measure",
+ "priority": "medium",
+ "source_ids": ["g-genai-reports"]
+ }
+ ],
+ "existing_links": [
+ {
+ "from_url": "https://example.com/blog/ai-citation-ready-blog-strategy",
+ "to_url": "https://example.com/blog/answer-passages-ai-search",
+ "anchor": "AI citation ready answer passages"
+ },
+ {
+ "from_url": "https://example.com/blog/blog-source-ledger",
+ "to_url": "https://example.com/blog/ai-citation-ready-blog-strategy",
+ "anchor": "AI citation ready blog strategy"
+ }
+ ],
+ "entity_terms": ["AI Overviews", "AI Mode", "Search Console", "source ledger"],
+ "source_ids": ["dfs-labs", "g-helpful-content", "g-gsc-api", "g-nlp"]
+}
diff --git a/tests/test_domain_adapters.py b/tests/test_domain_adapters.py
new file mode 100644
index 0000000..a031607
--- /dev/null
+++ b/tests/test_domain_adapters.py
@@ -0,0 +1,190 @@
+"""Subprocess tests for topic cluster and GEO domain adapters."""
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[1]
+PY = sys.executable
+TOPIC_FIXTURE = ROOT / "tests" / "fixtures" / "sample-topic-cluster-plan.json"
+GEO_FIXTURE = ROOT / "tests" / "fixtures" / "sample-geo-citation-audit.json"
+
+
+def run_cli(args: list[str | Path]) -> subprocess.CompletedProcess[str]:
+ return subprocess.run([str(arg) for arg in args], cwd=ROOT, text=True, capture_output=True, check=False)
+
+
+def run_script(script: str, *args: str | Path) -> subprocess.CompletedProcess[str]:
+ return run_cli([PY, f"scripts/{script}", *args])
+
+
+def assert_ok(proc: subprocess.CompletedProcess[str]) -> None:
+ assert proc.returncode == 0, proc.stderr or proc.stdout
+
+
+def assert_error_envelope(proc: subprocess.CompletedProcess[str]) -> dict[str, Any]:
+ assert proc.returncode == 2
+ payload = json.loads(proc.stdout)
+ assert payload["ok"] is False
+ assert payload["errors"]
+ return payload
+
+
+def assert_clean_report(report: str) -> None:
+ assert "\u2014" not in report
+ assert "\u2013" not in report
+ assert "--" not in report
+
+
+def assert_all_sources_cited(plan: dict[str, Any]) -> None:
+ citation_ids = {source["id"] for source in plan["source_citations"]}
+ assert citation_ids
+ for section_name in ("recommendations", "checks", "cluster_quality", "internal_link_matrix"):
+ for item in plan.get(section_name, []):
+ if "source_ids" in item:
+ assert item["source_ids"], item
+ assert set(item["source_ids"]) <= citation_ids
+
+
+def test_topic_cluster_scripts_valid_deterministic_output_and_citations(tmp_path: Path) -> None:
+ first_ingested = tmp_path / "topic-ingested-first.json"
+ second_ingested = tmp_path / "topic-ingested-second.json"
+ assert_ok(run_script("ingest_topic_cluster_input.py", TOPIC_FIXTURE, "-o", first_ingested))
+ assert_ok(run_script("ingest_topic_cluster_input.py", TOPIC_FIXTURE, "-o", second_ingested))
+ assert first_ingested.read_bytes() == second_ingested.read_bytes()
+
+ ingested = json.loads(first_ingested.read_text(encoding="utf-8"))
+ assert ingested["schema"] == "claude-blog-brain.ingested-topic-cluster.v1"
+ assert ingested["adapter"] == "ingest_topic_cluster_input"
+ assert ingested["signals"]["spoke_count"] == 3
+
+ first_plan = tmp_path / "topic-plan-first.json"
+ second_plan = tmp_path / "topic-plan-second.json"
+ assert_ok(run_script("synthesize_topic_cluster.py", first_ingested, "-o", first_plan))
+ assert_ok(run_script("synthesize_topic_cluster.py", first_ingested, "-o", second_plan))
+ assert first_plan.read_bytes() == second_plan.read_bytes()
+
+ plan = json.loads(first_plan.read_text(encoding="utf-8"))
+ assert plan["schema"] == "claude-blog-brain.topic-cluster-plan.v1"
+ assert plan["adapter"] == "synthesize_topic_cluster"
+ assert plan["internal_link_matrix"]
+ assert plan["recommendations"]
+ assert_all_sources_cited(plan)
+
+ first_report = tmp_path / "topic-report-first.md"
+ second_report = tmp_path / "topic-report-second.md"
+ assert_ok(run_script("render_topic_cluster_report.py", first_plan, "-o", first_report))
+ assert_ok(run_script("render_topic_cluster_report.py", first_plan, "-o", second_report))
+ assert first_report.read_bytes() == second_report.read_bytes()
+ report = first_report.read_text(encoding="utf-8")
+ assert report.startswith("# Topic Cluster Internal Link Matrix:")
+ assert "## Internal Link Matrix" in report
+ assert "`dfs-labs`" in report
+ assert "`g-helpful-content`" in report
+ assert_clean_report(report)
+
+
+def test_topic_cluster_malformed_input_json_error_envelope(tmp_path: Path) -> None:
+ bad_input = tmp_path / "bad-topic.json"
+ bad_output = tmp_path / "bad-topic-output.json"
+ bad_input.write_text('{"cluster_name": "Broken"', encoding="utf-8")
+
+ payload = assert_error_envelope(
+ run_script("ingest_topic_cluster_input.py", bad_input, "-o", bad_output, "--json")
+ )
+
+ assert "invalid JSON" in " ".join(str(error) for error in payload["errors"])
+ assert not bad_output.exists()
+
+
+def test_geo_scripts_valid_deterministic_output_and_citations(tmp_path: Path) -> None:
+ first_ingested = tmp_path / "geo-ingested-first.json"
+ second_ingested = tmp_path / "geo-ingested-second.json"
+ assert_ok(run_script("ingest_geo_citation_audit.py", GEO_FIXTURE, "-o", first_ingested))
+ assert_ok(run_script("ingest_geo_citation_audit.py", GEO_FIXTURE, "-o", second_ingested))
+ assert first_ingested.read_bytes() == second_ingested.read_bytes()
+
+ ingested = json.loads(first_ingested.read_text(encoding="utf-8"))
+ assert ingested["schema"] == "claude-blog-brain.ingested-geo-citation-audit.v1"
+ assert ingested["adapter"] == "ingest_geo_citation_audit"
+ assert ingested["signals"]["passage_count"] == 3
+
+ first_plan = tmp_path / "geo-plan-first.json"
+ second_plan = tmp_path / "geo-plan-second.json"
+ assert_ok(run_script("synthesize_geo_citation_readiness.py", first_ingested, "-o", first_plan))
+ assert_ok(run_script("synthesize_geo_citation_readiness.py", first_ingested, "-o", second_plan))
+ assert first_plan.read_bytes() == second_plan.read_bytes()
+
+ plan = json.loads(first_plan.read_text(encoding="utf-8"))
+ assert plan["schema"] == "claude-blog-brain.geo-citation-readiness.v1"
+ assert plan["adapter"] == "synthesize_geo_citation_readiness"
+ assert plan["readiness_score"] < 100
+ assert plan["recommendations"]
+ assert_all_sources_cited(plan)
+
+ first_report = tmp_path / "geo-report-first.md"
+ second_report = tmp_path / "geo-report-second.md"
+ assert_ok(run_script("render_geo_citation_report.py", first_plan, "-o", first_report))
+ assert_ok(run_script("render_geo_citation_report.py", first_plan, "-o", second_report))
+ assert first_report.read_bytes() == second_report.read_bytes()
+ report = first_report.read_text(encoding="utf-8")
+ assert report.startswith("# GEO Citation Readiness Report:")
+ assert "## Readiness Checks" in report
+ assert "`g-ai-opt-guide`" in report
+ assert "`ziptie-aio-source-selection`" in report
+ assert_clean_report(report)
+
+
+def test_geo_malformed_input_json_error_envelope(tmp_path: Path) -> None:
+ bad_input = tmp_path / "bad-geo.json"
+ bad_output = tmp_path / "bad-geo-output.json"
+ bad_input.write_text('{"audit_name": "Broken"', encoding="utf-8")
+
+ payload = assert_error_envelope(
+ run_script("ingest_geo_citation_audit.py", bad_input, "-o", bad_output, "--json")
+ )
+
+ assert "invalid JSON" in " ".join(str(error) for error in payload["errors"])
+ assert not bad_output.exists()
+
+
+def test_package_cli_new_adapter_subcommands_write_domain_outputs(tmp_path: Path) -> None:
+ topic_ingested = tmp_path / "cli-topic-ingested.json"
+ topic_plan = tmp_path / "cli-topic-plan.json"
+ topic_report = tmp_path / "cli-topic-report.md"
+ assert_ok(run_cli([PY, "-m", "claude_blog_brain", "cluster-ingest", TOPIC_FIXTURE, "--output", topic_ingested]))
+ assert_ok(run_cli([PY, "-m", "claude_blog_brain", "cluster-synthesize", topic_ingested, "--output", topic_plan]))
+ assert_ok(run_cli([PY, "-m", "claude_blog_brain", "cluster-report", topic_plan, "--output", topic_report]))
+ assert json.loads(topic_plan.read_text(encoding="utf-8"))["schema"] == "claude-blog-brain.topic-cluster-plan.v1"
+ assert "Topic Cluster Internal Link Matrix" in topic_report.read_text(encoding="utf-8")
+
+ geo_ingested = tmp_path / "cli-geo-ingested.json"
+ geo_plan = tmp_path / "cli-geo-plan.json"
+ geo_report = tmp_path / "cli-geo-report.md"
+ assert_ok(run_cli([PY, "-m", "claude_blog_brain", "geo-ingest", GEO_FIXTURE, "--output", geo_ingested]))
+ assert_ok(run_cli([PY, "-m", "claude_blog_brain", "geo-synthesize", geo_ingested, "--output", geo_plan]))
+ assert_ok(run_cli([PY, "-m", "claude_blog_brain", "geo-report", geo_plan, "--output", geo_report]))
+ assert json.loads(geo_plan.read_text(encoding="utf-8"))["schema"] == "claude-blog-brain.geo-citation-readiness.v1"
+ assert "GEO Citation Readiness Report" in geo_report.read_text(encoding="utf-8")
+
+
+def test_package_cli_new_pipelines_are_domain_specific(tmp_path: Path) -> None:
+ topic_dir = tmp_path / "topic-pipeline"
+ topic_proc = run_cli([PY, "-m", "claude_blog_brain", "cluster-pipeline", "--input", TOPIC_FIXTURE, "--out-dir", topic_dir])
+ assert_ok(topic_proc)
+ topic_report = topic_dir / "topic-cluster-internal-link-matrix.md"
+ assert topic_report.exists()
+ assert "Topic Cluster Internal Link Matrix" in topic_report.read_text(encoding="utf-8")
+ assert str(topic_report) in topic_proc.stdout
+
+ geo_dir = tmp_path / "geo-pipeline"
+ geo_proc = run_cli([PY, "-m", "claude_blog_brain", "geo-pipeline", "--input", GEO_FIXTURE, "--out-dir", geo_dir])
+ assert_ok(geo_proc)
+ geo_report = geo_dir / "geo-citation-readiness-report.md"
+ assert geo_report.exists()
+ assert "GEO Citation Readiness Report" in geo_report.read_text(encoding="utf-8")
+ assert str(geo_report) in geo_proc.stdout
diff --git a/tests/test_wiki_substance.py b/tests/test_wiki_substance.py
new file mode 100644
index 0000000..4aee4c2
--- /dev/null
+++ b/tests/test_wiki_substance.py
@@ -0,0 +1,128 @@
+"""Tests for wiki substance scoring."""
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from audit_brain import check_wiki_substance # noqa: E402
+
+
+def write_source_ledger(root: Path, sources: dict[str, str]) -> None:
+ references = root / "references"
+ references.mkdir(parents=True)
+ payload = {
+ "sources": [
+ {"id": source_id, "url": url}
+ for source_id, url in sorted(sources.items())
+ ]
+ }
+ (references / "source-ledger.json").write_text(json.dumps(payload), encoding="utf-8")
+
+
+def unique_words(seed: str, count: int = 135) -> str:
+ return " ".join(f"{seed}-substance-{index}" for index in range(count))
+
+
+def write_spoke(root: Path, folder: str, title: str, source_url: str, body: str) -> Path:
+ path = root / "wiki" / folder / f"{title}.md"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ f"""---
+type: spoke
+title: "{title}"
+domain: "Fixture Domain"
+status: active
+created: 2026-07-09
+updated: 2026-07-09
+tags: [fixture, active]
+source_urls:
+ - "{source_url}"
+---
+{body}
+""",
+ encoding="utf-8",
+ )
+ return path
+
+
+def clean_body(title: str, seed: str) -> str:
+ return f"""# {title}
+
+## {title} Evidence Table
+
+| Check | Specific action |
+|---|---|
+| {seed} proof | Record dated evidence before the recommendation is used. |
+
+## {title} Operating Notes
+
+{unique_words(seed)}
+"""
+
+
+def cloned_body(title: str) -> str:
+ shared = unique_words("shared-clone", 150)
+ return f"""# {title}
+
+## Shared Evidence Table
+
+| Check | Specific action |
+|---|---|
+| clone proof | Record dated evidence before the recommendation is used. |
+
+## Shared Operating Notes
+
+{shared}
+"""
+
+
+def test_clean_distinct_spoke_set_passes(tmp_path: Path) -> None:
+ sources = {
+ "source-alpha": "https://example.org/source-alpha",
+ "source-beta": "https://example.org/source-beta",
+ "source-gamma": "https://example.org/source-gamma",
+ }
+ write_source_ledger(tmp_path, sources)
+ write_spoke(tmp_path, "concepts", "Alpha Note", sources["source-alpha"], clean_body("Alpha Note", "alpha"))
+ write_spoke(tmp_path, "writing", "Beta Note", sources["source-beta"], clean_body("Beta Note", "beta"))
+ write_spoke(tmp_path, "schema", "Gamma Note", sources["source-gamma"], clean_body("Gamma Note", "gamma"))
+
+ ok, score, notes, critical, details = check_wiki_substance(tmp_path)
+
+ assert ok is True
+ assert score == 100
+ assert notes == []
+ assert critical == []
+ assert details["metrics"]["spoke_count"] == 3
+ assert details["metrics"]["near_duplicate_pairs"] == 0
+ assert details["metrics"]["table_or_procedure_coverage"] == 1.0
+ assert details["metrics"]["specific_citation_coverage"] == 1.0
+ assert details["metrics"]["density_floor"] >= 120
+
+
+def test_near_duplicate_spoke_pair_fails_with_critical(tmp_path: Path) -> None:
+ sources = {
+ "source-alpha": "https://example.org/source-alpha",
+ "source-beta": "https://example.org/source-beta",
+ }
+ write_source_ledger(tmp_path, sources)
+ write_spoke(tmp_path, "concepts", "Clone One", sources["source-alpha"], cloned_body("Clone One"))
+ write_spoke(tmp_path, "writing", "Clone Two", sources["source-alpha"], cloned_body("Clone Two"))
+ write_spoke(tmp_path, "schema", "Distinct Note", sources["source-beta"], clean_body("Distinct Note", "distinct"))
+
+ ok, score, notes, critical, details = check_wiki_substance(tmp_path)
+
+ assert ok is False
+ assert score <= 40
+ assert details["metrics"]["near_duplicate_pairs"] == 1
+ assert critical
+ assert "wiki_substance near_duplicate_pairs=1" in critical[0]
+ pair_paths = details["offenders"]["near_duplicate_pairs"][0]["paths"]
+ assert "wiki/concepts/Clone One.md" in pair_paths
+ assert "wiki/writing/Clone Two.md" in pair_paths
+ assert any("near duplicate spoke pairs: 1" == note for note in notes)
diff --git a/wiki/accounts/_index.md b/wiki/accounts/_index.md
deleted file mode 100644
index 786a9d2..0000000
--- a/wiki/accounts/_index.md
+++ /dev/null
@@ -1,23 +0,0 @@
----
-type: type-hub
-title: "Accounts Index"
-domain: "Blog Content Brain"
-status: active
-created: 2026-07-08
-updated: 2026-07-08
-tags: [type-hub, accounts, active]
-related:
- - "[[index|Index]]"
- - "[[Credential Boundary Rules]]"
-source_urls: []
----
-
-# Accounts Index
-
-Account notes are intentionally sparse in this public vault. Do not store account names, credentials, tokens, emails, or private client data.
-
-## Rules
-
-- Use labels such as `property_a` in exported data.
-- Keep account-specific details outside this vault unless sanitized.
-- Route access decisions through [[Credential Boundary Rules]].
diff --git a/wiki/experiments/_index.md b/wiki/experiments/_index.md
deleted file mode 100644
index aa49cb7..0000000
--- a/wiki/experiments/_index.md
+++ /dev/null
@@ -1,22 +0,0 @@
----
-type: type-hub
-title: "Experiments Index"
-domain: "Blog Content Brain"
-status: active
-created: 2026-07-08
-updated: 2026-07-08
-tags: [type-hub, experiments, active]
-related:
- - "[[index|Index]]"
- - "[[Blog Quality Score]]"
-source_urls: []
----
-
-# Experiments Index
-
-Experiment notes are for controlled tests and should not be presented as general rules.
-
-## Rules
-
-- Define the hypothesis, page set, metric, date window, and rollback note.
-- Keep experiments separate from verified requirements.
diff --git a/wiki/flows/_index.md b/wiki/flows/_index.md
deleted file mode 100644
index 7f9f6c9..0000000
--- a/wiki/flows/_index.md
+++ /dev/null
@@ -1,21 +0,0 @@
----
-type: type-hub
-title: "Flows Index"
-domain: "Blog Content Brain"
-status: active
-created: 2026-07-08
-updated: 2026-07-08
-tags: [type-hub, flows, active]
-related:
- - "[[index|Index]]"
- - "[[Claim Verification Flow]]"
-source_urls: []
----
-
-# Flows Index
-
-Flow notes turn recurring source and review work into operating sequences.
-
-## Notes
-
-- [[Claim Verification Flow]]
diff --git a/wiki/gaps/_index.md b/wiki/gaps/_index.md
deleted file mode 100644
index 6b7a78f..0000000
--- a/wiki/gaps/_index.md
+++ /dev/null
@@ -1,22 +0,0 @@
----
-type: type-hub
-title: "Gaps Index"
-domain: "Blog Content Brain"
-status: active
-created: 2026-07-08
-updated: 2026-07-08
-tags: [type-hub, gaps, active]
-related:
- - "[[index|Index]]"
- - "[[Evidence Gap Register]]"
-source_urls: []
----
-
-# Gaps Index
-
-Gaps are unresolved blockers, stale claims, missing sources, or maturity contradictions.
-
-## Current Route
-
-- [[Evidence Gap Register]]
-- [[Claim To Source Mapping]]
diff --git a/wiki/index.md b/wiki/index.md
index d65e140..c25cadc 100644
--- a/wiki/index.md
+++ b/wiki/index.md
@@ -63,11 +63,10 @@ Start at [[Start Here]], scan [[hot|Hot]], then open the theme or type hub close
## Type hubs
-Root wiki note count after this remediation pass: 257.
+Root wiki note count after this remediation pass: 252.
Folder counts below exclude `_index.md` files.
-- [[wiki/accounts/_index|Accounts]]: 0 notes
- [[wiki/briefs-outlines/_index|Briefs Outlines]]: 12 notes
- [[wiki/clusters/_index|Clusters]]: 12 notes
- [[wiki/concepts/_index|Concepts]]: 13 notes
@@ -77,10 +76,7 @@ Folder counts below exclude `_index.md` files.
- [[wiki/distribution/_index|Distribution]]: 12 notes
- [[wiki/eeat/_index|E-E-A-T]]: 13 notes
- [[wiki/entities/_index|Entities]]: 1 note
-- [[wiki/experiments/_index|Experiments]]: 0 notes
- [[wiki/flow/_index|FLOW]]: 12 notes
-- [[wiki/flows/_index|Flows]]: 1 note
-- [[wiki/gaps/_index|Gaps]]: 0 notes
- [[wiki/geo-aeo/_index|GEO AEO]]: 13 notes
- [[wiki/media/_index|Media]]: 13 notes
- [[wiki/meta/_index|Meta]]: 4 notes
@@ -89,10 +85,9 @@ Folder counts below exclude `_index.md` files.
- [[wiki/personas/_index|Personas]]: 13 notes
- [[wiki/platforms/_index|Platforms]]: 1 note
- [[wiki/quality/_index|Quality]]: 12 notes
-- [[wiki/questions/_index|Questions]]: 0 notes
- [[wiki/rewriting/_index|Rewriting]]: 13 notes
- [[wiki/schema/_index|Schema]]: 13 notes
-- [[wiki/sources/_index|Sources]]: 14 notes
+- [[wiki/sources/_index|Sources]]: 15 notes
- [[wiki/writing/_index|Writing]]: 13 notes
## Working memory
diff --git a/wiki/questions/_index.md b/wiki/questions/_index.md
deleted file mode 100644
index 6310206..0000000
--- a/wiki/questions/_index.md
+++ /dev/null
@@ -1,22 +0,0 @@
----
-type: type-hub
-title: "Questions Index"
-domain: "Blog Content Brain"
-status: active
-created: 2026-07-08
-updated: 2026-07-08
-tags: [type-hub, questions, active]
-related:
- - "[[index|Index]]"
- - "[[Evidence Gap Register]]"
-source_urls: []
----
-
-# Questions Index
-
-Question notes hold unresolved operating questions that are not yet evidence gaps or decisions.
-
-## Routing
-
-- Send missing proof to [[Evidence Gap Register]].
-- Send settled policy choices to [[decisions/_index|Decisions Index]].
diff --git a/wiki/flows/Claim Verification Flow.md b/wiki/sources/Claim Verification Flow.md
similarity index 93%
rename from wiki/flows/Claim Verification Flow.md
rename to wiki/sources/Claim Verification Flow.md
index ed515e6..7b4b4c3 100644
--- a/wiki/flows/Claim Verification Flow.md
+++ b/wiki/sources/Claim Verification Flow.md
@@ -1,12 +1,14 @@
---
-type: flow
+type: spoke
title: "Claim Verification Flow"
domain: "Source Evidence"
status: active
created: 2026-07-08
-updated: 2026-07-08
-tags: [flows, sources, evidence, active]
+updated: 2026-07-09
+tags: [sources, evidence, verification, active]
+confidence: advisory
related:
+ - "[[Research Pack Index]]"
- "[[Claim To Source Mapping]]"
- "[[Source Confidence Labels]]"
- "[[Evidence Gap Register]]"
diff --git a/wiki/sources/_index.md b/wiki/sources/_index.md
index 084c75b..e7aba2f 100644
--- a/wiki/sources/_index.md
+++ b/wiki/sources/_index.md
@@ -9,18 +9,20 @@ tags: [type-hub, sources, active]
related:
- "[[index|Index]]"
- "[[Research Pack Index]]"
+ - "[[Claim Verification Flow]]"
- "[[Claim To Source Mapping]]"
source_urls: []
---
# Sources Index
-Folder index for 14 source-governance notes.
+Folder index for 15 source-governance notes.
## Notes
- [[Canon Notes Map]]
- [[Claim To Source Mapping]]
+- [[Claim Verification Flow]]
- [[Current Requirements Digest]]
- [[Evidence Gap Register]]
- [[Google Source Priority Ladder]]