npm package: @graphito/core
Description: Core GDD framework for graph resolution, validation, and health scoring
Latest version: 0.1.0

# @gdd/core

Core GDD framework for graph resolution, validation, and health scoring.

## What is GDD?

Graph-Driven Development (GDD) transforms monolithic documentation into a dependency graph of specialized nodes, optimized for AI agent consumption. Instead of loading a `spec.md` document of 100,000+ tokens, GDD allows loading only the 3-5 relevant nodes for each task, reducing context by 71-90%.

## Installation

```bash
npm install @gdd/core
```

## Quick Start

```typescript
import { GDD } from '@gdd/core';

// Initialize GDD
const gdd = new GDD({
  systemMapPath: './system-map-v2.yaml',
  docsPath: './docs/nodes-v2'
});

// Resolve dependencies for a node
const nodes = gdd.resolve('feature-a');
console.log(`Resolved ${nodes.length} nodes`);
console.log(`Total tokens: ${nodes.reduce((sum, n) => sum + n.tokenCount, 0)}`);

// Validate system
const validation = gdd.validate();
if (validation.valid) {
  console.log('System is valid');
}

// Get health score
const health = gdd.health();
console.log(`Health Score: ${health.score}/100 (${health.status})`);

// Cleanup
gdd.dispose();
```

## API Reference

### GDD Class

Main orchestrator class for GDD framework.

#### Constructor

```typescript
new GDD(config: GDDCoreConfig)
```

**Config:**
- `systemMapPath`: Path to system-map-v2.yaml
- `docsPath`: Path to docs/nodes-v2 directory
- `configPath?`: Optional path to .gddrc.json
- `verbose?`: Enable verbose logging

#### Methods

##### `resolve(nodeNames: string | string[]): ResolvedNode[]`

Resolves node dependencies transitively and loads nodes.

**Returns:** Array of resolved nodes with token counts and depth information.

##### `validate(): ValidationResult`

Validates the entire GDD system.

**Returns:** Validation result with errors, warnings, and info messages.

##### `health(): HealthScore`

Calculates health score (0-100).

**Returns:** Health score with breakdown and status.

##### `predictDrift(): DriftReport`

Predicts which nodes are drifting.

**Returns:** Drift report with risk categories.

##### `repair(options?: RepairOptions): RepairReport`

Auto-repairs common issues.

**Options:**
- `dryRun?`: Don't actually modify files
- `updateCoverage?`: Update coverage from coverage-summary.json
- `updateTimestamps?`: Update last_updated timestamps
- `fixCrossReferences?`: Fix broken cross-references

**Returns:** Repair report with fixes applied.

##### `dispose(): void`

Cleanup resources (call when done).

## Types

### ResolvedNode

```typescript
interface ResolvedNode {
  id: string;
  frontmatter: NodeFrontmatter;
  content: string;
  filePath: string;
  lineCount: number;
  wordCount: number;
  tokenCount: number;
  depth: number;
  reason: 'requested' | 'dependency';
}
```

### HealthScore

```typescript
interface HealthScore {
  score: number; // 0-100
  breakdown: HealthBreakdown;
  status: 'healthy' | 'degraded' | 'critical';
  nodes_detected: number;
  nodes_total: number;
  nodes_missing: number;
}
```

### ValidationResult

```typescript
interface ValidationResult {
  valid: boolean;
  errors: ValidationIssue[];
  warnings: ValidationIssue[];
  info: ValidationIssue[];
  summary: {
    total_issues: number;
    error_count: number;
    warning_count: number;
    info_count: number;
  };
}
```

## Configuration

### GDDCoreConfig

```typescript
interface GDDCoreConfig {
  systemMapPath: string;      // Path to system-map-v2.yaml
  docsPath: string;           // Path to docs/nodes-v2 directory
  configPath?: string;        // Optional path to .gddrc.json
  verbose?: boolean;          // Enable verbose logging
}
```

### Defaults

- `verbose`: `false`
- `configPath`: Auto-detected from workspace root

## System Map Format

The `system-map-v2.yaml` file defines your system's dependency graph:

```yaml
metadata:
  version: 2.0.0
  total_nodes: 5
  gdd_version: '2.0'

nodes:
  feature-a:
    description: Feature A description
    status: production
    priority: critical
    owner: Back-end Dev
    last_updated: '2026-01-29T00:00:00.000Z'
    coverage: 85
    depends_on:
      - feature-b
    required_by: []
    docs:
      - docs/nodes-v2/feature-a.md
    files:
      - src/services/featureA.js
```

### Required Fields

- `description`: Human-readable description
- `status`: `production` | `development` | `deprecated`
- `priority`: `critical` | `high` | `medium` | `low`
- `owner`: Owner/team name
- `last_updated`: ISO 8601 date string
- `coverage`: Test coverage percentage (0-100)
- `docs`: Array of markdown file paths

### Optional Fields

- `depends_on`: Array of node IDs this node depends on
- `required_by`: Array of node IDs that depend on this node
- `files`: Array of source code file paths
- `workers`: Array of worker names
- `ssot_references`: Array of SSOT reference names
- `subnodes`: Array of subnode names

## Node Format

Each node is a markdown file with YAML frontmatter:

```markdown
---
node_id: feature-a
status: production
priority: critical
owner: Back-end Dev
last_updated: 2026-01-29
coverage: 85
coverage_source: auto
depends_on:
  - feature-b
---

# Feature A

Documentation content here...

## Dependencies

- **feature-b**: Description of dependency
```

### Frontmatter Fields

**Required:**
- `node_id`: Must match system-map key
- `status`: `production` | `development` | `deprecated`
- `priority`: `critical` | `high` | `medium` | `low`
- `owner`: Owner name
- `last_updated`: Date string (YYYY-MM-DD)
- `coverage`: Number (0-100)

**Optional:**
- `version`: Version string
- `coverage_source`: `auto` | `manual` (default: `auto`)
- `depends_on`: Array of node IDs
- `required_by`: Array of node IDs
- `workers`: Array of worker names
- `ssot_references`: Array of SSOT references
- `subnodes`: Array of subnode names

## Advanced Usage

### Custom Configuration

```typescript
import { GDD } from '@gdd/core';
import { createLogger } from '@gdd/core';

// Create custom logger
const logger = createLogger({
  verbose: true,
  level: 'debug'
});

const gdd = new GDD({
  systemMapPath: './system-map-v2.yaml',
  docsPath: './docs/nodes-v2',
  verbose: true
});
```

### CI/CD Integration

```typescript
// In CI pipeline
const gdd = new GDD({
  systemMapPath: './system-map-v2.yaml',
  docsPath: './docs/nodes-v2'
});

const health = gdd.health();
if (health.score < 87) {
  console.error(`Health score ${health.score} below threshold`);
  process.exit(1);
}

const validation = gdd.validate();
if (!validation.valid) {
  console.error('Validation failed');
  process.exit(1);
}
```

### Troubleshooting

**Error: "System map file not found"**
- Ensure `systemMapPath` points to a valid `system-map-v2.yaml` file
- Check file permissions

**Error: "Node file not found"**
- Verify `docsPath` contains the node files referenced in system-map
- Check that paths in `docs` field are relative to system-map directory

**Low health score**
- Run `gdd validate` to identify issues
- Check for missing nodes, broken dependencies, or outdated coverage
- Use `gdd repair` to auto-fix common issues

## Examples

- [Basic Usage](../examples/basic-usage/index.ts) - Complete TypeScript example
- [Sample Project](../examples/sample-project/) - Real-world project structure

## License

MIT