Files
skillshare/internal/plugin/pi_extensions_match.go
T
Willie ccc0fbdf74 feat(pi): manage individual extensions per target (#350)
* feat(pi): manage individual extensions per target

Keep package lifecycle in Plugins while letting global, account, and project Pi targets configure individual extensions with reviewed, lossless changes. Project overrides save only project settings and never grant trust.

Bind edits to native version contracts, settings snapshots, source ownership, and discovery; preserve unrelated resources and enforce renewable native locks, stale rejection, and backups. Verify Pi 0.99.2 and 1.0.0 without running extension factories.

Simplify configured-state UI and distinguish Skillshare-managed packages from native tool registrations, with localized guidance and regression coverage. Closes #342.

* fix(pi): address project extensions review findings

Keep exact project delta rules visible when their extension files are missing so users can remove stale rules without changing global settings or trust.

Show the project Extensions tab only when its generated Pi target resolves. Cover missing and agents-only projects, absent targets, and another project target with regression tests.

* fix(pi): recognize official Windows account launchers

Accept pi.cmd and pi.exe account launcher names on Windows, including case-insensitive and native Windows paths, before probing the existing exact-version gate. Preserve POSIX behavior and never probe unrecognized forks or stacked launcher suffixes.

Add platform-name and account-gate regressions covering verified, unsupported, and missing CLI versions. Focused race tests, make check, and Windows amd64/arm64 test cross-compilation pass; real Windows runtime remains unverified because the UTM guest is stopped.

* fix(pi): align rule removal and backup descriptions

Offer Remove rule only for owned exact +/- rules, not project delta globs that the apply path cannot remove. Keep supported glob rows switchable and cover delta and deltaOnly forms with RED/GREEN regressions.

Describe retained artifacts as extension-list and file-hash records rather than complete settings backups in English, all four website translations, and the implementation report.

* fix(pi): discard records for aborted extension applies

Require a validated preview and owned native lock before recording an extension change. Discard only the newly created record if final revalidation, lock ownership, or the atomic settings write fails; retain successful history and propagate cleanup errors with the original failure.

Keep discovery revalidation after record I/O so cleanup does not weaken the write-boundary guard. Cover global and new/existing project settings with nine RED/GREEN regressions, including injected commit failures. Align English and translated docs with the retained-record lifecycle.

* fix(pi): retain anonymous global packages in projects

Keep ordered anonymous registrations separate from the proven-identity map so unsupported query-bearing sources remain visible as redacted read-only packages, rather than being dropped or associated with a project override.

Preserve first-global-entry precedence for known identities. Add RED/GREEN coverage for string and object registrations, query/userinfo redaction, project entries, zero-write refusal, ordering, and continued editing of known packages.

* fix(pi): deduplicate only proven project identities

Exclude unresolved identities from project duplicate tracking. Preserve each anonymous registration as sourceUnknown instead of pretending unrelated query-bearing URLs are the same package.

Cover mixed string/object anonymous project sources, redaction and zero-write refusals, retained anonymous globals, and last-project-entry precedence for known packages. Verify known project entries remain editable.

* fix(pi): guard unresolved package precedence

An unresolved earlier global registration may own a later known package, and an unresolved later project registration may supersede an earlier known entry. Keep those potentially shadowed entries and inherited deltas Unknown/read-only instead of offering edits to ignored registrations. Do not infer identities by dropping credentials or queries.

Cover both ordering directions for global, inherited, project-owned, and delta views with RED/GREEN tests. Execute native query identity and dedupe evidence on Pi 0.99.2 and 1.0.0 through core and CLI-bundle contracts, now 28 scenarios and 87 assertions each. Align docs and evidence while retaining independent anonymous entries.

* fix(pi): propagate unreadable source ambiguity

Treat badSource entries as unresolved instead of letting an unreadable source expose editable later global registrations. Preserve the same uncertainty in inherited globals and before unreadable later project entries.

Add twelve global/inherited/project regressions for null, empty, whitespace and invalid UTF-8 sources. Native core and CLI-bundle evidence confirms invalid UTF-8 can decode to and own the same identity as a later valid source on both supported Pi versions; the executed contracts now pass 29 scenarios and 90 assertions.

* feat(pi): preserve filtered imports and reclaim stale locks

Adopt native object registrations without changing their configured resources. Keep lossless entries in scoped private state, retain current rules across lifecycle operations, restore filters before native installation, and preserve pending retries after failures.

Reclaim only unchanged empty directories after the native stale threshold, retaining renewed, replaced, nonempty and non-directory locks. Verify exact supported Pi contracts and keep unsupported cases read-only.

* docs(pi): record filtered import verification after branch sync

Document the current merged UI test count and repeated checks while retaining the native and visual verification limitations.

* docs(pi): clarify stale acquisition exception

Keep the lock safety summary consistent with the approved acquisition policy while preserving strict ownership for renewal and release.

* fix(pi): keep legacy npm fallback installations unknown

A missing user-scoped managed npm root cannot prove a package is absent because native Pi may use a legacy global npm or pnpm root. Keep it read-only without probing host-global state, while retaining missing-state behavior for project npm packages.

* fix(pi): preserve project precedence and batch restore ownership

Retain empty winning overrides when deleting them could expose older resource filters. Advance filtered restore batches only to exact writes made by the same Apply, while rejecting external changes and retaining failed native retries. Match Pi strict-false autoload semantics instead of treating null as a delta.
2026-10-03 20:47:20 +08:00

231 lines
6.0 KiB
Go

package plugin
import (
"path"
"strings"
"unicode/utf8"
)
// piTri is a selection that may be unknown: Skillshare evaluates Pi's resource
// filters only where it reproduces Pi exactly, and says so everywhere else.
type piTri int
const (
piUnknown piTri = iota
piOn
piOff
)
func (t piTri) String() string {
switch t {
case piOn:
return "loads"
case piOff:
return "skipped"
}
return "unknown"
}
func triNot(t piTri) piTri {
switch t {
case piOn:
return piOff
case piOff:
return piOn
}
return piUnknown
}
func triAnd(a, b piTri) piTri {
if a == piOff || b == piOff {
return piOff
}
if a == piOn && b == piOn {
return piOn
}
return piUnknown
}
// piGlobSupported reports whether a non-exact Pi pattern is in the grammar this
// package reproduces: '/'-separated segments of literals with '*' and '?' only,
// as minimatch 10 matches them without options (dot files need a literal dot).
// Globstars, braces, classes, extglobs, escapes, comments, negation and '.' or
// '..' segments are left to Pi. The golden test checks this against Pi's minimatch.
func piGlobSupported(pattern string) bool {
if pattern == "" || strings.ContainsAny(pattern, "[]{}()|\\") || strings.Contains(pattern, "**") ||
strings.HasPrefix(pattern, "#") || strings.HasPrefix(pattern, "!") {
return false
}
for i, seg := range strings.Split(pattern, "/") {
if seg == "" && i == 0 {
continue // absolute pattern
}
if seg == "" || seg == "." || seg == ".." {
return false
}
}
return true
}
// piGlobMatch matches subject against a supported pattern, segment by segment.
func piGlobMatch(pattern, subject string) piTri {
if piCountsDiffer(pattern, subject) {
return piUnknown
}
ps, ss := strings.Split(pattern, "/"), strings.Split(subject, "/")
if len(ps) != len(ss) {
return piOff
}
for i := range ps {
// Without the dot option, '*' and '?' never match a leading dot.
if strings.HasPrefix(ss[i], ".") && !strings.HasPrefix(ps[i], ".") {
return piOff
}
if ok, err := path.Match(ps[i], ss[i]); err != nil || !ok {
return piOff
}
}
return piOn
}
// piCountsDiffer reports whether Go's '?' (one rune) and minimatch's '?' (one
// UTF-16 code unit) can disagree for this pair: an astral character, or a name
// that is not UTF-8 and so is decoded differently.
func piCountsDiffer(pattern, subject string) bool {
if !strings.Contains(pattern, "?") {
return false
}
if !utf8.ValidString(pattern) || !utf8.ValidString(subject) {
return true
}
return strings.ContainsFunc(pattern+subject, func(r rune) bool { return r > 0xFFFF })
}
// piGlobMatches is Pi's matchesAnyPattern for one non-SKILL.md file: the pattern
// is tried against the path relative to the package, the base name, and the
// absolute path.
func piGlobMatches(pattern, rel, abs string) piTri {
if !piGlobSupported(pattern) {
return piUnknown
}
result := piOff
for _, subject := range []string{rel, path.Base(rel), abs} {
switch piGlobMatch(pattern, subject) {
case piOn:
return piOn
case piUnknown:
result = piUnknown
}
}
return result
}
// piExactMatches is Pi's matchesAnyExactPattern: a plain comparison after
// dropping a leading "./".
func piExactMatches(pattern, rel, abs string) bool {
pattern = strings.TrimPrefix(pattern, "./")
return pattern == rel || pattern == abs
}
// piExactRule reports whether a rule is an exact "+path" or "-path" for the file
// at rel, written relative or as its absolute path, as Pi compares them.
func piExactRule(rule, rel, abs string) bool {
return (strings.HasPrefix(rule, "+") || strings.HasPrefix(rule, "-")) && piExactMatches(rule[1:], rel, abs)
}
type piEvaluation struct {
state piTri
exact string // the last exact rule that decided the file, if any
globs []string // the include and ! rules that match it, or may
}
// piEvaluate is Pi's applyPatterns for one file of a non-empty rule list:
// includes (or everything), then ! excludes, then +exact, then -exact.
func piEvaluate(rules []string, rel, abs string) piEvaluation {
var e piEvaluation
included, hasInclude := piOff, false
excluded := piOff
forceOn, forceOff := false, false
for _, rule := range rules {
switch {
case strings.HasPrefix(rule, "+"):
if piExactMatches(rule[1:], rel, abs) {
forceOn, e.exact = true, rule
}
case strings.HasPrefix(rule, "-"):
if piExactMatches(rule[1:], rel, abs) {
forceOff, e.exact = true, rule
}
case strings.HasPrefix(rule, "!"):
if m := piGlobMatches(rule[1:], rel, abs); m != piOff {
e.globs = append(e.globs, rule)
if excluded != piOn {
excluded = m
}
}
default:
hasInclude = true
if m := piGlobMatches(rule, rel, abs); m != piOff {
e.globs = append(e.globs, rule)
if included != piOn {
included = m
}
}
}
}
if !hasInclude {
included = piOn
}
e.state = triAnd(included, triNot(excluded))
if forceOn {
e.state = piOn
}
if forceOff {
e.state = piOff
// "-" wins over "+", so name it as the deciding rule.
for _, rule := range rules {
if strings.HasPrefix(rule, "-") && piExactMatches(rule[1:], rel, abs) {
e.exact = rule
}
}
}
return e
}
// piEvaluateDelta is Pi's applyAutoloadDisabledPatterns for one file of a
// project autoload:false entry: the last matching rule decides; no match means
// the file is not named here (piOff with named false).
func piEvaluateDelta(rules []string, rel, abs string) (state piTri, named bool, rule string) {
for _, r := range rules {
target, on, exact := r, true, false
switch {
case strings.HasPrefix(r, "+"):
target, exact = r[1:], true
case strings.HasPrefix(r, "-"):
target, on, exact = r[1:], false, true
case strings.HasPrefix(r, "!"):
target, on = r[1:], false
}
var m piTri
if exact {
m = piOff
if piExactMatches(target, rel, abs) {
m = piOn
}
} else {
m = piGlobMatches(target, rel, abs)
}
switch m {
case piOn:
named, rule, state = true, r, piOff
if on {
state = piOn
}
case piUnknown:
// A later rule may still decide; until one does, the result is unknown.
named, rule, state = true, r, piUnknown
}
}
return state, named, rule
}