Compare commits

..

No commits in common. "2b41b336f948062e0c1a03ef65b405b9933a81a3" and "2e6c8b45e6c1a21b3bd52a245130bcc3825377ff" have entirely different histories.

16 changed files with 1 additions and 3159 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,3 +0,0 @@
# graphify
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.

View file

@ -1,34 +0,0 @@
{
"permissions": {
"allow": [
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push origin:*)",
"Bash(tea pr create:*)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Grep",
"hooks": [
{
"type": "command",
"command": "graphify hook-guard search",
"timeout": 10
}
]
},
{
"matcher": "Read|Glob",
"hooks": [
{
"type": "command",
"command": "graphify hook-guard read",
"timeout": 10
}
]
}
]
}
}

View file

@ -1 +0,0 @@
0.9.71

View file

@ -1,762 +0,0 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
/graphify <path> # full pipeline on specific path
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
If no path was given, use `.` (current directory). Do not ask the user for a path.
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
Follow these steps in order. Do not skip steps.
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```powershell
# Detect Python with graphify — uv/pipx-aware (fixes #831)
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
$GRAPHIFY_PYTHON = $null
function Find-GraphifyPython {
# 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically
if (Get-Command uv -ErrorAction SilentlyContinue) {
$uvDir = (uv tool dir 2>$null).Trim()
if ($uvDir) {
$py = Join-Path $uvDir "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 2. pipx install — 'pipx environment' respects PIPX_HOME automatically
if (Get-Command pipx -ErrorAction SilentlyContinue) {
$venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim()
if ($venvs) {
$py = Join-Path $venvs "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 3. Active venv / conda / pip-into-current-env
$pyCmd = Get-Command python -ErrorAction SilentlyContinue
if ($pyCmd) {
& $pyCmd.Source -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) {
return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim()
}
}
return $null
}
# Try to find the right Python (uv → pipx → active env)
$GRAPHIFY_PYTHON = Find-GraphifyPython
# Not found — install then re-detect
if (-not $GRAPHIFY_PYTHON) {
if (Get-Command uv -ErrorAction SilentlyContinue) {
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
} else {
pip install graphifyy -q 2>&1 | Select-Object -Last 3
}
$GRAPHIFY_PYTHON = Find-GraphifyPython
}
# Save interpreter path — all subsequent steps read this.
# `Out-File -Encoding utf8` always writes a BOM on Windows PowerShell 5.1 (utf8NoBOM
# only exists from PowerShell 6), and that BOM rides into the saved path, so the hook
# rebuild fails with WinError 123 (#3028). WriteAllText with an explicit BOM-less
# encoding writes the bytes POSIX writes, and adds no trailing newline.
$Utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_python'), [string]$GRAPHIFY_PYTHON, $Utf8NoBom)
# Save scan root so `graphify update` (no args) knows where to look next time.
# INPUT_PATH is captured through a single-quoted (literal) here-string, never
# substituted directly into the command line: an unquoted bareword argument
# substituted here would let a malicious path (a stray `;`, `|`, or `$(...)`)
# execute as script code the moment this line runs.
$InputPathRaw = @'
INPUT_PATH
'@
[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_root'), (Resolve-Path $InputPathRaw.Trim()).Path, $Utf8NoBom)
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent block, run Python through the saved interpreter — `& (Get-Content graphify-out\.graphify_python)` in place of a bare `python3` — so every step uses the interpreter that actually has graphify.**
### Step 2 - Detect files
```powershell
@'
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
print(f'Detected {result["total_files"]} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```powershell
@'
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('INPUT_PATH'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
print('No code files - skipping AST extraction')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
#### Part B - Semantic extraction (parallel subagents)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
```powershell
@'
import json
from pathlib import Path
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
```powershell
@'
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
# Only content files go to semantic extraction. Code is already covered structurally
# by the AST pass (Part A); flattening every category here makes subagents re-read
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
else:
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
**Step B2 - Dispatch ALL subagents in a single message**
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```powershell
$PROJECT_ROOT = (Get-Location).Path # cwd — where Part C globs graphify-out\ (NOT .graphify_root/scan dir, #1392)
# Then for chunk N: $CHUNK_PATH = Join-Path $PROJECT_ROOT "graphify-out\.graphify_chunk_0N.json"
```
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```powershell
@'
import json, glob
from pathlib import Path
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text(encoding="utf-8"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
```powershell
@'
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding="utf-8").splitlines() if line]
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH')
print(f'Cached {saved} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```powershell
@'
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Clean up temp files: `Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```powershell
@'
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
```powershell
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 4.5 - Graph health check (read-only integrity gate)
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
```powershell
@'
import json
from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
('missing_endpoint_edges', 'missing-endpoint edges'),
('self_loop_edges', 'self-loop edges'),
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
) if summary.get(k, 0)]
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```powershell
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
# Re-export so graph.json nodes carry the curated community_name (#2490).
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
# if it still refuses, surface the guard message - do not force past it.
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
print('Report updated with community labels')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```powershell
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```powershell
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```powershell
@'
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
# so the on-disk manifest is portable across clones/machines and a later --update
# matches cached files instead of missing every one (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
# a detected file whose chunk failed or was omitted must stay unstamped so the
# next --update re-queues it, otherwise it is marked done and its content is lost
# forever (#2015). This mirrors the library extract path exactly
# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
# raw corpus. Code files are always stamped (AST is deterministic); only semantic
# types are gated on output.
from graphify.cli import _stamped_manifest_files
_corpus = detect.get('all_files') or detect['files']
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding="utf-8"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
'@ | & (Get-Content graphify-out\.graphify_python) -
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json
Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction SilentlyContinue | Remove-Item -Force
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```powershell
if (-not (Test-Path graphify-out\.graphify_python)) {
$GRAPHIFY_PYTHON = $null
$graphifyCmd = Get-Command graphify -ErrorAction SilentlyContinue
if ($graphifyCmd) {
# The interpreter that owns the graphify entry point sits next to it
# (<env>\Scripts\python.exe for uv tool, pipx, and venv installs).
$py = Join-Path (Split-Path $graphifyCmd.Source) "python.exe"
if (Test-Path $py) { $GRAPHIFY_PYTHON = $py }
}
if (-not $GRAPHIFY_PYTHON) { $GRAPHIFY_PYTHON = "python" }
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
& $GRAPHIFY_PYTHON -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
}
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```powershell
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
## Troubleshooting
### PowerShell 5.1: Vertical scrolling stops working
If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue:
1. **Upgrade graphify**: `pip install --upgrade graphifyy`
2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly
3. **Reset your terminal**: close and reopen PowerShell
4. **Skip Leiden**: uninstall its backend (`pip uninstall graspologic` on Python < 3.13, `pip uninstall graspologic-native` on Python 3.13+) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.

View file

@ -1,56 +0,0 @@
# graphify reference: add a URL and watch a folder
Load this when the user ran `/graphify add <url>` or passed `--watch`. Neither is part of the default build.
## For /graphify add
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
try:
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
print(f'Saved to {out}')
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
---
## For --watch
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
$(cat graphify-out/.graphify_python) -m graphify.watch "$(cat graphify-out/.graphify_root)" --debounce 3
```
This watches the same folder graphify extracted, read from the trusted `graphify-out/.graphify_root` that Step 1 resolved - there is no path to substitute, so a scan root containing shell metacharacters can never be re-interpreted here. Behavior depends on what changed:
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
Press Ctrl+C to stop.
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.

View file

@ -1,87 +0,0 @@
# graphify reference: extra exports and benchmark
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag.
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
graphify export neo4j
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
```
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag)
**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact:
```bash
graphify export falkordb
```
**If `--falkordb-push <uri>`** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth:
```bash
graphify export falkordb --push falkordb://localhost:6379
```
Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
```bash
$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`:
```json
{
"mcpServers": {
"graphify": {
"command": "<absolute path from: cat graphify-out/.graphify_python>",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
graphify benchmark
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.

View file

@ -1,70 +0,0 @@
# graphify reference: extraction subagent prompt
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```

View file

