ctemcycle

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: GPL-3.0 Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ctemcycle provides public types and helpers reusable across the codebase.

Index

Constants

View Source
const (
	WeightValidationCoverage   = 0.30
	WeightResolutionThroughput = 0.25
	WeightMTTRTrend            = 0.20
	WeightPriorityStability    = 0.15
	WeightScopeStability       = 0.10 // reported only; excluded from Score (drift source deferred)
)

CTEM-program maturity, made TRANSPARENT.

A single "maturity score" is close to useless if an operator cannot see WHY it is what it is. So instead of an opaque number we return a breakdown: each component carries its raw metric value, a normalized 0–100 sub-score, its (effective) weight, and the resulting contribution. The composite is just the sum of contributions — reproducible by hand.

The score must reflect only MEASURED signal. Each component declares a base weight, but a component is folded in only when it actually has an input to measure; the ACTIVE base weights are then renormalized to sum to 1.0 so the composite stays on a 0–100 scale. A component that is currently unscorable is still REPORTED (for transparency) but with an effective weight of 0, so it contributes nothing:

base weights   validation_coverage   0.30  // are fixes proven?
               resolution_throughput 0.25  // resolved / opened
               mttr_trend            0.20  // is MTTR improving?
               priority_stability    0.15  // low P-class churn
               scope_stability       0.10  // low scope drift

When every component is active the effective weights are base/0.90 — e.g. a fully-scored tenant weights validation_coverage 0.30/0.90. scope_stability's drift source is deferred (always 0), so it carries no measured signal and is permanently excluded from Score until that source is wired — otherwise it would hand every tenant a fixed +10. mttr_trend is excluded when there is no prior cycle to compare against, and priority_stability is excluded when no findings were opened (there is then no prioritization work to be "stable" about) — either would otherwise inflate an inactive tenant toward a hollow ~35.

Only the metrics defined in review.go feed the score. CTEM stage coverage is reported ALONGSIDE (StageCoverage) as an explainability aid but is deliberately NOT folded into the weighted number, so the score means exactly one thing: the quality of the measured program.

Weights are intentionally simple, visible and tunable — change a const, the breakdown re-explains itself.

View Source
const (
	MetricMTTRHours          = "mttr_hours"
	MetricFindingsOpened     = "findings_opened"
	MetricFindingsResolved   = "findings_resolved"
	MetricPClassChurn        = "p_class_churn"       // count of priority transitions during the cycle
	MetricValidationCoverage = "validation_coverage" // % of closed findings with validation evidence
	MetricScopeDriftSize     = "scope_drift_size"
)

Cycle-level metric types used in the `ctem_cycle_metrics` table. These are the minimum set the review phase produces; the handler can add more without changing this contract — metric_type is just a string in the table.

Variables

This section is empty.

Functions

This section is empty.

Types

type CTEMStageCoverage added in v0.6.0

type CTEMStageCoverage struct {
	Scoping        bool `json:"scoping"`        // a scope was frozen at activation
	Discovery      bool `json:"discovery"`      // findings were opened
	Prioritization bool `json:"prioritization"` // priority classes were applied/changed
	Validation     bool `json:"validation"`     // closed findings carried evidence
	Mobilization   bool `json:"mobilization"`   // findings were resolved
	CoveredCount   int  `json:"covered_count"`  // 0..5
}

CTEMStageCoverage records which of the five CTEM stages the latest closed cycle exercised, derived from the six metrics. Reported for transparency; not part of the weighted score.

type Charter

type Charter struct {
	BusinessPriorities []string `json:"business_priorities"`
	RiskAppetite       string   `json:"risk_appetite"`
	InScopeServices    []string `json:"in_scope_services"`
	Objectives         []string `json:"objectives"`

	// ThreatScenarios names what the cycle is defending against
	// (e.g. "ransomware via exposed RDP", "supply-chain compromise"),
	// framing scope by adversary behavior rather than assets alone.
	ThreatScenarios []string `json:"threat_scenarios,omitempty"`
	// Exclusions lists what is explicitly out of scope, each with a
	// reason, so a deferral is a reasoned decision rather than a silent gap.
	Exclusions []CharterExclusion `json:"exclusions,omitempty"`
	// SuccessCriteria are the measurable/verifiable conditions that define
	// a successful cycle. They are persisted here; evaluating them against
	// real close-loop metrics is a future hook (see the CTEMCycleHandler
	// Close path where cycle metrics are computed).
	SuccessCriteria []CharterSuccessCriterion `json:"success_criteria,omitempty"`
	// EscalationPath records who blockers escalate to (person, role or channel).
	EscalationPath string `json:"escalation_path,omitempty"`
	// Roles records the accountable owners for the cycle.
	Roles CharterRoles `json:"roles,omitempty"`
	// Timeline is an optional free-text schedule/cadence for the cycle.
	Timeline string `json:"timeline,omitempty"`
	// ScopeRefinementNotes captures the feedback-to-scope loop that closes a
	// CTEM cycle: what the review learned about scope — gaps to add, items to
	// exclude next cycle, lessons for the next charter. Unlike the rest of the
	// charter (fixed at planning) this is written at cycle review/close, so it
	// is edited via SetScopeRefinementNotes rather than SetCharter.
	ScopeRefinementNotes string `json:"scope_refinement_notes,omitempty"`
}

