internal

package
v1.0.2-sin-code Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

SPDX-License-Identifier: MIT Purpose: adw — Architectural Debt Watchdogs. Detects god modules, circular dependencies, high coupling, long functions, large files, and code smells. Pure Go implementation.

SPDX-License-Identifier: MIT Purpose: Shared utilities for the sin-code unified binary (error printing, shared flags, output formatting). All subcommands import this package.

SPDX-License-Identifier: MIT Purpose: discover — file discovery with relevance scoring, pattern matching, and dependency analysis. Built-in Go implementation (no external binary dependency).

SPDX-License-Identifier: MIT Purpose: efm — Ephemeral Full-Stack Mocking. Manages docker-compose stacks and ephemeral test environments. Pure Go implementation.

SPDX-License-Identifier: MIT Purpose: execute — safe shell command execution with safety checks, secret redaction, timeout handling, and error analysis. Built-in Go implementation.

SPDX-License-Identifier: MIT Purpose: grasp — deep code understanding for a single file. Built-in Go implementation providing structure, dependencies, and usage context.

SPDX-License-Identifier: MIT Purpose: harvest — URL fetching with caching, structure extraction, and change detection. Built-in Go implementation using net/http with local disk cache.

SPDX-License-Identifier: MIT Purpose: ibd — Intent-Based Diffing. Compare two versions of code and determine if the changes match the stated intent. Pure Go implementation.

SPDX-License-Identifier: MIT Purpose: map — architecture mapping with dependency graphs, entry points, hot paths, and module-level analysis. Built-in Go implementation.

SPDX-License-Identifier: MIT Purpose: oracle — Verification Oracle. Compares source files against test files to verify coverage. Pure Go implementation.

SPDX-License-Identifier: MIT Purpose: orchestrate — task management with dependencies, parallel execution plans, blocker detection, and rollback plans. Built-in Go implementation with JSON file storage in ~/.local/state/sin-code/.

SPDX-License-Identifier: MIT Purpose: poc — Proof-of-Correctness. Verifies that code satisfies its specification by comparing code against spec documents (markdown, text, or structured requirements). Pure Go implementation.

SPDX-License-Identifier: MIT Purpose: sckg — Semantic Codebase Knowledge Graphs. Builds a knowledge graph of a codebase: files, functions, imports, and their relationships. Pure Go implementation.

SPDX-License-Identifier: MIT Purpose: scout — code search with regex, semantic, symbol, and usage search. Built-in Go implementation with file walking, context lines, and result ranking.

SPDX-License-Identifier: MIT Purpose: serve — start an MCP (Model Context Protocol) server that exposes all 13 sin-code subcommands as MCP tools. This replaces the 7 separate MCP server registrations in opencode.json with a single one.

Index

Constants

This section is empty.

Variables