@ -1,46 +0,0 @@
# graphify reference: GitHub clone and cross-repo merge
Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph.
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
**Single repo:**
```bash
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
# Use LOCAL_PATH as the target for all subsequent steps
```
**Multiple repos (cross-repo graph):**
```bash
# Clone each repo, run the full pipeline on each, then merge
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
# Run /graphify on each local path to produce their graph.json files
# Then merge:
graphify merge-graphs \
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
--out graphify-out/cross-repo-graph.json
```
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
**Multiple local subfolders (monorepo or multi-service layout):**
The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path:
```bash
graphify extract ./core/ # → ./core/graphify-out/graph.json
graphify extract ./service/ # → ./service/graphify-out/graph.json
graphify extract ./platform/ # → ./platform/graphify-out/graph.json
# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set
# Then merge at the project root:
graphify merge-graphs \
./core/graphify-out/graph.json \
./service/graphify-out/graph.json \
./platform/graphify-out/graph.json \
--out graphify-out/graph.json
```
Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate.

View file

@ -1,33 +0,0 @@
# graphify reference: commit hook and native CLAUDE.md integration
Load this when the user asked to install the post-commit hook or wire graphify into a project's CLAUDE.md.
## For git commit hook
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
```bash
graphify hook install # install
graphify hook uninstall # remove
graphify hook status # check
```
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
If a post-commit hook already exists, graphify appends to it rather than replacing it.
---
## For native CLAUDE.md integration
Run once per project to make graphify always-on in Claude Code sessions:
```bash
graphify claude install
```
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
```bash
graphify claude uninstall # remove the section
```

View file

@ -1,311 +0,0 @@
# graphify reference: query, path, explain
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
Two traversal modes - choose based on the question:
| Mode | Flag | Best for |
|------|------|----------|
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8')
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392)
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
subgraph_edges = []
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
subgraph_edges.append((node, neighbor))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_edges.append((n, neighbor))
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
"
```
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting):
- `useful` — the cited nodes answered the question well (they become *preferred sources*).
- `dead_end` — the question/path led nowhere; don't re-derive it next time.
- `corrected` — the saved answer was wrong; `--correction` records what was right.
At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing.
---
## For /graphify path
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```

View file

@ -1,52 +0,0 @@
# graphify reference: transcribe video and audio
Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command.
**Step 2 - Transcribe:**
```bash
export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported)
export GRAPHIFY_WHISPER_PROMPT="<the one-sentence domain hint you composed in Step 1>"
$(cat graphify-out/.graphify_python) -c "
import json, os, sys
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper
# print progress to stdout, which would otherwise corrupt the JSON file (#1392).
Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\")
print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr)
"
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, `export GRAPHIFY_WHISPER_MODEL=<name>` (it must be exported, not just assigned) before running the command above.

View file

@ -1,210 +0,0 @@
# graphify reference: incremental update and cluster-only
Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file.
## For --update (incremental re-extraction)
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
'files': r.get('new_files', {}),
'all_files': r.get('files', {}),
'total_files': r.get('new_total', 0),
'total_words': r.get('total_words', 0),
'skipped_sensitive': r.get('skipped_sensitive', []),
'needs_graph': True,
}, ensure_ascii=False), encoding=\"utf-8\")
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
"
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.build import build_merge
from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else
# False. Without it a --directed --update silently rebuilds undirected and collapses
# reciprocal A<->B edges (#1392).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
merged_out = {
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
'edges': [
# Explicit source/target last so they win over any stale attrs in d.
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
for u, v, d in G.edges(data=True)
],
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
# and new_extraction (build_merge combines them). Falling back to
# new_extraction only would silently drop prior-run hyperedges (#801).
'hyperedges': list(G.graph.get('hyperedges', [])),
'input_tokens': new_extraction.get('input_tokens', 0),
'output_tokens': new_extraction.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest so next --update diffs against today's state, not the
# prior run's baseline (prevents ghost-node reports on subsequent updates).
# root= matches the build_merge call above so the manifest keys stay relative to
# the scan root — portable across clones/machines, so --update keeps matching
# cached files instead of missing every one after a move (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output
# THIS run (new_extraction is this run's fresh extraction, read above before the
# merge overwrote the file): a changed doc whose chunk failed must stay unstamped
# so the next --update re-queues it, otherwise it is marked done and its content
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
G_new = build_from_json(new_extract, directed=IS_DIRECTED)
if old_data:
G_old = json_graph.node_link_graph(old_data, edges='links')
diff = graph_diff(G_old, G_new)
print(diff['summary'])
if diff['new_nodes']:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
Clean up after: `rm -f graphify-out/.graphify_old.json`
---
## For --cluster-only
Skip Steps 1–3. Re-run clustering on the existing graph:
```bash
graphify cluster-only .
```
`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual.

2
.gitignore vendored
View file

@ -32,5 +32,3 @@ server/clips/
# skills # skills
graphify-out/ graphify-out/
# skill links into .agents/skills (installed from skills-lock.json)
.claude/skills/design-taste-frontend

274
TODO.md
View file

@ -1,274 +0,0 @@
# TODO
- Instructions for this document: update it as things are completed, moving items from TODO to Done under the same category. Develop content here based on conversations. Leave the categories blank in Part 1: TODO when you are moving items out of them to Done.
- Status: everything up to v1.8.3-video-mgmt is tested and deployed. PR #14 (branch `audit`, v1.9.0 to v1.9.4-audit) was merged into main on 2026-09-29 (adc88e5). Branch `content-display` was merged as PR #15 (v1.9.5 to v1.9.11, 2026-09-29) and PR #16 (v1.9.12 to v1.9.14, 2026-09-30, c76df02). All of it is deployed and checked in a browser (2026-09-30). The design overhaul (PR #18, v1.10.0 to v1.10.2) and the revised palette (PR #19, branch `palette-test`) were merged into main on 2026-09-30 (6f86a11); not deployed yet. Branch `page-updates` (v1.10.3 to v1.10.6) was merged into main as PR #20 on 2026-10-01 (3e4a725); not deployed yet. Branch `page-fixes` (v1.10.7 to v1.10.10) was merged as PR #21 on 2026-10-01 (0bb4b86); not deployed yet. Back up the database before deploying (migrations 056 to 059: 056 and 057 rebuild content_blocks, 058 page_sections, 059 recreates v_events). Branch `audit-3` (v1.11.0-audit) is open as PR #22; branch `audit-ui` (v1.11.1-audit, on top of it) as PR #23; branch `newsletter-layout` (v1.11.2-newsletter, on top of that, migration 060) as PR #24.
---
# Part 1: TODO
## Pages
## Sections
## Page Features
## Accessibility Features
- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner.
## Mobile
## Page Editing
## Admin
## Data
## Navigation
## Tools
## Production cleanup
## Audits
## Future
- Timeline vine/tree SVG (you'll provide it); until then the timeline is solid teal dots on a teal rail, one color throughout.
- Legal check of the Privacy Policy and Terms for NGU's state and nonprofit status (wording read 2026-09-28, fine for now).
- Enforce the Content-Security-Policy after watching its reports on the server (`journalctl -u ngu-api | grep csp`, `docs/security-headers.md`).
- Potentially make new vertical nav circle a sun svg later on.
- Poetry Builder, need to import the metaphysical bible dictionary and virtue list.
---
# Part 2: Done
## Feature updates (branch `feature-updates`, v1.13.x, no PR yet; migrations 069 to 071, back up the database before deploying)
- [x] **Partner cards, logo first**: the organization cards (Partners, Ministries) lead with the logo, large and centered, the name under it as a small line (still the heading); with no logo, its initials. Cards sit raised with a shadow and an accent top edge.
- [x] **Frame a photo on upload**: photo fields (people, event photo and card background, blog cover and guest photo, hero photos, link card pictures, block images, schedule graphics and map images; not logos) open Frame the photo for a JPEG, PNG or WebP: drag (or arrow keys) to place, zoom slider, a shape menu (the field's own first; As uploaded keeps the photo's). The framed part is what uploads; Upload as is skips. Nothing stored beside the picture, so re-framing is uploading again.
- [ ] Check in a browser: the partner cards with and without logos (light, dark); framing a portrait into a square and a wide photo into 16:9, Upload as is, Cancel, and a PNG keeping its transparency.
- [x] **Content blocks: Shown in** (migration 071): The page, The card only, or The card and the page. A card block used to show on the page too without saying so; every existing card block became "both", so nothing moved. Pages no longer print card paragraphs separately; a "both" block comes with the page's blocks, in its place in the list.
- [ ] Check in a browser: an event with a "both" paragraph (on its card and page) and one with "card only" (card, not page); an organization, team and person page still show their text.
- [x] **Group pages**: the facts at the top sit in a framed card (City, Part of <name> Region, Ministry, Meets, Since, tags); email buttons go to the link's URL, not its label (`splitLinks` took the label); every website and email row is listed with its own label, not only the first.
- [x] **Tags** (migration 070): Data → Tags (Online and In-Person to start) replace the Online checkbox on organizations and events. Records ticked Online got the Online tag (nothing got In-Person). The tag with URL ID `online` still makes an event online (calendar filter, place line, search data) through `v_events`. Tags show on the record's page and on group entries in the Community map list and grid; the map no longer keeps online groups off their state's tile.
- [ ] Check in a browser: a group page's facts card (light, dark, reading mode), two emails and two websites, tags on a group and an event, the Tags list in Data, and the calendar's Online filter still working.
- [x] **Schedule presentation** (digital signage): an event page's schedule block has a Present button (everyone) opening `/events/<id>/present` in a new tab. A setup screen picks the days and entries and the seconds for each kind of slide (day overview, entry spotlight with the person's photo and name beside the entry, graphics, map images; 0 leaves one out); Play goes full screen and loops, the parts of each slide animating in, a bar showing the time left. The settings are in the address (bookmark it on a signage screen; `play=1` skips setup). Arrows step, Space pauses, S returns to setup; the screen is kept awake where the browser allows. Not by the clock: it loops what was picked.
- [x] **Map image on schedule entries** (migration 069): an entry's own map picture, shown in its fold-out in place of the Google map (the "Open in Google Maps" link stays when a place is set) and as a slide in the presentation.
- [ ] Check in a browser: the Present button, setup, each slide kind (light and dark, a long day of 9+ entries in two columns), full screen on the signage device, and a map image in the fold-out.
- [x] **Group map** (Community): hovering a state outlines it in ink while its region stays lit; the list puts each region's groups under their state's subheading, each entry a raised card; the region's list of states is gone from the list (its map note stays); the list no longer scrolls on hover, only on click (a state goes to its subheading, or its region when it has no groups; a legend region to that region).
- [x] **Side nav pill** too tall when the window narrows (Community): the pill (straight sides, round ends) was sized as an ellipse, about three times the list's height; it's sized as the pill now.
- [x] The "Hide past events" button was clipped at the bottom when it grew on hover: the event cards' root wrapper was `overflow-hidden`; it is `overflow-x-clip` now (the carousel still can't spill sideways).
## v1.13.1-data (branch `data`, merged as PR #28, 2026-10-06, 970730d; migrations 065 and 066, the consolidated baseline, then 067 and 068, back up the database before deploying; not checked in a browser yet)
- [x] Newsletter: a new draft's Coming Up "Pick from" showed "events no longer exists". Events is that select's blank choice, so new drafts now leave the source blank and older drafts' `events` loads as blank.
- [x] **Frame from a video**: a video featured card's Image field has "Frame at" (a typed time, prefilled from the link's `t=`); the server takes that one frame with yt-dlp and ffmpeg and saves it to `/uploads/thumbnails/` as the card's picture (`POST /api/admin/video-frame`, editors and up). Choosing any other picture already worked through the same field. Not tested end to end yet: needs yt-dlp, which is on the VPS but not the dev machine.
- [x] **Plausible reports to Discord** (migration 065): daily (yesterday) and weekly (Mondays, last 7 days with the change from the week before), each switched on in Panel → Site settings → Reports; sent at 8:00 America/Chicago. Needs `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` on the ngu-api service (`PLAUSIBLE_URL` if Plausible isn't on 127.0.0.1:8000). Try it with `node src/analyticsReport.js daily`. Tested with a stubbed Plausible only.
- [x] **Captions for uploaded videos** (migration 066): video blocks have a Captions field and the hero a Video captions field, each taking a WebVTT (.vtt) upload (kept as is, in `/uploads/captions/`), drawn as `<track kind="captions" default>` on a video file (WCAG 1.2.2). Embeds bring their own. Needs `text/vtt vtt;` in nginx's mime.types if it isn't there (`docs/media-uploads.md`, step 5).
- [x] **Migrations consolidated** into `066_schema.sql` (generated from the live v66 schema, checked identical: 136 objects, every table's columns) and `066_seed.sql` (single rows, event scopes, home sections, the five site pages and their sections, the Musicians tag; the hero words, paths, stats and the Organization address and tax ID are no longer seeded). A database at v66 skips both; one below v66 is refused. **Deploy order:** production is below v66, so deploy 33be618 (the last commit with the old files) first, let it migrate to v66, then deploy this.
- [x] **Partners section picks its organizations** (migration 067): the organization cards preset (Community → Partners) has "Cards: list" (Partners by default, Ministries, or both, every published, listed one by name) and an optional hand-picked "Cards: organizations" list (partners or ministries, in order, published ones, listed or not) that replaces it. Ministry cards link to their website only (no page). `/organizations` now takes `kind=ministry` and `ids=`.
- [x] **Links/redirects** (migration 068): Data → Links/redirects makes short links, `/go/<URL ID>`, for the newsletter. Each click is counted (Clicks, Last click on the list), sent to Plausible as a pageview of `/go/<URL ID>`, and redirected with the link's optional UTM tags added. Editors and up. `docs/redirects.md`.
- [x] Newsletter: Save as a new draft beside Save draft; a Title color; every part color is a color picker (any hex, or none) instead of the palette dropdown.
- [x] Region pages no longer show the raw domestic/international scope.
- [x] Keywords question (2026-10-04): Google has ignored `<meta name="keywords">` since 2009, so nothing to add. What counts is the words on the page: titles, headings and descriptions, which `pageMeta.js` already fills per page. The Google side is Search Console, which shows the searches the pages appear for.
## Pages and Data (branch `data`, merged as PR #27, v1.13.0-data, 2026-10-04, 3b45944; migrations 062 to 064, back up the database before deploying; not checked in a browser yet)
- [x] **Musician directory, as people tags** (migration 062): Data → People tags lists what people can be tagged as (Musicians seeded); a person's Directories repeater tags them, and their new Specialty line ("Vocals, piano · Gospel, folk") shows on their tile in a directory, with their links in the details panel. A People directory section preset (Community, Resources, Organization) shows a tag's first 12 and links to its full page, `/directory/<tag>` (eg. `/directory/musician`), titled and indexed like any page. Another directory (Speakers) is a new tag, no code.
- [x] **Ministry organizations** (migration 063): a new organization kind for Unity ministries. A group picks its ministry (Group → Ministry), and its page says "Ministry: <name>", linked to the ministry's website link when it has one. Ministries have no page, list, sitemap entry, timeline entry or 404 suggestion on the public site, and aren't offered where a record links to its organization (event hosts, teams, awards, roles, home organization, featured cards, timeline).
- [x] **Organization contacts and the recipient export** (migration 064): Data → Contact types holds the roles you make (none seeded); each organization has a private Contacts repeater (type, name, email, phone; editors and up only). Tools → Newsletter → Recipients filters them by contact type, organization kind, region (the region and its groups) and published, previews the matches and downloads a CSV for Mailchimp (Email, First Name, Last Name, Phone, Organization, Kind, Region, Contact type). A type still in use can't be deleted.
- [ ] Check in a browser: tag a person, the directory section and page (light, dark, reading mode), a group's ministry line, contacts on an organization (as a viewer too), the export and its CSV.
## Accessibility, second round (branch `accessibility`, merged as PR #26, v1.12.1-accessibility, 2026-10-03, 07e56bf; not checked in a browser yet)
- [x] **Reading mode rebuilt** (`src/components/ReaderView.tsx`): the page as text only, headings, paragraphs, links and pictures with a description, in one column, with a line of links to the site's pages at the top. No header, footer, backdrop, buttons, cards or forms; the accessibility button stays, to turn it off. The real page still renders, hidden, and the reader writes out what it drew, again whenever it changes, so every page works without a version of its own. A card that is one link gives its heading the link; a button that opens something (a person's tile, a schedule row) keeps its words as a line; carousel copies and decorative pictures (empty alt) are left out.
- [x] **Color blind modes cover the whole site**: each mode now replaces all three color families (teal, green, amber), not just green, with sets picked by simulation (each family's darkness can differ, since a red-green color blind eye sees one blue to yellow line plus light and dark). The closest pair goes from 11.4 to 27.9 (protanopia), 19.5 to 24.7 (deuteranopia) and 6.4 to 21.1 (tritanopia); every theme token still meets 4.5:1 in light and dark mode. The theme tokens, the backdrop circles, the side nav circle, the header and menu, the hero, the stats band and data colors all follow (`--pal-*` variables in index.css, `SWAPS` in color.ts).
- [x] **Reading mode spacing and width**: words from parts the page draws on their own lines (a name above a title, a flex row's items) no longer run together; the column is 60rem (was 42rem) and headings are bold, in the display face.
- [x] **Front page in reading mode**: bands the reader can't read well draw a text version of their own (`useReadingMode()`): the numbers, one line each ("1,200+ Members"), no longer stuck at 0 (the count waited for the band to scroll into view, which the hidden page never does; reduced motion now shows them at once too); the calendar, the next six weeks from today as a list (date, linked title, time, type, place) on any page that has one; the featured cards, each a linked heading with its words, a video card linking to its video. The countdown is left out, since the retreats band shows that event.
- [x] **Reading mode, every page and section** (audited section by section): the reader itself now reads an icon-only link's aria-label, puts a card's link on its first line or picture when it has no heading, gives each item of a row of facts or link buttons its own line, keeps line breaks, skips what CSS hides (a blog post's print-only footer), turns a form into one line saying it can't be used there, shows empty table cells as "-", and keeps section and heading ids so #links land (side nav, a post's contents). What it can't read draws its own text version (`useReadingMode()`): the hero (its words, buttons, every slide's caption, livestream and video links), the pathfinder (every path and its actions), the front page history (linked entries), event lists (every event, past ones too, no carousel), the org lists and groups map (every region and all its groups, linked), the history timeline (every year open, upcoming too), schedules (every day, fold-outs included), people tiles (everyone, with their details) and videos (a link). Heading levels fixed where cards repeated their section's level; org names are linked headings; Team pages lose their doubled "Members"; Giving links the treasurer's email.
- [x] **Local groups map fits a phone**: it scales to the column's width instead of holding 34rem and scrolling sideways.
## Navigation (branch `accessibility`)
- [x] **No fixed back links on record pages**: a group, region or partner page no longer ends its facts line with "All groups" (and so on), and a team page no longer says "Back to <org>" (its "A team of" link stays); records are reached from many pages, so the browser's back is the right way back. Not-found pages keep their link, having nowhere else to send a visitor.
- [x] **Side nav label on its circle, dark mode**: the lit label was its accent mixed halfway to white, which for the deep teal (Unity Regions) left 4.2:1 on a circle of the same teal. Labels now use `--nav-text-mix` (30% in dark mode): 6.8:1 or better for every accent.
## Accessibility (branch `accessibility`, merged as PR #25, v1.12.0-accessibility, 2026-10-03; not checked in a browser yet)
- [x] **Plausible analytics**, self-hosted behind nginx at `/pa/`: the API adds its script to every page (`analyticsTag`, `server/src/pageMeta.js`), counting under site.json's url hostname, so dev and live report separately.
- [x] **Accessibility panel:** the switches' knob stays in its track (an absolute child of a `<button>` with no `left` started from the centered content). The panel comes after its button in the page, so Tab goes into it, and opens on its first switch; each switch reads its help line.
- [x] **Reading mode** is now the page as plain text: one 42rem column, ink on white (or white on near-black in dark mode), every color, background, border, shadow, picture, video, map and decoration gone, controls outlined, links underlined, no motion (JS scrolls, the hero slideshow and the stats count-up too, `src/lib/motion.ts`). A picture or video with a description leaves "Image: ..." in its place (`data-reading-alt`, set by the panel).
- [x] **Color blind mode** (Protanopia, Deuteranopia, Tritanopia, Monochrome), a select in the panel that reloads the page. Simulated with the Machado (2009) matrices, green and amber blur together for protanopia and tritanopia, so there the green family becomes violet (same contrasts; the closest pair of families goes from 11.4 to 17.4 and from 6.4 to 21.6 in CIELAB). For deuteranopia the palette already stays apart and is kept. In all three, a color picked off the palette snaps to the nearest palette shade. Colors from the database are swapped as they arrive (api.ts, never under /admin), colors from code through `visionColor` (color.ts), CSS through the `--green-*` variables (index.css). Monochrome is a grayscale filter on the root.
- [x] **Audit fixes:** the fixed header no longer covers what's focused or jumped to (`scroll-padding-top` from `--header-h`, now on the root; the per-section offsets it replaces are gone). A new page moves focus to its content; closing the phone menu returns focus to its button; Escape closes a desktop dropdown. In-page jumps (section nav, a post's contents, #links) move focus with the scroll (`jumpTo`, `src/lib/focus.ts`). Carousel arrows stay focusable at the ends. Calendar: canceled bars say so to screen readers; a day's list takes focus and gives it back to the day on Close. Thank-you messages, a started video, the livestream and a schedule map take focus (`focusOnMount`); closing a person's details returns to their tile. The countdown's ticking digits are out of its link name, and its title wraps instead of being cut. Wide tables scroll from the keyboard. Map tiles with groups are buttons for the keyboard. Request form radio errors and required fields are tied to their inputs. Admin: field errors, help and required marks reach screen readers; search boxes, the role select, the color picker and the two picker dialogs have names; the section nav's error dot says "needs attention".
- [x] **Calendar window** (from the third audit): the calendar asks `/events` for only the six weeks on screen (`?from=&to=`, undated events and open-ended series included), keeps the last month up while the next loads, and fetches from the month's end on only when a month is empty, to offer the jump to the next event. Carousels ask for only their 12 most recent past events (`?past=12`); the grid's past list still pages through them all.
- [x] **Event photo** (migration 061): events have two pictures. **Event photo** (16:9, with a description for screen readers) is shown whole at the top of the event's page, as the front page's featured event (its box is 16:9 now, was 16:7), on featured cards, in newsletter picks and as the share preview. **Card background** is only the faded background of the event's card again. Each event's photo starts as its card background, so nothing changes on screen until one is replaced. Sizes for both are in `Data Requirements.md`.
- [ ] Check in a browser, light and dark: the panel (Tab order, knobs, Escape), reading mode on the home page, a blog post and an event, each color blind mode (backdrop circles, side nav, footer links, event colors), the calendar paging months, the jump to the next event and the filters, a carousel's past events, keyboard focus after page changes and section jumps, the phone menu.
## Page fixes (branch `page-fixes`)
- [x] **Details & Contact is plain blocks** (migration 058): the address, tax ID and email preset is gone; Organization's Details & Contact section holds them as blocks (the address, the nonprofit line with the tax ID, an email button), edited like any section.
- [x] **Header dropdowns close after a click**: they opened on hover or on any focus inside, and a click leaves focus on the link, so the menu stayed open after the pointer left. Now only keyboard focus (:focus-visible) opens them besides hover.
- [x] **A circle behind the side nav**: a solid circle with a slight drop shadow in the light shade of the section being read (teal, green or amber; their darkest in dark mode), easing from one to the next as you scroll; each entry also takes its section's color when hovered or lit, centered on the list, which the nav's text reads on in both modes. It sticks with the nav as the page scrolls or grows, stays centered on the list however wide the screen, sits a little left of the list's center but never left of the "On this page" heading's center (centered on the whole list once its titles reach further right), shows above and below the list (clipped sideways only), keeps its right edge inside the nav column so it never covers content (a narrower window slides it off the screen's left edge instead), and, with the whole nav, sits in front of the section lines; "On this page" starts level with the first section's title (lower if the circle needs room to start a few pixels below the first line), and once scrolling the nav sticks just under the header, while its circle grows into a sun in the corner: centered on the header's bottom left, so a quarter of it shows, big enough to reach past the list (never wider than the nav column), easing between the two. Held narrower than that by the window, it stays centered on the header's edge (so below the header it only curves inward) and becomes a quarter ellipse, as tall as it takes to cover the list. At rest it keeps 16px clear of the section's edge and becomes an ellipse too for a tall list. Both cover the longest list a page may have, 10 sections of two-line titles; for that, the side nav now shows from 1536px (2xl) up instead of 1408px (narrower, the list is as wide as its column and nothing inside it can cover it).
- [x] **Side nav no longer shifts the sections**: it sits in the left margin beside the content instead of taking a column, so sections stay centered where they'd be without it. It shows on screens 1536px (2xl) wide and up, where the margin fits it and its circle (titles wrap onto a second line); narrower, the header's dropdowns list the sections.
## Page editors, navigation and tools (branch `page-updates`, after v1.10.5)
- [x] **Page editors with sections** (9daf7b1, migration 056): Pages → Retreats, Community, Resources, Organization, History. Each page is a list of sections, each with a title (30 characters at most, so it fits the side nav; the editor says so), URL ID, blurb, accent, its own content blocks, and an optional preset drawn under the blocks: Community blog, local groups map, Unity Regions list, partner cards (Community); event carousel or grid with scope, type and first view (Retreats); timeline (History); address, tax ID and email (Organization). Every page was seeded as it looked. Organization's Details & Contact is its third section; Volunteering became a heading, paragraph and link buttons at the end of Leadership. The Community blog's settings (slots, pinned posts, feeds) are in the Community editor; its heading and blurb are its section's. The header dropdowns, footer site map and side nav follow each page's sections. The admin engine now saves nested collections to any depth (page, sections, blocks, items).
- [x] **Timeline entries under Data** (4a1d6fd).
- [x] **Navigation** (4a1d6fd and this branch): the footer site map spans the full width; section divider lines run behind the side nav; the side nav fits 30-character titles; front page section headings fit about 60 (noted in its editor); Home has no dropdown in the header.
- [x] **Newsletter drafts** (migration 057): Tools → Newsletter saves drafts (title, intro, blocks, picks, footer) to open again later, adds content blocks written for the issue (those an email can show), an editable footer (blank: the site's name and address; no unsubscribe link, Mailchimp adds one), and Post as blog post, which makes an unpublished post (intro, blocks, then each section's picks as link cards) and opens it in the post editor.
## Entity pages and pages (branch `page-updates`)
- [x] **Cleanup** (43797f3): removed the old-data fixes, since nothing before them was public: the /leadership redirect, the "ngu-" browser key move, the boot-time image sorter, and emoji path icons (migration 055 turns the seeded emoji into named icons). Kept on purpose: OrganizationDetail's redirect from a wrong-kind URL (/groups/x for a region) to the right one, and the migrations' own data rewrites (they already ran).
- [x] **Organization page editor** (43797f3): Pages → Organization page. Mission blocks; Leadership heading, blurb and blocks (eg. a People block for the Board of Trustees, then one for the Retreat Team, in that order); Volunteering title, blurb and links under the leadership. The page reads only from this editor now (not the NGU organization record).
- [x] **Navigation** (ed0f120): the second strip is gone; each top link drops down its sections on hover or focus. Retreats, Community, Resources, Organization and History have a sticky "On this page" column from lg up (the admin editors' SectionNav). Home's sections everywhere follow the front page's visible bands, in order, under their headings. Resources now comes before Organization in the nav and footer.
- [x] **Mobile** (a907a47, 8d319bc): surveyed every public page at 320 to 430px and fixed what was cut off or hard to use. Menu scrolls to its top when tall; page titles and the hero headline size down and wrap; hero buttons stack, slide controls are 40px; the retreat carousel has phone-sized cards, arrows beside the dots, 40px dots and swipe; the narrow event card's logo row restored; people tile details stay on screen and tiles keep 60% of their width; the community map scrolls sideways at a readable size; group and org cards, schedule rows, stats numbers, timeline rail cards and the banner fit; long emails wrap; tap targets 40px; the accessibility panel sits above the privacy notice.
- [x] **Accessibility button** (177a650): a button at the bottom right of every public page opens two switches. Dyslexia-friendly font (OpenDyslexic, self-hosted, downloaded only when chosen); Reading mode (no background circles, motion or shadows, one column, larger text, underlined links). Remembered in the browser, applied before the first paint.
- [x] **Newsletter builder** (2a92697): Tools → Newsletter. Pick upcoming events, published blog posts and featured cards, add a title and intro, and copy email-ready HTML or plain text (or download it) for Mailchimp, Gmail or Church Center. Nothing is sent or stored. The header is the site name in type, since email clients don't show the SVG logo; a PNG logo could go there later.
- [x] **People tiles, one row** (01de627): a whole list (leads and members) shares one row when it fits with tiles at three quarters of full width or more, 10 at most; a board of 7 is one row at normal width.
- [x] **Privacy** (this branch): Giving links ngu.churchcenteronline.com (the address the site uses; the TODO said ngu.churchcenter.org) and says Church Center's script loads with the Giving page and may use Google Analytics in its form; Cookies says the site uses self-hosted, cookieless Plausible and not Google Analytics. Last updated September 30, 2026.
- [x] **People blocks** (7c7cdaa, migration 054): a "People" content block shows a team's members as people tiles, people picked one by one (each with a title), or both.
- [x] **Host teams** (7c7cdaa): an organization host can name a team (any organization's) to show in its place; the event page reads "Hosted by" the team, linked to its page.
- [x] **Organization page** (499662b): Leadership is now Organization, at /organization (/leadership 301s there). Mission, Vision & Values come from the NGU organization record's description and content blocks (Data → Organizations → NGU); Leadership is that record's teams with their people; Details & Contact has the address, nonprofit status, email and the record's contact links. Add the mission text and the teams (Board of Trustees, Retreat Team, Committees & Volunteers) on that record.
- [x] **404 page** (79c4b24): suggests the closest pages and records to the address (typos, old /chapters/ links), then the main pages.
- [x] **Request form wording** (this branch): short field titles with a help line; "Short description" for a post's card; the Files note says why to send a .docx.
- [x] **Cross-browser** (design): the backdrop parallax checked in Firefox and Chrome/Safari.
## Design (branch `design-overhaul`)
- [x] **Revised palette** (PR #19, 79f1d09): teal, green, amber and ink, four shades each (main, darkest, light, lightest), as the theme defaults in both modes; the old grid's literals mapped over, the hero's filled button amber. Every text pair passes 4.5:1.
- [x] **Overhaul fixes, third batch** (a397f3e to 2df908f, not yet tagged):
- Admin: header, strip and footer as wide as the content; white (surface) background in light mode, the page ink in dark; home cards alternate teal and green, with a shadow.
- `tint-soft` is a faint teal again (#e8fcfe / #00252b), not green; it's the hover and faint-panel color everywhere.
- Cards sit on a new raised surface (`bg-raised`: white, or a touch of tint in dark mode) with a shadow: featured cards, the connect block, people tile captions, the timeline's featured entries.
- Buttons: a small plain radius everywhere (superellipse removed).
- Video stills: YouTube's 16:9 frame (no black bars; the 4:3 one cropped as a fallback), small rounded corners, a round centered play button shown on hover or keyboard focus (always on touch screens).
- People tiles: rows balanced between 2 and 10 across, avoiding a lone tile on the last row where the width allows.
- Map tiles and region tags are solid, dimmed by color instead of transparency; map tiles are square.
- Backdrop: 16 circles in four parallax layers, all slower than the page, the back ones visibly moving on long pages; a different seeded arrangement per page; tone changes only at a new top-level section, easing over 2.4s. Text passes 4.5:1 however many overlap.
- Timeline: the rail is brown wood; decade numbers are tags off the rail on a short slanted branch, colored like their decade's leaves; featured entries and rosters are solid, not see-through.
- Cross-browser findings: the site needs Chrome/Edge 111+, Safari 16.4+, Firefox 128+ (Tailwind v4's own floor: color-mix, cascade layers). Everything else used (container queries, dialog, inert, line-clamp, ResizeObserver) is supported there. One gap: the backdrop's parallax uses scroll-driven animations, which Firefox doesn't have yet (Chrome/Edge 115+, Safari 26+); in Firefox the circles stay still, which is fine but flat. Done: option 2, a Firefox fallback (a passive scroll handler writing --pb-y once a frame, same motion as the scroll-driven version). Still possible: a dev-only Playwright check that screenshots key pages in Chromium, Firefox and WebKit, light and dark (a new dev dependency), for a repeatable browser pass.
- [x] **Overhaul fixes** (v1.10.1, f37c093):
- Backdrop: two slow circles fixed to the window drift up as you scroll (CSS scroll-driven animation, still in browsers without it and under reduced motion); three sit down the page and move with their sections. No sideways movement. Text stays 4.5:1 or better even where three circles overlap.
- Featured cards and the connect section: 4px rules; video frames inset from the card edge.
- Calendar: the weekday row is a solid dark bar with white Poppins labels.
- History: decade numerals are dark tags on the rail instead of a white box.
- Notices: two thick corner brackets (top left, bottom right), no box or fill.
- People tiles: the frame is around the whole list; details open right under the tile (flipping to the tile's right edge near the screen edge) and close on Escape or a click elsewhere.
- Community: "Request a region update" and "Request a partner listing"; the region list no longer shows a group count.
- Palette suggestion (not applied): the current grid has three near-duplicate pairs (#5ce7ff/#5cf4ff, #c2f6ff/#c2fbff, #004552/#004c52) and no mid-tone for secondary text or warm accent. Suggested grid, darkest to lightest per family, every 600 step usable as text and under white text: Teal #003a45 #00748a #5cd3e6 #d6f5fa; Green #23361a #4a7431 #9cc47c #e6f0dd; Amber #4a2e00 #8f5b00 #f0bd4f #fdf1d6; Ink #001011 #3b5456 #a3b8b9 #f5f9f8.
- [x] **Overhaul** (d81f7bd to dd33ee2), following design-taste-frontend with your notes first:
- **Palette:** the 16-color grid is the site's default colors, light and dark (`themeDefaults.js`, `index.css`, `PALETTE` in `src/lib/color.ts`); every text pair passes the admin's 4.5:1 check. #008fa8 is for borders and decoration (3.8:1 as text), text and buttons use the grid's dark shades.
- **Corners:** none anywhere; buttons share one `btn` utility (Poppins Bold, superellipse corners where the browser has `corner-shape`, a small radius elsewhere). Dots stay round.
- **Fonts:** Poppins Bold for titles, headings and buttons, subheadings Poppins regular, body Montserrat. The stat numbers keep their weight.
- **Front page:** hero buttons are one cell split by a slash (filled left, clear right); the brand backdrop is flat teal with the dove (no rings, blobs or glow); the countdown straddles the hero and the next band; featured cards and the connect section are one continuous block with a teal rule between cells, the first featured card large with the next two beside it; the calendar is square; stats unchanged except its blurred glow.
- **Page background:** `PageBackdrop` draws flat overlapping palette circles behind every public page, shifting tone as each section reaches the middle of the window; sections no longer paint their own bands.
- **Footer:** Give sits right of the logo.
- **People tiles:** square photos, a 2px frame, even heights (two lines of name and title, then an ellipsis and the down arrow, whose details show it whole); no photo shows the initials on a palette color picked by the name.
- **Notices:** empty sections and form notes use the `notice` style (tinted panel, solid left bar) instead of dashed borders.
- **Timeline:** each year is a leaf, green now and turning gold then autumn going back, fully turned before 2000 (History page and the front page rail).
- **Admin home:** each group of cards has its own palette color.
- **No glow** anywhere: blobs, rings, the live-dot pulse and the stats glow are gone.
- [ ] Check in a browser, light and dark: every page, the backdrop's tone shifts, the split hero buttons (and on a phone), featured cards with 1, 2 and 3+ cards, the connect tabs, people tiles with long titles, the timeline leaves, the admin home. Superellipse corners show in Chrome and Edge; other browsers get a small radius.
- [ ] Production: any colors saved in Panel → Site settings → Colors still override the new defaults; clear them to get the palette.
## Deployed and checked (2026-09-30)
- [x] **Groups and US spelling (PR #17, v1.9.15-groups):** database backed up; migrations 052 and 053 ran; Drive folder renamed Requests/Groups; old links, admin text and the showcase records handled.
- [x] **Main (PR #14):** Node 22.13+ on the VPS; production nginx has HSTS, gzip and HTTP/2; migrations 037 to 043 ran; 640px copies made; Connect Nav emoji icons replaced with named ones.
- [x] **Content display (PRs #15 and #16):** database and uploads backed up; migrations 044 to 051 ran; nginx blocks for `/api/requests`, `/api/admin/files` and `/api/admin/import/docx`; Google service account, shared drive, Gmail and access groups set up.
- [x] **After deploying:** request emails set in Notices and tested; a test request made into a post; a PDF uploaded to Files and used in a link card; groups checked in the Panel; privacy contact email set in Site settings.
- [x] **Browser checks** in light and dark mode: every page, logos on dark, the new icons, the nav between 768 and 1024px, anchors, the hero headline, empty sections, the loading skeleton, Privacy and Terms, the data request form, the privacy notice, click-to-load embeds, Site settings → Colours, the Panel, the Request buttons and form.
## Front-end pages
- [x] **Chapters are groups** (38aff34, migration 052): kind `group`, table `groups`, pages at `/groups/<id>`, Community `#groups`, the front page count, the Request form type and `Requests/Groups`; the site's own chapter links in records rewritten. Names and prose written in the admin left as written.
- [x] **US English** (2ad65cd, migration 053): color, center, canceled, labeled and the rest, in UI text, help, comments, docs and names. Kept: the stored event status `'cancelled'` (shown as canceled), `aria-labelledby`, schema.org's `EventCancelled`, old migrations.
- [x] **Front page: Featured Content section** (d4f65d9, migration 030): add it under Front page → Sections; draws Front page → Featured cards.
- Three card types: a record on the site (title, picture and link fill themselves, anything typed overrides), a link ("Fetch preview" reads the page's title, description and preview image into the library), and a video (thumbnail with a play button; the player loads only when pressed).
- Cards are shared: `featured_cards` is owned polymorphically and `FeaturedCards.tsx` draws them, so the Community blog reuses both.
- [x] **Front page: featured event hero** (migration 033): Front page → Feature → "Featured event". The event's card beside the headline (photo or colour, title, theme, dates or schedule, place, tagline, action buttons, "Event details") under a "Featured event" badge. Front page → Featured event picks one; blank uses the countdown's event, and a pinned event that's over falls back the same way.
- [x] **Community page: Community blog section** (d374f9a, migration 031): first on the Community page, heading and blurb from the admin. Two halves, each pinned first then newest up to its slots: our posts, and community posts (pinned link/video cards, then the newest items from RSS/Atom feeds, read about every 30 minutes).
- [x] **Blog posts:** pages at /blog/<id> (no index page), content-block body, cover image, excerpt, date, tags, authors as person tiles (People records and/or a guest name and photo). Drafts until published; Listed works as everywhere else. Also on the QR page.
- [x] **Blog post PDF** (5dceeb5): print layout with author information, cover as a banner, the post's link and a QR code.
- [x] **Request form** (migration 046): one form at `/request` (footer link too), a tile per kind: blog post (new only), event, chapter, region (update only), partner, team, award, person; then new or update, a name, details, up to 3 files (.docx, PDF, JPEG, PNG, 10 MB each) and an email. `?type=chapter` opens it on one.
- Buttons: Community blog section and the end of every blog post ("Write for the blog"), Retreats (first band) and the front page calendar ("Add or update an event"), Local Chapters, Unity Regions ("Update a region"), Partner Organizations. None for people, teams or awards.
- Each type asks for its main details (4b249c9, migration 049, `fields` in `src/data/requestTypes.ts`), stored as one JSON column.
- The message (and a request's name) is marked Required on the Request, feedback and data request forms, with a countdown of characters still needed (110b655).
- [x] **Privacy Policy and Terms** (ee61568): written from what the code does. Covers collected data, no data on minors displayed, AI use (builds the site's structure, no database access, data not ingested), third parties, cookie policy. Data deletion requests have their own form. Privacy contact email in Site settings (migration 039).
- [x] **Cookie notice:** a dismissible notice linking to the privacy page, since nothing third-party loads before a click. The hero video and the schedule map are click-to-load (ee61568).
- [x] **Community links** (c62dc84): nav and the org pages' "All regions" / "All chapters" pointed at #local and #virtual, which don't exist; now #chapters and #regions. "Virtual Community" renamed "Unity Regions".
## Content blocks and editing
- [x] **Showcase seed:** `DB_PATH=./dev.db node src/seed-showcase.js` (in server/) writes a fully filled record of every kind, ids starting `showcase-`: /regions/showcase-region, /chapters/showcase-chapter, /teams/showcase-team, /awards/showcase-award, /people/showcase-person, /events/showcase-event (upcoming retreat), /events/showcase-series (weekly), /events/showcase-past-event, /blog/content-block-showcase (every block type).
- Published but unlisted by default. `--listed` puts them in lists, the map, counts and History; rerun without it to take them out. Refuses /var/lib/ngu unless `--production` (back up first, leave `--listed` off on a live site).
- [x] **Block editor** (migration 032): each block type shows only its own fields, with a plain-English name and description; a live preview under each open block; insert-below and duplicate on every repeater row.
- Text formatting in paragraphs, callouts, quotes and list items: **bold**, *italic*, [text](url), line breaks, blank line for a new paragraph.
- Types added: video (click to play), button, callout. Quotes get an attribution, images alt text separate from the caption.
- [x] **Schedule block** (migration 034): entries have a day (the tab), time, title, detail, location, person and link, and fold out for a description, the person's photo and page link, a graphic, and a Google map. One tab per day in entry order; the tab for today's weekday opens first; entries with no day get their own tab; arrow keys, Home and End move between tabs.
- [x] **Table of contents** (92e7938, migration 043): Blog posts → Show contents (off by default). With two or more headings, a sticky "On this page" column, the heading being read lit; a fold-out on phones. Content-block headings carry anchor ids everywhere. Sticky fix merged with PR #14.
- [x] **Link cards block** (4e9b4e3, migration 045): link, title, description, picture; "Fetch preview" fills the rest. Smaller cards, a grid of up to three in a row (9ff1cd6). "Choose a file" picks from Media → Files, taking the file's name and Drive's first-page picture.
- [x] **Table block** (migration 044): a row per line, cells split by |; any page can use it.
- [x] **Import from Word** (7f12824): Blog posts → Import from Word turns a .docx into an unpublished post (title, date, headings, paragraphs, lists, tables, bold, italic, links; images don't come over, the editor says how many). PDFs: save as .docx first. `docs/importing.md`. Tested with the Church Management Systems comparison doc (untracked, not committed); imported, authored and published after deploying.
## Entities and data
- [x] **Listed flag** (cd393e4, migration 027): separate from Published (which stays the hard gate). Unlisted: own page works; left out of list routes, a region's chapters, an org's events/teams/awards, the QR page, front page counts and countdown. Still shown where attached by hand: rosters, hosts, billed people, award recipients, timeline, a pinned countdown.
- [x] **People pages list their blog posts** (7876e06): published and listed posts they're an author of, as Community blog cards.
- [x] **Event card background image** (eaff238, migration 029): Events → Appearance → "Card background", under a light veil (`CARD_IMAGE_VEIL` in `EventList-Cards.tsx`); card size unchanged. Gradients dropped (migration 040), colour borders kept.
- [x] **Create or update records from a request** (4b249c9): Forms → Content requests shows the requested details; "Create <type> from this" opens the New editor filled in (URL ID, links, a description paragraph); an update picks the record (closest name first) and shows each requested value beside the current one ("Use this" / "Add it"). Nothing saves until Save. Decided 2026-09-29.
- [x] **Every record image is an upload** (a67ca98): a bare filename resolves to `/uploads/<file>`; only the nav/footer/admin NGU logos are bundled from `src/assets/logos`. Missing files (eg. `ngu-logo-white-bg.svg`, old public/org-logos) copied to the server.
## Admin page
- [x] **Admin home three cards across** (175a189): the home asks for the wide admin column.
- [x] **Editor side nav:** sticky "On this page" left of every editor (field groups, then collections with row counts, current one lit, red dot on a section with a save error); "Jump to" dropdown below lg. Editor pages widen to fit (`src/lib/adminWidth.tsx`). Each collection has its own card; repeater rows start folded, with Expand all / Collapse all. Stays in view while scrolling (960c854).
- [x] **Nav groups:** header menus Data (Events, Organizations, Teams, Awards, People, Blog posts), Pages (Front page, Timeline, Community blog section), Forms, Tools (Media, QR code generator, Video clips), Panel. Hover or focus drops the group down; the strip under the header lists it (the touch path). The admin home shows the same groups as cards. One list: `adminNav.ts`. Tools on the admin home (99c3a87); blog posts moved to Data (c03914a).
- [x] **Forms split** (99d83eb): Website feedback and Data requests, a card each on the admin home and tabs with what's new in each. Content requests: same triage (status, notes, delete), files downloadable, "Make a blog post from it" on a .docx; deleting a request deletes its Drive files.
- [x] **Pickers:** both centred (Tailwind's reset had removed the dialog's auto margin). The image picker has folder tabs (All, Logos, Images, Previews) opening on the field's folder, and a From requests tab (6ccbc03: photos sent with requests, the one being edited first; picking one copies it into the library once). The file picker has a tab per Drive folder.
## Server (settings, auth, file management)
- [x] **Media uploads** (eaff238, migration 028): files in `/var/lib/ngu/uploads` served by nginx; editors and up upload, admins and up delete; resized and converted to WebP unless "Keep original". Every image field has Upload and "Choose from library"; Tools → Media. Production setup done (`docs/media-uploads.md`); `server/pnpm-lock.yaml` committed (be07bc1).
- [x] **Image folders:** `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (link and Drive previews); existing images sorted once at boot, records rewritten (`docs/media-uploads.md`, Folders).
- [x] **Google Drive and Gmail:** a service account (`server/src/googleService.js`, no library) uploads to, downloads from and trashes in a shared drive, a folder per use found or made by name; the same account sends mail as a Workspace user. `docs/google-drive-and-mail.md`.
- Request files go in `Requests/<type>` (migration 050). Tools → Media → Requests (by type folder, linked to its request) and Forms → Content requests mark files Drive no longer has as Missing from Drive; Remove (admins) trashes it and takes it off the request.
- **Files for pages** (migration 048): Tools → Media → Files uploads PDF, Office, MP3, M4A and zip (50 MB) to "Media", shared as anyone with the link (Drive's own sharing, decided 2026-09-29). Folders three deep, New folder, Rename, Delete when empty (admins), a Folder dropdown to move a file. Delete checks what links to a file first. Files and folders added in Drive by hand are picked up.
- [x] **Email notices** (v1.9.5 to v1.9.7): Site settings → Notices, "Email new requests to" (content and data requests), with a test button.
- [x] **Site settings** (migration 035): Panel → Site settings, superadmins only. Site name, description, preview image, favicon, home-screen icon, each static page's title and intro, search indexing on/off. A setting wins, a blank falls back to site.json. Colours (migration 041) and Access (migration 047) live here too.
- [x] **SEO and page previews:** the API fills in each page's title, description, preview image, canonical URL and structured data (Organization, Event, BlogPosting); serves /sitemap.xml and /robots.txt. Unlisted records are noindex; missing ones 404. site.json holds the site's name, address, default description and preview image. Deploy steps done (`docs/seo.md`), sitemap submitted.
- [x] **Google sign-in:** "Sign in with Google" above email and password. Server-side OAuth code flow with PKCE; checks issuer, audience, expiry, verified email and the Workspace domain. The first sign-in links an admin-cli account by email. OAuth client set up (`docs/google-sign-in.md`).
- [x] **Access groups** (migration 047): Site settings → Access names a group per role. Someone in one gets a Google-only account with their highest group's role, rechecked at sign-in, hourly and on Panel → Re-sync now. Out of every group: disabled and signed out, back on when they return. Superadmins and admin-cli accounts are untouched. Panel → Check their groups tests an email. Decided 2026-09-29.
- [x] **Security:** server-side auth, field allowlists, cookies, scrypt hashing, parameterized SQL, upload checks, escaping and trimmed responses were already right. Added: rate limits on the real client IP, CSRF check on /api writes, security headers (HSTS from nginx), 90-day session cap, `__Host-` session cookie, five wrong passwords lock an email for 15 minutes, CSP in Report-Only with /api/csp-report. Row-level security isn't a SQLite feature; route role checks, descriptor allowlists and published/listed filters do that job.
- [x] **Organization-agnostic names:** ngu-tl → site-tl, nguLogo → siteLogo, __NGU_SITE__ → __SITE__, browser keys ngu- → site-, cookies site_session / site_oauth, QR files qr-<page>. Kept on purpose: record ids (ngu-board), /var/lib/ngu, ngu.db, the ngu-api service, the logo file, NGU as the organization's name in text.
## Tools
- [x] **Video clips** (migration 036, admins and up): paste a YouTube or Facebook link; yt-dlp downloads it (up to 4 h / 4 GB). Cut clips by start and end, shaped as filmed, 16:9, square or 9:16 with a movable crop; MP4 or MP3. One job at a time with progress; everything swept after a day. VPS setup done (`docs/video-clips.md`).
- Save to library or Save to Drive (migration 051), with a folder picker (Videos or Audio chosen first), streamed with a resumable upload.
- A finished download can be saved whole (06a0e07); it stays on the server to cut from either way.
- [x] **QR code generator** (/qr): "In the centre" (nothing, NGU dove, or any SVG in `src/assets/qr`, embedded so SVG and PNG downloads carry it); "A link I type" (site path, full http(s) address, or bare domain); code, background and dove colours with a reset, warning under 4:1 contrast or when inverted.
## Design and accessibility
- [x] **Design system** (c74ad74): colour tokens in index.css, gradients gone (migration 040), data colours through `src/lib/color.ts`, one BRAND accent and ACCENTS family. One source for colour defaults with a build check (f934b1d).
- [x] **Dark mode:** follows the system with a header toggle. Fixed: the Church Center popup (7c1723b), the featured timeline background (048c759), a light plate behind every logo (048c759, f59ab31). Palette for both modes in Panel → Site settings → Colours; saving refuses text under 4.5:1 in either mode (`server/src/theme.js`).
- [x] **Accessibility** (185f983): contrast fixes, inert hidden carousel and past cards, keyboard links on admin rows, modal mobile menu, skip link, focus ring, reduced motion (JS smooth scrolls too), alt text for blog covers and schedule graphics (migration 038). Admin-chosen colours as text go through `accentText`/`readableOn`.
- [x] **Icons:** Phosphor everywhere; platform links show their brand icon (3c02eb8: `PLATFORMS` in `src/lib/platforms.ts`, icons in `PlatformIcon.tsx`, shared with the footer and event cards).
## Newsletter (branch `newsletter-layout`)
- [x] **Every part editable and movable** (migration 060): a draft is one list of parts, top to bottom, each moved, copied or removed like content blocks, and each aligned left or center: the header (words, a PNG or JPEG logo, its band color or no band; remove the part to leave it out), the title, any email block, picked items (upcoming events, blog posts or front page cards, picked one by one in order, with the section's heading, its underline, the cards' left bar and the button label), and the footer (its lines and the line above). Dividers take a color, thickness and space above. Colors are the palette or none. A new draft starts with the parts the email always had. 057's drafts (title, intro, picks, footer, blocks) are dropped: that migration never reached a live database.
- [x] **More parts and room** (this branch, after v1.11.2): the builder takes the whole window (the editor beside a 42rem preview; `useWideAdminPage('full')`). A **Social bar** part: a colored band (or none) of the site's platform icons, each linked; no links added shows the footer's (`src/data/socialLinks.ts`). Icons are white or ink PNGs in `public/email/` (made by `scripts/email-icons.mjs`), picked to read on the band. An **Event countdown** part: pick an upcoming dated event (not a series); the email shows a picture the API draws when it's opened (`/api/countdown/<id>.png`: days, hours and minutes to local midnight in America/Chicago on its start date, then "Happening now", then "Thanks for joining us"), with a fixed "10 days to go" line under it as of copying, for clients that block pictures. Gmail keeps the picture from its first open.
- [x] **Resizable builder**: a handle between the parts and the preview (from lg up) sets the preview's width, from 320px (as a phone shows the email) to all but 360px of the parts list; drag it, or focus it and use the arrow keys, Home and End. Remembered in the browser.
- [ ] Production: install Poppins on the VPS for the countdown picture (CLAUDE.md, Deployment), or it uses a plain sans.
- [ ] Check in a browser: build an issue with every part, move them, center some, turn off the band and the lines, pick items and reorder them, save and reopen the draft, Post as blog post, paste the HTML into Mailchimp and a Gmail test send.
## Navigation (branch `audit-ui`)
- [x] **Side nav over everything**: its column had no z-index, so later layers (the Retreats carousel arrows) drew over its circle; it's z-20 now, and its empty area lets clicks through.
- [x] **Request button**: the National Retreats band no longer shows "Add or update an event" (`NO_EVENT_REQUEST_SCOPES` in `src/lib/sections.tsx`); where a request button stays, it takes its section's accent (border, text, hover tint).
## Audits
- [x] **Third audit, UI half** (branch `audit-ui`, v1.11.1-audit, not checked in a browser yet):
- Event cards: the photo is a lazy `<img>` of the -640 copy under the veil (was a full-size CSS background); the carousel draws only slides within 2 of the current one; past 12 events the dots become a "7 / 200" counter; the past grid shows one row collapsed, then 12 at a time with Show more, newest first (was oldest first).
- Community map: a search box over the list and grid (name and place); each region's grid shows 12, then Show all; below lg the list scrolls in its own 36rem box; hovering a tile no longer redraws the list.
- People tiles: one clip check for the whole list (was an observer per tile); 30 tiles, then Show all.
- Person pages: 6 events and 6 posts, then Show all; blog excerpts load only each post's first paragraph.
- Admin: pickers and the QR page's record select get a filter box past 50 options (`src/components/OptionFilter.tsx`); `/admin/options?only=` sends only the lists a form uses; Media library thumbnails use the -640 copy, videos don't preload, search waits 250 ms and drops stale answers (Drive files too), and says when the newest 500 are shown.
- Coming back to a page after the 60 s cache shows its last data while it refreshes (api.ts `peek`), instead of the skeleton.
- [ ] Check in a browser, light and dark: the Retreats carousel with many events (counter, swipe, height between cards), the past grid, the side nav over the carousel arrow, request buttons' colors, Community search and Show all (and the phone list box), people tiles Show all and cut-off titles, a person page, admin pickers' filter, an editor's dropdowns all filled, the Media library.
- [x] **Third audit** (2026-10-01, branch `audit-3`): security after the Drive integration and in general, and scalability at hundreds of records. Fixed: a zip bomb through the request form's .docx (each part unpacked once); request files must be named for what they are (a PDF named .html is refused); a team's roster hidden with its unpublished organization; `/people?ids=` no longer names a draft organization, and takes 200 ids (was 50, which dropped people from big people blocks); v_events takes the first published host (a draft partner's name and logo leaked into an event's preview) and reads event_hosts directly, about 18 times faster per lookup (migration 059, with an index on person_awards.event_id); group accounts can't sign in while access groups are off, and a sync can't undo a superadmin's disable; 64 KB body limit on login, feedback and csp-report; Drive pick-up races no longer 500; random upload boundary. Scalability: /events filters by scope, host, status and type on the server (each band fetches only its own; Home no longer prefetches every event); /organizations leaves out bodies and leadership (the map's group panel fetches its group); admin lists page with "Show more" and a real count; Content requests "find the record" searches by name; the newsletter asks for published posts only. Kept: viewers see Forms (decided 2026-09-28).
- [x] **First audit** (v1.9.0-audit, 2026-09-28): security (4066e9e), bugs (693dd84), cleanup (5274e09: no em-dashes, import extensions, dead code, shared helpers, hooks moved to src/lib), accessibility (185f983), leftovers (e4a9c96: one mediaUrl, orgPath on orgHref, one Logo component, adminSchema split per entity), more cleanup (d1a6332: url column type refusing unsafe schemes).
- [x] **Second audit** (2026-09-29, after v1.9.3-audit): bugs and security (be7e924: Panel role changes, hostile feed markup, SSRF ranges, prototype keys), speed (f72a960: lazy pages, preloads, 640px copies, gzip and HTTP/2), dark mode and design (048c759), structure (f934b1d).
## Decided / left as they are
- `noImplicitAny` stays off (about 480 errors); decided 2026-09-29, noted in CLAUDE.md.
- Viewers may see feedback emails, including data requests (2026-09-28).
- Left alone: the two date-range formatters and the two findOr404 helpers (different, not duplicates); content.js as one file; the chapter grid in OrgList-Map; unused `export` keywords on internal helpers; RetreatsBand's name.

View file

@ -1,11 +0,0 @@
{
"version": 1,
"skills": {
"design-taste-frontend": {
"source": "Leonxlnx/taste-skill",
"sourceType": "github",
"skillPath": "skills/taste-skill/SKILL.md",
"computedHash": "899b84384f74f540ea5284d9b2e9234e050998b42eacc805410b518d4226c0b3"
}
}
}