Skip to content
Merged
2 changes: 1 addition & 1 deletion docs/product/output-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ It is silent when:

This notice covers every project whose install does not resync the skills. `skills sync` itself never edits the user's `package.json` or root `.gitignore`. The synced copies are ordinary files that git tracks like any other file in the repository. Sync removes the `*` ignore file an older CLI wrote into its copies, but leaves a `.gitignore` the user authored in place.

Which agents get skill copies is configuration, never detection: `skills: { agents: [...] }` in `prisma.config.ts` names them, each agent name mapping to its directory — `claude` (`.claude/skills`), `cursor` (`.cursor/skills`), `agents` (`.agents/skills`), `devin` (`.devin/skills`). An unknown name is a config error naming the known agents. When the field or the whole config is absent, the default is every known agent, so a harness adopted later finds the skills already in place. An empty list (`agents: []`, what `prisma init --skills=none` scaffolds) is a recorded choice, not an omission: sync writes nothing and answers `No agents are configured to sync skills for.`, `skills list` reports the same, and the staleness notice never fires. Narrowing the list also removes what an earlier sync wrote: a copy this CLI installed (its `SKILL.md` names an allowlisted package) in the directory of an agent the config no longer names is reported by `skills list` as orphaned and removed by the next sync, along with the `<agent>/skills` and `<agent>` directories when that leaves them empty; `agents: []` after a full sync therefore removes all four directories and answers `Removed 1 skill.`. A skill in those directories that this CLI did not write is never touched. `prisma init` writes the section into a fresh `prisma.config.ts`; a config that already exists is never edited — init reports the exact snippet to add instead. init also adds `prisma` to `devDependencies` at the CLI's exact version when no dependency field declares it, so the scaffolded config's `prisma/config` import resolves after the next install. Everything anchors at the directory the command runs in: sync, list, and the `.prisma/skills.json` opt-out read from cwd (the postinstall hook runs with cwd at the package root, so the mainline never guesses), and the config resolves over the chain discovered from that anchor — cwd, or the file `--config` names — upward to the repository boundary, so the staleness notice and the skills commands agree on the governing settings from any directory. The notice reads the config only when the discovered chain holds at least one file and the full agent set already looks out of date, and evaluates the chain at most once; discovery is stat-only until a file exists, so a project without a config never pays a TypeScript transpile, uses the default agent set, and leans on the postinstall hook as the primary resync trigger.
Which agents get skill copies is configuration, never detection: `skills: { agents: [...] }` in `prisma.config.ts` names them, each agent name mapping to its directory — `claude` (`.claude/skills`), `cursor` (`.cursor/skills`), `agents` (`.agents/skills`), `devin` (`.devin/skills`). An unknown name is a config error naming the known agents. When the field or the whole config is absent, the default is every known agent, so a harness adopted later finds the skills already in place. An empty list (`agents: []`, what `prisma init --skills=none` scaffolds) is a recorded choice, not an omission: sync writes nothing and answers `No agents are configured to sync skills for.`, `skills list` reports the same, and the staleness notice never fires. Narrowing the list also removes what an earlier sync wrote: a copy this CLI installed (its `SKILL.md` names an allowlisted package) in the directory of an agent the config no longer names is reported by `skills list` as orphaned and removed by the next sync, along with the `<agent>/skills` and `<agent>` directories when that leaves them empty; `agents: []` after a full sync therefore removes all four directories and answers `Removed 1 skill.`. A skill in those directories that this CLI did not write is never touched. A copy that a symbolic link makes the same directory as a copy sync keeps is not an orphan, and a directory that an agent's skills directory, or its parent, links to is never removed, so the link does not dangle. A skill directory that is a link to a copy this CLI wrote is kept as a link and written through; a link that is dangling or points at a directory without a `SKILL.md` is replaced by a copy, and its target is left alone; a copy that a link at any level puts inside an installed package's files (only its `skills/` directory when the project is itself inside that package), or under a `node_modules` directory in the project, is refused as not managed by this CLI and is never pruned. `prisma init` writes the section into a fresh `prisma.config.ts`; a config that already exists is never edited — init reports the exact snippet to add instead. init also adds `prisma` to `devDependencies` at the CLI's exact version when no dependency field declares it, so the scaffolded config's `prisma/config` import resolves after the next install. Everything anchors at the directory the command runs in: sync, list, and the `.prisma/skills.json` opt-out read from cwd (the postinstall hook runs with cwd at the package root, so the mainline never guesses), and the config resolves over the chain discovered from that anchor — cwd, or the file `--config` names — upward to the repository boundary, so the staleness notice and the skills commands agree on the governing settings from any directory. The notice reads the config only when the discovered chain holds at least one file and the full agent set already looks out of date, and evaluates the chain at most once; discovery is stat-only until a file exists, so a project without a config never pays a TypeScript transpile, uses the default agent set, and leans on the postinstall hook as the primary resync trigger.

