diff --git a/.agents/skills/graphify/.graphify_version b/.agents/skills/graphify/.graphify_version new file mode 100644 index 0000000..8486678 --- /dev/null +++ b/.agents/skills/graphify/.graphify_version @@ -0,0 +1 @@ +0.9.48 \ No newline at end of file diff --git a/.agents/skills/graphify/SKILL.md b/.agents/skills/graphify/SKILL.md new file mode 100644 index 0000000..190827d --- /dev/null +++ b/.agents/skills/graphify/SKILL.md @@ -0,0 +1,710 @@ +--- +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 # full pipeline on specific path +/graphify https://github.com// # clone repo then run full pipeline on it +/graphify https://github.com// --branch # clone a specific branch +/graphify ... # clone multiple repos, build each, merge into one cross-repo graph +/graphify --mode deep # thorough extraction, richer INFERRED edges +/graphify --update # incremental - re-extract only new/changed files +/graphify --directed # build directed graph (preserves edge direction: source→target) +/graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy +/graphify --cluster-only # rerun clustering on existing graph +/graphify --no-viz # skip visualization, just report + JSON +/graphify --html # (HTML is generated by default - this flag is a no-op) +/graphify --svg # also export graph.svg (embeds in Notion, GitHub) +/graphify --graphml # export graph.graphml (Gephi, yEd) +/graphify --neo4j # generate graphify-out/cypher.txt for Neo4j +/graphify --neo4j-push bolt://localhost:7687 # push directly to Neo4j +/graphify --falkordb # generate graphify-out/cypher.txt for FalkorDB +/graphify --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB +/graphify --mcp # start MCP stdio server for agent access +/graphify --watch # watch folder, auto-rebuild on code changes (no LLM needed) +/graphify --wiki # build agent-crawlable wiki (index.md + one article per community) +/graphify --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault) +/graphify add # fetch URL, save to ./raw, update graph +/graphify add --author "Name" # tag who wrote it +/graphify add --contributor "Name" # tag who added it to the corpus +/graphify query "" # BFS traversal - broad context +/graphify query "" --dfs # DFS - trace a specific path +/graphify query "" --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 ""` 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 + +```bash +# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs) +PYTHON="" +GRAPHIFY_BIN=$(which graphify 2>/dev/null) +# 1. uv tool installs — most reliable on modern Mac/Linux +if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then + _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) + if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi +fi +# 2. Read shebang from graphify binary (pipx and direct pip installs) +if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then + _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') + case "$_SHEBANG" in + *[!a-zA-Z0-9/_.@-]*) ;; + *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;; + esac +fi +# 3. Fall back to python3 +if [ -z "$PYTHON" ]; then PYTHON="python3"; fi +if ! "$PYTHON" -c "import graphify" 2>/dev/null; then + if command -v uv >/dev/null 2>&1; then + uv tool install --upgrade graphifyy -q 2>&1 | tail -3 + _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) + if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi + else + "$PYTHON" -m pip install graphifyy -q 2>/dev/null \ + || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3 + fi +fi +# Write interpreter path for all subsequent steps (persists across invocations) +mkdir -p graphify-out +"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" +# Save scan root so `graphify update` (no args) knows where to look next time +echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root +``` + +If the import succeeds, print nothing and move straight to Step 2. + +**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.** + +### Step 2 - Detect files + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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: + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +#### 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`): + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +**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. + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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** + +> Uses the `Task` tool for parallel subagent dispatch. +> Call `Task` once per chunk — ALL in the same response so they run in parallel. + +Pass the extraction prompt as the task description: + +``` +Task(description="Your task is to perform the following. Follow the instructions below exactly.\n\n\n[extraction prompt, with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]\n\n\nExecute this now. Output ONLY the structured JSON response.") +``` + +Each subagent writes its result to its own `graphify-out/.graphify_chunk_NN.json`. Collect results as each `Task` completes and parse each as JSON. + +CHUNK_PATH must be an **absolute** path — derive it before dispatching: +```bash +PROJECT_ROOT=$(pwd) # cwd — where Part C globs graphify-out/ (NOT .graphify_root/scan dir, #1392) +# Then for chunk N: CHUNK_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, 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: +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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): +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +Merge cached + new results into `graphify-out/.graphify_semantic.json`: +```bash +$(cat graphify-out/.graphify_python) -c " +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)') +" +``` +Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json` + +#### Part C - Merge AST + semantic into final extraction + +```bash +$(cat graphify-out/.graphify_python) -c " +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)') +" +``` + +### 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. + +```bash +mkdir -p graphify-out +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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. + +```bash +$(cat graphify-out/.graphify_python) -c " +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).') +" +``` + +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: + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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 ` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`. + +```bash +graphify export obsidian +# or with custom dir: graphify export obsidian --dir ~/vaults/my-project +``` + +Generate the HTML graph (always, unless `--no-viz`): + +```bash +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 + +```bash +$(cat graphify-out/.graphify_python) -c " +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)') +" +rm -f 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 +find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null +rm -f graphify-out/.needs_update 2>/dev/null || true +``` + +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: + +```bash +if [ ! -f graphify-out/.graphify_python ]; then + GRAPHIFY_BIN=$(which graphify 2>/dev/null) + if [ -n "$GRAPHIFY_BIN" ]; then + PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') + case "$PYTHON" in *[!a-zA-Z0-9/_.@-]*) PYTHON="python3" ;; esac + else + PYTHON="python3" + fi + mkdir -p graphify-out + "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" +fi +``` + +## 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: + +```bash +graphify query "" +``` + +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 ` 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 AGENTS.md integration + +When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's AGENTS.md, see `references/hooks.md`. + +--- + +## 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. diff --git a/.agents/skills/graphify/references/add-watch.md b/.agents/skills/graphify/references/add-watch.md new file mode 100644 index 0000000..7784434 --- /dev/null +++ b/.agents/skills/graphify/references/add-watch.md @@ -0,0 +1,56 @@ +# graphify reference: add a URL and watch a folder + +Load this when the user ran `/graphify add ` 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 INPUT_PATH --debounce 3 +``` + +Replace INPUT_PATH with the folder to watch. 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. diff --git a/.agents/skills/graphify/references/exports.md b/.agents/skills/graphify/references/exports.md new file mode 100644 index 0000000..242ff86 --- /dev/null +++ b/.agents/skills/graphify/references/exports.md @@ -0,0 +1,87 @@ +# 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 `** - 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 `** - 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": "", + "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. diff --git a/.agents/skills/graphify/references/extraction-spec.md b/.agents/skills/graphify/references/extraction-spec.md new file mode 100644 index 0000000..388df76 --- /dev/null +++ b/.agents/skills/graphify/references/extraction-spec.md @@ -0,0 +1,70 @@ +# 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":"","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":"","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":""}],"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 +``` diff --git a/.agents/skills/graphify/references/github-and-merge.md b/.agents/skills/graphify/references/github-and-merge.md new file mode 100644 index 0000000..a41ea06 --- /dev/null +++ b/.agents/skills/graphify/references/github-and-merge.md @@ -0,0 +1,46 @@ +# 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 [--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 # → ~/.graphify/repos// +graphify clone # → ~/.graphify/repos// +# Run /graphify on each local path to produce their graph.json files +# Then merge: +graphify merge-graphs \ + ~/.graphify/repos///graphify-out/graph.json \ + ~/.graphify/repos///graphify-out/graph.json \ + --out graphify-out/cross-repo-graph.json +``` + +Graphify clones into `~/.graphify/repos//` 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. diff --git a/.agents/skills/graphify/references/hooks.md b/.agents/skills/graphify/references/hooks.md new file mode 100644 index 0000000..3fb74d1 --- /dev/null +++ b/.agents/skills/graphify/references/hooks.md @@ -0,0 +1,33 @@ +# graphify reference: commit hook and native AGENTS.md integration + +Load this when the user asked to install the post-commit hook or wire graphify into a project's AGENTS.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 AGENTS.md integration + +Run once per project to make graphify always-on in your agent sessions: + +```bash +graphify agents install +``` + +This writes a `## graphify` section to the local `AGENTS.md` that instructs your agent to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions. + +```bash +graphify agents uninstall # remove the section +``` diff --git a/.agents/skills/graphify/references/query.md b/.agents/skills/graphify/references/query.md new file mode 100644 index 0000000..56565eb --- /dev/null +++ b/.agents/skills/graphify/references/query.md @@ -0,0 +1,311 @@ +# 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 first to build the graph.') + raise SystemExit(1) +" +``` +If it fails, stop and tell the user to run `/graphify ` 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 +``` diff --git a/.agents/skills/graphify/references/transcribe.md b/.agents/skills/graphify/references/transcribe.md new file mode 100644 index 0000000..b967f83 --- /dev/null +++ b/.agents/skills/graphify/references/transcribe.md @@ -0,0 +1,52 @@ +# 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="" +$(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 `, `export GRAPHIFY_WHISPER_MODEL=` (it must be exported, not just assigned) before running the command above. diff --git a/.agents/skills/graphify/references/update.md b/.agents/skills/graphify/references/update.md new file mode 100644 index 0000000..3632fd4 --- /dev/null +++ b/.agents/skills/graphify/references/update.md @@ -0,0 +1,210 @@ +# 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. diff --git a/.cursor/rules/graphify.mdc b/.cursor/rules/graphify.mdc new file mode 100644 index 0000000..35471a9 --- /dev/null +++ b/.cursor/rules/graphify.mdc @@ -0,0 +1,21 @@ +--- +description: graphify knowledge graph context +alwaysApply: true +--- + +This project has a graphify knowledge graph at graphify-out/. + +**MANDATORY: Before using Read, Grep, Glob, or Bash to explore the codebase, you MUST run graphify first:** +- `graphify query ""` — scoped subgraph for any codebase or architecture question +- `graphify path "" ""` — dependency path between two symbols +- `graphify explain ""` — all nodes related to a concept + +This applies to YOU and to every subagent you spawn. Include this rule explicitly in every subagent prompt that involves code exploration. Do not skip graphify because files are "already known" or because you are executing a plan — the graph surfaces cross-file dependencies and INFERRED edges that grep and Read cannot find. + +Only use Read/Grep/Glob directly when: +1. graphify has already oriented you and you need to modify or debug specific lines +2. `graphify-out/graph.json` does not exist yet + +- If `graphify-out/wiki/index.md` exists, navigate it instead of reading raw files +- Read `graphify-out/GRAPH_REPORT.md` only for broad architecture review when query/path/explain do not surface enough context +- After modifying code files, run `graphify update .` to keep the graph current (AST-only, no API cost) diff --git a/.cursor/skills/graphify/SKILL.md b/.cursor/skills/graphify/SKILL.md new file mode 100644 index 0000000..190827d --- /dev/null +++ b/.cursor/skills/graphify/SKILL.md @@ -0,0 +1,710 @@ +--- +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 # full pipeline on specific path +/graphify https://github.com// # clone repo then run full pipeline on it +/graphify https://github.com// --branch # clone a specific branch +/graphify ... # clone multiple repos, build each, merge into one cross-repo graph +/graphify --mode deep # thorough extraction, richer INFERRED edges +/graphify --update # incremental - re-extract only new/changed files +/graphify --directed # build directed graph (preserves edge direction: source→target) +/graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy +/graphify --cluster-only # rerun clustering on existing graph +/graphify --no-viz # skip visualization, just report + JSON +/graphify --html # (HTML is generated by default - this flag is a no-op) +/graphify --svg # also export graph.svg (embeds in Notion, GitHub) +/graphify --graphml # export graph.graphml (Gephi, yEd) +/graphify --neo4j # generate graphify-out/cypher.txt for Neo4j +/graphify --neo4j-push bolt://localhost:7687 # push directly to Neo4j +/graphify --falkordb # generate graphify-out/cypher.txt for FalkorDB +/graphify --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB +/graphify --mcp # start MCP stdio server for agent access +/graphify --watch # watch folder, auto-rebuild on code changes (no LLM needed) +/graphify --wiki # build agent-crawlable wiki (index.md + one article per community) +/graphify --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault) +/graphify add # fetch URL, save to ./raw, update graph +/graphify add --author "Name" # tag who wrote it +/graphify add --contributor "Name" # tag who added it to the corpus +/graphify query "" # BFS traversal - broad context +/graphify query "" --dfs # DFS - trace a specific path +/graphify query "" --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 ""` 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 + +```bash +# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs) +PYTHON="" +GRAPHIFY_BIN=$(which graphify 2>/dev/null) +# 1. uv tool installs — most reliable on modern Mac/Linux +if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then + _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) + if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi +fi +# 2. Read shebang from graphify binary (pipx and direct pip installs) +if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then + _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') + case "$_SHEBANG" in + *[!a-zA-Z0-9/_.@-]*) ;; + *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;; + esac +fi +# 3. Fall back to python3 +if [ -z "$PYTHON" ]; then PYTHON="python3"; fi +if ! "$PYTHON" -c "import graphify" 2>/dev/null; then + if command -v uv >/dev/null 2>&1; then + uv tool install --upgrade graphifyy -q 2>&1 | tail -3 + _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) + if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi + else + "$PYTHON" -m pip install graphifyy -q 2>/dev/null \ + || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3 + fi +fi +# Write interpreter path for all subsequent steps (persists across invocations) +mkdir -p graphify-out +"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" +# Save scan root so `graphify update` (no args) knows where to look next time +echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root +``` + +If the import succeeds, print nothing and move straight to Step 2. + +**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.** + +### Step 2 - Detect files + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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: + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +#### 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`): + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +**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. + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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** + +> Uses the `Task` tool for parallel subagent dispatch. +> Call `Task` once per chunk — ALL in the same response so they run in parallel. + +Pass the extraction prompt as the task description: + +``` +Task(description="Your task is to perform the following. Follow the instructions below exactly.\n\n\n[extraction prompt, with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]\n\n\nExecute this now. Output ONLY the structured JSON response.") +``` + +Each subagent writes its result to its own `graphify-out/.graphify_chunk_NN.json`. Collect results as each `Task` completes and parse each as JSON. + +CHUNK_PATH must be an **absolute** path — derive it before dispatching: +```bash +PROJECT_ROOT=$(pwd) # cwd — where Part C globs graphify-out/ (NOT .graphify_root/scan dir, #1392) +# Then for chunk N: CHUNK_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, 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: +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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): +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +Merge cached + new results into `graphify-out/.graphify_semantic.json`: +```bash +$(cat graphify-out/.graphify_python) -c " +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)') +" +``` +Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json` + +#### Part C - Merge AST + semantic into final extraction + +```bash +$(cat graphify-out/.graphify_python) -c " +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)') +" +``` + +### 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. + +```bash +mkdir -p graphify-out +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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. + +```bash +$(cat graphify-out/.graphify_python) -c " +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).') +" +``` + +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: + +```bash +$(cat graphify-out/.graphify_python) -c " +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') +" +``` + +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 ` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`. + +```bash +graphify export obsidian +# or with custom dir: graphify export obsidian --dir ~/vaults/my-project +``` + +Generate the HTML graph (always, unless `--no-viz`): + +```bash +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 + +```bash +$(cat graphify-out/.graphify_python) -c " +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)') +" +rm -f 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 +find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null +rm -f graphify-out/.needs_update 2>/dev/null || true +``` + +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: + +```bash +if [ ! -f graphify-out/.graphify_python ]; then + GRAPHIFY_BIN=$(which graphify 2>/dev/null) + if [ -n "$GRAPHIFY_BIN" ]; then + PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') + case "$PYTHON" in *[!a-zA-Z0-9/_.@-]*) PYTHON="python3" ;; esac + else + PYTHON="python3" + fi + mkdir -p graphify-out + "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" +fi +``` + +## 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: + +```bash +graphify query "" +``` + +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 ` 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 AGENTS.md integration + +When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's AGENTS.md, see `references/hooks.md`. + +--- + +## 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. diff --git a/.cursor/skills/graphify/references/add-watch.md b/.cursor/skills/graphify/references/add-watch.md new file mode 100644 index 0000000..7784434 --- /dev/null +++ b/.cursor/skills/graphify/references/add-watch.md @@ -0,0 +1,56 @@ +# graphify reference: add a URL and watch a folder + +Load this when the user ran `/graphify add ` 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 INPUT_PATH --debounce 3 +``` + +Replace INPUT_PATH with the folder to watch. 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. diff --git a/.cursor/skills/graphify/references/exports.md b/.cursor/skills/graphify/references/exports.md new file mode 100644 index 0000000..242ff86 --- /dev/null +++ b/.cursor/skills/graphify/references/exports.md @@ -0,0 +1,87 @@ +# 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 `** - 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 `** - 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": "", + "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. diff --git a/.cursor/skills/graphify/references/extraction-spec.md b/.cursor/skills/graphify/references/extraction-spec.md new file mode 100644 index 0000000..388df76 --- /dev/null +++ b/.cursor/skills/graphify/references/extraction-spec.md @@ -0,0 +1,70 @@ +# 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":"","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":"","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":""}],"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 +``` diff --git a/.cursor/skills/graphify/references/github-and-merge.md b/.cursor/skills/graphify/references/github-and-merge.md new file mode 100644 index 0000000..a41ea06 --- /dev/null +++ b/.cursor/skills/graphify/references/github-and-merge.md @@ -0,0 +1,46 @@ +# 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 [--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 # → ~/.graphify/repos// +graphify clone # → ~/.graphify/repos// +# Run /graphify on each local path to produce their graph.json files +# Then merge: +graphify merge-graphs \ + ~/.graphify/repos///graphify-out/graph.json \ + ~/.graphify/repos///graphify-out/graph.json \ + --out graphify-out/cross-repo-graph.json +``` + +Graphify clones into `~/.graphify/repos//` 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. diff --git a/.cursor/skills/graphify/references/hooks.md b/.cursor/skills/graphify/references/hooks.md new file mode 100644 index 0000000..3fb74d1 --- /dev/null +++ b/.cursor/skills/graphify/references/hooks.md @@ -0,0 +1,33 @@ +# graphify reference: commit hook and native AGENTS.md integration + +Load this when the user asked to install the post-commit hook or wire graphify into a project's AGENTS.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 AGENTS.md integration + +Run once per project to make graphify always-on in your agent sessions: + +```bash +graphify agents install +``` + +This writes a `## graphify` section to the local `AGENTS.md` that instructs your agent to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions. + +```bash +graphify agents uninstall # remove the section +``` diff --git a/.cursor/skills/graphify/references/query.md b/.cursor/skills/graphify/references/query.md new file mode 100644 index 0000000..56565eb --- /dev/null +++ b/.cursor/skills/graphify/references/query.md @@ -0,0 +1,311 @@ +# 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 first to build the graph.') + raise SystemExit(1) +" +``` +If it fails, stop and tell the user to run `/graphify ` 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 +``` diff --git a/.cursor/skills/graphify/references/transcribe.md b/.cursor/skills/graphify/references/transcribe.md new file mode 100644 index 0000000..b967f83 --- /dev/null +++ b/.cursor/skills/graphify/references/transcribe.md @@ -0,0 +1,52 @@ +# 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="" +$(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 `, `export GRAPHIFY_WHISPER_MODEL=` (it must be exported, not just assigned) before running the command above. diff --git a/.cursor/skills/graphify/references/update.md b/.cursor/skills/graphify/references/update.md new file mode 100644 index 0000000..3632fd4 --- /dev/null +++ b/.cursor/skills/graphify/references/update.md @@ -0,0 +1,210 @@ +# 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. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..acc1967 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +graphify-out/graph.json merge=graphify diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..10d9ed8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,70 @@ +name: CI + +on: + push: + branches: [main, 'cursor/**'] + pull_request: + branches: [main] + +jobs: + lint-and-test: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: serviceops + POSTGRES_PASSWORD: serviceops + POSTGRES_DB: serviceops + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + version: 9.15.4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + + - run: pnpm install + + - name: Generate Prisma client + run: pnpm --filter @serviceops/api exec prisma generate + env: + DATABASE_URL: postgresql://serviceops:serviceops@localhost:5432/serviceops + + - name: Migrate database + run: pnpm --filter @serviceops/api exec prisma db push + env: + DATABASE_URL: postgresql://serviceops:serviceops@localhost:5432/serviceops + + - name: Typecheck + run: pnpm typecheck + + - name: Test API + run: pnpm --filter @serviceops/api test + env: + DATABASE_URL: postgresql://serviceops:serviceops@localhost:5432/serviceops + JWT_SECRET: test-secret + + docker-build: + runs-on: ubuntu-latest + needs: lint-and-test + steps: + - uses: actions/checkout@v4 + + - name: Build API image + run: docker build -f apps/api/Dockerfile -t serviceops-api:ci . + + - name: Build Web image + run: docker build -f apps/web/Dockerfile -t serviceops-web:ci . diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..aaa403d --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,43 @@ +name: Deploy + +on: + push: + branches: [main] + +permissions: + contents: read + packages: write + +jobs: + build-and-push: + runs-on: ubuntu-latest + if: github.repository != '' + steps: + - uses: actions/checkout@v4 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push API image + uses: docker/build-push-action@v6 + with: + context: . + file: apps/api/Dockerfile + push: true + tags: | + ghcr.io/${{ github.repository_owner }}/serviceops-api:latest + ghcr.io/${{ github.repository_owner }}/serviceops-api:${{ github.sha }} + + - name: Build and push Web image + uses: docker/build-push-action@v6 + with: + context: . + file: apps/web/Dockerfile + push: true + tags: | + ghcr.io/${{ github.repository_owner }}/serviceops-web:latest + ghcr.io/${{ github.repository_owner }}/serviceops-web:${{ github.sha }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b0b765 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Dependencies +node_modules/ +.pnpm-store/ + +# Environment +.env +.env.local +apps/api/.env +apps/web/.env + +# Build +dist/ +.next/ +out/ +coverage/ + +# Graphify — cost tracking locale (non committare) +graphify-out/cost.json + +# Python (graphify tooling) +__pycache__/ +*.py[cod] +.venv/ +venv/ + +# IDE +.idea/ +.vscode/ diff --git a/.graphifyignore b/.graphifyignore new file mode 100644 index 0000000..0514dd4 --- /dev/null +++ b/.graphifyignore @@ -0,0 +1,8 @@ +# Graphify ignore — stessa sintassi di .gitignore +.git/ +node_modules/ +dist/ +build/ +*.pyc +.venv/ +venv/ diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..4c2f52b --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +auto-install-peers=true +strict-peer-dependencies=false diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..8f431a1 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,102 @@ +# ServiceOps — Architettura + +## Panoramica + +ServiceOps è un SaaS B2B multi-tenant per piccole imprese di servizi. Il repository è un **monorepo pnpm** con: + +- `apps/api` — backend NestJS + Prisma + PostgreSQL +- `apps/web` — frontend Next.js 15 (App Router) +- `packages/config` — configurazione TypeScript condivisa + +``` +┌─────────────┐ REST/JSON ┌─────────────┐ Prisma ┌────────────┐ +│ Next.js │ ◄──────────────► │ NestJS │ ◄────────────► │ PostgreSQL │ +│ (web) │ JWT Bearer │ (api) │ │ │ +└─────────────┘ └─────────────┘ └────────────┘ +``` + +## Scelte tecnologiche + +### Prisma vs Drizzle + +**Scelta: Prisma** + +| Criterio | Prisma | Drizzle | +|----------|--------|---------| +| Migrations | Mature, team-friendly | Buone, più manuali | +| Multi-tenant patterns | Ampia documentazione | Flessibile ma più DIY | +| DX | Prisma Studio, generate client | Più leggero | +| Type safety | Client generato | SQL-first types | + +Per un prodotto B2B con molte entità correlate e team che evolve, Prisma offre migliore produttività e tooling (migrate, studio, seed). + +### REST vs GraphQL + +**Scelta: REST** + +- API B2B con CRUD prevedibili e report aggregati +- Caching HTTP e integrazioni future (Zapier, export) più semplici +- TanStack Query ottimizzato per REST +- GraphQL può essere aggiunto in un modulo `graphql` se servono query ad hoc complesse + +### Auth + +- JWT Bearer con `organizationId` e `role` nel payload +- `Membership` collega User ↔ Organization +- Tutte le query di dominio filtrano per `organizationId` (tenant isolation) +- SSO enterprise OIDC/SAML (`SsoService`, `OrganizationSsoConfig`, `ExternalIdentity`) +- Callback frontend `/auth/callback` con redirect da API + +## Moduli backend + +| Modulo | Responsabilità | +|--------|------------------| +| `auth` | Register, login, JWT, guard | +| `organizations` | Settings tenant, piano | +| `users` | Lista membri organizzazione | +| `crm` | Customer, Contact, Site | +| `jobs` | Job, JobItem, stati commessa | +| `activities` | Ore lavorate, MaterialUsage | +| `inventory` | Material, InventoryMovement | +| `billing` | Quote/Invoice con righe dettaglio, Subscription, Stripe + Lemon Squeezy checkout/webhook | +| `reports` | KPI dashboard, margini, PDF/CSV export | + +## Multi-tenant + +- Ogni tabella di dominio ha `organizationId` +- Indici su `(organizationId)` e `(organizationId, foreignKey)` +- JWT include `organizationId` — nessuna query cross-tenant senza switch esplicito +- Feature flags in `Organization.settings` JSON (inventory, billing, ecc.) + +## Scalabilità + +| Layer | Strategia attuale | Evoluzione | +|-------|-------------------|------------| +| DB | PostgreSQL gestito (Neon/Supabase/Railway) | Read replicas, connection pooling (PgBouncer) | +| API | Stateless NestJS containers | Horizontal scaling, rate limit per tenant | +| Cache | Non implementata | Redis per sessioni/KPI dashboard | +| Jobs async | Sync | BullMQ per report pesanti, email | +| File export | In-process PDF/CSV | S3 + worker per export grandi | +| Observability | stdout logging + OpenTelemetry opzionale (`OTEL_ENABLED`) | Sentry, Prometheus metrics | + +## Frontend + +- Next.js 15 App Router, TypeScript strict +- Tailwind + componenti UI minimali (pronti per shadcn/ui) +- TanStack Query per stato server +- Zod-ready (validazione form via React Hook Form) +- Layout con sidebar, auth guard, organization context da JWT + +## DevOps + +- `docker-compose.yml`: web + api + postgres +- GitHub Actions: lint, typecheck, test, docker build +- Dockerfile multi-stage per api e web (standalone Next.js) + +## Evoluzione futura + +- SSO enterprise: provisioning JIT, rotazione certificati SAML, SCIM +- OpenTelemetry: metriche e trace sampling in produzione +- Billing avanzato: pagamenti parziali, multi-currency +- Cache Redis, job async BullMQ, read replicas DB + diff --git a/DOMAIN.md b/DOMAIN.md new file mode 100644 index 0000000..bd49a96 --- /dev/null +++ b/DOMAIN.md @@ -0,0 +1,89 @@ +# ServiceOps — Dominio + +## Visione + +ServiceOps modella l'operatività di imprese che eseguono **lavori ripetitivi su clienti e impianti**: officine, installatori, studi tecnici con cantieri, aziende di manutenzione. + +## Entità principali + +### Organizzazione (tenant) + +- `Organization`: tenant root (nome, slug, settings, piano) +- `User`: utente globale (email univoca) +- `Membership`: ruolo nell'organizzazione (OWNER, ADMIN, MEMBER, TECHNICIAN) +- `Subscription`: piano e integrazione Stripe (skeleton) + +### CRM + +- `Customer`: anagrafica cliente (P.IVA, contatti, indirizzo) +- `Contact`: referenti del cliente +- `Site`: sedi/impianti/cantieri del cliente + +### Commesse + +- `Job`: commessa/lavoro (stato, cliente, sede, date, reference) +- `JobItem`: voci di ricavo (servizi, parti, quantità, prezzo) + +Stati: `DRAFT` → `CONFIRMED` → `IN_PROGRESS` → `COMPLETED` → `INVOICED` + +### Attività e costi + +- `Activity`: ore lavorate su commessa (tecnico, costo orario) +- `MaterialUsage`: materiali consumati su commessa +- `Material`: anagrafica magazzino +- `InventoryMovement`: movimenti IN/OUT magazzino + +### Economia + +Ricavi = somma `JobItem.quantity * unitPrice` +Costi ore = somma `Activity.hours * hourlyCost` +Costi materiali = somma `MaterialUsage.quantity * unitCost` +Margine = Ricavi − (Costi ore + Costi materiali) + +### Billing (skeleton) + +- `Quote`: preventivo collegato a job +- `Invoice`: fattura collegata a job + +## Relazioni + +``` +Organization + ├── Customer ── Site + │ └── Job ── JobItem (ricavi) + │ ├── Activity (ore) + │ └── MaterialUsage ── Material + ├── Material ── InventoryMovement + └── Quote / Invoice +``` + +## Casi d'uso + +### Officina meccanica + +1. Registra cliente con targa/referenza veicolo come `Job.reference` +2. Crea commessa "Revisione freni" +3. Aggiunge voci (pastiglie, manodopera) +4. Tecnico registra 2h a €35/h +5. Scarica materiale dal magazzino +6. Visualizza margine commessa e dashboard mensile + +### Impresa installazione + +1. Cliente con multiple `Site` (impianti) +2. Commesse per cantiere con `dueDate` +3. Report margini per cliente e export CSV per amministrazione + +### Studio tecnico + +1. Commesse per progetto/cantiere +2. Ore per tecnico su commessa +3. Report PDF commessa per cliente + +## Flussi MVP implementati + +1. **Onboarding**: register → crea Organization + User OWNER +2. **CRM**: crea Customer, aggiunge Site +3. **Commessa**: crea Job, aggiunge JobItem +4. **Costi**: registra Activity (ore) e MaterialUsage +5. **Report**: margini per job, KPI dashboard, export CSV/PDF diff --git a/README.md b/README.md index a2347c7..3a38963 100644 --- a/README.md +++ b/README.md @@ -1 +1,243 @@ -# ServiceOps \ No newline at end of file +# ServiceOps + +**English** · [Italiano](#italiano) + +Multi-tenant B2B SaaS for service businesses: customers, jobs, hours, materials, margins, and reports. + +--- + +## English + +### Overview + +ServiceOps is an operational system for small service companies that manage customers and recurring jobs/projects (workshops, installation and maintenance firms, technical studios with job sites, field service companies, and similar). + +It replaces scattered spreadsheets and chat threads with a single platform to: + +- Manage customers, sites, and job history +- Track jobs (status, quotes, hours, materials, external costs) +- Optionally manage a parts/materials warehouse +- Calculate revenue, costs, and margins per job and per organization +- View dashboards and reports with PDF/CSV export + +### Stack + +| Layer | Technologies | +|-------|--------------| +| Frontend | Next.js 15 (App Router), TypeScript, Tailwind CSS, TanStack Query, Zod | +| Backend | NestJS, Prisma ORM, PostgreSQL | +| Auth | JWT with multi-tenant `Organization` isolation | +| Infra | Docker Compose, GitHub Actions | + +### Quick start (local) + +#### Prerequisites + +- Node.js 22+ +- pnpm 9+ +- PostgreSQL 16 (or Docker) + +#### Setup + +```bash +pnpm install + +# Configure database +cp apps/api/.env.example apps/api/.env +# Edit DATABASE_URL if needed + +pnpm db:push # apply Prisma schema +pnpm dev # starts api (3001) + web (3000) +``` + +Open http://localhost:3000 → Register → create your organization → use the MVP. + +#### Docker Compose + +```bash +docker compose up --build +``` + +Services: `web` (3000), `api` (3001), `db` (5432). + +### Commands + +| Command | Description | +|---------|-------------| +| `pnpm dev` | Dev mode for api + web | +| `pnpm build` | Production build | +| `pnpm test` | Run tests | +| `pnpm typecheck` | TypeScript check | +| `pnpm db:push` | Sync database schema | +| `pnpm db:migrate` | Prisma migrate dev | + +### Repository structure + +``` +apps/ + api/ NestJS backend + web/ Next.js frontend +packages/ + config/ shared TypeScript config +``` + +### Documentation + +- [ARCHITECTURE.md](./ARCHITECTURE.md) — technical choices and scalability +- [DOMAIN.md](./DOMAIN.md) — domain model and use cases + +### Graphify + +This project includes [Graphify](https://github.com/Graphify-Labs/graphify) for a queryable knowledge graph of the codebase. + +```bash +graphify update . # refresh graph after code changes +graphify query "how does auth work?" +``` + +Output lives in `graphify-out/`. + +### Adding a backend module + +1. Create `apps/api/src//` with module, service, and controller +2. Add entities in `prisma/schema.prisma` with `organizationId` +3. Register the module in `app.module.ts` +4. Add the corresponding page/API client in the frontend + +### Tests + +```bash +pnpm --filter @serviceops/api test # unit tests +pnpm --filter @serviceops/api test:e2e # e2e (requires DB) +``` + +### MVP flows + +1. Register → creates organization and owner user +2. Create customers and sites +3. Create jobs and line items (revenue) +4. Log hours and material usage (costs) +5. View per-job margins and dashboard KPIs + +### License + +Proprietary — ServiceOps + +--- + +## Italiano + +### Panoramica + +ServiceOps è un sistema operativo per piccole imprese di servizi che gestiscono clienti e commesse/lavori ripetitivi (officine, imprese di installazione e manutenzione, studi tecnici con cantieri, aziende di servizi sul campo, ecc.). + +Sostituisce Excel, fogli sparsi e chat con una piattaforma unica per: + +- Gestire clienti, sedi/impianti e storico lavori +- Seguire commesse (stato, preventivo, ore, materiali, costi esterni) +- Gestire opzionalmente un magazzino materiali/ricambi +- Calcolare ricavi, costi e margini per commessa e per organizzazione +- Offrire dashboard e report con export PDF/CSV + +### Stack + +| Layer | Tecnologie | +|-------|------------| +| Frontend | Next.js 15 (App Router), TypeScript, Tailwind CSS, TanStack Query, Zod | +| Backend | NestJS, Prisma ORM, PostgreSQL | +| Auth | JWT con isolamento multi-tenant per `Organization` | +| Infra | Docker Compose, GitHub Actions | + +### Avvio rapido (locale) + +#### Prerequisiti + +- Node.js 22+ +- pnpm 9+ +- PostgreSQL 16 (o Docker) + +#### Setup + +```bash +pnpm install + +# Configura database +cp apps/api/.env.example apps/api/.env +# Modifica DATABASE_URL se necessario + +pnpm db:push # applica schema Prisma +pnpm dev # avvia api (3001) + web (3000) +``` + +Apri http://localhost:3000 → Registrati → crea organizzazione → usa il MVP. + +#### Docker Compose + +```bash +docker compose up --build +``` + +Servizi: `web` (3000), `api` (3001), `db` (5432). + +### Comandi + +| Comando | Descrizione | +|---------|-------------| +| `pnpm dev` | Dev mode api + web | +| `pnpm build` | Build produzione | +| `pnpm test` | Test | +| `pnpm typecheck` | Controllo TypeScript | +| `pnpm db:push` | Sync schema database | +| `pnpm db:migrate` | Prisma migrate dev | + +### Struttura del repository + +``` +apps/ + api/ backend NestJS + web/ frontend Next.js +packages/ + config/ configurazione TypeScript condivisa +``` + +### Documentazione + +- [ARCHITECTURE.md](./ARCHITECTURE.md) — scelte tecnologiche e scalabilità +- [DOMAIN.md](./DOMAIN.md) — modello di dominio e casi d'uso + +### Graphify + +Il progetto include [Graphify](https://github.com/Graphify-Labs/graphify) per un knowledge graph interrogabile del codebase. + +```bash +graphify update . # aggiorna grafo dopo modifiche +graphify query "come funziona l'auth?" +``` + +Output in `graphify-out/`. + +### Aggiungere un modulo backend + +1. Crea `apps/api/src//` con module, service e controller +2. Aggiungi entità in `prisma/schema.prisma` con `organizationId` +3. Registra il modulo in `app.module.ts` +4. Aggiungi pagina/client API nel frontend + +### Test + +```bash +pnpm --filter @serviceops/api test # unit +pnpm --filter @serviceops/api test:e2e # e2e (richiede DB) +``` + +### Flussi MVP + +1. Registrazione → crea organizzazione e utente owner +2. Crea clienti e sedi +3. Crea commesse e voci (ricavi) +4. Registra ore e materiali (costi) +5. Visualizza margini per commessa e KPI dashboard + +### Licenza + +Proprietario — ServiceOps diff --git a/apps/api/.env.example b/apps/api/.env.example new file mode 100644 index 0000000..50ffbe0 --- /dev/null +++ b/apps/api/.env.example @@ -0,0 +1,33 @@ +DATABASE_URL="postgresql://serviceops:serviceops@localhost:5432/serviceops?schema=public" +JWT_SECRET="change-me-in-production-use-long-random-string" +JWT_EXPIRES_IN="7d" +PORT=3001 +CORS_ORIGIN="http://localhost:3000" +NODE_ENV=development + +# Stripe (optional) +STRIPE_SECRET_KEY= +STRIPE_WEBHOOK_SECRET= +STRIPE_PRICE_PRO= +STRIPE_PRICE_BUSINESS= +STRIPE_SUCCESS_URL=http://localhost:3000/settings?billing=success +STRIPE_CANCEL_URL=http://localhost:3000/settings?billing=cancel + +# Lemon Squeezy (optional alternative) +LEMONSQUEEZY_API_KEY= +LEMONSQUEEZY_STORE_ID= +LEMONSQUEEZY_VARIANT_PRO= +LEMONSQUEEZY_VARIANT_BUSINESS= +LEMONSQUEEZY_WEBHOOK_SECRET= + +# SSO +OIDC_CALLBACK_URL=http://localhost:3001/auth/sso/oidc/callback +SAML_CALLBACK_URL=http://localhost:3001/auth/sso/saml/callback +SAML_ISSUER=serviceops +SAML_IDP_CERT= +FRONTEND_SSO_CALLBACK_URL=http://localhost:3000/auth/callback + +# OpenTelemetry (optional) +OTEL_ENABLED=0 +OTEL_SERVICE_NAME=serviceops-api +OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile new file mode 100644 index 0000000..ec544d1 --- /dev/null +++ b/apps/api/Dockerfile @@ -0,0 +1,26 @@ +FROM node:22-alpine AS base +RUN corepack enable && corepack prepare pnpm@9.15.4 --activate +WORKDIR /app + +FROM base AS deps +COPY package.json pnpm-workspace.yaml pnpm-lock.yaml* .npmrc ./ +COPY apps/api/package.json ./apps/api/ +COPY packages/config/package.json ./packages/config/ +RUN pnpm install --filter @serviceops/api... + +FROM deps AS build +COPY apps/api ./apps/api +COPY packages ./packages +RUN pnpm --filter @serviceops/api exec prisma generate +RUN pnpm --filter @serviceops/api run build + +FROM node:22-alpine AS runner +WORKDIR /app +ENV NODE_ENV=production +COPY --from=build /app/apps/api/dist ./dist +COPY --from=build /app/apps/api/package.json ./ +COPY --from=build /app/apps/api/prisma ./prisma +COPY --from=build /app/node_modules ./node_modules +COPY --from=build /app/apps/api/node_modules ./node_modules +EXPOSE 3001 +CMD ["sh", "-c", "npx prisma migrate deploy && node dist/main.js"] diff --git a/apps/api/jest.config.js b/apps/api/jest.config.js new file mode 100644 index 0000000..914ceeb --- /dev/null +++ b/apps/api/jest.config.js @@ -0,0 +1,11 @@ +module.exports = { + moduleFileExtensions: ['js', 'json', 'ts'], + rootDir: 'src', + testRegex: '.*\\.spec\\.ts$', + transform: { + '^.+\\.(t|j)s$': 'ts-jest', + }, + collectCoverageFrom: ['**/*.(t|j)s'], + coverageDirectory: '../coverage', + testEnvironment: 'node', +}; diff --git a/apps/api/nest-cli.json b/apps/api/nest-cli.json new file mode 100644 index 0000000..f9aa683 --- /dev/null +++ b/apps/api/nest-cli.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src", + "compilerOptions": { + "deleteOutDir": true + } +} diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..4a6266e --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,63 @@ +{ + "name": "@serviceops/api", + "version": "0.1.0", + "private": true, + "scripts": { + "build": "nest build", + "dev": "nest start --watch", + "start": "node dist/main.js", + "start:prod": "node dist/main.js", + "lint": "eslint \"{src,test}/**/*.ts\"", + "typecheck": "tsc --noEmit", + "test": "jest", + "test:e2e": "jest --config ./test/jest-e2e.json", + "prisma:generate": "prisma generate", + "prisma:migrate": "prisma migrate dev", + "prisma:push": "prisma db push" + }, + "dependencies": { + "@nestjs/common": "^11.0.7", + "@nestjs/config": "^4.0.0", + "@nestjs/core": "^11.0.7", + "@nestjs/jwt": "^11.0.0", + "@nestjs/passport": "^11.0.5", + "@nestjs/platform-express": "^11.0.7", + "@nestjs/throttler": "^6.4.0", + "@prisma/client": "^6.3.1", + "bcrypt": "^5.1.1", + "class-transformer": "^0.5.1", + "class-validator": "^0.14.1", + "csv-stringify": "^6.5.2", + "passport": "^0.7.0", + "passport-jwt": "^4.0.1", + "pdfkit": "^0.16.0", + "openid-client": "^5.6.5", + "@node-saml/node-saml": "^5.0.0", + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/auto-instrumentations-node": "^0.56.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.57.0", + "@opentelemetry/sdk-node": "^0.57.0", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "stripe": "^17.7.0", + "zod": "^3.24.1" + }, + "devDependencies": { + "@nestjs/cli": "^11.0.2", + "@nestjs/schematics": "^11.0.0", + "@nestjs/testing": "^11.0.7", + "@types/bcrypt": "^5.0.2", + "@types/express": "^5.0.0", + "@types/jest": "^29.5.14", + "@types/node": "^22.10.7", + "@types/passport-jwt": "^4.0.1", + "@types/pdfkit": "^0.13.8", + "@types/supertest": "^6.0.2", + "jest": "^29.7.0", + "prisma": "^6.3.1", + "supertest": "^7.0.0", + "ts-jest": "^29.2.5", + "ts-node": "^10.9.2", + "typescript": "^5.7.3" + } +} diff --git a/apps/api/prisma/migrations/migration_lock.toml b/apps/api/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..99e4f20 --- /dev/null +++ b/apps/api/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (i.e. Git) +provider = "postgresql" diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma new file mode 100644 index 0000000..d62d95e --- /dev/null +++ b/apps/api/prisma/schema.prisma @@ -0,0 +1,439 @@ +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +enum MembershipRole { + OWNER + ADMIN + MEMBER + TECHNICIAN +} + +enum SubscriptionPlan { + FREE + PRO + BUSINESS +} + +enum JobStatus { + DRAFT + CONFIRMED + IN_PROGRESS + COMPLETED + INVOICED +} + +enum JobItemType { + SERVICE + PART + OTHER +} + +enum InventoryMovementType { + IN + OUT +} + +enum DocumentStatus { + DRAFT + SENT + ACCEPTED + REJECTED + PAID + CANCELLED +} + +enum SsoProvider { + OIDC + SAML +} + +enum PaymentProvider { + STRIPE + LEMONSQUEEZY +} + +model Organization { + id String @id @default(cuid()) + name String + slug String @unique + settings Json @default("{}") + plan SubscriptionPlan @default(FREE) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + memberships Membership[] + customers Customer[] + sites Site[] + jobs Job[] + materials Material[] + inventoryMovements InventoryMovement[] + quotes Quote[] + invoices Invoice[] + subscriptions Subscription[] + + ssoConfig OrganizationSsoConfig? + + @@map("organizations") +} + +model User { + id String @id @default(cuid()) + email String @unique + passwordHash String + firstName String + lastName String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + memberships Membership[] + activities Activity[] + externalIdentities ExternalIdentity[] + + @@map("users") +} + +model Membership { + id String @id @default(cuid()) + userId String + organizationId String + role MembershipRole @default(MEMBER) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + + @@unique([userId, organizationId]) + @@index([organizationId]) + @@map("memberships") +} + +model Customer { + id String @id @default(cuid()) + organizationId String + name String + taxId String? + email String? + phone String? + address String? + city String? + postalCode String? + country String? @default("IT") + notes String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + contacts Contact[] + sites Site[] + jobs Job[] + + @@index([organizationId]) + @@index([organizationId, name]) + @@map("customers") +} + +model Contact { + id String @id @default(cuid()) + organizationId String + customerId String + name String + email String? + phone String? + role String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) + + @@index([organizationId]) + @@index([organizationId, customerId]) + @@map("contacts") +} + +model Site { + id String @id @default(cuid()) + organizationId String + customerId String + name String + address String? + city String? + postalCode String? + notes String? + latitude Float? + longitude Float? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) + jobs Job[] + + @@index([organizationId]) + @@index([organizationId, customerId]) + @@map("sites") +} + +model Job { + id String @id @default(cuid()) + organizationId String + customerId String + siteId String? + title String + reference String? + status JobStatus @default(DRAFT) + description String? + tags String[] @default([]) + startDate DateTime? + dueDate DateTime? + completedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) + site Site? @relation(fields: [siteId], references: [id], onDelete: SetNull) + items JobItem[] + activities Activity[] + materialUsages MaterialUsage[] + inventoryMovements InventoryMovement[] + quotes Quote[] + invoices Invoice[] + + @@index([organizationId]) + @@index([organizationId, status]) + @@index([organizationId, customerId]) + @@map("jobs") +} + +model JobItem { + id String @id @default(cuid()) + organizationId String + jobId String + description String + quantity Decimal @default(1) @db.Decimal(12, 4) + unitPrice Decimal @default(0) @db.Decimal(12, 4) + type JobItemType @default(SERVICE) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + job Job @relation(fields: [jobId], references: [id], onDelete: Cascade) + + @@index([organizationId]) + @@index([organizationId, jobId]) + @@map("job_items") +} + +model Activity { + id String @id @default(cuid()) + organizationId String + jobId String + userId String? + date DateTime @default(now()) + hours Decimal @db.Decimal(8, 2) + hourlyCost Decimal @default(0) @db.Decimal(12, 4) + description String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + job Job @relation(fields: [jobId], references: [id], onDelete: Cascade) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + + @@index([organizationId]) + @@index([organizationId, jobId]) + @@map("activities") +} + +model Material { + id String @id @default(cuid()) + organizationId String + name String + code String? + unit String @default("pz") + minStock Decimal? @db.Decimal(12, 4) + averageCost Decimal @default(0) @db.Decimal(12, 4) + stockQuantity Decimal @default(0) @db.Decimal(12, 4) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + usages MaterialUsage[] + movements InventoryMovement[] + + @@index([organizationId]) + @@unique([organizationId, code]) + @@map("materials") +} + +model MaterialUsage { + id String @id @default(cuid()) + organizationId String + jobId String + materialId String + quantity Decimal @db.Decimal(12, 4) + unitCost Decimal @default(0) @db.Decimal(12, 4) + notes String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + job Job @relation(fields: [jobId], references: [id], onDelete: Cascade) + material Material @relation(fields: [materialId], references: [id], onDelete: Cascade) + + @@index([organizationId]) + @@index([organizationId, jobId]) + @@map("material_usages") +} + +model InventoryMovement { + id String @id @default(cuid()) + organizationId String + materialId String + jobId String? + type InventoryMovementType + quantity Decimal @db.Decimal(12, 4) + date DateTime @default(now()) + notes String? + createdAt DateTime @default(now()) + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + material Material @relation(fields: [materialId], references: [id], onDelete: Cascade) + job Job? @relation(fields: [jobId], references: [id], onDelete: SetNull) + + @@index([organizationId]) + @@index([organizationId, materialId]) + @@map("inventory_movements") +} + +model Quote { + id String @id @default(cuid()) + organizationId String + jobId String? + number String + status DocumentStatus @default(DRAFT) + totalAmount Decimal @default(0) @db.Decimal(12, 4) + validUntil DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + job Job? @relation(fields: [jobId], references: [id], onDelete: SetNull) + lines QuoteLine[] + + @@unique([organizationId, number]) + @@index([organizationId]) + @@map("quotes") +} + +model QuoteLine { + id String @id @default(cuid()) + organizationId String + quoteId String + description String + quantity Decimal @default(1) @db.Decimal(12, 4) + unitPrice Decimal @default(0) @db.Decimal(12, 4) + createdAt DateTime @default(now()) + + quote Quote @relation(fields: [quoteId], references: [id], onDelete: Cascade) + + @@index([organizationId]) + @@index([organizationId, quoteId]) + @@map("quote_lines") +} + +model Invoice { + id String @id @default(cuid()) + organizationId String + jobId String? + number String + status DocumentStatus @default(DRAFT) + totalAmount Decimal @default(0) @db.Decimal(12, 4) + issuedAt DateTime? + dueAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + job Job? @relation(fields: [jobId], references: [id], onDelete: SetNull) + lines InvoiceLine[] + + @@unique([organizationId, number]) + @@index([organizationId]) + @@map("invoices") +} + +model InvoiceLine { + id String @id @default(cuid()) + organizationId String + invoiceId String + description String + quantity Decimal @default(1) @db.Decimal(12, 4) + unitPrice Decimal @default(0) @db.Decimal(12, 4) + createdAt DateTime @default(now()) + + invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade) + + @@index([organizationId]) + @@index([organizationId, invoiceId]) + @@map("invoice_lines") +} + +model Subscription { + id String @id @default(cuid()) + organizationId String + plan SubscriptionPlan @default(FREE) + paymentProvider PaymentProvider @default(STRIPE) + stripeCustomerId String? + stripeSubscriptionId String? + lemonSqueezyCustomerId String? + lemonSqueezySubscriptionId String? + status String @default("active") + currentPeriodEnd DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + + @@index([organizationId]) + @@map("subscriptions") +} + +model OrganizationSsoConfig { + id String @id @default(cuid()) + organizationId String @unique + provider SsoProvider + enabled Boolean @default(false) + issuer String + clientId String? + clientSecret String? + metadataUrl String? + idpCert String? + emailAttribute String @default("email") + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + + @@map("organization_sso_configs") +} + +model ExternalIdentity { + id String @id @default(cuid()) + userId String + organizationId String + provider SsoProvider + externalId String + email String + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([provider, externalId, organizationId]) + @@index([organizationId]) + @@map("external_identities") +} diff --git a/apps/api/src/MODULES.md b/apps/api/src/MODULES.md new file mode 100644 index 0000000..3d5d88d --- /dev/null +++ b/apps/api/src/MODULES.md @@ -0,0 +1,22 @@ +# Backend modules + +| Module | Path | Responsibility | +|--------|------|----------------| +| `auth` | `src/auth/` | JWT login, register, switch organization | +| `organizations` | `src/organizations/` | Tenant settings, create additional orgs | +| `users` | `src/users/` | List members of current organization | +| `crm` | `src/crm/` | Customers, sites, contacts | +| `jobs` | `src/jobs/` | Jobs, line items, economics on read | +| `activities` | `src/activities/` | Labor hours, material usage on jobs | +| `inventory` | `src/inventory/` | Materials, movements, low-stock alerts | +| `billing` | `src/billing/` | Quotes, invoices, Stripe checkout/webhooks | +| `reports` | `src/reports/` | Dashboard KPIs, margins, PDF/CSV export | +| `prisma` | `src/prisma/` | Database client (global module) | + +## Adding a module + +1. Create folder under `src//` with `*.module.ts`, `*.service.ts`, `*.controller.ts` +2. Add DTOs with `class-validator` in `dto/` +3. Ensure all Prisma queries filter by `organizationId` +4. Register in `app.module.ts` +5. Add frontend page + TanStack Query hooks diff --git a/apps/api/src/activities/activities.controller.ts b/apps/api/src/activities/activities.controller.ts new file mode 100644 index 0000000..78dd23d --- /dev/null +++ b/apps/api/src/activities/activities.controller.ts @@ -0,0 +1,29 @@ +import { Controller, Get, Post, Body, Query } from '@nestjs/common'; +import { ActivitiesService } from './activities.service'; +import { CreateActivityDto, CreateMaterialUsageDto } from './dto/activities.dto'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('activities') +export class ActivitiesController { + constructor(private readonly activitiesService: ActivitiesService) {} + + @Get() + list(@CurrentUser() user: AuthUserPayload, @Query('jobId') jobId?: string) { + return this.activitiesService.list(user.organizationId, jobId); + } + + @Post() + createActivity(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateActivityDto) { + return this.activitiesService.createActivity(user.organizationId, dto); + } + + @Get('material-usages') + listMaterialUsages(@CurrentUser() user: AuthUserPayload, @Query('jobId') jobId?: string) { + return this.activitiesService.listMaterialUsages(user.organizationId, jobId); + } + + @Post('material-usages') + createMaterialUsage(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateMaterialUsageDto) { + return this.activitiesService.createMaterialUsage(user.organizationId, dto); + } +} diff --git a/apps/api/src/activities/activities.module.ts b/apps/api/src/activities/activities.module.ts new file mode 100644 index 0000000..45e3cef --- /dev/null +++ b/apps/api/src/activities/activities.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { ActivitiesController } from './activities.controller'; +import { ActivitiesService } from './activities.service'; + +@Module({ + controllers: [ActivitiesController], + providers: [ActivitiesService], +}) +export class ActivitiesModule {} diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts new file mode 100644 index 0000000..ef70761 --- /dev/null +++ b/apps/api/src/activities/activities.service.ts @@ -0,0 +1,90 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateActivityDto, CreateMaterialUsageDto } from './dto/activities.dto'; + +@Injectable() +export class ActivitiesService { + constructor(private readonly prisma: PrismaService) {} + + list(organizationId: string, jobId?: string) { + return this.prisma.activity.findMany({ + where: { organizationId, ...(jobId ? { jobId } : {}) }, + include: { + job: { select: { id: true, title: true } }, + user: { select: { id: true, firstName: true, lastName: true } }, + }, + orderBy: { date: 'desc' }, + }); + } + + async createActivity(organizationId: string, dto: CreateActivityDto) { + await this.ensureJob(organizationId, dto.jobId); + return this.prisma.activity.create({ + data: { + organizationId, + jobId: dto.jobId, + userId: dto.userId, + date: new Date(dto.date), + hours: dto.hours, + hourlyCost: dto.hourlyCost, + description: dto.description, + }, + }); + } + + async createMaterialUsage(organizationId: string, dto: CreateMaterialUsageDto) { + await this.ensureJob(organizationId, dto.jobId); + const material = await this.prisma.material.findFirst({ + where: { id: dto.materialId, organizationId }, + }); + if (!material) throw new NotFoundException('Material not found'); + + const usage = await this.prisma.$transaction(async (tx) => { + const created = await tx.materialUsage.create({ + data: { + organizationId, + jobId: dto.jobId, + materialId: dto.materialId, + quantity: dto.quantity, + unitCost: dto.unitCost, + notes: dto.notes, + }, + include: { material: true }, + }); + + await tx.material.update({ + where: { id: dto.materialId }, + data: { stockQuantity: { decrement: dto.quantity } }, + }); + + await tx.inventoryMovement.create({ + data: { + organizationId, + materialId: dto.materialId, + jobId: dto.jobId, + type: 'OUT', + quantity: dto.quantity, + notes: `Usage on job ${dto.jobId}`, + }, + }); + + return created; + }); + + return usage; + } + + listMaterialUsages(organizationId: string, jobId?: string) { + return this.prisma.materialUsage.findMany({ + where: { organizationId, ...(jobId ? { jobId } : {}) }, + include: { material: true, job: { select: { id: true, title: true } } }, + orderBy: { createdAt: 'desc' }, + }); + } + + private async ensureJob(organizationId: string, jobId: string) { + const job = await this.prisma.job.findFirst({ where: { id: jobId, organizationId } }); + if (!job) throw new NotFoundException('Job not found'); + return job; + } +} diff --git a/apps/api/src/activities/dto/activities.dto.ts b/apps/api/src/activities/dto/activities.dto.ts new file mode 100644 index 0000000..7f50164 --- /dev/null +++ b/apps/api/src/activities/dto/activities.dto.ts @@ -0,0 +1,18 @@ +import { IsNumber, IsOptional, IsString, MinLength, IsDateString } from 'class-validator'; + +export class CreateActivityDto { + @IsString() @MinLength(1) jobId!: string; + @IsDateString() date!: string; + @IsNumber() hours!: number; + @IsNumber() hourlyCost!: number; + @IsOptional() @IsString() description?: string; + @IsOptional() @IsString() userId?: string; +} + +export class CreateMaterialUsageDto { + @IsString() @MinLength(1) jobId!: string; + @IsString() @MinLength(1) materialId!: string; + @IsNumber() quantity!: number; + @IsNumber() unitCost!: number; + @IsOptional() @IsString() notes?: string; +} diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts new file mode 100644 index 0000000..5e1cc32 --- /dev/null +++ b/apps/api/src/app.module.ts @@ -0,0 +1,40 @@ +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'; +import { APP_FILTER, APP_GUARD } from '@nestjs/core'; +import { ActivitiesModule } from './activities/activities.module'; +import { AuthModule } from './auth/auth.module'; +import { BillingModule } from './billing/billing.module'; +import { CrmModule } from './crm/crm.module'; +import { GlobalExceptionFilter } from './common/filters/global-exception.filter'; +import { InventoryModule } from './inventory/inventory.module'; +import { JobsModule } from './jobs/jobs.module'; +import { OrganizationsModule } from './organizations/organizations.module'; +import { PrismaModule } from './prisma/prisma.module'; +import { ReportsModule } from './reports/reports.module'; +import { UsersModule } from './users/users.module'; + +@Module({ + imports: [ + ConfigModule.forRoot({ isGlobal: true }), + ThrottlerModule.forRoot([ + { name: 'default', ttl: 60000, limit: 120 }, + { name: 'auth', ttl: 60000, limit: 20 }, + ]), + PrismaModule, + AuthModule, + OrganizationsModule, + UsersModule, + CrmModule, + JobsModule, + ActivitiesModule, + InventoryModule, + BillingModule, + ReportsModule, + ], + providers: [ + { provide: APP_FILTER, useClass: GlobalExceptionFilter }, + { provide: APP_GUARD, useClass: ThrottlerGuard }, + ], +}) +export class AppModule {} diff --git a/apps/api/src/auth/auth.controller.ts b/apps/api/src/auth/auth.controller.ts new file mode 100644 index 0000000..3f7f7df --- /dev/null +++ b/apps/api/src/auth/auth.controller.ts @@ -0,0 +1,38 @@ +import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common'; +import { Throttle } from '@nestjs/throttler'; +import { AuthService } from './auth.service'; +import { LoginDto, RegisterDto } from './dto/login.dto'; +import { SwitchOrganizationDto } from './dto/switch-organization.dto'; +import { Public, CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; +import { JwtAuthGuard } from './guards/jwt-auth.guard'; + +@Controller('auth') +export class AuthController { + constructor(private readonly authService: AuthService) {} + + @Public() + @Throttle({ auth: { limit: 10, ttl: 60000 } }) + @Post('register') + register(@Body() dto: RegisterDto) { + return this.authService.register(dto); + } + + @Public() + @Throttle({ auth: { limit: 10, ttl: 60000 } }) + @Post('login') + login(@Body() dto: LoginDto) { + return this.authService.login(dto); + } + + @UseGuards(JwtAuthGuard) + @Get('me') + me(@CurrentUser() user: AuthUserPayload) { + return this.authService.me(user.userId); + } + + @UseGuards(JwtAuthGuard) + @Post('switch-organization') + switchOrganization(@CurrentUser() user: AuthUserPayload, @Body() dto: SwitchOrganizationDto) { + return this.authService.switchOrganization(user.userId, dto.organizationId); + } +} diff --git a/apps/api/src/auth/auth.module.ts b/apps/api/src/auth/auth.module.ts new file mode 100644 index 0000000..4db9566 --- /dev/null +++ b/apps/api/src/auth/auth.module.ts @@ -0,0 +1,32 @@ +import { Module } from '@nestjs/common'; +import { JwtModule } from '@nestjs/jwt'; +import { PassportModule } from '@nestjs/passport'; +import { ConfigModule, ConfigService } from '@nestjs/config'; +import { APP_GUARD } from '@nestjs/core'; +import { AuthController } from './auth.controller'; +import { AuthService } from './auth.service'; +import { SsoController } from './sso.controller'; +import { SsoService } from './sso.service'; +import { JwtAuthGuard } from './guards/jwt-auth.guard'; +import { JwtStrategy } from './strategies/jwt.strategy'; + +@Module({ + imports: [ + PassportModule.register({ defaultStrategy: 'jwt' }), + JwtModule.registerAsync({ + imports: [ConfigModule], + inject: [ConfigService], + useFactory: (config: ConfigService) => { + const expiresIn = config.get('JWT_EXPIRES_IN', '7d'); + return { + secret: config.get('JWT_SECRET', 'dev-secret'), + signOptions: { expiresIn: expiresIn as '7d' }, + }; + }, + }), + ], + controllers: [AuthController, SsoController], + providers: [AuthService, SsoService, JwtStrategy, { provide: APP_GUARD, useClass: JwtAuthGuard }], + exports: [AuthService, SsoService], +}) +export class AuthModule {} diff --git a/apps/api/src/auth/auth.service.ts b/apps/api/src/auth/auth.service.ts new file mode 100644 index 0000000..2ba5a8c --- /dev/null +++ b/apps/api/src/auth/auth.service.ts @@ -0,0 +1,160 @@ +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { JwtService } from '@nestjs/jwt'; +import * as bcrypt from 'bcrypt'; +import { MembershipRole } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { slugify } from '../common/utils/economics.util'; +import { LoginDto } from './dto/login.dto'; +import { RegisterDto } from './dto/register.dto'; +import { SwitchOrganizationDto } from './dto/switch-organization.dto'; + +@Injectable() +export class AuthService { + constructor( + private readonly prisma: PrismaService, + private readonly jwt: JwtService, + private readonly config: ConfigService, + ) {} + + async register(dto: RegisterDto) { + const existing = await this.prisma.user.findUnique({ where: { email: dto.email } }); + if (existing) { + throw new UnauthorizedException('Email already registered'); + } + + const passwordHash = await bcrypt.hash(dto.password, 12); + const baseSlug = dto.organizationSlug ?? slugify(dto.organizationName); + const slug = `${baseSlug}-${Date.now().toString(36)}`; + + const result = await this.prisma.$transaction(async (tx) => { + const user = await tx.user.create({ + data: { + email: dto.email, + passwordHash, + firstName: dto.firstName, + lastName: dto.lastName, + }, + }); + + const organization = await tx.organization.create({ + data: { + name: dto.organizationName, + slug, + settings: { + currency: 'EUR', + timezone: 'Europe/Rome', + dateFormat: 'DD/MM/YYYY', + features: { inventory: true, billing: true }, + }, + }, + }); + + await tx.membership.create({ + data: { + userId: user.id, + organizationId: organization.id, + role: MembershipRole.OWNER, + }, + }); + + await tx.subscription.create({ + data: { organizationId: organization.id, plan: 'FREE', status: 'active' }, + }); + + return { user, organization }; + }); + + return this.buildAuthResponse(result.user, result.organization.id, MembershipRole.OWNER); + } + + async login(dto: LoginDto) { + const user = await this.prisma.user.findUnique({ where: { email: dto.email } }); + if (!user) { + throw new UnauthorizedException('Invalid credentials'); + } + + const valid = await bcrypt.compare(dto.password, user.passwordHash); + if (!valid) { + throw new UnauthorizedException('Invalid credentials'); + } + + const membership = await this.prisma.membership.findFirst({ + where: { userId: user.id }, + orderBy: { createdAt: 'asc' }, + }); + + if (!membership) { + throw new UnauthorizedException('No organization membership found'); + } + + return this.buildAuthResponse(user, membership.organizationId, membership.role); + } + + async switchOrganization(userId: string, organizationId: string) { + const membership = await this.prisma.membership.findFirst({ + where: { userId, organizationId }, + }); + if (!membership) { + throw new UnauthorizedException('Not a member of this organization'); + } + + const user = await this.prisma.user.findUnique({ where: { id: userId } }); + if (!user) throw new UnauthorizedException('User not found'); + + return this.buildAuthResponse(user, organizationId, membership.role); + } + + async me(userId: string) { + const user = await this.prisma.user.findUnique({ + where: { id: userId }, + select: { + id: true, + email: true, + firstName: true, + lastName: true, + memberships: { + select: { + role: true, + organization: { select: { id: true, name: true, slug: true, plan: true, settings: true } }, + }, + }, + }, + }); + + return user; + } + + private async buildAuthResponse( + user: { id: string; email: string; firstName: string; lastName: string }, + organizationId: string, + role: MembershipRole, + ) { + const organization = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { id: true, name: true, slug: true, plan: true }, + }); + + const payload = { + sub: user.id, + email: user.email, + organizationId, + role, + }; + + const accessToken = this.jwt.sign(payload); + + return { + accessToken, + user: { + id: user.id, + email: user.email, + firstName: user.firstName, + lastName: user.lastName, + organizationId, + organizationName: organization?.name ?? '', + role, + }, + }; + } +} diff --git a/apps/api/src/auth/dto/login.dto.ts b/apps/api/src/auth/dto/login.dto.ts new file mode 100644 index 0000000..a783ca3 --- /dev/null +++ b/apps/api/src/auth/dto/login.dto.ts @@ -0,0 +1,35 @@ +import { IsEmail, IsOptional, IsString, MinLength } from 'class-validator'; + +export class RegisterDto { + @IsEmail() + email!: string; + + @IsString() + @MinLength(8) + password!: string; + + @IsString() + @MinLength(1) + firstName!: string; + + @IsString() + @MinLength(1) + lastName!: string; + + @IsString() + @MinLength(2) + organizationName!: string; + + @IsOptional() + @IsString() + organizationSlug?: string; +} + +export class LoginDto { + @IsEmail() + email!: string; + + @IsString() + @MinLength(1) + password!: string; +} diff --git a/apps/api/src/auth/dto/register.dto.ts b/apps/api/src/auth/dto/register.dto.ts new file mode 100644 index 0000000..dde3296 --- /dev/null +++ b/apps/api/src/auth/dto/register.dto.ts @@ -0,0 +1 @@ +export { LoginDto, RegisterDto } from './login.dto'; diff --git a/apps/api/src/auth/dto/sso.dto.ts b/apps/api/src/auth/dto/sso.dto.ts new file mode 100644 index 0000000..dd0b4b6 --- /dev/null +++ b/apps/api/src/auth/dto/sso.dto.ts @@ -0,0 +1,34 @@ +import { IsBoolean, IsEnum, IsOptional, IsString, IsUrl, MinLength } from 'class-validator'; +import { SsoProvider } from '@prisma/client'; + +export class UpdateSsoConfigDto { + @IsEnum(SsoProvider) + provider!: SsoProvider; + + @IsBoolean() + enabled!: boolean; + + @IsString() + @MinLength(3) + issuer!: string; + + @IsOptional() + @IsString() + clientId?: string; + + @IsOptional() + @IsString() + clientSecret?: string; + + @IsOptional() + @IsUrl({ require_tld: false }) + metadataUrl?: string; + + @IsOptional() + @IsString() + idpCert?: string; + + @IsOptional() + @IsString() + emailAttribute?: string; +} diff --git a/apps/api/src/auth/dto/switch-organization.dto.ts b/apps/api/src/auth/dto/switch-organization.dto.ts new file mode 100644 index 0000000..99e82a4 --- /dev/null +++ b/apps/api/src/auth/dto/switch-organization.dto.ts @@ -0,0 +1,7 @@ +import { IsString, MinLength } from 'class-validator'; + +export class SwitchOrganizationDto { + @IsString() + @MinLength(1) + organizationId!: string; +} diff --git a/apps/api/src/auth/guards/jwt-auth.guard.ts b/apps/api/src/auth/guards/jwt-auth.guard.ts new file mode 100644 index 0000000..fee1f1a --- /dev/null +++ b/apps/api/src/auth/guards/jwt-auth.guard.ts @@ -0,0 +1,20 @@ +import { Injectable, ExecutionContext } from '@nestjs/common'; +import { AuthGuard } from '@nestjs/passport'; +import { Reflector } from '@nestjs/core'; +import { IS_PUBLIC_KEY } from '../../common/decorators/auth.decorator'; + +@Injectable() +export class JwtAuthGuard extends AuthGuard('jwt') { + constructor(private reflector: Reflector) { + super(); + } + + canActivate(context: ExecutionContext) { + const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ + context.getHandler(), + context.getClass(), + ]); + if (isPublic) return true; + return super.canActivate(context); + } +} diff --git a/apps/api/src/auth/sso.controller.ts b/apps/api/src/auth/sso.controller.ts new file mode 100644 index 0000000..dfae74d --- /dev/null +++ b/apps/api/src/auth/sso.controller.ts @@ -0,0 +1,66 @@ +import { Controller, Get, Post, Patch, Body, Param, Query, Res, ForbiddenException } from '@nestjs/common'; +import { Response } from 'express'; +import { SsoService } from './sso.service'; +import { UpdateSsoConfigDto } from './dto/sso.dto'; +import { Public, CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('auth/sso') +export class SsoController { + constructor(private readonly ssoService: SsoService) {} + + @Public() + @Get('config/:slug') + getPublicConfig(@Param('slug') slug: string) { + return this.ssoService.getPublicConfigBySlug(slug); + } + + @Public() + @Get('oidc/:slug') + async oidcLogin(@Param('slug') slug: string, @Res() res: Response) { + const url = await this.ssoService.initiateOidcLogin(slug); + return res.redirect(url); + } + + @Public() + @Get('oidc/callback') + async oidcCallback(@Query() query: Record, @Res() res: Response) { + const { accessToken } = await this.ssoService.handleOidcCallback(query); + const frontend = process.env.FRONTEND_SSO_CALLBACK_URL ?? 'http://localhost:3000/auth/callback'; + return res.redirect(`${frontend}?token=${encodeURIComponent(accessToken)}`); + } + + @Public() + @Get('saml/:slug') + async samlLogin(@Param('slug') slug: string, @Res() res: Response) { + const url = await this.ssoService.initiateSamlLogin(slug); + return res.redirect(url); + } + + @Public() + @Get('saml/:slug/metadata') + async samlMetadata(@Param('slug') slug: string) { + const xml = await this.ssoService.getSamlMetadata(slug); + return xml; + } + + @Public() + @Post('saml/callback') + async samlCallback(@Body() body: Record, @Res() res: Response) { + const { accessToken } = await this.ssoService.handleSamlCallback(body); + const frontend = process.env.FRONTEND_SSO_CALLBACK_URL ?? 'http://localhost:3000/auth/callback'; + return res.redirect(`${frontend}?token=${encodeURIComponent(accessToken)}`); + } + + @Get('config') + getConfig(@CurrentUser() user: AuthUserPayload) { + return this.ssoService.getConfig(user.organizationId); + } + + @Patch('config') + updateConfig(@CurrentUser() user: AuthUserPayload, @Body() dto: UpdateSsoConfigDto) { + if (user.role !== 'OWNER' && user.role !== 'ADMIN') { + throw new ForbiddenException('Only OWNER or ADMIN can configure SSO'); + } + return this.ssoService.updateConfig(user.organizationId, dto); + } +} diff --git a/apps/api/src/auth/sso.service.ts b/apps/api/src/auth/sso.service.ts new file mode 100644 index 0000000..b720b5a --- /dev/null +++ b/apps/api/src/auth/sso.service.ts @@ -0,0 +1,323 @@ +import { + BadRequestException, + Injectable, + Logger, + NotFoundException, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { Issuer, generators } from 'openid-client'; +import { SAML, ValidateInResponseTo } from '@node-saml/node-saml'; +import { MembershipRole, SsoProvider } from '@prisma/client'; +import * as bcrypt from 'bcrypt'; +import { randomBytes } from 'crypto'; +import { JwtService } from '@nestjs/jwt'; +import { PrismaService } from '../prisma/prisma.service'; +import { UpdateSsoConfigDto } from './dto/sso.dto'; + +interface PendingOidcLogin { + codeVerifier: string; + organizationId: string; + expiresAt: number; +} + +@Injectable() +export class SsoService { + private readonly logger = new Logger(SsoService.name); + private readonly pendingOidc = new Map(); + + constructor( + private readonly prisma: PrismaService, + private readonly jwt: JwtService, + private readonly config: ConfigService, + ) {} + + async getPublicConfigBySlug(slug: string) { + const org = await this.prisma.organization.findUnique({ + where: { slug }, + include: { ssoConfig: true }, + }); + if (!org?.ssoConfig?.enabled) return null; + return { + organizationId: org.id, + organizationName: org.name, + slug: org.slug, + provider: org.ssoConfig.provider, + }; + } + + async updateConfig(organizationId: string, dto: UpdateSsoConfigDto) { + return this.prisma.organizationSsoConfig.upsert({ + where: { organizationId }, + create: { + organizationId, + provider: dto.provider, + enabled: dto.enabled, + issuer: dto.issuer, + clientId: dto.clientId, + clientSecret: dto.clientSecret, + metadataUrl: dto.metadataUrl, + idpCert: dto.idpCert, + emailAttribute: dto.emailAttribute ?? 'email', + }, + update: { + provider: dto.provider, + enabled: dto.enabled, + issuer: dto.issuer, + clientId: dto.clientId, + clientSecret: dto.clientSecret, + metadataUrl: dto.metadataUrl, + idpCert: dto.idpCert, + emailAttribute: dto.emailAttribute ?? 'email', + }, + }); + } + + async getConfig(organizationId: string) { + return this.prisma.organizationSsoConfig.findUnique({ where: { organizationId } }); + } + + async initiateOidcLogin(orgSlug: string): Promise { + const org = await this.getOrgWithSso(orgSlug, SsoProvider.OIDC); + const cfg = org.ssoConfig!; + if (!cfg.clientId) throw new BadRequestException('OIDC clientId not configured'); + + const issuer = await Issuer.discover(cfg.issuer); + const client = new issuer.Client({ + client_id: cfg.clientId, + client_secret: cfg.clientSecret ?? undefined, + redirect_uris: [this.oidcCallbackUrl()], + response_types: ['code'], + }); + + const codeVerifier = generators.codeVerifier(); + const codeChallenge = generators.codeChallenge(codeVerifier); + const state = generators.state(); + + this.pendingOidc.set(state, { + codeVerifier, + organizationId: org.id, + expiresAt: Date.now() + 10 * 60 * 1000, + }); + + return client.authorizationUrl({ + scope: 'openid email profile', + state, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + } + + async handleOidcCallback(query: Record): Promise<{ accessToken: string }> { + const state = query.state; + if (!state) throw new BadRequestException('Missing state'); + const pending = this.pendingOidc.get(state); + if (!pending || pending.expiresAt < Date.now()) { + throw new BadRequestException('Invalid or expired SSO session'); + } + this.pendingOidc.delete(state); + + const cfg = await this.prisma.organizationSsoConfig.findUnique({ + where: { organizationId: pending.organizationId }, + }); + if (!cfg?.enabled || cfg.provider !== SsoProvider.OIDC) { + throw new BadRequestException('SSO not configured'); + } + + const issuer = await Issuer.discover(cfg.issuer); + const client = new issuer.Client({ + client_id: cfg.clientId!, + client_secret: cfg.clientSecret ?? undefined, + redirect_uris: [this.oidcCallbackUrl()], + }); + + const params = client.callbackParams( + `${this.oidcCallbackUrl()}?${new URLSearchParams(query).toString()}`, + ); + const tokenSet = await client.callback(this.oidcCallbackUrl(), params, { + state, + code_verifier: pending.codeVerifier, + }); + + const claims = tokenSet.claims(); + const emailAttr = cfg.emailAttribute ?? 'email'; + const email = (claims[emailAttr] as string) ?? claims.email; + const externalId = claims.sub; + if (!email || !externalId) { + throw new BadRequestException('IdP did not return required claims (email/sub)'); + } + + return this.loginOrProvisionSsoUser({ + organizationId: pending.organizationId, + provider: SsoProvider.OIDC, + externalId, + email, + firstName: (claims.given_name as string) ?? email.split('@')[0] ?? 'User', + lastName: (claims.family_name as string) ?? '', + }); + } + + async getSamlMetadata(orgSlug: string): Promise { + const org = await this.getOrgWithSso(orgSlug, SsoProvider.SAML); + const saml = this.buildSamlInstance(org.slug, org.ssoConfig); + return saml.generateServiceProviderMetadata(null); + } + + async initiateSamlLogin(orgSlug: string): Promise { + const org = await this.getOrgWithSso(orgSlug, SsoProvider.SAML); + const saml = this.buildSamlInstance(org.slug, org.ssoConfig); + return await saml.getAuthorizeUrlAsync(orgSlug, undefined, {}); + } + + async handleSamlCallback(body: Record): Promise<{ accessToken: string }> { + const orgSlug = body.RelayState; + if (!orgSlug) throw new BadRequestException('Missing RelayState (org slug)'); + + const org = await this.getOrgWithSso(orgSlug, SsoProvider.SAML); + const saml = this.buildSamlInstance(org.slug, org.ssoConfig); + const { profile } = await saml.validatePostResponseAsync(body); + + const email = profile?.email ?? profile?.nameID; + const externalId = profile?.nameID; + if (!email || !externalId) { + throw new BadRequestException('SAML response missing email/nameID'); + } + + return this.loginOrProvisionSsoUser({ + organizationId: org.id, + provider: SsoProvider.SAML, + externalId, + email: String(email), + firstName: String(profile?.givenName ?? email.split('@')[0] ?? 'User'), + lastName: String(profile?.familyName ?? ''), + }); + } + + private async loginOrProvisionSsoUser(params: { + organizationId: string; + provider: SsoProvider; + externalId: string; + email: string; + firstName: string; + lastName: string; + }): Promise<{ accessToken: string }> { + let external = await this.prisma.externalIdentity.findUnique({ + where: { + provider_externalId_organizationId: { + provider: params.provider, + externalId: params.externalId, + organizationId: params.organizationId, + }, + }, + include: { user: true }, + }); + + let user = external?.user; + + if (!user) { + const existing = await this.prisma.user.findUnique({ where: { email: params.email } }); + if (existing) { + user = existing; + } else { + user = await this.prisma.user.create({ + data: { + email: params.email, + passwordHash: await bcrypt.hash(randomBytes(32).toString('hex'), 12), + firstName: params.firstName, + lastName: params.lastName, + }, + }); + } + + await this.prisma.externalIdentity.upsert({ + where: { + provider_externalId_organizationId: { + provider: params.provider, + externalId: params.externalId, + organizationId: params.organizationId, + }, + }, + create: { + userId: user.id, + organizationId: params.organizationId, + provider: params.provider, + externalId: params.externalId, + email: params.email, + }, + update: { email: params.email }, + }); + } + + const membership = await this.prisma.membership.findFirst({ + where: { userId: user.id, organizationId: params.organizationId }, + }); + + if (!membership) { + await this.prisma.membership.create({ + data: { + userId: user.id, + organizationId: params.organizationId, + role: MembershipRole.MEMBER, + }, + }); + } + + const role = membership?.role ?? MembershipRole.MEMBER; + const payload = { + sub: user.id, + email: user.email, + organizationId: params.organizationId, + role, + }; + + return { accessToken: this.jwt.sign(payload) }; + } + + private async getOrgWithSso(slug: string, provider: SsoProvider) { + const org = await this.prisma.organization.findUnique({ + where: { slug }, + include: { ssoConfig: true }, + }); + if (!org?.ssoConfig?.enabled || org.ssoConfig.provider !== provider) { + throw new NotFoundException('SSO not enabled for this organization'); + } + return { id: org.id, slug: org.slug, ssoConfig: org.ssoConfig }; + } + + private buildSamlInstance( + orgSlug: string, + cfg: { + issuer: string; + metadataUrl: string | null; + idpCert: string | null; + }, + ) { + const entryPoint = cfg.metadataUrl ?? cfg.issuer; + if (!entryPoint) { + throw new ServiceUnavailableException('SAML entry point not configured'); + } + + const idpCert = cfg.idpCert ?? this.config.get('SAML_IDP_CERT'); + if (!idpCert) { + throw new ServiceUnavailableException('SAML IdP certificate not configured'); + } + + return new SAML({ + issuer: this.config.get('SAML_ISSUER', 'serviceops'), + callbackUrl: this.samlCallbackUrl(), + entryPoint, + idpIssuer: cfg.issuer, + idpCert, + wantAssertionsSigned: false, + validateInResponseTo: ValidateInResponseTo.never, + }); + } + + private oidcCallbackUrl(): string { + return this.config.get('OIDC_CALLBACK_URL', 'http://localhost:3001/auth/sso/oidc/callback'); + } + + private samlCallbackUrl(): string { + return this.config.get('SAML_CALLBACK_URL', 'http://localhost:3001/auth/sso/saml/callback'); + } +} diff --git a/apps/api/src/auth/strategies/jwt.strategy.ts b/apps/api/src/auth/strategies/jwt.strategy.ts new file mode 100644 index 0000000..9265a8c --- /dev/null +++ b/apps/api/src/auth/strategies/jwt.strategy.ts @@ -0,0 +1,35 @@ +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { PassportStrategy } from '@nestjs/passport'; +import { ExtractJwt, Strategy } from 'passport-jwt'; +import { AuthUserPayload } from '../../common/decorators/auth.decorator'; + +interface JwtPayload { + sub: string; + email: string; + organizationId: string; + role: string; +} + +@Injectable() +export class JwtStrategy extends PassportStrategy(Strategy) { + constructor(config: ConfigService) { + super({ + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + ignoreExpiration: false, + secretOrKey: config.get('JWT_SECRET', 'dev-secret'), + }); + } + + validate(payload: JwtPayload): AuthUserPayload { + if (!payload.sub || !payload.organizationId) { + throw new UnauthorizedException(); + } + return { + userId: payload.sub, + email: payload.email, + organizationId: payload.organizationId, + role: payload.role, + }; + } +} diff --git a/apps/api/src/billing/billing.controller.ts b/apps/api/src/billing/billing.controller.ts new file mode 100644 index 0000000..931e0eb --- /dev/null +++ b/apps/api/src/billing/billing.controller.ts @@ -0,0 +1,111 @@ +import { + Controller, + Get, + Post, + Body, + Param, + Req, + Headers, + RawBodyRequest, +} from '@nestjs/common'; +import { Request } from 'express'; +import { PaymentProvider } from '@prisma/client'; +import { BillingService } from './billing.service'; +import { + CreateCheckoutDto, + CreateDocumentLineDto, + CreateInvoiceFromJobDto, + CreateQuoteFromJobDto, +} from './dto/billing.dto'; +import { CurrentUser, AuthUserPayload, Public } from '../common/decorators/auth.decorator'; + +@Controller('billing') +export class BillingController { + constructor(private readonly billingService: BillingService) {} + + @Get('quotes') + listQuotes(@CurrentUser() user: AuthUserPayload) { + return this.billingService.listQuotes(user.organizationId); + } + + @Get('quotes/:id') + getQuote(@CurrentUser() user: AuthUserPayload, @Param('id') id: string) { + return this.billingService.getQuote(user.organizationId, id); + } + + @Get('invoices') + listInvoices(@CurrentUser() user: AuthUserPayload) { + return this.billingService.listInvoices(user.organizationId); + } + + @Get('invoices/:id') + getInvoice(@CurrentUser() user: AuthUserPayload, @Param('id') id: string) { + return this.billingService.getInvoice(user.organizationId, id); + } + + @Get('subscription') + getSubscription(@CurrentUser() user: AuthUserPayload) { + return this.billingService.getSubscription(user.organizationId); + } + + @Post('quotes/from-job') + createQuoteFromJob(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateQuoteFromJobDto) { + return this.billingService.createQuoteFromJob(user.organizationId, dto); + } + + @Post('invoices/from-job') + createInvoiceFromJob(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateInvoiceFromJobDto) { + return this.billingService.createInvoiceFromJob(user.organizationId, dto); + } + + @Post('quotes/:id/lines') + addQuoteLine( + @CurrentUser() user: AuthUserPayload, + @Param('id') id: string, + @Body() dto: CreateDocumentLineDto, + ) { + return this.billingService.addQuoteLine(user.organizationId, id, dto); + } + + @Post('invoices/:id/lines') + addInvoiceLine( + @CurrentUser() user: AuthUserPayload, + @Param('id') id: string, + @Body() dto: CreateDocumentLineDto, + ) { + return this.billingService.addInvoiceLine(user.organizationId, id, dto); + } + + @Post('checkout') + createCheckout(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateCheckoutDto) { + return this.billingService.createCheckoutSession(user.organizationId, dto); + } + + @Post('stripe/checkout') + createStripeCheckout(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateCheckoutDto) { + return this.billingService.createCheckoutSession(user.organizationId, { + plan: dto.plan, + provider: PaymentProvider.STRIPE, + }); + } + + @Public() + @Post('stripe/webhook') + stripeWebhook( + @Req() req: RawBodyRequest, + @Headers('stripe-signature') signature: string | undefined, + ) { + const rawBody = req.rawBody ?? Buffer.from(''); + return this.billingService.handleStripeWebhook(rawBody, signature); + } + + @Public() + @Post('lemonsqueezy/webhook') + lemonWebhook( + @Req() req: RawBodyRequest, + @Headers('x-signature') signature: string | undefined, + ) { + const rawBody = req.rawBody ?? Buffer.from(''); + return this.billingService.handleLemonWebhook(rawBody, signature); + } +} diff --git a/apps/api/src/billing/billing.module.ts b/apps/api/src/billing/billing.module.ts new file mode 100644 index 0000000..7d92152 --- /dev/null +++ b/apps/api/src/billing/billing.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { BillingController } from './billing.controller'; +import { BillingService } from './billing.service'; + +@Module({ + controllers: [BillingController], + providers: [BillingService], +}) +export class BillingModule {} diff --git a/apps/api/src/billing/billing.service.ts b/apps/api/src/billing/billing.service.ts new file mode 100644 index 0000000..163a3df --- /dev/null +++ b/apps/api/src/billing/billing.service.ts @@ -0,0 +1,482 @@ +import { + BadRequestException, + Injectable, + Logger, + NotFoundException, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { DocumentStatus, PaymentProvider, SubscriptionPlan } from '@prisma/client'; +import Stripe from 'stripe'; +import { createHmac } from 'crypto'; +import { PrismaService } from '../prisma/prisma.service'; +import { Decimal } from '@prisma/client/runtime/library'; +import { computeJobEconomics, decimalToNumber } from '../common/utils/economics.util'; +import { + CreateCheckoutDto, + CreateDocumentLineDto, + CreateInvoiceFromJobDto, + CreateQuoteFromJobDto, +} from './dto/billing.dto'; + +@Injectable() +export class BillingService { + private readonly logger = new Logger(BillingService.name); + private stripe: Stripe | null = null; + + constructor( + private readonly prisma: PrismaService, + private readonly config: ConfigService, + ) { + const secret = this.config.get('STRIPE_SECRET_KEY'); + if (secret) { + this.stripe = new Stripe(secret); + } + } + + listQuotes(organizationId: string) { + return this.prisma.quote.findMany({ + where: { organizationId }, + orderBy: { createdAt: 'desc' }, + include: { + job: { select: { id: true, title: true } }, + lines: true, + }, + }); + } + + async getQuote(organizationId: string, id: string) { + const quote = await this.prisma.quote.findFirst({ + where: { id, organizationId }, + include: { job: { select: { id: true, title: true } }, lines: true }, + }); + if (!quote) throw new NotFoundException('Quote not found'); + return quote; + } + + listInvoices(organizationId: string) { + return this.prisma.invoice.findMany({ + where: { organizationId }, + orderBy: { createdAt: 'desc' }, + include: { + job: { select: { id: true, title: true } }, + lines: true, + }, + }); + } + + async getInvoice(organizationId: string, id: string) { + const invoice = await this.prisma.invoice.findFirst({ + where: { id, organizationId }, + include: { job: { select: { id: true, title: true } }, lines: true }, + }); + if (!invoice) throw new NotFoundException('Invoice not found'); + return invoice; + } + + getSubscription(organizationId: string) { + return this.prisma.subscription.findFirst({ + where: { organizationId }, + orderBy: { createdAt: 'desc' }, + }); + } + + async createQuoteFromJob(organizationId: string, dto: CreateQuoteFromJobDto) { + const job = await this.getJobWithEconomics(organizationId, dto.jobId); + const number = await this.nextDocumentNumber(organizationId, 'Q'); + const lines = this.jobItemsToLines(job.items); + + return this.prisma.$transaction(async (tx) => { + const quote = await tx.quote.create({ + data: { + organizationId, + jobId: dto.jobId, + number, + status: DocumentStatus.DRAFT, + totalAmount: job.economics.revenue, + validUntil: dto.validUntil ? new Date(dto.validUntil) : undefined, + }, + }); + + if (lines.length > 0) { + await tx.quoteLine.createMany({ + data: lines.map((line) => ({ + organizationId, + quoteId: quote.id, + ...line, + })), + }); + } + + return tx.quote.findUnique({ + where: { id: quote.id }, + include: { job: { select: { id: true, title: true } }, lines: true }, + }); + }); + } + + async createInvoiceFromJob(organizationId: string, dto: CreateInvoiceFromJobDto) { + const job = await this.getJobWithEconomics(organizationId, dto.jobId); + const number = await this.nextDocumentNumber(organizationId, 'INV'); + const lines = this.jobItemsToLines(job.items); + + return this.prisma.$transaction(async (tx) => { + const invoice = await tx.invoice.create({ + data: { + organizationId, + jobId: dto.jobId, + number, + status: DocumentStatus.DRAFT, + totalAmount: job.economics.revenue, + issuedAt: new Date(), + dueAt: dto.dueAt ? new Date(dto.dueAt) : undefined, + }, + }); + + if (lines.length > 0) { + await tx.invoiceLine.createMany({ + data: lines.map((line) => ({ + organizationId, + invoiceId: invoice.id, + ...line, + })), + }); + } + + return tx.invoice.findUnique({ + where: { id: invoice.id }, + include: { job: { select: { id: true, title: true } }, lines: true }, + }); + }); + } + + async addQuoteLine(organizationId: string, quoteId: string, dto: CreateDocumentLineDto) { + await this.ensureQuote(organizationId, quoteId); + const line = await this.prisma.quoteLine.create({ + data: { + organizationId, + quoteId, + description: dto.description, + quantity: dto.quantity, + unitPrice: dto.unitPrice, + }, + }); + await this.recalculateQuoteTotal(organizationId, quoteId); + return line; + } + + async addInvoiceLine(organizationId: string, invoiceId: string, dto: CreateDocumentLineDto) { + await this.ensureInvoice(organizationId, invoiceId); + const line = await this.prisma.invoiceLine.create({ + data: { + organizationId, + invoiceId, + description: dto.description, + quantity: dto.quantity, + unitPrice: dto.unitPrice, + }, + }); + await this.recalculateInvoiceTotal(organizationId, invoiceId); + return line; + } + + async createCheckoutSession(organizationId: string, dto: CreateCheckoutDto) { + const provider = dto.provider ?? PaymentProvider.STRIPE; + if (provider === PaymentProvider.LEMONSQUEEZY) { + return this.createLemonCheckout(organizationId, dto.plan); + } + return this.createStripeCheckout(organizationId, dto.plan); + } + + private async createStripeCheckout(organizationId: string, plan: SubscriptionPlan) { + if (!this.stripe) { + throw new ServiceUnavailableException( + 'Stripe is not configured. Set STRIPE_SECRET_KEY and price IDs.', + ); + } + + const priceId = this.stripePriceForPlan(plan); + if (!priceId) { + throw new BadRequestException(`No Stripe price configured for plan ${plan}`); + } + + const org = await this.prisma.organization.findUnique({ where: { id: organizationId } }); + if (!org) throw new NotFoundException('Organization not found'); + + const subscription = await this.getSubscription(organizationId); + let customerId = subscription?.stripeCustomerId; + + if (!customerId) { + const customer = await this.stripe.customers.create({ + name: org.name, + metadata: { organizationId }, + }); + customerId = customer.id; + if (subscription) { + await this.prisma.subscription.update({ + where: { id: subscription.id }, + data: { stripeCustomerId: customerId, paymentProvider: PaymentProvider.STRIPE }, + }); + } + } + + const session = await this.stripe.checkout.sessions.create({ + mode: 'subscription', + customer: customerId, + line_items: [{ price: priceId, quantity: 1 }], + success_url: this.config.get('STRIPE_SUCCESS_URL', 'http://localhost:3000/settings?billing=success'), + cancel_url: this.config.get('STRIPE_CANCEL_URL', 'http://localhost:3000/settings?billing=cancel'), + metadata: { organizationId, plan }, + }); + + return { url: session.url, sessionId: session.id, provider: PaymentProvider.STRIPE }; + } + + async createLemonCheckout(organizationId: string, plan: SubscriptionPlan) { + const apiKey = this.config.get('LEMONSQUEEZY_API_KEY'); + const storeId = this.config.get('LEMONSQUEEZY_STORE_ID'); + const variantId = this.lemonVariantForPlan(plan); + + if (!apiKey || !storeId || !variantId) { + throw new ServiceUnavailableException( + 'Lemon Squeezy not configured. Set LEMONSQUEEZY_API_KEY, STORE_ID and variant IDs.', + ); + } + + const response = await fetch('https://api.lemonsqueezy.com/v1/checkouts', { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + Accept: 'application/vnd.api+json', + 'Content-Type': 'application/vnd.api+json', + }, + body: JSON.stringify({ + data: { + type: 'checkouts', + attributes: { + checkout_data: { + custom: { organizationId, plan }, + }, + }, + relationships: { + store: { data: { type: 'stores', id: storeId } }, + variant: { data: { type: 'variants', id: variantId } }, + }, + }, + }), + }); + + if (!response.ok) { + const err = await response.text(); + this.logger.error(`Lemon Squeezy checkout failed: ${err}`); + throw new BadRequestException('Failed to create Lemon Squeezy checkout'); + } + + const json = (await response.json()) as { + data: { attributes: { url: string } }; + }; + + await this.prisma.subscription.updateMany({ + where: { organizationId }, + data: { paymentProvider: PaymentProvider.LEMONSQUEEZY }, + }); + + return { url: json.data.attributes.url, provider: PaymentProvider.LEMONSQUEEZY }; + } + + async handleStripeWebhook(rawBody: Buffer, signature: string | undefined) { + if (!this.stripe) { + throw new ServiceUnavailableException('Stripe not configured'); + } + + const webhookSecret = this.config.get('STRIPE_WEBHOOK_SECRET'); + if (!webhookSecret) { + throw new ServiceUnavailableException('STRIPE_WEBHOOK_SECRET not configured'); + } + + if (!signature) { + throw new BadRequestException('Missing stripe-signature header'); + } + + const event = this.stripe.webhooks.constructEvent(rawBody, signature, webhookSecret); + + switch (event.type) { + case 'checkout.session.completed': { + const session = event.data.object as Stripe.Checkout.Session; + const organizationId = session.metadata?.organizationId; + const plan = session.metadata?.plan as SubscriptionPlan | undefined; + if (organizationId && plan) { + await this.activateSubscription(organizationId, plan, { + paymentProvider: PaymentProvider.STRIPE, + stripeCustomerId: session.customer as string, + stripeSubscriptionId: session.subscription as string, + }); + } + break; + } + case 'customer.subscription.deleted': { + const sub = event.data.object as Stripe.Subscription; + await this.prisma.subscription.updateMany({ + where: { stripeSubscriptionId: sub.id }, + data: { status: 'cancelled', plan: SubscriptionPlan.FREE }, + }); + break; + } + default: + this.logger.log(`Unhandled Stripe event: ${event.type}`); + } + + return { received: true }; + } + + async handleLemonWebhook(rawBody: Buffer, signature: string | undefined) { + const secret = this.config.get('LEMONSQUEEZY_WEBHOOK_SECRET'); + if (!secret) { + throw new ServiceUnavailableException('LEMONSQUEEZY_WEBHOOK_SECRET not configured'); + } + + if (!signature || !this.verifyLemonSignature(rawBody, signature, secret)) { + throw new BadRequestException('Invalid Lemon Squeezy webhook signature'); + } + + const payload = JSON.parse(rawBody.toString('utf8')) as { + meta?: { event_name?: string; custom_data?: { organizationId?: string; plan?: SubscriptionPlan } }; + data?: { attributes?: { customer_id?: number; subscription_id?: number } }; + }; + + const eventName = payload.meta?.event_name; + const organizationId = payload.meta?.custom_data?.organizationId; + const plan = payload.meta?.custom_data?.plan; + + if (eventName === 'subscription_created' && organizationId && plan) { + await this.activateSubscription(organizationId, plan, { + paymentProvider: PaymentProvider.LEMONSQUEEZY, + lemonSqueezyCustomerId: String(payload.data?.attributes?.customer_id ?? ''), + lemonSqueezySubscriptionId: String(payload.data?.attributes?.subscription_id ?? ''), + }); + } + + if (eventName === 'subscription_cancelled' && organizationId) { + await this.prisma.subscription.updateMany({ + where: { organizationId }, + data: { status: 'cancelled', plan: SubscriptionPlan.FREE }, + }); + } + + return { received: true }; + } + + private verifyLemonSignature(rawBody: Buffer, signature: string, secret: string): boolean { + const digest = createHmac('sha256', secret).update(rawBody).digest('hex'); + return digest === signature; + } + + private async activateSubscription( + organizationId: string, + plan: SubscriptionPlan, + data: { + paymentProvider: PaymentProvider; + stripeCustomerId?: string; + stripeSubscriptionId?: string; + lemonSqueezyCustomerId?: string; + lemonSqueezySubscriptionId?: string; + }, + ) { + await this.prisma.organization.update({ + where: { id: organizationId }, + data: { plan }, + }); + await this.prisma.subscription.updateMany({ + where: { organizationId }, + data: { + plan, + status: 'active', + paymentProvider: data.paymentProvider, + stripeCustomerId: data.stripeCustomerId, + stripeSubscriptionId: data.stripeSubscriptionId, + lemonSqueezyCustomerId: data.lemonSqueezyCustomerId, + lemonSqueezySubscriptionId: data.lemonSqueezySubscriptionId, + }, + }); + } + + private stripePriceForPlan(plan: SubscriptionPlan): string | undefined { + const map: Record = { + PRO: this.config.get('STRIPE_PRICE_PRO'), + BUSINESS: this.config.get('STRIPE_PRICE_BUSINESS'), + }; + return map[plan]; + } + + private lemonVariantForPlan(plan: SubscriptionPlan): string | undefined { + const map: Record = { + PRO: this.config.get('LEMONSQUEEZY_VARIANT_PRO'), + BUSINESS: this.config.get('LEMONSQUEEZY_VARIANT_BUSINESS'), + }; + return map[plan]; + } + + private jobItemsToLines( + items: Array<{ description: string; quantity: Decimal | number; unitPrice: Decimal | number }>, + ) { + return items.map((item) => ({ + description: item.description, + quantity: decimalToNumber(item.quantity), + unitPrice: decimalToNumber(item.unitPrice), + })); + } + + private async recalculateQuoteTotal(organizationId: string, quoteId: string) { + const lines = await this.prisma.quoteLine.findMany({ where: { quoteId, organizationId } }); + const total = lines.reduce( + (sum, l) => sum + decimalToNumber(l.quantity) * decimalToNumber(l.unitPrice), + 0, + ); + await this.prisma.quote.update({ where: { id: quoteId }, data: { totalAmount: total } }); + } + + private async recalculateInvoiceTotal(organizationId: string, invoiceId: string) { + const lines = await this.prisma.invoiceLine.findMany({ where: { invoiceId, organizationId } }); + const total = lines.reduce( + (sum, l) => sum + decimalToNumber(l.quantity) * decimalToNumber(l.unitPrice), + 0, + ); + await this.prisma.invoice.update({ where: { id: invoiceId }, data: { totalAmount: total } }); + } + + private async ensureQuote(organizationId: string, quoteId: string) { + const quote = await this.prisma.quote.findFirst({ where: { id: quoteId, organizationId } }); + if (!quote) throw new NotFoundException('Quote not found'); + return quote; + } + + private async ensureInvoice(organizationId: string, invoiceId: string) { + const invoice = await this.prisma.invoice.findFirst({ where: { id: invoiceId, organizationId } }); + if (!invoice) throw new NotFoundException('Invoice not found'); + return invoice; + } + + private async nextDocumentNumber(organizationId: string, prefix: string): Promise { + const count = + prefix === 'Q' + ? await this.prisma.quote.count({ where: { organizationId } }) + : await this.prisma.invoice.count({ where: { organizationId } }); + return `${prefix}-${new Date().getFullYear()}-${String(count + 1).padStart(4, '0')}`; + } + + private async getJobWithEconomics(organizationId: string, jobId: string) { + const job = await this.prisma.job.findFirst({ + where: { id: jobId, organizationId }, + include: { items: true, activities: true, materialUsages: true }, + }); + if (!job) throw new NotFoundException('Job not found'); + + const economics = computeJobEconomics({ + items: job.items, + activities: job.activities, + materialUsages: job.materialUsages, + }); + + return { ...job, economics }; + } +} diff --git a/apps/api/src/billing/dto/billing.dto.ts b/apps/api/src/billing/dto/billing.dto.ts new file mode 100644 index 0000000..d5d20b9 --- /dev/null +++ b/apps/api/src/billing/dto/billing.dto.ts @@ -0,0 +1,27 @@ +import { IsEnum, IsNumber, IsOptional, IsString, MinLength } from 'class-validator'; +import { PaymentProvider, SubscriptionPlan } from '@prisma/client'; + +export class CreateQuoteFromJobDto { + @IsString() @MinLength(1) jobId!: string; + @IsOptional() @IsString() validUntil?: string; +} + +export class CreateInvoiceFromJobDto { + @IsString() @MinLength(1) jobId!: string; + @IsOptional() @IsString() dueAt?: string; +} + +export class CreateCheckoutDto { + @IsEnum(SubscriptionPlan) + plan!: SubscriptionPlan; + + @IsOptional() + @IsEnum(PaymentProvider) + provider?: PaymentProvider; +} + +export class CreateDocumentLineDto { + @IsString() @MinLength(1) description!: string; + @IsNumber() quantity!: number; + @IsNumber() unitPrice!: number; +} diff --git a/apps/api/src/common/decorators/auth.decorator.ts b/apps/api/src/common/decorators/auth.decorator.ts new file mode 100644 index 0000000..2ab60b4 --- /dev/null +++ b/apps/api/src/common/decorators/auth.decorator.ts @@ -0,0 +1,18 @@ +import { createParamDecorator, ExecutionContext, SetMetadata } from '@nestjs/common'; + +export const IS_PUBLIC_KEY = 'isPublic'; +export const Public = () => SetMetadata(IS_PUBLIC_KEY, true); + +export interface AuthUserPayload { + userId: string; + email: string; + organizationId: string; + role: string; +} + +export const CurrentUser = createParamDecorator( + (_data: unknown, ctx: ExecutionContext): AuthUserPayload => { + const request = ctx.switchToHttp().getRequest<{ user: AuthUserPayload }>(); + return request.user; + }, +); diff --git a/apps/api/src/common/filters/global-exception.filter.ts b/apps/api/src/common/filters/global-exception.filter.ts new file mode 100644 index 0000000..a65e930 --- /dev/null +++ b/apps/api/src/common/filters/global-exception.filter.ts @@ -0,0 +1,47 @@ +import { + ExceptionFilter, + Catch, + ArgumentsHost, + HttpException, + HttpStatus, + Logger, +} from '@nestjs/common'; +import { Request, Response } from 'express'; + +@Catch() +export class GlobalExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(GlobalExceptionFilter.name); + + catch(exception: unknown, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + + let status = HttpStatus.INTERNAL_SERVER_ERROR; + let message = 'Internal server error'; + let details: unknown = undefined; + + if (exception instanceof HttpException) { + status = exception.getStatus(); + const res = exception.getResponse(); + if (typeof res === 'string') { + message = res; + } else if (typeof res === 'object' && res !== null) { + const obj = res as Record; + message = (obj.message as string) ?? message; + details = obj; + } + } else if (exception instanceof Error) { + message = exception.message; + this.logger.error(exception.message, exception.stack); + } + + response.status(status).json({ + statusCode: status, + message, + details, + path: request.url, + timestamp: new Date().toISOString(), + }); + } +} diff --git a/apps/api/src/common/utils/economics.util.spec.ts b/apps/api/src/common/utils/economics.util.spec.ts new file mode 100644 index 0000000..e893ace --- /dev/null +++ b/apps/api/src/common/utils/economics.util.spec.ts @@ -0,0 +1,27 @@ +import { computeJobEconomics } from './economics.util'; + +describe('computeJobEconomics', () => { + it('calculates revenue, costs and margin', () => { + const result = computeJobEconomics({ + items: [{ quantity: 2, unitPrice: 100 }], + activities: [{ hours: 3, hourlyCost: 25 }], + materialUsages: [{ quantity: 4, unitCost: 10 }], + }); + + expect(result.revenue).toBe(200); + expect(result.laborCost).toBe(75); + expect(result.materialCost).toBe(40); + expect(result.margin).toBe(85); + expect(result.marginPercent).toBe(42.5); + }); + + it('handles zero revenue', () => { + const result = computeJobEconomics({ + items: [], + activities: [{ hours: 1, hourlyCost: 20 }], + materialUsages: [], + }); + expect(result.revenue).toBe(0); + expect(result.marginPercent).toBe(0); + }); +}); diff --git a/apps/api/src/common/utils/economics.util.ts b/apps/api/src/common/utils/economics.util.ts new file mode 100644 index 0000000..349af43 --- /dev/null +++ b/apps/api/src/common/utils/economics.util.ts @@ -0,0 +1,48 @@ +import { Decimal } from '@prisma/client/runtime/library'; + +export function decimalToNumber(value: Decimal | number | null | undefined): number { + if (value === null || value === undefined) return 0; + if (typeof value === 'number') return value; + return Number(value.toString()); +} + +export function slugify(input: string): string { + return input + .toLowerCase() + .trim() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 48); +} + +export interface JobEconomics { + revenue: number; + laborCost: number; + materialCost: number; + margin: number; + marginPercent: number; +} + +export function computeJobEconomics(params: { + items: Array<{ quantity: Decimal | number; unitPrice: Decimal | number }>; + activities: Array<{ hours: Decimal | number; hourlyCost: Decimal | number }>; + materialUsages: Array<{ quantity: Decimal | number; unitCost: Decimal | number }>; +}): JobEconomics { + const revenue = params.items.reduce( + (sum, item) => sum + decimalToNumber(item.quantity) * decimalToNumber(item.unitPrice), + 0, + ); + const laborCost = params.activities.reduce( + (sum, a) => sum + decimalToNumber(a.hours) * decimalToNumber(a.hourlyCost), + 0, + ); + const materialCost = params.materialUsages.reduce( + (sum, m) => sum + decimalToNumber(m.quantity) * decimalToNumber(m.unitCost), + 0, + ); + const totalCost = laborCost + materialCost; + const margin = revenue - totalCost; + const marginPercent = revenue > 0 ? (margin / revenue) * 100 : 0; + + return { revenue, laborCost, materialCost, margin, marginPercent }; +} diff --git a/apps/api/src/crm/crm.controller.ts b/apps/api/src/crm/crm.controller.ts new file mode 100644 index 0000000..b2d4bf3 --- /dev/null +++ b/apps/api/src/crm/crm.controller.ts @@ -0,0 +1,80 @@ +import { Controller, Get, Post, Patch, Delete, Body, Param, Query } from '@nestjs/common'; +import { CrmService } from './crm.service'; +import { CreateCustomerDto, CreateSiteDto, CreateContactDto, UpdateContactDto } from './dto/crm.dto'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('crm') +export class CrmController { + constructor(private readonly crmService: CrmService) {} + + @Get('customers') + listCustomers(@CurrentUser() user: AuthUserPayload) { + return this.crmService.listCustomers(user.organizationId); + } + + @Get('customers/:id') + getCustomer(@CurrentUser() user: AuthUserPayload, @Param('id') id: string) { + return this.crmService.getCustomer(user.organizationId, id); + } + + @Post('customers') + createCustomer(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateCustomerDto) { + return this.crmService.createCustomer(user.organizationId, dto); + } + + @Patch('customers/:id') + updateCustomer( + @CurrentUser() user: AuthUserPayload, + @Param('id') id: string, + @Body() dto: Partial, + ) { + return this.crmService.updateCustomer(user.organizationId, id, dto); + } + + @Get('sites') + listSites(@CurrentUser() user: AuthUserPayload, @Query('customerId') customerId?: string) { + return this.crmService.listSites(user.organizationId, customerId); + } + + @Post('customers/:customerId/sites') + createSite( + @CurrentUser() user: AuthUserPayload, + @Param('customerId') customerId: string, + @Body() dto: CreateSiteDto, + ) { + return this.crmService.createSite(user.organizationId, customerId, dto); + } + + @Get('customers/:customerId/contacts') + listContacts(@CurrentUser() user: AuthUserPayload, @Param('customerId') customerId: string) { + return this.crmService.listContacts(user.organizationId, customerId); + } + + @Post('customers/:customerId/contacts') + createContact( + @CurrentUser() user: AuthUserPayload, + @Param('customerId') customerId: string, + @Body() dto: CreateContactDto, + ) { + return this.crmService.createContact(user.organizationId, customerId, dto); + } + + @Patch('customers/:customerId/contacts/:contactId') + updateContact( + @CurrentUser() user: AuthUserPayload, + @Param('customerId') customerId: string, + @Param('contactId') contactId: string, + @Body() dto: UpdateContactDto, + ) { + return this.crmService.updateContact(user.organizationId, customerId, contactId, dto); + } + + @Delete('customers/:customerId/contacts/:contactId') + deleteContact( + @CurrentUser() user: AuthUserPayload, + @Param('customerId') customerId: string, + @Param('contactId') contactId: string, + ) { + return this.crmService.deleteContact(user.organizationId, customerId, contactId); + } +} diff --git a/apps/api/src/crm/crm.module.ts b/apps/api/src/crm/crm.module.ts new file mode 100644 index 0000000..60dbeed --- /dev/null +++ b/apps/api/src/crm/crm.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { CrmController } from './crm.controller'; +import { CrmService } from './crm.service'; + +@Module({ + controllers: [CrmController], + providers: [CrmService], + exports: [CrmService], +}) +export class CrmModule {} diff --git a/apps/api/src/crm/crm.service.ts b/apps/api/src/crm/crm.service.ts new file mode 100644 index 0000000..a52d36f --- /dev/null +++ b/apps/api/src/crm/crm.service.ts @@ -0,0 +1,98 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateCustomerDto, CreateSiteDto, CreateContactDto, UpdateContactDto } from './dto/crm.dto'; + +@Injectable() +export class CrmService { + constructor(private readonly prisma: PrismaService) {} + + listCustomers(organizationId: string) { + return this.prisma.customer.findMany({ + where: { organizationId }, + orderBy: { name: 'asc' }, + include: { sites: true, _count: { select: { jobs: true } } }, + }); + } + + async getCustomer(organizationId: string, id: string) { + const customer = await this.prisma.customer.findFirst({ + where: { id, organizationId }, + include: { + contacts: true, + sites: true, + jobs: { orderBy: { createdAt: 'desc' }, take: 20 }, + }, + }); + if (!customer) throw new NotFoundException('Customer not found'); + return customer; + } + + createCustomer(organizationId: string, dto: CreateCustomerDto) { + return this.prisma.customer.create({ + data: { ...dto, organizationId }, + }); + } + + async updateCustomer(organizationId: string, id: string, dto: Partial) { + await this.ensureCustomer(organizationId, id); + return this.prisma.customer.update({ where: { id }, data: dto }); + } + + async createSite(organizationId: string, customerId: string, dto: CreateSiteDto) { + await this.ensureCustomer(organizationId, customerId); + return this.prisma.site.create({ + data: { ...dto, organizationId, customerId }, + }); + } + + listSites(organizationId: string, customerId?: string) { + return this.prisma.site.findMany({ + where: { organizationId, ...(customerId ? { customerId } : {}) }, + include: { customer: { select: { id: true, name: true } } }, + orderBy: { name: 'asc' }, + }); + } + + listContacts(organizationId: string, customerId: string) { + return this.prisma.contact.findMany({ + where: { organizationId, customerId }, + orderBy: { name: 'asc' }, + }); + } + + async createContact(organizationId: string, customerId: string, dto: CreateContactDto) { + await this.ensureCustomer(organizationId, customerId); + return this.prisma.contact.create({ + data: { ...dto, organizationId, customerId }, + }); + } + + async updateContact( + organizationId: string, + customerId: string, + contactId: string, + dto: UpdateContactDto, + ) { + await this.ensureContact(organizationId, customerId, contactId); + return this.prisma.contact.update({ where: { id: contactId }, data: dto }); + } + + async deleteContact(organizationId: string, customerId: string, contactId: string) { + await this.ensureContact(organizationId, customerId, contactId); + return this.prisma.contact.delete({ where: { id: contactId } }); + } + + private async ensureContact(organizationId: string, customerId: string, contactId: string) { + const contact = await this.prisma.contact.findFirst({ + where: { id: contactId, organizationId, customerId }, + }); + if (!contact) throw new NotFoundException('Contact not found'); + return contact; + } + + private async ensureCustomer(organizationId: string, id: string) { + const customer = await this.prisma.customer.findFirst({ where: { id, organizationId } }); + if (!customer) throw new NotFoundException('Customer not found'); + return customer; + } +} diff --git a/apps/api/src/crm/dto/crm.dto.ts b/apps/api/src/crm/dto/crm.dto.ts new file mode 100644 index 0000000..c38c5d0 --- /dev/null +++ b/apps/api/src/crm/dto/crm.dto.ts @@ -0,0 +1,41 @@ +import { IsEmail, IsOptional, IsString, MinLength } from 'class-validator'; + +export class CreateCustomerDto { + @IsString() + @MinLength(1) + name!: string; + + @IsOptional() @IsString() taxId?: string; + @IsOptional() @IsEmail() email?: string; + @IsOptional() @IsString() phone?: string; + @IsOptional() @IsString() address?: string; + @IsOptional() @IsString() city?: string; + @IsOptional() @IsString() postalCode?: string; + @IsOptional() @IsString() country?: string; + @IsOptional() @IsString() notes?: string; +} + +export class CreateSiteDto { + @IsString() + @MinLength(1) + name!: string; + + @IsOptional() @IsString() address?: string; + @IsOptional() @IsString() city?: string; + @IsOptional() @IsString() postalCode?: string; + @IsOptional() @IsString() notes?: string; +} + +export class CreateContactDto { + @IsString() @MinLength(1) name!: string; + @IsOptional() @IsEmail() email?: string; + @IsOptional() @IsString() phone?: string; + @IsOptional() @IsString() role?: string; +} + +export class UpdateContactDto { + @IsOptional() @IsString() @MinLength(1) name?: string; + @IsOptional() @IsEmail() email?: string; + @IsOptional() @IsString() phone?: string; + @IsOptional() @IsString() role?: string; +} diff --git a/apps/api/src/inventory/dto/inventory.dto.ts b/apps/api/src/inventory/dto/inventory.dto.ts new file mode 100644 index 0000000..205b82a --- /dev/null +++ b/apps/api/src/inventory/dto/inventory.dto.ts @@ -0,0 +1,19 @@ +import { IsEnum, IsNumber, IsOptional, IsString, MinLength } from 'class-validator'; +import { InventoryMovementType } from '@prisma/client'; + +export class CreateMaterialDto { + @IsString() @MinLength(1) name!: string; + @IsOptional() @IsString() code?: string; + @IsOptional() @IsString() unit?: string; + @IsOptional() @IsNumber() minStock?: number; + @IsOptional() @IsNumber() averageCost?: number; + @IsOptional() @IsNumber() stockQuantity?: number; +} + +export class CreateInventoryMovementDto { + @IsString() @MinLength(1) materialId!: string; + @IsEnum(InventoryMovementType) type!: InventoryMovementType; + @IsNumber() quantity!: number; + @IsOptional() @IsString() jobId?: string; + @IsOptional() @IsString() notes?: string; +} diff --git a/apps/api/src/inventory/inventory.controller.ts b/apps/api/src/inventory/inventory.controller.ts new file mode 100644 index 0000000..c4f3805 --- /dev/null +++ b/apps/api/src/inventory/inventory.controller.ts @@ -0,0 +1,37 @@ +import { Controller, Get, Post, Body, Query } from '@nestjs/common'; +import { InventoryService } from './inventory.service'; +import { CreateInventoryMovementDto, CreateMaterialDto } from './dto/inventory.dto'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('inventory') +export class InventoryController { + constructor(private readonly inventoryService: InventoryService) {} + + @Get('materials') + listMaterials(@CurrentUser() user: AuthUserPayload) { + return this.inventoryService.listMaterials(user.organizationId); + } + + @Post('materials') + createMaterial(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateMaterialDto) { + return this.inventoryService.createMaterial(user.organizationId, dto); + } + + @Get('movements') + listMovements( + @CurrentUser() user: AuthUserPayload, + @Query('materialId') materialId?: string, + ) { + return this.inventoryService.listMovements(user.organizationId, materialId); + } + + @Post('movements') + createMovement(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateInventoryMovementDto) { + return this.inventoryService.createMovement(user.organizationId, dto); + } + + @Get('materials/low-stock') + listLowStock(@CurrentUser() user: AuthUserPayload) { + return this.inventoryService.listLowStock(user.organizationId); + } +} diff --git a/apps/api/src/inventory/inventory.module.ts b/apps/api/src/inventory/inventory.module.ts new file mode 100644 index 0000000..4795564 --- /dev/null +++ b/apps/api/src/inventory/inventory.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { InventoryController } from './inventory.controller'; +import { InventoryService } from './inventory.service'; + +@Module({ + controllers: [InventoryController], + providers: [InventoryService], +}) +export class InventoryModule {} diff --git a/apps/api/src/inventory/inventory.service.ts b/apps/api/src/inventory/inventory.service.ts new file mode 100644 index 0000000..1d0d0bd --- /dev/null +++ b/apps/api/src/inventory/inventory.service.ts @@ -0,0 +1,76 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateInventoryMovementDto, CreateMaterialDto } from './dto/inventory.dto'; + +@Injectable() +export class InventoryService { + constructor(private readonly prisma: PrismaService) {} + + listMaterials(organizationId: string) { + return this.prisma.material.findMany({ + where: { organizationId }, + orderBy: { name: 'asc' }, + }); + } + + createMaterial(organizationId: string, dto: CreateMaterialDto) { + return this.prisma.material.create({ + data: { + organizationId, + name: dto.name, + code: dto.code, + unit: dto.unit ?? 'pz', + minStock: dto.minStock, + averageCost: dto.averageCost ?? 0, + stockQuantity: dto.stockQuantity ?? 0, + }, + }); + } + + listMovements(organizationId: string, materialId?: string) { + return this.prisma.inventoryMovement.findMany({ + where: { organizationId, ...(materialId ? { materialId } : {}) }, + include: { material: true, job: { select: { id: true, title: true } } }, + orderBy: { date: 'desc' }, + }); + } + + async createMovement(organizationId: string, dto: CreateInventoryMovementDto) { + const material = await this.prisma.material.findFirst({ + where: { id: dto.materialId, organizationId }, + }); + if (!material) throw new NotFoundException('Material not found'); + + const delta = dto.type === 'IN' ? dto.quantity : -dto.quantity; + + return this.prisma.$transaction(async (tx) => { + const movement = await tx.inventoryMovement.create({ + data: { + organizationId, + materialId: dto.materialId, + jobId: dto.jobId, + type: dto.type, + quantity: dto.quantity, + notes: dto.notes, + }, + }); + + await tx.material.update({ + where: { id: dto.materialId }, + data: { stockQuantity: { increment: delta } }, + }); + + return movement; + }); + } + + async listLowStock(organizationId: string) { + const materials = await this.prisma.material.findMany({ + where: { organizationId, minStock: { not: null } }, + orderBy: { name: 'asc' }, + }); + return materials.filter( + (m) => m.minStock && Number(m.stockQuantity) < Number(m.minStock), + ); + } +} diff --git a/apps/api/src/jobs/dto/jobs.dto.ts b/apps/api/src/jobs/dto/jobs.dto.ts new file mode 100644 index 0000000..18e8edc --- /dev/null +++ b/apps/api/src/jobs/dto/jobs.dto.ts @@ -0,0 +1,42 @@ +import { + IsArray, + IsEnum, + IsOptional, + IsString, + MinLength, + IsNumber, + IsDateString, +} from 'class-validator'; +import { JobItemType, JobStatus } from '@prisma/client'; + +export class CreateJobDto { + @IsString() + @MinLength(1) + customerId!: string; + + @IsOptional() @IsString() siteId?: string; + @IsString() @MinLength(1) title!: string; + @IsOptional() @IsString() reference?: string; + @IsOptional() @IsString() description?: string; + @IsOptional() @IsArray() @IsString({ each: true }) tags?: string[]; + @IsOptional() @IsDateString() startDate?: string; + @IsOptional() @IsDateString() dueDate?: string; +} + +export class UpdateJobDto { + @IsOptional() @IsString() title?: string; + @IsOptional() @IsString() reference?: string; + @IsOptional() @IsEnum(JobStatus) status?: JobStatus; + @IsOptional() @IsString() description?: string; + @IsOptional() @IsArray() @IsString({ each: true }) tags?: string[]; + @IsOptional() @IsDateString() startDate?: string; + @IsOptional() @IsDateString() dueDate?: string; + @IsOptional() @IsDateString() completedAt?: string; +} + +export class CreateJobItemDto { + @IsString() @MinLength(1) description!: string; + @IsNumber() quantity!: number; + @IsNumber() unitPrice!: number; + @IsOptional() @IsEnum(JobItemType) type?: JobItemType; +} diff --git a/apps/api/src/jobs/jobs.controller.ts b/apps/api/src/jobs/jobs.controller.ts new file mode 100644 index 0000000..a721633 --- /dev/null +++ b/apps/api/src/jobs/jobs.controller.ts @@ -0,0 +1,47 @@ +import { Controller, Get, Post, Patch, Body, Param, Query } from '@nestjs/common'; +import { JobStatus } from '@prisma/client'; +import { JobsService } from './jobs.service'; +import { CreateJobDto, CreateJobItemDto, UpdateJobDto } from './dto/jobs.dto'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('jobs') +export class JobsController { + constructor(private readonly jobsService: JobsService) {} + + @Get() + list( + @CurrentUser() user: AuthUserPayload, + @Query('status') status?: JobStatus, + @Query('customerId') customerId?: string, + ) { + return this.jobsService.list(user.organizationId, status, customerId); + } + + @Get(':id') + get(@CurrentUser() user: AuthUserPayload, @Param('id') id: string) { + return this.jobsService.getById(user.organizationId, id); + } + + @Post() + create(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateJobDto) { + return this.jobsService.create(user.organizationId, dto); + } + + @Patch(':id') + update( + @CurrentUser() user: AuthUserPayload, + @Param('id') id: string, + @Body() dto: UpdateJobDto, + ) { + return this.jobsService.update(user.organizationId, id, dto); + } + + @Post(':id/items') + addItem( + @CurrentUser() user: AuthUserPayload, + @Param('id') id: string, + @Body() dto: CreateJobItemDto, + ) { + return this.jobsService.addItem(user.organizationId, id, dto); + } +} diff --git a/apps/api/src/jobs/jobs.module.ts b/apps/api/src/jobs/jobs.module.ts new file mode 100644 index 0000000..eb92c91 --- /dev/null +++ b/apps/api/src/jobs/jobs.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { JobsController } from './jobs.controller'; +import { JobsService } from './jobs.service'; + +@Module({ + controllers: [JobsController], + providers: [JobsService], + exports: [JobsService], +}) +export class JobsModule {} diff --git a/apps/api/src/jobs/jobs.service.ts b/apps/api/src/jobs/jobs.service.ts new file mode 100644 index 0000000..e737e10 --- /dev/null +++ b/apps/api/src/jobs/jobs.service.ts @@ -0,0 +1,97 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { JobStatus } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { computeJobEconomics } from '../common/utils/economics.util'; +import { CreateJobDto, CreateJobItemDto, UpdateJobDto } from './dto/jobs.dto'; + +@Injectable() +export class JobsService { + constructor(private readonly prisma: PrismaService) {} + + list(organizationId: string, status?: JobStatus, customerId?: string) { + return this.prisma.job.findMany({ + where: { + organizationId, + ...(status ? { status } : {}), + ...(customerId ? { customerId } : {}), + }, + include: { + customer: { select: { id: true, name: true } }, + site: { select: { id: true, name: true } }, + }, + orderBy: { updatedAt: 'desc' }, + }); + } + + async getById(organizationId: string, id: string) { + const job = await this.prisma.job.findFirst({ + where: { id, organizationId }, + include: { + customer: true, + site: true, + items: true, + activities: { include: { user: { select: { id: true, firstName: true, lastName: true } } } }, + materialUsages: { include: { material: true } }, + }, + }); + if (!job) throw new NotFoundException('Job not found'); + + const economics = computeJobEconomics({ + items: job.items, + activities: job.activities, + materialUsages: job.materialUsages, + }); + + return { ...job, economics }; + } + + create(organizationId: string, dto: CreateJobDto) { + return this.prisma.job.create({ + data: { + organizationId, + customerId: dto.customerId, + siteId: dto.siteId, + title: dto.title, + reference: dto.reference, + description: dto.description, + tags: dto.tags ?? [], + startDate: dto.startDate ? new Date(dto.startDate) : undefined, + dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined, + }, + include: { customer: { select: { id: true, name: true } } }, + }); + } + + async update(organizationId: string, id: string, dto: UpdateJobDto) { + await this.ensureJob(organizationId, id); + return this.prisma.job.update({ + where: { id }, + data: { + ...dto, + startDate: dto.startDate ? new Date(dto.startDate) : undefined, + dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined, + completedAt: dto.completedAt ? new Date(dto.completedAt) : undefined, + }, + }); + } + + async addItem(organizationId: string, jobId: string, dto: CreateJobItemDto) { + await this.ensureJob(organizationId, jobId); + return this.prisma.jobItem.create({ + data: { + organizationId, + jobId, + description: dto.description, + quantity: dto.quantity, + unitPrice: dto.unitPrice, + type: dto.type, + }, + }); + } + + private async ensureJob(organizationId: string, id: string) { + const job = await this.prisma.job.findFirst({ where: { id, organizationId } }); + if (!job) throw new NotFoundException('Job not found'); + return job; + } +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts new file mode 100644 index 0000000..e3e4f1d --- /dev/null +++ b/apps/api/src/main.ts @@ -0,0 +1,32 @@ +import './telemetry'; +import { ValidationPipe } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import { AppModule } from './app.module'; + +async function bootstrap() { + const app = await NestFactory.create(AppModule, { rawBody: true }); + + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + transformOptions: { enableImplicitConversion: true }, + }), + ); + + const config = app.get(ConfigService); + const port = config.get('PORT', 3001); + const corsOrigin = config.get('CORS_ORIGIN', 'http://localhost:3000'); + + app.enableCors({ + origin: corsOrigin.split(',').map((o) => o.trim()), + credentials: true, + }); + + await app.listen(port); + console.log(`ServiceOps API running on http://localhost:${port}`); +} + +bootstrap(); diff --git a/apps/api/src/organizations/dto/organizations.dto.ts b/apps/api/src/organizations/dto/organizations.dto.ts new file mode 100644 index 0000000..3426549 --- /dev/null +++ b/apps/api/src/organizations/dto/organizations.dto.ts @@ -0,0 +1,7 @@ +import { IsString, MinLength } from 'class-validator'; + +export class CreateOrganizationDto { + @IsString() + @MinLength(2) + name!: string; +} diff --git a/apps/api/src/organizations/organizations.controller.ts b/apps/api/src/organizations/organizations.controller.ts new file mode 100644 index 0000000..bb0d8c9 --- /dev/null +++ b/apps/api/src/organizations/organizations.controller.ts @@ -0,0 +1,27 @@ +import { Controller, Get, Patch, Post, Body } from '@nestjs/common'; +import { OrganizationsService } from './organizations.service'; +import { CreateOrganizationDto } from './dto/organizations.dto'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('organizations') +export class OrganizationsController { + constructor(private readonly organizationsService: OrganizationsService) {} + + @Get('current') + getCurrent(@CurrentUser() user: AuthUserPayload) { + return this.organizationsService.getById(user.organizationId); + } + + @Post() + create(@CurrentUser() user: AuthUserPayload, @Body() dto: CreateOrganizationDto) { + return this.organizationsService.createForUser(user.userId, dto); + } + + @Patch('current/settings') + updateSettings( + @CurrentUser() user: AuthUserPayload, + @Body() body: Record, + ) { + return this.organizationsService.updateSettings(user.organizationId, body); + } +} diff --git a/apps/api/src/organizations/organizations.module.ts b/apps/api/src/organizations/organizations.module.ts new file mode 100644 index 0000000..7f4b9f3 --- /dev/null +++ b/apps/api/src/organizations/organizations.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { OrganizationsController } from './organizations.controller'; +import { OrganizationsService } from './organizations.service'; + +@Module({ + controllers: [OrganizationsController], + providers: [OrganizationsService], + exports: [OrganizationsService], +}) +export class OrganizationsModule {} diff --git a/apps/api/src/organizations/organizations.service.ts b/apps/api/src/organizations/organizations.service.ts new file mode 100644 index 0000000..777ebea --- /dev/null +++ b/apps/api/src/organizations/organizations.service.ts @@ -0,0 +1,60 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { MembershipRole, Prisma } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { slugify } from '../common/utils/economics.util'; +import { CreateOrganizationDto } from './dto/organizations.dto'; + +@Injectable() +export class OrganizationsService { + constructor(private readonly prisma: PrismaService) {} + + async getById(organizationId: string) { + const org = await this.prisma.organization.findUnique({ where: { id: organizationId } }); + if (!org) throw new NotFoundException('Organization not found'); + return org; + } + + async updateSettings(organizationId: string, settings: Record) { + const org = await this.prisma.organization.findUnique({ where: { id: organizationId } }); + if (!org) throw new NotFoundException('Organization not found'); + + const merged = { ...(org.settings as Record), ...settings }; + return this.prisma.organization.update({ + where: { id: organizationId }, + data: { settings: merged as Prisma.InputJsonValue }, + }); + } + + async createForUser(userId: string, dto: CreateOrganizationDto) { + const slug = `${slugify(dto.name)}-${Date.now().toString(36)}`; + + return this.prisma.$transaction(async (tx) => { + const organization = await tx.organization.create({ + data: { + name: dto.name, + slug, + settings: { + currency: 'EUR', + timezone: 'Europe/Rome', + dateFormat: 'DD/MM/YYYY', + features: { inventory: true, billing: true }, + }, + }, + }); + + await tx.membership.create({ + data: { + userId, + organizationId: organization.id, + role: MembershipRole.OWNER, + }, + }); + + await tx.subscription.create({ + data: { organizationId: organization.id, plan: 'FREE', status: 'active' }, + }); + + return organization; + }); + } +} diff --git a/apps/api/src/prisma/prisma.module.ts b/apps/api/src/prisma/prisma.module.ts new file mode 100644 index 0000000..7207426 --- /dev/null +++ b/apps/api/src/prisma/prisma.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { PrismaService } from './prisma.service'; + +@Global() +@Module({ + providers: [PrismaService], + exports: [PrismaService], +}) +export class PrismaModule {} diff --git a/apps/api/src/prisma/prisma.service.ts b/apps/api/src/prisma/prisma.service.ts new file mode 100644 index 0000000..bb6565f --- /dev/null +++ b/apps/api/src/prisma/prisma.service.ts @@ -0,0 +1,13 @@ +import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; +import { PrismaClient } from '@prisma/client'; + +@Injectable() +export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { + async onModuleInit() { + await this.$connect(); + } + + async onModuleDestroy() { + await this.$disconnect(); + } +} diff --git a/apps/api/src/reports/reports.controller.ts b/apps/api/src/reports/reports.controller.ts new file mode 100644 index 0000000..90b4023 --- /dev/null +++ b/apps/api/src/reports/reports.controller.ts @@ -0,0 +1,44 @@ +import { Controller, Get, Param, Res, Header } from '@nestjs/common'; +import { Response } from 'express'; +import { ReportsService } from './reports.service'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('reports') +export class ReportsController { + constructor(private readonly reportsService: ReportsService) {} + + @Get('dashboard') + dashboard(@CurrentUser() user: AuthUserPayload) { + return this.reportsService.dashboardKpis(user.organizationId); + } + + @Get('jobs/margins') + jobMargins(@CurrentUser() user: AuthUserPayload) { + return this.reportsService.jobMargins(user.organizationId); + } + + @Get('customers/:customerId') + customerReport(@CurrentUser() user: AuthUserPayload, @Param('customerId') customerId: string) { + return this.reportsService.customerReport(user.organizationId, customerId); + } + + @Get('jobs/export/csv') + @Header('Content-Type', 'text/csv') + async exportCsv(@CurrentUser() user: AuthUserPayload, @Res() res: Response) { + const csv = await this.reportsService.exportJobsCsv(user.organizationId); + res.setHeader('Content-Disposition', 'attachment; filename="jobs-margins.csv"'); + res.send(csv); + } + + @Get('jobs/:jobId/pdf') + async exportPdf( + @CurrentUser() user: AuthUserPayload, + @Param('jobId') jobId: string, + @Res() res: Response, + ) { + const pdf = await this.reportsService.exportJobPdf(user.organizationId, jobId); + res.setHeader('Content-Type', 'application/pdf'); + res.setHeader('Content-Disposition', `attachment; filename="job-${jobId}.pdf"`); + res.send(pdf); + } +} diff --git a/apps/api/src/reports/reports.module.ts b/apps/api/src/reports/reports.module.ts new file mode 100644 index 0000000..73377e6 --- /dev/null +++ b/apps/api/src/reports/reports.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { ReportsController } from './reports.controller'; +import { ReportsService } from './reports.service'; + +@Module({ + controllers: [ReportsController], + providers: [ReportsService], +}) +export class ReportsModule {} diff --git a/apps/api/src/reports/reports.service.ts b/apps/api/src/reports/reports.service.ts new file mode 100644 index 0000000..19c69b8 --- /dev/null +++ b/apps/api/src/reports/reports.service.ts @@ -0,0 +1,166 @@ +import { Injectable } from '@nestjs/common'; +import { JobStatus } from '@prisma/client'; +import PDFDocument from 'pdfkit'; +import { stringify } from 'csv-stringify/sync'; +import { PrismaService } from '../prisma/prisma.service'; +import { computeJobEconomics, decimalToNumber } from '../common/utils/economics.util'; + +@Injectable() +export class ReportsService { + constructor(private readonly prisma: PrismaService) {} + + async dashboardKpis(organizationId: string) { + const jobs = await this.prisma.job.findMany({ + where: { organizationId }, + include: { items: true, activities: true, materialUsages: true }, + }); + + let totalRevenue = 0; + let totalMargin = 0; + const openStatuses: JobStatus[] = ['DRAFT', 'CONFIRMED', 'IN_PROGRESS']; + let openJobs = 0; + let overdueJobs = 0; + const now = new Date(); + + for (const job of jobs) { + const econ = computeJobEconomics({ + items: job.items, + activities: job.activities, + materialUsages: job.materialUsages, + }); + totalRevenue += econ.revenue; + totalMargin += econ.margin; + if (openStatuses.includes(job.status)) openJobs += 1; + if (job.dueDate && job.dueDate < now && openStatuses.includes(job.status)) overdueJobs += 1; + } + + const customerCount = await this.prisma.customer.count({ where: { organizationId } }); + + const lowStockMaterials = await this.prisma.material.findMany({ + where: { organizationId, minStock: { not: null } }, + }); + const lowStockCount = lowStockMaterials.filter( + (m) => m.minStock && decimalToNumber(m.stockQuantity) < decimalToNumber(m.minStock), + ).length; + + return { + totalRevenue, + totalMargin, + averageMarginPercent: totalRevenue > 0 ? (totalMargin / totalRevenue) * 100 : 0, + jobCount: jobs.length, + openJobs, + overdueJobs, + customerCount, + lowStockCount, + }; + } + + async jobMargins(organizationId: string) { + const jobs = await this.prisma.job.findMany({ + where: { organizationId }, + include: { + customer: { select: { id: true, name: true } }, + items: true, + activities: true, + materialUsages: true, + }, + orderBy: { updatedAt: 'desc' }, + }); + + return jobs.map((job) => { + const economics = computeJobEconomics({ + items: job.items, + activities: job.activities, + materialUsages: job.materialUsages, + }); + return { + jobId: job.id, + title: job.title, + status: job.status, + customerName: job.customer.name, + ...economics, + }; + }); + } + + async customerReport(organizationId: string, customerId: string) { + const customer = await this.prisma.customer.findFirst({ + where: { id: customerId, organizationId }, + include: { + jobs: { + include: { items: true, activities: true, materialUsages: true }, + }, + }, + }); + if (!customer) return null; + + const jobs = customer.jobs.map((job) => { + const economics = computeJobEconomics({ + items: job.items, + activities: job.activities, + materialUsages: job.materialUsages, + }); + return { id: job.id, title: job.title, status: job.status, ...economics }; + }); + + const totalRevenue = jobs.reduce((s, j) => s + j.revenue, 0); + const totalMargin = jobs.reduce((s, j) => s + j.margin, 0); + + return { + customer: { id: customer.id, name: customer.name }, + jobs, + totalRevenue, + totalMargin, + }; + } + + async exportJobsCsv(organizationId: string): Promise { + const margins = await this.jobMargins(organizationId); + return stringify(margins, { header: true }); + } + + async exportJobPdf(organizationId: string, jobId: string): Promise { + const job = await this.prisma.job.findFirst({ + where: { id: jobId, organizationId }, + include: { + customer: true, + items: true, + activities: true, + materialUsages: { include: { material: true } }, + }, + }); + if (!job) throw new Error('Job not found'); + + const economics = computeJobEconomics({ + items: job.items, + activities: job.activities, + materialUsages: job.materialUsages, + }); + + const doc = new PDFDocument({ margin: 50 }); + const chunks: Buffer[] = []; + doc.on('data', (chunk: Buffer) => chunks.push(chunk)); + + doc.fontSize(18).text('ServiceOps — Report Commessa', { underline: true }); + doc.moveDown(); + doc.fontSize(12).text(`Commessa: ${job.title}`); + doc.text(`Cliente: ${job.customer.name}`); + doc.text(`Stato: ${job.status}`); + doc.moveDown(); + doc.text(`Ricavi: €${economics.revenue.toFixed(2)}`); + doc.text(`Costo ore: €${economics.laborCost.toFixed(2)}`); + doc.text(`Costo materiali: €${economics.materialCost.toFixed(2)}`); + doc.text(`Margine: €${economics.margin.toFixed(2)} (${economics.marginPercent.toFixed(1)}%)`); + doc.moveDown(); + doc.text('Voci:'); + for (const item of job.items) { + doc.text( + `- ${item.description}: ${decimalToNumber(item.quantity)} x €${decimalToNumber(item.unitPrice)}`, + ); + } + doc.end(); + + await new Promise((resolve) => doc.on('end', resolve)); + return Buffer.concat(chunks); + } +} diff --git a/apps/api/src/telemetry.ts b/apps/api/src/telemetry.ts new file mode 100644 index 0000000..c824aa6 --- /dev/null +++ b/apps/api/src/telemetry.ts @@ -0,0 +1,25 @@ +/** + * OpenTelemetry bootstrap — import before NestFactory in main.ts. + * Enable with OTEL_ENABLED=1 and optional OTEL_EXPORTER_OTLP_ENDPOINT. + */ +import { NodeSDK } from '@opentelemetry/sdk-node'; +import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; +import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; + +if (process.env.OTEL_ENABLED === '1') { + const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + const sdk = new NodeSDK({ + serviceName: process.env.OTEL_SERVICE_NAME ?? 'serviceops-api', + traceExporter: endpoint ? new OTLPTraceExporter({ url: endpoint }) : undefined, + instrumentations: [ + getNodeAutoInstrumentations({ + '@opentelemetry/instrumentation-fs': { enabled: false }, + }), + ], + }); + + sdk.start(); + console.log( + `[otel] tracing enabled${endpoint ? ` → ${endpoint}` : ' (default exporter)'}`, + ); +} diff --git a/apps/api/src/users/users.controller.ts b/apps/api/src/users/users.controller.ts new file mode 100644 index 0000000..02ace1c --- /dev/null +++ b/apps/api/src/users/users.controller.ts @@ -0,0 +1,13 @@ +import { Controller, Get } from '@nestjs/common'; +import { UsersService } from './users.service'; +import { CurrentUser, AuthUserPayload } from '../common/decorators/auth.decorator'; + +@Controller('users') +export class UsersController { + constructor(private readonly usersService: UsersService) {} + + @Get() + list(@CurrentUser() user: AuthUserPayload) { + return this.usersService.listForOrganization(user.organizationId); + } +} diff --git a/apps/api/src/users/users.module.ts b/apps/api/src/users/users.module.ts new file mode 100644 index 0000000..440ef36 --- /dev/null +++ b/apps/api/src/users/users.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { UsersController } from './users.controller'; +import { UsersService } from './users.service'; + +@Module({ + controllers: [UsersController], + providers: [UsersService], +}) +export class UsersModule {} diff --git a/apps/api/src/users/users.service.ts b/apps/api/src/users/users.service.ts new file mode 100644 index 0000000..e9f4e91 --- /dev/null +++ b/apps/api/src/users/users.service.ts @@ -0,0 +1,16 @@ +import { Injectable } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; + +@Injectable() +export class UsersService { + constructor(private readonly prisma: PrismaService) {} + + listForOrganization(organizationId: string) { + return this.prisma.membership.findMany({ + where: { organizationId }, + include: { + user: { select: { id: true, email: true, firstName: true, lastName: true } }, + }, + }); + } +} diff --git a/apps/api/test/app.e2e-spec.ts b/apps/api/test/app.e2e-spec.ts new file mode 100644 index 0000000..996e4ec --- /dev/null +++ b/apps/api/test/app.e2e-spec.ts @@ -0,0 +1,90 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { INestApplication, ValidationPipe } from '@nestjs/common'; +import request from 'supertest'; +import { AppModule } from '../src/app.module'; +import { PrismaService } from '../src/prisma/prisma.service'; + +describe('ServiceOps E2E', () => { + let app: INestApplication; + let prisma: PrismaService; + let token: string; + + beforeAll(async () => { + const moduleFixture: TestingModule = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + + app = moduleFixture.createNestApplication(); + app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true })); + await app.init(); + + prisma = app.get(PrismaService); + }); + + afterAll(async () => { + await app.close(); + }); + + it('registers organization and user', async () => { + const res = await request(app.getHttpServer()) + .post('/auth/register') + .send({ + email: `test-${Date.now()}@example.com`, + password: 'password123', + firstName: 'Mario', + lastName: 'Rossi', + organizationName: 'Officina Test', + }) + .expect(201); + + token = res.body.accessToken; + expect(token).toBeDefined(); + }); + + it('creates customer, job, activity and reads margins', async () => { + const customerRes = await request(app.getHttpServer()) + .post('/crm/customers') + .set('Authorization', `Bearer ${token}`) + .send({ name: 'Cliente Demo' }) + .expect(201); + + const jobRes = await request(app.getHttpServer()) + .post('/jobs') + .set('Authorization', `Bearer ${token}`) + .send({ title: 'Riparazione impianto', customerId: customerRes.body.id }) + .expect(201); + + await request(app.getHttpServer()) + .post(`/jobs/${jobRes.body.id}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ description: 'Intervento', quantity: 1, unitPrice: 500 }) + .expect(201); + + await request(app.getHttpServer()) + .post('/activities') + .set('Authorization', `Bearer ${token}`) + .send({ + jobId: jobRes.body.id, + date: new Date().toISOString(), + hours: 2, + hourlyCost: 30, + }) + .expect(201); + + const jobDetail = await request(app.getHttpServer()) + .get(`/jobs/${jobRes.body.id}`) + .set('Authorization', `Bearer ${token}`) + .expect(200); + + expect(jobDetail.body.economics.revenue).toBe(500); + expect(jobDetail.body.economics.laborCost).toBe(60); + expect(jobDetail.body.economics.margin).toBe(440); + + const dashboard = await request(app.getHttpServer()) + .get('/reports/dashboard') + .set('Authorization', `Bearer ${token}`) + .expect(200); + + expect(dashboard.body.totalRevenue).toBeGreaterThan(0); + }); +}); diff --git a/apps/api/test/jest-e2e.json b/apps/api/test/jest-e2e.json new file mode 100644 index 0000000..e9d912f --- /dev/null +++ b/apps/api/test/jest-e2e.json @@ -0,0 +1,9 @@ +{ + "moduleFileExtensions": ["js", "json", "ts"], + "rootDir": ".", + "testEnvironment": "node", + "testRegex": ".e2e-spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + } +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..26b3a7c --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "target": "ES2022", + "sourceMap": true, + "outDir": "./dist", + "baseUrl": "./", + "incremental": true, + "skipLibCheck": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noUncheckedIndexedAccess": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "test"] +} diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..d658484 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1 @@ +NEXT_PUBLIC_API_URL=http://localhost:3001 diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile new file mode 100644 index 0000000..5acee64 --- /dev/null +++ b/apps/web/Dockerfile @@ -0,0 +1,28 @@ +FROM node:22-alpine AS base +RUN corepack enable && corepack prepare pnpm@9.15.4 --activate +WORKDIR /app + +FROM base AS deps +COPY package.json pnpm-workspace.yaml pnpm-lock.yaml* .npmrc ./ +COPY apps/web/package.json ./apps/web/ +RUN pnpm install --filter @serviceops/web... + +FROM deps AS build +COPY apps/web ./apps/web +ENV NEXT_TELEMETRY_DISABLED=1 +ARG NEXT_PUBLIC_API_URL=http://localhost:3001 +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL +RUN pnpm --filter @serviceops/web run build + +FROM node:22-alpine AS runner +WORKDIR /app +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 +RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs +COPY --from=build /app/apps/web/public ./public +COPY --from=build --chown=nextjs:nodejs /app/apps/web/.next/standalone ./ +COPY --from=build --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static +USER nextjs +EXPOSE 3000 +ENV PORT=3000 HOSTNAME=0.0.0.0 +CMD ["node", "apps/web/server.js"] diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts new file mode 100644 index 0000000..6080add --- /dev/null +++ b/apps/web/next-env.d.ts @@ -0,0 +1,2 @@ +/// +/// diff --git a/apps/web/next.config.js b/apps/web/next.config.js new file mode 100644 index 0000000..472a914 --- /dev/null +++ b/apps/web/next.config.js @@ -0,0 +1,7 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = { + output: 'standalone', + transpilePackages: [], +}; + +module.exports = nextConfig; diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..f2da4f3 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,36 @@ +{ + "name": "@serviceops/web", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev -p 3000", + "build": "next build", + "start": "next start -p 3000", + "lint": "next lint", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@tanstack/react-query": "^5.66.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.474.0", + "next": "^15.1.6", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "react-hook-form": "^7.54.2", + "tailwind-merge": "^2.6.0", + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^22.10.7", + "@types/react": "^19.0.7", + "@types/react-dom": "^19.0.3", + "autoprefixer": "^10.4.20", + "eslint": "^9.18.0", + "eslint-config-next": "^15.1.6", + "postcss": "^8.5.1", + "tailwindcss": "^3.4.17", + "typescript": "^5.7.3" + } +} diff --git a/apps/web/postcss.config.js b/apps/web/postcss.config.js new file mode 100644 index 0000000..12a703d --- /dev/null +++ b/apps/web/postcss.config.js @@ -0,0 +1,6 @@ +module.exports = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/apps/web/src/app/activities/page.tsx b/apps/web/src/app/activities/page.tsx new file mode 100644 index 0000000..41d411f --- /dev/null +++ b/apps/web/src/app/activities/page.tsx @@ -0,0 +1,32 @@ +'use client'; + +import { useQuery } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Card } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +export default function ActivitiesPage() { + const { token } = useAuth(); + const { data } = useQuery>({ + queryKey: ['activities'], + queryFn: () => apiFetch('/activities', {}, token), + }); + + return ( + + +

