-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathcli.py
More file actions
686 lines (627 loc) · 30.2 KB
/
Copy pathcli.py
File metadata and controls
686 lines (627 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# Copyright 2026 Neo4j Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CLI entry point for create-context-graph."""
from __future__ import annotations
import logging
import os
import re
import sys
from pathlib import Path
import click
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from create_context_graph.config import SUPPORTED_FRAMEWORKS, FRAMEWORK_ALIASES, ProjectConfig
from create_context_graph.ontology import list_available_domains, load_domain
from create_context_graph.renderer import ProjectRenderer
console = Console()
def _derive_domain_id(neo4j_uri: str) -> str:
"""Derive a domain ID from the Neo4j URI, falling back to 'discovered-database'."""
try:
from urllib.parse import urlparse
parsed = urlparse(neo4j_uri)
host = parsed.hostname or ""
path = parsed.path.strip("/") if parsed.path else ""
if path and path != "neo4j":
return re.sub(r"[^a-z0-9]+", "-", path.lower()).strip("-") or "discovered-database"
if host and host not in ("localhost", "127.0.0.1", "0.0.0.0"):
name = host.split(".")[0]
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "discovered-database"
except Exception:
pass
return "discovered-database"
def _refine_discovered_system_prompt(
ontology,
discovered_schema: dict,
anthropic_api_key: str | None,
) -> None:
"""Interactively refine the discovered ontology system prompt."""
if not sys.stdin.isatty():
return
import questionary
from create_context_graph.discovery import refine_system_prompt
original_prompt = ontology.system_prompt
console.print("\n[bold]Auto-generated system prompt:[/bold]\n")
console.print(original_prompt)
user_input = questionary.text(
"Edit the system prompt, enter a rough description, or press Enter to keep:",
).ask()
if user_input is None:
raise SystemExit("Aborted.")
user_input = user_input.strip()
if not user_input:
return
if not anthropic_api_key:
ontology.system_prompt = user_input
return
refined_prompt = refine_system_prompt(
user_input,
discovered_schema,
anthropic_api_key,
)
console.print("\n[bold]Refined system prompt:[/bold]\n")
console.print(refined_prompt)
while True:
action = questionary.select(
"How would you like to proceed?",
choices=[
questionary.Choice("Accept", value="accept"),
questionary.Choice("Refine further", value="refine"),
questionary.Choice("Edit manually", value="edit"),
questionary.Choice("Use my original text", value="original"),
],
).ask()
if action is None:
raise SystemExit("Aborted.")
if action == "accept":
ontology.system_prompt = refined_prompt
return
if action == "original":
ontology.system_prompt = user_input
return
if action == "edit":
manual_prompt = questionary.text(
"Edit system prompt:",
default=refined_prompt,
).ask()
if manual_prompt is None:
raise SystemExit("Aborted.")
ontology.system_prompt = manual_prompt
return
feedback = questionary.text("What should be refined?").ask()
if feedback is None:
raise SystemExit("Aborted.")
refined_prompt = refine_system_prompt(
user_input,
discovered_schema,
anthropic_api_key,
feedback=feedback,
)
console.print("\n[bold]Refined system prompt:[/bold]\n")
console.print(refined_prompt)
@click.command()
@click.argument("project_name", required=False)
@click.option(
"--domain",
type=str,
help="Domain ID (e.g., financial-services, healthcare, software-engineering)",
)
@click.option(
"--framework",
type=click.Choice(SUPPORTED_FRAMEWORKS + list(FRAMEWORK_ALIASES.keys()), case_sensitive=False),
help="Agent framework to use",
)
@click.option("--demo-data", is_flag=True, help="Generate synthetic demo data")
@click.option("--ingest", is_flag=True, help="Ingest generated data into Neo4j")
@click.option("--neo4j-uri", envvar="NEO4J_URI", help="Neo4j connection URI")
@click.option("--neo4j-username", envvar="NEO4J_USERNAME", default="neo4j")
@click.option("--neo4j-password", envvar="NEO4J_PASSWORD", default="password")
@click.option("--neo4j-aura-env", type=click.Path(exists=True), help="Path to Neo4j Aura .env file with credentials")
@click.option("--neo4j-local", is_flag=True, help="Use @johnymontana/neo4j-local for local Neo4j (no Docker)")
@click.option("--anthropic-api-key", envvar="ANTHROPIC_API_KEY", help="Anthropic API key for LLM generation")
@click.option("--openai-api-key", envvar="OPENAI_API_KEY", help="OpenAI API key for LLM generation")
@click.option("--google-api-key", envvar="GOOGLE_API_KEY", help="Google/Gemini API key (required for google-adk framework)")
@click.option("--custom-domain", type=str, help="Natural language description for custom domain generation (requires --anthropic-api-key)")
@click.option("--connector", multiple=True, help="SaaS connector to enable (github, slack, jira, notion, gmail, gcal, salesforce, linear, google-workspace, claude-code, claude-ai, chatgpt, local-file)")
@click.option("--linear-api-key", envvar="LINEAR_API_KEY", help="Linear API key (required for --connector linear)")
@click.option("--linear-team", envvar="LINEAR_TEAM", help="Linear team key to filter import (e.g., ENG)")
@click.option("--claude-code-scope", type=click.Choice(["current", "all"]), default="current", help="Import sessions from current project (default) or all projects")
@click.option("--claude-code-project", help="Explicit project path to import Claude Code sessions for")
@click.option("--claude-code-since", help="Import Claude Code sessions since date (ISO format)")
@click.option("--claude-code-max-sessions", type=int, default=0, help="Maximum number of Claude Code sessions to import (0=all)")
@click.option("--claude-code-content", type=click.Choice(["truncated", "full", "none"]), default="truncated", help="Content storage mode for Claude Code messages")
@click.option("--local-file-path", "local_file_path", multiple=True, type=click.Path(), help="Path to a file or directory to ingest with --connector local-file (repeatable)")
@click.option("--local-file-pattern", default="**/*", help="Glob pattern filter for local-file ingest")
@click.option("--local-file-recursive/--local-file-no-recursive", default=True, help="Recurse into subdirectories during local-file ingest")
@click.option("--local-file-follow-links", is_flag=True, default=False, help="Follow symlinks during local-file ingest")
@click.option("--local-file-exclude", "local_file_exclude", multiple=True, help="Glob pattern to exclude from local-file ingest (repeatable)")
@click.option("--gws-folder-id", envvar="GWS_FOLDER_ID", help="Google Drive folder ID to scope import")
@click.option("--gws-include-comments/--gws-no-comments", default=True, help="Import comment threads from Docs/Sheets/Slides")
@click.option("--gws-include-revisions/--gws-no-revisions", default=True, help="Import revision history metadata")
@click.option("--gws-include-activity/--gws-no-activity", default=True, help="Import Drive Activity events")
@click.option("--gws-include-calendar", is_flag=True, default=False, help="Import Calendar events")
@click.option("--gws-include-gmail", is_flag=True, default=False, help="Import Gmail thread metadata")
@click.option("--gws-since", help="Import data since date (ISO format, default 90 days ago)")
@click.option("--gws-mime-types", default="docs,sheets,slides", help="Comma-separated MIME types (docs,sheets,slides,pdf,all)")
@click.option("--gws-max-files", type=int, default=500, help="Maximum files to import (safety limit)")
@click.option("--import-type", "import_type", type=click.Choice(["claude-ai", "chatgpt"]), help="Chat history import type (claude-ai or chatgpt)")
@click.option("--import-file", type=click.Path(), help="Path to chat export file (.zip, .json, .jsonl)")
@click.option("--import-depth", type=click.Choice(["fast", "deep"]), default="fast", help="Import extraction depth (fast=messages only, deep=full)")
@click.option("--import-filter-after", type=str, help="Only import conversations after this date (ISO 8601)")
@click.option("--import-filter-before", type=str, help="Only import conversations before this date (ISO 8601)")
@click.option("--import-filter-title", type=str, help="Only import conversations matching this title pattern (regex)")
@click.option("--import-max-conversations", type=int, default=0, help="Maximum conversations to import (0=all)")
@click.option("--with-mcp", is_flag=True, default=False, help="Generate MCP server configuration for Claude Desktop")
@click.option("--mcp-profile", type=click.Choice(["core", "extended"], case_sensitive=False), default="extended", help="MCP tool profile (core=6 tools, extended=16 tools)")
@click.option("--session-strategy", type=click.Choice(["per_conversation", "per_day", "persistent"], case_sensitive=False), default="per_conversation", help="Memory session strategy")
@click.option("--auto-extract/--no-auto-extract", default=True, help="Auto-extract entities from conversation messages")
@click.option("--auto-preferences/--no-auto-preferences", default=True, help="Auto-detect user preferences from conversation messages")
@click.option("--output-dir", type=click.Path(), help="Output directory (default: ./<project-name>)")
@click.option("--demo", is_flag=True, help="Shortcut for --reset-database --demo-data --ingest")
@click.option("--dry-run", is_flag=True, help="Preview what would be generated without creating files")
@click.option("--reset-database", is_flag=True, help="Clear all Neo4j data before ingesting")
@click.option(
"--from-database",
is_flag=True,
default=False,
help="Discover schema from an existing Neo4j database (no --domain required)",
)
@click.option("--verbose", is_flag=True, help="Enable verbose debug output")
@click.option("--list-domains", is_flag=True, help="List available domains and exit")
@click.version_option(package_name="create-context-graph")
def main(
project_name: str | None,
domain: str | None,
framework: str | None,
demo_data: bool,
ingest: bool,
neo4j_uri: str | None,
neo4j_username: str,
neo4j_password: str,
neo4j_aura_env: str | None,
neo4j_local: bool,
anthropic_api_key: str | None,
openai_api_key: str | None,
google_api_key: str | None,
custom_domain: str | None,
connector: tuple[str, ...],
linear_api_key: str | None,
linear_team: str | None,
gws_folder_id: str | None,
gws_include_comments: bool,
gws_include_revisions: bool,
gws_include_activity: bool,
gws_include_calendar: bool,
gws_include_gmail: bool,
gws_since: str | None,
gws_mime_types: str,
gws_max_files: int,
claude_code_scope: str,
claude_code_project: str | None,
claude_code_since: str | None,
claude_code_max_sessions: int,
claude_code_content: str,
local_file_path: tuple[str, ...],
local_file_pattern: str,
local_file_recursive: bool,
local_file_follow_links: bool,
local_file_exclude: tuple[str, ...],
import_type: str | None,
import_file: str | None,
import_depth: str,
import_filter_after: str | None,
import_filter_before: str | None,
import_filter_title: str | None,
import_max_conversations: int,
with_mcp: bool,
mcp_profile: str,
session_strategy: str,
auto_extract: bool,
auto_preferences: bool,
output_dir: str | None,
demo: bool,
dry_run: bool,
reset_database: bool,
from_database: bool,
verbose: bool,
list_domains: bool,
) -> None:
"""Create a domain-specific context graph application.
Generates a full-stack application with a FastAPI backend,
Next.js frontend, Neo4j knowledge graph, and AI agent—
all customized for your industry domain.
"""
# Verbose logging
if verbose:
logging.basicConfig(level=logging.DEBUG, format="%(name)s %(levelname)s: %(message)s")
# --demo is a shortcut for --reset-database --demo-data --ingest
if demo:
reset_database = True
demo_data = True
ingest = True
if from_database and not neo4j_uri:
console.print("[red]Error:[/red] --neo4j-uri is required with --from-database.")
raise SystemExit(1)
if from_database and (not neo4j_username or not neo4j_password):
console.print(
"[red]Error:[/red] --neo4j-username and --neo4j-password (or NEO4J_USERNAME / "
"NEO4J_PASSWORD env vars) are required with --from-database."
)
raise SystemExit(1)
if from_database and connector:
console.print(
"[yellow]Warning:[/yellow] --connector flags are ignored when --from-database is set."
)
# Validate --import-type / --import-file co-dependency
if import_type and not import_file:
console.print("[red]Error:[/red] --import-file is required when --import-type is specified.")
raise SystemExit(1)
if import_file and not import_type:
console.print("[red]Error:[/red] --import-type is required when --import-file is specified.")
raise SystemExit(1)
# Auto-add chat import connector when --import-type is provided
if import_type:
connector = tuple(list(connector) + [import_type])
# List domains mode
if list_domains:
domains = list_available_domains()
console.print("\n[bold]Available domains:[/bold]\n")
for d in domains:
console.print(f" {d['id']:30s} {d['name']}")
console.print()
return
# Handle custom domain generation (non-interactive)
custom_domain_yaml = None
custom_ontology = None
if custom_domain:
if not anthropic_api_key:
console.print("[red]Error:[/red] --anthropic-api-key is required for custom domain generation.")
raise SystemExit(1)
from create_context_graph.custom_domain import (
display_ontology_summary,
generate_custom_domain,
)
console.print("[bold]Generating custom domain ontology...[/bold]")
try:
custom_ontology, custom_domain_yaml = generate_custom_domain(
custom_domain, anthropic_api_key
)
except ValueError as e:
console.print(f"[red]Error:[/red] {e}")
raise SystemExit(1)
display_ontology_summary(custom_ontology, console)
domain = custom_ontology.domain.id
discovered_ontology = None
if from_database:
from create_context_graph.discovery import (
build_ontology_from_discovery,
discover_ontology_from_database,
)
console.print("[bold]Discovering schema from Neo4j database...[/bold]")
try:
discovered_schema = discover_ontology_from_database(
neo4j_uri,
neo4j_username,
neo4j_password,
)
except ConnectionError as e:
console.print(f"[red]Error:[/red] {e}")
raise SystemExit(1)
property_count = sum(
len(properties)
for properties in (discovered_schema.get("properties") or {}).values()
)
console.print(
" "
f"{len(discovered_schema.get('labels') or [])} labels, "
f"{len(discovered_schema.get('relationship_types') or [])} relationship types, "
f"{property_count} properties"
)
discovered_domain_id = _derive_domain_id(neo4j_uri)
discovered_ontology = build_ontology_from_discovery(
discovered_schema,
discovered_domain_id,
)
_refine_discovered_system_prompt(
discovered_ontology,
discovered_schema,
anthropic_api_key,
)
domain = discovered_ontology.domain.id
# Resolve deprecated framework aliases
if framework:
framework = FRAMEWORK_ALIASES.get(framework, framework)
# Handle Neo4j Aura .env import
if neo4j_aura_env:
from create_context_graph.wizard import _parse_aura_env
neo4j_uri, neo4j_username, neo4j_password = _parse_aura_env(neo4j_aura_env)
# Determine neo4j_type from flags
if neo4j_aura_env:
neo4j_type_resolved = "aura"
elif neo4j_local:
neo4j_type_resolved = "local"
elif neo4j_uri and "aura" in (neo4j_uri or ""):
neo4j_type_resolved = "aura"
elif from_database:
neo4j_type_resolved = "existing"
else:
neo4j_type_resolved = "docker"
# Validate empty project name in non-interactive mode
if project_name is not None and not project_name.strip():
console.print("[red]Error:[/red] Project name cannot be empty.")
raise SystemExit(1)
# Auto-generate project name when all required flags are provided but no positional arg
if not project_name and (domain or custom_domain) and framework:
domain_part = domain or "custom"
project_name = f"{domain_part}-{framework}-app"
if not project_name and from_database and framework and domain:
project_name = f"{domain}-{framework}-app"
# Non-TTY detection: give a helpful error when wizard would be required but stdin isn't interactive
if not project_name and not sys.stdin.isatty():
missing = []
if not from_database and not domain and not custom_domain:
missing.append("--domain")
if not framework:
missing.append("--framework")
console.print(f"[red]Error:[/red] Non-interactive mode requires: {', '.join(missing or ['--domain and --framework'])}")
console.print("Tip: Provide all required flags, e.g.:")
console.print(" create-context-graph --domain healthcare --framework pydanticai --demo-data")
raise SystemExit(1)
# If all required args are provided, skip wizard
if project_name and (domain or custom_domain or from_database) and framework:
config = ProjectConfig(
project_name=project_name,
domain=domain or "custom",
framework=framework,
data_source="none"
if from_database
else ("saas" if connector else ("demo" if demo_data else "none")),
neo4j_uri=neo4j_uri or "neo4j://localhost:7687",
neo4j_username=neo4j_username,
neo4j_password=neo4j_password,
neo4j_type=neo4j_type_resolved,
anthropic_api_key=anthropic_api_key,
openai_api_key=openai_api_key,
google_api_key=google_api_key,
generate_data=False if from_database else demo_data,
custom_domain_yaml=custom_domain_yaml,
saas_connectors=[] if from_database else list(connector),
with_mcp=with_mcp,
mcp_profile=mcp_profile,
session_strategy=session_strategy,
auto_extract=auto_extract,
auto_preferences=auto_preferences,
from_database=from_database,
)
# Populate SaaS credentials from CLI flags
if "linear" in config.saas_connectors:
creds = {}
if linear_api_key:
creds["api_key"] = linear_api_key
if linear_team:
creds["team_key"] = linear_team
config.saas_credentials["linear"] = creds
if not linear_api_key:
console.print(
"[yellow]Warning:[/yellow] --connector linear requires a Linear API key. "
"Set LINEAR_API_KEY in your .env or pass --linear-api-key."
)
if "google-workspace" in config.saas_connectors:
creds = {
"folder_id": gws_folder_id or "",
"include_comments": str(gws_include_comments).lower(),
"include_revisions": str(gws_include_revisions).lower(),
"include_activity": str(gws_include_activity).lower(),
"include_calendar": str(gws_include_calendar).lower(),
"include_gmail": str(gws_include_gmail).lower(),
"since": gws_since or "",
"mime_types": gws_mime_types or "",
"max_files": str(gws_max_files),
}
config.saas_credentials["google-workspace"] = creds
if "claude-code" in config.saas_connectors:
creds = {
"scope": claude_code_scope,
"project_filter": claude_code_project or "",
"since": claude_code_since or "",
"max_sessions": str(claude_code_max_sessions),
"content_mode": claude_code_content,
}
config.saas_credentials["claude-code"] = creds
if "local-file" in connector:
if not local_file_path:
console.print(
"[red]Error:[/red] --connector local-file requires at least one "
"--local-file-path."
)
raise SystemExit(1)
# ProjectConfig.saas_credentials values are typed as
# ``dict[str, str]`` — list-valued fields are stored joined by
# os.pathsep here and split back in LocalFileConnector.authenticate.
# os.pathsep (':' on POSIX, ';' on Windows) cannot appear in a
# well-formed filesystem path, so this is safe for all platforms.
config.saas_credentials["local-file"] = {
"paths": os.pathsep.join(local_file_path),
"pattern": local_file_pattern,
"recursive": str(local_file_recursive).lower(),
"follow_links": str(local_file_follow_links).lower(),
"exclude": os.pathsep.join(local_file_exclude),
}
if import_type and import_file:
creds = {
"file_path": str(Path(import_file).resolve()),
"depth": import_depth,
"filter_after": import_filter_after or "",
"filter_before": import_filter_before or "",
"filter_title": import_filter_title or "",
"max_conversations": str(import_max_conversations),
}
config.saas_credentials[import_type] = creds
# Warn if google-adk is selected without a Google API key
if config.resolved_framework == "google-adk" and not google_api_key:
console.print(
"[yellow]Warning:[/yellow] google-adk framework requires a Google/Gemini API key. "
"Set GOOGLE_API_KEY in your .env or pass --google-api-key."
)
# Warn if openai-agents is selected without an OpenAI API key
if config.resolved_framework == "openai-agents" and not openai_api_key:
console.print(
"[yellow]Warning:[/yellow] openai-agents framework requires an OpenAI API key. "
"Set OPENAI_API_KEY in your .env or pass --openai-api-key."
)
else:
# Launch interactive wizard
from create_context_graph.wizard import run_wizard
config = run_wizard()
# Resolve output directory
out = Path(output_dir) if output_dir else Path.cwd() / config.project_slug
# Dry run: show what would be generated and exit
if dry_run:
console.print("\n[bold]Dry run — no files will be created[/bold]\n")
console.print(f" Project: {config.project_name}")
console.print(f" Slug: {config.project_slug}")
console.print(f" Domain: {config.domain}")
console.print(f" Framework: {config.framework}")
console.print(f" Neo4j: {config.neo4j_type} ({config.neo4j_uri})")
console.print(f" Data: {config.data_source}")
if config.from_database:
console.print(" Schema: discovered from database")
if config.saas_connectors:
console.print(f" Connectors: {', '.join(config.saas_connectors)}")
console.print(f" Memory: strategy={config.session_strategy}, extract={config.auto_extract}, preferences={config.auto_preferences}")
if config.with_mcp:
console.print(f" MCP: profile={config.mcp_profile}")
console.print(f" Output: {out}")
console.print()
return
if out.exists() and any(out.iterdir()):
console.print(f"[red]Error:[/red] Directory {out} already exists and is not empty.")
raise SystemExit(1)
# Load domain ontology
if discovered_ontology:
ontology = discovered_ontology
elif custom_ontology:
ontology = custom_ontology
elif config.custom_domain_yaml:
from create_context_graph.ontology import load_domain_from_yaml_string
ontology = load_domain_from_yaml_string(config.custom_domain_yaml)
else:
try:
ontology = load_domain(config.domain)
except FileNotFoundError:
console.print(f"[red]Error:[/red] Domain '{config.domain}' not found.")
available = list_available_domains()
console.print("Available domains: " + ", ".join(d["id"] for d in available))
raise SystemExit(1)
# Generate project
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("Creating project scaffold...", total=None)
renderer = ProjectRenderer(config, ontology)
renderer.render(out)
progress.update(task, description="Project generated!")
# Generate demo data if requested
fixture_path = out / "data" / "fixtures.json"
if not config.from_database and (config.generate_data or demo_data):
console.print("\n[bold]Generating demo data...[/bold]")
from create_context_graph.generator import generate_fixture_data
generate_fixture_data(
ontology,
fixture_path,
api_key=config.anthropic_api_key or anthropic_api_key,
)
# Import data from SaaS connectors if configured
if not config.from_database and config.saas_connectors:
import json
from create_context_graph.connectors import get_connector, merge_connector_results, NormalizedData
console.print("\n[bold]Importing data from connected services...[/bold]")
results: list[NormalizedData] = []
for conn_id in config.saas_connectors:
try:
conn = get_connector(conn_id)
creds = config.saas_credentials.get(conn_id, {})
console.print(f" Connecting to {conn.service_name}...")
conn.authenticate(creds)
console.print(f" Fetching data from {conn.service_name}...")
data = conn.fetch()
results.append(data)
entity_count = sum(len(v) for v in data.entities.values())
console.print(f" [green]✓[/green] {conn.service_name}: {entity_count} entities, {len(data.documents)} documents")
except Exception as e:
console.print(f" [yellow]⚠[/yellow] {conn_id}: {e}")
if results:
merged = merge_connector_results(results)
fixture_path.parent.mkdir(parents=True, exist_ok=True)
fixture_path.write_text(json.dumps(merged.model_dump(), indent=2, default=str))
console.print(f"\n[green]Imported data written to {fixture_path}[/green]")
# Reset Neo4j database if requested
if reset_database:
console.print("\n[bold]Resetting Neo4j database...[/bold]")
from create_context_graph.ingest import reset_neo4j
try:
reset_neo4j(
config.neo4j_uri,
config.neo4j_username,
config.neo4j_password,
)
console.print(" [green]Database cleared[/green]")
except Exception as e:
console.print(f" [red]Failed to reset database:[/red] {e}")
# Ingest into Neo4j if requested
if ingest and fixture_path.exists():
console.print("\n[bold]Ingesting data into Neo4j...[/bold]")
from create_context_graph.ingest import ingest_data
ingest_data(
fixture_path,
ontology,
config.neo4j_uri,
config.neo4j_username,
config.neo4j_password,
)
console.print(" [dim]Tip: Use --reset-database if you previously ingested a different domain into this Neo4j instance.[/dim]")
# Success message
console.print()
console.print(f"[bold green]Done![/bold green] Your {ontology.domain.name} context graph app is ready.")
console.print()
try:
display_path = out.relative_to(Path.cwd())
except ValueError:
display_path = out
def _step(cmd: str, comment: str) -> None:
console.print(f" [bold]{cmd}[/bold]{' ' * (18 - len(cmd))}# {comment}")
console.print(f" [bold]cd {display_path}[/bold]")
_step("make install", "Install dependencies")
if config.neo4j_type == "docker":
_step("make docker-up", "Start Neo4j")
elif config.neo4j_type == "local":
_step("make neo4j-start", "Start Neo4j (requires Node.js)")
if config.from_database:
_step("make start", "Start backend + frontend (data already in Neo4j)")
elif config.saas_connectors:
_step("make import", "Fetch real data from connected services")
_step("make seed", "Apply schema + ingest data into Neo4j")
elif ingest:
_step("make seed", "Re-seed sample data (already ingested)")
else:
_step("make seed", "Apply schema + seed sample data")
if config.with_mcp:
_step("make mcp-server", "Start MCP server for Claude Desktop")
if not config.from_database:
_step("make start", "Start backend + frontend")
console.print()
console.print(" Backend: http://localhost:8000")
console.print(" Frontend: http://localhost:3000")
console.print()