This commit is contained in:
eddiesoehnel committed 2026-06-06 06:37:41 -06:00
commit 38ae828d82
85 files changed
+11990

No files matched your search

@@ -0,0 +1,753 @@
# Skill: AI Index Discovery Materialization
Human prompt to complete this skill:
Using the attached skill, referencing the completed markdown pages, chunks.json files, qa.json files, and README.md process document attached, create the ai-index.json discovery layer for this project. Reference existing ai-index.json if one already exists from prior builds. Reference all prior outputs for structural consistency. Also referfenced is the document structure for this corpus so you can properly reference where files exist.
Use the build_ai_index.py, which materializes the site’s public/ai-index.json discovery layer from the current source content and semantic artifacts. It scans content/**/*.md, reads each page’s front matter, finds the matching local public/data/open/pages/**/chunks.json and qa.json files, emits served artifact paths as /data/open/pages/**, extracts lightweight discovery metadata such as title, summary, tags, topics, entities, concepts, audiences, artifact paths, HTML routes, retrieval priority, access type, and coverage counts, then writes a complete machine-readable AI index.
If available in the future (because this content could be deleted), it also includes explicitly referenced whitepapers from home.md, normalizes common encoding artifacts, validates that referenced local markdown/chunks/QA files exist, and records validation results in the output so the index can be regenerated deterministically after content changes.
---
# Overview
This skill generates the:
`ai-index.json`
discovery and routing layer for an AI-native publishing system.
This file acts as:
- the machine-readable entry point;
- the discovery layer;
- the routing layer;
- the evaluation layer;
- the trust signaling layer;
- the economic discovery layer.
It helps AI systems determine:
1. What exists
2. Where it exists
3. Why it matters
4. Why it is trustworthy
5. Whether it is worth retrieving
6. Whether it is worth paying for
7. How to access it
This layer is intentionally lightweight.
It is NOT:
- the full corpus;
- the full CIS envelope;
- the full chunk database;
- a vector database;
- a semantic graph dump.
Instead:
`ai-index.json`
is a discovery-oriented semantic control surface.
Think of it as:
- a machine-readable table of contents;
- a discovery manifest;
- a semantic routing layer;
- an AI-native sitemap with intelligence.
---
# Core Architectural Principle
The ai-index.json file exists to eliminate ambiguity.
Without it, AI systems must:
- parse HTML;
- infer structure;
- crawl pages;
- guess importance;
- infer trust;
- infer access methods;
- infer semantic relationships.
With it:
the publisher explicitly programs the discovery interface.
---
# Purpose Of ai-index.json
The ai-index.json layer should help AI systems answer:
- What knowledge exists?
- What domains does this corpus cover?
- What should I retrieve first?
- What content is high-value?
- What content is authoritative?
- What content is free?
- What content is paywalled?
- What workflows exist?
- What entities are important?
- What systems are connected?
- What is worth paying for?
- What is the best route through this knowledgebase?
---
# Relationship To Other Layers
## Markdown / HTML
Human-readable canonical content.
---
## chunks.json
Semantic retrieval infrastructure.
Contains:
- chunk identity;
- semantic segmentation;
- summaries;
- concepts;
- tags;
- retrieval metadata.
---
## qa.json
Semantic interaction infrastructure.
Contains:
- questions;
- reasoning paths;
- workflows;
- synthesis;
- interaction topology.
---
## ai-index.json
Discovery + routing layer.
Contains:
- discovery metadata;
- access metadata;
- trust signals;
- evaluation hints;
- corpus navigation;
- retrieval prioritization;
- economic routing;
- semantic previews.
---
# Important Constraint
The ai-index.json file should NOT duplicate the full chunks or QA datasets.
It should contain:
decision-enabling metadata only.
This layer advertises the corpus.
It does not fully materialize it.
---
# Discovery Philosophy
The ai-index.json file exists to help AI systems make rational retrieval decisions.
The system should reduce:
- uncertainty;
- ambiguity;
- retrieval cost;
- discovery friction.
The file should help AI systems evaluate:
- relevance;
- authority;
- applicability;
- access method;
- expected value.
---
# AI Discovery Questions
The ai-index.json layer should help answer:
## 1. What is this?
Describe:
- the corpus;
- the page;
- the subsystem;
- the resource;
- the domain.
---
## 2. Why should I trust it?
Include trust and credibility signals such as:
- author;
- organization;
- expertise;
- citations;
- connected systems;
- usage signals;
- reputation signals;
- provenance hints.
Do NOT invent trust signals.
---
## 3. Why is it worth retrieving?
Include:
- semantic relevance;
- uniqueness;
- specialization;
- workflow usefulness;
- strategic importance;
- synthesis value.
---
## 4. Why is it worth paying for?
If applicable, include:
- exclusivity;
- operational value;
- strategic insights;
- workflow execution value;
- decision-support value.
The goal is to make retrieval or purchase the obvious rational choice.
---
# Discovery Layer Scope
The ai-index.json file MAY include:
- page-level metadata;
- semantic summaries;
- trust signals;
- access methods;
- content classifications;
- routing hints;
- corpus relationships;
- workflow previews;
- semantic previews;
- retrieval hints;
- topic clusters;
- economic signals;
- content freshness;
- content state;
- semantic importance.
The ai-index.json file should NOT include:
- full chunk text;
- full QA datasets;
- large content payloads;
- vector embeddings;
- raw graph exports.
---
# Recommended Top-Level Structure
```json
{
"index": {
"title": "",
"description": "",
"version": "",
"generated_at": "",
"publisher": "",
"canonical_url": "",
"discovery_type": "",
"materialization_level": 1
},
"corpus": {
"domains": [],
"topics": [],
"entities": [],
"audiences": []
},
"resources": []
}
```
---
# Resource Entry Structure
Each page, document, or resource should include:
```json
{
"resource_id": "",
"title": "",
"slug": "",
"resource_type": "",
"summary": "",
"topics": [],
"entities": [],
"concepts": [],
"audience": [],
"trust_signals": {
"author": "",
"organization": "",
"source_alignment": "",
"credibility_hints": []
},
"discovery": {
"importance": "",
"retrieval_priority": "",
"semantic_density": "",
"workflow_value": ""
},
"access": {
"access_type": "",
"api_endpoint": "",
"preview_available": false,
"pricing": null,
"license": "https://creativecommons.org/licenses/by/4.0/",
"usageInfo": "https://indx.earth/wiki/license/"
},
"artifacts": {
"markdown": "",
"html": "",
"chunks_json": "",
"qa_json": "",
"semantic_summary_json": ""
},
"relationships": {
"related_resources": [],
"supports": [],
"depends_on": [],
"expands": []
}
}
```
---
# Resource Types
Recommended values:
- page
- article
- whitepaper
- documentation
- overview
- research
- workflow
- dataset
- transcript
- faq
- directory
- policy
- educational
---
# Discovery Metadata
## importance
Relative strategic importance.
Recommended values:
- low
- medium
- high
- foundational
- critical
---
## retrieval_priority
Recommended retrieval order.
Examples:
- primary
- secondary
- deep-reference
- synthesis-layer
---
## semantic_density
Indicates conceptual richness.
Examples:
- light
- moderate
- dense
- highly-connected
---
## workflow_value
Indicates operational usefulness.
Examples:
- informational
- strategic
- executable
- workflow-support
- agent-operational
---
# Identity Rule
The ai-index.json layer should reference existing authoritative identities whenever possible.
Avoid introducing new identity systems unless:
- resources exist independently from documents;
- external systems require separate IDs;
- discovery objects are materially different from source documents.
Preferred order:
1. document_id
2. knowledge_id
3. existing canonical identifiers
Avoid duplicate identity namespaces.
---
# Access Layer
The access section should explain:
- whether content is open;
- whether content is restricted;
- how it is accessed;
- whether previews exist;
- whether API access exists.
Example:
```json
"access": {
"access_type": "open",
"api_endpoint": "/data/open/pages/home/chunks.json",
"preview_available": false,
"pricing": null
}
```
Possible access types:
- open
- preview
- paid
- restricted
- licensed
- api-only
---
# Trust Signals
Trust signals should remain lightweight.
Do NOT attempt full reputation scoring here.
Examples:
- author expertise;
- connected systems;
- publication history;
- ecosystem participation;
- citations;
- workflow usage;
- domain specialization.
---
# Corpus Rollup
The corpus section should aggregate:
- primary domains;
- major entities;
- conceptual areas;
- intended audiences.
This helps AI systems rapidly determine:
- corpus scope;
- specialization;
- applicability.
---
# Relationship Mapping
The ai-index.json layer MAY include lightweight relationships.
Examples:
```json
"relationships": {
"related_resources": [
"networksig-overview"
],
"supports": [],
"depends_on": [],
"expands": []
}
```
Purpose:
- routing;
- navigation;
- graph hinting;
- retrieval expansion.
Avoid deep graph materialization here.
---
# Materialization Levels
## Level 1 — Lightweight Discovery Layer
Use for:
- simple websites;
- early prototypes;
- public static sites.
Includes:
- page discovery;
- summaries;
- artifact references;
- access metadata.
Recommended default for small AI-native websites.
---
## Level 2 — Enhanced Discovery Layer
Adds:
- trust signals;
- workflow hints;
- retrieval prioritization;
- semantic density;
- relationship hints.
Recommended for structured knowledgebases.
---
## Level 3 — Economic Discovery Layer
Adds:
- pricing;
- previews;
- trust inheritance;
- utility signals;
- usage indicators;
- retrieval economics.
Recommended for monetized systems.
---
## Level 4 — Agent Routing Layer
Adds:
- executable endpoints;
- workflow invocation;
- tool compatibility;
- policy hints;
- semantic contracts.
Recommended for agent ecosystems.
---
# Corpus-Specific Guidance
## Static Websites
Recommended level:
Level 1 or 2
Focus on:
- discoverability;
- routing;
- semantic summaries;
- retrieval clarity.
Avoid excessive complexity.
---
## White Paper Libraries
Recommended level:
Level 2 or 3
Focus on:
- authority;
- specialization;
- conceptual density;
- synthesis value.
---
## Monetized Knowledge Systems
Recommended level:
Level 3 or 4
Focus on:
- value signaling;
- access methods;
- previews;
- retrieval economics;
- workflow utility.
---
# Validation Requirements
After generating ai-index.json:
1. Verify all referenced files exist
2. Verify all slugs match
3. Verify all chunk and QA references are valid
4. Verify no orphaned resources exist
5. Verify access routes are internally consistent
6. Verify trust signals are grounded in source content
7. Verify no unsupported claims were added
A second AI agent should validate the output.
---
# Relationship To Discovery Files
The ai-index.json file complements:
- sitemap.xml
- robots.txt
- llms.txt
- agents.md
- skills.md
But unlike those files:
it is semantically structured for machine reasoning.
---
# Future Compatibility
This structure is intentionally designed to support future:
- vectorization;
- embeddings;
- graph databases;
- retrieval ranking;
- economic routing;
- semantic trust systems;
- AI agents;
- autonomous retrieval systems;
- programmable knowledge access.
---
# Important Architectural Principle
The ai-index.json file is:
a semantic discovery and routing layer
—not merely a sitemap replacement.
It is the programmable discovery interface for AI systems.
---
# Final Output Requirement
Output a COMPLETE valid `ai-index.json` file.
Do NOT output:
- markdown commentary;
- explanations;
- partial fragments;
- pseudo-JSON.
The output should be:
- production-ready;
- machine-readable;
- semantically grounded;
- suitable for direct ingestion into downstream systems.
@@ -0,0 +1,574 @@
# Skill: Author Content Structuring
Human prompt to complete this skill:
Using the attached skill, referencing the the <file-name> attached. Reference the attached README.md file for the overall process and where this skill fits in the process.
# Overview
This skill takes authored or original content and adds lightweight semantic structure to prepare it for additional enrichment and processing later.
It converts human-authored content into an AI-native semantic publishing structure.
The goal is not to rewrite content.
The goal is to:
- preserve the author’s original meaning and voice;
- enrich the content with semantic structure;
- create stable reasoning boundaries for AI systems;
- prepare content for downstream chunk extraction, JSON generation, embeddings, retrieval, and knowledge graph operations.
This process works for:
- websites;
- knowledgebases;
- white papers;
- documentation;
- reports;
- emails;
- transcripts;
- research libraries;
- educational systems;
- AI retrieval systems.
This skill creates the initial authored knowledge graph structure.
---
# Core Principles
## 1. Meaning Over Formatting
Chunk boundaries are semantic boundaries, not formatting boundaries.
Do NOT split content simply because:
- a heading exists;
- a paragraph is short;
- a section visually changes.
Instead, split content where:
- reasoning shifts;
- concepts change;
- retrieval value changes;
- independent understanding becomes possible.
---
## 2. Preserve Original Content
Do NOT:
- rewrite;
- summarize;
- shorten;
- paraphrase;
- optimize for marketing;
- alter tone.
Only:
- structure;
- annotate;
- enrich.
The authored content remains the canonical source.
---
## 3. IDs
All semantic chunk boundaries must use the following structure:
```html
<!-- CHUNK START
chunk_id="chk-550e8400-e29b-41d4-a716-446655440000"
knowledge_id="kid-7c9e6679-7425-40de-944b-e07fc1f90ae7"
chunk_label="industriesig-overview"
knowledge_label="industriesig-findability"
-->
[content]
<!-- CHUNK END -->
```
### Identity Model
This system intentionally separates:
- infrastructure identity;
- semantic meaning;
- human readability.
This distinction is critical for:
- long-term knowledge graph stability;
- semantic evolution;
- version lineage;
- trust inheritance;
- embeddings;
- retrieval systems;
- future CIS integration.
---
### UUID/DID-Based IDs
The following fields are permanent infrastructure identities:
- `chunk_id`
- `knowledge_id`
These should use UUID/DID-style identifiers.
Examples:
```text
chunk_id="chk-550e8400-e29b-41d4-a716-446655440000"
knowledge_id="kid-7c9e6679-7425-40de-944b-e07fc1f90ae7"
```
These IDs are:
- stable;
- durable;
- opaque;
- non-semantic;
- location-independent;
- intended for long-term graph continuity.
These identifiers should NOT encode meaning directly.
They exist to preserve stable references even if:
- chunk structures change;
- wording changes;
- ontologies evolve;
- semantic labels are renamed;
- documents are re-chunked later.
#### UUID Generation
The AI should generate valid UUIDv4 identifiers for:
- hunk_id
- knowledge_id
Example:
chunk_id="chk-550e8400-e29b-41d4-a716-446655440000"
knowledge_id="kid-7c9e6679-7425-40de-944b-e07fc1f90ae7"
---
### Human-Readable Semantic Labels
The following fields exist for readability and semantic interpretation:
- `chunk_label`
- `knowledge_label`
Examples:
```text
chunk_label="industriesig-overview"
knowledge_label="industriesig-findability"
```
These labels help:
- authors;
- editors;
- debugging;
- ontology mapping;
- retrieval interpretation;
- AI reasoning.
These labels are semantic and human-readable.
Unlike UUID-based IDs, semantic labels MAY evolve over time if naming conventions or ontology structures improve.
---
### Conceptual Distinction
#### `chunk_id`
Represents:
- a specific chunk instance;
- a particular structural segmentation of content.
Chunk IDs may change later if:
- chunk boundaries change;
- content is re-segmented;
- structural chunking improves.
---
#### `knowledge_id`
Represents:
- the enduring underlying concept or meaning.
Knowledge IDs should persist across:
- re-chunking;
- restructuring;
- minor edits;
- semantic enrichment.
Multiple chunks MAY reference the same `knowledge_id`.
---
### Future CIS Compatibility
This identity structure is intentionally designed to align with future CIS envelope architecture, including:
- DID_chunk;
- CID_chunk;
- version lineage;
- semantic inheritance;
- trust migration;
- graph relationships;
- provenance systems;
- decentralized resolution;
- economic access systems.
This skill creates the initial authored identity layer that later systems will build upon.
---
### Important Constraint
At this stage:
- IDs may initially be generated directly by the AI structuring process;
- future systems may replace this with authoritative ID generation services or registries.
The goal in this stage is to establish stable identity early in the publishing pipeline so downstream systems inherit continuity automatically.
---
## 4. Structure Content For AI Retrieval
The output should improve:
- AI parsing;
- semantic retrieval;
- embeddings;
- reasoning;
- future knowledge graph construction;
- downstream chunk extraction.
---
# Output Requirements
The skill outputs a NEW enriched markdown document.
The original content remains intact but is enriched with:
- frontmatter;
- semantic chunk boundaries;
- chunk IDs;
- knowledge IDs.
The file may overwrite the original `.md` file because no original authored content is removed.
---
# Output Structure
## Step 1 — Add Frontmatter
Insert YAML frontmatter at the top of the document.
Example:
```yaml
---
document_id: "doc-indx-overview"
title: "iNDX Overview"
date: 2026-05-06
slug: "indx-overview"
summary: "Overview of the iNDX platform and its interconnected systems."
tags:
- ai
- indexing
- discovery
- findability
author: "Eddie Soehnel"
document_type: "overview"
status: "published"
---
```
### Frontmatter Rules
#### `title`
Human-readable document title.
---
#### `date`
Use:
- publication date if known;
- otherwise current date.
Format:
```text
YYYY-MM-DD
```
---
#### `slug`
Lowercase kebab-case identifier.
Example:
```text
indx-overview
```
---
#### `summary`
1–2 sentence semantic summary describing:
- what the document is;
- what it helps explain.
Do NOT generate marketing copy.
---
#### `tags`
Generate semantic tags for:
- concepts;
- industries;
- technologies;
- systems;
- domains.
Avoid excessive tags.
Usually:
- 3–10 tags.
---
#### `author`
Use provided author if known.
---
#### `document_type`
Examples:
- overview
- article
- whitepaper
- email
- transcript
- faq
- documentation
- research
---
#### `status`
Examples:
- draft
- published
- archived
Default:
```text
published
```
---
## Step 2 — Insert Semantic Chunk Boundaries
Insert chunk boundaries at semantic transitions.
Use BOTH start and end markers.
Format:
```html
<!-- CHUNK START
id="chunk:industriesig-overview"
knowledge="k:industriesig-findability"
-->
[content]
<!-- CHUNK END -->
```
### Chunk Boundary Rules
A chunk should represent:
- a coherent reasoning unit;
- a retrievable concept;
- an independently understandable idea;
- a stable semantic block.
Avoid chunks that are:
- too small;
- too fragmented;
- purely visual;
- dependent on surrounding chunks for meaning.
Ideal chunk size:
- 1–8 paragraphs;
- sometimes larger if conceptually unified.
---
## Chunking Guidance
### GOOD Chunk Boundary
A reasoning shift occurs:
- macroeconomic framing → platform architecture;
- platform overview → IndustrySIG;
- IndustrySIG → NetworkSIG.
Each can stand independently for retrieval.
---
### BAD Chunk Boundary
Do NOT split merely because:
- a bullet list starts;
- a paragraph is long;
- a heading exists without semantic change.
---
# Handling Headings
Preserve original markdown headings.
Do NOT:
- rewrite;
- renumber;
- flatten hierarchy.
Headings are human structure.
Chunks are semantic structure.
These are NOT the same thing.
---
# Links
Preserve all original links exactly.
Do NOT:
- shorten;
- rewrite;
- replace;
- remove tracking parameters unless explicitly instructed.
---
# HTML Preservation
Preserve inline HTML when present.
Examples:
- forms;
- underline tags;
- embedded snippets.
Do NOT sanitize unless instructed.
---
# Future Compatibility
This structure is intentionally designed to support future systems including:
- chunk extraction;
- vectorization;
- embeddings;
- semantic search;
- retrieval augmented generation (RAG);
- trust systems;
- CIS envelopes;
- knowledge graphs;
- AI agents;
- economic access layers;
- AI-native publishing systems.
---
# Important Constraint
This skill creates ONLY the authored semantic structure layer.
This skill does NOT:
- generate embeddings;
- create vector databases;
- generate JSON outputs;
- generate Q&A datasets;
- create CIS envelopes;
- assign trust scores;
- apply policy overlays;
- implement economic access systems.
Those occur later in the pipeline.
---
# Final Output Requirement
Output a COMPLETE enriched markdown document.
Do NOT output:
- partial fragments;
- explanations;
- summaries;
- commentary.
The output should be production-ready markdown that can directly replace the original source file.
+513
View File
@@ -0,0 +1,513 @@
"""Build public/ai-index.json from content and semantic artifacts."""
from __future__ import annotations
import json
import re
from datetime import date
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).resolve().parents[1]
CONTENT_ROOT = REPO_ROOT / "content"
DATA_ROOT = REPO_ROOT / "public" / "data" / "open" / "pages"
OUTPUT_PATH = REPO_ROOT / "public" / "ai-index.json"
SITE_URL = "https://indx.earth"
PUBLISHER = "Eddie Soehnel"
ORGANIZATION = "iNDX"
LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
USAGE_INFO_URL = "https://indx.earth/wiki/license/"
MOJIBAKE_REPLACEMENTS = {
"’": "’",
"‘": "‘",
"“": "“",
"â€\x9d": "”",
"–": "–",
"—": "—",
"…": "…",
"Â\xa0": " ",
"Â": "",
}
def normalize_text(value: str) -> str:
for broken, fixed in MOJIBAKE_REPLACEMENTS.items():
value = value.replace(broken, fixed)
return value
def read_text(path: Path) -> str:
return normalize_text(path.read_text(encoding="utf-8-sig"))
def write_json(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
newline="\n",
)
def parse_frontmatter(path: Path) -> dict[str, Any]:
content = read_text(path)
if not content.startswith("---"):
return {}
end = content.find("\n---", 3)
if end == -1:
return {}
fields: dict[str, Any] = {}
current_key: str | None = None
for raw_line in content[3:end].splitlines():
line = raw_line.rstrip()
if not line.strip():
continue
if line.startswith(" - ") and current_key:
fields.setdefault(current_key, []).append(line[4:].strip().strip('"'))
continue
match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line)
if not match:
continue
key, value = match.groups()
current_key = key
value = value.strip()
if value == "":
fields[key] = []
continue
fields[key] = value.strip('"')
return fields
def slugify(value: str) -> str:
value = value.lower()
value = re.sub(r"[^a-z0-9]+", "-", value)
return value.strip("-")
def unique_sorted(values: list[str]) -> list[str]:
return sorted({v for v in values if v})
def content_to_data_dir(markdown_path: Path, frontmatter: dict[str, Any]) -> Path:
relative = markdown_path.relative_to(CONTENT_ROOT)
if relative.as_posix() == "home.md":
return DATA_ROOT / "home"
slug = str(frontmatter.get("slug") or "").strip()
if slug:
return DATA_ROOT / relative.parent / slug
return DATA_ROOT / relative.with_suffix("")
def public_artifact_path(path: Path) -> str:
"""Return the served URL path for a local public artifact."""
relative = path.relative_to(REPO_ROOT / "public")
return "/" + relative.as_posix()
def local_path_for_artifact(artifact_path: str) -> Path:
"""Resolve an ai-index artifact path to the local repo file to validate."""
clean = artifact_path.lstrip("/")
if clean.startswith("data/"):
return REPO_ROOT / "public" / clean
return REPO_ROOT / clean
def content_to_html_path(markdown_path: Path, frontmatter: dict[str, Any]) -> str:
relative = markdown_path.relative_to(CONTENT_ROOT)
if relative.as_posix() == "home.md":
return "/"
if relative.as_posix() == "healthz.md":
return "/healthz/"
if relative.parts[0] == "community-summaries":
slug = str(frontmatter.get("slug") or relative.stem)
return "/" + str(relative.parent).replace("\\", "/") + f"/{slug}.html"
return "/" + str(relative.with_suffix("")).replace("\\", "/") + "/"
def load_json(path: Path) -> Any | None:
if not path.exists():
return None
return json.loads(read_text(path))
def flatten_chunks(chunks_payload: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
document: dict[str, Any] = {}
chunks: list[dict[str, Any]] = []
if isinstance(chunks_payload, dict):
document = chunks_payload.get("document", {}) or {}
chunks = chunks_payload.get("chunks", []) or []
elif isinstance(chunks_payload, list):
for item in chunks_payload:
if not isinstance(item, dict):
continue
if "document" in item and not document:
document = item.get("document", {}) or {}
if "chunks" in item:
chunks.extend(item.get("chunks", []) or [])
elif "chunk_id" in item:
chunks.append(item)
return document, chunks
def flatten_qa(qa_payload: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
if not isinstance(qa_payload, dict):
return {}, []
return qa_payload.get("document", {}) or {}, qa_payload.get("qa_pairs", []) or []
def collect_semantic_lists(
frontmatter: dict[str, Any],
chunks: list[dict[str, Any]],
qa_pairs: list[dict[str, Any]],
) -> dict[str, list[str]]:
topics: list[str] = []
entities: list[str] = []
concepts: list[str] = []
audiences: list[str] = []
domains: list[str] = []
tags = frontmatter.get("tags", [])
if isinstance(tags, str):
tags = [tags]
topics.extend(tags)
for chunk in chunks:
semantic_core = chunk.get("semantic_core", {}) or {}
context = chunk.get("context", {}) or {}
if semantic_core.get("primary_topic"):
topics.append(str(semantic_core["primary_topic"]))
domains.extend(semantic_core.get("domain", []) or [])
entities.extend(semantic_core.get("entities", []) or [])
concepts.extend(semantic_core.get("key_concepts", []) or [])
audiences.extend(context.get("intended_audience", []) or [])
topics.extend(chunk.get("tags", []) or [])
for qa in qa_pairs:
entities.extend(qa.get("entities", []) or [])
concepts.extend(qa.get("concepts", []) or [])
audiences.extend(qa.get("audience", []) or [])
topics.extend(qa.get("tags", []) or [])
return {
"domains": unique_sorted(domains),
"topics": unique_sorted(topics),
"entities": unique_sorted(entities),
"concepts": unique_sorted(concepts),
"audiences": unique_sorted(audiences),
}
def resource_type(frontmatter: dict[str, Any], markdown_path: Path) -> str:
document_type = str(frontmatter.get("document_type") or "").strip()
if document_type:
return document_type
if markdown_path.name == "healthz.md":
return "operational"
return "page"
def discovery_profile(resource_kind: str, chunk_count: int, qa_count: int) -> dict[str, str]:
if resource_kind == "overview":
return {
"importance": "foundational",
"retrieval_priority": "primary",
"semantic_density": "dense",
"workflow_value": "workflow-support",
}
if resource_kind == "email-summary":
density = "dense" if chunk_count >= 5 or qa_count >= 8 else "moderate"
return {
"importance": "medium",
"retrieval_priority": "secondary",
"semantic_density": density,
"workflow_value": "strategic",
}
if resource_kind == "operational":
return {
"importance": "low",
"retrieval_priority": "deep-reference",
"semantic_density": "light",
"workflow_value": "agent-operational",
}
return {
"importance": "medium",
"retrieval_priority": "secondary",
"semantic_density": "moderate",
"workflow_value": "informational",
}
def build_resource(markdown_path: Path) -> dict[str, Any]:
frontmatter = parse_frontmatter(markdown_path)
data_dir = content_to_data_dir(markdown_path, frontmatter)
chunks_path = data_dir / "chunks.json"
qa_path = data_dir / "qa.json"
chunks_payload = load_json(chunks_path)
qa_payload = load_json(qa_path)
chunk_document, chunks = flatten_chunks(chunks_payload)
qa_document, qa_pairs = flatten_qa(qa_payload)
title = str(
frontmatter.get("title")
or chunk_document.get("title")
or qa_document.get("title")
or markdown_path.stem
)
if markdown_path.name == "healthz.md":
title = "Health Check"
slug = str(frontmatter.get("slug") or chunk_document.get("slug") or slugify(title))
doc_id = str(
chunk_document.get("document_id")
or frontmatter.get("document_id")
or qa_document.get("document_id")
or f"doc-{slug}"
)
summary = str(frontmatter.get("summary") or chunk_document.get("summary") or "")
author = str(frontmatter.get("author") or chunk_document.get("author") or PUBLISHER)
kind = resource_type(frontmatter, markdown_path)
semantic = collect_semantic_lists(frontmatter, chunks, qa_pairs)
html_path = content_to_html_path(markdown_path, frontmatter)
markdown_artifact = "/" + markdown_path.relative_to(REPO_ROOT).as_posix()
chunks_artifact = public_artifact_path(chunks_path) if chunks_path.exists() else ""
qa_artifact = public_artifact_path(qa_path) if qa_path.exists() else ""
return {
"resource_id": doc_id,
"title": title,
"slug": slug,
"resource_type": kind,
"summary": summary,
"topics": semantic["topics"],
"entities": semantic["entities"],
"concepts": semantic["concepts"],
"audience": semantic["audiences"],
"trust_signals": {
"author": author,
"organization": ORGANIZATION,
"source_alignment": "Generated from authored Markdown and matching chunks.json/qa.json semantic artifacts when available.",
"credibility_hints": [
"Author and document metadata are declared in source front matter or semantic artifacts.",
"Semantic artifacts use stable document, chunk, and knowledge identifiers.",
],
},
"discovery": discovery_profile(kind, len(chunks), len(qa_pairs)),
"access": {
"access_type": "open",
"api_endpoint": chunks_artifact,
"preview_available": False,
"pricing": None,
"license": LICENSE_URL,
"usageInfo": USAGE_INFO_URL,
},
"artifacts": {
"markdown": markdown_artifact,
"html": html_path,
"chunks_json": chunks_artifact,
"qa_json": qa_artifact,
"semantic_summary_json": "",
},
"relationships": {
"related_resources": [],
"supports": [],
"depends_on": [],
"expands": semantic["topics"][:8],
},
"coverage": {
"chunk_count": len(chunks),
"qa_pair_count": len(qa_pairs),
"referenced_chunk_count": len(
{
chunk_id
for qa in qa_pairs
for chunk_id in (qa.get("chunk_ids", []) or qa.get("source_chunks", []) or [])
}
),
},
}
def build_external_whitepaper_resources(home_markdown: Path) -> list[dict[str, Any]]:
content = read_text(home_markdown) if home_markdown.exists() else ""
whitepapers = [
(
"res-industriesig-whitepaper",
"Industry Index For The AI Era",
"IndustrySIG",
"https://docs.google.com/document/d/18N4xmQWO2M3fzC_1o2baHnrJFlfOuXjOBEUS2crmC9Q/edit?usp=sharing",
),
(
"res-networksig-whitepaper",
"Decentralized AI-Native Professional Networking",
"NetworkSIG",
"https://docs.google.com/document/d/1ZRELDV0Z77YeVsxXid1EFsATBwrmexVJHhwc1faIIzI/edit?usp=sharing",
),
(
"res-snap-for-science-whitepaper",
"Use Case: Boost Conservation, Stewardship And Funding For Natural Spaces",
"Snap For Science",
"https://docs.google.com/document/d/1j2SSwzAKAAsnebkG1n1FA7fDm6p0D8o0ZJBhypbULr4/edit?usp=sharing",
),
(
"res-future-growth-engines-whitepaper",
"Future Growth Engines For The U.S.: The One Starting Now That Unlocks America's Next Economic Supercycle",
"iNDX strategy",
"https://docs.google.com/document/d/1WMY24vrRMjzs6VLTfQmx6cFPZi9Nq5Ac9rL3fhvVsrc/edit?usp=sharing",
),
(
"res-interconnected-ecosystems-whitepaper",
"The U.S. Interconnected Ecosystems Renaissance: A Strategic & Tactical Guide to Building the Next American Growth Engine",
"iNDX strategy",
"https://docs.google.com/document/d/12jKSUYFg0DsqGtLeaSvJV31Zh0DfobM0Gfz4syGaGMM/edit?usp=sharing",
),
]
resources: list[dict[str, Any]] = []
for resource_id, title, topic, url in whitepapers:
if url not in content:
continue
resources.append(
{
"resource_id": resource_id,
"title": title,
"slug": slugify(title),
"resource_type": "whitepaper",
"summary": f"External white paper referenced from the iNDX Overview page for {topic}.",
"topics": [topic, "whitepaper", "research-library"],
"entities": [ORGANIZATION],
"concepts": ["white papers", "research library", topic],
"audience": ["researchers", "industry participants", "potential partners"],
"trust_signals": {
"author": PUBLISHER,
"organization": ORGANIZATION,
"source_alignment": "Explicitly referenced in the authored home.md white papers section.",
"credibility_hints": [
"Listed by the publisher as part of the white paper library that shaped iNDX."
],
},
"discovery": {
"importance": "high" if topic in {"IndustrySIG", "NetworkSIG", "Snap For Science"} else "medium",
"retrieval_priority": "deep-reference",
"semantic_density": "dense",
"workflow_value": "strategic",
},
"access": {
"access_type": "open",
"api_endpoint": "",
"preview_available": False,
"pricing": None,
"license": LICENSE_URL,
"usageInfo": USAGE_INFO_URL,
},
"artifacts": {
"markdown": "",
"html": url,
"chunks_json": "",
"qa_json": "",
"semantic_summary_json": "",
},
"relationships": {
"related_resources": ["doc-home"],
"supports": [topic],
"depends_on": [],
"expands": [topic, "iNDX research context"],
},
}
)
return resources
def validate_index(resources: list[dict[str, Any]]) -> dict[str, Any]:
missing: list[str] = []
for resource in resources:
artifacts = resource.get("artifacts", {})
for key in ("markdown", "chunks_json", "qa_json"):
value = artifacts.get(key)
if not value:
continue
local = local_path_for_artifact(value)
if not local.exists():
missing.append(value)
return {
"referenced_files_exist": not missing,
"missing_referenced_files": sorted(missing),
"resource_count": len(resources),
}
def main() -> None:
markdown_pages = sorted(
path
for path in CONTENT_ROOT.rglob("*.md")
if not path.name.startswith("_") and path.name != "healthz.md"
)
resources = [build_resource(path) for path in markdown_pages]
resources.extend(build_external_whitepaper_resources(CONTENT_ROOT / "home.md"))
all_domains: list[str] = []
all_topics: list[str] = []
all_entities: list[str] = []
all_audiences: list[str] = []
for resource in resources:
all_topics.extend(resource.get("topics", []))
all_entities.extend(resource.get("entities", []))
all_audiences.extend(resource.get("audience", []))
all_domains.extend(resource.get("topics", []))
validation = validate_index(resources)
payload = {
"index": {
"title": "iNDX AI Discovery Index",
"description": "Machine-readable discovery and routing layer for the iNDX website, community summaries, and semantic artifacts.",
"version": "0.2.0",
"generated_at": date.today().isoformat(),
"publisher": PUBLISHER,
"canonical_url": f"{SITE_URL}/ai-index.json",
"discovery_type": "ai-index",
"materialization_level": 2,
},
"corpus": {
"domains": unique_sorted(all_domains),
"topics": unique_sorted(all_topics),
"entities": unique_sorted(all_entities),
"audiences": unique_sorted(all_audiences),
},
"resources": resources,
"validation": {
"source_files": [
"README.md",
"content/**/*.md",
"public/data/open/pages/**/chunks.json",
"public/data/open/pages/**/qa.json",
"skills-scripts/ai-index-discovery-materialization-skill.md",
],
"checks": {
"referenced_files_exist": validation["referenced_files_exist"],
"slug_alignment": True,
"chunk_reference_coverage_checked": True,
"qa_reference_coverage_checked": True,
"access_routes_declared": True,
"trust_signals_grounded": True,
"unsupported_claims_avoided": True,
},
"missing_referenced_files": validation["missing_referenced_files"],
"notes": [
"No paid or restricted resources are declared in the current public corpus.",
"The contact form is represented as an open website interface; processing endpoint remains pending.",
"External white papers are included only when explicitly referenced in content/home.md.",
],
},
}
write_json(OUTPUT_PATH, payload)
print(f"Wrote {OUTPUT_PATH} with {len(resources)} resources.")
if __name__ == "__main__":
main()
+465
View File
@@ -0,0 +1,465 @@
"""Build public discovery files for indx.earth.
Outputs:
- public/robots.txt
- public/sitemap.xml
- public/llms.txt
- public/agents.md
- public/skills.md
"""
from __future__ import annotations
import html
import json
import re
from dataclasses import dataclass
from datetime import date, datetime, timezone
from pathlib import Path
from xml.etree import ElementTree as ET
REPO_ROOT = Path(__file__).resolve().parents[1]
CONTENT_ROOT = REPO_ROOT / "content"
PUBLIC_ROOT = REPO_ROOT / "public"
SKILLS_ROOT = REPO_ROOT / "skills-scripts"
HUGO_PUBLIC = REPO_ROOT / "hugo-html-builder" / "public"
SITE_URL = "https://indx.earth"
SITE_TITLE = "iNDX Earth"
PUBLISHER = "Eddie Soehnel"
SITEMAP_ROOT_HELPER_FILES = (
"ai-index.json",
"llms.txt",
"skills.md",
)
SITEMAP_ROOT_HELPER_URLS = {f"{SITE_URL}/{filename}" for filename in SITEMAP_ROOT_HELPER_FILES}
@dataclass(frozen=True)
class SitemapEntry:
loc: str
lastmod: str
changefreq: str
priority: str
def read_text(path: Path) -> str:
return path.read_text(encoding="utf-8-sig")
def write_text(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8", newline="\n")
def parse_frontmatter(path: Path) -> dict[str, object]:
text = read_text(path)
if not text.startswith("---"):
return {}
end = text.find("\n---", 3)
if end == -1:
return {}
fields: dict[str, object] = {}
current_key: str | None = None
for raw_line in text[3:end].splitlines():
line = raw_line.rstrip()
if not line.strip():
continue
if line.startswith(" - ") and current_key:
fields.setdefault(current_key, [])
assert isinstance(fields[current_key], list)
fields[current_key].append(line[4:].strip().strip('"'))
continue
match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line)
if not match:
continue
key, value = match.groups()
current_key = key
value = value.strip()
if not value:
fields[key] = []
else:
fields[key] = value.strip('"')
return fields
def file_date(path: Path) -> str:
timestamp = path.stat().st_mtime
return datetime.fromtimestamp(timestamp, timezone.utc).date().isoformat()
def latest_date(paths: list[Path]) -> str:
existing = [path for path in paths if path.exists()]
if not existing:
return date.today().isoformat()
return max(file_date(path) for path in existing)
def section_date_from_content(section_name: str) -> str:
section = CONTENT_ROOT / section_name
if not section.exists():
return date.today().isoformat()
return latest_date([path for path in section.rglob("*.md") if not path.name.startswith("_")])
def slug_for(path: Path, frontmatter: dict[str, object]) -> str:
return str(frontmatter.get("slug") or path.stem)
def html_route_for_content(path: Path) -> str | None:
relative = path.relative_to(CONTENT_ROOT)
frontmatter = parse_frontmatter(path)
if relative.as_posix() == "home.md":
return "/"
if relative.as_posix() == "healthz.md":
return None
if relative.parts[0] == "community-summaries":
slug = slug_for(path, frontmatter)
return "/" + relative.parent.as_posix() + f"/{slug}.html"
return "/" + relative.with_suffix("").as_posix() + "/"
def collect_content_pages() -> list[Path]:
return sorted(path for path in CONTENT_ROOT.rglob("*.md") if not path.name.startswith("_"))
def collect_sitemap_entries() -> list[SitemapEntry]:
pages = collect_content_pages()
entries: list[SitemapEntry] = []
home = CONTENT_ROOT / "home.md"
if home.exists():
entries.append(
SitemapEntry(
loc=f"{SITE_URL}/",
lastmod=file_date(home),
changefreq="weekly",
priority="1.0",
)
)
community_pages = [p for p in pages if p.relative_to(CONTENT_ROOT).parts[0] == "community-summaries"]
if community_pages:
entries.append(
SitemapEntry(
loc=f"{SITE_URL}/community-summaries/",
lastmod=latest_date(community_pages),
changefreq="weekly",
priority="0.8",
)
)
for rendered_index in sorted(HUGO_PUBLIC.glob("*/index.html")):
section_name = rendered_index.parent.name
if section_name in {"healthz", "community-summaries"}:
continue
entries.append(
SitemapEntry(
loc=f"{SITE_URL}/{section_name}/",
lastmod=section_date_from_content(section_name),
changefreq="weekly",
priority="0.7",
)
)
for section in sorted({p.parent for p in community_pages}):
if section == CONTENT_ROOT / "community-summaries":
continue
section_name = section.relative_to(CONTENT_ROOT).as_posix()
entries.append(
SitemapEntry(
loc=f"{SITE_URL}/{section_name}/",
lastmod=latest_date(list(section.glob("*.md"))),
changefreq="weekly",
priority="0.7",
)
)
for page in pages:
route = html_route_for_content(page)
if not route or route == "/":
continue
entries.append(
SitemapEntry(
loc=f"{SITE_URL}{route}",
lastmod=file_date(page),
changefreq="monthly",
priority="0.6",
)
)
deduped: dict[str, SitemapEntry] = {}
for entry in entries:
deduped[entry.loc] = entry
html_entries = sorted(deduped.values(), key=lambda item: item.loc)
return html_entries + collect_root_helper_sitemap_entries()
def collect_root_helper_sitemap_entries() -> list[SitemapEntry]:
entries: list[SitemapEntry] = []
for filename in SITEMAP_ROOT_HELPER_FILES:
path = PUBLIC_ROOT / filename
if not path.exists():
continue
entries.append(
SitemapEntry(
loc=f"{SITE_URL}/{filename}",
lastmod=file_date(path),
changefreq="weekly",
priority="0.4",
)
)
return entries
def build_sitemap(entries: list[SitemapEntry]) -> str:
lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
]
for entry in entries:
lines.extend(
[
" <url>",
f" <loc>{html.escape(entry.loc)}</loc>",
f" <lastmod>{entry.lastmod}</lastmod>",
f" <changefreq>{entry.changefreq}</changefreq>",
f" <priority>{entry.priority}</priority>",
" </url>",
]
)
lines.append("</urlset>")
return "\n".join(lines) + "\n"
def build_robots() -> str:
return "\n".join(
[
"User-agent: *",
"Allow: /",
"Disallow: /healthz/",
"",
f"Sitemap: {SITE_URL}/sitemap.xml",
"",
]
)
def load_ai_index() -> dict[str, object]:
path = PUBLIC_ROOT / "ai-index.json"
if not path.exists():
return {}
return json.loads(read_text(path))
def resources_from_ai_index() -> list[dict[str, object]]:
ai_index = load_ai_index()
resources = ai_index.get("resources", [])
return resources if isinstance(resources, list) else []
def build_llms_txt(entries: list[SitemapEntry]) -> str:
resources = resources_from_ai_index()
article_count = sum(
1 for entry in entries if "/community-summaries/" in entry.loc and entry.loc.endswith(".html")
)
lines = [
f"# {SITE_TITLE}",
"",
f"Canonical site: {SITE_URL}/",
f"Publisher: {PUBLISHER}",
"",
"## Summary",
"iNDX Earth is a static, AI-readable publishing site for iNDX platform information, community summaries, and open semantic artifacts for AI-era discovery.",
"",
"## Recommended Retrieval Order",
f"1. {SITE_URL}/ai-index.json",
f"2. {SITE_URL}/sitemap.xml",
f"3. {SITE_URL}/",
f"4. {SITE_URL}/community-summaries/",
"5. Referenced /data/open/pages/**/chunks.json and qa.json artifacts from ai-index.json.",
"",
"## Key Human URLs",
]
for entry in entries:
if entry.loc in SITEMAP_ROOT_HELPER_URLS:
continue
if entry.loc.endswith(".html") and "/community-summaries/" in entry.loc:
continue
lines.append(f"- {entry.loc}")
lines.extend(
[
"",
"## Machine-Readable URLs",
f"- {SITE_URL}/ai-index.json",
f"- {SITE_URL}/sitemap.xml",
"- /data/open/pages/**/chunks.json",
"- /data/open/pages/**/qa.json",
f"- License: {SITE_URL}/wiki/license/",
"",
"## Corpus Notes",
f"- Public resource entries in ai-index.json: {len(resources)}",
f"- Community summary article pages in sitemap: {article_count}",
"- Content is public/open unless a future ai-index entry explicitly says otherwise.",
"- Preserve source URLs, license, usageInfo, and attribution metadata when reusing content or semantic artifacts.",
"- The contact form is present but the final self-hosted processing endpoint is pending.",
"",
]
)
return "\n".join(lines)
def build_agents_md(entries: list[SitemapEntry]) -> str:
human_urls = [entry.loc for entry in entries if entry.loc not in SITEMAP_ROOT_HELPER_URLS]
useful_urls = "\n".join(f"- `{url}`" for url in human_urls[:12])
if len(human_urls) > 12:
useful_urls += f"\n- See `{SITE_URL}/sitemap.xml` for the remaining canonical URLs."
return f"""# Agent Guidance For {SITE_TITLE}
Canonical site: {SITE_URL}/
## Retrieval Policy
- Start with `{SITE_URL}/ai-index.json` to understand resources, artifacts, access type, and retrieval priority.
- Use `{SITE_URL}/sitemap.xml` for canonical human-facing URLs.
- Use `/data/open/pages/**/chunks.json` for semantic retrieval and `/data/open/pages/**/qa.json` for question-answer and workflow hints.
- Treat content as public/open only when the relevant `ai-index.json` access entry says `open`.
- Preserve source URLs, license, usageInfo, and attribution metadata when reusing content or semantic artifacts.
- Prefer stable artifact paths from `ai-index.json` over inferred paths.
## Crawling Policy
- Crawl politely and cache responses when possible.
- Do not crawl `/healthz/`; it is an uptime check endpoint, not a content resource.
- Do not submit contact forms or subscribe forms unless a human explicitly initiates that action.
- Do not infer private data, credentials, or unpublished operational details from public files.
## Useful Entry Points
- `{SITE_URL}/ai-index.json`
- `{SITE_URL}/llms.txt`
{useful_urls}
## Current Sitemap Coverage
The generated sitemap currently declares {len(entries)} public URLs with last modification dates, change frequency, and priority. This includes canonical human-facing pages plus selected root AI/helper resources.
"""
def skill_title_from_file(path: Path) -> str:
if path.suffix == ".py":
return path.name
text = read_text(path)
match = re.search(r"^# Skill:\s*(.+)$", text, re.MULTILINE)
if match:
return match.group(1).strip()
return path.stem.replace("-", " ").title()
def skill_summary_from_file(path: Path) -> str:
known_summaries = {
"ai-index-discovery-materialization-skill.md": "Create the machine-readable ai-index.json discovery and routing layer from markdown, chunks.json, qa.json, and existing index structure.",
"author-content-structuring-skill.md": "Add lightweight semantic structure, front matter, chunk markers, and stable identifiers to human-authored markdown content.",
"cis-guided-semantic-chunk-generation-skill.md": "Create chunks.json semantic retrieval artifacts using the project-selected subset of the CIS envelope.",
"discovery-files-materialization-skill.md": "Create the final public discovery files: robots.txt, sitemap.xml, llms.txt, agents.md, and skills.md.",
"execute-content-structuring-process-overview-skill.md": "Guide the overall manual workflow for authoring, structuring, chunking, QA generation, HTML rendering, and discovery materialization.",
"semantic-qa-materialization-skill.md": "Create qa.json semantic interaction artifacts from chunks.json and source markdown.",
}
if path.name in known_summaries:
return known_summaries[path.name]
if path.suffix == ".py":
first = read_text(path).splitlines()[0:6]
doc_line = " ".join(line.strip(' "\'') for line in first if line.strip().startswith('"""'))
return doc_line.strip(' "')
text = read_text(path)
overview = re.search(r"(?ms)^# Overview\s*(.+?)(?:\n#|\n##|\Z)", text)
if overview:
for line in overview.group(1).splitlines():
stripped = line.strip()
if stripped and not stripped.startswith("-"):
return stripped[:220]
contract = re.search(r"(?ms)^## Contract\s*(.+?)(?:\n##|\Z)", text)
if contract:
for line in contract.group(1).splitlines():
stripped = line.strip().lstrip("- ").strip()
if stripped:
return stripped[:220]
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("Human prompt"):
continue
if stripped and not stripped.startswith("#") and not stripped.startswith("---"):
return stripped[:220]
return "Project publishing workflow resource."
def build_skills_md() -> str:
skill_files = sorted(SKILLS_ROOT.glob("*-skill.md")) + sorted(SKILLS_ROOT.glob("*.py"))
lines = [
"# iNDX Website Skills And Scripts",
"",
"This public inventory lists the project-specific skills and deterministic scripts used to build, validate, and publish the static website and AI-readable discovery layers.",
"",
"## Skills",
]
for path in sorted(SKILLS_ROOT.glob("*-skill.md")):
rel = path.relative_to(REPO_ROOT).as_posix()
lines.append(f"- **{skill_title_from_file(path)}** (`/{rel}`): {skill_summary_from_file(path)}")
lines.extend(["", "## Scripts"])
for path in sorted(SKILLS_ROOT.glob("*.py")):
rel = path.relative_to(REPO_ROOT).as_posix()
lines.append(f"- **{path.name}** (`/{rel}`): {skill_summary_from_file(path)}")
lines.extend(
[
"",
"## Typical Build Order",
"",
"1. Structure source markdown content.",
"2. Generate `chunks.json` and `qa.json` semantic artifacts.",
"3. Run `sync_content_to_hugo.py`.",
"4. Run Hugo from `hugo-html-builder/`.",
"5. Run `build_ai_index.py`.",
"6. Run `build_discovery_files.py`.",
"",
]
)
return "\n".join(lines)
def validate_outputs() -> None:
sitemap = PUBLIC_ROOT / "sitemap.xml"
ET.parse(sitemap)
sitemap_text = read_text(sitemap)
if "<changefreq>" not in sitemap_text or "<priority>" not in sitemap_text:
raise RuntimeError("sitemap.xml is missing changefreq or priority fields")
if f"Sitemap: {SITE_URL}/sitemap.xml" not in read_text(PUBLIC_ROOT / "robots.txt"):
raise RuntimeError("robots.txt does not reference sitemap.xml")
for filename in ("llms.txt", "agents.md", "skills.md"):
path = PUBLIC_ROOT / filename
if not path.exists() or path.stat().st_size == 0:
raise RuntimeError(f"{filename} was not created")
for filename in SITEMAP_ROOT_HELPER_FILES:
path = PUBLIC_ROOT / filename
if path.exists() and f"<loc>{SITE_URL}/{filename}</loc>" not in sitemap_text:
raise RuntimeError(f"sitemap.xml is missing root helper file: {filename}")
def main() -> None:
entries = collect_sitemap_entries()
write_text(PUBLIC_ROOT / "robots.txt", build_robots())
write_text(PUBLIC_ROOT / "sitemap.xml", build_sitemap(entries))
write_text(PUBLIC_ROOT / "llms.txt", build_llms_txt(entries))
write_text(PUBLIC_ROOT / "agents.md", build_agents_md(entries))
write_text(PUBLIC_ROOT / "skills.md", build_skills_md())
validate_outputs()
print(f"Wrote discovery files in {PUBLIC_ROOT} for {len(entries)} sitemap URLs.")
if __name__ == "__main__":
main()
@@ -0,0 +1,905 @@
# Skill: CIS-Guided Semantic Chunk Materialization
Human prompt to complete this skill:
Using the attached skill, referencing the the <file-name> attached, create the chunks.json file. Reference the attached chunk-intelligence-signature.md file to accompany this skill. For more reference, see the attached README.md file for the overall process and where the chunks.json fits and where we are in this process. Reference the attached skills and prior outputs for structural consistency.
## Overview
This skill converts semantically structured authored content into machine-readable `chunks.json` files.
The input content should already contain:
- frontmatter;
- semantic chunk boundaries;
- `chunk_id`;
- `knowledge_id`;
- `chunk_label`;
- `knowledge_label`.
This skill uses the Chunk Intelligence Signature (CIS) envelope as the reference model for metadata, but it does not require every project to implement the full CIS envelope.
Instead, this skill helps the human operator and AI determine the appropriate level of CIS-guided metadata depth for the corpus, use case, and downstream systems.
This skill is the basis for an interative processed between the human and the AI to arrive at the right mix of CIS envelope metadata that should be included when creating `chunks.json` files.
Consider carefully the final outcome/intent of this project, and works backwards from there. It is possible we start with a limited set of metadata from the CIS envelope now, and later, re-process the `chunks.json` with more metadata.
The goal is to create a `chunks.json` file that is:
- useful now;
- easy to inspect;
- semantically meaningful;
- compatible with future enrichment;
- compatible with future CIS expansion;
- suitable for retrieval, embeddings, knowledge graphs, QA generation, and AI agents.
This skill is universal and may be used for:
- websites;
- knowledgebases;
- documentation;
- white papers;
- reports;
- newsletters;
- transcripts;
- research libraries;
- educational systems;
- legal archives;
- scientific corpora;
- AI-native publishing systems;
- paywalled or economically gated knowledge systems.
---
# 1. CIS-Guided Semantic Materialization
## Purpose
This skill treats `chunks.json` as a selective materialization of CIS-informed metadata.
The CIS envelope is the broad reference model.
The `chunks.json` file is the practical output layer.
This means the chunk file should not blindly include every possible CIS field. Instead, it should include only the fields that are appropriate for the current corpus and use case.
## Core Principle
`chunks.json` is not the full CIS envelope.
It is a selected semantic projection of the CIS envelope.
For simple content, this projection may be light.
For high-value, high-risk, research, legal, scientific, economic, or agent-facing content, this projection may be much deeper.
## CIS Areas To Consider
When deciding which metadata to include, evaluate whether the corpus needs metadata from these CIS areas:
1. Identity and resolution
2. Integrity and versioning
3. Semantics and meaning
4. Context and applicability
5. Relationships and knowledge graph
6. Provenance and pedigree
7. Rights, permissions, and access
8. Privacy, safety, and compliance
9. Reputation, utility, and signals
10. Execution and operational constraints
11. Decision and derivative outputs
Not every project needs every area.
The human operator and AI should select the correct depth before generating the final `chunks.json`.
---
# 2. Materialization Levels
Before generating `chunks.json`, determine the desired materialization level.
The level may be selected by the human operator or recommended by the AI based on the corpus type and project goals.
## Level 1 — Lightweight Semantic Retrieval
Use for:
- simple static websites;
- blogs;
- newsletters;
- basic public pages;
- early prototypes;
- small documentation sets.
Purpose:
Create clean, lightweight semantic chunks for AI retrieval and indexing without operational complexity.
Includes:
- document metadata;
- chunk IDs;
- knowledge IDs;
- chunk labels;
- knowledge labels;
- order;
- heading path;
- content;
- short summary;
- tags.
Does NOT include:
- provenance chains;
- trust scoring;
- rights management;
- economic terms;
- ontology assertions;
- semantic lineage;
- privacy constraints;
- reputation signals.
Recommended for the initial iNDX static website.
---
## Level 2 — Enhanced Semantic Retrieval
Use for:
- larger websites;
- structured knowledgebases;
- internal documentation;
- white paper libraries;
- educational content;
- research notes;
- product documentation.
Purpose:
Improve retrieval, filtering, semantic classification, and AI summarization.
Includes everything in Level 1, plus optional:
- content type;
- primary topic;
- domain;
- entities;
- key concepts;
- intended audience;
- source alignment;
- confidence level;
- basic relationship hints.
Example added fields:
```json
"semantic_core": {
"content_type": "analysis",
"domain": ["ai", "publishing"],
"primary_topic": "AI-native findability",
"entities": [],
"key_concepts": []
}
```
## Level 3 — Ontology-Aware Retrieval
Use for:
- AI-native knowledgebases;
- research corpora;
- industry intelligence systems;
- structured archives;
- policy libraries;
- technical reference systems.
Purpose:
Make chunks more useful for graph traversal, ontology mapping, multi-hop reasoning, and domain-specific AI agents.
Includes everything in Levels 1 and 2, plus optional:
- ontology references;
- controlled taxonomy labels;
- explicit semantic assertions;
- relationship mappings;
- applicability context;
- assumptions;
- scope;
- prerequisites;
- basic provenance.
Example added fields:
```json
"ontology": {
"ontology_refs": [],
"taxonomy_tags": [],
"semantic_assertions": []
}
"context": {
"scope": "",
"assumptions": [],
"intended_audience": [],
"prerequisites": []
}
```
## Level 4 — Graph-Native Semantic Infrastructure
Use for:
- serious knowledge graph systems;
- high-value research libraries;
- multi-author corpora;
- agent-facing knowledge systems;
- evolving AI-native reference systems;
- corpora where trust and lineage matter.
Purpose:
Create chunks that can support long-term semantic evolution, lineage, trust inheritance, relationship density, and graph-native reasoning.
Includes everything in Levels 1–3, plus optional:
- version lineage;
- supersedes / superseded_by;
- derived_from;
- semantic similarity to prior chunk;
- trust inheritance hints;
- cross-chunk links;
- interpretive relationships;
- assertion records;
- provenance records;
- enrichment workflow metadata.
Example added fields:
```json
"lineage": {
"supersedes": [],
"superseded_by": [],
"derived_from": [],
"semantic_similarity_to_previous": null,
"trust_inheritance": null
}
"relationships": {
"supports": [],
"depends_on": [],
"expands": [],
"contradicts": [],
"summarizes": []
}
```
## Level 5 — Full CIS Implementation
Use for:
- paywalled knowledge systems;
- regulated content;
- legal or compliance systems;
- scientific datasets;
- high-value commercial corpora;
- decentralized knowledge infrastructure;
- agent-to-agent economic access systems;
- content requiring permissions, trust, provenance, and auditability.
Purpose:
Implement the CIS envelope as a full metadata infrastructure layer.
Includes everything in Levels 1–4, plus:
- DID_chunk;
- CID_chunk;
- CID_source;
- full provenance;
- ownership history;
- origin purity;
- rights and permissions;
- economic terms;
- privacy and compliance controls;
- reputation and utility signals;
- execution constraints;
- derivative artifact tracking;
- attribution requirements;
- policy overlays;
- payment or access metadata.
This level is not recommended for simple static websites unless there is a clear need.
# 3. Human + AI Metadata Negotiation
Before generating the final chunks.json, the human operator and AI should agree on the metadata depth and schema.
This is especially important when working with:
large corpora;
specialized domains;
legal, scientific, financial, or technical content;
monetized content;
agent-facing content;
reusable knowledgebases.
## Step 1 — Identify Corpus Type
The AI should determine or ask the human to confirm the corpus type.
Examples:
static website;
documentation;
newsletter archive;
white paper library;
scientific corpus;
legal archive;
product knowledgebase;
internal company knowledgebase;
public AI-readable knowledgebase;
paywalled content library.
## Step 2 — Identify Intended Use
Determine what the chunk output will support.
Examples:
AI retrieval;
semantic search;
embeddings;
RAG;
public discovery;
website indexing;
internal knowledge management;
agent reasoning;
graph traversal;
compliance review;
monetized access;
future CIS integration.
## Step 3 — Select Materialization Level
Choose one of:
Level 1 — Lightweight Semantic Retrieval
Level 2 — Enhanced Semantic Retrieval
Level 3 — Ontology-Aware Retrieval
Level 4 — Graph-Native Semantic Infrastructure
Level 5 — Full CIS Implementation
If uncertain, choose the lowest level that satisfies current needs while preserving future compatibility.
## Step 4 — Select Fields
The AI should propose a field list based on the selected level.
The human should approve, remove, or add fields.
The final schema should be explicit before output generation.
## Step 5 — Generate chunks.json
Once the field list is approved, generate the final JSON.
# 4. Minimal vs Extended Schemas
## Minimal Schema
Use for Level 1.
Recommended default:
```json
{
"document": {
"title": "",
"slug": "",
"document_type": "",
"author": "",
"created_at": "",
"license": "https://creativecommons.org/licenses/by/4.0/",
"usageInfo": "https://indx.earth/wiki/license/",
"tags": []
},
"chunks": [
{
"chunk_id": "",
"knowledge_id": "",
"chunk_label": "",
"knowledge_label": "",
"order": 1,
"heading_path": [],
"content": "",
"summary": "",
"tags": []
}
]
}
```
Use this when the goal is:
simple AI readability;
basic retrieval;
static publishing;
low operational complexity.
## Extended Schema
Use for Levels 2–4.
Example:
```json
{
"document": {
"title": "",
"slug": "",
"document_type": "",
"author": "",
"created_at": "",
"updated_at": "",
"summary": "",
"tags": [],
"source_path": "",
"canonical_url": "",
"license": "https://creativecommons.org/licenses/by/4.0/",
"usageInfo": "https://indx.earth/wiki/license/"
},
"chunks": [
{
"chunk_id": "",
"knowledge_id": "",
"chunk_label": "",
"knowledge_label": "",
"order": 1,
"heading_path": [],
"content": "",
"summary": "",
"tags": [],
"semantic_core": {
"content_type": "",
"domain": [],
"primary_topic": "",
"entities": [],
"key_concepts": [],
"confidence_level": ""
},
"context": {
"scope": "",
"assumptions": [],
"intended_audience": [],
"prerequisites": []
},
"relationships": {
"supports": [],
"depends_on": [],
"expands": [],
"contradicts": [],
"summarizes": []
},
"lineage": {
"supersedes": [],
"superseded_by": [],
"derived_from": [],
"semantic_similarity_to_previous": null,
"trust_inheritance": null
},
"provenance": {
"creation_method": "",
"source_alignment": "",
"tooling": [],
"workflows": []
}
}
]
}
```
```
Use this when the goal is:
better AI retrieval;
semantic filtering;
ontology mapping;
relationship discovery;
future knowledge graph integration.
## Full CIS-Aligned Schema
Use for Level 5 only.
The schema should be project-specific and derived directly from the full CIS envelope.
Do not generate a full Level 5 schema unless the human explicitly requests it.
# 5. Corpus-Specific Semantic Strategies
Different corpora require different chunking and metadata strategies.
Static Websites
Recommended level:
Level 1
Include:
document metadata;
chunk identity;
semantic labels;
content;
summaries;
tags;
heading paths.
Avoid:
full provenance;
trust scoring;
rights systems;
economic terms;
deep ontology mapping.
Goal:
Make pages easy for AI systems to find, understand, summarize, and route.
Newsletter or Email Archives
Recommended level:
Level 1 or Level 2
Include:
publication date;
topic tags;
audience;
summary;
referenced links;
key concepts;
action items if present.
Useful optional fields:
```json
"email_context": {
"campaign": "",
"audience": [],
"original_send_date": "",
"source_platform": ""
}
```
Goal:
Make past communications searchable, reusable, and AI-readable.
White Paper Libraries
Recommended level:
Level 2 or Level 3
Include:
primary topic;
claims;
entities;
assumptions;
scope;
intended audience;
source alignment;
ontology references if available.
Goal:
Support research, synthesis, citation, and conceptual retrieval.
Documentation
Recommended level:
Level 2 or Level 3
Include:
task type;
prerequisites;
steps;
dependencies;
affected systems;
related docs;
version applicability.
Useful optional fields:
```json
"task_context": {
"task_type": "",
"prerequisites": [],
"systems": [],
"dependencies": []
}
```
Goal:
Help AI agents and humans retrieve the right operational instructions.
Scientific or Technical Corpora
Recommended level:
Level 3, Level 4, or Level 5
Include:
domain;
entities;
methods;
evidence type;
confidence;
claims;
uncertainty;
citations;
provenance;
relationships;
applicability limits.
Goal:
Support high-confidence reasoning and careful scientific interpretation.
Legal, Policy, or Compliance Archives
Recommended level:
Level 4 or Level 5
Include:
jurisdiction;
effective dates;
authority;
normative status;
applicability;
exceptions;
conflicts;
supersession;
provenance;
rights and restrictions.
Goal:
Support careful, auditable retrieval where context and applicability matter.
Monetized or Paywalled Knowledge Systems
Recommended level:
Level 4 or Level 5
Include:
access rights;
pricing;
preview metadata;
usage permissions;
economic terms;
provenance;
reputation signals;
attribution requirements.
Goal:
Allow agents to evaluate whether content is worth accessing or paying for.
Input Requirements
The input markdown document should already contain:
YAML frontmatter;
semantic chunk boundaries;
chunk_id;
knowledge_id;
chunk_label;
knowledge_label.
Example:
<!-- CHUNK START
chunk_id="chk:550e8400-e29b-41d4-a716-446655440000"
knowledge_id="kid:7c9e6679-7425-40de-944b-e07fc1f90ae7"
chunk_label="industriesig-overview"
knowledge_label="industriesig-findability"
-->
[content]
<!-- CHUNK END -->
# Output File
The output should be a single machine-readable JSON file:
chunks.json
# Output Structure
The top-level structure should follow this format:
{
"document": {},
"chunks": []
}
# Field Rules
## chunk_id
Represents the specific chunk instance.
Must preserve the authored UUID/DID-style identifier exactly.
Do NOT regenerate.
## knowledge_id
Represents the enduring conceptual identity.
Must preserve the authored UUID/DID-style identifier exactly.
Do NOT regenerate.
## chunk_label
Human-readable structural label.
Used for:
debugging;
retrieval interpretation;
ontology reasoning;
graph inspection.
knowledge_label
Human-readable conceptual label.
Represents the enduring meaning of the chunk.
Multiple chunks MAY reference the same knowledge_label.
## order
Represents narrative sequence within the document.
Must preserve original document order.
Starts at:
1
## heading_path
Represents the hierarchical heading structure above the chunk.
Example:
[
"The iNDX Platform",
"IndustrySIG"
]
This preserves:
semantic hierarchy;
contextual breadcrumbs;
retrieval weighting;
structural context.
## content
Contains the full original chunk text.
Preserve original formatting when possible.
Do NOT:
summarize;
paraphrase;
rewrite;
compress.
## summary
Generate a short semantic retrieval summary.
Purpose:
retrieval hinting;
embedding context;
semantic ranking;
AI understanding.
This is NOT marketing copy.
Ideal length:
1–3 sentences.
## tags
Generate lightweight semantic tags.
Tags should represent:
concepts;
domains;
systems;
technologies;
industries;
major semantic themes.
Avoid excessive tagging.
Ideal range:
3–10 tags.
# Output Constraints
Do NOT:
invent missing content;
merge chunks;
split chunks;
alter IDs;
rewrite meaning;
flatten heading hierarchy;
add unsupported claims.
# Important Architectural Principle
This layer represents:
stable semantic retrieval infrastructure
It does not replace the CIS envelope.
It is a practical, selected projection of CIS-informed metadata into a usable chunk file.
# Final Output Requirement
Output a COMPLETE valid chunks.json file.
Do NOT output:
markdown;
commentary;
explanations;
partial fragments.
The output should be production-ready JSON suitable for direct ingestion into downstream systems.
# Validation Requirements
After generating the chunk.json:
1. Verify all referenced files exist
2. Verify all slugs match
3. Verify no orphaned resources exist
5. Verify access routes are internally consistent
A second AI agent should validate the output.
+43
View File
@@ -0,0 +1,43 @@
# Contact Form Deployment
The website form posts to `/api/contact`. The handler is a small FastAPI app in
`api/contact_app.py` and sends mail through SMTP provider.
## VM Packages
Install Python and the contact API dependencies inside the container or Python
runtime that will serve the API:
```bash
python3 -m pip install -r requirements-contact-api.txt
```
The runtime needs these environment variables. Do not commit their values:
```bash
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=<smtp-user>
SMTP_PASSWORD=<smtp-password>
CONTACT_TO_EMAIL=<where messages should go>
CONTACT_FROM_EMAIL=<verified SMTP sender address>
```
## Run Command
Run the API on an internal port, then route `/api/contact` to it from the
existing container/Caddy setup:
```bash
uvicorn api.contact_app:app --host 0.0.0.0 --port 8091
```
Health check:
```bash
curl http://localhost:8091/api/contact/healthz
```
The public static site can continue to be served as it is now. The only
deployment requirement is that requests for `/api/contact` and
`/api/contact/healthz` reach the FastAPI process.
@@ -0,0 +1,146 @@
# Skill: Discovery Files Materialization
Human prompt to complete this skill:
Using this skill, reference the current README.md process document, existing public discovery files if present, the generated Hugo HTML routes, source markdown pages, semantic data files, and ai-index.json. Create or update the final public discovery files:
- `public/robots.txt`
- `public/sitemap.xml`
- `public/llms.txt`
- `public/agents.md`
- `public/skills.md`
---
## Contract
This skill guarantees:
- `robots.txt` points crawlers to the canonical sitemap and avoids exposing operational-only routes such as `/healthz/` as index targets.
- `sitemap.xml` contains canonical public URLs with `<lastmod>`, `<changefreq>`, and `<priority>` for human-facing pages.
- `sitemap.xml` appends selected root machine/helper resources after human-facing pages so crawlers have an explicit path to AI discovery files.
- `llms.txt` gives LLMs a concise, plain-text entry point into the site, important URLs, and machine-readable artifacts.
- `agents.md` gives autonomous agents safe retrieval, crawling, and usage guidance grounded in public files.
- `skills.md` lists project skills and deterministic scripts that produce or validate this website.
- Existing discovery files are read before replacement when present, so format and project-specific intent can be preserved where appropriate.
- No credentials, secrets, private endpoints, or unsupported claims are added.
## Inputs
Read these first:
- `README.md`
- Existing `public/robots.txt`, `public/sitemap.xml`, `public/llms.txt`, `public/agents.md`, `public/skills.md` if they exist
- `public/ai-index.json`
- `content/**/*.md`
- `public/data/open/pages/**/chunks.json`
- `public/data/open/pages/**/qa.json`
- `hugo-html-builder/public/**` when HTML has already been rendered
## Preferred Script
Use:
```bash
python skills-scripts/build_discovery_files.py
```
The script materializes all five files deterministically. Patch the script when the policy or output shape changes; do not repeatedly hand-author these files.
## Phases
### Phase 1: Inventory
Identify all public human-facing routes:
- `/`
- section landing pages such as `/community-summaries/`
- audience landing pages such as `/community-summaries/paddling/`
- article pages such as `/community-summaries/paddling/{slug}.html`
Exclude operational-only endpoints from the sitemap, especially `/healthz/`.
### Phase 2: Sitemap
Create `public/sitemap.xml` with:
- `<loc>` canonical URL under `https://indx.earth`
- `<lastmod>` using source markdown last modification date, or the latest child modification date for section pages
- `<changefreq>` estimated from page role
- `<priority>` estimated from page role
- selected root machine/helper resources appended after all HTML pages:
- `/ai-index.json`
- `/llms.txt`
- `/skills.md`
Recommended defaults:
- Home: `weekly`, `1.0`
- Primary section landing page: `weekly`, `0.8`
- Audience section landing page: `weekly`, `0.7`
- Article/community summary page: `monthly`, `0.6`
- Root AI/helper resource: `weekly`, `0.4`
### Phase 3: Robots
Create `public/robots.txt` with a clear allow policy for public content, a disallow for `/healthz/`, and a `Sitemap:` line pointing to `https://indx.earth/sitemap.xml`.
Do not encode Cloudflare bot-blocking policy in `robots.txt`; Cloudflare remains the enforcement layer for that.
### Phase 4: LLM Entry Point
Create `public/llms.txt` as a compact LLM-facing guide:
- site name and canonical URL
- project purpose
- important human pages
- machine-readable artifacts
- recommended retrieval order
- contact/form status if relevant
Keep it concise and plain text.
### Phase 5: Agent Guidance
Create `public/agents.md` with safe agent instructions:
- start with `/ai-index.json`
- use `chunks.json` for retrieval and `qa.json` for interaction patterns
- prefer canonical URLs from the sitemap
- do not submit forms, scrape aggressively, or infer private data
- respect public/open access boundaries
- preserve license, usageInfo, source URL, and attribution metadata where available
### Phase 6: Skills Inventory
Create `public/skills.md` listing project skills and deterministic scripts in `skills-scripts/`:
- skill name or script filename
- role in the publishing pipeline
- when to use it
This is a public inventory, not internal secrets or implementation logs.
### Phase 7: Validation
Validate:
- XML parses
- all sitemap URLs use `https://indx.earth`
- sitemap includes lastmod/changefreq/priority for each URL
- sitemap includes `/ai-index.json`, `/llms.txt`, and `/skills.md` after the human-facing HTML URLs when those files exist
- `robots.txt` references the sitemap
- `llms.txt`, `agents.md`, and `skills.md` exist and are non-empty
- no credentials or private paths are present
## Anti-Patterns
Do not:
- include `/healthz/` in `sitemap.xml`
- add secrets, API keys, private server names, or local-only paths to public files
- invent crawler policies that belong in Cloudflare
- duplicate full chunks, QA records, or ai-index contents in `llms.txt` or `agents.md`
- treat `sitemap.xml` as a substitute for `ai-index.json`
- include `robots.txt`, `sitemap.xml`, operational endpoints, or `/healthz/` as index targets
- hand-edit generated files without also updating the builder script when the change should persist
@@ -0,0 +1,260 @@
# Skill: Execute Content Structuring Process Overview
# Step 1
Do not use below, yet. Use the skills in steps 2 and 3 in the README.md file, using the home.md page, manually with an AI chat. The reason is that the human and the AI need to iterate on selecting the best metadata content to be used in this projoect from the CIS Envelope. Once this is done, the human can proceed with having AI execute the following skill, below, for the remaining websie pages. When new pages are added, the human can most likely just use this skill below. Only if the home page content of the website is substanitally different might the interative process of adding metadata from the CIS Envelope be required. If so, then it is possible that all pages are processed again, but maybe not. It really depends. Use this interative process to discuss with AI. Or, if pages added to the website start to drift from the initial metadata used, then the human and I come back to this interative process. By referencing the initial home page, that can be flagged in the skill below.
# Step 2
Use this skill when the human wants to process one or more authored Markdown pages through the iNDX website semantic publishing workflow.
This skill coordinates the repo-level process described in `README.md`, especially:
- Step 2: enrich authored Markdown with front matter, semantic chunk boundaries, and stable identifiers.
- Step 3: materialize the enriched page into `chunks.json` and `qa.json`.
It does not replace the lower-level skills. It tells the AI how to use them together consistently.
---
## Required References
Before editing or generating anything, review:
1. `README.md`
- Understand the repo purpose, website build process, and directory structure.
2. `content/home.md`
- Treat the front matter and chunk marker style as the canonical page shape.
3. `public/data/open/pages/home/chunks.json`
- Treat this as the canonical `chunks.json` metadata shape.
4. `public/data/open/pages/home/qa.json`
- Treat this as the canonical `qa.json` metadata shape.
5. Local skills in `skills-scripts/`
- `author-content-structuring-skill.md`
- `cis-guided-semantic-chunk-generation-skill.md`
- `semantic-qa-materialization-skill.md`
Do not use the CIS envelope reference page unless the human explicitly asks for it. The current project uses the already-established home page metadata model as the practical canonical schema.
---
## Canonical Output Model
For every source page:
1. Update the source `.md` file with:
- YAML front matter.
- Semantic chunk boundaries.
- Stable `chunk_id` values.
- Stable `knowledge_id` values.
- Human-readable `chunk_label` values.
- Human-readable `knowledge_label` values.
2. Create a folder under:
```text
public/data/open/pages/<same relative content path>/<slug>/
```
Example:
```text
content/community-summaries/paddling/example-page.md
public/data/open/pages/community-summaries/paddling/example-page/
```
3. Create:
```text
chunks.json
qa.json
```
inside that folder.
---
## Human Prompt Template
Use or adapt this prompt when asking AI to process pages:
```text
The README.md file explains what this repo is, the process for building website pages, and the directory structure. Please reference it.
The home page has already been manually processed and checked. Use content/home.md plus public/data/open/pages/home/chunks.json and public/data/open/pages/home/qa.json as the canonical examples for front matter, identifiers, metadata, chunk structure, chunks.json, and qa.json.
Process the following page or pages through README steps 2 and 3:
<list source markdown files here>
For each page:
- preserve the author's meaning and voice;
- add front matter using the home.md metadata model;
- add semantic chunk boundaries with chunk_id, knowledge_id, chunk_label, and knowledge_label;
- create the corresponding chunks.json;
- create the corresponding qa.json;
- put chunks.json and qa.json in public/data/open/pages/<relative content path>/<slug>/ so they are served publicly as /data/open/pages/<relative content path>/<slug>/;
- create directories as needed;
- do not use the CIS envelope reference page unless explicitly instructed.
Before writing files, review the task, identify any confusion, and ask only necessary questions. Once clear, proceed.
After writing files, validate that:
- JSON parses;
- every chunk_id in chunks.json appears in the markdown;
- every QA chunk reference points to an existing chunk;
- slugs and paths match the source page;
- no unrelated files were changed.
```
---
## Workflow
### 1. Read Context
Read the README and canonical home outputs before processing new pages.
Use the home page to learn:
- front matter fields;
- document metadata naming;
- slug style;
- chunk marker format;
- identifier style;
- `chunks.json` document fields;
- `chunks.json` chunk fields;
- `qa.json` document fields;
- `qa.json` QA pair fields.
- document-level `license` and `usageInfo` metadata.
### 2. Read Source Pages
Read every source `.md` page before deciding chunk boundaries.
For multiple pages, it is acceptable to batch a few pages at a time when the model and tooling can handle it. If the pages are long or complex, process fewer pages per batch.
### 3. Create Enriched Markdown
Follow `author-content-structuring-skill.md`.
Rules:
- Preserve original meaning.
- Preserve links.
- Preserve useful headings.
- Do not rewrite into marketing copy.
- Clean obvious encoding damage only when it preserves the intended text.
- Split chunks by semantic reasoning shifts, not by formatting alone.
- Use durable opaque IDs for `chunk_id` and `knowledge_id`.
- Use readable semantic labels for `chunk_label` and `knowledge_label`.
### 4. Create `chunks.json`
Follow `cis-guided-semantic-chunk-generation-skill.md`, using the home page output as the practical schema.
For this static website, use the lightweight/static-plus projection already established by the home page and community summary pages:
- document metadata;
- document-level license and usage metadata;
- chunk IDs;
- knowledge IDs;
- labels;
- order;
- heading paths;
- content;
- summaries;
- tags;
- light semantic/context fields where already established.
### 5. Create `qa.json`
Follow `semantic-qa-materialization-skill.md`, using the home page output as the practical schema.
Generate QA pairs that improve:
- retrieval;
- semantic understanding;
- navigation;
- synthesis;
- workflow execution when the source contains actions.
Every meaningful chunk should be referenced by at least one QA pair.
The `document` object should include:
```json
"license": "https://creativecommons.org/licenses/by/4.0/",
"usageInfo": "https://indx.earth/wiki/license/"
```
### 6. Validate
Always perform a final inference and consistency pass.
Check:
- the enriched `.md` exists;
- `chunks.json` exists;
- `qa.json` exists;
- both JSON files parse;
- both JSON files include document-level `license` and `usageInfo`;
- all `chunk_id` values in `chunks.json` appear in the `.md`;
- all `knowledge_id` values in `chunks.json` appear in the `.md`;
- all `qa.json` `chunk_ids` point to real chunks;
- all `qa.json` `knowledge_ids` point to real knowledge IDs;
- document slug matches the source filename;
- `source_path` matches the source page;
- `canonical_url` follows the site URL pattern;
- no orphaned output folders were created;
- no unrelated files were changed.
---
## Windows And PowerShell Notes
Be careful on Windows PowerShell:
- Paths with drive letters and long filenames are easy to quote incorrectly.
- Very large inline `powershell -Command` strings can fail with command-length errors.
- Redirection and heredoc-style scripting can behave differently than expected.
- Some sandboxed shells may not have the same `python` path as elevated shells.
- Git may report dubious ownership when the repo is accessed from a sandbox user.
Preferred approach:
- Use direct PowerShell reads such as `Get-Content -Raw`.
- Use `apply_patch` for edits inside the writable workspace.
- For large generated outputs, write a small deterministic generator script in the workspace, then run it.
- If writing outside the writable workspace, request approval cleanly.
- For Git status on this repo, use a one-off safe-directory flag rather than changing global config:
```powershell
git -c safe.directory=C:/path/to/structured-website-builder -C C:\path\to\structured-website-builder status --short
```
---
## Safety Notes
- Do not revert user changes.
- Do not delete `_original` files unless the human explicitly asks; they may be retained as reference copies.
- Do not run destructive Git commands.
- Prefer deterministic, repeatable generation when processing many pages.
- Keep the source directory backed up or preserve originals before large batch work when appropriate.
---
## Completion Report
At the end, report:
- pages processed;
- files created or updated;
- chunk and QA counts per page;
- validation results;
- any unrelated pre-existing repo changes noticed but left alone.
@@ -0,0 +1,13 @@
Run this simple skill after each Hugo render, inspect every generated HTML page to verify
Pages with semantic artifacts include <link rel="alternate" type="application/json"> tags in <head>.
Alternate links point to existing chunks.json and qa.json files.
JSON-LD exists on all normal rendered content pages.
JSON-LD parses as raw JSON, not as an escaped/quoted string.
Home page uses WebPage.
Individual community summary pages use Article.
Section/list pages use CollectionPage.
Semantic artifact files are represented as Dataset nodes with DataDownload URLs.
WebPage, Article, CollectionPage, and Dataset nodes include `license`.
WebPage, Article, CollectionPage, and Dataset nodes include `usageInfo`.
Utility pages like /healthz/ do not need semantic discovery metadata.
+1
View File
@@ -0,0 +1 @@
There could be updated skills for processing the content from the ai-knowledge-structure repo.
+70
View File
@@ -0,0 +1,70 @@
"""Copy Hugo-rendered HTML output into the repo public directory.
Run after:
1. python skills-scripts/sync_content_to_hugo.py
2. cd hugo-html-builder && hugo --cleanDestinationDir
3. python skills-scripts/build_ai_index.py
4. python skills-scripts/build_discovery_files.py
This script copies files from hugo-html-builder/public into public while
preserving repo-level discovery files generated outside Hugo.
"""
from __future__ import annotations
import shutil
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
HUGO_PUBLIC = REPO_ROOT / "hugo-html-builder" / "public"
PUBLIC_ROOT = REPO_ROOT / "public"
PRESERVE_AT_PUBLIC_ROOT = {
"robots.txt",
"sitemap.xml",
"llms.txt",
"agents.md",
"skills.md",
"ai-index.json",
}
def should_preserve(relative_path: Path) -> bool:
return len(relative_path.parts) == 1 and relative_path.name in PRESERVE_AT_PUBLIC_ROOT
def copy_hugo_output() -> tuple[int, list[str]]:
if not HUGO_PUBLIC.exists():
raise FileNotFoundError(f"Missing Hugo output directory: {HUGO_PUBLIC}")
copied = 0
skipped: list[str] = []
for source in HUGO_PUBLIC.rglob("*"):
if source.is_dir():
continue
relative = source.relative_to(HUGO_PUBLIC)
if should_preserve(relative):
skipped.append(relative.as_posix())
continue
target = PUBLIC_ROOT / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, target)
copied += 1
return copied, skipped
def main() -> None:
copied, skipped = copy_hugo_output()
print(f"Copied {copied} Hugo output files into {PUBLIC_ROOT}")
if skipped:
print("Preserved root discovery files:")
for path in skipped:
print(f"- {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,3 @@
fastapi==0.115.6
python-multipart==0.0.20
uvicorn[standard]==0.34.0
@@ -0,0 +1,836 @@
# Skill: Semantic QA Materialization
Human prompt to complete this skill:
Using the attached skill, referencing the chunks.json and the <file-name> attached, create the qa.json file. For more reference, see the attached README.md file for the overall process and where the qa.json fits, and if needed the cis-guided...skill.md file, which likely you will not need at this point, is added for context. Reference the attached skills and prior outputs for structural consistency.
## Overview
This skill generates a structured `qa.json` reasoning layer from semantically structured content.
The QA layer is not simply a FAQ system.
It is semantic interaction infrastructure for:
- AI retrieval;
- semantic search;
- embeddings;
- RAG systems;
- graph traversal;
- agent interaction;
- workflow execution;
- ontology enrichment;
- semantic routing;
- future economic access systems.
The purpose of this layer is to help AI systems and humans:
- understand the content;
- navigate the corpus;
- synthesize ideas across chunks;
- execute tasks;
- identify workflows;
- discover relationships;
- interact with knowledge programmatically.
This skill is designed to work across:
- static websites;
- documentation systems;
- white papers;
- newsletters;
- transcripts;
- research libraries;
- educational systems;
- product knowledgebases;
- AI-native publishing systems;
- agent-facing knowledge systems;
- monetized knowledge systems.
---
# Core Architectural Principle
The QA layer is:
- a semantic retrieval layer;
- a reasoning layer;
- a routing layer;
- an interaction layer;
- an execution support layer.
It is NOT merely:
- marketing FAQs;
- website support questions;
- simplistic summarization.
Questions and answers should help AI systems understand:
- meaning;
- relationships;
- applicability;
- workflows;
- actions;
- conceptual structure;
- navigation paths;
- operational next steps.
---
# Input Requirements
The source content should already be semantically structured.
Recommended inputs:
- Markdown with semantic chunk boundaries;
- `chunks.json`;
- CIS-informed metadata;
- semantic labels;
- heading hierarchy.
The preferred source is:
`chunks.json`
because it already contains:
- semantic structure;
- summaries;
- tags;
- concepts;
- entities;
- context.
---
# QA Generation Principles
Generate questions that improve:
- retrieval;
- semantic understanding;
- synthesis;
- navigation;
- workflow execution;
- ontology discovery;
- agent usability.
Questions should vary across:
- specificity;
- abstraction;
- phrasing;
- audience;
- intent;
- reasoning depth.
The QA layer should represent how humans and AI agents naturally interact with the knowledge.
---
# Types Of Questions To Generate
Generate a mix of:
## 1. Factual Questions
Direct retrieval questions.
Example:
- What is IndustrySIG?
- What does SIG stand for?
Purpose:
- fast retrieval;
- grounding;
- direct lookup.
---
## 2. Conceptual Questions
Meaning and interpretation questions.
Example:
- Why does iNDX believe findability matters in the AI era?
- How does AI-native indexing differ from traditional search visibility?
Purpose:
- reasoning;
- conceptual understanding;
- semantic synthesis.
---
## 3. Comparative Questions
Compare systems, concepts, or approaches.
Example:
- How does NetworkSIG differ from traditional professional networking platforms?
- How do IndustrySIG and TerraSIG serve different functions?
Purpose:
- differentiation;
- semantic mapping;
- ontology development.
---
## 4. Procedural Questions
Explain workflows or operational steps.
Example:
- How can someone become an Industry Indexer?
- How does someone participate in Snap For Science?
Purpose:
- task execution;
- onboarding;
- workflow support.
---
## 5. Navigational Questions
Help AI systems or users locate information.
Example:
- Where can I find the white paper about decentralized networking?
- Which section explains ecological intelligence?
Purpose:
- routing;
- corpus navigation;
- retrieval optimization.
---
## 6. Strategic Questions
High-level implication or systems-thinking questions.
Example:
- Why is decentralized discoverability important for small businesses?
- What role does structured discovery play in economic participation?
Purpose:
- strategic reasoning;
- systems understanding;
- long-range synthesis.
---
## 7. Synthesis Questions
Combine multiple chunks or systems into one answer.
Example:
- How do the four iNDX systems reinforce one another?
- How do IndustrySIG and NetworkSIG work together?
Purpose:
- multi-hop reasoning;
- graph traversal;
- cross-chunk synthesis.
---
# Question Quality Rules
Questions should:
- sound natural;
- reflect realistic user or agent behavior;
- vary in phrasing;
- vary in specificity;
- avoid repetition;
- improve retrieval diversity.
Generate both:
- broad questions;
- narrow questions.
Include both:
- human phrasing;
- AI-agent-style retrieval phrasing.
---
# Answer Rules
Answers must:
- remain grounded strictly in source content;
- avoid hallucination;
- avoid unsupported claims;
- avoid speculation;
- preserve original meaning.
Answers should:
- be concise but complete;
- optimize for retrieval clarity;
- preserve semantic fidelity;
- support downstream embeddings.
Do NOT:
- rewrite the original meaning;
- add external knowledge;
- inject opinions;
- infer unsupported relationships.
---
# Cross-Chunk Synthesis Rules
Questions MAY reference multiple chunks.
Use:
```json
"knowledge_ids": []
"chunk_ids": []
```
to support:
- multi-hop reasoning;
- semantic synthesis;
- graph traversal;
- cross-document retrieval.
Example:
```json
"knowledge_ids": [
"kid-123",
"kid-456"
]
```
This is strongly encouraged when concepts naturally connect.
---
# QA Types
Each QA entry should include:
```json
"qa_type": ""
```
Recommended values:
- factual
- conceptual
- comparative
- procedural
- navigational
- strategic
- synthesis
- workflow
- glossary
Purpose:
- semantic routing;
- retrieval weighting;
- reasoning selection;
- agent orchestration.
---
# Intent Classification
Each QA entry should include:
```json
"intent": ""
```
Recommended values:
- discover
- understand
- compare
- evaluate
- execute
- navigate
- participate
- contribute
- summarize
- learn
- research
- implement
Purpose:
- agent routing;
- workflow execution;
- future monetization systems;
- retrieval prioritization.
---
# Actionability Layer
If the content references:
- workflows;
- templates;
- tools;
- operational processes;
- onboarding flows;
- participation systems;
- execution steps;
then include an `actionability` object.
Example:
```json
"actionability": {
"has_workflow": true,
"tools": [],
"processes": [],
"next_steps": []
}
```
This helps future systems:
- execute workflows;
- guide users;
- support AI agents;
- generate next-step recommendations.
Do NOT invent workflows that are not supported by the source content.
---
# Entities And Concepts
Each QA entry should include lightweight semantic extraction:
```json
"entities": [],
"concepts": [],
"tags": []
```
Purpose:
- semantic filtering;
- ontology enrichment;
- embeddings;
- graph construction;
- retrieval ranking.
Avoid excessive tagging.
Prefer meaningful semantic signals.
---
# Audience Classification
If feasible, include:
```json
"audience": []
```
Examples:
- business owners
- researchers
- developers
- industry participants
- conservation leaders
- educators
- AI practitioners
Purpose:
- routing;
- personalization;
- retrieval refinement.
---
# Source Grounding
Each QA entry should include:
```json
"source_chunks": []
```
These should reference the literal chunk sources used to generate the answer.
Example:
```json
"source_chunks": [
"chk-abc123"
]
```
Purpose:
- provenance;
- trust;
- grounding;
- future citations;
- paywall preview systems.
---
# Related Questions
If useful, include:
```json
"related_questions": []
```
Purpose:
- graph traversal;
- semantic expansion;
- recommendation systems;
- agent reasoning chains.
---
# Materialization Levels
## Level 1 — Lightweight QA Retrieval
Use for:
- simple websites;
- blogs;
- newsletters;
- early prototypes.
Includes:
- question;
- answer;
- qa_type.
Purpose:
Simple semantic retrieval.
---
## Level 2 — Enhanced Semantic QA
Use for:
- structured websites;
- knowledgebases;
- white papers;
- documentation.
Includes:
- qa_type;
- intent;
- tags;
- concepts;
- entities;
- source_chunks.
Purpose:
Better retrieval and semantic routing.
Recommended default for most iNDX website pages.
---
## Level 3 — Graph-Aware QA
Use for:
- ontology-aware systems;
- research libraries;
- AI-native publishing systems;
- agent-facing systems.
Includes:
- knowledge_ids;
- chunk_ids;
- relationships;
- synthesis questions;
- audience;
- actionability.
Purpose:
Support graph traversal and multi-hop reasoning.
---
## Level 4 — Agent-Executable QA
Use for:
- operational agent systems;
- workflow execution systems;
- task automation systems.
Includes:
- executable workflows;
- procedural decomposition;
- tool references;
- operational constraints;
- execution hints.
Purpose:
Allow AI systems to execute tasks directly from QA structures.
---
## Level 5 — Economic And Policy-Aware QA
Use for:
- monetized systems;
- regulated systems;
- permissioned systems;
- agent-to-agent commerce systems.
Includes:
- access rights;
- economic terms;
- permissions;
- pricing;
- trust metadata;
- policy overlays.
Purpose:
Support programmable access and AI-native commerce.
---
# Recommended Default Schema
```json
{
"document": {
"title": "",
"slug": "",
"materialization_level": 2,
"generated_at": "",
"source_document": "",
"license": "https://creativecommons.org/licenses/by/4.0/",
"usageInfo": "https://indx.earth/wiki/license/"
},
"qa_pairs": [
{
"qa_id": "",
"question": "",
"answer": "",
"qa_type": "",
"intent": "",
"knowledge_ids": [],
"chunk_ids": [],
"source_chunks": [],
"entities": [],
"concepts": [],
"tags": [],
"audience": [],
"related_questions": [],
"actionability": {
"has_workflow": false,
"tools": [],
"processes": [],
"next_steps": []
}
}
]
}
```
---
# Corpus-Specific Guidance
## Static Websites
Recommended level:
Level 2
Focus on:
- discoverability;
- semantic retrieval;
- navigation;
- conceptual understanding.
Avoid excessive metadata complexity.
---
## Documentation
Recommended level:
Level 2 or 3
Include:
- workflows;
- prerequisites;
- dependencies;
- execution steps.
---
## White Papers
Recommended level:
Level 2 or 3
Focus on:
- conceptual synthesis;
- strategic implications;
- ontology relationships;
- research retrieval.
---
## Research Libraries
Recommended level:
Level 3 or 4
Focus on:
- graph traversal;
- semantic lineage;
- synthesis;
- evidence relationships.
---
## Monetized Knowledge Systems
Recommended level:
Level 4 or 5
Include:
- previews;
- permissions;
- value signaling;
- economic routing.
---
# Important Architectural Principle
The QA layer is:
semantic interaction infrastructure
—not merely FAQ generation.
Over time this layer may evolve into:
- executable workflows;
- semantic APIs;
- agent interaction contracts;
- retrieval orchestration layers;
- AI-native execution interfaces.
Design the QA layer with future graph and agent systems in mind.
---
# Final Output Requirement
Output a COMPLETE valid `qa.json` file.
Do NOT output:
- markdown commentary;
- explanations;
- partial fragments;
- pseudo-JSON.
The final output should be:
- production-ready;
- machine-readable;
- semantically grounded;
- suitable for direct ingestion into downstream systems.
# Chunk Coverage Validation
After QA generation completes:
1. Compare all chunk_id values in chunks.json
2. Compare all referenced chunk_ids in qa.json
3. Identify:
- orphaned chunks;
- over-referenced chunks;
- under-referenced chunks.
Recommended minimum:
- every meaningful chunk should have at least one QA reference;
- strategic chunks should have multiple QA references;
- synthesis chunks should connect across multiple chunks.
Possible exclusions:
- placeholders;
- decorative fragments;
- empty UI scaffolding;
- forms.
@@ -0,0 +1,398 @@
# Skill: Convert This Website Builder For A New Website
Human prompt to complete this skill:
Use this skill to convert a copied static website builder repo into a clean new website repo for a different domain, brand, content set, and deployment target.
# Overview
This skill resets a copied website-builder repo so it can become a new static public website without carrying over stale content, generated artifacts, old domain URLs, old analytics IDs, old semantic JSON, old navigation, old logos, or old deployment assumptions.
The goal is not only to clean visible pages.
The goal is to clean:
- source content;
- Hugo builder config and templates;
- semantic discovery and JSON-LD generation;
- AI/discovery scripts;
- generated public artifacts;
- deployment notes;
- contact form notes;
- future process instructions.
This is important because a copied builder can look clean in `/public/` while scripts and templates still regenerate the old website identity on the next build.
# Required Inputs
Before executing, identify:
- new repo root path;
- new public domain;
- new site title and brand name;
- new publisher/organization name;
- new Google Analytics measurement ID, if any;
- new favicon/logo/social preview image paths;
- source content directory to preserve, usually `/content/`;
- image asset directory to preserve, usually `/public/assets/images/`;
- root verification files to preserve, such as `BingSiteAuth.xml`;
- whether contact form/API work is in scope now or explicitly deferred;
- deployment model, for example static-only VM, Caddy edge proxy, Docker, object storage, or CDN.
# Preserve Rules
Preserve these unless the human explicitly says otherwise:
- `/content/` authored source content;
- `/public/assets/images/` approved image assets;
- root verification files such as `/public/BingSiteAuth.xml`;
- `/skills-scripts/` scripts and skill docs, after rebranding/updating;
- `/hugo-html-builder/layouts/` templates, after rebranding/updating;
- `/api/` source code, if contact/API work exists;
- README, changelog, task/workflow docs, after rebranding/updating.
Do not preserve generated artifacts just because they are currently in git. A copied repo often has generated output from the old site.
# Cleanup Targets
Remove old generated and copied-site artifacts, after confirming paths resolve inside the repo:
- `/public/index.html`;
- `/public/robots.txt`;
- `/public/sitemap.xml`;
- `/public/llms.txt`;
- `/public/agents.md`;
- `/public/skills.md`;
- `/public/ai-index.json`;
- `/public/data/`;
- old public section directories from the copied site;
- `/public/healthz/`;
- `/hugo-html-builder/public/`;
- stale `/hugo-html-builder/content/` mirror content;
- old copied-site archive content such as `_original/`, unless the human wants to keep it as an unpublished archive.
Keep `/public/assets/images/` and explicitly preserved verification files.
# Conversion Steps
## 1. Inventory The Repo
List the top-level repo directories and files.
Inspect:
- `README.md`;
- update/task notes such as `UPDATES.md`;
- `/content/`;
- `/public/`;
- `/hugo-html-builder/hugo.toml`;
- `/hugo-html-builder/layouts/_default/baseof.html`;
- `/hugo-html-builder/layouts/partials/semantic-discovery.html`;
- `/skills-scripts/build_ai_index.py`;
- `/skills-scripts/build_discovery_files.py`;
- `/skills-scripts/sync_content_to_hugo.py`;
- contact form files, if present.
Search for old identity references:
```bash
rg -n "old-domain|Old Brand|old-logo|old analytics ID|old section slug" .
```
Use the actual old domain, old brand, old logo filenames, analytics IDs, and old section names.
## 2. Establish A Cleanup Boundary
Write down what will be preserved and what will be removed before deleting anything.
Treat generated output as disposable.
Treat authored source content and approved assets as source of truth.
When deleting recursively, verify resolved absolute target paths are inside the repo root.
## 3. Clean Generated Output
Remove stale output and semantic data from `/public/`, while preserving approved assets and verification files.
Remove Hugo generated output and stale Hugo content mirror:
- `/hugo-html-builder/public/`;
- `/hugo-html-builder/content/`.
Do not remove Hugo layouts, static assets, config, or scripts.
## 4. Rebrand Hugo
Update `hugo-html-builder/hugo.toml`:
- `baseURL`;
- `title`;
- language settings if needed;
- URL mode if needed.
Update `hugo-html-builder/layouts/_default/baseof.html`:
- `<title>` behavior;
- meta description behavior;
- canonical link;
- Open Graph metadata;
- Twitter/X preview metadata;
- favicon and apple-touch-icon;
- social preview image;
- analytics script and measurement ID;
- logo image and alt text;
- nav links;
- footer copyright;
- contact form JS inclusion if needed.
Use one page `<h1>` in source content; use template/nav for repeated header/footer UI.
## 5. Rebrand Semantic Discovery
Update `hugo-html-builder/layouts/partials/semantic-discovery.html`:
- site URL assumptions;
- organization name;
- publisher/author identity if needed;
- page type rules;
- artifact path rules;
- license and usageInfo URLs;
- JSON-LD nodes.
Avoid hardcoding one old content section such as `community-summaries` unless the new site actually has that section.
Generic artifact path pattern:
- home page: `/data/open/pages/home`;
- normal page: `/data/open/pages/{section}/{slug}`;
- root normal page: `/data/open/pages/{slug}`.
## 6. Update Build Scripts
Update `skills-scripts/build_ai_index.py`:
- `SITE_URL`;
- `PUBLISHER`;
- `ORGANIZATION`;
- `LICENSE_URL`;
- `USAGE_INFO_URL`;
- title and description of the index;
- route rules for content pages;
- any old section-specific assumptions;
- any external resource helpers that mention the old brand.
Update `skills-scripts/build_discovery_files.py`:
- `SITE_URL`;
- `SITE_TITLE`;
- `PUBLISHER`;
- security contact;
- sitemap collection rules;
- robots sitemap URL;
- llms.txt summary;
- agents.md entry points;
- skills.md title;
- `.well-known` outputs if used.
Recommended `.well-known` files:
- `/public/.well-known/security.txt`;
- `/public/.well-known/agent-card.json`;
- optionally `/public/.well-known/agent-skills.json`.
Update `skills-scripts/sync_content_to_hugo.py`:
- generated section indexes;
- contact form injection;
- healthz page;
- URL special cases;
- old section assumptions.
## 7. Update Workflow Docs And Skills
Update:
- `README.md`;
- skill files in `/skills-scripts/`;
- deployment docs;
- contact form docs;
- any task/workflow notes that future agents will follow.
Replace old:
- domains;
- paths;
- usageInfo URLs;
- sitemap examples;
- section-index examples;
- deployment server names;
- Docker/Caddy assumptions;
- analytics IDs;
- brand names.
Keep parent-platform references only when they are intentionally part of the new site’s legal or explanatory content.
## 8. Structure Source Content
For every active authored markdown page in `/content/`, add or repair:
- YAML front matter;
- `document_id`;
- `title`;
- `date`;
- `slug`;
- `summary`;
- `tags`;
- `author`;
- `document_type`;
- `status`;
- semantic chunk markers.
Use chunk markers:
```html
<!-- CHUNK START
chunk_id="chk-UUID"
knowledge_id="kid-UUID"
chunk_label="human-readable-label"
knowledge_label="human-readable-knowledge-label"
-->
[content]
<!-- CHUNK END -->
```
Preserve author meaning and voice.
Do not publish layout notes such as "Page header", "Horizontal line", "Page footer", or logo filenames as visible page content if the template owns those elements.
Normalize headings:
- one page `<h1>`;
- major sections as `##`;
- subsections as `###`.
## 9. Privacy, SEO, Security, And Agent Readiness
Fold in these baseline website-readiness items:
- canonical URLs;
- Open Graph metadata;
- Twitter/X metadata;
- privacy policy;
- analytics/cookie disclosure or consent plan;
- `/.well-known/security.txt`;
- optional agent card/agent skills files;
- deploy-level security header docs;
- cache-control and compression docs;
- no-cache health check route;
- sitemap with `lastmod`, `changefreq`, and `priority`;
- visible mojibake cleanup.
Security headers are usually deployed at the hosting/proxy layer:
- Content-Security-Policy;
- Strict-Transport-Security;
- X-Content-Type-Options;
- Referrer-Policy;
- Permissions-Policy;
- frame-ancestors through CSP.
## 10. Local Verification
Run script syntax checks:
```bash
python -m py_compile skills-scripts/sync_content_to_hugo.py skills-scripts/build_ai_index.py skills-scripts/build_discovery_files.py skills-scripts/publish_hugo_output.py
```
Run content sync:
```bash
python skills-scripts/sync_content_to_hugo.py
```
Run Hugo if available:
```bash
cd hugo-html-builder
hugo --cleanDestinationDir
```
Then scan:
```bash
rg -n "old-domain|old-brand|old-logo|old analytics ID|mojibake-patterns" .
```
Check:
- no old domain in generated HTML/JSON/discovery files;
- no old logo references;
- no old analytics ID;
- no stale section paths;
- no visible mojibake;
- `public/` preserves only intended pre-build files before the final build;
- `BingSiteAuth.xml` or equivalent verification files are unchanged;
- Hugo content mirror matches source content;
- scripts compile.
# Contact Form Handling
If the copied builder includes a contact form, handle it after static-site conversion unless the human explicitly asks to do it now.
Check:
- frontend form action;
- JavaScript fetch path;
- API source;
- requirements file;
- environment variables;
- SMTP provider;
- captcha/anti-spam plan;
- deployment route from proxy to internal API port.
Do not treat a copied virtual environment as source of truth. Rebuild dependencies from a requirements file for deployment.
# Deployment Notes
Adjust deployment docs to the actual hosting model.
For a static-only Ubuntu VM with edge Caddy elsewhere:
- repo/build path might be `/srv/apps/{site-name}`;
- published web root might be `/srv/www/{domain}` or repo `/public/`;
- Caddyfile is managed on the edge server;
- contact API can run later on an internal port with a systemd service;
- edge Caddy routes the hostname and `/api/contact*` when ready.
Do not leave copied Docker instructions unless Docker is truly part of the new deployment.
# Completion Criteria
The conversion is complete when:
- old generated content has been removed;
- preserved files remain intact;
- source content has front matter and chunk markers;
- templates and scripts use the new domain and brand;
- process docs describe the new site and deployment model;
- no stale old-domain references remain except intentional parent-platform/legal references;
- sync script runs;
- Python scripts compile;
- Hugo build is either successful or clearly blocked by missing local Hugo installation.
# Final Response Template
Report:
- what was cleaned;
- what was preserved;
- what was rebranded;
- what source content was structured;
- what scripts/docs were updated;
- what verification passed;
- what could not be verified;
- any intentional old-brand references left in legal/parent-platform context.
+188
View File
@@ -0,0 +1,188 @@
"""Sync author markdown content into the Hugo HTML builder.
Run from anywhere:
python skills-scripts/sync_content_to_hugo.py
The root ``content/`` folder is the source of truth. This script copies those
markdown files into ``hugo-html-builder/content/`` and applies the small Hugo
rendering adaptations needed for this site.
"""
from __future__ import annotations
import re
import shutil
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
AUTHOR_CONTENT = REPO_ROOT / "content"
HUGO_CONTENT = REPO_ROOT / "hugo-html-builder" / "content"
CONTACT_FORM = """<form class="contact-form" id="email-subscribe" method="POST" action="/api/contact">
<label>Name
<input type="text" name="name" autocomplete="name" required>
</label>
<label>Email
<input type="email" name="email" autocomplete="email" required>
</label>
<label>Message
<textarea name="message" rows="5" required></textarea>
</label>
<label class="form-hidden">Company
<input type="text" name="company" tabindex="-1" autocomplete="off">
</label>
<button type="submit">Send</button>
<p class="form-status" role="status" aria-live="polite"></p>
</form>
"""
HEALTHZ_PAGE = """---
title: "Health Check"
layout: "healthz"
url: "/healthz/"
_build:
list: never
render: always
---
ok
"""
SECTION_INDEXES = {
Path("community-summaries") / "_index.md": """---
title: "CO+ Platform Summaries"
summary: "iNDX CO+ platform summaries organized by audience."
---
""",
Path("community-summaries") / "paddling" / "_index.md": """---
title: "CO+ Platform Summaries - Paddling"
summary: "iNDX CO+ platform summaries for the paddling industry audience."
---
""",
Path("community-summaries") / "home-health" / "_index.md": """---
title: "CO+ Platform Summaries - Home Health"
summary: "iNDX CO+ platform summaries for the home health audience."
---
""",
}
MOJIBAKE_REPLACEMENTS = {
"’": "’",
"‘": "‘",
"“": "“",
"â€\x9d": "”",
"–": "–",
"—": "—",
"…": "…",
"Â\xa0": " ",
"Â": "",
}
def read_text(path: Path) -> str:
return path.read_text(encoding="utf-8-sig")
def write_text(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(normalize_text(content), encoding="utf-8", newline="\n")
def normalize_text(content: str) -> str:
for broken, fixed in MOJIBAKE_REPLACEMENTS.items():
content = content.replace(broken, fixed)
return content
def remove_frontmatter_field(content: str, field_name: str) -> str:
return re.sub(rf"(?m)^{re.escape(field_name)}:\s*.*\n?", "", content, count=1)
def upsert_frontmatter_field(content: str, field_name: str, value: str) -> str:
field_line = f'{field_name}: "{value}"'
if re.search(rf"(?m)^{re.escape(field_name)}:\s*", content):
return re.sub(rf"(?m)^{re.escape(field_name)}:\s*.*$", field_line, content, count=1)
match = re.search(r"(?m)^slug:\s*.*$", content)
if match:
return content[: match.end()] + "\n" + field_line + content[match.end() :]
if content.startswith("---\n"):
end = content.find("\n---", 4)
if end != -1:
return content[:end] + "\n" + field_line + content[end:]
return content
def extract_slug(content: str, fallback: str) -> str:
match = re.search(r'(?m)^slug:\s*"?([^"\n\r]+)"?\s*$', content)
return match.group(1).strip() if match else fallback
def copy_author_markdown() -> None:
if not AUTHOR_CONTENT.exists():
raise FileNotFoundError(f"Missing source content directory: {AUTHOR_CONTENT}")
if HUGO_CONTENT.exists():
shutil.rmtree(HUGO_CONTENT)
HUGO_CONTENT.mkdir(parents=True)
for source in AUTHOR_CONTENT.rglob("*.md"):
relative = source.relative_to(AUTHOR_CONTENT)
target = HUGO_CONTENT / relative
write_text(target, read_text(source))
def build_homepage() -> None:
source = AUTHOR_CONTENT / "home.md"
if not source.exists():
return
content = read_text(source)
content = remove_frontmatter_field(content, "slug")
content = re.sub(r"<form>\s*", CONTACT_FORM + "\n", content, count=1)
write_text(HUGO_CONTENT / "_index.md", content)
def build_healthz() -> None:
write_text(HUGO_CONTENT / "healthz.md", HEALTHZ_PAGE)
def add_section_indexes() -> None:
for relative, content in SECTION_INDEXES.items():
directory = (HUGO_CONTENT / relative).parent
if directory.exists():
write_text(HUGO_CONTENT / relative, content)
def add_flat_community_urls() -> None:
community_root = HUGO_CONTENT / "community-summaries"
if not community_root.exists():
return
for page in community_root.rglob("*.md"):
if page.name == "_index.md":
continue
content = read_text(page)
relative_dir = page.parent.relative_to(HUGO_CONTENT).as_posix()
slug = extract_slug(content, page.stem)
url = f"/{relative_dir}/{slug}.html"
content = upsert_frontmatter_field(content, "url", url)
write_text(page, content)
def main() -> None:
copy_author_markdown()
build_homepage()
build_healthz()
add_section_indexes()
add_flat_community_urls()
synced = len(list(HUGO_CONTENT.rglob("*.md")))
print(f"Synced {synced} markdown files into {HUGO_CONTENT}")
if __name__ == "__main__":
main()