Attività

+
+ {data?.map((a: { id: string; hours: number; hourlyCost: number; job: { title: string } }) => ( + +

{a.job.title}

+

{Number(a.hours)}h · €{Number(a.hourlyCost)}/h

+
+ ))} +
+
+
+ ); +} diff --git a/apps/web/src/app/auth/callback/page.tsx b/apps/web/src/app/auth/callback/page.tsx new file mode 100644 index 0000000..f8d4063 --- /dev/null +++ b/apps/web/src/app/auth/callback/page.tsx @@ -0,0 +1,55 @@ +'use client'; + +import { useEffect } from 'react'; +import { useRouter, useSearchParams } from 'next/navigation'; +import { useAuth } from '@/lib/auth-context'; +import { Card } from '@/components/ui/primitives'; +import { API_URL } from '@/lib/api'; + +export default function AuthCallbackPage() { + const params = useSearchParams(); + const router = useRouter(); + const { refreshSession } = useAuth(); + + useEffect(() => { + const token = params.get('token'); + if (!token) { + router.replace('/login?error=sso'); + return; + } + + (async () => { + const me = await fetch(`${API_URL}/auth/me`, { + headers: { Authorization: `Bearer ${token}` }, + }).then((r) => r.json()); + + const membership = me.memberships?.find( + (m: { organization: { id: string } }) => + m.organization.id === (JSON.parse(localStorage.getItem('serviceops_user') || '{}').organizationId || me.memberships[0]?.organization?.id), + ) ?? me.memberships?.[0]; + + const user = { + id: me.id, + email: me.email, + firstName: me.firstName, + lastName: me.lastName, + organizationId: membership?.organization?.id ?? '', + organizationName: membership?.organization?.name ?? '', + role: membership?.role ?? 'MEMBER', + }; + + localStorage.setItem('serviceops_token', token); + localStorage.setItem('serviceops_user', JSON.stringify(user)); + await refreshSession(); + router.replace('/dashboard'); + })().catch(() => router.replace('/login?error=sso')); + }, [params, router, refreshSession]); + + return ( +
+ +

Completamento accesso SSO...

+
+
+ ); +} diff --git a/apps/web/src/app/billing/invoices/[id]/page.tsx b/apps/web/src/app/billing/invoices/[id]/page.tsx new file mode 100644 index 0000000..c27365c --- /dev/null +++ b/apps/web/src/app/billing/invoices/[id]/page.tsx @@ -0,0 +1,83 @@ +'use client'; + +import { use, useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import Link from 'next/link'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface DocumentLine { + id: string; + description: string; + quantity: number; + unitPrice: number; +} + +interface InvoiceDetail { + id: string; + number: string; + status: string; + totalAmount: number; + job?: { title: string }; + lines?: DocumentLine[]; +} + +export default function InvoiceDetailPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = use(params); + const { token } = useAuth(); + const qc = useQueryClient(); + const [line, setLine] = useState({ description: '', quantity: '1', unitPrice: '0' }); + + const { data: invoice, isLoading } = useQuery({ + queryKey: ['invoice', id], + queryFn: () => apiFetch(`/billing/invoices/${id}`, {}, token), + }); + + const addLine = useMutation({ + mutationFn: () => + apiFetch(`/billing/invoices/${id}/lines`, { + method: 'POST', + body: JSON.stringify({ + description: line.description, + quantity: Number(line.quantity), + unitPrice: Number(line.unitPrice), + }), + }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['invoice', id] }); + setLine({ description: '', quantity: '1', unitPrice: '0' }); + }, + }); + + if (isLoading) return

