This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"git.cin.su/m/Assistant/adapters/models"
|
||||
"git.cin.su/m/Assistant/runtime/health"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := os.Getenv("LISTEN_ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8083"
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "cognitive-worker", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
mux.HandleFunc("POST /v1/proposals/deterministic", deterministicProposal)
|
||||
log.Printf("cognitive-worker listening on %s", addr)
|
||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func deterministicProposal(w http.ResponseWriter, r *http.Request) {
|
||||
var request models.DeterministicRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid deterministic proposal request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(models.Propose(request))
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/postgres"
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
authoritydomain "git.cin.su/m/Assistant/modules/authority/domain"
|
||||
commitdomain "git.cin.su/m/Assistant/modules/commit/domain"
|
||||
"git.cin.su/m/Assistant/runtime/health"
|
||||
)
|
||||
|
||||
type authorizationRequest struct {
|
||||
Proposal commitcontract.ActionProposal
|
||||
AuthorizedID commitcontract.AuthorizedActionID
|
||||
GrantID authority.GrantID
|
||||
PrincipalID identity.PrincipalID
|
||||
}
|
||||
type authorityValidator struct{}
|
||||
|
||||
func (authorityValidator) Validate(context authority.AuthorizationContext) error {
|
||||
return authoritydomain.ValidateGrant(context.Binding, context.Scope, context.Grant)
|
||||
}
|
||||
|
||||
func main() {
|
||||
addr := os.Getenv("LISTEN_ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8082"
|
||||
}
|
||||
config := postgres.ContinuityConfig{Host: os.Getenv("POSTGRES_HOST"), Port: os.Getenv("POSTGRES_PORT"), Database: os.Getenv("POSTGRES_DATABASE")}
|
||||
config.User, config.Password = os.Getenv("POSTGRES_USER"), os.Getenv("POSTGRES_PASSWORD")
|
||||
repository, err := postgres.OpenCommit(context.Background(), config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer repository.Close()
|
||||
config.User, config.Password = os.Getenv("AUTHORITY_POSTGRES_USER"), os.Getenv("AUTHORITY_POSTGRES_PASSWORD")
|
||||
authorityRepository, err := postgres.OpenAuthority(context.Background(), config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer authorityRepository.Close()
|
||||
coreURL := os.Getenv("CORE_RUNTIME_URL")
|
||||
if coreURL == "" {
|
||||
log.Fatal("CORE_RUNTIME_URL is required")
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "commit-runtime", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
mux.HandleFunc("POST /v1/authorized-actions", func(w http.ResponseWriter, r *http.Request) {
|
||||
var request authorizationRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid authorization request", 400)
|
||||
return
|
||||
}
|
||||
grant, scope, err := authorityRepository.LoadGrant(r.Context(), request.GrantID)
|
||||
if err != nil {
|
||||
http.Error(w, "authority grant not found", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
binding, err := loadJSON[identity.PrincipalBinding](r.Context(), coreURL+"/v1/principal-bindings/"+url.PathEscape(string(request.Proposal.ActorID))+"/"+url.PathEscape(string(request.PrincipalID)))
|
||||
if err != nil {
|
||||
http.Error(w, "identity binding unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
target, err := loadJSON[struct {
|
||||
TaskID string
|
||||
GoalID string
|
||||
ScopeID string
|
||||
Revision uint64
|
||||
}](r.Context(), coreURL+"/v1/tasks/"+url.PathEscape(string(request.Proposal.Target.TaskID)))
|
||||
if err != nil || target.TaskID != string(request.Proposal.Target.TaskID) || target.GoalID != string(request.Proposal.Target.GoalID) || target.ScopeID != string(request.Proposal.Target.ScopeID) || target.Revision != uint64(request.Proposal.Target.Revision) {
|
||||
http.Error(w, "work target is stale or unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
action, err := commitdomain.Authorize(request.Proposal, commitdomain.AuthorizationContext{Binding: binding, Scope: scope, Grant: grant}, authorityValidator{}, request.AuthorizedID)
|
||||
if err != nil {
|
||||
http.Error(w, "authorization denied", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := repository.SaveAuthorized(r.Context(), action); err != nil {
|
||||
http.Error(w, "save authorized action", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/action-attempts", func(w http.ResponseWriter, r *http.Request) {
|
||||
var attempt commitcontract.ActionAttempt
|
||||
if err := json.NewDecoder(r.Body).Decode(&attempt); err != nil {
|
||||
http.Error(w, "invalid action attempt", 400)
|
||||
return
|
||||
}
|
||||
if attempt.State != commitcontract.ActionUnknownOutcome && attempt.State != commitcontract.ActionSucceeded && attempt.State != commitcontract.ActionFailed {
|
||||
http.Error(w, "attempt must have terminal outcome", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := repository.SaveAttempt(r.Context(), attempt); err != nil {
|
||||
http.Error(w, "save action attempt", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
log.Printf("commit-runtime listening on %s", addr)
|
||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func loadJSON[T any](ctx context.Context, endpoint string) (T, error) {
|
||||
var value T
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return value, err
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
return value, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return value, fmt.Errorf("remote query status %d", response.StatusCode)
|
||||
}
|
||||
return value, json.NewDecoder(response.Body).Decode(&value)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.cin.su/m/Assistant/adapters/postgres"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/runtime/health"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := os.Getenv("LISTEN_ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8081"
|
||||
}
|
||||
repository, err := postgres.OpenContinuity(context.Background(), postgres.ContinuityConfig{Host: os.Getenv("POSTGRES_HOST"), Port: os.Getenv("POSTGRES_PORT"), Database: os.Getenv("POSTGRES_DATABASE"), User: os.Getenv("POSTGRES_USER"), Password: os.Getenv("POSTGRES_PASSWORD")})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer repository.Close()
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "continuity-runtime", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
mux.HandleFunc("POST /v1/prospective-items", func(w http.ResponseWriter, r *http.Request) {
|
||||
var item continuity.ProspectiveItem
|
||||
if err := json.NewDecoder(r.Body).Decode(&item); err != nil {
|
||||
http.Error(w, "invalid prospective item", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := repository.Save(r.Context(), item); err != nil {
|
||||
http.Error(w, "save prospective item", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/prospective-items/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
item, err := repository.Load(r.Context(), continuity.ProspectiveItemID(r.PathValue("id")))
|
||||
if err != nil {
|
||||
http.Error(w, "prospective item not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(item)
|
||||
})
|
||||
log.Printf("continuity-runtime listening on %s", addr)
|
||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.cin.su/m/Assistant/adapters/postgres"
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/situation"
|
||||
"git.cin.su/m/Assistant/contracts/work"
|
||||
capabilitydomain "git.cin.su/m/Assistant/modules/capability/domain"
|
||||
identitydomain "git.cin.su/m/Assistant/modules/identity/domain"
|
||||
situationdomain "git.cin.su/m/Assistant/modules/situation/domain"
|
||||
"git.cin.su/m/Assistant/runtime/health"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := os.Getenv("LISTEN_ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8080"
|
||||
}
|
||||
bootstrapToken, sessionKey := os.Getenv("CREATOR_BOOTSTRAP_TOKEN"), []byte(os.Getenv("CREATOR_SESSION_SIGNING_KEY"))
|
||||
repository, err := postgres.OpenSituation(context.Background(), postgres.ContinuityConfig{Host: os.Getenv("POSTGRES_HOST"), Port: os.Getenv("POSTGRES_PORT"), Database: os.Getenv("POSTGRES_DATABASE"), User: os.Getenv("POSTGRES_USER"), Password: os.Getenv("POSTGRES_PASSWORD")})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer repository.Close()
|
||||
workRepository, err := postgres.OpenWork(context.Background(), postgres.ContinuityConfig{Host: os.Getenv("POSTGRES_HOST"), Port: os.Getenv("POSTGRES_PORT"), Database: os.Getenv("POSTGRES_DATABASE"), User: os.Getenv("WORK_POSTGRES_USER"), Password: os.Getenv("WORK_POSTGRES_PASSWORD")})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer workRepository.Close()
|
||||
capabilityRepository, err := postgres.OpenCapability(context.Background(), postgres.ContinuityConfig{Host: os.Getenv("POSTGRES_HOST"), Port: os.Getenv("POSTGRES_PORT"), Database: os.Getenv("POSTGRES_DATABASE"), User: os.Getenv("CAPABILITY_POSTGRES_USER"), Password: os.Getenv("CAPABILITY_POSTGRES_PASSWORD")})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer capabilityRepository.Close()
|
||||
identityRepository, err := postgres.OpenIdentity(context.Background(), postgres.ContinuityConfig{Host: os.Getenv("POSTGRES_HOST"), Port: os.Getenv("POSTGRES_PORT"), Database: os.Getenv("POSTGRES_DATABASE"), User: os.Getenv("IDENTITY_POSTGRES_USER"), Password: os.Getenv("IDENTITY_POSTGRES_PASSWORD")})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer identityRepository.Close()
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "core-runtime", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
mux.HandleFunc("POST /v1/creator/sessions", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !identitydomain.BootstrapMatches(bootstrapToken, bearerToken(r)) {
|
||||
http.Error(w, "creator authentication denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
token, session, err := identitydomain.IssueCreatorSession(sessionKey, time.Now(), 8*time.Hour)
|
||||
if err != nil {
|
||||
http.Error(w, "creator session unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Token string
|
||||
Session identity.CreatorSession
|
||||
}{token, session})
|
||||
})
|
||||
mux.HandleFunc("GET /v1/creator/sessions/current", func(w http.ResponseWriter, r *http.Request) {
|
||||
session, err := identitydomain.ValidateCreatorSession(sessionKey, bearerToken(r), time.Now())
|
||||
if err != nil {
|
||||
http.Error(w, "creator session denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(session)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/principal-bindings/{actor}/{principal}", func(w http.ResponseWriter, r *http.Request) {
|
||||
binding, err := identityRepository.LoadBinding(r.Context(), identity.ActorID(r.PathValue("actor")), identity.PrincipalID(r.PathValue("principal")))
|
||||
if err != nil {
|
||||
http.Error(w, "principal binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(binding)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/tasks/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
target, err := workRepository.Load(r.Context(), work.TaskID(r.PathValue("id")))
|
||||
if err != nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(target)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/capabilities/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
var status capability.Health
|
||||
if err := json.NewDecoder(r.Body).Decode(&status); err != nil {
|
||||
http.Error(w, "invalid capability health", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := capabilitydomain.ValidateHealth(status); err != nil {
|
||||
http.Error(w, "invalid capability health", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := capabilityRepository.SaveHealth(r.Context(), status); err != nil {
|
||||
http.Error(w, "save capability health", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/capabilities/{id}/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
status, err := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID(r.PathValue("id")))
|
||||
if err != nil {
|
||||
http.Error(w, "capability health not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(status)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/capabilities/health-projection/rebuild", func(w http.ResponseWriter, r *http.Request) {
|
||||
rebuilt, err := capabilityRepository.RebuildHealthProjection(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "rebuild capability health projection", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(struct{ Rebuilt int64 }{rebuilt})
|
||||
})
|
||||
mux.HandleFunc("POST /v1/focus-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
var binding situation.FocusBinding
|
||||
if err := json.NewDecoder(r.Body).Decode(&binding); err != nil {
|
||||
http.Error(w, "invalid focus binding", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := repository.Save(r.Context(), binding); err != nil {
|
||||
http.Error(w, "save focus binding", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/focus", func(w http.ResponseWriter, r *http.Request) {
|
||||
runtime := situation.RuntimeBinding{SessionID: situation.SessionID(r.URL.Query().Get("session_id")), Workspace: situation.WorkspaceID(r.URL.Query().Get("workspace_id"))}
|
||||
bindings, err := repository.ByRuntime(r.Context(), runtime)
|
||||
if err != nil {
|
||||
http.Error(w, "load focus", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
focus, err := situationdomain.NewResolver(bindings).Resolve(runtime)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(focus)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/tasks", func(w http.ResponseWriter, r *http.Request) {
|
||||
var target work.TaskTarget
|
||||
if err := json.NewDecoder(r.Body).Decode(&target); err != nil {
|
||||
http.Error(w, "invalid task", 400)
|
||||
return
|
||||
}
|
||||
if err := workRepository.Create(r.Context(), target); err != nil {
|
||||
http.Error(w, "create task", 500)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/tasks/{id}/commit", func(w http.ResponseWriter, r *http.Request) {
|
||||
var target work.TaskTarget
|
||||
if err := json.NewDecoder(r.Body).Decode(&target); err != nil {
|
||||
http.Error(w, "invalid task commit", 400)
|
||||
return
|
||||
}
|
||||
target.TaskID = work.TaskID(r.PathValue("id"))
|
||||
revision, err := workRepository.Commit(r.Context(), target)
|
||||
if err != nil {
|
||||
http.Error(w, "task revision conflict", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(struct{ Revision work.TaskRevision }{revision})
|
||||
})
|
||||
mux.HandleFunc("POST /v1/focus-task-commits", func(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
SessionID situation.SessionID
|
||||
Workspace situation.WorkspaceID
|
||||
Target work.TaskTarget
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, "invalid guarded commit", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
bindings, err := repository.ByRuntime(r.Context(), situation.RuntimeBinding{SessionID: request.SessionID, Workspace: request.Workspace})
|
||||
if err != nil {
|
||||
http.Error(w, "load focus", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
focus, err := situationdomain.NewResolver(bindings).Resolve(situation.RuntimeBinding{SessionID: request.SessionID, Workspace: request.Workspace})
|
||||
if err != nil {
|
||||
http.Error(w, "focus unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := situationdomain.ValidateTaskTarget(focus, request.Target); err != nil {
|
||||
http.Error(w, "target outside resolved focus", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
revision, err := workRepository.Commit(r.Context(), request.Target)
|
||||
if err != nil {
|
||||
http.Error(w, "task revision conflict", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(struct{ Revision work.TaskRevision }{revision})
|
||||
})
|
||||
log.Printf("core-runtime listening on %s", addr)
|
||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) string {
|
||||
value := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(value, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(value, "Bearer ")
|
||||
}
|
||||
@@ -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