Charter holds the business context for a CTEM cycle.

Beyond the original asset/service scope (BusinessPriorities, RiskAppetite, InScopeServices, Objectives), the charter captures the ctem.org scope-charter playbook elements so a cycle's scope is defined by what it defends against, how success is measured, what is deliberately excluded (and why), and who owns escalation — not just an asset list. All playbook fields are optional and additive: the struct is (de)serialized to the ctem_cycles.charter JSONB column, so charters written before these fields existed still load with the new fields left at their zero value.

type CharterExclusion added in v0.6.0

type CharterExclusion struct {
	Item   string `json:"item"`
	Reason string `json:"reason"`
}

CharterExclusion is an item deliberately left out of a cycle's scope, paired with the reason it was excluded.

type CharterRoles added in v0.6.0

type CharterRoles struct {
	Sponsor            string `json:"sponsor,omitempty"`
	Operator           string `json:"operator,omitempty"`
	EngineeringPartner string `json:"engineering_partner,omitempty"`
}

CharterRoles records the accountable owners for a cycle's execution.

type CharterSuccessCriterion added in v0.6.0

type CharterSuccessCriterion struct {
	Name   string `json:"name"`
	Metric string `json:"metric"`
	Target string `json:"target"`
}

CharterSuccessCriterion is a measurable/verifiable condition that defines cycle success — a named target expressed as a metric and its goal value.

type Cycle

type Cycle struct {
	// contains filtered or unexported fields
}

Cycle represents a CTEM assessment cycle.

func NewCycle

func NewCycle(tenantID shared.ID, name string, createdBy shared.ID) (*Cycle, error)

NewCycle creates a new CTEM cycle in planning status.

func ReconstituteCycle

func ReconstituteCycle(data CycleData) *Cycle

ReconstituteCycle recreates from persistence.

func (*Cycle) Activate

func (c *Cycle) Activate() error

Activate transitions from planning to active. This should trigger scope snapshot creation externally.

func (*Cycle) Charter

func (c *Cycle) Charter() Charter

func (*Cycle) Close

func (c *Cycle) Close(closedBy shared.ID) error

Close transitions from review to closed. Metrics should be computed externally and stored in ctem_cycle_metrics.

func (*Cycle) CreatedAt

func (c *Cycle) CreatedAt() time.Time

func (*Cycle) CreatedBy

func (c *Cycle) CreatedBy() shared.ID

func (*Cycle) EndDate

func (c *Cycle) EndDate() *time.Time

func (*Cycle) ID

func (c *Cycle) ID() shared.ID

Getters

func (*Cycle) IsActive

func (c *Cycle) IsActive() bool

IsActive returns true if the cycle is in active status.

func (*Cycle) Name

func (c *Cycle) Name() string

func (*Cycle) SetCharter

func (c *Cycle) SetCharter(charter Charter) error

SetCharter updates the cycle charter (only in planning status).

func (*Cycle) SetDates

func (c *Cycle) SetDates(start, end time.Time) error

SetDates sets the cycle start/end dates.

func (*Cycle) SetScopeRefinementNotes added in v0.6.0

func (c *Cycle) SetScopeRefinementNotes(notes string) error

SetScopeRefinementNotes records the feedback-to-scope notes captured during cycle review or close. This is the one charter field deliberately editable after planning: it is only meaningful once the cycle has run, so it is allowed in review and closed status (and rejected in planning/active, where the charter proper is edited via SetCharter).

func (*Cycle) StartDate

func (c *Cycle) StartDate() *time.Time

func (*Cycle) StartReview

func (c *Cycle) StartReview() error

StartReview transitions from active to review.

func (*Cycle) Status

func (c *Cycle) Status() CycleStatus

func (*Cycle) TenantID

func (c *Cycle) TenantID() shared.ID

type CycleData

type CycleData struct {
	ID        shared.ID
	TenantID  shared.ID
	Name      string
	Status    CycleStatus
	StartDate *time.Time
	EndDate   *time.Time
	Charter   Charter
	ClosedBy  *shared.ID
	ClosedAt  *time.Time
	CreatedBy shared.ID
	CreatedAt time.Time
	UpdatedAt time.Time
}

CycleData is the persistence representation.

type CycleMetric

type CycleMetric struct {
	MetricType string
	Value      float64
	ComputedAt time.Time
}

CycleMetric holds a computed metric for a cycle.

type CycleMetricSet added in v0.6.0

type CycleMetricSet map[string]float64

CycleMetricSet is the computed metric map for one cycle: metric_type → value. Values are DECIMAL(12,2) in storage.

type CycleMetrics added in v0.6.0

type CycleMetrics struct {
	CycleID  shared.ID          `json:"cycle_id"`
	Name     string             `json:"name"`
	ClosedAt time.Time          `json:"closed_at"`
	Metrics  map[string]float64 `json:"metrics"`
}

CycleMetrics bundles a closed cycle with its latest metric values — the unit the trend endpoint iterates over. Metrics holds the most recent value per metric_type for the cycle.

func (CycleMetrics) Value added in v0.6.0

func (c CycleMetrics) Value(key string) float64

Value returns the metric value for key, or 0 when absent.

type CycleStatus

type CycleStatus string

CycleStatus represents the lifecycle status of a CTEM cycle.

const (
	CycleStatusPlanning CycleStatus = "planning"
	CycleStatusActive   CycleStatus = "active"
	CycleStatusReview   CycleStatus = "review"
	CycleStatusClosed   CycleStatus = "closed"
)

type MaturityBreakdown added in v0.6.0

type MaturityBreakdown struct {
	Score          float64             `json:"score"` // sum of contributions, 0–100
	Components     []MaturityComponent `json:"components"`
	StageCoverage  CTEMStageCoverage   `json:"ctem_stage_coverage"`
	CyclesAnalyzed int                 `json:"cycles_analyzed"`
}

MaturityBreakdown is the full, explainable maturity result.

func ComputeMaturity added in v0.6.0

func ComputeMaturity(cycles []CycleMetrics) MaturityBreakdown

ComputeMaturity builds the transparent breakdown from a tenant's closed cycles, ordered by closed_at ASCENDING. Level components read the latest cycle; trend components compare the latest to the prior cycle. Returns a zero-score breakdown when no cycles are given.

type MaturityComponent added in v0.6.0

type MaturityComponent struct {
	Name         string  `json:"name"`
	RawValue     float64 `json:"raw_value"`    // underlying metric value
	Score        float64 `json:"score"`        // normalized 0–100
	Weight       float64 `json:"weight"`       // effective 0..1; active weights sum to 1.0
	Contribution float64 `json:"contribution"` // score * weight
	Detail       string  `json:"detail"`       // how the sub-score was derived
}

MaturityComponent is one transparent, weighted input to the composite.

type MetricsRepository added in v0.6.0

type MetricsRepository interface {
	// Compute runs the metric queries over the cycle's active window
	// and returns the values WITHOUT persisting them. Returns
	// shared.ErrNotFound when the cycle does not belong to the tenant.
	Compute(ctx context.Context, tenantID, cycleID shared.ID) (CycleMetricSet, error)
	// UpsertBatch replaces the stored metric rows for one cycle with
	// the given set (delete-then-insert inside a transaction). No-op on
	// an empty set. Tenant-scoped: writes nothing for a foreign cycle.
	UpsertBatch(ctx context.Context, tenantID, cycleID shared.ID, metrics CycleMetricSet) error
	// Get returns the persisted metric rows for one cycle, newest
	// first. Empty (not an error) when none are stored yet.
	Get(ctx context.Context, tenantID, cycleID shared.ID) ([]StoredMetric, error)
	// ListClosedForTenant batch-loads every closed cycle's latest
	// metrics in a single query, ordered by closed_at ascending, for
	// the trend/maturity endpoint. No N+1.
	ListClosedForTenant(ctx context.Context, tenantID shared.ID) ([]CycleMetrics, error)
}