`Agent skills are up to date.` appears only when installed skills exist and are current — a project with nothing to sync never borrows that line. The three empty states each name themselves: `agents: []` answers `No agents are configured to sync skills for.`; a project with no allowlisted package installed answers `No Prisma packages with agent skills are installed.`; installed packages whose versions ship no skills at all (older releases without a `skills/` directory) answer `No Prisma dependencies in your project ship agent skills to sync.` from sync and `No Prisma dependencies in your project ship agent skills.` from list. The sync JSON result carries a `skills` array naming every skill the installed packages ship, so machine consumers can make the same distinction. `prisma init` reports it in its JSON `skills.outcome`, whose values are `synced`, `up-to-date`, `no-agents`, `no-packages`, `no-skills`, `failed`, and `skipped`; a `skipped` outcome that no flag explains carries `reason: "governing-config"` — another `prisma.config.ts` on the discovered chain governs the directory, so the step belongs at the repository root — and the JSON `postinstall` report carries the same field for the same case. A project where at least one installed package ships skills keeps the ordinary summaries even when another installed package ships none.

Expand Down
235 changes: 213 additions & 22 deletions packages/cli/src/lib/skills/status.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// biome-ignore-all lint/performance/noAwaitInLoops: the allowlist is walked in order — a package resolved from an earlier directory decides what a later one is compared against — and the reads are a handful of stats on small files.
import { readdir, stat } from "node:fs/promises";
import { lstat, readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";

import { compareVersionStrings } from "../semver-order";
import {
AGENT_SKILL_DIRS,
type AgentName,
agentSkillDirs,
DEFAULT_AGENTS,
Expand All @@ -21,21 +22,28 @@ export interface InstalledSourcePackage {
readonly name: string;
readonly version: string;
readonly dir: string;
/** Every directory this package resolves to across the root and the
* workspace members, the winning `dir` among them. */
readonly dirs: readonly string[];
/** Every version this package resolves to across the root and the
* workspace members, when the members disagree. */
readonly conflictingVersions: readonly string[];
}

/** "unmanaged": the directory holds a SKILL.md this CLI did not write —
* unstamped, unreadable, or stamped by a package outside the
* allowlist. Sync never touches it. A directory without a SKILL.md
* allowlist — or lies, through a link, in a package's files (only
* its skills directory when the project is inside that package).
* Sync never touches it. A directory without a SKILL.md
* reads as "absent" so an interrupted copy is repaired by the next
* sync. */
export type SkillTargetState = "synced" | "stale" | "absent" | "unmanaged";

export interface SkillTarget {
/** Harness directory, relative to the project root. */
readonly dir: string;
/** Where the copy is on disk, the directory sync writes. */
readonly copyDir: string;
readonly syncedVersion: string | null;
readonly state: SkillTargetState;
}
Expand Down Expand Up @@ -95,9 +103,12 @@ export async function readSkillsStatus(
options?.checkDisabled ?? (await readSkillsCheckDisabled(projectRoot));
const packages = await findInstalledSourcePackages(projectRoot);
const sources = await collectSkillSources(packages);
const linkedIntoPackage = await linkedIntoPackageTest(projectRoot, packages);
const skills: SkillStatus[] = [];
for (const source of sources.values()) {
skills.push(await readSkillStatus(projectRoot, dirs, source));
skills.push(
await readSkillStatus(projectRoot, dirs, source, linkedIntoPackage),
);
}
skills.sort((left, right) => left.skill.localeCompare(right.skill));

Expand All @@ -109,12 +120,19 @@ export async function readSkillsStatus(
orphans:
options?.orphans === false
? []
: await findOrphanedSkills(
: await findOrphanedSkills({
projectRoot,
dirs,
new Set(sources.keys()),
provided: new Set(sources.keys()),
unconfiguredDirs,
),
wantedCopies: new Set(
skills.flatMap((skill) =>
skill.targets.map((target) => target.copyDir),
),
),
linkTargets: await harnessLinkTargets(projectRoot),
linkedIntoPackage,
}),
upToDate: skills.every((skill) => skill.upToDate),
};
}
Expand Down Expand Up @@ -159,6 +177,7 @@ export async function findInstalledSourcePackages(
name,
version: highest.version,
dir: highest.dir,
dirs: [...new Set(resolutions.map((one) => one.dir))],
conflictingVersions: versions.length > 1 ? versions : [],
});
}
Expand Down Expand Up @@ -201,15 +220,20 @@ async function readSkillStatus(
projectRoot: string,
dirs: readonly string[],
source: SkillSource,
linkedIntoPackage: LinkedIntoPackage,
): Promise<SkillStatus> {
const targets: SkillTarget[] = [];
for (const dir of dirs) {
const skillFile = path.join(projectRoot, dir, source.skill, "SKILL.md");
const copyDir = await locateCopy(path.join(projectRoot, dir, source.skill));
const skillFile = path.join(copyDir, "SKILL.md");
const stamp = await readSkillStamp(skillFile);
targets.push({
dir,
copyDir,
syncedVersion: stamp?.libraryVersion ?? null,
state: await targetState(skillFile, stamp, source.version),
state: (await linkedIntoPackage(copyDir, dir, source.skill))
? "unmanaged"
: await targetState(skillFile, stamp, source.version),
});
}

Expand Down Expand Up @@ -258,15 +282,29 @@ async function missingFromDisk(target: string): Promise<boolean> {
* SKILL.md names an allowlisted package as its `library` — and that
* nothing wants any more: in a configured directory, one no installed
* package still provides; in the directory of an agent the config no
* longer names, every one. A skill from anywhere else is someone
* else's file and is never touched.
* longer names, every one. A copy whose location on disk is, or holds,
* a copy sync keeps or the target of a harness directory link is
* wanted. A skill from anywhere
* else, or a copy a link puts inside a package's files, is never
* touched.
*/
export async function findOrphanedSkills(
projectRoot: string,
dirs: readonly string[],
provided: ReadonlySet<string>,
unconfiguredDirs: readonly string[] = [],
): Promise<OrphanedSkill[]> {
async function findOrphanedSkills({
projectRoot,
dirs,
provided,
unconfiguredDirs,
wantedCopies,
linkTargets,
linkedIntoPackage,
}: {
readonly projectRoot: string;
readonly dirs: readonly string[];
readonly provided: ReadonlySet<string>;
readonly unconfiguredDirs: readonly string[];
readonly wantedCopies: ReadonlySet<string>;
readonly linkTargets: ReadonlySet<string>;
readonly linkedIntoPackage: LinkedIntoPackage;
}): Promise<OrphanedSkill[]> {
const orphans = new Map<string, { library: string | null; dirs: string[] }>();
const scan = [
...dirs.map((dir) => ({ dir, wanted: provided })),
Expand All @@ -279,16 +317,19 @@ export async function findOrphanedSkills(
if (wanted.has(skill)) {
continue;
}
const stamp = await readSkillStamp(
path.join(harnessDir, skill, "SKILL.md"),
);
if (stamp?.library === null || stamp === null) {
const library = await managingLibrary(harnessDir, skill);
if (library === null) {
continue;
}
if (!isSkillSourcePackage(stamp.library)) {
const copyDir = await locateCopy(path.join(harnessDir, skill));
const kept = [...wantedCopies, ...linkTargets];
if (
kept.some((keptDir) => isSameOrInside(keptDir, copyDir)) ||
(await linkedIntoPackage(copyDir, dir, skill))
) {
continue;
}
const entry = orphans.get(skill) ?? { library: stamp.library, dirs: [] };
const entry = orphans.get(skill) ?? { library, dirs: [] };
entry.dirs.push(dir);
orphans.set(skill, entry);
}
Expand All @@ -301,6 +342,156 @@ export async function findOrphanedSkills(
}));
}

async function managingLibrary(
harnessDir: string,
skill: string,
): Promise<string | null> {
const stamp = await readSkillStamp(path.join(harnessDir, skill, "SKILL.md"));
if (
stamp === null ||
stamp.library === null ||
!isSkillSourcePackage(stamp.library)
) {
return null;
}
return stamp.library;
}

/**
* Where the copy at `copyPath` is on disk. A link at `copyPath` is
* followed only to a directory holding a SKILL.md; any other link is
* itself the copy, so replacing it removes the link and never its
* target.
*/
async function locateCopy(copyPath: string): Promise<string> {
if (await isSymbolicLink(copyPath)) {
try {
const target = await realpath(copyPath);
if (await isFile(path.join(target, "SKILL.md"))) {
return target;
}
} catch {
// A dangling link is replaced like a missing copy.
}
return path.join(
await resolveExisting(path.dirname(copyPath)),
path.basename(copyPath),
);
}
return resolveExisting(copyPath);
}

/** `target` with every symbolic link followed, as far as the path
* exists on disk. */
async function resolveExisting(target: string): Promise<string> {
const absolute = path.resolve(target);
try {
return await realpath(absolute);
} catch {
const parent = path.dirname(absolute);
if (parent === absolute) {
return absolute;
}
return path.join(await resolveExisting(parent), path.basename(absolute));
}
}

async function isSymbolicLink(target: string): Promise<boolean> {
try {
return (await lstat(target)).isSymbolicLink();
} catch {
return false;
}
}

/** Tells whether a link moved the copy of `skill` in harness directory
* `dir` into a package manager's files: under a node_modules
* directory within the project, or inside an installed source
* package. When the project is itself inside that package, only the
* package's skills directory counts. */
async function linkedIntoPackageTest(
projectRoot: string,
packages: readonly InstalledSourcePackage[],
): Promise<LinkedIntoPackage> {
const realRoot = await resolveExisting(projectRoot);
const protectedDirs: string[] = [];
for (const dir of packages.flatMap((installed) => installed.dirs)) {
const packageDir = await resolveExisting(dir);
protectedDirs.push(
isSameOrInside(realRoot, packageDir)
? path.join(packageDir, PACKAGE_SKILLS_DIR)
: packageDir,
);
}
return async (copyDir, dir, skill) =>
(protectedDirs.some((protectedDir) =>
isSameOrInside(copyDir, protectedDir),
) ||
(isSameOrInside(copyDir, realRoot) &&
path
.relative(realRoot, copyDir)
.split(path.sep)
.includes("node_modules"))) &&
(await reachedThroughLink(projectRoot, path.join(dir, skill)));
}

type LinkedIntoPackage = (
copyDir: string,
dir: string,
skill: string,
) => Promise<boolean>;

/** Whether any directory on `relativePath` below `projectRoot` is a
* symbolic link. */
async function reachedThroughLink(
projectRoot: string,
relativePath: string,
): Promise<boolean> {
let current = projectRoot;
for (const part of relativePath.split(path.sep)) {
current = path.join(current, part);
if (await isSymbolicLink(current)) {
return true;
}
}
return false;
}

function isSameOrInside(target: string, dir: string): boolean {
const relative = path.relative(dir, target);
return (
relative === "" ||
(relative !== ".." &&
!relative.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relative))
);
}

/** The real directories that a symbolic link at any agent's harness
* directory, or at one of its parents, points to. */
export async function harnessLinkTargets(
projectRoot: string,
): Promise<Set<string>> {
const targets = new Set<string>();
for (const dir of Object.values(AGENT_SKILL_DIRS)) {
for (
let current: string = dir;
current !== "." && current !== "";
current = path.dirname(current)
) {
const candidate = path.join(projectRoot, current);
try {
if ((await lstat(candidate)).isSymbolicLink()) {
targets.add(await realpath(candidate));
}
} catch {
// A missing or dangling path protects nothing.
}
}
}
return targets;
}

/** The subdirectories of `dir` that hold a SKILL.md. */
async function skillDirectories(dir: string): Promise<string[]> {
let entries: string[];
Expand Down
Loading
Loading