Caricamento...

; + + return ( + + + ← Billing +

{invoice?.number}

+

{invoice?.job?.title} — €{Number(invoice?.totalAmount).toFixed(2)}

+ + +

Righe dettaglio

+
    + {invoice?.lines?.map((l: { id: string; description: string; quantity: number; unitPrice: number }) => ( +
  • + {l.description}: {Number(l.quantity)} × €{Number(l.unitPrice).toFixed(2)} +
  • + ))} +
+
+ setLine({ ...line, description: e.target.value })} /> + setLine({ ...line, quantity: e.target.value })} /> + setLine({ ...line, unitPrice: e.target.value })} /> +
+ +
+
+
+ ); +} diff --git a/apps/web/src/app/billing/page.tsx b/apps/web/src/app/billing/page.tsx new file mode 100644 index 0000000..7f31c47 --- /dev/null +++ b/apps/web/src/app/billing/page.tsx @@ -0,0 +1,115 @@ +'use client'; + +import Link from 'next/link'; +import { useMutation, useQuery } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface DocumentLine { + id: string; + description: string; + quantity: number; + unitPrice: number; +} + +interface Quote { + id: string; + number: string; + status: string; + totalAmount: number; + job?: { title: string }; + lines?: DocumentLine[]; +} + +export default function BillingPage() { + const { token } = useAuth(); + + const { data: quotes } = useQuery({ + queryKey: ['quotes'], + queryFn: () => apiFetch('/billing/quotes', {}, token), + }); + + const { data: invoices } = useQuery({ + queryKey: ['invoices'], + queryFn: () => apiFetch('/billing/invoices', {}, token), + }); + + const { data: subscription } = useQuery({ + queryKey: ['subscription'], + queryFn: () => apiFetch<{ plan: string; status: string; paymentProvider?: string }>('/billing/subscription', {}, token), + }); + + const checkout = useMutation({ + mutationFn: (params: { plan: 'PRO' | 'BUSINESS'; provider?: string }) => + apiFetch<{ url: string }>( + '/billing/checkout', + { method: 'POST', body: JSON.stringify(params) }, + token, + ), + onSuccess: (data) => { + if (data.url) window.location.href = data.url; + }, + }); + + return ( + + +

Billing

+ + +

Subscription

+

+ Piano: {subscription?.plan ?? 'FREE'} — {subscription?.status ?? 'active'} + {subscription?.paymentProvider ? ` (${subscription.paymentProvider})` : ''} +

+
+ + + + +
+
+ +
+ +

Preventivi

+
    + {quotes?.map((q) => ( +
  • + + {q.number} — {q.job?.title} + + €{Number(q.totalAmount).toFixed(2)} ({q.status}) +
  • + ))} +
+
+ +

Fatture

+
    + {invoices?.map((inv) => ( +
  • + + {inv.number} — {inv.job?.title} + + €{Number(inv.totalAmount).toFixed(2)} ({inv.status}) +
  • + ))} +
+
+
+
+
+ ); +} diff --git a/apps/web/src/app/billing/quotes/[id]/page.tsx b/apps/web/src/app/billing/quotes/[id]/page.tsx new file mode 100644 index 0000000..6d81b36 --- /dev/null +++ b/apps/web/src/app/billing/quotes/[id]/page.tsx @@ -0,0 +1,83 @@ +'use client'; + +import { use, useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import Link from 'next/link'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface DocumentLine { + id: string; + description: string; + quantity: number; + unitPrice: number; +} + +interface QuoteDetail { + id: string; + number: string; + status: string; + totalAmount: number; + job?: { title: string }; + lines?: DocumentLine[]; +} + +export default function QuoteDetailPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = use(params); + const { token } = useAuth(); + const qc = useQueryClient(); + const [line, setLine] = useState({ description: '', quantity: '1', unitPrice: '0' }); + + const { data: quote, isLoading } = useQuery({ + queryKey: ['quote', id], + queryFn: () => apiFetch(`/billing/quotes/${id}`, {}, token), + }); + + const addLine = useMutation({ + mutationFn: () => + apiFetch(`/billing/quotes/${id}/lines`, { + method: 'POST', + body: JSON.stringify({ + description: line.description, + quantity: Number(line.quantity), + unitPrice: Number(line.unitPrice), + }), + }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['quote', id] }); + setLine({ description: '', quantity: '1', unitPrice: '0' }); + }, + }); + + if (isLoading) return