View Source
var AdwCmd = &cobra.Command{
	Use:   "adw",
	Short: "Architectural Debt Watchdogs — detect god modules, circular deps, etc.",
	Long: `Detect and report architectural debt in a codebase. Pure Go implementation.

Detects:
  - God modules (files with >15 imports or >500 lines)
  - Circular dependencies (import cycles)
  - High coupling (files imported by >10 others)
  - Long functions (>100 lines)
  - Large files (>500 lines)
  - TODO/FIXME comments
  - Missing tests (source files without corresponding test files)

Examples:
  sin-code adw .
  sin-code adw ./src --strict
  sin-code adw . --format json`,
	Args: cobra.ArbitraryArgs,
	RunE: func(cmd *cobra.Command, args []string) error {
		path := "."
		if len(args) > 0 {
			path = args[0]
		}
		absPath, err := filepath.Abs(path)
		if err != nil {
			return fmt.Errorf("invalid path: %w", err)
		}
		if info, err := os.Stat(absPath); err != nil || !info.IsDir() {
			if err != nil {
				return fmt.Errorf("path not found: %w", err)
			}
			return fmt.Errorf("path is not a directory: %s", absPath)
		}

		result := scanDebt(absPath, adwStrict)

		if adwFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(result)
		}
		return outputTextADW(result)
	},
}
View Source
var DiscoverCmd = &cobra.Command{
	Use:   "discover [path]",
	Short: "Discover files with relevance scoring and pattern matching",
	Long: `Discover files in a directory with relevance scoring, pattern matching,
and dependency analysis. Pure Go implementation — no external binary needed.

Example:
  sin-code discover . --pattern "**/*.go" --sort_by relevance --format json`,
	Args: cobra.ArbitraryArgs,
	RunE: func(cmd *cobra.Command, args []string) error {
		path := "."
		if len(args) > 0 {
			path = args[0]
		}
		absPath, err := filepath.Abs(path)
		if err != nil {
			return fmt.Errorf("invalid path: %w", err)
		}
		if info, err := os.Stat(absPath); err != nil || !info.IsDir() {
			if err != nil {
				return fmt.Errorf("path not found: %w", err)
			}
			return fmt.Errorf("path is not a directory: %s", absPath)
		}

		results, err := discoverFiles(absPath, discoverPattern, discoverLimit)
		if err != nil {
			return err
		}

		sortResults(results, discoverSort)
		if len(results) > discoverLimit {
			results = results[:discoverLimit]
		}

		if discoverFormat == "json" {
			return outputJSON(results)
		}
		return outputText(results)
	},
}
View Source
var EfmCmd = &cobra.Command{
	Use:   "efm",
	Short: "Ephemeral Full-Stack Mocking — spin up disposable test environments",
	Long: `Manage disposable full-stack environments (Docker Compose, ephemeral containers).
Pure Go implementation.

Examples:
  sin-code efm --action list
  sin-code efm --action up --stack docker-compose.yml --ttl 3600
  sin-code efm --action down --stack docker-compose.yml
  sin-code efm --action status`,
	RunE: func(cmd *cobra.Command, args []string) error {
		return runEFM(efmAction, efmStack, efmTTL, efmFormat)
	},
}
View Source
var ExecuteCmd = &cobra.Command{
	Use:   "execute",
	Short: "Execute shell commands safely with secret redaction and timeout",
	Long: `Execute shell commands with safety checks, secret redaction, timeout
handling, and error analysis. Pure Go implementation — no external binary needed.

Example:
  sin-code execute --command "ls -la" --timeout 10 --format json`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if execCommand == "" {
			return fmt.Errorf("--command is required")
		}
		if err := checkSafety(execCommand); err != nil {
			return err
		}
		return runCommand(execCommand, execTimeout, execFormat, execStream)
	},
}
View Source
var GraspCmd = &cobra.Command{
	Use:   "grasp [path]",
	Short: "Deep code understanding for a single file",
	Long: `Deep code understanding for individual files — structure, dependencies,
usage, and related context. Pure Go implementation.

Example:
  sin-code grasp cmd/sin-code/main.go --format json`,
	Args: cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		absPath, err := filepath.Abs(args[0])
		if err != nil {
			return fmt.Errorf("invalid path: %w", err)
		}
		info, err := os.Stat(absPath)
		if err != nil {
			return fmt.Errorf("file not found: %w", err)
		}
		if info.IsDir() {
			return fmt.Errorf("path is a directory, not a file: %s", absPath)
		}

		result, err := analyzeFile(absPath, info)
		if err != nil {
			return err
		}

		if graspFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(result)
		}
		return outputTextGrasp(result)
	},
}
View Source
var HarvestCmd = &cobra.Command{
	Use:   "harvest",
	Short: "Fetch URLs with caching, structure extraction, and change detection",
	Long: `Fetch URLs with caching, structure extraction, change detection, and
auth management. Pure Go implementation with local disk cache.

Example:
  sin-code harvest --url https://api.example.com/data --format json`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if harvestURL == "" {
			return fmt.Errorf("--url is required")
		}
		return harvestURLFetch(harvestURL, harvestMethod, harvestTimeout, harvestFormat)
	},
}
View Source
var IbdCmd = &cobra.Command{
	Use:   "ibd",
	Short: "Intent-Based Diffing — compare code changes against stated intent",
	Long: `Compare two versions of code and determine if the changes match the
stated intent. Pure Go implementation.

Examples:
  sin-code ibd --before old.py --after new.py --intent "add retry logic"
  sin-code ibd --before v1.0 --after HEAD --intent "refactor authentication"
  sin-code ibd file.go --from main --to feature-branch --intent "add error handling"`,
	RunE: func(cmd *cobra.Command, args []string) error {
		var beforePath, afterPath string

		if ibdBefore != "" && ibdAfter != "" {
			beforePath = ibdBefore
			afterPath = ibdAfter
		} else if len(args) > 0 {
			beforePath = args[0]

			if ibdFrom != "" && ibdTo != "" {

				fmt.Fprintf(os.Stderr, "Note: Git diff (--from/--to) requires manual diff extraction. Reading file as-is.\n")
			}
		} else {
			return fmt.Errorf("either --before/--after or a target path is required")
		}

		result, err := diffWithIntent(beforePath, afterPath, ibdIntent)
		if err != nil {
			return err
		}

		if ibdFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(result)
		}
		return outputTextIBD(result)
	},
}
View Source
var MapCmd = &cobra.Command{
	Use:   "map [path]",
	Short: "Map code architecture with dependency graphs and hot-path analysis",
	Long: `Map code architecture with dependency graphs, entry points, hot paths,
and module-level analysis. Pure Go implementation.

Example:
  sin-code map . --action map --format json`,
	Args: cobra.ArbitraryArgs,
	RunE: func(cmd *cobra.Command, args []string) error {
		path := "."
		if len(args) > 0 {
			path = args[0]
		}
		absPath, err := filepath.Abs(path)
		if err != nil {
			return fmt.Errorf("invalid path: %w", err)
		}
		info, err := os.Stat(absPath)
		if err != nil {
			return fmt.Errorf("path not found: %w", err)
		}
		if !info.IsDir() {
			return fmt.Errorf("path is not a directory: %s", absPath)
		}

		result, err := mapArchitecture(absPath, mapAction)
		if err != nil {
			return err
		}

		if mapFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(result)
		}
		return outputTextMap(result)
	},
}
View Source
var OracleCmd = &cobra.Command{
	Use:   "oracle",
	Short: "Verification Oracle — verify claims with evidence",
	Long: `Verify that source code has corresponding test coverage.
Compares functions/methods in a source file with test cases in a test file.

Examples:
  sin-code oracle --claim src/main.py --evidence tests/test_main.py
  sin-code oracle --claim cmd/sin-code/main.go --evidence cmd/sin-code/main_test.go`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if oracleClaim == "" {
			return fmt.Errorf("--claim (source file) is required")
		}
		if oracleEvidence == "" {
			return fmt.Errorf("--evidence (test file) is required")
		}

		result, err := verifyCoverage(oracleClaim, oracleEvidence)
		if err != nil {
			return err
		}

		if oracleFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(result)
		}
		return outputTextOracle(result)
	},
}
View Source
var OrchestrateCmd = &cobra.Command{
	Use:   "orchestrate",
	Short: "Manage tasks with dependencies, parallel execution, and rollback plans",
	Long: `Manage tasks with dependencies, parallel execution plans, blocker
detection, and rollback plans. Pure Go implementation with JSON file storage.

Example:
  sin-code orchestrate --action add --title "Implement feature X" --tags "urgent,backend"
  sin-code orchestrate --action list --format json
  sin-code orchestrate --action complete --id 1`,
	RunE: func(cmd *cobra.Command, args []string) error {
		return runOrchestrate(orchAction, orchTitle, orchTags, orchID, orchFormat)
	},
}
View Source
var PocCmd = &cobra.Command{
	Use:   "poc",
	Short: "Proof-of-Correctness — verify code satisfies its specification",
	Long: `Verify that code satisfies its specification. Compares code against
spec documents (markdown, text, or structured requirements) and checks for
compliance.

Pure Go implementation. Checks:
  - Required functions/classes mentioned in spec exist in code
  - Function signatures match specification
  - Required imports are present
  - No forbidden patterns (e.g., os.Exit in library code)

Examples:
  sin-code poc --spec spec.md --code src/main.py
  sin-code poc --spec requirements.json --code src/`,
	RunE: func(cmd *cobra.Command, args []string) error {
		target := pocCode
		if target == "" {
			target = pocSpec
		}
		if target == "" {
			return fmt.Errorf("--code (or --spec for back-compat) is required")
		}

		result, err := verifyCorrectness(pocSpec, target)
		if err != nil {
			return err
		}

		if pocFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(result)
		}
		return outputTextPOC(result)
	},
}
View Source
var SckgCmd = &cobra.Command{
	Use:   "sckg",
	Short: "Semantic Codebase Knowledge Graphs — build & query code graph",
	Long: `Build and query a semantic graph of a codebase. Pure Go implementation.

Actions:
  build  — Build the knowledge graph from source code
  query  — Query the graph for relationships (requires --query)
  stats  — Show graph statistics
  export — Export graph as JSON

Examples:
  sin-code sckg . --action build
  sin-code sckg . --action query --query "auth module dependencies"
  sin-code sckg . --action stats
  sin-code sckg . --action export --format json`,
	Args: cobra.ArbitraryArgs,
	RunE: func(cmd *cobra.Command, args []string) error {
		path := "."
		if len(args) > 0 {
			path = args[0]
		}
		absPath, err := filepath.Abs(path)
		if err != nil {
			return fmt.Errorf("invalid path: %w", err)
		}
		if info, err := os.Stat(absPath); err != nil || !info.IsDir() {
			if err != nil {
				return fmt.Errorf("path not found: %w", err)
			}
			return fmt.Errorf("path is not a directory: %s", absPath)
		}

		switch sckgAction {
		case "build":
			graph, err := buildGraph(absPath)
			if err != nil {
				return err
			}
			if sckgFormat == "json" {
				enc := json.NewEncoder(os.Stdout)
				enc.SetIndent("", "  ")
				return enc.Encode(graph)
			}
			return outputTextSCKGBuild(graph)
		case "query":
			if sckgQuery == "" {
				return fmt.Errorf("--query is required for action=query")
			}
			graph, err := buildGraph(absPath)
			if err != nil {
				return err
			}
			results := queryGraph(graph, sckgQuery)
			if sckgFormat == "json" {
				enc := json.NewEncoder(os.Stdout)
				enc.SetIndent("", "  ")
				return enc.Encode(results)
			}
			return outputTextSCKGQuery(results)
		case "stats":
			graph, err := buildGraph(absPath)
			if err != nil {
				return err
			}
			stats := graphStats(graph)
			if sckgFormat == "json" {
				enc := json.NewEncoder(os.Stdout)
				enc.SetIndent("", "  ")
				return enc.Encode(stats)
			}
			return outputTextSCKGStats(stats)
		case "export":
			graph, err := buildGraph(absPath)
			if err != nil {
				return err
			}
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(graph)
		default:
			return fmt.Errorf("unknown action: %s (use build|query|stats|export)", sckgAction)
		}
	},
}
View Source
var ScoutCmd = &cobra.Command{
	Use:   "scout",
	Short: "Search code with regex, semantic, symbol, and usage search",
	Long: `Search code with regex, semantic, symbol, and usage search. Includes
basic dead-code detection. Pure Go implementation.

Example:
  sin-code scout --query "func.*main" --path . --search_type regex --format json`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if scoutQuery == "" {
			return fmt.Errorf("--query is required")
		}
		absPath, err := filepath.Abs(scoutPath)
		if err != nil {
			return fmt.Errorf("invalid path: %w", err)
		}
		if info, err := os.Stat(absPath); err != nil || !info.IsDir() {
			if err != nil {
				return fmt.Errorf("path not found: %w", err)
			}
			return fmt.Errorf("path is not a directory: %s", absPath)
		}

		results, err := searchFiles(absPath, scoutQuery, scoutType, scoutMax)
		if err != nil {
			return err
		}

		if scoutFormat == "json" {
			enc := json.NewEncoder(os.Stdout)
			enc.SetIndent("", "  ")
			return enc.Encode(results)
		}
		return outputTextScout(results)
	},
}
View Source
var ServeCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start an MCP server exposing all 13 sin-code tools",
	Long: `Start a Model Context Protocol (MCP) server that exposes all 13 sin-code
subcommands as MCP tools. This allows opencode (and any MCP-compatible client)
to use sin-code as a single registered MCP server instead of registering 13
separate binaries.

Example opencode.json entry:

  "sin-code": {
    "command": ["/Users/jeremy/.local/bin/sin-code", "serve"],
    "description": "SIN-Code unified toolchain (13 tools)",
    "enabled": true,
    "type": "local"
  }

Then use sin_discover, sin_execute, sin_map, sin_grasp, sin_scout, sin_harvest,
sin_orchestrate, sin_ibd, sin_poc, sin_sckg, sin_adw, sin_oracle, sin_efm as
MCP tools.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		server := mcp.NewServer(&mcp.Implementation{
			Name:    "sin-code",
			Version: ServerVersion,
		}, &mcp.ServerOptions{
			Capabilities: &mcp.ServerCapabilities{
				Tools: &mcp.ToolCapabilities{},
			},
		})

		registerAllMCPTools(server)

		if serveTransport == "stdio" {
			return server.Run(ctx, &mcp.StdioTransport{})
		}
		return fmt.Errorf("unsupported transport: %s (only stdio supported)", serveTransport)
	},
}
View Source
var ServerVersion = "dev"

ServerVersion is set at build time via -ldflags "-X github.com/OpenSIN-Code/SIN-Code-Bundle/cmd/sin-code/internal.ServerVersion=..."

Functions

func PrintError

func PrintError(err error)

PrintError prints an error to stderr in a consistent format and exits with code 1.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL