Files
skillshare/internal/audit/rules_list.go
T
Rusty ShacklefordandWillie 60e19f96d5 feat(project): support a visible skillshare/ project directory (#256) (#258)
* fix(project): refuse to re-init a project that lost its config.yaml

Every project-mode command auto-initializes when .skillshare/config.yaml
is missing. That is right for a repository with no project directory at
all, and for the shared skills repo produced by 'init -p --config local',
which gitignores config.yaml so each developer regenerates their own.

It was wrong for the case in between. A .skillshare/ that already held
skills or agents, whose config.yaml was simply gone, was re-initialized
into an empty config. Every configured target was dropped, the target
symlinks were left behind pointing at a project the config no longer
described, and the command exited 0. Nothing said anything had happened.

Add ensureProjectConfig, which replaces the open-coded auto-init at every
project command entry point. It initializes as before when there is no
project directory, and when config.yaml is gitignored, so both intentional
cases keep working untouched. When the directory holds skills or agents
and its config is neither present nor gitignored, it now returns an error
pointing at version control or an explicit 'skillshare init -p' instead of
writing over the project.

The gitignore check is treated as inconclusive on error, so a repository
that cannot be inspected is guarded rather than overwritten.

* feat(project): support a visible skillshare/ project directory

Project mode is identified only by .skillshare/config.yaml, and trash,
backups, logs and audit-rules.yaml anchor to that same hidden directory.
The sources option (#153) made project content relocatable, but the
marker and operational state stay hidden, so repositories that treat
skills as reviewable content still carry a hidden directory whose only
job is to hold config.yaml.

Resolve the project directory through a new leaf package that checks
.skillshare/config.yaml first and skillshare/config.yaml second, and
derive every config, state, source-default and gitignore path from the
result. The hidden name wins whenever both exist, so an existing project
never moves and no migration is needed. The package imports nothing else
internal because internal/audit cannot import internal/config without a
cycle.

Add init -p --visible to create the visible layout. Default init -p
behaviour and output are unchanged.

Two ambiguities the visible name introduces:

- The global config directory is also called skillshare
  (<config-home>/skillshare), so the two places that infer scope from a
  config path now exclude the global location by full path rather than
  by directory name. TestLogDir_Global asserted a fixture path without
  declaring a config home, which hid this; it now sets XDG_CONFIG_HOME.
- An unrelated directory named skillshare/ must not be adopted as a
  partially initialized project, so the visible name is only claimed
  when it carries a marker of its own: a skills/ or agents/ directory,
  or a .gitignore that ignores config.yaml.

The missing-config guard added in the previous commit is generalized to
resolve through the new package, so it covers both layouts. The
gitignored-config marker matters there too. A repository shared by
'init -p --visible --config local' before any skill was committed clones
with nothing but that .gitignore, because git drops the empty skills/
and agents/ directories; recognizing it keeps the repair pointed at the
visible directory instead of writing a hidden one beside it.

Refs #256

* fix(project): reconcile visible directory support with main

Consolidate the missing-config guard and regression tests already merged in #260. Preserve both directory layouts and document and test resyncing target links after a rename. Follow-up for #258.

---------

Co-authored-by: Willie <egg358358@gmail.com>
2026-09-05 12:07:00 +08:00

205 lines
5.4 KiB
Go

package audit
import (
"path/filepath"
"sort"
"skillshare/internal/projectdir"
)
// CompiledRule is the public view of a rule for listing/display.
type CompiledRule struct {
ID string `json:"id"`
Severity string `json:"severity"`
Pattern string `json:"pattern"`
Message string `json:"message"`
Regex string `json:"regex"`
Exclude string `json:"exclude,omitempty"`
Enabled bool `json:"enabled"`
Source string `json:"source"` // "builtin", "global", "project"
}
// PatternGroup summarizes rules grouped by pattern name.
type PatternGroup struct {
Pattern string `json:"pattern"`
Total int `json:"total"`
Enabled int `json:"enabled"`
Disabled int `json:"disabled"`
MaxSeverity string `json:"maxSeverity"`
}
// ListRules returns all rules (builtin + global overrides) with enable/disable status.
// Disabled rules are included with Enabled=false.
func ListRules() ([]CompiledRule, error) {
base := builtinYAML()
globalUser, err := loadUserRules(globalAuditRulesPath())
if err != nil {
return nil, err
}
return buildCompiledList(base, globalUser, nil)
}
// ListRulesWithProject returns all rules (builtin + global + project overrides)
// with enable/disable status.
func ListRulesWithProject(projectRoot string) ([]CompiledRule, error) {
base := builtinYAML()
globalUser, err := loadUserRules(globalAuditRulesPath())
if err != nil {
return nil, err
}
projectPath := filepath.Join(projectdir.Resolve(projectRoot), auditRulesFileName)
projectUser, err := loadUserRules(projectPath)
if err != nil {
return nil, err
}
return buildCompiledList(base, globalUser, projectUser)
}
// buildCompiledList merges base, global user, and project user rule layers
// and produces the full listing. Disabled rules are included with Enabled=false.
func buildCompiledList(base, globalUser, projectUser []yamlRule) ([]CompiledRule, error) {
// Track which IDs are overridden at each layer.
globalOverrides := indexByID(globalUser)
projectOverrides := indexByID(projectUser)
// Track pattern-level directives at each layer.
globalPatternOverrides := patternLevelSet(globalUser)
projectPatternOverrides := patternLevelSet(projectUser)
// Merge layers: base → global → project
merged := base
if globalUser != nil {
merged = mergeYAMLRules(merged, globalUser)
}
if projectUser != nil {
merged = mergeYAMLRules(merged, projectUser)
}
var result []CompiledRule
for _, yr := range merged {
// Skip pattern-level directives — they're not real rules.
if isPatternLevel(yr) {
continue
}
enabled := yr.Enabled == nil || *yr.Enabled
sev := yr.Severity
if s, err := NormalizeSeverity(sev); err == nil {
sev = s
}
source := determineSource(yr.ID, yr.Pattern, globalOverrides, projectOverrides,
globalPatternOverrides, projectPatternOverrides)
result = append(result, CompiledRule{
ID: yr.ID,
Severity: sev,
Pattern: yr.Pattern,
Message: yr.Message,
Regex: yr.Regex,
Exclude: yr.Exclude,
Enabled: enabled,
Source: source,
})
}
return result, nil
}
// determineSource returns the source layer for a rule.
func determineSource(id, pattern string,
globalIDs, projectIDs map[string]bool,
globalPatterns, projectPatterns map[string]bool,
) string {
// Project-level ID override takes precedence.
if projectIDs[id] {
return "project"
}
// Project-level pattern override.
if projectPatterns[pattern] {
return "project"
}
// Global-level ID override.
if globalIDs[id] {
return "global"
}
// Global-level pattern override.
if globalPatterns[pattern] {
return "global"
}
return "builtin"
}
// indexByID returns a set of rule IDs present in a yamlRule slice (non-pattern-level only).
func indexByID(rules []yamlRule) map[string]bool {
m := make(map[string]bool)
for _, r := range rules {
if !isPatternLevel(r) && r.ID != "" {
m[r.ID] = true
}
}
return m
}
// patternLevelSet returns the set of pattern names targeted by pattern-level directives.
func patternLevelSet(rules []yamlRule) map[string]bool {
m := make(map[string]bool)
for _, r := range rules {
if isPatternLevel(r) {
m[r.Pattern] = true
}
}
return m
}
// PatternSummary groups rules by pattern and returns summary stats.
// Sorted by severity (most severe first), then by pattern name.
func PatternSummary(rules []CompiledRule) []PatternGroup {
groups := make(map[string]*PatternGroup)
for _, r := range rules {
g, ok := groups[r.Pattern]
if !ok {
g = &PatternGroup{Pattern: r.Pattern, MaxSeverity: r.Severity}
groups[r.Pattern] = g
}
g.Total++
if r.Enabled {
g.Enabled++
} else {
g.Disabled++
}
if SeverityRank(r.Severity) < SeverityRank(g.MaxSeverity) {
g.MaxSeverity = r.Severity
}
}
result := make([]PatternGroup, 0, len(groups))
for _, g := range groups {
result = append(result, *g)
}
sort.Slice(result, func(i, j int) bool {
ri := SeverityRank(result[i].MaxSeverity)
rj := SeverityRank(result[j].MaxSeverity)
if ri != rj {
return ri < rj
}
return result[i].Pattern < result[j].Pattern
})
return result
}
// UniquePatterns returns a sorted list of distinct pattern names from builtin rules.
func UniquePatterns() []string {
seen := make(map[string]bool)
for _, yr := range builtinYAML() {
if yr.Pattern != "" {
seen[yr.Pattern] = true
}
}
result := make([]string, 0, len(seen))
for p := range seen {
result = append(result, p)
}
sort.Strings(result)
return result
}