MetricsRepository computes, persists and reads per-cycle metrics. All methods are tenant-scoped: the tenant is checked by joining ctem_cycles (ctem_cycle_metrics itself has no tenant_id column).

type ReviewSnapshot

type ReviewSnapshot struct {
	CycleID              shared.ID
	TenantID             shared.ID
	Delta                ScopeDelta
	FindingsToRevalidate []shared.ID
	ComputedAt           time.Time
}

ReviewSnapshot bundles everything the handler computes on transition into review. Persisting this record gives the reviewer a deterministic view of the cycle outcome.

func NewReviewSnapshot

func NewReviewSnapshot(cycleID, tenantID shared.ID) ReviewSnapshot

NewReviewSnapshot builds an empty snapshot for a cycle at a given moment. Callers fill Delta and FindingsToRevalidate via the handler's SQL computations.

type ScopeChangeEvent

type ScopeChangeEvent struct {
	CycleID  shared.ID
	TenantID shared.ID
	AssetID  shared.ID
	Kind     ScopeChangeKind
	At       time.Time
	// Reason is a short string for audit / UI ("asset created",
	// "asset decommissioned", "business service membership
	// changed").
	Reason string
}

ScopeChangeEvent is the in-memory domain shape. Emitted by the assets service + consumed by the cycle handler.

func (ScopeChangeEvent) Validate

func (e ScopeChangeEvent) Validate() error

Validate ensures required fields are set.

type ScopeChangeKind

type ScopeChangeKind string

ScopeChangeKind enumerates what happened.

const (
	ScopeChangeAdded   ScopeChangeKind = "added"
	ScopeChangeRemoved ScopeChangeKind = "removed"
)

type ScopeDelta

type ScopeDelta struct {
	// AddedAssetIDs are assets that NOW match the cycle's scope
	// targets but were not in the frozen snapshot (created or
	// retagged during the active phase).
	AddedAssetIDs []shared.ID
	// RemovedAssetIDs are assets that were in the frozen snapshot
	// but no longer exist or no longer match the scope (deleted,
	// decommissioned, untagged).
	RemovedAssetIDs []shared.ID
	// UnchangedCount is the number of assets in both sets. Kept as
	// a count (not a list) because it is typically the vast majority
	// and we do not need the IDs.
	UnchangedCount int
	// ComputedAt is the wall-clock time the delta was produced.
	// Exposed to the UI so reviewers know the freshness.
	ComputedAt time.Time
}

ScopeDelta describes the difference between a cycle's frozen scope snapshot and the current tenant asset set.

func (ScopeDelta) IsEmpty

func (d ScopeDelta) IsEmpty() bool

IsEmpty returns true when the snapshot matches the current scope exactly — no assets added, none removed.

func (ScopeDelta) Size

func (d ScopeDelta) Size() int

Size returns the total magnitude of the delta (added + removed). Used by the UI to show a single "scope drift" badge without exposing the full lists.

type ScopeDeltaRollup

type ScopeDeltaRollup struct {
	CycleID         shared.ID
	AddedAssets     []shared.ID
	RemovedAssets   []shared.ID
	AddedByReason   map[string]int
	RemovedByReason map[string]int
	ComputedAt      time.Time
}

ScopeDeltaRollup aggregates a batch of ScopeChangeEvents for display. The cycle-review endpoint returns this so the UI shows "during this cycle so far: +12 assets, -3 assets".

func RollupChanges

func RollupChanges(cycleID shared.ID, events []ScopeChangeEvent) ScopeDeltaRollup

RollupChanges folds a sequence of ScopeChangeEvents into a ScopeDeltaRollup. Malformed events (validation fails) are skipped, not fatal — the rollup is best-effort aggregation for the UI.

func (ScopeDeltaRollup) IsEmpty

func (r ScopeDeltaRollup) IsEmpty() bool

IsEmpty returns true when no added/removed events contributed.

func (ScopeDeltaRollup) Size

func (r ScopeDeltaRollup) Size() int

Size returns the absolute drift magnitude.

type StoredMetric added in v0.6.0

type StoredMetric struct {
	MetricType string    `json:"metric_type"`
	Value      float64   `json:"value"`
	ComputedAt time.Time `json:"computed_at"`
}

StoredMetric is one persisted ctem_cycle_metrics row.

Jump to

Keyboard shortcuts

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