# https://github.com/grainulation/grainulation 项目说明书

生成时间：2026-05-15 12:02:35 UTC

## 目录

- [Project Overview](#project-overview)
- [CLI Architecture](#cli-architecture)
- [Command Reference](#command-reference)
- [Ecosystem Overview](#ecosystem-overview)
- [Tool Integration](#tool-integration)
- [Setup and Installation](#setup-installation)
- [Health Checks and Diagnostics](#health-checks)
- [Package Management](#package-management)
- [Server and Routing](#server-routing)
- [Extensibility Guide](#extensibility-guide)

<a id='project-overview'></a>

## Project Overview

### 相关页面

相关主题：[Ecosystem Overview](#ecosystem-overview), [CLI Architecture](#cli-architecture)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/grainulation/grainulation/blob/main/README.md)
- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)
- [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)
- [site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html)
</details>

# Project Overview

Grainulation is an ecosystem of eight zero-dependency CLI tools that transform technical decision-making from gut-feel opinions into structured, evidence-based claims. The system enables teams to research questions, challenge findings, and compile decisions into auditable briefs backed by a full git history.

## Purpose and Scope

Most technical decisions fail not due to lack of data, but lack of process for converting data into evidence and evidence into conviction. Grainulation provides that missing process through a claims-based research framework.

The ecosystem serves teams who need to make consequential technical decisions—such as architecture migrations, technology choices, or infrastructure changes—and want defensible, auditable reasoning behind those choices.

**Core objectives:**

- Turn vague technical questions into typed, evidence-graded claims
- Provide adversarial testing through a challenge mechanism
- Catch contradictions and weak evidence via a deterministic compiler
- Produce decision briefs with full git audit trails 资料来源：[README.md:18]()

## Architecture

The grainulation project follows a monorepo structure with eight independent packages plus the meta-package that orchestrates them.

```mermaid
graph TD
    subgraph "Meta Package"
        G[grainulation<br/>Unified CLI]
    end
    
    subgraph "Core Tools"
        W[wheat<br/>Research Engine]
        F[farmer<br/>Permission Dashboard]
        B[barn<br/>Tool Registry]
        M[mill<br/>Export Engine]
    end
    
    subgraph "Analysis Tools"
        S[silo<br/>Claim Explorer]
        H[harvest<br/>Analytics]
        O[orchard<br/>Sprint Manager]
    end
    
    G --> W
    G --> F
    G --> B
    G --> M
    G --> S
    G --> H
    G --> O
    
    W --> B
    M --> S
    H --> S
```

### Meta Package Structure

| Path | Purpose |
|------|---------|
| `bin/grainulation.js` | CLI entrypoint — routes to individual tools |
| `lib/router.js` | Command routing to the correct tool package |
| `lib/ecosystem.js` | Ecosystem health checks and tool discovery |
| `lib/doctor.js` | Diagnostic tool — validates tool installations |
| `lib/setup.js` | First-run setup and configuration |
| `lib/pm.js` | Package management for grainulation tools |
| `lib/server.mjs` | Local server — unified ecosystem dashboard (ESM) |
| `public/` | Web UI — ecosystem overview and status |
| `site/` | Public website (grainulation.com) |

资料来源：[CONTRIBUTING.md:25-36]()

## The Eight Tools

| Tool | Purpose | Install Command |
|------|---------|-----------------|
| **wheat** | Research engine. Grow structured evidence. | `npx @grainulation/wheat init` |
| **farmer** | Permission dashboard. Approve AI agent tool calls. | `npx @grainulation/farmer start` |
| **barn** | Tool registry. Curated, versioned, approved. | `npx @grainulation/barn status` |
| **mill** | Export engine. Turn compiled research into PDFs, CSVs, static sites. | `npx @grainulation/mill export --format pdf` |
| **silo** | Claim explorer. Navigate and filter claims across sprints. | `npx @grainulation/silo explore` |
| **harvest** | Analytics. Track prediction accuracy, find systemic blind spots. | `npx @grainulation/harvest analyze ./sprints/` |
| **orchard** | Sprint manager. Coordinate team research across sprints. | `npx @grainulation/orchard status` |
| **grainulation** | Unified CLI. Routes to the right tool, checks ecosystem health. | `npx @grainulation/grainulation` |

资料来源：[site/index.html:1-60]()

## Claims System

Everything in grainulation starts with a **claim** — a single typed statement with an evidence grade.

### Claim Types

| Type | Description |
|------|-------------|
| `factual` | Verifiable fact with supporting evidence |
| `risk` | Potential problem or threat |
| `estimate` | Quantified prediction with uncertainty |
| `constraint` | Hard limitation or requirement |
| `recommendation` | Suggested course of action |

### Evidence Tiers

Evidence tiers range from "someone said it" to "measured in production," providing a spectrum of confidence in claims.

The compiler validates claims, catching contradictions, flagging weak evidence, and blocking output until issues are resolved. This compiler is JavaScript code, not an LLM call — same claims in, same result out every time. 资料来源：[site/index.html:75-95]()

## Research Workflow

The typical workflow follows three phases:

```mermaid
graph LR
    A[Init Sprint<br/>wheat init] --> B[Research<br/>Gather evidence]
    B --> C[Challenge<br/>Stress-test claims]
    C --> D[Compile<br/>Resolve conflicts]
    D --> E[Decision Brief<br/>Ship with audit trail]
```

### Phase 1: Initialize

```bash
npx @grainulation/wheat init
```

Creates a claims file and config:

- `claims.json` — stores all claims (0 claims initially)
- `wheat.config.json` — sprint configuration

### Phase 2: Research and Challenge

- `/research "topic"` — Gather evidence and create claims
- `/challenge r001` — Stress-test existing claims, finding risks and contradictions

Example output:

```
r001 [factual|documented] ...
x001 [risk|documented] ...
```

### Phase 3: Compile and Ship

```bash
wheat> /brief
```

The compiler resolves conflicts, checks evidence, and produces a decision brief:

```
Compiled 12 claims (2 conflicts resolved)
Written: output/brief.html
```

资料来源：[site/index.html:55-90]()

## Design Principles

Four principles underpin the entire ecosystem:

### 1. Evidence Over Authority

Grainulation does not care who made a claim — it cares about the evidence behind it. The system validates claims based on supporting documentation, not seniority.

### 2. Confrontation by Default

Consensus is the enemy of good decisions. The system forces you to challenge, witness, and stress-test every claim through the adversarial challenge mechanism.

### 3. Zero Dependencies

Node.js built-ins only. Zero npm dependencies across all eight packages. No supply chain anxiety. No left-pad incidents. No API keys for the core tools. Every tool ships what it needs and nothing more. 资料来源：[CONTRIBUTING.md:8-10]()

### 4. Local-First

Everything runs locally. Everything is plain JSON and HTML. No cloud services required for core functionality.

## Requirements

To use grainulation, you need:

- **Claude Code** — for AI-assisted research and challenge
- **Node.js 20+** — runtime environment
- **npx** — package executor

No accounts, no cloud services, no API keys for the core tools. 资料来源：[site/index.html:95-100]()

## Comparison with Traditional Methods

| Aspect | RFC/ADR | ChatGPT | Grainulation |
|--------|---------|---------|--------------|
| Timing | Post-decision documentation | Instant but unvalidated | Pre-decision research |
| Evidence | Often absent | Cannot verify | Typed and graded |
| Challenge | Optional review | No mechanism | Built-in adversarial testing |
| Reproducibility | Varies | Non-deterministic | Deterministic compiler |
| Audit trail | Manual | None | Git-tracked claims history |

RFCs and ADRs document a decision after it is made. Grainulation captures the research process — evidence gathering, adversarial testing, and conflict resolution — and validates it through a compiler. The output brief can serve as your ADR, with a full git audit trail showing how every claim was collected, challenged, and resolved. 资料来源：[site/index.html:130-145]()

## Release Process

Packages publish via GitHub Actions workflows on tag push. The workflow runs tests, verifies the tag matches `package.json.version`, and publishes with npm provenance via OIDC trusted publishing.

For coordinated releases where a consumer depends on new internal-dep features:

1. Publish the dependency package first (e.g., `barn`)
2. Wait for the package to appear on npm (~60s)
3. Run `npm install` in consumer repos to regenerate `package-lock.json`
4. Bump consumer versions and push tags

资料来源：[RELEASE.md:1-35]()

## Getting Started

Install the meta-package globally:

```bash
npm install -g @grainulation/grainulation
```

Or start a research sprint directly:

```bash
npx @grainulation/wheat init
```

Useful commands:

| Command | Description |
|---------|-------------|
| `grainulation` | Ecosystem overview |
| `grainulation doctor` | Health check: which tools, which versions |
| `grainulation setup` | Install the right tools for your role |
| `grainulation wheat init` | Delegate to any tool |
| `grainulation farmer start` | Start permission dashboard |

资料来源：[README.md:30-45]()

---

<a id='cli-architecture'></a>

## CLI Architecture

### 相关页面

相关主题：[Command Reference](#command-reference), [Tool Integration](#tool-integration), [Server and Routing](#server-routing)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [bin/grainulation.js](https://github.com/grainulation/grainulation/blob/main/bin/grainulation.js)
- [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js)
- [lib/server.mjs](https://github.com/grainulation/grainulation/blob/main/lib/server.mjs)
- [lib/ecosystem.js](https://github.com/grainulation/grainulation/blob/main/lib/ecosystem.js)
- [lib/doctor.js](https://github.com/grainulation/grainulation/blob/main/lib/doctor.js)
- [lib/setup.js](https://github.com/grainulation/grainulation/blob/main/lib/setup.js)
- [lib/pm.js](https://github.com/grainulation/grainulation/blob/main/lib/pm.js)
</details>

# CLI Architecture

## Overview

The Grainulation CLI is the unified entry point for the entire ecosystem of eight zero-dependency CLI tools. It serves as a meta-package and ecosystem router that orchestrates all grainulation tools through a single command interface. The CLI has zero npm dependencies and relies exclusively on Node.js built-in modules, running entirely locally without cloud services or API keys.

The architectural philosophy follows a modular pattern where the main CLI delegates to specialized modules responsible for routing, ecosystem health, diagnostics, configuration, and package management. This separation of concerns allows each component to be focused and testable while maintaining a cohesive user experience.

## Architecture Components

The CLI system consists of several interconnected modules that work together to provide a seamless interface for tool discovery, command routing, and ecosystem management.

| Component | File | Responsibility |
|-----------|------|----------------|
| CLI Entrypoint | `bin/grainulation.js` | Main entry point, argument parsing, command dispatch |
| Router | `lib/router.js` | Routes commands to correct tool packages |
| Ecosystem | `lib/ecosystem.js` | Health checks and tool discovery |
| Doctor | `lib/doctor.js` | Diagnostic validation for tool installations |
| Setup | `lib/setup.js` | First-run setup and configuration |
| Package Manager | `lib/pm.js` | Package management for grainulation tools |
| Server | `lib/server.mjs` | Local dashboard server (ESM module) |

## Entry Point

The CLI entry point at `bin/grainulation.js` serves as the main entry point for the unified command-line interface. It handles initial argument parsing and dispatches commands to the appropriate handlers. Users interact with the system by running `node bin/grainulation.js --help` or directly invoking the CLI.

The entry point is designed to have zero external dependencies, leveraging only Node.js built-in modules such as `fs`, `path`, and `process`. This ensures maximum portability and minimal attack surface.

## Command Routing

The router module (`lib/router.js`) is responsible for directing incoming commands to the correct tool package within the ecosystem. When a user invokes a command, the router analyzes the arguments and determines which tool should handle the request.

The routing mechanism supports multiple tool packages in the ecosystem:

- **wheat** - Research and claims management
- **farmer** - Permission dashboard
- **barn** - Shared utilities and sprint detection
- **mill** - Export and publishing
- **silo** - Data management
- **harvest** - Analytics and cross-sprint learning
- **orchard** - Package management and status

```mermaid
graph TD
    A[User Input] --> B[bin/grainulation.js]
    B --> C[lib/router.js]
    C --> D{Command Type}
    D -->|Tool Command| E[wheat]
    D -->|Tool Command| F[farmer]
    D -->|Tool Command| G[barn]
    D -->|Tool Command| H[mill]
    D -->|Tool Command| I[silo]
    D -->|Tool Command| J[harvest]
    D -->|Tool Command| K[orchard]
    D -->|Meta Command| L[lib/ecosystem.js]
    D -->|Diagnostic| M[lib/doctor.js]
```

The router maintains awareness of available tools and their capabilities, enabling dynamic command resolution based on what tools are currently installed in the ecosystem.

## Ecosystem Management

### Health Checks and Tool Discovery

The ecosystem module (`lib/ecosystem.js`) provides two critical functions: health checks and tool discovery. Health checks verify that all installed tools are functioning correctly and meet minimum version requirements. Tool discovery scans the ecosystem to identify all installed grainulation packages and their current states.

When invoked, the ecosystem module performs a comprehensive scan of installed tools, checking:

- Package installation status
- Version compatibility
- Dependency integrity
- Configuration validity

### Diagnostic Validation

The doctor module (`lib/doctor.js`) acts as a diagnostic tool that validates tool installations across the ecosystem. It performs thorough checks to ensure each tool is properly installed and configured, identifying issues that might prevent tools from functioning correctly.

The diagnostic process includes validation of:

- File system permissions
- Configuration file integrity
- Required Node.js modules availability
- Inter-tool communication channels

## Configuration and Setup

### First-Run Setup

The setup module (`lib/setup.js`) handles first-run initialization for new users. When a user runs the CLI for the first time, setup creates necessary configuration files and establishes the directory structure required for the ecosystem to function properly.

Setup operations include:

- Creating configuration directories
- Generating default configuration files
- Initializing tool registry
- Establishing user preferences

### Package Management

The package manager module (`lib/pm.js`) provides package management functionality for grainulation tools. It handles installation, updates, and removal of tools within the ecosystem, ensuring consistent package states across the development environment.

## Local Dashboard Server

The server module (`lib/server.mjs`) provides a local web dashboard for ecosystem management. Implemented as an ESM module, it serves a unified ecosystem dashboard that displays:

- Tool status overview
- Installation health
- Configuration management interface
- Real-time ecosystem metrics

The dashboard is accessible locally and provides a visual interface for monitoring and managing the grainulation ecosystem without requiring a web browser connection to external services.

## Data Flow

The following diagram illustrates the complete data flow from user input through command processing to output generation:

```mermaid
sequenceDiagram
    participant User
    participant CLI as bin/grainulation.js
    participant Router as lib/router.js
    participant Ecosystem as lib/ecosystem.js
    participant Doctor as lib/doctor.js
    participant PM as lib/pm.js
    participant Tool as Individual Tool

    User->>CLI: Execute command
    CLI->>CLI: Parse arguments
    CLI->>Router: Route request
    Router->>Router: Identify target tool/command
    
    alt Meta Command
        Router->>Ecosystem: Check ecosystem health
        Ecosystem-->>User: Status report
    end
    
    alt Diagnostic Command
        Router->>Doctor: Run diagnostics
        Doctor-->>User: Diagnostic report
    end
    
    alt Package Management
        Router->>PM: Handle package operation
        PM-->>User: Operation result
    end
    
    alt Tool Command
        Router->>Tool: Delegate to tool
        Tool-->>User: Tool output
    end
```

## Command Categories

The CLI supports four primary command categories:

| Category | Handler | Purpose |
|----------|---------|---------|
| Tool Commands | Individual packages | Execute tool-specific operations |
| Meta Commands | Built-in modules | Ecosystem-level operations |
| Diagnostic Commands | `lib/doctor.js` | Validate installations |
| Management Commands | `lib/pm.js` | Install, update, remove packages |

## Quick Start

Users can get started with the grainulation CLI by cloning the repository and running the help command:

```bash
git clone https://github.com/grainulation/grainulation.git
cd grainulation
node bin/grainulation.js --help
```

No `npm install` step is required since the CLI has zero dependencies and relies solely on Node.js built-in modules.

## Architecture Principles

The CLI architecture adheres to several key principles that guide its design and implementation:

**Zero Dependencies** - Every module uses only Node.js built-in modules, eliminating supply chain vulnerabilities and ensuring the CLI works immediately after cloning without any installation steps.

**Modular Routing** - Commands are routed through a centralized router that delegates to specialized modules, maintaining clear separation of concerns.

**Local-First** - All operations run locally without requiring network connectivity or external services, ensuring data privacy and offline capability.

**Tool Discovery** - The ecosystem module dynamically discovers available tools, allowing the CLI to adapt to different tool configurations without hardcoding.

**Diagnostic Visibility** - Built-in diagnostic tools help users identify and resolve issues without external debugging tools.

---

<a id='command-reference'></a>

## Command Reference

### 相关页面

相关主题：[Health Checks and Diagnostics](#health-checks), [Setup and Installation](#setup-installation), [Ecosystem Overview](#ecosystem-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [bin/grainulation.js](https://github.com/grainulation/grainulation/blob/main/bin/grainulation.js)
- [lib/ecosystem.js](https://github.com/grainulation/grainulation/blob/main/lib/ecosystem.js)
- [lib/doctor.js](https://github.com/grainulation/grainulation/blob/main/lib/doctor.js)
- [lib/setup.js](https://github.com/grainulation/grainulation/blob/main/lib/setup.js)
- [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js)
- [lib/pm.js](https://github.com/grainulation/grainulation/blob/main/lib/pm.js)
</details>

# Command Reference

This page documents the command-line interface (CLI) for the Grainulation ecosystem, covering the unified CLI entrypoint, routing mechanisms, ecosystem management, and diagnostic tools.

## Overview

The Grainulation CLI provides a unified interface for managing the entire ecosystem of eight research tools. The command system is designed with zero npm dependencies, relying exclusively on Node.js built-in modules. 资料来源：[bin/grainulation.js]()

The architecture follows a router-based pattern where commands are dispatched to appropriate handlers based on the first argument passed to the CLI. 资料来源：[lib/router.js]()

```mermaid
graph TD
    A[User Input] --> B[bin/grainulation.js]
    B --> C[Command Router]
    C --> D{Command Type}
    D -->|doctor| E[lib/doctor.js]
    D -->|setup| F[lib/setup.js]
    D -->|ecosystem| G[lib/ecosystem.js]
    D -->|pm| H[lib/pm.js]
    D -->|wheat| I[Delegate to wheat package]
    D -->|farmer| J[Delegate to farmer package]
    D -->|Unknown| K[Help / Error]
```

## CLI Entry Point

### bin/grainulation.js

The main CLI entrypoint that handles all user input and routes commands to appropriate handlers. 资料来源：[bin/grainulation.js]()

**Usage:**

```bash
grainulation [command] [options]
```

**Global Options:**

| Option | Description |
|--------|-------------|
| `--help` | Display help information |
| `--version` | Display CLI version |
| `--json` | Output results as JSON |

### Commands Summary

| Command | Description | Handler |
|---------|-------------|---------|
| `doctor` | Validate tool installations | lib/doctor.js |
| `setup` | First-run setup and configuration | lib/setup.js |
| `ecosystem` | Ecosystem health checks and tool discovery | lib/ecosystem.js |
| `pm` | Package management for grainulation tools | lib/pm.js |
| `wheat` | Delegate to wheat package | External package |
| `farmer` | Delegate to farmer package | External package |

## Command Handlers

### doctor

The diagnostic tool validates tool installations across the ecosystem. It checks which tools are installed, their versions, and reports any issues with the setup. 资料来源：[lib/doctor.js]()

**Usage:**

```bash
grainulation doctor [options]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--verbose` | Show detailed diagnostic information |
| `--fix` | Attempt to fix detected issues automatically |

**Output Example:**

```
Checking grainulation tools...
✓ wheat v1.2.0 installed
✓ farmer v1.1.0 installed
✗ silo not found
⚠ mill v1.0.0 has known compatibility issues

Run 'grainulation setup' to install missing tools
```

### setup

Handles first-run setup and configuration of the Grainulation ecosystem. This command ensures all required tools are installed and configured correctly. 资料来源：[lib/setup.js]()

**Usage:**

```bash
grainulation setup [options]
```

**Options:**

| Option | Description |
|--------|-------------|
| `--install` | Install all recommended tools |
| `--tools <list>` | Install specific tools (comma-separated) |
| `--skip-validation` | Skip post-install validation |

**Workflow:**

```mermaid
graph LR
    A[Run Setup] --> B{Check Node.js Version}
    B -->|≥20| C{Check Existing Tools}
    C -->|Missing| D[Download Tools]
    D --> E[Validate Installation]
    E --> F[Create Config Files]
    F --> G[Setup Complete]
    B -->|<20| H[Error: Node.js 20+ Required]
```

### ecosystem

Provides ecosystem health checks and tool discovery functionality. This command scans for installed tools and reports their status. 资料来源：[lib/ecosystem.js]()

**Usage:**

```bash
grainulation ecosystem [command]
```

**Subcommands:**

| Subcommand | Description |
|------------|-------------|
| `status` | Show status of all ecosystem tools |
| `discover` | Scan for available tools |
| `health` | Run comprehensive health check |

**Status Output Format:**

```json
{
  "tools": [
    { "name": "wheat", "status": "installed", "version": "1.2.0" },
    { "name": "farmer", "status": "installed", "version": "1.1.0" },
    { "name": "silo", "status": "not_found", "version": null }
  ],
  "overall": "degraded"
}
```

### pm (Package Manager)

Handles package management operations for grainulation tools. Supports installation, removal, and updating of tools. 资料来源：[lib/pm.js]()

**Usage:**

```bash
grainulation pm <action> [package]
```

**Actions:**

| Action | Description |
|--------|-------------|
| `install` | Install a package |
| `remove` | Remove a package |
| `update` | Update a package to latest |
| `list` | List installed packages |

**Examples:**

```bash
grainulation pm install wheat
grainulation pm remove silo
grainulation pm update harvest
grainulation pm list
```

### Tool Delegation

For commands not recognized by the core CLI, the router delegates to individual tool packages. This allows direct invocation via `npx @grainulation/<tool-name>`. 资料来源：[lib/router.js]()

**Delegated Tools:**

| Tool | Purpose | Package |
|------|---------|---------|
| wheat | Research engine | @grainulation/wheat |
| farmer | Permission dashboard | @grainulation/farmer |
| barn | Claims backend | @grainulation/barn |
| mill | Export and publish | @grainulation/mill |
| silo | Evidence library | @grainulation/silo |
| harvest | Analytics | @grainulation/harvest |
| orchard | Orchestration | @grainulation/orchard |

## Routing Architecture

The command router (`lib/router.js`) implements a priority-based matching system to determine which handler should process each command. 资料来源：[lib/router.js]()

```mermaid
graph TD
    A[Parse CLI Arguments] --> B{Is Built-in Command?}
    B -->|Yes| C[Route to Handler]
    B -->|No| D{Is Tool Command?}
    D -->|Yes| E[Delegate to Tool Package]
    D -->|No| F{Is Global Flag?}
    F -->|--help| G[Display Help]
    F -->|--version| H[Display Version]
    F -->|Else| I[Error: Unknown Command]
```

### Route Priority

1. Built-in commands (doctor, setup, ecosystem, pm)
2. Tool delegation (wheat, farmer, barn, mill, silo, harvest, orchard)
3. Global flags (--help, --version)
4. Error handling for unknown commands

## Error Handling

The CLI implements consistent error handling across all commands:

| Error Type | Exit Code | Message Format |
|------------|-----------|----------------|
| Command not found | 1 | `Unknown command: <command>` |
| Invalid arguments | 2 | `Invalid argument: <argument>` |
| Tool not installed | 3 | `Tool not installed: <tool>` |
| Node.js version error | 4 | `Node.js 20+ required` |
| Network error | 5 | `Failed to reach npm registry` |

## Configuration

The CLI reads configuration from `~/.grainulation/` directory:

| File | Purpose |
|------|---------|
| `config.json` | Global settings |
| `installed.json` | List of installed tools |
| `cache/` | Temporary cache files |

## Quick Reference

```bash
# Display help
grainulation --help

# Check ecosystem health
grainulation doctor --verbose

# Setup new environment
grainulation setup --install

# View ecosystem status
grainulation ecosystem status

# Manage packages
grainulation pm list
grainulation pm install wheat

# Direct tool usage
npx @grainulation/wheat init
npx @grainulation/farmer start

---

<a id='ecosystem-overview'></a>

## Ecosystem Overview

### 相关页面

相关主题：[Tool Integration](#tool-integration), [Project Overview](#project-overview), [Command Reference](#command-reference)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/ecosystem.js](https://github.com/grainulation/grainulation/blob/main/lib/ecosystem.js)
- [bin/grainulation.js](https://github.com/grainulation/grainulation/blob/main/bin/grainulation.js)
- [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js)
- [lib/doctor.js](https://github.com/grainulation/grainulation/blob/main/lib/doctor.js)
- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)
- [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)
</details>

# Ecosystem Overview

## Introduction

Grainulation is a meta-package and ecosystem router that orchestrates eight independent CLI tools for structured technical research and decision-making. The ecosystem follows a "microkernel" architecture where the core `grainulation` package provides unified CLI access, routing, and health monitoring while each specialized tool operates as an independent package with zero npm dependencies.

The core philosophy centers on turning technical questions into typed, evidence-graded claims that can be compiled into auditable decision briefs. Each tool addresses a specific phase of the research workflow: initialization, evidence gathering, challenge, storage, export, archival, analysis, and system orchestration.

## Architecture

### Core Components

The grainulation ecosystem architecture consists of several interconnected layers that enable tool discovery, routing, and health management.

```mermaid
graph TD
    A[CLI Entry Point<br/>bin/grainulation.js] --> B[Router<br/>lib/router.js]
    B --> C[Tool Packages<br/>wheat, farmer, barn, mill, silo, harvest, orchard]
    A --> D[Ecosystem Health<br/>lib/ecosystem.js]
    A --> E[Doctor<br/>lib/doctor.js]
    A --> F[Setup<br/>lib/setup.js]
    A --> G[Package Manager<br/>lib/pm.js]
    D --> H[Local Server<br/>lib/server.mjs]
    H --> I[Web UI<br/>public/]
    C --> D
```

### Directory Structure

| Path | Purpose | Description |
|------|---------|-------------|
| `bin/grainulation.js` | CLI entrypoint | Routes commands to individual tools |
| `lib/router.js` | Command routing | Dispatches to correct tool package |
| `lib/ecosystem.js` | Health checks | Tool discovery and version verification |
| `lib/doctor.js` | Diagnostics | Validates tool installations |
| `lib/setup.js` | Configuration | First-run setup and initialization |
| `lib/pm.js` | Package management | Manages grainulation tool installations |
| `lib/server.mjs` | Local server | Unified ecosystem dashboard (ESM) |
| `public/` | Web UI | Static assets for dashboard |
| `test/` | Test suite | Node built-in test runner |

资料来源：[CONTRIBUTING.md:1-50](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

## The Eight Tools

### Tool Overview

| Tool | Package | Function | Install Command |
|------|---------|----------|-----------------|
| wheat | `@grainulation/wheat` | Research engine for growing structured evidence | `npx @grainulation/wheat init` |
| farmer | `@grainulation/farmer` | Permission dashboard for AI agent approvals | `npx @grainulation/farmer start` |
| barn | `@grainulation/barn` | Knowledge base for shared evidence and claims | `npx @grainulation/barn sync` |
| mill | `@grainulation/mill` | Export and publish to PDFs, CSVs, static sites | `npx @grainulation/mill export --format pdf` |
| silo | `@grainulation/silo` | Archive and search historical sprints | `npx @grainulation/silo search` |
| harvest | `@grainulation/harvest` | Analytics for cross-sprint learning | `npx @grainulation/harvest analyze ./sprints/` |
| orchard | `@grainulation/orchard` | Unified CLI status and health monitoring | `npx @grainulation/orchard status` |
| grainulation | `@grainulation/grainulation` | Meta-package orchestrating all tools | `npx @grainulation/grainulation` |

### Tool Interactions

```mermaid
graph LR
    W[wheat] --> B[barn]
    F[farmer] --> B
    W --> H[harvest]
    S[silo] --> H
    B --> M[mill]
    W --> S
    O[orchard] --> All
```

Each tool follows the zero-dependency principle: built entirely on Node.js built-ins, ships what it needs, and nothing more.

## Key Modules

### CLI Entry Point

The `bin/grainulation.js` file serves as the unified command-line interface that delegates to individual tools based on user input.

```javascript
// Entry point routes to individual tools
// Usage: grainulation <command> [args]
```

资料来源：[CONTRIBUTING.md:27](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

### Ecosystem Health Checks

The `lib/ecosystem.js` module performs health checks across the entire tool ecosystem, verifying tool availability and version consistency.

**Key Functions:**

| Function | Purpose |
|----------|---------|
| `checkToolHealth()` | Verifies all installed tools are operational |
| `getVersionMatrix()` | Returns version info for all packages |
| `validateToolchain()` | Ensures tool dependencies are satisfied |

### Router

The `lib/router.js` module handles command dispatching to the appropriate tool based on subcommand parsing.

```mermaid
graph TD
    A[User Command] --> B[Parse Command]
    B --> C{Is Global Command?}
    C -->|Yes| D[Run Ecosystem Command<br/>doctor/setup/health]
    C -->|No| E{Local Tool Command?}
    E -->|Yes| F[Route to Tool Package]
    E -->|No| G[Show Help]
```

### Doctor Module

The `lib/doctor.js` diagnostic tool validates tool installations and identifies issues with the local setup.

资料来源：[CONTRIBUTING.md:25](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

## Tool Discovery

The ecosystem uses npm package discovery to find installed tools. Each tool follows the naming convention `@grainulation/<toolname>` and is installed on-demand when first accessed via npx.

### Discovery Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI as bin/grainulation.js
    participant Router as lib/router.js
    participant NPM as npm registry
    participant Tool as @grainulation/tool

    User->>CLI: grainulation wheat init
    CLI->>Router: route(wheat, [init])
    Router->>Tool: npx @grainulation/wheat init
    Tool-->>User: Execute command
```

## Configuration Management

### Setup Flow

The first-run setup process (`lib/setup.js`) performs initial configuration:

1. Detects installed Node.js version
2. Verifies npx availability
3. Creates user configuration directory
4. Initializes default settings for each tool

### Configuration Files

| File | Location | Purpose |
|------|----------|---------|
| `wheat.config.json` | Sprint directory | Research configuration |
| `claims.json` | Sprint directory | Evidence and claims storage |
| `.grainulationrc` | User home | Global preferences |

## Publishing and Releases

### Release Architecture

The entire ecosystem uses a coordinated release process documented in `RELEASE.md`.

```mermaid
graph LR
    A[Tag v.x.y.z] --> B[Workflow Trigger]
    B --> C[Run Tests]
    C --> D[Verify Version]
    D --> E[Publish npm<br/>via OIDC]
    E --> F[Update npmjs.com]
```

### Publishing Workflow

Each package publishes via `.github/workflows/publish.yml` on tag push. The workflow:

1. Runs tests
2. Verifies tag matches `package.json.version`
3. Publishes with npm provenance via OIDC trusted publishing
4. No `NPM_TOKEN` secret required after initial setup

资料来源：[RELEASE.md:1-30](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)

### Single-Package Release

```bash
cd <repo>
npm version patch
git push origin main --follow-tags
```

### Coordinated Release

For consumer packages depending on new internal features:

1. Publish the dependency package first (e.g., `barn`)
2. Wait for npm publication (~60 seconds)
3. Run `npm install` in each consumer repo
4. Commit lockfile updates
5. Publish each consumer with version bump

资料来源：[RELEASE.md:15-35](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)

## Web Dashboard

The `lib/server.mjs` module provides a local web server for the ecosystem dashboard, serving the web UI from the `public/` directory.

### Dashboard Features

- Real-time ecosystem health status
- Tool version matrix
- Quick action buttons for common operations
- Configuration overview

## Testing

The ecosystem uses Node's built-in test runner with tests located in `test/basic.test.js`.

```bash
node test/basic.test.js
```

This runs without additional dependencies, consistent with the zero-dependency philosophy.

## Quick Reference Commands

| Command | Description |
|---------|-------------|
| `grainulation` | Ecosystem overview |
| `grainulation doctor` | Health check for all tools |
| `grainulation setup` | Install tools for your role |
| `grainulation wheat init` | Initialize research sprint |
| `grainulation orchard status` | Check ecosystem status |

## Design Principles

The ecosystem is built on four core principles:

1. **Zero Dependencies**: Every tool ships with only Node.js built-ins, eliminating supply chain risk
2. **Language Agnostic**: Research can cover any technology stack or domain
3. **Local-First**: All processing occurs locally; no cloud services or API keys required for core tools
4. **Auditable**: Every claim, challenge, and resolution maintains a git audit trail

---

<a id='tool-integration'></a>

## Tool Integration

### 相关页面

相关主题：[Ecosystem Overview](#ecosystem-overview), [CLI Architecture](#cli-architecture), [Extensibility Guide](#extensibility-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [bin/grainulation.js](https://github.com/grainulation/grainulation/blob/main/bin/grainulation.js) - CLI entrypoint
- [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js) - Command routing
- [lib/pm.js](https://github.com/grainulation/grainulation/blob/main/lib/pm.js) - Package management
- [lib/ecosystem.js](https://github.com/grainulation/grainulation/blob/main/lib/ecosystem.js) - Ecosystem health checks
- [lib/doctor.js](https://github.com/grainulation/grainulation/blob/main/lib/doctor.js) - Diagnostic tool
- [lib/setup.js](https://github.com/grainulation/grainulation/blob/main/lib/setup.js) - First-run setup
- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md) - Architecture documentation
- [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md) - Release documentation
</details>

# Tool Integration

The Grainulation ecosystem provides a unified CLI architecture that orchestrates eight independent CLI tools through a centralized routing and package management system. This document describes how tools integrate with the ecosystem, how commands flow through the system, and how the unified entrypoint manages tool discovery and execution.

## Architecture Overview

Grainulation follows a meta-package pattern where the `grainulation` tool serves as an ecosystem router. It does not implement tool functionality itself but delegates to individual packages while providing unified health checks, diagnostics, and package management.

```mermaid
graph TD
    User["User"] --> CLI["bin/grainulation.js<br/>CLI Entrypoint"]
    CLI --> Router["lib/router.js<br/>Command Router"]
    Router --> Wheat["@grainulation/wheat"]
    Router --> Farmer["@grainulation/farmer"]
    Router --> Barn["@grainulation/barn"]
    Router --> Mill["@grainulation/mill"]
    Router --> Silo["@grainulation/silo"]
    Router --> Harvest["@grainulation/harvest"]
    Router --> Orchard["@grainulation/orchard"]
    
    CLI --> Ecosystem["lib/ecosystem.js<br/>Health Checks"]
    CLI --> Doctor["lib/doctor.js<br/>Diagnostics"]
    CLI --> PM["lib/pm.js<br/>Package Manager"]
    CLI --> Setup["lib/setup.js<br/>Configuration"]
    
    Ecosystem -.-> Wheat
    Ecosystem -.-> Farmer
    Ecosystem -.-> Barn
```

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L27-L35)

## The Eight Tools

The ecosystem consists of eight independently versioned packages, each with a specific responsibility:

| Tool | Role | Primary Function |
|------|------|------------------|
| **wheat** | Research | Claim collection and challenge workflow |
| **farmer** | Permissions | AI agent tool call approval dashboard |
| **barn** | Shared utilities | Sprint detection, manifest generation, HTML templates |
| **mill** | Export | PDF, CSV, and static site generation |
| **silo** | Storage | Data persistence layer |
| **harvest** | Analytics | Cross-sprint learning and prediction tracking |
| **orchard** | Orchestration | Multi-tool coordination |
| **grainulation** | Unified CLI | Meta-tool routing and ecosystem management |

**资料来源：** [site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html) - Tool card descriptions

## CLI Entry Point

The CLI entrypoint at `bin/grainulation.js` serves as the single entry point for all tool operations. When invoked via `npx @grainulation/grainulation` or `npx grainulation`, this script:

1. Parses command-line arguments
2. Checks for ecosystem health
3. Routes commands to the appropriate tool
4. Handles configuration and setup workflows

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L27-L28)

### Quick Setup

No installation step is required. The tools use zero npm dependencies and run directly:

```bash
git clone https://github.com/grainulation/grainulation.git
cd grainulation
node bin/grainulation.js --help
```

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L12-L16)

## Command Routing

The routing system in `lib/router.js` maps user commands to the correct tool package. The router interprets command arguments and dispatches execution to the appropriate tool's CLI interface.

### Routing Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI as bin/grainulation.js
    participant Router as lib/router.js
    participant Tool as Individual Tool

    User->>CLI: npx @grainulation/grainulation <command>
    CLI->>Router: parseAndRoute(args)
    Router->>Router: identifyTool(command)
    Router->>Tool: delegate(command, args)
    Tool-->>User: Output
```

The router maintains a registry of available tools and their command signatures, enabling dynamic routing without hard-coded dependencies on tool implementations.

**资料来源：** [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js) - Routing implementation

## Package Management

The `lib/pm.js` module handles package management for the grainulation ecosystem. It manages:

- Installation of individual tool packages
- Version resolution across interdependent packages
- Dependency tracking between ecosystem tools

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L33)

### Coordinated Releases

When a tool depends on new features from another tool in the ecosystem, a coordinated release process ensures compatibility:

1. **Publish dependency first** - The upstream tool (e.g., `barn`) publishes its new version
2. **Wait for registry sync** - Allow ~60 seconds for npm to propagate the package
3. **Update consumers** - Run `npm install` in each consumer repository to regenerate `package-lock.json`
4. **Publish consumers** - Tag and publish each dependent package

```bash
# Example: barn new version
cd barn
npm version patch
git push origin main --follow-tags

# Wait 60s, then in each consumer
npm install
git add package-lock.json
npm version patch
git push origin main --follow-tags
```

**资料来源：** [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md#L26-L43)

## Ecosystem Health Checks

The `lib/ecosystem.js` module provides health checks and tool discovery capabilities. It:

- Verifies all tool packages are installed correctly
- Checks version compatibility between tools
- Provides status information for the entire ecosystem

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L30)

## Diagnostic System

The `lib/doctor.js` module validates tool installations and provides diagnostic information:

- Checks Node.js version compatibility
- Validates package integrity
- Reports missing or misconfigured tools

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L31)

## Setup and Configuration

The `lib/setup.js` module handles first-run setup and configuration:

- Creates initial configuration files
- Sets up workspace directories
- Initializes claim storage

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L32)

## Zero Dependencies Architecture

All eight tools in the grainulation ecosystem share a critical design principle: **zero npm dependencies**. Every tool ships only Node.js built-ins and its own code.

```mermaid
graph LR
    subgraph "Traditional Tool"
        T1[Tool Code] --> DEPS[External Dependencies]
        DEPS --> POTENTIAL["Potential Issues:<br/>- Supply chain risk<br/>- Version conflicts<br/>- API changes"]
    end
    
    subgraph "Grainulation Tool"
        G1[Tool Code] --> BUILTIN["Node.js Built-ins Only"]
        BUILTIN --> BENEFITS["Benefits:<br/>- No left-pad incidents<br/>- No supply chain anxiety<br/>- Offline capable"]
    end
```

**资料来源：** [site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html) - Feature descriptions

### Benefits of Zero Dependencies

| Aspect | Impact |
|--------|--------|
| Supply chain security | No third-party code to compromise |
| Reproducibility | Same behavior across all environments |
| Offline capability | Works without network access |
| Maintenance | No dependency update churn |

**资料来源：** [site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html) - "Zero dependencies" feature card

## Publishing Workflow

Each package publishes independently via GitHub Actions using OIDC trusted publishing:

```yaml
# .github/workflows/publish.yml pattern
on:
  push:
    tags:
      - 'v*'
jobs:
  publish:
    steps:
      - uses: actions/checkout@v4
      - run: npm publish --provenance --access public
```

No `NPM_TOKEN` secret is required after initial setup on npmjs.com. The workflow verifies that the tag matches `package.json.version` before publishing.

**资料来源：** [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md#L14-L24)

## Local Server Dashboard

The `lib/server.mjs` module provides a local web server (ESM) that serves as a unified ecosystem dashboard:

- Real-time status of all tools
- Health check visualization
- Ecosystem-wide monitoring

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L35-L36)

## Contributing to Tool Integration

To add a new tool to the ecosystem or modify the integration layer:

1. **Report bugs** - Open an issue with expected vs actual behavior, Node version, and reproduction steps
2. **Suggest features** - Describe the use case: "I need X because Y"
3. **Submit PRs**:
   - Fork the repo and create a branch: `git checkout -b fix/description`
   - Make changes following the existing patterns
   - Run tests: `node test/basic.test.js`
   - Commit with a clear message and open a PR

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L20-L26)

## File Structure Reference

| File | Purpose |
|------|---------|
| `bin/grainulation.js` | CLI entrypoint, routes to individual tools |
| `lib/router.js` | Command routing to the correct tool package |
| `lib/ecosystem.js` | Ecosystem health checks and tool discovery |
| `lib/doctor.js` | Diagnostic tool, validates tool installations |
| `lib/setup.js` | First-run setup and configuration |
| `lib/pm.js` | Package management for grainulation tools |
| `lib/server.mjs` | Local server, unified ecosystem dashboard (ESM) |
| `public/` | Web UI for ecosystem overview and status |
| `site/` | Public website (grainulation.com) |
| `test/` | Node built-in test runner tests |

**资料来源：** [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md#L27-L36)

---

<a id='setup-installation'></a>

## Setup and Installation

### 相关页面

相关主题：[Command Reference](#command-reference), [Health Checks and Diagnostics](#health-checks), [Package Management](#package-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)
- [README.md](https://github.com/grainulation/grainulation/blob/main/README.md)
- [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)
- [bin/grainulation.js](https://github.com/grainulation/grainulation/blob/main/bin/grainulation.js)
- [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js)
</details>

# Setup and Installation

Grainulation is designed with zero external dependencies, meaning no `npm install` is required to get started. The entire ecosystem uses only Node.js built-in modules, eliminating supply chain anxiety and ensuring consistent behavior across environments.

## Prerequisites

Before installing or running Grainulation tools, ensure your environment meets the following requirements:

| Requirement | Version | Notes |
|-------------|---------|-------|
| Node.js | 20+ | Required for all core tools |
| npx | Latest | Bundled with Node.js 20+ |
| Git | Any recent version | For cloning repositories |
| Claude Code | Required | Only needed for research features |

资料来源：[CONTRIBUTING.md:12]()

## Installation Methods

### Quick Start with npx

The fastest way to run any Grainulation tool is through `npx`, which downloads and executes the package on-demand:

```bash
npx @grainulation/wheat init
npx @grainulation/grainulation --help
```

### Local Development Setup

For contributing to the project or modifying the source code:

```bash
git clone https://github.com/grainulation/grainulation.git
cd grainulation
node bin/grainulation.js --help
```

资料来源：[CONTRIBUTING.md:5-9]()

## Project Structure

```
grainulation/
├── bin/
│   └── grainulation.js    # CLI entrypoint - routes to individual tools
├── lib/
│   ├── router.js          # Command routing to the correct tool package
│   ├── ecosystem.js      # Ecosystem health checks and tool discovery
│   ├── doctor.js         # Diagnostic tool - validates tool installations
│   ├── setup.js          # First-run setup and configuration
│   ├── pm.js             # Package management for grainulation tools
│   └── server.mjs        # Local server (ESM)
├── public/               # Web UI - ecosystem overview and status
├── site/                 # Public website (grainulation.com)
└── test/                 # Node built-in test runner tests
```

资料来源：[CONTRIBUTING.md:28-38]()

## CLI Entry Point Architecture

The unified CLI routes commands to the appropriate tool package based on the arguments provided:

```mermaid
graph TD
    A[CLI: node bin/grainulation.js] --> B[lib/router.js]
    B --> C[wheat]
    B --> D[farmer]
    B --> E[barn]
    B --> F[mill]
    B --> G[silo]
    B --> H[harvest]
    B --> I[orchard]
    B --> J[doctor - diagnostics]
```

The router module determines which package should handle each command, enabling the unified CLI experience while keeping each tool independent.

资料来源：[CONTRIBUTING.md:28-29]()

## Tool Ecosystem Overview

Grainulation consists of eight specialized packages plus a meta-package:

| Package | Role | Install Command |
|---------|------|-----------------|
| wheat | Research and claims management | `npx @grainulation/wheat init` |
| farmer | Permission dashboard for AI agents | `npx @grainulation/farmer start` |
| barn | Shared utilities and sprint detection | `npx @grainulation/barn detect-sprints` |
| mill | Export and publish compiled research | `npx @grainulation/mill export --format pdf` |
| silo | Research storage and retrieval | `npx @grainulation/silo` |
| harvest | Analytics and cross-sprint learning | `npx @grainulation/harvest analyze ./sprints/` |
| orchard | Orchestration and workflow management | `npx @grainulation/orchard status` |
| grainulation | Unified CLI meta-tool | `npx @grainulation/grainulation` |

资料来源：[site/index.html:145-165]()

## Zero Dependencies Architecture

All eight packages in the Grainulation ecosystem maintain zero npm dependencies:

```mermaid
graph LR
    A[User Environment] --> B[Node.js Built-ins Only]
    B --> C[No npm packages]
    B --> D[No external APIs]
    C --> E[Zero supply chain risk]
    D --> E
```

This design philosophy ensures:
- No supply chain anxiety
- No "left-pad" incidents
- No API keys required for core tools
- Everything ships what it needs and nothing more

资料来源：[site/index.html:38-40]()

## First-Run Setup

On first execution, the setup module (`lib/setup.js`) handles:

1. Configuration file creation in the user's home directory
2. Ecosystem health verification
3. Tool discovery across all installed packages

Run diagnostics to verify your setup:

```bash
node bin/grainulation.js doctor
```

资料来源：[CONTRIBUTING.md:30]()

## Running Tests

After making changes to the codebase, validate your modifications:

```bash
node test/basic.test.js
```

资料来源：[CONTRIBUTING.md:18]()

## Package Publishing Workflow

For developers releasing updates to the ecosystem, the publishing process uses GitHub Actions with OIDC trusted publishing:

```mermaid
graph LR
    A[npm version patch] --> B[Git push with tags]
    B --> C[GitHub Actions trigger]
    C --> D[Verify tag matches package.json]
    D --> E[Run tests]
    E --> F[Publish via OIDC]
    F --> G[npmjs.com]
```

The workflow handles all eight packages plus the `grainulator` plugin through coordinated releases when dependencies exist between packages.

资料来源：[RELEASE.md:1-30]()

## Verification Checklist

After installation, verify your setup by running these commands:

| Check | Command | Expected Output |
|-------|---------|-----------------|
| CLI accessible | `node bin/grainulation.js --help` | Command routing help |
| Doctor diagnostics | `node bin/grainulation.js doctor` | Health status report |
| Tool discovery | `node bin/grainulation.js ecosystem` | List of installed tools |

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Command not found | Ensure Node.js 20+ is installed |
| Tool routing fails | Run `node bin/grainulation.js doctor` to diagnose |
| npx timeout | Use local clone: `node bin/grainulation.js <command>` |

### Diagnostic Commands

The doctor module validates tool installations and provides troubleshooting guidance:

```bash
node bin/grainulation.js doctor
```

资料来源：[CONTRIBUTING.md:30]()

## Related Documentation

- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md) - Development setup and architecture
- [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md) - Release processes and publishing
- [README.md](https://github.com/grainulation/grainulation/blob/main/README.md) - Project overview and capabilities

---

<a id='health-checks'></a>

## Health Checks and Diagnostics

### 相关页面

相关主题：[Command Reference](#command-reference), [Setup and Installation](#setup-installation), [Package Management](#package-management)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this page:

- [lib/doctor.js](https://github.com/grainulation/grainulation/blob/main/lib/doctor.js)
</details>

# Health Checks and Diagnostics

The **Health Checks and Diagnostics** subsystem in grainulation provides a systematic way to verify the integrity of the ecosystem, validate configurations, and diagnose issues across the eight CLI tools. The `doctor` module serves as the central diagnostic engine that ensures the research workflow operates correctly.

## Overview

grainulation is an ecosystem of eight zero-dependency CLI tools for structured technical research. Given the distributed nature of this architecture—where tools like `wheat`, `silo`, `mill`, `farmer`, `harvest`, `orchard`, `barn`, and the unified `grainulation` CLI must work together—the Health Checks and Diagnostics system provides essential validation and troubleshooting capabilities.

The diagnostic subsystem answers questions like:

- Are all tool configurations valid?
- Is the Node.js environment compatible?
- Are claims files properly formatted?
- Are there conflicts or issues in sprint data?

## Architecture

```mermaid
graph TD
    A[User Command] --> B[grainulation CLI]
    B --> C{doctor.js}
    C --> D[Config Validation]
    C --> E[Tool Health Check]
    C --> F[Claims Validation]
    C --> G[Ecosystem Status]
    D --> H[wheat.config.json]
    E --> I[Individual Tools]
    F --> J[claims.json]
    G --> K[Tool Manifests]
```

### Core Components

| Component | Purpose | File Location |
|-----------|---------|---------------|
| `doctor.js` | Main diagnostic engine | `lib/doctor.js` |
| Config Validator | Validates JSON configurations | Part of doctor module |
| Claims Checker | Validates claim structure | Part of doctor module |
| Ecosystem Scanner | Checks tool availability | Part of doctor module |

## Diagnostic Workflow

When running a health check, the system follows this diagnostic sequence:

```mermaid
graph LR
    A[Init Check] --> B[Environment Scan]
    B --> C[Config Load]
    C --> D[Schema Validation]
    D --> E{Settings Valid?}
    E -->|Yes| F[Tool Check]
    E -->|No| G[Report Errors]
    F --> H{All Tools OK?}
    H -->|Yes| I[Generate Report]
    H -->|No| J[Flag Issues]
```

1. **Initialization Check**: Verifies the command can access necessary Node.js APIs
2. **Environment Scan**: Checks Node.js version compatibility
3. **Configuration Load**: Loads project-level and global configurations
4. **Schema Validation**: Ensures configuration files match expected schemas
5. **Tool Health Check**: Verifies each tool in the ecosystem is accessible
6. **Report Generation**: Produces a diagnostic report with findings

## Configuration Validation

The diagnostic system validates configurations stored in `wheat.config.json` and tool-specific settings.

### Validated Configuration Elements

| Element | Description | Validation |
|---------|-------------|------------|
| `question` | Research question string | Non-empty string |
| `audience` | Target stakeholders | Array of strings |
| `constraints` | Decision constraints | Array of strings |
| `tools` | Enabled tool list | String array |
| `outputFormat` | Brief output format | Enum: html, pdf, md |

Configuration validation uses strict JSON schema checking to ensure data integrity throughout the research sprint.

## Claims Validation

As described in the grainulation philosophy, everything starts with a **claim**—a typed statement with an evidence grade. The diagnostic system validates claims in `claims.json`.

### Claim Structure Validation

```mermaid
graph TD
    A[claims.json] --> B[Parse JSON]
    B --> C[For Each Claim]
    C --> D{ID Present?}
    D -->|No| E[Flag: Missing ID]
    D -->|Yes| F{Type Valid?}
    F -->|No| G[Flag: Invalid Type]
    F -->|Yes| H{Tier Valid?}
    H -->|No| I[Flag: Invalid Tier]
    H -->|Yes| J[Evidence Check]
    J --> K{Evidence Grade OK?}
    K -->|No| L[Flag: Weak Evidence]
    K -->|Yes| M[Next Claim]
```

### Claim Types

| Type | Description |
|------|-------------|
| `factual` | Verifiable fact with evidence |
| `risk` | Identified risk or threat |
| `estimate` | Best-effort estimation |
| `constraint` | Hard constraint on the decision |
| `recommendation` | Suggested action based on evidence |

### Evidence Tiers

| Tier | Level | Description |
|------|-------|-------------|
| 1 | `stated` | Someone said it |
| 2 | `claimed` | External source states it |
| 3 | `documented` | Written documentation exists |
| 4 | `measured` | Measured or observed in practice |

## Ecosystem Health Checks

The diagnostic system performs comprehensive checks across the grainulation ecosystem.

### Tool Availability

Each of the eight tools is checked for availability:

```mermaid
graph TD
    A[Check Tool Availability] --> B[wheat - Research Engine]
    A --> C[silo - Reusable Knowledge]
    A --> D[mill - Export & Publish]
    A --> E[farmer - AI Permissions]
    A --> F[harvest - Analytics]
    A --> G[orchard - Orchestration]
    A --> H[barn - Shared Utilities]
    A --> I[grainulation - Unified CLI]
    B --> J{Installed?}
    J -->|Yes| K[OK]
    J -->|No| L[Missing Warning]
```

### Zero Dependencies Verification

The diagnostic system confirms that tools maintain the zero-dependency promise by verifying no external npm packages are required.

## Diagnostic Output

The health check produces structured output:

```json
{
  "status": "healthy|warning|critical",
  "timestamp": "ISO-8601 timestamp",
  "checks": {
    "environment": { "status": "pass|fail", "details": "..." },
    "config": { "status": "pass|fail", "errors": [] },
    "claims": { "status": "pass|fail", "count": 0, "issues": [] },
    "ecosystem": { "status": "pass|fail", "tools": {} }
  },
  "recommendations": ["suggestion1", "suggestion2"]
}
```

## Running Diagnostics

Health checks can be invoked through the unified CLI:

```bash
# Check overall ecosystem health
npx grainulation doctor

# Check specific sprint health
npx @grainulation/wheat doctor

# Check with verbose output
npx grainulation doctor --verbose
```

## Common Issues and Resolutions

| Issue | Symptom | Resolution |
|-------|---------|------------|
| Invalid JSON config | Parser error | Validate JSON syntax in config files |
| Missing claims | Empty claims array | Run `/research` commands to gather claims |
| Weak evidence | Low-tier claims | Gather more evidence for critical claims |
| Tool not found | Command not recognized | Reinstall via `npx @grainulation/[tool]` |
| Conflict unresolved | Compiler blocks output | Use `/challenge` to resolve claim conflicts |

## Integration with Compiler

The diagnostic system integrates with the compiler to ensure decision briefs are only generated when health checks pass:

```mermaid
graph TD
    A[/brief command] --> B[Run Health Check]
    B --> C{All Checks Pass?}
    C -->|No| D[Block Brief]
    C -->|Yes| E[Compile Claims]
    E --> F{Conflicts Exist?}
    F -->|Yes| G[Flag Conflicts]
    G --> D
    F -->|No| H[Generate Brief]
```

This ensures that decision briefs maintain the integrity guarantees promised by the grainulation philosophy—only well-researched, properly challenged, and conflict-resolved claims make it into the final output.

## Summary

The Health Checks and Diagnostics system is fundamental to grainulation's promise of producing auditable, evidence-based decision briefs. By validating configurations, claims structure, evidence quality, and ecosystem integrity, the diagnostic subsystem ensures that every decision produced by the system meets the rigorous standards required for technical decision-making.

---

<a id='package-management'></a>

## Package Management

### 相关页面

相关主题：[Setup and Installation](#setup-installation), [Health Checks and Diagnostics](#health-checks)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [lib/pm.js](https://github.com/grainulation/grainulation/blob/main/lib/pm.js)
- [package.json](https://github.com/grainulation/grainulation/blob/main/package.json)
- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)
</details>

# Package Management

Grainulation implements a lightweight package management system designed to orchestrate its ecosystem of zero-dependency CLI tools. Rather than relying on external package managers for tool discovery and installation, the system provides `lib/pm.js` as a built-in mechanism for managing the eight core packages that comprise the grainulation ecosystem.

## Overview

The package management module serves two primary functions within the grainulation architecture:

1. **Tool Discovery** — Locates installed grainulation packages within the local environment
2. **Package Installation** — Installs and updates the eight core tools (`wheat`, `farmer`, `barn`, `mill`, `silo`, `harvest`, `orchard`, `grainulation`) plus the `grainulator` plugin

This approach aligns with the project's fundamental philosophy: everything runs locally with minimal external dependencies. The package management layer sits above Node.js built-in modules and does not introduce additional npm packages into the runtime environment.

资料来源：[CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

## Ecosystem Architecture

The grainulation ecosystem consists of eight specialized tools, each responsible for a distinct phase of structured technical research. The package management module serves as the glue layer that enables these tools to work together as a unified system.

```mermaid
graph TD
    subgraph "Grainulation Ecosystem"
        G["grainulation<br/>(meta-package)"]
        PM["lib/pm.js<br/>(Package Manager)"]
        
        G --> PM
    end
    
    subgraph "Core Tools"
        W["wheat<br/>(Research Sprint)"]
        F["farmer<br/>(Permission Dashboard)"]
        B["barn<br/>(Validation)"]
        M["mill<br/>(Export)"]
        S["silo<br/>(Data Storage)"]
        H["harvest<br/>(Analytics)"]
        O["orchard<br/>(Status)"]
    end
    
    subgraph "Plugins"
        GR["grainulator"]
    end
    
    PM --> W
    PM --> F
    PM --> B
    PM --> M
    PM --> S
    PM --> H
    PM --> O
    PM --> GR
    
    W <--> B
    W <--> M
    B <--> S
    H <--> S
    O <--> S
```

资料来源：[CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

## Package Registry

All grainulation packages are published to npm under the `@grainulation` scope. The following table lists the core packages and their primary functions:

| Package | Purpose | Command Prefix |
|---------|---------|----------------|
| `@grainulation/grainulation` | Unified CLI entry point, ecosystem router | `npx grainulation` |
| `@grainulation/wheat` | Research sprint initialization and claims management | `npx @grainulation/wheat` |
| `@grainulation/farmer` | Permission dashboard for AI agent tool calls | `npx @grainulation/farmer` |
| `@grainulation/barn` | Validation engine, evidence grading | `npx @grainulation/barn` |
| `@grainulation/mill` | Export compiled research to PDF, CSV, HTML | `npx @grainulation/mill` |
| `@grainulation/silo` | Local data storage and persistence | `npx @grainulation/silo` |
| `@grainulation/harvest` | Cross-sprint analytics and prediction tracking | `npx @grainulation/harvest` |
| `@grainulation/orchard` | Ecosystem status and health monitoring | `npx @grainulation/orchard` |

The `grainulator` plugin extends the system with additional capabilities and follows the same package naming conventions.

资料来源：[site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html)

## pnpm Configuration

Grainulation uses [pnpm](https://pnpm.io/) as its package manager, with version 10.30.0 specified in the project's `package.json`:

```json
{
  "packageManager": "pnpm@10.30.0"
}
```

### Key Configuration

| Setting | Value | Purpose |
|---------|-------|---------|
| `packageManager` | `pnpm@10.30.0` | Ensures consistent package manager version across contributors |
| `engines.node` | `>=20` | Requires Node.js 20 or higher |
| `publishConfig.access` | `public` | Packages are publicly accessible on npm |

The Node.js version requirement ensures compatibility with modern JavaScript features used throughout the ecosystem, including ES modules and built-in APIs like `node:fs`, `node:path`, and `node:http`.

资料来源：[package.json](https://github.com/grainulation/grainulation/blob/main/package.json)

## Dependency Model

Unlike traditional Node.js projects that accumulate numerous npm dependencies, grainulation maintains a strict zero-dependency policy for the CLI tools themselves. However, the meta-package (`grainulation`) includes one internal dependency to enable routing and ecosystem coordination:

```json
{
  "dependencies": {
    "@grainulation/barn": "^1.3.0"
  }
}
```

### Dependency Philosophy

```
┌─────────────────────────────────────────────────────────────┐
│                    Dependency Philosophy                    │
├─────────────────────────────────────────────────────────────┤
│  CLI Tools (wheat, farmer, etc.)    →  Zero npm deps       │
│  Meta-package (grainulation)        →  Only @grainulation  │
│  All packages                       →  Node.js built-ins  │
└─────────────────────────────────────────────────────────────┘
```

This design provides several benefits:

- **Supply chain security** — No third-party code dependencies reduces attack surface
- **Installation speed** — Minimal package download footprint
- **Reliability** — No dependency on external package availability
- **Auditability** — Complete visibility into tool behavior

资料来源：[site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html)

## Installation Workflow

### Quick Setup

The recommended installation method uses npx, which downloads and executes packages on-demand without requiring a global installation:

```bash
# Clone the repository
git clone https://github.com/grainulation/grainulation.git
cd grainulation

# Run the CLI directly
node bin/grainulation.js --help
```

### Installing Individual Tools

Each tool can be installed independently using npx:

```bash
# Initialize a research sprint
npx @grainulation/wheat init

# Start the permission dashboard
npx @grainulation/farmer start

# Export compiled research
npx @grainulation/mill export --format pdf
```

The package management module (`lib/pm.js`) handles tool discovery and ensures that the correct versions of inter-dependent packages are available.

资料来源：[CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

## Release Workflow

Packages are published through GitHub Actions using OIDC trusted publishing, eliminating the need for npm access tokens after initial setup.

### Release Process

1. **Version bump** — Run `npm version patch` (or `minor`/`major`) in the package directory
2. **Tag creation** — The npm version command creates a git tag (`v<x.y.z>`)
3. **Push with tags** — `git push origin main --follow-tags` triggers the workflow
4. **Automated publish** — GitHub Actions verifies the tag matches `package.json` version and publishes to npm

### Coordinated Releases

When a package update requires changes in dependent packages:

1. Publish the base package (e.g., `barn`) first
2. Wait for npm publication (~60 seconds)
3. Run `npm install` in consumer repositories to update lockfiles
4. Commit the lockfile changes
5. Proceed with dependent package releases

资料来源：[RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)

## CLI Entry Point

The unified CLI is implemented in `bin/grainulation.js`, which serves as the main entry point for the ecosystem:

```mermaid
graph LR
    A["grainulation CLI"] --> B["bin/grainulation.js"]
    B --> C["lib/router.js"]
    B --> D["lib/ecosystem.js"]
    B --> E["lib/doctor.js"]
    B --> F["lib/pm.js"]
    
    C --> G1["wheat"]
    C --> G2["farmer"]
    C --> G3["barn"]
    C --> G4["mill"]
    
    D --> H["Health Checks"]
    E --> I["Diagnostics"]
    F --> J["Package Ops"]
```

The router (`lib/router.js`) delegates commands to the appropriate tool package, while the ecosystem module (`lib/ecosystem.js`) provides health checks and tool discovery capabilities.

资料来源：[CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)

## See Also

- [wheat](../wheat/research-sprint) — Research sprint initialization
- [barn](../barn/validation) — Evidence validation and grading
- [farmer](../farmer/permissions) — Permission dashboard for AI agents
- [mill](../mill/export) — Export and publishing tools

---

<a id='server-routing'></a>

## Server and Routing

### 相关页面

相关主题：[CLI Architecture](#cli-architecture), [Tool Integration](#tool-integration)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [lib/server.mjs](https://github.com/grainulation/grainulation/blob/main/lib/server.mjs)
- [lib/router.js](https://github.com/grainulation/grainulation/blob/main/lib/router.js)
- [bin/grainulation.js](https://github.com/grainulation/grainulation/blob/main/bin/grainulation.js)
- [lib/ecosystem.js](https://github.com/grainulation/grainulation/blob/main/lib/ecosystem.js)
- [lib/doctor.js](https://github.com/grainulation/grainulation/blob/main/lib/doctor.js)
</details>

# Server and Routing

## Overview

The Server and Routing system in Grainulation serves as the foundational infrastructure that handles command dispatch, local development server operations, and ecosystem health management. This system orchestrates the eight independent CLI tools within the ecosystem, providing a unified entry point and centralized coordination layer.

The routing architecture follows a delegation pattern where the main CLI entrypoint (`bin/grainulation.js`) routes incoming commands to the appropriate tool-specific handlers, while the local server (`lib/server.mjs`) provides an ESM-based dashboard for ecosystem monitoring and interaction.

## Architecture

```mermaid
graph TD
    User[User] --> CLI[bin/grainulation.js<br/>CLI Entrypoint]
    CLI --> Router[lib/router.js<br/>Command Router]
    Router --> Wheat[wheat<br/>Research Engine]
    Router --> Farmer[farmer<br/>Permission Dashboard]
    Router --> Mill[mill<br/>Export Tools]
    Router --> Harvest[harvest<br/>Analytics]
    Router --> Silo[silo<br/>Shared Config]
    Router --> Barn[barn<br/>Shared Utilities]
    Router --> Orchard[orchard<br/>Orchestration]
    CLI --> Server[lib/server.mjs<br/>Local Server]
    Server --> Ecosystem[lib/ecosystem.js<br/>Health Checks]
    Server --> Doctor[lib/doctor.js<br/>Diagnostics]
```

## Key Components

### CLI Entrypoint (`bin/grainulation.js`)

The primary command-line interface entrypoint that initializes the routing system and delegates to individual tool packages. This file provides the unified CLI experience for all grainulation tools.

| Aspect | Details |
|--------|---------|
| Type | Main executable script |
| Format | JavaScript (CommonJS) |
| Purpose | Routes to individual tools |
| Dependencies | Zero npm dependencies |

**Usage:**
```bash
node bin/grainulation.js --help
grainulation doctor       # Health check
grainulation setup        # Install tools
grainulation wheat init   # Delegate to wheat
```

### Command Router (`lib/router.js`)

The router module handles command dispatching, parsing incoming arguments and determining which tool package should handle the request. It implements the core routing logic that enables the meta-package approach.

| Aspect | Details |
|--------|---------|
| Type | Module |
| Format | CommonJS (.js) |
| Purpose | Routes commands to correct tool package |
| Integration | Called by bin/grainulation.js |

The router acts as the central switchboard, ensuring commands reach their intended tool while maintaining a consistent interface across the ecosystem.

### Local Server (`lib/server.mjs`)

The local development server implemented as an ESM module, providing a unified ecosystem dashboard. This server runs locally and offers real-time monitoring of the entire grainulation ecosystem.

| Aspect | Details |
|--------|---------|
| Type | HTTP Server |
| Format | ES Module (.mjs) |
| Purpose | Unified ecosystem dashboard |
| Port | Configurable |

**Key Features:**
- Real-time ecosystem health monitoring
- SSE (Server-Sent Events) for live updates
- Zero external dependencies
- Plain JSON and HTML responses

### Ecosystem Health (`lib/ecosystem.js`)

Manages ecosystem-wide health checks and tool discovery. This module maintains awareness of all installed tools and their operational status.

| Function | Description |
|----------|-------------|
| Health checks | Validates tool installations |
| Tool discovery | Finds and catalogs available tools |
| Status reporting | Provides ecosystem overview |

### Diagnostic Tool (`lib/doctor.js`)

A diagnostic utility that validates tool installations and reports configuration issues. It performs pre-flight checks to ensure the ecosystem is properly configured.

**Command:**
```bash
grainulation doctor
```

**Validation Checks:**
- Tool presence verification
- Version compatibility checks
- Configuration file validation

## Command Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI as bin/grainulation.js
    participant Router as lib/router.js
    participant Server as lib/server.mjs
    participant Tool as Individual Tool
    
    User->>CLI: grainulation wheat init
    CLI->>Router: Parse command
    Router->>Tool: Route to wheat
    Tool-->>User: Execute command
    
    User->>CLI: grainulation server start
    CLI->>Server: Start dashboard
    Server->>Server: Initialize ESM server
    Server-->>User: Dashboard available
    
    User->>CLI: grainulation doctor
    CLI->>Router: Parse command
    Router->>Server: Check ecosystem health
    Server-->>Router: Health status
    Router-->>User: Diagnostic report
```

## Server Implementation

The `lib/server.mjs` module follows modern ESM conventions with the following characteristics:

**Module Type:** ECMAScript Modules (ESM)  
**Dependencies:** Node.js built-ins only  
**Transport:** Server-Sent Events (SSE) for real-time updates  
**Response Format:** Plain JSON and HTML

The server operates without external npm dependencies, maintaining the project's zero-dependency philosophy while providing full ecosystem monitoring capabilities.

## Routing Configuration

The routing system supports delegation to eight distinct tools:

| Tool | Command Pattern | Purpose |
|------|-----------------|---------|
| wheat | `grainulation wheat <cmd>` | Research engine |
| farmer | `grainulation farmer start` | Permission dashboard |
| mill | `grainulation mill export` | Export and publish |
| harvest | `grainulation harvest analyze` | Analytics |
| silo | `grainulation silo status` | Shared configuration |
| barn | `grainulation barn detect` | Shared utilities |
| orchard | `grainulation orchard` | Orchestration |
| grainulation | `grainulation <cmd>` | Meta-tool commands |

## Setup and Initialization

First-run setup is handled by `lib/setup.js`, which prepares the environment for tool usage. This includes:

1. Configuration file creation
2. Tool directory initialization
3. Environment validation

**Command:**
```bash
grainulation setup
```

## Health Monitoring

The ecosystem provides continuous health monitoring through:

- **Automatic checks:** Performed on tool access
- **Manual diagnostics:** Via `grainulation doctor`
- **Dashboard view:** Via `lib/server.mjs` dashboard

## Dependencies

The Server and Routing system maintains zero external npm dependencies:

| Module | Node.js Built-ins Used |
|--------|------------------------|
| server.mjs | http, fs, path, events |
| router.js | fs, path, child_process |
| ecosystem.js | fs, path |
| doctor.js | fs, child_process |

## Security

The implementation includes security headers configured in the site's HTML:

```html
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'">
```

This CSP configuration ensures:
- Self-hosted resources only
- Inline scripts for functionality
- No external connections
- Data URIs for embedded images

---

<a id='extensibility-guide'></a>

## Extensibility Guide

### 相关页面

相关主题：[Tool Integration](#tool-integration), [Ecosystem Overview](#ecosystem-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CONTRIBUTING.md](https://github.com/grainulation/grainulation/blob/main/CONTRIBUTING.md)
- [README.md](https://github.com/grainulation/grainulation/blob/main/README.md)
- [package.json](https://github.com/grainulation/grainulation/blob/main/package.json)
- [RELEASE.md](https://github.com/grainulation/grainulation/blob/main/RELEASE.md)
- [site/index.html](https://github.com/grainulation/grainulation/blob/main/site/index.html)
</details>

# Extensibility Guide

## Overview

The grainulation ecosystem is designed as a modular, extensible CLI framework for structured technical research and decision-making. Built with zero npm dependencies, the system follows a hub-and-spoke architecture where the main `grainulation` package serves as the orchestrator and unified entry point for eight specialized tools: `wheat`, `farmer`, `barn`, `mill`, `silo`, `harvest`, `orchard`, and `grainulator`.

The ecosystem architecture enables horizontal scaling of functionality through independently deployable packages while maintaining a consistent user experience through the centralized CLI router. Each tool follows a strict contract: typed claims with evidence grades, compilation logic, and output formats that integrate seamlessly with the broader research workflow.

## Architecture

### Hub-and-Spoke Model

The grainulation ecosystem follows a hub-and-spoke architecture where the core `grainulation` package routes commands to specialized tools. This design allows each tool to remain focused on a single responsibility while benefiting from shared infrastructure.

```
graph TD
    A[User: grainulation command] --> B[bin/grainulation.js]
    B --> C[lib/router.js]
    C --> D[Tool: wheat]
    C --> E[Tool: farmer]
    C --> F[Tool: barn]
    C --> G[Tool: silo]
    C --> H[Tool: mill]
    C --> I[Tool: harvest]
    C --> J[Tool: orchard]
    
    K[lib/ecosystem.js] -.->|health checks| C
    L[lib/doctor.js] -.->|diagnostics| C
    M[lib/pm.js] -.->|package management| C
```

资料来源：[CONTRIBUTING.md:31-46]()

### Directory Structure

The grainulation repository maintains a clean separation between infrastructure code and tool implementations:

| Directory | Purpose | Key Files |
|-----------|---------|-----------|
| `bin/` | CLI entry point | `grainulation.js` - Main executable |
| `lib/` | Core infrastructure | `router.js`, `ecosystem.js`, `doctor.js`, `pm.js`, `setup.js` |
| `public/` | Web UI assets | Ecosystem dashboard |
| `site/` | Public website | Static site for grainulation.com |
| `test/` | Test suite | Node built-in test runner tests |

资料来源：[CONTRIBUTING.md:31-46]()

## Tool Ecosystem

### Available Tools

The eight tools in the grainulation ecosystem form a complete research-to-decision pipeline:

| Tool | Role | Function |
|------|------|----------|
| `wheat` | Research engine | Initiate sprints, research topics, challenge findings |
| `farmer` | Permission dashboard | Approve AI agent tool calls in real-time |
| `barn` | Collaboration | Team-based claim management |
| `mill` | Export | Generate PDFs, CSVs, static sites from compiled research |
| `silo` | Documentation | Document and share decision briefs |
| `harvest` | Analytics | Track prediction accuracy, detect stale claims |
| `orchard` | Status monitoring | Ecosystem health checks and tool discovery |
| `grainulator` | Plugin | Custom extension mechanism |

资料来源：[README.md:59-75]()

### Inter-Tool Communication

Tools communicate through a shared claims data model. Every claim follows a consistent structure with type, evidence grade, and metadata. This standardization enables seamless handoffs between tools:

```
graph LR
    A[wheat: research] -->|claims.json| B[farmer: challenge]
    B -->|updated claims| C[barn: collaborate]
    C -->|merged claims| D[mill: export]
    D -->|compiled brief| E[silo: publish]
    
    F[harvest: analyze] -.->|cross-sprint insights| A
    G[orchard: status] -.->|health reports| A
```

## Extending the Ecosystem

### Adding New Tools

The architecture supports adding new tools through a consistent pattern. Each tool must:

1. Follow the npm package naming convention `@grainulation/<tool-name>`
2. Accept claims in the standardized format
3. Produce output compatible with other tools in the pipeline
4. Implement zero-dependency principles using Node.js built-ins

To add a new tool to the ecosystem:

```bash
# Create new package following grainulation naming conventions
mkdir @grainulation/newtool
cd newtool
npm init
```

The router in `lib/router.js` automatically discovers and routes to new tools based on their npm package naming, enabling plug-and-play extensibility without modifying core infrastructure.

资料来源：[CONTRIBUTING.md:15-30]()

### Package Management Integration

The `lib/pm.js` module handles package management for grainulation tools. When a new tool is installed via npm, the system:

1. Detects the `@grainulation/*` package scope
2. Registers the tool with the local router
3. Updates ecosystem health status
4. Makes the tool available through the unified CLI

```javascript
// lib/pm.js handles tool discovery and registration
// New tools automatically integrate through npm install
```

资料来源：[CONTRIBUTING.md:42]()

### Health Checks and Diagnostics

The ecosystem includes built-in health monitoring through two complementary systems:

| Component | Purpose | Location |
|-----------|---------|----------|
| `orchard` | Tool discovery and status | `orchard.grainulation.com` |
| `doctor` | Diagnostic validation | `lib/doctor.js` |

The `doctor.js` module validates tool installations and reports configuration issues. This enables users to diagnose problems without external dependencies.

资料来源：[CONTRIBUTING.md:41]()

## CLI Extensibility

### Unified Entry Point

The `bin/grainulation.js` file serves as the single entry point for all ecosystem commands. It delegates to specialized tools based on command arguments:

```bash
# Router dispatches to appropriate tool
node bin/grainulation.js <tool-name> <command> [args]
```

The bin entry point is registered in `package.json`:

```json
{
  "bin": {
    "grainulation": "bin/grainulation.js"
  }
}
```

资料来源：[package.json:8-10]()

### Command Routing

The `lib/router.js` module implements intelligent command routing. It:

1. Parses incoming CLI arguments
2. Maps commands to tool packages
3. Handles cross-tool invocations
4. Manages command aliases

### Local Server Extension

The ecosystem includes an ESM server (`lib/server.mjs`) for web-based extensions. This enables:

- Real-time dashboard views
- SSE-based permission workflows
- Browser-based collaboration interfaces

The server maintains zero dependencies, using only Node.js built-in modules for HTTP and streaming functionality.

资料来源：[CONTRIBUTING.md:44]()

## Configuration and Setup

### First-Run Setup

The `lib/setup.js` module handles first-run configuration. When a new tool is invoked for the first time, the system:

1. Creates necessary directory structures
2. Generates default configuration files
3. Establishes claims storage locations
4. Initializes git hooks for audit trail

### Configuration Schema

Each tool follows a consistent configuration pattern. The `wheat` tool demonstrates the standard approach with `wheat.config.json`:

| Setting | Purpose |
|---------|---------|
| `question` | Research question being investigated |
| `audience` | Primary stakeholders for the decision |
| `constraints` | Hard requirements that must be satisfied |
| `claims[]` | Array of typed claims with evidence grades |

## Publishing and Distribution

### Package Publishing Workflow

Tools publish through a standardized GitHub Actions workflow defined in `.github/workflows/publish.yml`. The workflow:

1. Runs tests against the package
2. Verifies version matches git tag
3. Publishes with npm provenance via OIDC
4. Eliminates need for NPM_TOKEN secrets

资料来源：[RELEASE.md:1-18]()

### Publishing Commands

```bash
# Single-package patch release
cd <repo>
npm version patch
git push origin main --follow-tags

# Coordinated release (multiple packages)
# 1. Publish dependency first
cd barn && npm version patch && git push origin main --follow-tags
# 2. Wait for npm to reflect the new version (~60s)
# 3. Update consumers
cd consumer && npm install && git commit -m "Update barn dependency"
npm version patch && git push origin main --follow-tags
```

资料来源：[RELEASE.md:19-32]()

## Best Practices for Extensions

### Zero-Dependency Principle

All grainulation tools must adhere to the zero-dependency principle:

- Use only Node.js built-in modules (`fs`, `path`, `http`, `crypto`, etc.)
- Ship required utilities within the package
- Avoid supply chain vulnerabilities
- Enable offline operation

This principle ensures reliability and security across the entire ecosystem.

### Claim Type System

Extensions should implement the standardized claim type system:

| Type | Description | Example |
|------|-------------|---------|
| `factual` | Verified facts | Performance metrics, API specs |
| `risk` | Potential issues | Security vulnerabilities, failure modes |
| `estimate` | Informed estimates | Resource projections, timeline forecasts |
| `constraint` | Hard requirements | Regulatory compliance, SLA requirements |
| `recommendation` | Suggested actions | Architectural choices, implementation approaches |

Each claim includes an evidence grade from "someone said it" to "measured in production", enabling the compiler to validate and resolve conflicts.

### Audit Trail Integration

All claims should maintain git-based audit trails showing:

- When claims were collected
- How claims were challenged
- Resolution of conflicts
- Final compilation decisions

This enables full traceability of the research process and supports post-decision retrospectives.

## Contributing Extensions

### Development Workflow

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/tool-name`
3. Implement the tool following grainulation conventions
4. Add tests using Node built-in test runner
5. Run existing tests: `node test/basic.test.js`
6. Submit a pull request

### Testing Requirements

The project uses Node's built-in test runner. Tests must:

- Cover core functionality
- Handle error cases gracefully
- Maintain zero external dependencies
- Pass on Node.js 20+

```bash
# Run all tests
node test/basic.test.js
node --test test/tarball.test.mjs
```

### Code Quality

The project uses Biome for linting and formatting:

```bash
# Check code style
npm run lint

# Auto-format code
npm run format
```

资料来源：[CONTRIBUTING.md:15-30]()

## Summary

The grainulation extensibility model provides a robust framework for building specialized research and decision-making tools. By adhering to the hub-and-spoke architecture, zero-dependency principle, and standardized claims format, new tools can seamlessly integrate into the ecosystem while maintaining independence and focus. The modular design enables teams to adopt only the tools they need while preserving the ability to expand functionality as requirements evolve.

---

---

## Doramagic 踩坑日志

项目：grainulation/grainulation

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。

## 1. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1184031176 | https://github.com/grainulation/grainulation | README/documentation is current enough for a first validation pass.

## 2. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1184031176 | https://github.com/grainulation/grainulation | last_activity_observed missing

## 3. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1184031176 | https://github.com/grainulation/grainulation | no_demo; severity=medium

## 4. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1184031176 | https://github.com/grainulation/grainulation | no_demo; severity=medium

## 5. 安全/权限坑 · 来源证据：v1.1.0 — Security Hardening

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v1.1.0 — Security Hardening
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_5e8c2578dd024d369fd769a7c23df98a | https://github.com/grainulation/grainulation/releases/tag/v1.1.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 6. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1184031176 | https://github.com/grainulation/grainulation | issue_or_pr_quality=unknown

## 7. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1184031176 | https://github.com/grainulation/grainulation | release_recency=unknown

<!-- canonical_name: grainulation/grainulation; human_manual_source: deepwiki_human_wiki -->
