Files
Rusty Shackleford da3383ed5f fix(plugins): separate shared intent from local installation state (#660)
* fix(plugins): separate shared intent from machine-local receipts

Shared configs currently carry native paths, reviewed snapshots and pending
failures, so one host can publish local progress over another host's target
selection. Persist versioned declarations separately from local applied and
pending receipts, and reconcile reviewed installs, imports and cleanup against
this machine's native inventory without rewriting intent during sync/update.

Keep snapshot names and adapter safeguards, move the operation lock locally,
validate legacy adoption with local evidence, and invalidate approval on local
state or native-context changes. Preserve source recipes after native adoption,
require local import for absent native-only targets, and document the shared
writer upgrade boundary in schemas and translated references.

Cover two-host behavior, generated legacy fixtures, failure/recovery, stale
intent, cleanup, npm recipes and the existing CLI/API/UI consumers with focused
resource-capped tests. Fixes #651.

* fix(plugins): preserve intent and ownership across host transitions

Repeat-add must retain shared target selection, and update previews must resolve
the requested ref before reviewing fresh or replacement installs. Keep disabled
targets on the uninstall path and reject refs unsupported by native-only/npm
intent before they can produce invalid shared declarations.

Block changed-context add/import before Pi registration preparation so a new
account cannot overwrite the old receipt. Preserve unresolved legacy bindings
as passive private proof candidates before rewriting shared YAML, retaining
original intent/store for later verified adoption and cleanup. Never compose
these hints as executable state, and persist their explicit resolution.

Cover the five review classes, native/private failure boundaries, requested-ref
retry, and original-context hint proofs with isolated focused regressions.
Keep local format v1 and baseline account validation unchanged. Refs #651.

* fix(plugins): allow receipt-only orphan cleanup to complete

An installation already removed on this host can retain a local receipt when
another host removes or replaces shared intent. Sync correctly plans forget,
but native command verification rejects that metadata-only action and blocks
all targets before the receipt can be cleared.

Exclude forget from native command verification while retaining host inventory
checks and OMP scoped cleanup preparation. The existing completion path then
persists receipt deletion, including pending work and passive legacy hints.

Cover the cross-host disable/re-enable/remove walk, five native adapters,
failed work with a legacy hint, and absent source replacement alongside a
healthy target. Assert Apply completion, unchanged shared bytes/mtime, and a
quiet second sync. Refs #651.

* fix(plugin): reconcile ref intent across inventory consumers

Validate explicit ref changes before disabled targets can save them and reuse
one reviewed discovery throughout a preview. Surface shared ref changes as local
reconciliation work while preserving the applied native identity and receipts.

Reuse scoped legacy proofs for Pi extension ownership and make full inventory
the dashboard's authoritative package/host pair. Cover invalid and replacement
refs, read-only ownership, and shared-state properties without new persisted
state or dependencies.

* test(plugin): repair and consolidate host-state fixtures

Create source intent and a pending imported Claude update through supported
operations so direct and batch updates exercise the intended fixture. Keep the
marketplace-loss case locally owned before testing its skipped reinstall.

Consolidate cross-host repeat-add and requested-ref replacement/orphan retries
at their existing owners, retaining failure recovery and shared-byte checks.
Trim duplicate HTTP and translated-text assertions from consumer tests.

* fix(plugin): reconcile legacy snapshot reads and native imports

Resolve legacy snapshot ownership through existing scoped proofs before listing,
reading or discovering cached source files. Keep adoption read-only and limit
proof work to the requested package and targets; current receipts need no CLI.

Only preserve reviewed source metadata on reimport when intent remains source
managed. Native-only intent must not resurrect an older Git source after a
same-ID local import. Retain identity mismatch and reviewed-source safeguards.

Remove the unused source-folding helper left by the old shared runtime writer.

* Preserve reviewed package versions locally

* Fix reviewed package version lifecycle

* fix(plugin): report missing local imports in doctor

Show the local-import instruction instead of claiming a skipped imported
plugin is healthy. Preserve the missing-CLI warning and shared config bytes.

Keep fixture native settings inside scratch XDG directories and serialize
the fake CLI calls used by concurrent inventories. Update assertions to
separate shared declarations from local versions and native IDs, and align
the raw-write audit with private plugin state and operation locks.

* test(plugin): use declarations for doctor source fixture

The missing-CLI case has no native ID, so encode it with the version 2
declaration schema. Keep the native-only import case in legacy syntax.

* fix(plugin): install shared sources from reviewed snapshots

When a source target is already declared, first sync must install its
reviewed local snapshot even if the native client has a package from the
same marketplace. Keep explicit add adoption and native-only import intact.

Extend the existing two-host adoption check to cover an independent native
installation on the second host and verify a quiet subsequent sync.

* fix(plugin): preserve reviewed retries and native collision boundaries

Retry a pending source update through the existing reviewed update path,
so a rolled-back native failure cannot clear progress at the old snapshot.
Record default-source versions for add, sync, and update while retaining
the recipe fingerprint and generic-version checks for target overrides.

Keep explicit native adoption, but block shared Claude sources when an
independent same-name native plugin could shadow their hooks. Extract the
existing adoption decision so the preview function becomes smaller.

* test(plugin): respect OMP update safety in version control

Check generic and target versions during review, then confirm the existing
OMP upgrade guard preserves the installed and default-source versions.

* fix(plugin): declare first local native imports explicitly

A first local import into a shared source target now changes that target
to native-only intent while preserving its sync selection. Verified source
reimports retain their reviewed source and the preview discloses conversion.

Cover the explicit import, local sync, and other-host cleanup flow, and
remove the unconsumed internal observation assertion from the OMP test.

* docs(plugin): explain first local import intent changes

Describe the shared native-only target conversion and its effect on other
machines, while distinguishing verified source reimports.

* fix(plugin): verify checked sources before native reinstalls

A checked update that becomes an install after native removal must still
match the source digest the user approved. Reject moved or unchecked
sources before native work, and allow a stable approved reinstall.

Clear completed reinstalls from dashboard update availability while keeping
failed targets available for retry. Cover both native presence states in
the existing checked-update tests and the dashboard outcome rule.

* fix(plugin): guard replacement before cleanup

* fix(plugin): refresh discovery for each manager action

A later Add action must review the current source even when the manager
previously observed that source. Keep discovery sharing across one action
while ending its cache before the next wizard invocation.

Exercise a fresh source version after an earlier Add preview without TTY
input or native writes, using an unavailable client to stop at review.

* test(plugin): cover desired checks and final update outcomes

Consolidate checked batch approval and dashboard completion tests while
retaining removed-native, digest, version and approval controls. Reproduce
stale shared recipes and failed or unfinished replacement installs.

* test(plugin): make stale source discovery observable

Remove the old repository before native-only and npm desired checks so
those existing cases cannot pass by reading the applied source.

* fix(plugin): check desired source and final outcome

* test(plugin): bind checked updates to the observed recipe

Reproduce a shared candidate change with equal version, commit and digest,
and preserve a freshly checked replacement whose native ID differs. Use
actual check observations in approval and native update controls, reject
missing source identity, and verify the UI carries the observation through.

* fix(plugin): bind checked update to source recipe

* fix(ui): classify npm recipes as Pi packages

* fix(plugin): retain legacy removal intent during migration

Omit pending removals from shared declarations while retaining original local ownership proof so sync retries cleanup.

Verification: focused regression passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* fix(plugin): keep imports local to an existing shared recipe

Adopt a native installation into its local receipt without converting the shared source target or removing other machines installations.

Verification: focused import regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* fix(plugin): capture legacy evidence on first read

Persist passive hints before another machine writes v2 and save verified adoption on reads. Apply reuses preview receipts instead of querying every legacy binding again. Document the per-machine pre-migration read.

Verification: migration regressions passed in isolated Linux Codex container runs, not the devcontainer (GOMAXPROCS=4, -p=4).

* fix(plugin): target named declarations in interactive imports

Offer unresolved package names in dashboard and TUI imports and pass the selected name in single and batch requests. Drop display-only rendered assertions.

Verification: 47 UI tests passed with at most four workers in an isolated Linux Codex container, not the devcontainer.

* fix(plugin): localize shared intent plan guidance

Add message keys for local imports, account changes, cleanup and native collisions across all dashboard locales. Localized guidance contains no CLI flags.

Verification: failing localization regression now passes in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* refactor(plugin): reuse preview inventory and guard apply boundaries

Capture hints on first load without persisting in-memory adoption during preview, keeping approval revisions stable. Apply reuses preview inventory. Reuse accountEnv and guard applyChange plus native write boundaries without inspecting argv.

Verification: migration, receipt, account and sync regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* test(plugin): organize host state coverage around lifecycle scenarios

Group migration, ref drift, account context and cleanup tests behind shared host fixtures and public Preview/Apply assertions. Cover Codex, Cursor, Antigravity and project scopes; add second-machine doctor coverage and the two-machine runbook. Consolidate package-version tests and remove the unused private-record fixture.

Verification: focused plugin regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* docs(plugin): explain local imports and per-machine migration

Document local receipts, per-machine review and commit pinning, config-path state identity and the required legacy read on every machine. Align sharing, doctor, troubleshooting, file-layout and four translated plugin references; restore schema editing guidance.

Verification: context-router check passed. Runtime verification uses an isolated Linux Codex container, not the devcontainer.

* refactor(plugin): separate unrelated review scope

Move project OMP configuration, plugin list ordering, and npm Pi classification to independent local branches based on upstream/main. Keep the shared intent change focused and cover named import selection in the pure flow helper.

The three local branches have passing builds in a Linux Codex container, not the devcontainer, with isolated test homes and capped parallelism.

* perf(plugin): avoid recapturing v2 state on reads

Only compare and persist passive migration hints when legacy bindings exist. Native v2 reads need no state serialization for migration.

Verification: pending removal and first-read/import regressions passed in a Linux Codex container, not the devcontainer, with isolated HOME/XDG/TMPDIR and GOMAXPROCS=4 GOFLAGS=-p=4.

* docs(plugin): clarify native marketplace repair after import

A local import receipt is not a reviewed reinstall source. Correct the remaining troubleshooting instruction and its four translations to require native-client repair, and align the nearby code comment.

Validation: checked against prepareChange, context-router check and git diff --check passed. Verification for this review ran in a Linux Codex container, not the devcontainer.

* fix(plugins): preserve local ownership across shared intent changes

Retain completed legacy migration markers so unchanged v1 YAML cannot
uninstall a later manual reinstall. Serialize read-side hint persistence
with native operations and keep local imports when shared recipes change.
Require explicit dashboard import names and validate recipe identities.

Correct schema descriptions, messages, CLI ref status, translated migration
guidance and runbooks. Add failing-first Preview/Apply regressions and a
real two-ssenv CLI lifecycle script.

* fix(plugins): preserve migration history and show retained import guidance

Mark existing legacy hints and receipts as captured before cleanup so state
from the previous serializer cannot re-adopt a later manual installation.
Keep recipe-change guidance in unchanged sync outcomes and visible dashboard
rows, and resolve nested OpenCode entries through their package manifest.

Cover public migration, ref, account, import and message contracts across
adapters. Correct the real two-host Cursor assertions, explicit dashboard
selection flow, and remaining localized guidance.

* fix(plugins): retain explicit OpenCode entry during import matching

Standalone OpenCode packages can rely on a reviewed explicit entry rather
than an SDK dependency. Preserve that entry when reading native package
identity so matching nested imports remain supported.

* fix(plugins): preserve migrated imports and verify native entry identity

Recognize older native-only receipts by their existing declaration
fingerprint so remote source recipe edits cannot replace migrated imports.
Keep managed npm receipts distinct through their source fingerprints.

Only borrow an ancestor OpenCode package identity when its resolved entry
is the actual registered file. Retain nested and explicit entry support.
Add public two-host migration and mismatching-entry regressions.

* fix(plugins): retain imported ownership through repeated adds

Persist inferred imported ownership when a matching add refreshes the
receipt intent, so later shared recipe changes still preserve local
native installations. Keep the legacy replacement regression aligned
with that ownership contract while retaining removed-intent cleanup.

Reject missing or unstatable absolute OpenCode entries before identity
matching rather than falling back to the file name. Cover both paths
through public Preview and Apply regressions.

* test(plugins): isolate OpenCode adapter fixtures from host config

Keep native registration fixtures inside their fake agent home by setting
XDG_CONFIG_HOME and clearing inherited OpenCode overrides. Ambient config
writes can otherwise leak into config-discovery tests in other packages.

Cover the XDG, file, directory and inline override cases with temporary
config sentinels, while retaining the existing MCP listing expectation.

* fix(plugin): let local imports return to the shared source

Add a local unimport action that removes only this machine’s installation and receipt while preserving the shared source declaration. Keep retained-import guidance visible across matching adds, list, doctor and dashboard consumers.

Avoid idle OMP guidance and unchanged legacy-read locks, preserve localized errors, keep import identity checks offline, and normalize OpenCode drive URLs. Cover the A/B transition and align translations, runbooks and environment cleanup.

* fix(plugin): complete unimport validation and guidance

Reject missing targets before planning local unimports and share per-target eligibility with the wizard. Make native uninstall effects explicit in help and translated docs, preserve structured update guidance, and cover error paths and shell completion.
2026-10-31 04:23:20 +08:00

842 lines
34 KiB
Go

package plugin
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
// The fixtures follow scripts/pi/phase0-contract.mjs: one local package with three
// extensions, a skill and a prompt, under an isolated HOME and agent directory.
type piFixture struct {
t *testing.T
home string
agentDir string
pkg string
svc *Service
version string
}
func newPiFixture(t *testing.T) *piFixture {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
agentDir := filepath.Join(home, ".pi", "agent")
t.Setenv("PI_CODING_AGENT_DIR", agentDir)
f := &piFixture{t: t, home: home, agentDir: agentDir, pkg: filepath.Join(home, "pkgs", "tools"), version: "0.99.2"}
writeTree(t, f.pkg, map[string]string{
"package.json": `{"name":"tools"}`,
"extensions/a.ts": "throw new Error('never imported')",
"extensions/b.ts": "throw new Error('never imported')",
"extensions/c.ts": "throw new Error('never imported')",
"skills/review/SKILL.md": "---\nname: review\ndescription: fixture\n---\n",
"prompts/commit.md": "fixture\n",
})
f.svc = &Service{ConfigPath: filepath.Join(home, "config.yaml"), StateDir: filepath.Join(home, "state"), Run: func(_ context.Context, _ string, _ []string, bin string, args ...string) ([]byte, error) {
if len(args) == 1 && args[0] == "--version" && f.version != "" {
return []byte(f.version + "\n"), nil
}
return nil, errors.New("not found: " + bin)
}}
return f
}
func writeTree(t *testing.T, root string, files map[string]string) {
t.Helper()
for rel, content := range files {
p := filepath.Join(root, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
}
func (f *piFixture) writeJSON(file string, v any) {
f.t.Helper()
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
f.t.Fatal(err)
}
writeTree(f.t, filepath.Dir(file), map[string]string{filepath.Base(file): string(data)})
}
func (f *piFixture) global(v any) { f.writeJSON(filepath.Join(f.agentDir, "settings.json"), v) }
func (f *piFixture) view(target string) *PiExtensionsView {
f.t.Helper()
v, err := f.svc.PiExtensions(context.Background(), target)
if err != nil {
f.t.Fatal(err)
}
return v
}
// selections maps "path:selection" for one package, like the contract's pick().
func selections(p PiExtensionPackage) []string {
out := []string{}
for _, r := range p.Rows {
out = append(out, r.Path+":"+r.Selection)
}
return out
}
func TestPiMissingManagedNpmRootDoesNotClaimLegacyIsMissing(t *testing.T) {
for _, scope := range []string{"user", "project"} {
t.Run(scope, func(t *testing.T) {
f := newPiFixture(t)
p := openPiPackage("npm:@fixture/legacy@1.2.3", f.agentDir, filepath.Join(f.home, "project", ".pi"), scope)
if scope == "user" {
if p.install != "unknown" || p.problem != "sourceUnknown" {
t.Fatalf("legacy fallback was called missing: %+v", p)
}
f.global(map[string]any{"packages": []any{map[string]any{"source": "npm:@fixture/legacy@1.2.3", "extensions": []string{"-absent.ts"}}}})
v := f.view("pi")
pkg := v.Packages[0]
if pkg.Install != "unknown" || pkg.Problem != "sourceUnknown" || len(pkg.Rows) != 0 {
t.Fatalf("uncertain npm installation offered exact missing rows: %+v", pkg)
}
} else if p.install != "missing" || p.problem != "notInstalled" {
t.Fatalf("project has no legacy fallback: %+v", p)
}
})
}
}
func assertRows(t *testing.T, got []string, want ...string) {
t.Helper()
if len(got) != len(want) {
t.Fatalf("rows %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("rows %v, want %v", got, want)
}
}
}
func TestPiExtensionsGlobalSelectionMatchesContract(t *testing.T) {
cases := []struct {
name string
entry any
want []string
}{
{"S1 string entry loads everything", "PKG", []string{"extensions/a.ts:loads", "extensions/b.ts:loads", "extensions/c.ts:loads"}},
{"S2 -path excludes one exact path", map[string]any{"source": "PKG", "extensions": []string{"-extensions/b.ts"}}, []string{"extensions/a.ts:loads", "extensions/b.ts:skipped", "extensions/c.ts:loads"}},
{"S3 [] disables every extension", map[string]any{"source": "PKG", "extensions": []string{}}, []string{"extensions/a.ts:skipped", "extensions/b.ts:skipped", "extensions/c.ts:skipped"}},
{"S4 include glob then !glob", map[string]any{"source": "PKG", "extensions": []string{"extensions/*.ts", "!extensions/c.ts"}}, []string{"extensions/a.ts:loads", "extensions/b.ts:loads", "extensions/c.ts:skipped"}},
{"S5 + beats !, - beats +", map[string]any{"source": "PKG", "extensions": []string{"!extensions/*.ts", "+extensions/a.ts", "+extensions/b.ts", "-extensions/b.ts"}}, []string{"extensions/a.ts:loads", "extensions/b.ts:skipped", "extensions/c.ts:skipped"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
f := newPiFixture(t)
entry := c.entry
if s, ok := entry.(string); ok && s == "PKG" {
entry = f.pkg
} else {
m := entry.(map[string]any)
m["source"] = f.pkg
}
f.global(map[string]any{"packages": []any{entry}})
v := f.view("pi")
if !v.Editable || v.Scope != "global" || len(v.Packages) != 1 {
t.Fatalf("view: %+v", v)
}
assertRows(t, selections(v.Packages[0]), c.want...)
for _, r := range v.Packages[0].Rows {
if r.Editable == (r.Origin == "emptyList") {
t.Fatalf("%s: editable %v on a verified Pi", r.Path, r.Editable)
}
}
})
}
}
func TestPiExtensionsVersionGate(t *testing.T) {
for _, c := range []struct{ version, readOnly string }{{"0.99.2", ""}, {"1.0.0", ""}, {"1.0.1", ""}, {"1.10.0", ""}, {"0.99.1", piReadOnlyUnsupported}, {"0.85.0", piReadOnlyUnsupported}, {"1.0.1-beta.1", piReadOnlyUnsupported}, {"pi 1.0.1", piReadOnlyUnsupported}, {"", piReadOnlyNoCLI}} {
f := newPiFixture(t)
f.version = c.version
f.global(map[string]any{"packages": []any{f.pkg}})
v := f.view("pi")
if v.ReadOnly != c.readOnly || v.Editable != (c.readOnly == "") {
t.Fatalf("%q: readOnly=%q editable=%v", c.version, v.ReadOnly, v.Editable)
}
if c.readOnly != "" && v.Packages[0].Rows[0].Editable {
t.Fatalf("%q: a row is editable on an unsupported Pi", c.version)
}
}
}
func TestPiCLIIsNative(t *testing.T) {
for _, c := range []struct {
goos, cli string
want bool
}{
{"linux", "pi", true},
{"linux", "/usr/local/bin/pi", true},
{"darwin", "/opt/homebrew/bin/pi", true},
{"linux", "pi.cmd", false},
{"darwin", "pi.exe", false},
{"linux", "PI", false},
{"windows", "pi", true},
{"windows", "pi.cmd", true},
{"windows", "pi.exe", true},
{"windows", `C:\Users\tester\AppData\Roaming\npm\pi.cmd`, true},
{"windows", `C:\Program Files\Pi\PI.EXE`, true},
{"windows", "C:/tools/Pi.CmD", true},
{"windows", `\\server\tools\pi.exe`, true},
{"windows", "omo.cmd", false},
{"windows", `C:\tools\senpi.exe`, false},
{"windows", "not-pi.exe", false},
{"windows", "pi.exe.cmd", false},
{"windows", "pi.ps1", false},
{"windows", "pi.bat", false},
{"windows", "pi.cmd.exe", false},
{"linux", `C:\tools\pi.cmd`, false},
} {
t.Run(c.goos+"/"+c.cli, func(t *testing.T) {
if got := piCLIIsNative(c.cli, c.goos); got != c.want {
t.Fatalf("piCLIIsNative(%q, %q) = %v, want %v", c.cli, c.goos, got, c.want)
}
})
}
}
func TestPiExtensionsAccountLauncherGate(t *testing.T) {
launchers := []string{"pi", "omo", "senpi", "pi.ps1", "pi.exe.cmd"}
if runtime.GOOS == "windows" {
launchers = append(launchers, "pi.cmd", "pi.exe", `C:\tools\PI.CMD`, `C:\tools\pi.exe`, "omo.cmd", "senpi.exe")
} else {
launchers = append(launchers, "/usr/local/bin/pi", "pi.cmd", "pi.exe")
}
for _, cli := range launchers {
for _, version := range []string{"0.99.2", "1.0.0", "0.99.1", ""} {
t.Run(cli+"/"+version, func(t *testing.T) {
f := newPiFixture(t)
f.version = version
f.svc.Accounts = map[string]Account{"pi-work": {Agent: "pi", Dir: f.agentDir, CLI: cli}}
run := f.svc.Run
calls := 0
f.svc.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
calls++
if bin != cli || !slices.Equal(args, []string{"--version"}) {
t.Fatalf("unexpected execution: %s %v", bin, args)
}
return run(ctx, dir, env, bin, args...)
}
gotVersion, readOnly := f.svc.piGate(context.Background(), "pi-work")
if !piCLIIsNative(cli, runtime.GOOS) {
if calls != 0 || gotVersion != "" || readOnly != piReadOnlyFork {
t.Fatalf("fork was probed: calls=%d version=%q readOnly=%q", calls, gotVersion, readOnly)
}
return
}
want := ""
if version == "" {
want = piReadOnlyNoCLI
} else if version == "0.99.1" {
want = piReadOnlyUnsupported
}
if calls != 1 || gotVersion != version || readOnly != want {
t.Fatalf("native gate: calls=%d version=%q readOnly=%q, want %q/%q", calls, gotVersion, readOnly, version, want)
}
})
}
}
}
func TestPiExtensionsAccountUsesItsOwnDirectoryAndCLI(t *testing.T) {
f := newPiFixture(t)
work := filepath.Join(f.home, ".pi-work", "agent")
f.writeJSON(filepath.Join(work, "settings.json"), map[string]any{"packages": []any{map[string]any{"source": f.pkg, "extensions": []string{"-extensions/a.ts"}}}})
f.svc.Accounts = map[string]Account{"pi-work": {Agent: "pi", Dir: work}}
v := f.view("pi-work")
if v.Scope != "account" || !v.Editable || v.SettingsPath != filepath.Join(work, "settings.json") {
t.Fatalf("account view: %+v", v)
}
assertRows(t, selections(v.Packages[0]), "extensions/a.ts:skipped", "extensions/b.ts:loads", "extensions/c.ts:loads")
// A fork is known unsupported from its name, so it is never run to ask its version.
f.svc.Accounts = map[string]Account{"pi-work": {Agent: "pi", Dir: work, CLI: "/usr/local/bin/omo"}}
f.svc.Run = func(_ context.Context, _ string, _ []string, bin string, _ ...string) ([]byte, error) {
t.Fatalf("the fork %s was run", bin)
return nil, nil
}
if v := f.view("pi-work"); v.ReadOnly != piReadOnlyFork || v.Packages[0].Rows[0].Editable {
t.Fatalf("a fork CLI must be read-only: %+v", v)
}
}
func TestPiExtensionsRefusesNonStrictJSON(t *testing.T) {
f := newPiFixture(t)
writeTree(t, f.agentDir, map[string]string{"settings.json": "{\n // comment\n \"packages\": []\n}\n"})
v := f.view("pi")
if v.Problem != "invalidJson" || v.ReadOnly != piReadOnlySettings || len(v.Packages) != 0 {
t.Fatalf("view: %+v", v)
}
}
func TestPiExtensionsSymlinkedSettingsAreRefused(t *testing.T) {
f := newPiFixture(t)
real := filepath.Join(f.home, "dotfiles", "settings.json")
writeTree(t, filepath.Dir(real), map[string]string{"settings.json": `{"packages":[]}`})
if err := os.MkdirAll(f.agentDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(real, filepath.Join(f.agentDir, "settings.json")); err != nil {
t.Fatal(err)
}
if v := f.view("pi"); v.Problem != "symlink" || v.Editable {
t.Fatalf("view: %+v", v)
}
}
// A linked home volume or dotfiles folder above the agent directory is the
// user's own layout; only links inside the agent directory are refused.
func TestPiExtensionsAgentDirUnderSymlinkedAncestorIsEditable(t *testing.T) {
f := newPiFixture(t)
volume := filepath.Join(f.home, "volume")
if err := os.MkdirAll(volume, 0o755); err != nil {
t.Fatal(err)
}
linked := filepath.Join(f.home, "linked")
if err := os.Symlink(volume, linked); err != nil {
t.Fatal(err)
}
f.agentDir = filepath.Join(linked, "agent")
t.Setenv("PI_CODING_AGENT_DIR", f.agentDir)
f.global(map[string]any{"packages": []any{f.pkg}})
if v := f.view("pi"); v.Problem != "" || !v.Editable {
t.Fatalf("view: %+v", v)
}
}
func TestPiExtensionsUnsupportedGlobIsUnknownAndReadOnly(t *testing.T) {
f := newPiFixture(t)
f.global(map[string]any{"packages": []any{map[string]any{"source": f.pkg, "extensions": []string{"!extensions/**", "+extensions/a.ts"}}}})
rows := f.view("pi").Packages[0].Rows
assertRows(t, selections(PiExtensionPackage{Rows: rows}), "extensions/a.ts:loads", "extensions/b.ts:unknown", "extensions/c.ts:unknown")
if !rows[0].Editable || rows[1].Editable || rows[2].Editable {
t.Fatalf("only the row an exact rule decides can change: %+v", rows)
}
}
func TestPiExtensionsDiscoveryRefusesWhatItCannotReproduce(t *testing.T) {
cases := map[string]struct {
files map[string]string
problem string
}{
"ignore files": {map[string]string{"extensions/.gitignore": "c.ts\n"}, piProblemIgnoreFiles},
"manifest glob": {map[string]string{"package.json": `{"pi":{"extensions":["extensions/*.ts"]}}`}, piProblemManifestGlob},
"manifest escapes": {map[string]string{"package.json": `{"pi":{"extensions":["../outside.ts"]}}`}, piProblemPathEscapes},
"absolute manifest": {map[string]string{"package.json": `{"pi":{"extensions":["/etc/passwd"]}}`}, piProblemPathEscapes},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
f := newPiFixture(t)
writeTree(t, f.pkg, c.files)
f.global(map[string]any{"packages": []any{f.pkg}})
p := f.view("pi").Packages[0]
if p.Problem != c.problem || len(p.Rows) != 0 {
t.Fatalf("package: %+v", p)
}
})
}
}
func TestPiExtensionsLinkOutOfPackageIsUnsafe(t *testing.T) {
f := newPiFixture(t)
outside := filepath.Join(f.home, "outside.ts")
writeTree(t, f.home, map[string]string{"outside.ts": "x"})
if err := os.Symlink(outside, filepath.Join(f.pkg, "extensions", "d.ts")); err != nil {
t.Fatal(err)
}
f.global(map[string]any{"packages": []any{f.pkg}})
if p := f.view("pi").Packages[0]; p.Problem != piProblemUnsafeLink || len(p.Rows) != 0 {
t.Fatalf("package: %+v", p)
}
}
func TestPiExtensionsManifestAndInstallLocations(t *testing.T) {
f := newPiFixture(t)
npm := filepath.Join(f.agentDir, "npm", "node_modules", "@acme", "tools")
writeTree(t, npm, map[string]string{
"package.json": `{"name":"@acme/tools","pi":{"extensions":["./src/main.ts","./plugins","!plugins/skip.ts"]}}`,
"src/main.ts": "x",
"plugins/one.ts": "x",
"plugins/skip.ts": "x",
"plugins/dir/index.ts": "x",
"extensions/ignored.ts": "x",
})
f.global(map[string]any{"packages": []any{"npm:@acme/tools@1.2.0", "git:github.com/acme/none@v1"}})
v := f.view("pi")
if p := v.Packages[0]; p.Kind != "npm" || p.Identity != "npm:@acme/tools" || p.Install != "present" {
t.Fatalf("npm package: %+v", p)
}
assertRows(t, selections(v.Packages[0]), "src/main.ts:loads", "plugins/dir/index.ts:loads", "plugins/one.ts:loads")
if p := v.Packages[1]; p.Kind != "git" || p.Identity != "git:github.com/acme/none" || p.Install != "missing" || p.Problem != "notInstalled" || len(p.Rows) != 0 {
t.Fatalf("git package: %+v", p)
}
}
func TestPiExtensionsShowTheInstalledVersion(t *testing.T) {
f := newPiFixture(t)
writeTree(t, filepath.Join(f.agentDir, "npm", "node_modules", "pi-mcp-adapter"), map[string]string{
"package.json": `{"name":"pi-mcp-adapter","version":"5.0.0"}`,
"index.ts": "x",
})
f.global(map[string]any{"packages": []any{"npm:pi-mcp-adapter"}})
if p := f.view("pi").Packages[0]; p.Version != "5.0.0" {
t.Fatalf("version: %+v", p)
}
}
// A version that is not a string is someone's mistake, not a reason to lose the manifest Pi reads.
func TestPiExtensionsKeepTheManifestOfAPackageWithAnOddVersion(t *testing.T) {
f := newPiFixture(t)
writeTree(t, f.pkg, map[string]string{"package.json": `{"name":"tools","version":1,"pi":{"extensions":["./extensions/a.ts"]}}`})
f.global(map[string]any{"packages": []any{f.pkg}})
p := f.view("pi").Packages[0]
if p.Version != "" {
t.Fatalf("version: %q", p.Version)
}
assertRows(t, selections(p), "extensions/a.ts:loads")
}
func TestPiExtensionsListsARuleForAMissingFile(t *testing.T) {
f := newPiFixture(t)
f.global(map[string]any{"packages": []any{map[string]any{"source": f.pkg, "extensions": []string{"-extensions/gone.ts"}}}})
rows := f.view("pi").Packages[0].Rows
last := rows[len(rows)-1]
if last.Path != "extensions/gone.ts" || last.File != "missing" || last.Selection != "none" || last.Rule != "-extensions/gone.ts" || !last.Editable {
t.Fatalf("missing row: %+v", last)
}
}
// Unruled tells the switch whether removing a row's own rule gives the state it
// wants: -a would load a again; +b is redundant, so b loads either way.
func TestPiExtensionsUnruledIsTheSelectionWithoutTheRowsRule(t *testing.T) {
f := newPiFixture(t)
f.global(map[string]any{"packages": []any{map[string]any{"source": f.pkg, "extensions": []string{"-extensions/a.ts", "+extensions/b.ts"}}}})
got := []string{}
for _, r := range f.view("pi").Packages[0].Rows {
got = append(got, r.Path+":"+r.Unruled)
}
assertRows(t, got, "extensions/a.ts:loads", "extensions/b.ts:loads", "extensions/c.ts:")
}
// In a project override, a row without its rule inherits the global selection.
func TestPiExtensionsUnruledInAnOverrideIsTheInheritedSelection(t *testing.T) {
f := newPiFixture(t)
root := filepath.Join(f.home, "code", "acme")
f.global(map[string]any{"packages": []any{map[string]any{"source": f.pkg, "extensions": []string{"-extensions/c.ts"}}}})
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"packages": []any{
map[string]any{"source": f.pkg, "autoload": false, "extensions": []string{"+extensions/c.ts", "-extensions/a.ts"}},
}})
f.svc.ProjectRoot = root
got := []string{}
for _, r := range f.view("pi").Packages[0].Rows {
got = append(got, r.Path+":"+r.Unruled)
}
assertRows(t, got, "extensions/a.ts:loads", "extensions/c.ts:skipped", "extensions/b.ts:")
}
// A project view names the plugin Skillshare installed, for the project's entry and an inherited global one.
func TestPiProjectExtensionsNameTheManagedPlugin(t *testing.T) {
for _, project := range []bool{true, false} {
f := newPiFixture(t)
root := filepath.Join(f.home, "code", "acme")
writeTree(t, f.home, map[string]string{"config.yaml": "plugins:\n packages:\n powers:\n bindings:\n pi:\n id: " + f.pkg + "\n"})
f.global(map[string]any{"packages": []any{f.pkg}})
entries := []any{}
if project {
entries = append(entries, map[string]any{"source": f.pkg, "autoload": false, "extensions": []string{"-extensions/a.ts"}})
}
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"packages": entries})
f.svc.ProjectRoot = root
seedLocalBinding(t, f.svc, "powers", "pi", Binding{ID: f.pkg})
if got := f.view("pi").Packages[0]; got.ManagedBy != "powers" {
t.Fatalf("project entry %v: managedBy = %q, scope %s", project, got.ManagedBy, got.Scope)
}
}
}
// A dashboard in project mode reads the project's config; the global config still owns inherited packages and their overrides.
func TestPiProjectModeNamesTheGlobalManagedPlugin(t *testing.T) {
f := newPiFixture(t)
root := filepath.Join(f.home, "code", "acme")
writeTree(t, f.home, map[string]string{"config.yaml": "plugins:\n packages:\n powers:\n bindings:\n pi:\n id: " + f.pkg + "\n"})
f.global(map[string]any{"packages": []any{f.pkg}})
seedLocalBinding(t, f.svc, "powers", "pi", Binding{ID: f.pkg})
for _, scope := range []string{"global", "project"} {
entries := []any{}
if scope == "project" {
// The override Skillshare writes when a global package's extension is switched in the project.
entries = append(entries, map[string]any{"source": f.pkg, "autoload": false, "extensions": []string{"-extensions/a.ts"}})
}
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"packages": entries})
f.svc.ProjectRoot, f.svc.GlobalConfigPath, f.svc.ConfigPath = root, filepath.Join(f.home, "config.yaml"), filepath.Join(root, ".skillshare", "config.yaml")
if got := f.view("pi").Packages[0]; got.Scope != scope || got.ManagedBy != "powers" {
t.Fatalf("scope = %q, want %q; managedBy = %q", got.Scope, scope, got.ManagedBy)
}
}
}
// An entry Skillshare can't edit, here a non-list "extensions", still names the plugin that owns it.
func TestPiExtensionsNameTheManagedPluginOfAProblemEntry(t *testing.T) {
for _, project := range []bool{false, true} {
f := newPiFixture(t)
writeTree(t, f.home, map[string]string{"config.yaml": "plugins:\n packages:\n powers:\n bindings:\n pi:\n id: " + f.pkg + "\n"})
entry := []any{map[string]any{"source": f.pkg, "extensions": nil}}
if project {
root := filepath.Join(f.home, "code", "acme")
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"packages": entry})
f.svc.ProjectRoot = root
} else {
f.global(map[string]any{"packages": entry})
}
seedLocalBinding(t, f.svc, "powers", "pi", Binding{ID: f.pkg})
if got := f.view("pi").Packages[0]; got.Problem == "" || got.ManagedBy != "powers" {
t.Fatalf("project %v: problem = %q, managedBy = %q", project, got.Problem, got.ManagedBy)
}
}
}
func TestPiExtensionsMarksAnExtraInPisFolder(t *testing.T) {
f := newPiFixture(t)
extra := filepath.Join(f.home, "extras", "pi-ext")
writeTree(t, extra, map[string]string{"guard.ts": "x"})
writeTree(t, filepath.Join(f.agentDir, "extensions"), map[string]string{"scratch.ts": "x"})
if err := os.Symlink(filepath.Join(extra, "guard.ts"), filepath.Join(f.agentDir, "extensions", "guard.ts")); err != nil {
t.Fatal(err)
}
f.global(map[string]any{"extensions": []string{"-extensions/scratch.ts"}})
f.svc.ExtrasSources = map[string]string{"pi-ext": extra}
folder := f.view("pi").Folders[0]
if len(folder.Rows) != 2 || folder.Rows[0].Provenance != "extras" || folder.Rows[0].Extra != "pi-ext" || folder.Rows[0].Selection != "loads" ||
folder.Rows[1].Provenance != "native" || folder.Rows[1].Selection != "skipped" {
t.Fatalf("folder: %+v", folder)
}
}
func TestPiExtensionsProjectScopeShapes(t *testing.T) {
f := newPiFixture(t)
root := filepath.Join(f.home, "code", "acme")
only := filepath.Join(f.home, "pkgs", "lint")
writeTree(t, only, map[string]string{"extensions/lint.ts": "x"})
other := filepath.Join(f.home, "pkgs", "other")
writeTree(t, other, map[string]string{"extensions/o.ts": "x"})
f.global(map[string]any{
"defaultProjectTrust": "ask",
"packages": []any{
map[string]any{"source": f.pkg, "extensions": []string{"-extensions/c.ts"}},
map[string]any{"source": other, "extensions": []string{"-extensions/o.ts"}},
},
})
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"packages": []any{
map[string]any{"source": f.pkg, "autoload": false, "extensions": []string{"+extensions/c.ts", "-extensions/a.ts"}},
map[string]any{"source": only, "autoload": false, "extensions": []string{"+extensions/lint.ts"}},
}})
f.writeJSON(filepath.Join(f.agentDir, "trust.json"), map[string]any{root: true})
f.svc.ProjectRoot = root
v := f.view("pi")
if v.Scope != "project" || !v.Editable || v.ReadOnly != "" {
t.Fatalf("project view: %+v", v)
}
if v.Trust == nil || v.Trust.Saved != "trusted" || v.Trust.Default != "ask" {
t.Fatalf("trust hints: %+v", v.Trust)
}
// S6: the delta decides a and c, b inherits the global selection.
delta := v.Packages[0]
if delta.Shape != "delta" {
t.Fatalf("delta: %+v", delta)
}
assertRows(t, selections(delta), "extensions/a.ts:skipped", "extensions/c.ts:loads", "extensions/b.ts:loads")
if delta.Rows[2].Origin != "inherited" {
t.Fatalf("b should be inherited: %+v", delta.Rows[2])
}
// S7: a delta with no global entry names only its own paths.
if v.Packages[1].Shape != "deltaOnly" {
t.Fatalf("delta only: %+v", v.Packages[1])
}
assertRows(t, selections(v.Packages[1]), "extensions/lint.ts:loads")
if v.Packages[2].Shape != "global" {
t.Fatalf("global-only: %+v", v.Packages[2])
}
assertRows(t, selections(v.Packages[2]), "extensions/o.ts:skipped")
// Trust is shown, never required: every shape here can be switched.
for _, p := range v.Packages {
for _, r := range p.Rows {
if !r.Editable {
t.Fatalf("%s row %s is read-only", p.Shape, r.Path)
}
}
}
}
// Pi loads its global extensions folder whether or not it trusts the project, so
// the project view lists it next to the project's own folder, each with its scope
// and evaluated by that scope's own rules.
func TestPiExtensionsProjectListsGlobalAndProjectFolders(t *testing.T) {
f := newPiFixture(t)
root := filepath.Join(f.home, "code", "acme")
extra := filepath.Join(f.home, "extras", "pi-ext")
writeTree(t, extra, map[string]string{"guard.ts": "x"})
writeTree(t, filepath.Join(f.agentDir, "extensions"), map[string]string{"scratch.ts": "x"})
if err := os.Symlink(filepath.Join(extra, "guard.ts"), filepath.Join(f.agentDir, "extensions", "guard.ts")); err != nil {
t.Fatal(err)
}
writeTree(t, filepath.Join(root, ".pi", "extensions"), map[string]string{"local.ts": "x"})
f.global(map[string]any{"extensions": []string{"-extensions/scratch.ts"}})
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"extensions": []string{"-extensions/local.ts"}})
f.svc.ExtrasSources = map[string]string{"pi-ext": extra}
f.svc.ProjectRoot = root
got := []string{}
for _, folder := range f.view("pi").Folders {
for _, r := range folder.Rows {
got = append(got, folder.Scope+":"+r.Path+":"+r.Selection+":"+r.Provenance)
}
}
want := []string{
"project:extensions/local.ts:skipped:native",
"global:extensions/guard.ts:loads:extras",
"global:extensions/scratch.ts:skipped:native",
}
if !slices.Equal(got, want) {
t.Fatalf("folders:\n got %q\nwant %q", got, want)
}
}
func TestPiExtensionsProjectReplacingEntries(t *testing.T) {
for name, entry := range map[string]func(string) any{
"S8 object without autoload": func(src string) any { return map[string]any{"source": src, "extensions": []string{"+extensions/c.ts"}} },
"S9 string": func(src string) any { return src },
} {
t.Run(name, func(t *testing.T) {
f := newPiFixture(t)
root := filepath.Join(f.home, "code", "acme")
f.global(map[string]any{"packages": []any{map[string]any{"source": f.pkg, "extensions": []string{"-extensions/c.ts"}}}})
f.writeJSON(filepath.Join(root, ".pi", "settings.json"), map[string]any{"packages": []any{entry(f.pkg)}})
f.svc.ProjectRoot = root
p := f.view("pi").Packages[0]
if p.Shape != "replaces" || len(p.GlobalRules) != 1 {
t.Fatalf("package: %+v", p)
}
assertRows(t, selections(p), "extensions/a.ts:loads", "extensions/b.ts:loads", "extensions/c.ts:loads")
})
}
}
// A URL or git source can carry credentials in its userinfo or its query; neither
// may reach the dashboard. Local paths and npm names are shown as written.
func TestPiExtensionsSourceDisplayCarriesNoURLCredentials(t *testing.T) {
hidden := map[string]string{
"git:https://dummy-user:dummy-pass@example.com/acme/tools?access_token=dummy-token": "git:https://***@example.com/acme/tools?***",
"https://example.com/acme/tools.git?access_token=dummy-token": "https://example.com/acme/tools.git?***",
"git:example.com/acme/tools?token=dummy-token": "git:example.com/acme/tools?***",
}
for source, want := range hidden {
if got := redactSource(source); got != want {
t.Errorf("redactSource(%q) = %q, want %q", source, got, want)
}
}
for _, kept := range []string{"/home/me/pkgs/what?.ts", "./pkgs/a?b", "npm:@acme/tools", "git@github.com:acme/tools"} {
if got := redactSource(kept); got != kept {
t.Errorf("redactSource(%q) = %q, want it unchanged", kept, got)
}
}
}
// Skillshare has not verified how Pi resolves a git source with a query, so such a
// source is Unknown: no identity carries the query and nothing becomes editable.
func TestPiExtensionsGitSourceWithAQueryIsUnknown(t *testing.T) {
for _, source := range []string{"git:example.com/acme/tools?token=dummy-token", "https://example.com/acme/tools?access_token=dummy-token"} {
if src := resolvePiSource(source, "/agent", "", "user"); src.kind != "unknown" || src.identity != "" {
t.Errorf("%s: %+v", source, src)
}
}
}
// The display source is redacted, but the file keeps the raw registration: a string
// entry converted to an object still holds the source exactly as the user wrote it.
func TestPiExtensionsConvertingAnEntryKeepsItsRawSource(t *testing.T) {
f := newPiFixture(t)
raw := "git:https://dummy-user:dummy-pass@example.com/acme/tools"
writeTree(t, filepath.Join(f.agentDir, "git", "example.com", "acme", "tools"), map[string]string{"package.json": `{"name":"tools"}`, "extensions/a.ts": "x"})
f.rawGlobal(`{"packages": ["` + raw + `"]}`)
view, err := json.Marshal(f.view("pi"))
if err != nil {
t.Fatal(err)
}
ch := PiExtensionChange{Index: 0, Source: "git:https://***@example.com/acme/tools", Path: "extensions/a.ts", Action: "exclude"}
plan, err := f.svc.PreviewPiExtensions(context.Background(), "pi", []PiExtensionChange{ch})
if err != nil {
t.Fatal(err)
}
shown, _ := json.Marshal(plan)
if strings.Contains(string(view)+string(shown), "dummy-") {
t.Fatalf("a credential reached the dashboard:\n%s\n%s", view, shown)
}
if _, err := f.svc.ApplyPiExtensions(context.Background(), "pi", []PiExtensionChange{ch}, plan.Revision); err != nil {
t.Fatal(err)
}
if got, want := f.read(f.settingsPath()), `{"packages": [{"source":"`+raw+`","extensions":["-extensions/a.ts"]}]}`; got != want {
t.Fatalf("file:\n%s\nwant:\n%s", got, want)
}
}
func TestPiExtensionsRedactsSourceCredentials(t *testing.T) {
f := newPiFixture(t)
f.global(map[string]any{"packages": []any{"https://user:secret@example.com/acme/tools.git"}})
p := f.view("pi").Packages[0]
if p.Source != "https://***@example.com/acme/tools.git" || p.Identity != "git:example.com/acme/tools" {
t.Fatalf("package: %+v", p)
}
}
// PiMinVersion must be a version scripts/pi/version-matrix.sh ran and passed, and every
// recorded version must have passed: the contract against dist/core and against the
// CLI's bundle, and the lock test against that version's own proper-lockfile.
func TestPiMinVersionHasExecutedEvidence(t *testing.T) {
data, err := os.ReadFile(filepath.Join("..", "..", "scripts", "pi", "version-evidence.json"))
if err != nil {
t.Fatal(err)
}
var doc struct {
Package string `json:"package"`
Versions []struct {
Version string `json:"version"`
Passed bool `json:"passed"`
Checks []struct {
Name string `json:"name"`
Exit int `json:"exit"`
} `json:"checks"`
} `json:"versions"`
}
if err := json.Unmarshal(data, &doc); err != nil || doc.Package != "@earendil-works/pi-coding-agent" {
t.Fatalf("evidence: %v %s", err, doc.Package)
}
passed := []string{}
for _, v := range doc.Versions {
names := []string{}
ok := v.Passed
for _, c := range v.Checks {
names = append(names, c.Name)
ok = ok && c.Exit == 0
}
slices.Sort(names)
if ok && slices.Equal(names, []string{"contract/bundle", "contract/core", "native-lock", "project-native"}) {
passed = append(passed, v.Version)
}
}
if len(passed) != len(doc.Versions) || !slices.Contains(passed, PiMinVersion) {
t.Fatalf("PiMinVersion = %s, recorded %d versions, executed and passed: %v", PiMinVersion, len(doc.Versions), passed)
}
}
// Legacy ownership is proved in the requested scope, without upgrading either file.
func TestPiExtensionsVerifiedLegacyOwnership(t *testing.T) {
for _, mode := range []string{"global", "project", "account", "inherited", "foreign", "absent", "bad-snapshot", "private", "bad-registration", "changed-context"} {
t.Run(mode, func(t *testing.T) {
var calls []string
s := fakePiNpm(t, &calls)
target := "pi"
if mode == "account" {
target = "work"
s.Accounts = map[string]Account{target: {Agent: "pi", Dir: t.TempDir()}}
}
if mode == "project" {
s.ProjectRoot = t.TempDir()
}
if mode == "bad-registration" || mode == "private" {
file, _ := s.piSettingsPath(target)
writePluginFile(t, filepath.Dir(file), filepath.Base(file), `{"packages":[{"source":"npm:demo","extensions":["-private.ts"]}]}`)
applyPluginRequest(t, s, Request{Action: "import", Name: "demo", From: target, Plugin: "npm:demo"})
} else {
applyPluginRequest(t, s, Request{Action: "add", Source: hostStatePiSource(t), Targets: []string{target}})
}
b := readState(t, s).packages["demo"].Bindings[target]
// Serialize the same public binding that the legacy writer persisted.
raw, err := yaml.Marshal(map[string]any{"plugins": map[string]any{"packages": map[string]Package{"demo": {Bindings: map[string]Binding{target: b}}}}})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(s.ConfigPath, raw, 0600); err != nil {
t.Fatal(err)
}
if mode == "changed-context" {
d := readState(t, s)
s.captureLegacy(d)
if err := s.saveState(d); err != nil {
t.Fatal(err)
}
previous, _ := s.piSettingsPath(target)
settings, err := os.ReadFile(previous)
if err != nil {
t.Fatal(err)
}
t.Setenv("PI_CODING_AGENT_DIR", t.TempDir())
current, _ := s.piSettingsPath(target)
writePluginFile(t, filepath.Dir(current), filepath.Base(current), string(settings))
} else if err := os.Remove(s.statePath()); err != nil {
t.Fatal(err)
}
if mode == "foreign" {
s.StateDir = t.TempDir()
}
file, _ := s.piSettingsPath(target)
if mode == "absent" {
writePluginFile(t, filepath.Dir(file), filepath.Base(file), `{"packages":[]}`)
}
if mode == "bad-snapshot" {
writePluginFile(t, s.snapshotPath(b, target), ".skillshare-digest", "bad")
}
if mode == "bad-registration" {
path, err := s.piRegistrationPath(b.PiRegistration)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("changed"), 0600); err != nil {
t.Fatal(err)
}
}
shared := s.ConfigPath
if mode == "inherited" {
s.GlobalConfigPath = s.ConfigPath
s.ProjectRoot = t.TempDir()
s.ConfigPath = filepath.Join(s.ProjectRoot, ".skillshare", "config.yaml")
}
same := unchanged(t, shared, s.ConfigPath, file)
before := len(calls)
view, err := s.PiExtensions(context.Background(), target)
if err != nil {
t.Fatal(err)
}
owner := ""
for _, p := range view.Packages {
if p.ManagedBy != "" {
owner = p.ManagedBy
}
}
want := mode == "global" || mode == "project" || mode == "account" || mode == "inherited" || mode == "private"
if (owner == "demo") != want {
t.Fatalf("managedBy=%q, expected ownership=%v", owner, want)
}
same()
if len(calls) != before {
t.Fatal("ownership read mutated native installation")
}
})
}
}