internal

package
v1.0.4-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: 23 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: config — view and manage sin-code configuration files. Supports reading, setting, and listing configuration values. Docs: config.doc.md

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: security — fast security analysis for Go, Python, Node, and generic projects. Auto-detects project type, finds available security tools, and runs a targeted scan. Docs: security.doc.md

SPDX-License-Identifier: MIT Purpose: self-update — check for and install new sin-code releases from GitHub. Auto-detects platform, downloads the correct binary, and replaces the current one. Docs: self-update.doc.md

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 ConfigCmd = &cobra.Command{
	Use:   "config",
	Short: "View and manage sin-code configuration",
	Long: `Manage sin-code configuration files and settings.

Configuration files:
  ~/.config/sin/sin-code.toml    Main configuration (theme, defaults)
  ~/.config/sin/tui.toml         TUI preferences (theme, keybindings)

Subcommands:
  config get <key>          Get a configuration value
  config set <key> <value>  Set a configuration value
  config list               List all configuration values
  config path               Show configuration directory path
  config init               Create default configuration files`,
}
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 SecurityCmd = &cobra.Command{
	Use:   "security [path]",
	Short: "Fast security analysis — auto-detects project type and runs available tools",
	Long: `security runs a targeted security scan based on the project type detected at <path>.

Supported project types and tools:
  Go        → govulncheck, gosec, go vet (if available)
  Python    → bandit, safety (if available)
  Node.js   → npm audit (if available)
  Generic   → secrets scan (grep for high-entropy strings), file-permission checks

The scan is fast (defaults to 5-minute timeout) and produces a concise summary.
Use --format json for machine-readable output.`,
	Args: cobra.MaximumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		path := "."
		if len(args) > 0 {
			path = args[0]
		}
		path, _ = filepath.Abs(path)

		projType, _ := cmd.Flags().GetString("type")
		if projType == "" || projType == "auto" {
			projType = detectProjectType(path)
		}

		toolFilter, _ := cmd.Flags().GetString("tools")
		format, _ := cmd.Flags().GetString("format")
		timeoutSec, _ := cmd.Flags().GetInt("timeout")
		strict, _ := cmd.Flags().GetBool("strict")

		result := runSecurityScan(path, projType, toolFilter, timeoutSec)
		result.Strict = strict

		if format == "json" {
			out, _ := json.MarshalIndent(result, "", "  ")
			fmt.Println(string(out))
		} else {
			printSecurityResult(result)
		}

		if strict && result.Summary.Issues > 0 {
			return fmt.Errorf("security scan found %d issues (strict mode)", result.Summary.Issues)
		}
		return nil
	},
}

SecurityCmd runs a fast security analysis tailored to the detected project type.

View Source
var SelfUpdateCmd = &cobra.Command{
	Use:   "self-update",
	Short: "Check for and install the latest sin-code release",
	Long: `self-update checks GitHub releases for a newer version of sin-code,
downloads the correct binary for your platform, and installs it.

The current binary is backed up before replacement. If the update fails,
the backup is restored automatically.

Usage:
  sin-code self-update              # Check and install latest stable
  sin-code self-update --version    # Show current version info
  sin-code self-update --dry-run    # Check only, don't install

Supported platforms: darwin/amd64, darwin/arm64, linux/amd64, linux/arm64, windows/amd64`,
	RunE: func(cmd *cobra.Command, args []string) error {
		dryRun, _ := cmd.Flags().GetBool("dry-run")
		showVersion, _ := cmd.Flags().GetBool("version")

		if showVersion {
			return printVersionInfo()
		}

		return runSelfUpdate(dryRun)
	},
}
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.

func SetCurrentVersion

func SetCurrentVersion(v string)

Types

type GitHubRelease

type GitHubRelease struct {
	TagName   string `json:"tag_name"`
	Name      string `json:"name"`
	Published string `json:"published_at"`
	Body      string `json:"body"`
	Assets    []struct {
		Name string `json:"name"`
		Size int    `json:"size"`
		URL  string `json:"browser_download_url"`
	} `json:"assets"`
}

type SecurityResult

type SecurityResult struct {
	ProjectType string          `json:"project_type"`
	Path        string          `json:"path"`
	Duration    time.Duration   `json:"duration"`
	Strict      bool            `json:"strict"`
	Tools       []ToolResult    `json:"tools"`
	Summary     SecuritySummary `json:"summary"`
}

type SecuritySummary

type SecuritySummary struct {
	ToolsRun int `json:"tools_run"`
	Issues   int `json:"issues"`
	Errors   int `json:"errors"`
	Skipped  int `json:"skipped"`
	NotFound int `json:"not_found"`
}

type SinCodeConfig

type SinCodeConfig struct {
	Theme            string `toml:"theme"`
	DefaultTimeout   int    `toml:"default_timeout"`
	DefaultFormat    string `toml:"default_format"`
	MCPServerEnabled bool   `toml:"mcp_server_enabled"`
}

type ToolResult

type ToolResult struct {
	Name     string `json:"name"`
	Status   string `json:"status"` // ok, issues, skipped, error, not_found
	Issues   int    `json:"issues"`
	Duration string `json:"duration"`
	Output   string `json:"output,omitempty"`
	Error    string `json:"error,omitempty"`
}

Jump to

Keyboard shortcuts

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