Documentation
¶
Overview ¶
Package ctemcycle provides public types and helpers reusable across the codebase.
Index ¶
- Constants
- func RecognizedCriterionMetrics() []string
- type CTEMStageCoverage
- type Charter
- type CharterEvaluation
- type CharterExclusion
- type CharterRoles
- type CharterSuccessCriterion
- type CriterionEvaluation
- type CriterionOutcome
- type Cycle
- func (c *Cycle) Activate() error
- func (c *Cycle) Charter() Charter
- func (c *Cycle) Close(closedBy shared.ID) error
- func (c *Cycle) CreatedAt() time.Time
- func (c *Cycle) CreatedBy() shared.ID
- func (c *Cycle) EndDate() *time.Time
- func (c *Cycle) ID() shared.ID
- func (c *Cycle) IsActive() bool
- func (c *Cycle) Name() string
- func (c *Cycle) SetCharter(charter Charter) error
- func (c *Cycle) SetDates(start, end time.Time) error
- func (c *Cycle) SetScopeRefinementNotes(notes string) error
- func (c *Cycle) StartDate() *time.Time
- func (c *Cycle) StartReview() error
- func (c *Cycle) Status() CycleStatus
- func (c *Cycle) TenantID() shared.ID
- type CycleData
- type CycleMetric
- type CycleMetricSet
- type CycleMetrics
- type CycleStatus
- type MaturityBreakdown
- type MaturityComponent
- type MetricsRepository
- type ReviewSnapshot
- type ScopeChangeEvent
- type ScopeChangeKind
- type ScopeDelta
- type ScopeDeltaRollup
- type StoredMetric
Constants ¶
const ( MetricP0Resolved = "p0_resolved" MetricP1Resolved = "p1_resolved" MetricP0OpenAtClose = "p0_open_at_close" MetricP1OpenAtClose = "p1_open_at_close" MetricRiskBefore = "risk_before" MetricRiskAfter = "risk_after" MetricRiskReductionPct = "risk_reduction_pct" // MetricCharterCompletionRate is met / (met + unmet) × 100. It is only // stored when at least one criterion was measurable — a cycle whose // criteria are all free text has no completion rate, not a rate of 0. MetricCharterCompletionRate = "charter_completion_rate" )
Metric keys computed at close in addition to the six in review.go. They exist so the most common charter criteria ("resolve every P0", "cut risk by 20%") have something real to be checked against.
const ( UnitHours = "hours" UnitCount = "count" UnitPercent = "percent" UnitScore = "score" )
Units a metric is expressed in. Thresholds are converted to the metric's base unit before comparison.
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.
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 ¶
func RecognizedCriterionMetrics ¶
func RecognizedCriterionMetrics() []string
RecognizedCriterionMetrics returns the canonical metric names a criterion can use, sorted — for error messages and UI hints.
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. At close each one is checked against the cycle's
// computed metrics (EvaluateCharter in criteria.go) and the verdicts are
// stored on ctem_cycles.charter_evaluation.
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 CharterEvaluation ¶
type CharterEvaluation struct {
EvaluatedAt time.Time `json:"evaluated_at"`
Criteria []CriterionEvaluation `json:"criteria"`
Met int `json:"met"`
Unmet int `json:"unmet"`
NotMeasurable int `json:"not_measurable"`
// CompletionRate is met / (met + unmet) × 100, rounded to 2 decimals.
// Nil when no criterion was measurable.
CompletionRate *float64 `json:"completion_rate,omitempty"`
}
CharterEvaluation is the result of checking every success criterion of a cycle's charter at close. Stored on ctem_cycles.charter_evaluation.
func EvaluateCharter ¶
func EvaluateCharter(criteria []CharterSuccessCriterion, metrics CycleMetricSet, now time.Time) CharterEvaluation
EvaluateCharter checks every success criterion against the cycle's metrics. Criteria that are entirely blank are skipped.
type CharterExclusion ¶ added in v0.6.0
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 CriterionEvaluation ¶
type CriterionEvaluation struct {
Name string `json:"name"`
Metric string `json:"metric"`
Target string `json:"target"`
// MetricKey is the cycle metric the criterion resolved to (empty when
// the metric name was not recognized).
MetricKey string `json:"metric_key,omitempty"`
// Comparator is one of <=, <, >=, >, = (empty when the target did not
// parse).
Comparator string `json:"comparator,omitempty"`
// Threshold is the target converted to Unit.
Threshold *float64 `json:"threshold,omitempty"`
// Actual is the measured value in Unit (nil when there was no data).
Actual *float64 `json:"actual,omitempty"`
Unit string `json:"unit,omitempty"`
Outcome CriterionOutcome `json:"outcome"`
// Reason explains a not_measurable outcome.
Reason string `json:"reason,omitempty"`
}
CriterionEvaluation is the persisted verdict for one charter criterion. Name/Metric/Target echo the charter as written; the remaining fields show how it was interpreted, so a verdict can always be checked by hand.
func EvaluateCriterion ¶
func EvaluateCriterion(c CharterSuccessCriterion, metrics CycleMetricSet) CriterionEvaluation
EvaluateCriterion checks one criterion against the cycle's metric set.
type CriterionOutcome ¶
type CriterionOutcome string
CriterionOutcome is the verdict for one success criterion.
const ( CriterionMet CriterionOutcome = "met" CriterionUnmet CriterionOutcome = "unmet" CriterionNotMeasurable CriterionOutcome = "not_measurable" )
type Cycle ¶
type Cycle struct {
// contains filtered or unexported fields
}
Cycle represents a CTEM assessment cycle.
func ReconstituteCycle ¶
ReconstituteCycle recreates from persistence.
func (*Cycle) Activate ¶
Activate transitions from planning to active. This should trigger scope snapshot creation externally.
func (*Cycle) Close ¶
Close transitions from review to closed. Metrics should be computed externally and stored in ctem_cycle_metrics.
func (*Cycle) SetCharter ¶
SetCharter updates the cycle charter (only in planning status).
func (*Cycle) SetScopeRefinementNotes ¶ added in v0.6.0
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) StartReview ¶
StartReview transitions from active to review.
func (*Cycle) Status ¶
func (c *Cycle) Status() CycleStatus
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 ¶
CycleMetric holds a computed metric for a cycle.
type CycleMetricSet ¶ added in v0.6.0
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)
// GetSuccessCriteria returns the success criteria on the cycle's
// charter. Returns shared.ErrNotFound for a foreign cycle.
GetSuccessCriteria(ctx context.Context, tenantID, cycleID shared.ID) ([]CharterSuccessCriterion, error)
// SaveCharterEvaluation stores the close-time verdicts on the cycle.
// Returns shared.ErrNotFound (and writes nothing) for a foreign cycle.
SaveCharterEvaluation(ctx context.Context, tenantID, cycleID shared.ID, ev CharterEvaluation) 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.