Caricamento...

; + + return ( + + + ← Billing +

{quote?.number}

+

{quote?.job?.title} — €{Number(quote?.totalAmount).toFixed(2)}

+ + +

Righe dettaglio

+
    + {quote?.lines?.map((l: { id: string; description: string; quantity: number; unitPrice: number }) => ( +
  • + {l.description}: {Number(l.quantity)} × €{Number(l.unitPrice).toFixed(2)} +
  • + ))} +
+
+ setLine({ ...line, description: e.target.value })} /> + setLine({ ...line, quantity: e.target.value })} /> + setLine({ ...line, unitPrice: e.target.value })} /> +
+ +
+
+
+ ); +} diff --git a/apps/web/src/app/customers/[id]/page.tsx b/apps/web/src/app/customers/[id]/page.tsx new file mode 100644 index 0000000..1134f22 --- /dev/null +++ b/apps/web/src/app/customers/[id]/page.tsx @@ -0,0 +1,128 @@ +'use client'; + +import { useState } from 'react'; +import { use } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface Contact { + id: string; + name: string; + email?: string; + phone?: string; + role?: string; +} + +export default function CustomerDetailPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = use(params); + const { token } = useAuth(); + const qc = useQueryClient(); + const [siteName, setSiteName] = useState(''); + const [contactForm, setContactForm] = useState({ name: '', email: '', phone: '', role: '' }); + + const { data: customer, isLoading } = useQuery<{ + name: string; + sites?: Array<{ id: string; name: string; address?: string }>; + contacts?: Contact[]; + jobs?: Array<{ id: string; title: string; status: string }>; + }>({ + queryKey: ['customer', id], + queryFn: () => apiFetch(`/crm/customers/${id}`, {}, token), + }); + + const createSite = useMutation({ + mutationFn: (name: string) => + apiFetch(`/crm/customers/${id}/sites`, { method: 'POST', body: JSON.stringify({ name }) }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['customer', id] }); + setSiteName(''); + }, + }); + + const createContact = useMutation({ + mutationFn: (body: typeof contactForm) => + apiFetch(`/crm/customers/${id}/contacts`, { method: 'POST', body: JSON.stringify(body) }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['customer', id] }); + setContactForm({ name: '', email: '', phone: '', role: '' }); + }, + }); + + const deleteContact = useMutation({ + mutationFn: (contactId: string) => + apiFetch(`/crm/customers/${id}/contacts/${contactId}`, { method: 'DELETE' }, token), + onSuccess: () => qc.invalidateQueries({ queryKey: ['customer', id] }), + }); + + if (isLoading) return

Caricamento...

; + + return ( + + +

{customer?.name}

+ + +

Contatti

+
{ + e.preventDefault(); + createContact.mutate(contactForm); + }} + > + setContactForm({ ...contactForm, name: e.target.value })} required /> + setContactForm({ ...contactForm, email: e.target.value })} /> + setContactForm({ ...contactForm, phone: e.target.value })} /> + setContactForm({ ...contactForm, role: e.target.value })} /> + +
+
    + {customer?.contacts?.map((c) => ( +
  • + + {c.name} + {c.role ? ` (${c.role})` : ''} + {c.email ? ` — ${c.email}` : ''} + {c.phone ? ` — ${c.phone}` : ''} + + +
  • + ))} +
+
+ + +

Sedi / impianti

+
{ + e.preventDefault(); + createSite.mutate(siteName); + }} + > + setSiteName(e.target.value)} placeholder="Nome sede" /> + +
+
    + {customer?.sites?.map((s) => ( +
  • {s.name} {s.address ? `— ${s.address}` : ''}
  • + ))} +
+
+ + +

Storico commesse

+
    + {customer?.jobs?.map((j) => ( +
  • {j.title} — {j.status}
  • + ))} +
+
+
+
+ ); +} diff --git a/apps/web/src/app/customers/page.tsx b/apps/web/src/app/customers/page.tsx new file mode 100644 index 0000000..03caa83 --- /dev/null +++ b/apps/web/src/app/customers/page.tsx @@ -0,0 +1,79 @@ +'use client'; + +import { useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import Link from 'next/link'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface Customer { + id: string; + name: string; + email?: string; + phone?: string; + _count?: { jobs: number }; +} + +export default function CustomersPage() { + const { token } = useAuth(); + const qc = useQueryClient(); + const [name, setName] = useState(''); + + const { data: customers, isLoading } = useQuery({ + queryKey: ['customers'], + queryFn: () => apiFetch('/crm/customers', {}, token), + }); + + const createMutation = useMutation({ + mutationFn: (payload: { name: string }) => + apiFetch('/crm/customers', { method: 'POST', body: JSON.stringify(payload) }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['customers'] }); + setName(''); + }, + }); + + return ( + + +
+

Clienti

+
+ +

Nuovo cliente

+
{ + e.preventDefault(); + createMutation.mutate({ name }); + }} + > + setName(e.target.value)} /> + +
+
+ {isLoading ? ( +

Caricamento...

+ ) : ( +
+ {customers?.map((c) => ( + +
+ {c.name} + {c._count?.jobs ?? 0} commesse +
+ + ))} +
+ )} +
+
+ ); +} diff --git a/apps/web/src/app/dashboard/page.tsx b/apps/web/src/app/dashboard/page.tsx new file mode 100644 index 0000000..218efe5 --- /dev/null +++ b/apps/web/src/app/dashboard/page.tsx @@ -0,0 +1,70 @@ +'use client'; + +import { useQuery } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Card } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface DashboardKpis { + totalRevenue: number; + totalMargin: number; + averageMarginPercent: number; + jobCount: number; + openJobs: number; + overdueJobs: number; + customerCount: number; + lowStockCount: number; +} + +export default function DashboardPage() { + const { token } = useAuth(); + const { data, isLoading } = useQuery({ + queryKey: ['dashboard'], + queryFn: () => apiFetch('/reports/dashboard', {}, token), + }); + + return ( + + +

Dashboard

+ {isLoading ? ( +

Caricamento KPI...

+ ) : ( +
+ + + + + + + + 0)} + /> +
+ )} +
+
+ ); +} + +function KpiCard({ + title, + value, + alert, +}: { + title: string; + value: string; + alert?: boolean; +}) { + return ( + +

{title}

+

{value}

+
+ ); +} diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css new file mode 100644 index 0000000..7d13ae1 --- /dev/null +++ b/apps/web/src/app/globals.css @@ -0,0 +1,16 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +:root { + --background: 0 0% 100%; + --foreground: 222 47% 11%; + --primary: 221 83% 53%; + --primary-foreground: 210 40% 98%; + --muted: 210 40% 96%; + --border: 214 32% 91%; +} + +body { + @apply bg-slate-50 text-slate-900 antialiased; +} diff --git a/apps/web/src/app/inventory/page.tsx b/apps/web/src/app/inventory/page.tsx new file mode 100644 index 0000000..7ff7581 --- /dev/null +++ b/apps/web/src/app/inventory/page.tsx @@ -0,0 +1,85 @@ +'use client'; + +import { useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +export default function InventoryPage() { + const { token } = useAuth(); + const qc = useQueryClient(); + const [name, setName] = useState(''); + const [minStock, setMinStock] = useState(''); + + const { data: materials } = useQuery>({ + queryKey: ['materials'], + queryFn: () => apiFetch('/inventory/materials', {}, token), + }); + + const { data: lowStock } = useQuery({ + queryKey: ['low-stock'], + queryFn: () => apiFetch>( + '/inventory/materials/low-stock', + {}, + token, + ), + }); + + const create = useMutation({ + mutationFn: (payload: { name: string; minStock?: number }) => + apiFetch('/inventory/materials', { method: 'POST', body: JSON.stringify(payload) }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['materials'] }); + setName(''); + }, + }); + + return ( + + +

Magazzino

+ {lowStock && lowStock.length > 0 && ( + +

Alert scorte minime

+
    + {lowStock.map((m) => ( +
  • + {m.name}: {Number(m.stockQuantity)} / min {Number(m.minStock)} +
  • + ))} +
+
+ )} + +
{ + e.preventDefault(); + create.mutate({ + name, + minStock: minStock ? Number(minStock) : undefined, + }); + }} + > + setName(e.target.value)} placeholder="Nome materiale" /> + setMinStock(e.target.value)} placeholder="Scorta min." type="number" /> + +
+
+
+ {materials?.map((m: { id: string; name: string; stockQuantity: number; averageCost: number }) => ( + +

{m.name}

+

+ Scorta: {Number(m.stockQuantity)} · Costo medio: €{Number(m.averageCost)} +

+
+ ))} +
+
+
+ ); +} diff --git a/apps/web/src/app/jobs/[id]/page.tsx b/apps/web/src/app/jobs/[id]/page.tsx new file mode 100644 index 0000000..7b3d633 --- /dev/null +++ b/apps/web/src/app/jobs/[id]/page.tsx @@ -0,0 +1,207 @@ +'use client'; + +import { useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useParams } from 'next/navigation'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface JobDetail { + id: string; + title: string; + status: string; + customer: { name: string }; + economics: { + revenue: number; + laborCost: number; + materialCost: number; + margin: number; + marginPercent: number; + }; + items: Array<{ id: string; description: string; quantity: number; unitPrice: number }>; + activities: Array<{ id: string; hours: number; hourlyCost: number; description?: string }>; + materialUsages: Array<{ id: string; quantity: number; unitCost: number; material: { name: string } }>; +} + +export default function JobDetailPage() { + const { id } = useParams<{ id: string }>(); + const { token } = useAuth(); + const qc = useQueryClient(); + + const { data: job, isLoading } = useQuery({ + queryKey: ['job', id], + queryFn: () => apiFetch(`/jobs/${id}`, {}, token), + }); + + const { data: materials } = useQuery({ + queryKey: ['materials'], + queryFn: () => apiFetch>('/inventory/materials', {}, token), + }); + + const addItem = useMutation({ + mutationFn: (body: { description: string; quantity: number; unitPrice: number }) => + apiFetch(`/jobs/${id}/items`, { method: 'POST', body: JSON.stringify(body) }, token), + onSuccess: () => qc.invalidateQueries({ queryKey: ['job', id] }), + }); + + const addActivity = useMutation({ + mutationFn: (body: { jobId: string; date: string; hours: number; hourlyCost: number }) => + apiFetch('/activities', { method: 'POST', body: JSON.stringify(body) }, token), + onSuccess: () => qc.invalidateQueries({ queryKey: ['job', id] }), + }); + + const addMaterial = useMutation({ + mutationFn: (body: { jobId: string; materialId: string; quantity: number; unitCost: number }) => + apiFetch('/activities/material-usages', { method: 'POST', body: JSON.stringify(body) }, token), + onSuccess: () => qc.invalidateQueries({ queryKey: ['job', id] }), + }); + + const createQuote = useMutation({ + mutationFn: () => + apiFetch('/billing/quotes/from-job', { method: 'POST', body: JSON.stringify({ jobId: id }) }, token), + }); + + const createInvoice = useMutation({ + mutationFn: () => + apiFetch('/billing/invoices/from-job', { method: 'POST', body: JSON.stringify({ jobId: id }) }, token), + }); + + if (isLoading || !job) return

Caricamento...

; + + return ( + + +

{job.title}

+

Cliente: {job.customer.name} · Stato: {job.status}

+
+ + + {createQuote.isSuccess && Preventivo creato} + {createInvoice.isSuccess && Fattura creata} +
+ +
+

Ricavi

€{job.economics.revenue.toFixed(2)}

+

Costo ore

€{job.economics.laborCost.toFixed(2)}

+

Costo materiali

€{job.economics.materialCost.toFixed(2)}

+

Margine

€{job.economics.margin.toFixed(2)} ({job.economics.marginPercent.toFixed(1)}%)

+
+ +
+ +

Aggiungi voce (ricavo)

+ addItem.mutate({ + description: v.description as string, + quantity: Number(v.quantity), + unitPrice: Number(v.unitPrice), + })} + /> +
    + {job.items.map((i) => ( +
  • {i.description}: {Number(i.quantity)} x €{Number(i.unitPrice)}
  • + ))} +
+
+ + +

Registra ore

+ addActivity.mutate({ + jobId: id, + date: new Date().toISOString(), + hours: Number(v.hours), + hourlyCost: Number(v.hourlyCost), + })} + /> +
    + {job.activities.map((a) => ( +
  • {Number(a.hours)}h @ €{Number(a.hourlyCost)}
  • + ))} +
