This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArchitectureSentinelNegativeCases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
importPath string
|
||||
want string
|
||||
}{
|
||||
{"domain infrastructure import", "git.cin.su/m/Assistant/adapters/postgres", "domain imports forbidden /adapters/"},
|
||||
{"cross-module implementation import", "git.cin.su/m/Assistant/modules/beta/domain", "cross-module implementation import beta"},
|
||||
{"undeclared contract dependency", "git.cin.su/m/Assistant/contracts/beta", "undeclared contract dependency contracts.beta"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
root := architectureFixture(t, test.importPath)
|
||||
err := checkArchitectureAt(root)
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("sentinel error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchitectureSentinelAcceptsDeclaredContractDependency(t *testing.T) {
|
||||
root := architectureFixture(t, "git.cin.su/m/Assistant/contracts/beta")
|
||||
registry := `{"registry_version":1,"semantic_generation":1,"architecture_generation":1,"modules":{"alpha":{"id":"mod.alpha","owns":[],"database_schema":"alpha","boundary_class":"remote_capable","may_depend_on":["contracts.beta"]},"beta":{"id":"mod.beta","owns":[],"database_schema":"beta","boundary_class":"remote_capable","may_depend_on":[]}}}`
|
||||
writeFixture(t, filepath.Join(root, "architecture", "architecture-registry.json"), registry)
|
||||
if err := checkArchitectureAt(root); err != nil {
|
||||
t.Fatalf("declared dependency rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightRejectsProtectedPathBelowTierE(t *testing.T) {
|
||||
registry := Registry{ProtectedPaths: []string{"architecture/**", "security/**"}}
|
||||
taskPacket := TaskPacket{TaskID: "DEV-bad", RiskTier: "C", Intent: "weaken guardrail"}
|
||||
taskPacket.AllowedChangeScope.Paths = []string{"architecture/architecture-registry.json"}
|
||||
if err := validateTaskScope(taskPacket, registry); err == nil || !strings.Contains(err.Error(), "protected path") {
|
||||
t.Fatalf("protected path task error = %v", err)
|
||||
}
|
||||
taskPacket.RiskTier = "E"
|
||||
if err := validateTaskScope(taskPacket, registry); err != nil {
|
||||
t.Fatalf("Tier E protected path rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func architectureFixture(t *testing.T, importPath string) string {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
registry := `{"registry_version":1,"semantic_generation":1,"architecture_generation":1,"modules":{"alpha":{"id":"mod.alpha","owns":[],"database_schema":"alpha","boundary_class":"remote_capable","may_depend_on":[]},"beta":{"id":"mod.beta","owns":[],"database_schema":"beta","boundary_class":"remote_capable","may_depend_on":[]}}}`
|
||||
writeFixture(t, filepath.Join(root, "architecture", "architecture-registry.json"), registry)
|
||||
writeFixture(t, filepath.Join(root, "modules", "alpha", "domain", "fixture.go"), "package domain\nimport _ \""+importPath+"\"\n")
|
||||
return root
|
||||
}
|
||||
|
||||
func writeFixture(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Registry struct {
|
||||
RegistryVersion int `json:"registry_version"`
|
||||
SemanticGeneration int `json:"semantic_generation"`
|
||||
ArchitectureGeneration int `json:"architecture_generation"`
|
||||
Modules map[string]struct {
|
||||
ID string `json:"id"`
|
||||
Owns []string `json:"owns"`
|
||||
DatabaseSchema string `json:"database_schema"`
|
||||
BoundaryClass string `json:"boundary_class"`
|
||||
MayDependOn []string `json:"may_depend_on"`
|
||||
Forbidden []string `json:"forbidden"`
|
||||
} `json:"modules"`
|
||||
ProtectedPaths []string `json:"protected_paths"`
|
||||
}
|
||||
|
||||
type TaskPacket struct {
|
||||
TaskID string `json:"task_id"`
|
||||
RiskTier string `json:"risk_tier"`
|
||||
Intent string `json:"intent"`
|
||||
AllowedChangeScope struct {
|
||||
Paths []string `json:"paths"`
|
||||
} `json:"allowed_change_scope"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "doctor":
|
||||
err = doctor()
|
||||
case "check-architecture":
|
||||
err = checkArchitecture()
|
||||
case "show-registry":
|
||||
err = showRegistry()
|
||||
case "preflight":
|
||||
err = preflight(os.Args[2:])
|
||||
default:
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "devctl:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Println("devctl doctor | check-architecture | show-registry | preflight -task <json>")
|
||||
}
|
||||
|
||||
func loadRegistry() (Registry, error) {
|
||||
b, err := os.ReadFile("architecture/architecture-registry.json")
|
||||
if err != nil {
|
||||
return Registry{}, err
|
||||
}
|
||||
var r Registry
|
||||
if err = json.Unmarshal(b, &r); err != nil {
|
||||
return Registry{}, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func doctor() error {
|
||||
r, err := loadRegistry()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("architecture generation=%d semantic generation=%d modules=%d\n", r.ArchitectureGeneration, r.SemanticGeneration, len(r.Modules))
|
||||
for _, tool := range []string{"git", "go", "docker"} {
|
||||
p, e := exec.LookPath(tool)
|
||||
if e != nil {
|
||||
fmt.Printf("WARN: %s not found\n", tool)
|
||||
} else {
|
||||
fmt.Printf("OK: %s -> %s\n", tool, p)
|
||||
}
|
||||
}
|
||||
cmd := exec.Command("git", "remote", "get-url", "origin")
|
||||
out, e := cmd.CombinedOutput()
|
||||
if e == nil {
|
||||
fmt.Printf("git origin: %s", out)
|
||||
} else {
|
||||
fmt.Println("WARN: git origin not configured; run scripts/bootstrap.ps1")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func showRegistry() error {
|
||||
r, e := loadRegistry()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
b, _ := json.MarshalIndent(r, "", " ")
|
||||
fmt.Println(string(b))
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkArchitecture() error {
|
||||
return checkArchitectureAt(".")
|
||||
}
|
||||
|
||||
func checkArchitectureAt(root string) error {
|
||||
b, err := os.ReadFile(filepath.Join(root, "architecture", "architecture-registry.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var r Registry
|
||||
if err := json.Unmarshal(b, &r); err != nil {
|
||||
return err
|
||||
}
|
||||
var violations []string
|
||||
err = filepath.WalkDir(filepath.Join(root, "modules"), func(path string, d fs.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.IsDir() || !strings.HasSuffix(path, ".go") {
|
||||
return nil
|
||||
}
|
||||
relative, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts := strings.Split(filepath.ToSlash(relative), "/")
|
||||
if len(parts) < 3 {
|
||||
return nil
|
||||
}
|
||||
owner := parts[1]
|
||||
module, ok := r.Modules[owner]
|
||||
if !ok {
|
||||
violations = append(violations, relative+": unknown module owner "+owner)
|
||||
return nil
|
||||
}
|
||||
parsed, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
allowed := map[string]bool{}
|
||||
for _, dependency := range module.MayDependOn {
|
||||
allowed[dependency] = true
|
||||
}
|
||||
for _, imported := range parsed.Imports {
|
||||
importPath := strings.Trim(imported.Path.Value, "\"")
|
||||
if strings.Contains(filepath.ToSlash(relative), "/domain/") {
|
||||
for _, bad := range []string{"/adapters/", "/runtime/", "/cmd/"} {
|
||||
if strings.Contains(importPath, "git.cin.su/m/Assistant"+bad) {
|
||||
violations = append(violations, relative+": domain imports forbidden "+bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
modulePrefix := "git.cin.su/m/Assistant/modules/"
|
||||
if strings.HasPrefix(importPath, modulePrefix) {
|
||||
other := strings.Split(strings.TrimPrefix(importPath, modulePrefix), "/")[0]
|
||||
if other != owner {
|
||||
violations = append(violations, relative+": cross-module implementation import "+other)
|
||||
}
|
||||
}
|
||||
contractPrefix := "git.cin.su/m/Assistant/contracts/"
|
||||
if strings.HasPrefix(importPath, contractPrefix) {
|
||||
contractOwner := strings.Split(strings.TrimPrefix(importPath, contractPrefix), "/")[0]
|
||||
if contractOwner != owner && !allowed["contracts."+contractOwner] {
|
||||
violations = append(violations, relative+": undeclared contract dependency contracts."+contractOwner)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(violations) > 0 {
|
||||
for _, v := range violations {
|
||||
fmt.Println("VIOLATION:", v)
|
||||
}
|
||||
return fmt.Errorf("%d architecture violation(s): %s", len(violations), strings.Join(violations, "; "))
|
||||
}
|
||||
fmt.Println("architecture checks: OK")
|
||||
return nil
|
||||
}
|
||||
|
||||
func preflight(args []string) error {
|
||||
var task string
|
||||
for i := 0; i < len(args); i++ {
|
||||
if args[i] == "-task" && i+1 < len(args) {
|
||||
task = args[i+1]
|
||||
i++
|
||||
}
|
||||
}
|
||||
if task == "" {
|
||||
return errors.New("missing -task <json>")
|
||||
}
|
||||
b, err := os.ReadFile(task)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var taskPacket TaskPacket
|
||||
if err = json.Unmarshal(b, &taskPacket); err != nil {
|
||||
return fmt.Errorf("task packet must be valid JSON in V1: %w", err)
|
||||
}
|
||||
if taskPacket.TaskID == "" || taskPacket.Intent == "" || taskPacket.RiskTier == "" {
|
||||
return errors.New("task packet missing task_id, intent, or risk_tier")
|
||||
}
|
||||
registry, err := loadRegistry()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateTaskScope(taskPacket, registry); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("task preflight loaded: %s tier=%s\n", taskPacket.TaskID, taskPacket.RiskTier)
|
||||
return checkArchitecture()
|
||||
}
|
||||
|
||||
func validateTaskScope(taskPacket TaskPacket, registry Registry) error {
|
||||
if taskPacket.RiskTier == "E" {
|
||||
return nil
|
||||
}
|
||||
for _, allowed := range taskPacket.AllowedChangeScope.Paths {
|
||||
allowed = filepath.ToSlash(allowed)
|
||||
for _, protected := range registry.ProtectedPaths {
|
||||
prefix := strings.TrimSuffix(filepath.ToSlash(protected), "/**")
|
||||
if allowed == prefix || strings.HasPrefix(allowed, prefix+"/") {
|
||||
return fmt.Errorf("task %s tier %s may not write protected path %s", taskPacket.TaskID, taskPacket.RiskTier, allowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user