+
+ + +

Registra materiale

+
+ + +
+ { + const materialId = (document.getElementById('material-select') as HTMLSelectElement)?.value; + if (!materialId) return; + addMaterial.mutate({ + jobId: id, + materialId, + quantity: Number(v.quantity), + unitCost: Number(v.unitCost), + }); + }} + /> +
    + {job.materialUsages.map((m) => ( +
  • {m.material.name}: {Number(m.quantity)} x €{Number(m.unitCost)}
  • + ))} +
+
+
+
+
+ ); +} + +function QuickForm({ + fields, + onSubmit, +}: { + fields: Array<{ key: string; label: string; type?: string }>; + onSubmit: (values: Record) => void; +}) { + const [values, setValues] = useState>({}); + + return ( +
{ + e.preventDefault(); + onSubmit(values); + setValues({}); + }} + > + {fields.map((f) => ( +
+ + setValues({ ...values, [f.key]: e.target.value })} + /> +
+ ))} + +
+ ); +} diff --git a/apps/web/src/app/jobs/page.tsx b/apps/web/src/app/jobs/page.tsx new file mode 100644 index 0000000..12ae7c5 --- /dev/null +++ b/apps/web/src/app/jobs/page.tsx @@ -0,0 +1,101 @@ +'use client'; + +import { useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import Link from 'next/link'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface Job { + id: string; + title: string; + status: string; + customer: { id: string; name: string }; +} + +interface Customer { + id: string; + name: string; +} + +export default function JobsPage() { + const { token } = useAuth(); + const qc = useQueryClient(); + const [title, setTitle] = useState(''); + const [customerId, setCustomerId] = useState(''); + + const { data: jobs, isLoading } = useQuery({ + queryKey: ['jobs'], + queryFn: () => apiFetch('/jobs', {}, token), + }); + + const { data: customers } = useQuery({ + queryKey: ['customers'], + queryFn: () => apiFetch('/crm/customers', {}, token), + }); + + const createMutation = useMutation({ + mutationFn: (payload: { title: string; customerId: string }) => + apiFetch('/jobs', { method: 'POST', body: JSON.stringify(payload) }, token), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['jobs'] }); + setTitle(''); + }, + }); + + return ( + + +

Commesse

+ +

Nuova commessa

+
+ + +
+
+ + setTitle(e.target.value)} /> +
+ +
+ {isLoading ? ( +

Caricamento...

+ ) : ( +
+ {jobs?.map((job) => ( + +
+ {job.title} + {job.status} +
+

{job.customer.name}

+ + ))} +
+ )} +
+
+ ); +} diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx new file mode 100644 index 0000000..57971e2 --- /dev/null +++ b/apps/web/src/app/layout.tsx @@ -0,0 +1,21 @@ +import type { Metadata } from 'next'; +import { Inter } from 'next/font/google'; +import './globals.css'; +import { Providers } from './providers'; + +const inter = Inter({ subsets: ['latin'] }); + +export const metadata: Metadata = { + title: 'ServiceOps', + description: 'Sistema operativo per imprese di servizi', +}; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx new file mode 100644 index 0000000..0ee5b0a --- /dev/null +++ b/apps/web/src/app/login/page.tsx @@ -0,0 +1,85 @@ +'use client'; + +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useRouter } from 'next/navigation'; +import Link from 'next/link'; +import { useAuth } from '@/lib/auth-context'; +import { loginSchema } from '@/lib/schemas'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { API_URL } from '@/lib/api'; +import { z } from 'zod'; + +type LoginForm = z.infer; + +export default function LoginPage() { + const { login } = useAuth(); + const router = useRouter(); + const [orgSlug, setOrgSlug] = useState(''); + const [ssoProvider, setSsoProvider] = useState<'oidc' | 'saml'>('oidc'); + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + setError, + } = useForm({ resolver: zodResolver(loginSchema) }); + + const onSubmit = async (data: LoginForm) => { + try { + await login(data.email, data.password); + router.push('/dashboard'); + } catch (err) { + setError('root', { message: err instanceof Error ? err.message : 'Errore di accesso' }); + } + }; + + return ( +
+ +

Accedi a ServiceOps

+
+
+ + + {errors.email &&

{errors.email.message}

} +
+
+ + + {errors.password &&

{errors.password.message}

} +
+ {errors.root &&

{errors.root.message}

} + +
+

+ Non hai un account? Registrati +

+
+ + +
+ setOrgSlug(e.target.value)} placeholder="mio-slug" /> + +
+
+
+
+ ); +} diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx new file mode 100644 index 0000000..f889cb6 --- /dev/null +++ b/apps/web/src/app/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from 'next/navigation'; + +export default function Home() { + redirect('/dashboard'); +} diff --git a/apps/web/src/app/providers.tsx b/apps/web/src/app/providers.tsx new file mode 100644 index 0000000..524bb94 --- /dev/null +++ b/apps/web/src/app/providers.tsx @@ -0,0 +1,15 @@ +'use client'; + +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { useState } from 'react'; +import { AuthProvider } from '@/lib/auth-context'; + +export function Providers({ children }: { children: React.ReactNode }) { + const [queryClient] = useState(() => new QueryClient()); + + return ( + + {children} + + ); +} diff --git a/apps/web/src/app/register/page.tsx b/apps/web/src/app/register/page.tsx new file mode 100644 index 0000000..b2ed52f --- /dev/null +++ b/apps/web/src/app/register/page.tsx @@ -0,0 +1,77 @@ +'use client'; + +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useRouter } from 'next/navigation'; +import Link from 'next/link'; +import { z } from 'zod'; +import { useAuth } from '@/lib/auth-context'; +import { registerSchema } from '@/lib/schemas'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; + +type RegisterForm = z.infer; + +export default function RegisterPage() { + const { register: registerUser } = useAuth(); + const router = useRouter(); + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + setError, + } = useForm({ resolver: zodResolver(registerSchema) }); + + const onSubmit = async (data: RegisterForm) => { + try { + await registerUser(data); + router.push('/dashboard'); + } catch (err) { + setError('root', { message: err instanceof Error ? err.message : 'Errore registrazione' }); + } + }; + + return ( +
+ +

Crea il tuo account

+

Onboarding: crea organizzazione e primo utente owner

+
+
+ + + {errors.firstName &&

{errors.firstName.message}

} +
+
+ + + {errors.lastName &&

{errors.lastName.message}

} +
+
+ + + {errors.email &&

{errors.email.message}

} +
+
+ + + {errors.password &&

{errors.password.message}

} +
+
+ + + {errors.organizationName && ( +

{errors.organizationName.message}

+ )} +
+ {errors.root &&

{errors.root.message}

} + +
+

+ Hai già un account? Accedi +

+
+
+ ); +} diff --git a/apps/web/src/app/reports/page.tsx b/apps/web/src/app/reports/page.tsx new file mode 100644 index 0000000..16f4a70 --- /dev/null +++ b/apps/web/src/app/reports/page.tsx @@ -0,0 +1,65 @@ +'use client'; + +import { useQuery } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Card } from '@/components/ui/primitives'; +import { apiFetch, API_URL } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface JobMargin { + jobId: string; + title: string; + customerName: string; + revenue: number; + margin: number; + marginPercent: number; +} + +export default function ReportsPage() { + const { token } = useAuth(); + const { data } = useQuery({ + queryKey: ['job-margins'], + queryFn: () => apiFetch('/reports/jobs/margins', {}, token), + }); + + return ( + + +
+
+ {data?.map((row) => ( + +
+
+

{row.title}

+

{row.customerName}

+
+
+

€{row.revenue.toFixed(2)}

+

+ Margine €{row.margin.toFixed(2)} ({row.marginPercent.toFixed(1)}%) +

+
+
+
+ ))} +
+ + + ); +} diff --git a/apps/web/src/app/settings/page.tsx b/apps/web/src/app/settings/page.tsx new file mode 100644 index 0000000..bfb3a3f --- /dev/null +++ b/apps/web/src/app/settings/page.tsx @@ -0,0 +1,125 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { AppShell } from '@/components/layout/app-shell'; +import { AuthGuard } from '@/components/layout/auth-guard'; +import { Button, Card, Input, Label } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; +import { useAuth } from '@/lib/auth-context'; + +interface SsoConfig { + provider: string; + enabled: boolean; + issuer: string; + clientId?: string; + metadataUrl?: string; +} + +export default function SettingsPage() { + const { token, user } = useAuth(); + const qc = useQueryClient(); + const [ssoForm, setSsoForm] = useState({ + provider: 'OIDC', + enabled: false, + issuer: '', + clientId: '', + clientSecret: '', + metadataUrl: '', + idpCert: '', + }); + + const { data: org } = useQuery<{ name: string; plan: string }>({ + queryKey: ['organization'], + queryFn: () => apiFetch('/organizations/current', {}, token), + }); + + const { data: users } = useQuery>({ + queryKey: ['users'], + queryFn: () => apiFetch('/users', {}, token), + }); + + const { data: ssoConfig } = useQuery({ + queryKey: ['sso-config'], + queryFn: () => apiFetch('/auth/sso/config', {}, token), + enabled: user?.role === 'OWNER' || user?.role === 'ADMIN', + }); + + useEffect(() => { + if (ssoConfig) { + setSsoForm({ + provider: ssoConfig.provider ?? 'OIDC', + enabled: ssoConfig.enabled ?? false, + issuer: ssoConfig.issuer ?? '', + clientId: ssoConfig.clientId ?? '', + clientSecret: '', + metadataUrl: ssoConfig.metadataUrl ?? '', + idpCert: '', + }); + } + }, [ssoConfig]); + + const saveSso = useMutation({ + mutationFn: () => apiFetch('/auth/sso/config', { method: 'PATCH', body: JSON.stringify(ssoForm) }, token), + onSuccess: () => qc.invalidateQueries({ queryKey: ['sso-config'] }), + }); + + return ( + + +

Impostazioni

+ +

Organizzazione

+

{org?.name}

+

Piano: {org?.plan}

+
+ + {(user?.role === 'OWNER' || user?.role === 'ADMIN') && ( + +

SSO Enterprise (OIDC / SAML)

+
+
+ + +
+
+ setSsoForm({ ...ssoForm, enabled: e.target.checked })} + /> + +
+ setSsoForm({ ...ssoForm, issuer: e.target.value })} /> + setSsoForm({ ...ssoForm, clientId: e.target.value })} /> + setSsoForm({ ...ssoForm, clientSecret: e.target.value })} /> + setSsoForm({ ...ssoForm, metadataUrl: e.target.value })} /> + setSsoForm({ ...ssoForm, idpCert: e.target.value })} /> +
+ +
+ )} + + +

Utenti

+
    + {users?.map((m) => ( +
  • + {m.user.firstName} {m.user.lastName} — {m.user.email} ({m.role}) +
  • + ))} +
+
+
+
+ ); +} diff --git a/apps/web/src/components/layout/app-shell.tsx b/apps/web/src/components/layout/app-shell.tsx new file mode 100644 index 0000000..25ee48c --- /dev/null +++ b/apps/web/src/components/layout/app-shell.tsx @@ -0,0 +1,70 @@ +'use client'; + +import Link from 'next/link'; +import { usePathname } from 'next/navigation'; +import { cn } from '@/lib/utils'; +import { useAuth } from '@/lib/auth-context'; +import { OrganizationSwitcher } from './organization-switcher'; + +const links = [ + { href: '/dashboard', label: 'Dashboard' }, + { href: '/customers', label: 'Clienti' }, + { href: '/jobs', label: 'Commesse' }, + { href: '/activities', label: 'Attività' }, + { href: '/inventory', label: 'Magazzino' }, + { href: '/billing', label: 'Billing' }, + { href: '/reports', label: 'Report' }, + { href: '/settings', label: 'Impostazioni' }, +]; + +export function AppShell({ children }: { children: React.ReactNode }) { + const pathname = usePathname(); + const { user, logout } = useAuth(); + + return ( +
+ +
+
+
+

Organizzazione

+
+

{user?.organizationName ?? user?.organizationId}

+ +
+
+
+ + {user?.firstName} {user?.lastName} + + +
+
+
{children}
+
+
+ ); +} diff --git a/apps/web/src/components/layout/auth-guard.tsx b/apps/web/src/components/layout/auth-guard.tsx new file mode 100644 index 0000000..f4c3a89 --- /dev/null +++ b/apps/web/src/components/layout/auth-guard.tsx @@ -0,0 +1,18 @@ +'use client'; + +import { useEffect } from 'react'; +import { useRouter } from 'next/navigation'; +import { useAuth } from '@/lib/auth-context'; + +export function AuthGuard({ children }: { children: React.ReactNode }) { + const { user, loading } = useAuth(); + const router = useRouter(); + + useEffect(() => { + if (!loading && !user) router.replace('/login'); + }, [user, loading, router]); + + if (loading) return
Caricamento...
; + if (!user) return null; + return <>{children}; +} diff --git a/apps/web/src/components/layout/organization-switcher.tsx b/apps/web/src/components/layout/organization-switcher.tsx new file mode 100644 index 0000000..7001f07 --- /dev/null +++ b/apps/web/src/components/layout/organization-switcher.tsx @@ -0,0 +1,61 @@ +'use client'; + +import { useState } from 'react'; +import { useAuth } from '@/lib/auth-context'; +import { Button, Input } from '@/components/ui/primitives'; +import { apiFetch } from '@/lib/api'; + +export function OrganizationSwitcher() { + const { user, memberships, token, switchOrganization } = useAuth(); + const [creating, setCreating] = useState(false); + const [newOrgName, setNewOrgName] = useState(''); + + if (!user) return null; + + const handleCreate = async () => { + if (!newOrgName.trim() || !token) return; + const org = await apiFetch<{ id: string }>( + '/organizations', + { method: 'POST', body: JSON.stringify({ name: newOrgName }) }, + token, + ); + setNewOrgName(''); + setCreating(false); + await switchOrganization(org.id); + }; + + return ( +
+ + {creating ? ( +
+ setNewOrgName(e.target.value)} + placeholder="Nuova org" + /> + +
+ ) : ( + + )} +
+ ); +} diff --git a/apps/web/src/components/ui/primitives.tsx b/apps/web/src/components/ui/primitives.tsx new file mode 100644 index 0000000..f61fbb2 --- /dev/null +++ b/apps/web/src/components/ui/primitives.tsx @@ -0,0 +1,48 @@ +import { cn } from '@/lib/utils'; + +export function Button({ + className, + variant = 'default', + ...props +}: React.ButtonHTMLAttributes & { + variant?: 'default' | 'outline' | 'ghost'; +}) { + return ( +