diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index aeaf5bf..7727457 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "jfrog", - "version": "0.1.18", + "version": "0.1.19", "description": "JFrog skills and the JFrog MCP server for Codex \u2014 interact with the JFrog Platform.", "author": { "name": "JFrog", diff --git a/package.json b/package.json index 92bb8ec..de7efe7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codex-plugin", - "version": "0.1.18", + "version": "0.1.19", "private": true, "type": "module", "description": "JFrog skills and MCP server plugin for OpenAI Codex.", diff --git a/scripts/sync-skills-vendor.json b/scripts/sync-skills-vendor.json index f011ed2..b651305 100644 --- a/scripts/sync-skills-vendor.json +++ b/scripts/sync-skills-vendor.json @@ -1,6 +1,6 @@ { "repo": "jfrog/jfrog-skills", - "pin": "v0.44.0", + "pin": "v0.47.0", "paths": [ "skills" ] diff --git a/skills/jfrog-ai-catalog/SKILL.md b/skills/jfrog-ai-catalog/SKILL.md index 2a76241..b86444b 100644 --- a/skills/jfrog-ai-catalog/SKILL.md +++ b/skills/jfrog-ai-catalog/SKILL.md @@ -48,50 +48,105 @@ Pick the row matching the user's intent and read that reference file. - The [environment check](../jfrog/SKILL.md#environment-check) — confirm `jf` is installed before the first `jf` call, and install it if missing. - The [server selection rules](../jfrog/SKILL.md#server-selection-rules-mandatory) - — resolve the default `` once and reuse it, pass `--server-id ` - after the subcommand on every `jf` call, and use one server per request. - **Resolve it now, before any `jf` call:** - ```bash - jf config show 2>/dev/null \ - | awk '/^Server ID:/{id=$NF} /^Default:[[:space:]]*true/{print id; exit}' - # stdout: the default server-id; if empty, stop and ask which server to use - ``` + — pass `--server-id ` after the subcommand on every `jf` call, and use + one server per request. `` comes from the next bullet: in + this skill it is the AI Governance server, not the jf CLI default + server the base skill uses. - The stop-on-error rule — on any `jf` failure, stop and never switch servers. One addition specific to this skill: never `cat` or parse `~/.jfrog/jfrog-cli.conf.v6` (it can hold access tokens); list servers only with `jf config show`, which redacts secrets. -- **Agent Guard registry.** Catalog discovery and repo provisioning run through - `npx --yes @jfrog/agent-guard`. `` is the npm registry that - provides the `@jfrog/agent-guard` package itself: use `JFROG_AGENT_GUARD_REPO` - if set, otherwise - `https://releases.jfrog.io/artifactory/api/npm/coding-agents-npm/`. Pass the - same `` to Agent Guard as `--server ""` so it targets the same server - as your `jf` calls. Agent Guard also reads `JFROG_URL` / `JF_URL` directly when - set, so make sure the `` you resolved points at that same host. -- **Resolve the project (``) only when needed.** - It is required for `--list-skills`, `--list-skill-versions`, - `--provision-skills-repository`, `--list-agent-plugins`, - `--list-agent-plugin-versions`, `--provision-agent-plugins-repository`, and - listing AI Catalog policies (`references/listing-policies.md`). - Resolve it with this priority: - 1. Parse `~/.jfrog/setup.json` (if present) and read `.servers[""].currentActiveProject`. - 2. Fall back to `$JF_PROJECT`. - 3. If still empty, ask the user for the project key - do **not** guess. +- **The AI Governance server and project.** The AI Governance server is the + JFrog Platform server (a jf CLI server ID) that governs the user's AI + assets: its AI Catalog lists the skills, plugins and MCP servers they may + use, and Agent Guard, where the organization has turned it on, enforces + that. The AI Governance project is the JFrog project on that server that + scopes the AI Catalog: which skills, plugins and MCP servers the user sees + and may install. Both are saved in `setup.json` in the JFrog CLI home + directory, separately from the jf CLI default server; the AI Governance + server can be the same server as that default or a different one. The user + chooses both in + `/jfrog-init`; another skill saves one only when it is missing or unclear + and the user answers that skill's question. + Read and change the file only through `jfrog-ai-governance-config.mjs`. + + In this skill, flows that need a project (listed below) use the AI + Governance server and project. Flows that need a server but no project use + the AI Governance server; only when no AI Governance server is saved do they + use the jf CLI default server instead. Read both once, before the first + `jf` or Agent Guard call: ```bash - PROJECT=$(jq -r --arg sid "" '.servers[$sid].currentActiveProject // empty' \ - ~/.jfrog/setup.json 2>/dev/null) - [ -z "$PROJECT" ] && PROJECT="${JF_PROJECT:-}" + node /scripts/jfrog-ai-governance-config.mjs get ``` + + `` is the AI Governance server ID that `get` returned (`serverId`), and + `` is its AI Governance project key (`project`). Flows that need + ``: browsing or searching skills and plugins, listing versions, + installing (the repository comes from the versions listing), updating a + skill (only from a repository still in the project's `--allowed-only` + listing), listing policies, and publishing with no repository named. + Removing an installed skill or plugin touches local files only: it needs + neither and skips this read and the status handling below. All other + flows need only ``. + Then act on `status`: + - `ok` — continue with `` and ``. + - `no_project` — the server is set, the project is not (e.g. the user told + `/jfrog-init` they don't use AI Catalog). When the flow needs ``, + ask: "Which AI Governance project on `` should I use? I need its + project key." (`` is the host of the `jpdUrl` that `get` returned.) + The answer is `` from now on. Save it by running + `node /scripts/jfrog-ai-governance-config.mjs set "" ""`. + Never take the key from `JF_PROJECT` or other env vars; they are no longer + used (`get` notes them on stderr). + - `ambiguous` — several servers are saved (e.g. set up for more than one + JFrog platform) and none is marked as the AI Governance server. Run + `node /scripts/jfrog-ai-governance-config.mjs list`, show the + user each `serverId` with its `jpdUrl`, and ask: "Which of these is your AI + Governance server?" Wait for the answer, ``, save it with + `node /scripts/jfrog-ai-governance-config.mjs set ""`, + and run `get` again. + - `missing` — AI Governance is not set up. If the flow needs + ``, reply with this exact line and stop: + "AI Governance isn't set up. Run `/jfrog-init` to set it up." + When publishing, reply instead: "AI Governance isn't set up. Run + `/jfrog-init` to set it up, or tell me a repository to publish to." + Otherwise `` is the jf CLI default server: + + ```bash + jf config show 2>/dev/null \ + | awk '/^Server ID:/{id=$NF} /^Default:[[:space:]]*true/{print id; exit}' + # stdout: the default server-id; if empty, stop and ask which server to use + ``` + + Then say once: "Using `` from your jf CLI config." + - `corrupt` — `setup.json` can't be read. Ask the user to run + `/jfrog-init` to repair the AI Governance setup, and stop. + + If a `jfrog-ai-governance-config.mjs set` command above fails, show the + user its error. For a rejected project key, ask once more; otherwise, or if + the second key is rejected too, ask the user to run `/jfrog-init` to repair + the AI Governance setup, and stop. + + When the user names another JFrog server or project, say: "Your AI Governance + server is `` with project ``. To change it, run + `/jfrog-init`." If they want to change it, stop; the AI Governance server and + project are chosen in `/jfrog-init`, so they run that first. + There is no non-admin way to look up or validate project keys (the `/access/api/v1/projects` list endpoint needs admin), so you cannot - silently correct a display name to a key. If the value looks like a + silently correct a display name to a key. If the project key looks like a display name (spaces, mixed case) rather than a short slug, ask the user to confirm the project **key** specifically. Never assume - `default`, never invent one. Install, update, remove, and publishing to - an explicit `--repo` are keyed by skill/plugin **name** and/or **repo**, - not a project. + `default`, never invent one. +- **Agent Guard registry.** Catalog discovery and repo provisioning run through + `npx --yes @jfrog/agent-guard`. `` is the npm registry that + provides the `@jfrog/agent-guard` package itself: use `JFROG_AGENT_GUARD_REPO` + if set, otherwise + `https://releases.jfrog.io/artifactory/api/npm/coding-agents-npm/`. Always pass + the same `` to Agent Guard as `--server ""` so it targets the same + server as your `jf` calls. - **Bundle manifests differ by type.** Skill bundles require `SKILL.md` in the bundle root; plugin bundles require `plugin.json`. Validate the correct file before installing or publishing. @@ -106,8 +161,9 @@ flowchart TD C --> D D -->|List all skills / versions| E[npx @jfrog/agent-guard --list-skills --allowed-only] D -->|List policies for skills| M[Resolve project, run list-skill-policies.mjs] - D -->|Install / update skill| F[Resolve slug + version, then jf skills install/update] - D -->|List installed skills / remove| G[jf skills list / rm -rf install dir] + D -->|Install skill| F[Resolve slug + version, then jf skills install] + D -->|Update skill| N[Resolve project, run jfrog-update-skill.mjs] + D -->|List installed skills / remove| G[jf skills list / jfrog-remove-skill.mjs] D -->|Publish skill| H[Resolve/provision repo, validate bundle, jf skills publish] D -->|List all plugins / versions| I[npx @jfrog/agent-guard --list-agent-plugins] D -->|Install / update plugin| J[Resolve slug + version, then jf agent plugins install/update] diff --git a/skills/jfrog-ai-catalog/references/discovering-plugins.md b/skills/jfrog-ai-catalog/references/discovering-plugins.md index 8aed8a3..f0efe58 100644 --- a/skills/jfrog-ai-catalog/references/discovering-plugins.md +++ b/skills/jfrog-ai-catalog/references/discovering-plugins.md @@ -6,14 +6,14 @@ List-all and versions go through the **Agent Guard**. ```bash npx --yes --registry @jfrog/agent-guard \ - --list-agent-plugins --project "" [--name ] [--server ""] [--page-size ] [--cursor ] [--format json] + --list-agent-plugins --project "" [--name ] --server "" [--page-size ] [--cursor ] [--format json] ``` | Flag | Required | Purpose | |------|----------|---------| -| `--project ` | **Yes** | AI Catalog project to list. | +| `--project ` | **Yes** | AI Governance project to list. | | `--name ` | No | Find plugins by name: server-side, case-insensitive substring, scoped to the project. | -| `--server ` | No | jf CLI config entry to authenticate with (defaults to the resolved single server). | +| `--server ` | **Yes** | The AI Governance server (its jf CLI server ID). | | `--page-size ` | No | Results per page. Pass `50` to stay bounded. The Agent Guard defaults to 500 if omitted. | | `--cursor ` | No | Continuation cursor from a previous page's JSON, to fetch the next page. | | `--format json` | No | Raw page JSON instead of the default compact TSV (name + last-updated). | @@ -45,7 +45,7 @@ repo-scoped (Artifactory registry contents), unlike `--list-agent-plugins`, whic project-scoped: ```bash -jf agent plugins list --repo "" --server-id "" --format json +jf agent plugins list --repo "" --server-id "" --format json ``` Never run a bare `jf agent plugins list` (it errors): always pass `--repo ` here, or @@ -70,7 +70,7 @@ line instead: ```bash npx --yes --registry @jfrog/agent-guard \ - --list-agent-plugin-versions --project "" --agent-plugin "" [--server ""] [--page-size ] [--cursor ] [--format json] + --list-agent-plugin-versions --project "" --agent-plugin "" --server "" [--page-size ] [--cursor ] [--format json] # JSON: versions[].version, versions[].locations[].repoKey (page through with cursor like above) ``` diff --git a/skills/jfrog-ai-catalog/references/discovering-skills.md b/skills/jfrog-ai-catalog/references/discovering-skills.md index 1a4267e..71828d6 100644 --- a/skills/jfrog-ai-catalog/references/discovering-skills.md +++ b/skills/jfrog-ai-catalog/references/discovering-skills.md @@ -13,15 +13,15 @@ path — see *List a repo's skills* for when it's appropriate to use. ```bash npx --yes --registry @jfrog/agent-guard \ - --list-skills --project "" --allowed-only [--name ] [--server ""] [--page-size ] [--cursor ] --format json + --list-skills --project "" --allowed-only [--name ] --server "" [--page-size ] [--cursor ] --format json ``` | Flag | Required | Purpose | |------|----------|---------| -| `--project ` | **Yes** | AI Catalog project to list. | +| `--project ` | **Yes** | AI Governance project to list. | | `--allowed-only` | **Yes** | Limit results to skills allowed by project policy. Never omit it. | | `--name ` | No | Find skills by name: server-side, case-insensitive substring, scoped to the project. | -| `--server ` | No | jf CLI config entry to authenticate with (defaults to the resolved single server). | +| `--server ` | **Yes** | The AI Governance server (its jf CLI server ID). | | `--page-size ` | No | Results per page. Pass `50` to stay bounded. The Agent Guard defaults to 500 if omitted. | | `--cursor ` | No | Continuation cursor from a previous page's JSON, to fetch the next page. | | `--format json` | **Yes** | Raw page JSON used to render the result. | @@ -70,7 +70,7 @@ repo-scoped (Artifactory registry contents), unlike `--list-skills`, which is project-scoped: ```bash -jf skills list --repo "" --server-id "" --format json +jf skills list --repo "" --server-id "" --format json ``` Never run a bare `jf skills list` (it errors): always pass `--repo ` here, or @@ -104,7 +104,7 @@ same result" means the one fully-paged, merged result, not a single HTTP call. ```bash npx --yes --registry @jfrog/agent-guard \ - --list-skill-versions --project "" --skill "" --allowed-only [--server ""] [--cursor ] --format json + --list-skill-versions --project "" --skill "" --allowed-only --server "" [--cursor ] --format json # JSON: versions[].version, versions[].locations[].repoKey, versions[].locations[].allowStatus, exhausted, cursor ``` diff --git a/skills/jfrog-ai-catalog/references/installing-plugins.md b/skills/jfrog-ai-catalog/references/installing-plugins.md index c238a90..9680958 100644 --- a/skills/jfrog-ai-catalog/references/installing-plugins.md +++ b/skills/jfrog-ai-catalog/references/installing-plugins.md @@ -13,11 +13,11 @@ Install by **slug** (the registry `slug`/`name`, never a display name). Latest version is used by default, and the user may pass an explicit version. **The `jf agent plugins install` command takes no project.** Resolving which repo hosts the slug uses `--list-agent-plugin-versions` (below), which does require `--project`, so -use `` resolved at session start (see SKILL.md Prerequisites). +use the AI Governance project `` (see SKILL.md Prerequisites). ```bash jf agent plugins install "" \ - --server-id "" \ + --server-id "" \ --version "latest" \ --repo "" \ --harness "" \ @@ -63,7 +63,7 @@ up where the slug is hosted with the Agent Guard: ```bash npx --yes --registry @jfrog/agent-guard \ - --list-agent-plugin-versions --project "" --agent-plugin "" [--server ""] --format json + --list-agent-plugin-versions --project "" --agent-plugin "" --server "" --format json # read versions[].version and versions[].locations[].repoKey ``` @@ -98,7 +98,7 @@ After install, confirm the slug shows up as installed — don't guess where the source of truth for what's actually installed: ```bash -jf agent plugins list --server-id "" --harness "" --format json \ +jf agent plugins list --server-id "" --harness "" --format json \ | jq -e --arg slug "" '.[] | select(.name == $slug)' >/dev/null \ && echo "installed" || echo "MISSING from installed list" ``` @@ -116,13 +116,13 @@ To upgrade an installed plugin to a newer version, use the CLI (it re-downloads and reinstalls in place): ```bash -jf agent plugins update --slug "" --server-id "" --harness "" --version "latest" --quiet +jf agent plugins update --slug "" --server-id "" --harness "" --version "latest" --quiet # Preview without touching Artifactory: -jf agent plugins update --slug "" --server-id "" --harness "" --dry-run +jf agent plugins update --slug "" --server-id "" --harness "" --dry-run # Reinstall even if already at the target version: -jf agent plugins update --slug "" --server-id "" --harness "" --force --quiet +jf agent plugins update --slug "" --server-id "" --harness "" --force --quiet # Update all installed plugins at once: -jf agent plugins update --all --server-id "" --harness "" --quiet +jf agent plugins update --all --server-id "" --harness "" --quiet ``` Note: unlike `jf skills update`, the slug is passed as `--slug ` (a named diff --git a/skills/jfrog-ai-catalog/references/installing-skills.md b/skills/jfrog-ai-catalog/references/installing-skills.md index 3d6cc7b..1997721 100644 --- a/skills/jfrog-ai-catalog/references/installing-skills.md +++ b/skills/jfrog-ai-catalog/references/installing-skills.md @@ -23,16 +23,17 @@ target is already installed, so its repo is fixed — not automatically by `jf`, but by reading it back from that install's own record (see *Update an installed skill* below) — and `allowStatus` is a per-repo fact, not per-version, so every version in that already-allowed repo is equally -allowed. "Latest version in this specific, already-resolved repo" carries +allowed — once update has confirmed that repo is still in the `--allowed-only` +listing. "Latest version in this specific, already-resolved repo" carries none of the version/repo ambiguity this rule exists to prevent. **The `jf skills install` command takes no project.** Resolving which repo hosts the slug uses `--list-skill-versions` (below), which does require `--project`, so -use `` resolved at session start (see SKILL.md Prerequisites). +use the AI Governance project `` (see SKILL.md Prerequisites). ```bash jf skills install "" \ - --server-id "" \ + --server-id "" \ --version "" \ --repo "" \ --harness "" \ @@ -94,7 +95,7 @@ one Agent Guard query: ```bash npx --yes --registry @jfrog/agent-guard \ - --list-skill-versions --project "" --skill "" --allowed-only [--server ""] [--cursor ] --format json + --list-skill-versions --project "" --skill "" --allowed-only --server "" [--cursor ] --format json # read versions[].version, versions[].locations[].repoKey, versions[].locations[].allowStatus, exhausted, cursor ``` @@ -235,7 +236,7 @@ find out why (the path is the archive `//-.zip`, URL-encoded): ```bash -jf api --server-id "" \ +jf api --server-id "" \ '/artifactory/api/skills//xrayStatus?path=%2F%2F-.zip' ``` @@ -288,39 +289,50 @@ On success, reply using **this exact template**: To upgrade an installed skill to a newer version, use the CLI (it re-downloads and reinstalls in place). **`jf skills update` does not remember which repo the -skill was installed from — you must resolve and pass `--repo` yourself.** +skill was installed from — a repo has to be passed with `--repo`.** Without it, update either fails with `multiple skills repositories found` (listing every skills repo on the whole server, not scoped to this project or its governance policy at all) or, if handed some other repo, silently updates -from it — even one that never hosted the originally installed skill. Never -run `jf skills update` without a resolved `--repo`. +from it — even one that never hosted the originally installed skill. The +script below resolves and checks the repo for you. -**Resolve `` from the existing install, never by asking the user or -guessing.** Every install writes it to `.jfrog/skill-info.json` under the -install directory: +**Run the update script; never build the `jf skills update` command yourself.** +It reads `` from the install's `.jfrog/skill-info.json`, checks it is a +plain id, confirms it is still in the project's `--allowed-only` listing, and +only then runs `jf skills update`. That file is untrusted (a project can commit +its own copy), so never paste a value from it into a command. -```bash -jq -r '.repo' "//.jfrog/skill-info.json" -``` - -If that file or its `.repo` field is missing (for example, a skill that was -manually copied in rather than installed with `jf skills install`), tell the -user you can't safely determine which repo to update from and stop. Do not -substitute a repo from a fresh catalog listing instead — a same-named repo -returned there is not proof it is the repo this specific install came from. +With `` and `` from *Prerequisites* in `../SKILL.md`, +run the script with network access: ```bash -jf skills update "" --server-id "" --harness "" --repo "" --version "latest" --quiet -# Preview without touching Artifactory: -jf skills update "" --server-id "" --harness "" --repo "" --dry-run -# Reinstall even if already at the target version: -jf skills update "" --server-id "" --harness "" --repo "" --force --quiet +node "/scripts/jfrog-update-skill.mjs" --slug '' --install-dir "" \ + --server-id "" --project "" --harness "" +# Preview without changing the install (still checks the allowed repos): add --dry-run +# Reinstall even if already at the target version: add --force ``` -Use the same install-target flag (`--harness`/`--global`/`--project-dir`/ -`--path`) the skill was installed with (Copilot: plus `--global`). After -updating, re-verify the `SKILL.md` (see *Verify the install landed* above). If the update download 403s, handle it -as in *Handling a blocked download* above. +Keep the slug in single quotes (double quotes don't stop `$(...)`). If it has +anything but letters, digits, `.`, `_` or `-`, don't run the command: tell the +user the skill name isn't valid. + +Use the same install target the skill was installed with: +`--harness ""`, `--global`, `--project-dir ""` or `--path ""` +(`--harness` can be combined with `--global`, as Copilot does, or with +`--project-dir`). Always invoke via `node `. + +Handle the exit code: + +- **0** — updated. Re-verify the `SKILL.md` (see *Verify the install landed* + above) and reply with the template below. +- **3** — refused (the repo is missing or unsafe, or is no longer + governance-allowed). Show the single stderr line **verbatim** and stop. Do not + retry, and do not pick a repo from the catalog listing instead — a same-named + repo returned there is not proof it is the repo this install came from. +- **1** — failed. If the download 403s, handle it as in *Handling a blocked + download* above, using the repo the script printed (`Updating from repo: …`) + and the version from `jf`'s `Using latest version: ` line; otherwise report the error line. +- **2** — usage error: a bug in how the script was invoked. On success, reply using **this exact template**: diff --git a/skills/jfrog-ai-catalog/references/listing-policies.md b/skills/jfrog-ai-catalog/references/listing-policies.md index a43f1ab..ad4b2e3 100644 --- a/skills/jfrog-ai-catalog/references/listing-policies.md +++ b/skills/jfrog-ai-catalog/references/listing-policies.md @@ -22,16 +22,16 @@ say to the user, the same way the rest of this skill never surfaces ## List the policies The query, auto-pagination, and error-scrubbing are **all owned by a bundled -script** — this is fully deterministic once `` and `` are +script** — this is fully deterministic once `` and `` are known, so none of it is left to be reconstructed freehand each time. Presentation is not: the script hands back structured data, and you build the response. -Resolve `` per **Resolve the project** in `../SKILL.md`'s -Prerequisites (never assume `default`, never invent one), then run: +With `` and `` from *Prerequisites* in `../SKILL.md` (never +assume `default`, never invent one), run: ```bash -node /scripts/list-skill-policies.mjs --project "" --server-id "" +node /scripts/list-skill-policies.mjs --project "" --server-id "" ``` Always invoke via `node ` — never execute the file directly. diff --git a/skills/jfrog-ai-catalog/references/managing-installed-plugins.md b/skills/jfrog-ai-catalog/references/managing-installed-plugins.md index f510ddc..ace9bd9 100644 --- a/skills/jfrog-ai-catalog/references/managing-installed-plugins.md +++ b/skills/jfrog-ai-catalog/references/managing-installed-plugins.md @@ -8,11 +8,11 @@ present the union, not just the first: ```bash # Project/harness install (the default target) -jf agent plugins list --server-id "" --harness "" --format json +jf agent plugins list --server-id "" --harness "" --format json # Global install (a separate location, always check it too) -jf agent plugins list --server-id "" --harness "" --global --format json +jf agent plugins list --server-id "" --harness "" --global --format json # Add --check-updates to compare installed versions against the registry -jf agent plugins list --server-id "" --harness "" --check-updates +jf agent plugins list --server-id "" --harness "" --check-updates ``` Resolve `` to the current agent (see `installing-plugins.md`). diff --git a/skills/jfrog-ai-catalog/references/managing-installed-skills.md b/skills/jfrog-ai-catalog/references/managing-installed-skills.md index f72f723..afe2b99 100644 --- a/skills/jfrog-ai-catalog/references/managing-installed-skills.md +++ b/skills/jfrog-ai-catalog/references/managing-installed-skills.md @@ -8,11 +8,11 @@ present the union, not just the first: ```bash # Project/harness install (the default target) -jf skills list --server-id "" --harness "" --format json +jf skills list --server-id "" --harness "" --format json # Global install (a separate location, always check it too) -jf skills list --server-id "" --harness "" --global --format json +jf skills list --server-id "" --harness "" --global --format json # Add --check-updates to compare installed versions against the registry -jf skills list --server-id "" --harness "" --check-updates +jf skills list --server-id "" --harness "" --check-updates ``` Resolve `` to the current agent (see `installing-skills.md`). @@ -49,22 +49,26 @@ skill, see *Update an installed skill* in `installing-skills.md`. ## Remove a skill "Remove" defaults to removing the **locally installed** skill. There is no -`jf skills uninstall`. Delete the installed skill directory after confirming it -exists: - -```bash -if [ -d "/" ]; then - rm -rf "/" -else - echo "Not installed, nothing to remove" -fi -``` +`jf skills uninstall`. **Confirm before deleting.** Show exactly what will be removed using **this exact template** and wait for an explicit "yes": > Removing skill `` deletes its local install from ``. Do you want to remove it? +Only after the "yes", delete the installed skill directory with the script (it +rejects a slug that isn't a plain name): + +```bash +node "/scripts/jfrog-remove-skill.mjs" --slug '' --install-dir "" +``` + +Keep the slug in single quotes (double quotes don't stop `$(...)`). If it has +anything but letters, digits, `.`, `_` or `-`, don't run the command: tell the +user the skill name isn't valid. + +On exit `1` or `3`, show its stderr line verbatim and stop. On `2`, fix the call. + On success, reply using **this exact template**: > Removed `` from ``. diff --git a/skills/jfrog-ai-catalog/references/publishing-plugins.md b/skills/jfrog-ai-catalog/references/publishing-plugins.md index 53d3ba0..689c862 100644 --- a/skills/jfrog-ai-catalog/references/publishing-plugins.md +++ b/skills/jfrog-ai-catalog/references/publishing-plugins.md @@ -24,12 +24,12 @@ in this order: 2. **No repo given. Provision the project's plugins repository.** Use Agent Guard to create (or resolve, if it already exists) the project's local plugins - repo, then publish to the returned key. This needs `` (resolve it per - *Prerequisites* in `../SKILL.md`, asking only if it is unknown): + repo, then publish to the returned key. This needs `` (see + *Prerequisites* in `../SKILL.md`): ```bash npx --yes --registry @jfrog/agent-guard \ - --provision-agent-plugins-repository --project "" [--server ""] [--format json] + --provision-agent-plugins-repository --project "" --server "" [--format json] ``` It prints the bare repo key (or `{"repoKey":""}` with `--format json`). @@ -45,14 +45,14 @@ npx --yes --registry @jfrog/agent-guard \ ```bash jf api '/artifactory/api/repositories?packageType=plugins&type=local' \ - --server-id "" 2>/dev/null | jq -r '.[].key' + --server-id "" 2>/dev/null | jq -r '.[].key' ``` Then **wait for the user to pick one** (by name). If the command printed one or more repos, reply in **this exact format**, sorted by name, one row per key, and nothing else: - Provisioning a plugins repository for project `` on `` failed, so + Provisioning a plugins repository for project `` on `` failed, so pick an existing repository to publish `` to: | Repository | @@ -62,7 +62,7 @@ jf api '/artifactory/api/repositories?packageType=plugins&type=local' \ If the command printed nothing (no plugins repos on the server), reply with one line instead, filling `` with the provisioning error: - > No plugins repositories on `` to publish to (provisioning failed: ``). Tell me a repository to use, or ask me to retry. + > No plugins repositories on `` to publish to (provisioning failed: ``). Tell me a repository to use, or ask me to retry. **Never auto-select a repo, even if one exists whose name matches the project.** A name match is not consent. Do not publish to any repo the user did @@ -114,7 +114,7 @@ To generate a key pair and register its public key in one step: ```bash jf evd gen-keys --key-alias "" \ - --key-file-path "" --server-id "" + --key-file-path "" --server-id "" # writes /evidence.key (private) + /evidence.pub, uploads the # public key as a trusted key under ``` @@ -129,7 +129,7 @@ Once `` is resolved and the bundle validated, **show the user what will be published and wait for an explicit confirmation**. Reply using this exact template and do not run `jf agent plugins publish` until the user agrees: - > Publishing plugin `` uploads it to repository `` on server ``. Do you want to publish it? + > Publishing plugin `` uploads it to repository `` on server ``. Do you want to publish it? Never combine this final confirmation step with the previous signing step into one prompt. @@ -148,7 +148,7 @@ unsigned. ```bash jf agent plugins publish "" \ - --server-id "" \ + --server-id "" \ --repo "" \ --quiet \ [--version ""] \ @@ -179,7 +179,7 @@ existing version and `` with the next patch (for example `3.0.0` to `3.0.1 | Option | Action | |--------|--------| -| **Overwrite** | Run `jf agent plugins delete "" --version "" --repo "" --server-id ""`, then re-run the publish unchanged. | +| **Overwrite** | Run `jf agent plugins delete "" --version "" --repo "" --server-id ""`, then re-run the publish unchanged. | | **Publish as a new version** | Re-run the publish with `--version ` (the user's semver, or ``). | | **Abort** | Stop and report that nothing was published. | @@ -187,12 +187,12 @@ existing version and `` with the next patch (for example `3.0.0` to `3.0.1 - **Success.** Reply using **this exact template**: - > Published `@` to `` on ``. + > Published `@` to `` on ``. - **Other failure.** Reply using **this exact template**, quoting the CLI error verbatim in ``: - > Publishing `` to `` on `` failed: ``. + > Publishing `` to `` on `` failed: ``. On 401/403/404, follow the stop-on-error rule from the base `jfrog` skill (see *Prerequisites* in `../SKILL.md`): stop and do not retry against a diff --git a/skills/jfrog-ai-catalog/references/publishing-skills.md b/skills/jfrog-ai-catalog/references/publishing-skills.md index 34bbc87..72f782e 100644 --- a/skills/jfrog-ai-catalog/references/publishing-skills.md +++ b/skills/jfrog-ai-catalog/references/publishing-skills.md @@ -33,12 +33,12 @@ order: 2. **No repo given. Provision the project's skills repository.** Use Agent Guard to create (or resolve, if it already exists) the project's local skills - repo, then publish to the returned key. This needs `` (resolve it per - *Prerequisites* in `../SKILL.md`, asking only if it is unknown): + repo, then publish to the returned key. This needs `` (see + *Prerequisites* in `../SKILL.md`): ```bash npx --yes --registry @jfrog/agent-guard \ - --provision-skills-repository --project "" [--server ""] [--format json] + --provision-skills-repository --project "" --server "" [--format json] ``` It prints the bare repo key (or `{"repoKey":""}` with `--format json`). @@ -50,26 +50,25 @@ npx --yes --registry @jfrog/agent-guard \ retry in a loop. Publishing is mutating, so you must get an explicit repo from the user here. This is the one case where you do ask before publishing. - First list the existing skills repos. When `` is known, scope the - list to that project so you offer only its repositories; fall back to the - server-wide list only when the project is unknown or the project-scoped list - comes back empty: + First list the existing skills repos. Scope the list to `` so you + offer only its repositories; fall back to the server-wide list only when the + project-scoped list comes back empty: ```bash -# project-scoped (preferred when is known) +# project-scoped jf api '/artifactory/api/repositories?packageType=skills&type=local&project=' \ - --server-id "" 2>/dev/null | jq -r '.[].key' + --server-id "" 2>/dev/null | jq -r '.[].key' -# server-wide fallback (project unknown, or the scoped list was empty) +# server-wide fallback (the scoped list was empty) jf api '/artifactory/api/repositories?packageType=skills&type=local' \ - --server-id "" 2>/dev/null | jq -r '.[].key' + --server-id "" 2>/dev/null | jq -r '.[].key' ``` Then **wait for the user to pick one** (by name). If the command printed one or more repos, reply in **this exact format**, sorted by name, one row per key, and nothing else: - Provisioning a skills repository for project `` on `` failed, so + Provisioning a skills repository for project `` on `` failed, so pick an existing repository to publish `` to: | Repository | @@ -79,7 +78,7 @@ jf api '/artifactory/api/repositories?packageType=skills&type=local' \ If the command printed nothing (no skills repos on the server), reply with one line instead, filling `` with the provisioning error: - > No skills repositories on `` to publish to (provisioning failed: ``). Tell me a repository to use, or ask me to retry. + > No skills repositories on `` to publish to (provisioning failed: ``). Tell me a repository to use, or ask me to retry. **Never auto-select a repo, even if one exists whose name matches the project.** A name match is not consent. Do not publish to any repo the user did @@ -149,7 +148,7 @@ To generate a key pair and register its public key in one step: ```bash jf evd gen-keys --key-alias "" \ - --key-file-path "" --server-id "" + --key-file-path "" --server-id "" # writes /evidence.key (private) + /evidence.pub, uploads the # public key as a trusted key under ``` @@ -173,7 +172,7 @@ when `--version` is omitted). Fill `` with the value recorded in > About to publish: > - Skill: `` > - Version: `` - > - Destination: `` on `` + > - Destination: `` on `` > - Signing: `` > > Do you want to publish it? @@ -194,7 +193,7 @@ fallback cannot sign the artifact. ```bash jf skills publish "" \ - --server-id "" \ + --server-id "" \ --repo "" \ --skip-scan \ --quiet \ @@ -237,7 +236,7 @@ existing version and `` with the next patch (for example `3.0.0` to `3.0.1 | Option | Action | |--------|--------| -| **Overwrite** | Run `jf skills delete "" --version "" --repo "" --server-id ""`, then re-run the publish unchanged. | +| **Overwrite** | Run `jf skills delete "" --version "" --repo "" --server-id ""`, then re-run the publish unchanged. | | **Publish as a new version** | Re-run the publish with `--version ` (the user's semver, or ``). | | **Abort** | Stop and report that nothing was published. | @@ -246,7 +245,7 @@ existing version and `` with the next patch (for example `3.0.0` to `3.0.1 - **Success.** Reply using **this exact template**. Do not mention Xray scanning, async watches, or indexing: - > Published `@` to `` on ``. + > Published `@` to `` on ``. - **Blocked by the Xray scan** (only when `--skip-scan` was omitted, shown by `[VIOLATION] … identified as malicious` or `blocked by Xray security scan`). Publish uploads the archive first, then scans, so on a scan block the artifact @@ -254,13 +253,13 @@ existing version and `` with the next patch (for example `3.0.0` to `3.0.1 claim it was removed. Verify: ```bash -jf api '/artifactory/api/storage///' --server-id "" +jf api '/artifactory/api/storage///' --server-id "" # 200 = still present, 404 = already gone ``` If it is still present, tell the user the malicious-flagged artifact remains and offer to delete it (`jf skills delete "" --version "" - --repo "" --server-id ""`). Treat the malicious flag as a real security signal. Reply + --repo "" --server-id ""`). Treat the malicious flag as a real security signal. Reply using **this exact template**: > Publish of `@` was **blocked by the Xray scan** (``). @@ -271,7 +270,7 @@ jf api '/artifactory/api/storage///' --server-id "" - **Other failure.** Reply using **this exact template**, quoting the CLI error verbatim in ``: - > Publishing `` to `` on `` failed: ``. + > Publishing `` to `` on `` failed: ``. On 401/403/404, follow the stop-on-error rule from the base `jfrog` skill (see *Prerequisites* in `../SKILL.md`): stop and do not retry against a diff --git a/skills/jfrog-ai-catalog/scripts/jfrog-ai-governance-config.mjs b/skills/jfrog-ai-catalog/scripts/jfrog-ai-governance-config.mjs new file mode 100755 index 0000000..db7f8aa --- /dev/null +++ b/skills/jfrog-ai-catalog/scripts/jfrog-ai-governance-config.mjs @@ -0,0 +1,548 @@ +#!/usr/bin/env node +// jfrog-ai-governance-config.mjs — resolve and update the JFrog AI Governance +// server and project in ${JFROG_CLI_HOME_DIR:-~/.jfrog}/setup.json. +// +// Usage, commands, options and exit codes: see USAGE below (also printed on a +// usage error). +// +// Contract: +// - Exactly one entry has `isDefault`. A v1 file with a single entry is +// treated as its default and migrated (written back as v2) by `get`. +// - `set` on an ambiguous file (no clear default) needs no --force and +// leaves the target as the only default. +// - A file whose `version` is newer than this script knows is read, but +// never written. +// - Unknown keys are preserved on every write. +// - Writes are temp file + rename, no lock. +// - stderr: an `info:` line if deprecated env vars are set; `debug:` lines +// with JF_AGENT_GUARD_LOG_LEVEL=debug. +// - Self-contained (Node builtins only): copied verbatim into the hooks, +// which import resolveAiGovernanceConfig and run `server-id`. +// +// File shape: +// { "version", "servers": { "": { "jpdUrl", "currentActiveProject"?, +// "isDefault"? } } } + +import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { + mkdirSync, + readFileSync, + realpathSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const USAGE = `\ +Usage: jfrog-ai-governance-config.mjs [options] + +Commands: + get Print the AI Governance server and project as JSON: + {status, serverId?, jpdUrl?, project?, path?}. + status: ok | no_project | ambiguous | missing | corrupt + (corrupt: setup.json is not valid; path names it). + list Print every saved server as a JSON array of + {serverId, jpdUrl, project?, isDefault}. + set [project] Make the AI Governance server (jpdUrl + from \`jf config show\`). + Project omitted: keep the saved one. + server-id Print only the server id, for command substitution. + Prints nothing if the id is invalid (see set). + Always exits 0. + +Options: + --no-project set: save no project; clears a saved one (needs --force). + --force set: override the saved server or project, or + replace a corrupt file. Only when you know what + you are doing. + +Environment: + JF_AGENT_GUARD_LOG_LEVEL=debug Print debug lines on stderr. + +Exit codes: + 0 ok + 1 set failed (message on stderr) + 2 usage error +`; +const CURRENT_VERSION = 2; +const DEPRECATED_ENV = [ + "JFROG_URL", + "JF_URL", + "JFROG_ACCESS_TOKEN", + "JF_ACCESS_TOKEN", + "JF_PROJECT", + "JFROG_PROJECT", + "JF_SERVER", + "JFROG_SERVER_ID", + "JF_SERVER_ID", +]; +const NOOP_LOG = { debug() {} }; +// The charset the hooks accept for ids passed to agent-guard. The jf CLI does +// not limit server ids (it only rejects delete, use, show, clear): enforced here. +const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const SAFE_ID_RULE = + 'letters, digits, ".", "_" or "-", starting with a letter or digit, at most 128 characters'; + +// import.meta.url is symlink-resolved, argv[1] is not; compare real paths. +function isMainModule(moduleUrl) { + if (!process.argv[1]) return false; + try { + return fileURLToPath(moduleUrl) === realpathSync(process.argv[1]); + } catch { + return false; + } +} + +const isObject = (v) => + v !== null && typeof v === "object" && !Array.isArray(v); +const nonEmpty = (v) => typeof v === "string" && v !== ""; + +function aiGovernanceConfigPath(env) { + return join( + env.JFROG_CLI_HOME_DIR || join(homedir(), ".jfrog"), + "setup.json", + ); +} + +// A missing file has no entries. A file that exists but is unreadable, not a +// JSON object, or has a non-object `servers` is `corrupt` (and has no data). +function loadSetup(path, log) { + const corrupt = { data: null, entries: [], corrupt: true }; + let parsed; + try { + parsed = JSON.parse(readFileSync(path, "utf8")); + } catch (err) { + if (err.code === "ENOENT") { + log.debug(`no setup.json at ${path}`); + return { data: null, entries: [], absent: true }; + } + log.debug( + err instanceof SyntaxError + ? `${path} is not valid JSON` + : `could not read ${path}: ${err.code || err.message}`, + ); + return corrupt; + } + if (!isObject(parsed)) { + log.debug(`${path} is not a JSON object`); + return corrupt; + } + if (parsed.servers !== undefined && !isObject(parsed.servers)) { + log.debug(`${path}: "servers" is not an object`); + return corrupt; + } + const entries = Object.entries(parsed.servers ?? {}).filter(([, e]) => + isObject(e), + ); + return { data: parsed, entries }; +} + +const isNewer = (data) => + typeof data?.version === "number" && data.version > CURRENT_VERSION; + +// The entry `get` would select, or null when ambiguous. A lone entry without +// isDefault is the implied default. +function select(entries) { + const defaults = entries.filter(([, e]) => e.isDefault === true); + if (defaults.length === 1) { + return { id: defaults[0][0], entry: defaults[0][1], implied: false }; + } + if (defaults.length === 0 && entries.length === 1) { + return { id: entries[0][0], entry: entries[0][1], implied: true }; + } + return null; +} + +function writeAtomic(path, data) { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`; + try { + // "wx" fails if anything (e.g. a planted symlink) already exists at tmp. + writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { + flag: "wx", + mode: 0o644, + }); + renameSync(tmp, path); + } catch (err) { + try { + unlinkSync(tmp); + } catch { + // Never created or already renamed. + } + throw err; + } +} + +/** + * Select the AI Governance server from setup.json, migrating a lone v1 entry to v2. + * @param {object} [options] + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{status: "missing" | "ambiguous"} + * | {status: "corrupt", path: string} + * | {status: "ok" | "no_project", serverId: string, jpdUrl: string, project?: string}} + * corrupt: the file exists but is not a valid setup object. + */ +export function resolveAiGovernanceConfig({ + env = process.env, + log = NOOP_LOG, +} = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + const { data, entries, corrupt } = loadSetup(path, log); + if (corrupt) return { status: "corrupt", path }; + if (entries.length === 0) { + log.debug("missing: no usable entries"); + return { status: "missing" }; + } + const sel = select(entries); + if (!sel) { + const marked = entries.filter(([, e]) => e.isDefault === true).length; + log.debug( + marked + ? `ambiguous: ${marked} entries marked isDefault` + : `ambiguous: ${entries.length} entries, none marked isDefault`, + ); + return { status: "ambiguous" }; + } + log.debug( + `default "${sel.id}" (${sel.implied ? "only entry, implied" : "explicit isDefault"})`, + ); + if (sel.implied && !isNewer(data)) { + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: { + ...data.servers, + [sel.id]: { ...sel.entry, isDefault: true }, + }, + }); + log.debug(`migrated ${path}: "${sel.id}" is now the default`); + } catch (err) { + log.debug(`migration write to ${path} failed: ${err.message}`); + } + } + const base = { serverId: sel.id, jpdUrl: sel.entry.jpdUrl }; + const project = sel.entry.currentActiveProject; + if (nonEmpty(project)) return { status: "ok", ...base, project }; + log.debug(`no_project: "${sel.id}" has no currentActiveProject`); + return { status: "no_project", ...base }; +} + +// Same as `get` but never migrates. +function listAiGovernanceConfig({ env = process.env, log = NOOP_LOG } = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + return loadSetup(path, log) + .entries.map(([serverId, e]) => ({ + serverId, + jpdUrl: e.jpdUrl, + ...(nonEmpty(e.currentActiveProject) && { + project: e.currentActiveProject, + }), + isDefault: e.isDefault === true, + })) + .sort((a, b) => a.serverId.localeCompare(b.serverId)); +} + +// Platform root URL, or "" when `raw` is not an http(s) URL. A missing scheme +// means https. +function normalizeJpdUrl(raw) { + const s = raw.trim(); + try { + const url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(s) ? s : `https://${s}`); + if (!["http:", "https:"].includes(url.protocol)) return ""; + return url.origin + url.pathname.replace(/(\/(artifactory|ui))*\/*$/, ""); + } catch { + return ""; + } +} + +// Returns the server list, or null when jf could not be run or its output +// was unusable (reported to the caller as "could not run jf", distinct from +// "server not configured"). jf is looked up on PATH only. +function loadJfServers(env, log) { + // On Windows an npm-installed jf is a .cmd shim, which only a shell can + // launch; the command is a constant, so passing it as one string is safe. + const opts = { encoding: "utf8", env, timeout: 30_000 }; + const r = + process.platform === "win32" + ? spawnSync("jf config show --format=json", { ...opts, shell: true }) + : spawnSync("jf", ["config", "show", "--format=json"], opts); + if (r.error || r.status !== 0) { + log.debug( + `jf config show failed: ${r.error?.message || `exit ${r.status}`}`, + ); + return null; + } + try { + const parsed = JSON.parse(r.stdout); + if (Array.isArray(parsed)) return parsed; + if (Array.isArray(parsed?.servers)) return parsed.servers; + } catch (err) { + log.debug(`jf config show output not parseable: ${err.message}`); + } + return null; +} + +/** + * Make serverId the AI Governance server. + * Without force it refuses to switch away from another default server, and to + * change or clear the saved non-empty project. An empty project is an error: + * pass noProject to save none. + * @param {string} serverId jf CLI server id + * @param {string} [project] undefined keeps the saved project (unless noProject) + * @param {object} [options] + * @param {boolean} [options.force] override the refusals above + * @param {boolean} [options.noProject] save no project; excludes a project + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{ok: true} | {ok: false, error: string}} + */ +export function setAiGovernanceConfig( + serverId, + project, + { force = false, noProject = false, env = process.env, log = NOOP_LOG } = {}, +) { + if (project === "") { + return { + ok: false, + error: "an empty project is not accepted; pass noProject to unset", + }; + } + if (noProject && project !== undefined) { + return { + ok: false, + error: "project and noProject are mutually exclusive", + }; + } + if (noProject) project = ""; + if (nonEmpty(project) && !SAFE_ID.test(project)) { + return { + ok: false, + error: `invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}`, + }; + } + if (!SAFE_ID.test(serverId)) { + return { + ok: false, + error: `invalid server id ${JSON.stringify(serverId)}: ${SAFE_ID_RULE}; re-add the server to the jf CLI under a valid id`, + }; + } + const path = aiGovernanceConfigPath(env); + const { data, entries, absent, corrupt } = loadSetup(path, log); + if (corrupt && !force) { + return refuse(`${path} is corrupt`, log); + } + if (isNewer(data)) { + return refuse( + `${path} was written by a newer version (${data.version}); refusing to modify it`, + log, + ); + } + const current = select(entries); + const previous = entries.find(([id]) => id === serverId)?.[1]; + // The project to protect is the target's own; it matters only when there is + // no default or the target is the default. + const existing = previous?.currentActiveProject; + const currentProject = current?.entry.currentActiveProject; + log.debug( + current + ? `current default: "${current.id}" (${nonEmpty(currentProject) ? `project "${currentProject}"` : "no project"})` + : "no current default", + ); + if (current && current.id !== serverId) { + if (!force) { + return refuse( + `the AI Governance server in ${path} is "${current.id}"; setting "${serverId}" would change it`, + log, + ); + } + log.debug(`switching default "${current.id}" -> "${serverId}" (--force)`); + } else if ( + previous && + project !== undefined && + project !== (existing ?? "") + ) { + if (!force && nonEmpty(existing)) { + const change = nonEmpty(project) ? `setting "${project}"` : "clearing it"; + return refuse( + `"${serverId}" uses project "${existing}"; ${change} would change it`, + log, + ); + } + log.debug( + nonEmpty(project) + ? `setting project of "${serverId}" to "${project}"` + : `clearing project of "${serverId}"`, + ); + } else if (current) { + log.debug(`"${serverId}" is already the default; refreshing`); + } else { + log.debug(`new default "${serverId}"`); + } + // The jf CLI is consulted only once the saved state allows the change, so a + // refusal names the saved server, not a missing jf config entry. + const jfServers = loadJfServers(env, log); + if (!jfServers) { + return { + ok: false, + error: + "could not run `jf config show`; is the JFrog CLI installed and on PATH?", + }; + } + const jpdUrlOf = (s) => + normalizeJpdUrl(`${s.url ?? ""}`.trim() || `${s.artifactoryUrl ?? ""}`); + const jf = jfServers.find( + (s) => isObject(s) && s.serverId === serverId && jpdUrlOf(s), + ); + log.debug( + `jf config show returned servers: ${jfServers + .filter(isObject) + .map((s) => s.serverId) + .join(", ")}`, + ); + if (!jf) { + log.debug(`"${serverId}" not found in jf config show`); + return { + ok: false, + error: `server "${serverId}" is not in the jf CLI config`, + }; + } + log.debug(`"${serverId}" -> ${jpdUrlOf(jf)}`); + const nextServers = Object.fromEntries( + entries.map(([id, e]) => { + const { isDefault: _drop, ...rest } = e; + return [id, rest]; + }), + ); + const { currentActiveProject: saved, ...kept } = previous ?? {}; + const nextProject = project === undefined ? saved : project; + nextServers[serverId] = { + ...kept, + jpdUrl: jpdUrlOf(jf), + ...(nonEmpty(nextProject) && { currentActiveProject: nextProject }), + isDefault: true, + }; + log.debug(`${absent ? "creating" : "updating"} ${path}`); + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: nextServers, + }); + } catch (err) { + log.debug(`write to ${path} failed: ${err.message}`); + return { ok: false, error: `write failed: ${err.message}` }; + } + log.debug(`wrote ${path}`); + return { ok: true }; +} + +function refuse(error, log) { + log.debug(`refused: ${error}`); + return { ok: false, error }; +} + +function usage() { + process.stderr.write(USAGE); + return 2; +} + +function main(argv, env) { + const [mode, ...rest] = argv; + const log = { + debug: (m) => + env.JF_AGENT_GUARD_LOG_LEVEL === "debug" && + process.stderr.write(`debug: ${m}\n`), + }; + + if (mode === "server-id") { + try { + const cfg = resolveAiGovernanceConfig({ env, log }); + if (cfg.status === "ok" || cfg.status === "no_project") { + if (!SAFE_ID.test(cfg.serverId)) { + log.debug( + `server-id: ${JSON.stringify(cfg.serverId)} not printed: invalid id (${SAFE_ID_RULE})`, + ); + } else { + process.stdout.write(`${cfg.serverId}\n`); + } + } + } catch { + // Always exit 0 with no output: callers use this in $(...). + } + return 0; + } + + const flags = ["--force", "--no-project"]; + const [serverId, project, ...extra] = rest.filter((a) => !flags.includes(a)); + const force = rest.includes("--force"); + const noProject = rest.includes("--no-project"); + const argsOk = + mode === "set" + ? nonEmpty(serverId) && !extra.length && !(noProject && project) + : !rest.length; + const stray = rest.some((a) => a.startsWith("-") && !flags.includes(a)); + const badProject = nonEmpty(project) && !SAFE_ID.test(project); + if (badProject) { + process.stderr.write( + `ai-governance-config: invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}\n`, + ); + } + const emptyProject = mode === "set" && project === ""; + if (emptyProject) { + process.stderr.write( + "ai-governance-config: an empty project is not accepted; use --no-project to unset\n", + ); + } + if ( + !["get", "list", "set"].includes(mode) || + !argsOk || + stray || + badProject || + emptyProject + ) { + return usage(); + } + + const used = DEPRECATED_ENV.filter((name) => nonEmpty(env[name])); + if (used.length) { + process.stderr.write( + `info: ${used.join(", ")} set but ignored (deprecated); AI Governance config comes from ${aiGovernanceConfigPath(env)}. Continuing normally without using them.\n`, + ); + } + + if (mode === "get") { + process.stdout.write( + JSON.stringify(resolveAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + if (mode === "list") { + process.stdout.write( + JSON.stringify(listAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + const result = setAiGovernanceConfig(serverId, project, { + force, + noProject, + env, + log, + }); + if (!result.ok) { + process.stderr.write(`ai-governance-config: ${result.error}\n`); + return 1; + } + return 0; +} + +if (isMainModule(import.meta.url)) { + process.exitCode = main(process.argv.slice(2), process.env); +} diff --git a/skills/jfrog-ai-catalog/scripts/jfrog-remove-skill.mjs b/skills/jfrog-ai-catalog/scripts/jfrog-remove-skill.mjs new file mode 100644 index 0000000..feaa523 --- /dev/null +++ b/skills/jfrog-ai-catalog/scripts/jfrog-remove-skill.mjs @@ -0,0 +1,31 @@ +#!/usr/bin/env node +// jfrog-remove-skill.mjs — delete an installed skill's directory. +// +// node jfrog-remove-skill.mjs --slug --install-dir +// +// The slug comes from `jf skills list`, so it must be a plain name. No shell is +// used. Exit: 0 removed | 1 not installed | 2 usage error | 3 invalid slug. +// On 1 and 3, stderr is one line to show the user. + +import { existsSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { parseArgs } from 'node:util'; + +function fail(code, message) { + process.stderr.write(`${message}\n`); + process.exit(code); +} + +let values = {}; +try { + ({ values } = parseArgs({ options: { slug: { type: 'string' }, 'install-dir': { type: 'string' } } })); +} catch {} +const { slug, 'install-dir': installDir } = values; +if (!slug || !installDir) fail(2, 'usage: jfrog-remove-skill.mjs --slug --install-dir '); + +// Letters, digits, "." "_" "-", starting with a letter or digit (so never "." / ".." / "-x"). +if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) fail(3, "That skill name isn't valid, so I can't remove it."); + +const target = join(installDir, slug); +if (!existsSync(target)) fail(1, 'Not installed, nothing to remove'); +rmSync(target, { recursive: true }); diff --git a/skills/jfrog-ai-catalog/scripts/jfrog-update-skill.mjs b/skills/jfrog-ai-catalog/scripts/jfrog-update-skill.mjs new file mode 100644 index 0000000..b5d9418 --- /dev/null +++ b/skills/jfrog-ai-catalog/scripts/jfrog-update-skill.mjs @@ -0,0 +1,213 @@ +#!/usr/bin/env node +// jfrog-update-skill.mjs — update an installed skill, only from a repo that is +// still governance-allowed. +// +// node jfrog-update-skill.mjs --slug --install-dir --server-id \ +// --project [--dry-run] [--force] +// : --harness [--global | --project-dir ] | --global | --project-dir +// | --path +// +// The repo comes from //.jfrog/skill-info.json, which any +// project can commit, so it is untrusted: it must be a plain id and appear in +// the project's `--allowed-only` listing. No shell is used (spawnSync, +// shell:false), so a value is only ever one argument. The one exception is npx +// on Windows (see runNpx). +// +// Exit: 0 updated | 1 failed | 2 usage error | 3 refused (unsafe or not allowed) +// On 1 and 3, stderr is one line to show the user. `jf` output passes through. + +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const DEFAULT_REGISTRY = 'https://releases.jfrog.io/artifactory/api/npm/coding-agents-npm/'; +const MAX_PAGES = 20; +const REQUIRED_FLAGS = ['--slug', '--install-dir', '--server-id', '--project']; +const TARGET_FLAGS = ['--harness', '--project-dir', '--path']; +const VALUE_FLAGS = [...REQUIRED_FLAGS, ...TARGET_FLAGS]; +const BOOL_FLAGS = ['--global', '--dry-run', '--force']; +// A plain id: letters, digits, "." "_" "-". Never "." / "..", never a leading "-". +const SAFE_ID = /^[A-Za-z0-9._-]+$/; +const USAGE = + 'usage: jfrog-update-skill.mjs --slug --install-dir --server-id ' + + '--project [--dry-run] [--force]\n' + + ': --harness [--global | --project-dir ] | --global | --project-dir | --path '; + +// An error with the exit code to finish with. +class Stop extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +const listingError = (reason) => + new Stop(1, `Could not check the allowed repositories${reason ? `: ${reason}` : ''}`); + +function isSafeId(value) { + return ( + typeof value === 'string' && + SAFE_ID.test(value) && + value !== '.' && + value !== '..' && + !value.startsWith('-') + ); +} + +function parseArgs(argv) { + const args = {}; + for (let i = 0; i < argv.length; i++) { + const flag = argv[i]; + if (BOOL_FLAGS.includes(flag)) { + args[flag] = true; + } else if (VALUE_FLAGS.includes(flag)) { + const value = argv[++i]; + if (value === undefined || value.startsWith('--')) { + throw new Stop(2, `${flag} requires a value\n${USAGE}`); + } + args[flag] = value.trim(); + } else { + throw new Stop(2, `unknown argument: ${flag}\n${USAGE}`); + } + } + for (const flag of REQUIRED_FLAGS) { + if (!args[flag]) throw new Stop(2, `${flag} is required\n${USAGE}`); + } + + // --path stands alone; otherwise any mix of --harness / --project-dir / --global + // (at least one). `jf` rejects combinations it doesn't support. + const targets = TARGET_FLAGS.filter((flag) => args[flag]); + const validTarget = args['--path'] + ? targets.length === 1 && !args['--global'] + : targets.length > 0 || args['--global']; + if (!validTarget) throw new Stop(2, `invalid install target\n${USAGE}`); + + if (!isSafeId(args['--slug'])) throw new Stop(3, "That skill name isn't valid, so I can't update it."); + return args; +} + +// Never prints the file's value: it is untrusted. +function readInstalledRepo(installDir, slug) { + let repo; + try { + repo = JSON.parse(readFileSync(join(installDir, slug, '.jfrog', 'skill-info.json'), 'utf8')).repo; + } catch { + // A missing or unreadable file is handled like a missing repo. + } + if (!isSafeId(repo)) { + throw new Stop(3, "I can't safely tell which repo this skill was installed from, so I can't update it."); + } + return repo; +} + +function lastErrorLine(text) { + const lines = String(text || '') + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.includes('Trace ID')); + return lines[lines.length - 1] ?? ''; +} + +// Windows runs npx as npx.cmd, which only works through cmd.exe. reject cmd +// metacharacters in the arguments and pass one quoted command string. +const CMD_UNSAFE = /[&|;$<>`"'%^!\r\n]/; + +function runNpx(args, options) { + if (process.platform !== 'win32') return spawnSync('npx', args, options); + if (args.some((arg) => CMD_UNSAFE.test(arg))) throw listingError('unsafe argument'); + const command = ['npx', ...args.map((arg) => `"${arg}"`)].join(' '); + return spawnSync(command, { ...options, shell: process.env.ComSpec || 'cmd.exe' }); +} + +function fetchPage({ slug, project, serverId }, cursor) { + const registry = process.env.JFROG_AGENT_GUARD_REPO || DEFAULT_REGISTRY; + const cursorArgs = cursor ? ['--cursor', cursor] : []; + const result = runNpx( + [ + '--yes', '--registry', registry, '@jfrog/agent-guard', + '--list-skill-versions', '--project', project, '--skill', slug, '--allowed-only', + '--server', serverId, '--format', 'json', ...cursorArgs, + ], + { encoding: 'utf8', timeout: 120_000, stdio: ['ignore', 'pipe', 'pipe'] }, + ); + if (result.error || result.status !== 0) throw listingError(lastErrorLine(result.stderr)); + try { + return JSON.parse(result.stdout.trim()); + } catch { + throw listingError('unreadable response'); + } +} + +// Every allowed repo that hosts the slug. An incomplete listing is an error: +// the repo we need could be on a page we never read. +function listAllowedRepos(query) { + const repos = new Set(); + let cursor = ''; + for (let page = 0; page < MAX_PAGES; page++) { + const data = fetchPage(query, cursor); + for (const version of data.versions ?? []) { + for (const location of version.locations ?? []) { + if (typeof location.repoKey === 'string') repos.add(location.repoKey); + } + } + if (data.exhausted === true) return repos; + if (!data.cursor) throw listingError('incomplete listing'); + cursor = data.cursor; + } + throw listingError('too many pages'); +} + +function targetArgs(args) { + const flags = TARGET_FLAGS.filter((flag) => args[flag]).flatMap((flag) => [flag, args[flag]]); + return args['--global'] ? [...flags, '--global'] : flags; +} + +function runUpdate(args, repo) { + // Always --quiet: an agent shell has no TTY, so a prompt would fail. + const mode = args['--dry-run'] + ? ['--dry-run', '--quiet'] + : ['--version', 'latest', '--quiet', ...(args['--force'] ? ['--force'] : [])]; + process.stdout.write(`Updating from repo: ${repo}\n`); + const result = spawnSync( + 'jf', + [ + 'skills', 'update', args['--slug'], + '--server-id', args['--server-id'], + ...targetArgs(args), + '--repo', repo, + ...mode, + ], + { stdio: 'inherit' }, + ); + if (result.error) throw new Stop(1, 'Could not run the jf CLI'); + // jf's own exit codes must not be read as 2 or 3. + process.exitCode = result.status === 0 ? 0 : 1; +} + +function main() { + const args = parseArgs(process.argv.slice(2)); + const slug = args['--slug']; + + const repo = readInstalledRepo(args['--install-dir'], slug); + const allowed = listAllowedRepos({ slug, project: args['--project'], serverId: args['--server-id'] }); + if (!allowed.has(repo)) { + throw new Stop( + 3, + `\`${slug}\` is installed from \`${repo}\`, which is not governance-allowed for this project, so I can't update it.`, + ); + } + runUpdate(args, repo); +} + +// Set exitCode instead of exiting, so pending output is flushed. +try { + main(); +} catch (error) { + if (error instanceof Stop) { + process.stderr.write(`${error.message}\n`); + process.exitCode = error.code; + } else { + process.stderr.write('Updating the skill failed: an unexpected error occurred.\n'); + process.exitCode = 1; + } +} diff --git a/skills/jfrog-ai-catalog/scripts/list-skill-policies.mjs b/skills/jfrog-ai-catalog/scripts/list-skill-policies.mjs index 705b84f..753622a 100644 --- a/skills/jfrog-ai-catalog/scripts/list-skill-policies.mjs +++ b/skills/jfrog-ai-catalog/scripts/list-skill-policies.mjs @@ -6,7 +6,7 @@ // script's — it hands back structured data, not pre-rendered text. // // Usage: -// node list-skill-policies.mjs --project --server-id +// node list-skill-policies.mjs --project --server-id // // stdout (exit 0): one JSON object, always with these three keys: // - message: non-null only for "no policies apply" (or indistinguishably, @@ -267,7 +267,7 @@ function main() { const { project, serverId } = parseArgs(process.argv.slice(2)); if (!project || !serverId) { process.stderr.write( - 'usage: list-skill-policies.mjs --project --server-id \n' + 'usage: list-skill-policies.mjs --project --server-id \n' ); process.exitCode = 2; throw DONE; diff --git a/skills/jfrog-init/SKILL.md b/skills/jfrog-init/SKILL.md index a0e3372..2bc9a4d 100644 --- a/skills/jfrog-init/SKILL.md +++ b/skills/jfrog-init/SKILL.md @@ -4,7 +4,7 @@ description: Set up and verify the JFrog plugin. Run on first install, to comple disable-model-invocation: true compatibility: >- Requires Node.js 18 or newer, and network access to the JFrog platform. -allowed-tools: Bash(node --version) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-catalog-runtime.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jf-cli.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jf-config.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jfrog-mcp.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-opencode-mcp-auth.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jfrog-mcp-responding.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-project.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-server-ping.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-reinstall-jfrog-plugin.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-state-file.mjs" get*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-state-file.mjs" path*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-resolve-mcp-config.mjs" --harness) Bash(npx --version) Bash(uname:*) AskUserQuestion +allowed-tools: Bash(node --version) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-catalog-runtime.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jf-cli.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jf-config.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jfrog-mcp.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-opencode-mcp-auth.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jfrog-mcp-responding.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-project.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-server-ping.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-reinstall-jfrog-plugin.mjs"*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-ai-governance-config.mjs" get*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-ai-governance-config.mjs" list*) Bash(node "${CLAUDE_SKILL_DIR}/scripts/jfrog-resolve-mcp-config.mjs" --harness) Bash(npx --version) Bash(uname:*) AskUserQuestion metadata: role: workflow --- @@ -17,7 +17,7 @@ Walks a fixed, ordered checklist and stops at the first non-passing result, guid the user through the matching fix before re-checking. Every detector in `scripts/` is idempotent, read-only, JSON-emitting, and implemented in Node (`.mjs`), so the same detector runs unmodified on macOS, Linux, and -Windows. Step 3's web-login uses this skill's own local `.mjs` scripts, +Windows. Step 3's and Step 4's web-login use this skill's own local `.mjs` scripts, same as every other step. The one interactive fix step that isn't a Node script at all is Step 1's Node install itself — a missing Node can't run a `.mjs` installer, so that one step branches on OS or shell directly. @@ -29,19 +29,21 @@ this is just the map: - **`jf` (JFrog CLI)** — `AskUserQuestion` Yes/No before auto-installing (Step 2). - **`jf config`** — `AskUserQuestion` picker (web login, in-session, vs. - access token, which never enters this conversation) (Step 3/4). -- **Project selection** — the user answers with a project name or key; - an `AskUserQuestion` picker offers the first two enumerated projects - plus "Other" (Step 6). -- Everything else is read-only, except: Step 5's placeholder + access token, which never enters this conversation) (Step 3, and + Step 4 for a different AI Governance server). +- **AI Governance server and project** — an `AskUserQuestion` asks + whether the AI Governance server is the same server or a different + one; then "keep ``?" or a picker with the first two enumerated + projects, "No AI Catalog" and "Other" (Step 4). +- Everything else is read-only, except: Step 4's save of the AI + Governance server and project; Step 5's placeholder substitution and OpenCode-only `mcp.jfrog` write (both unattended, no - `AskUserQuestion` — see `references/script-invocation.md`); Step 8's - headers-helper install and Claude Code config writes (same, see `references/marketplace-setup.md`); and - the Final summary's state write below. + `AskUserQuestion` — see `references/script-invocation.md`); and Step 7's + headers-helper install and Claude Code config writes (same, see `references/marketplace-setup.md`). -Step 1's `nvm` install and `jfrog-install-jf-cli.mjs`, Step 3's -web-login scripts, Step 8's `jfrog-add-claude-marketplace.mjs` call, -and the Final summary's `jfrog-state-file.mjs set` call are +Step 1's `nvm` install and `jfrog-install-jf-cli.mjs`, Step 3's and +Step 4's web-login scripts, Step 4's `jfrog-ai-governance-config.mjs set` +call, and Step 7's `jfrog-add-claude-marketplace.mjs` call are deliberately **not** in `allowed-tools` and will raise the harness's own approval prompt — intended, not a misconfiguration; see `references/script-invocation.md`. @@ -81,11 +83,11 @@ Non-Claude harnesses need both. ## At a glance (always-read core) -- **Order matters.** Walk [Steps 1](#step-1-nodejs--18-installed)–[8](#step-8-claude-agent-plugin-marketplace-registered) +- **Order matters.** Walk [Steps 1](#step-1-nodejs--18-installed)–[7](#step-7-claude-agent-plugin-marketplace-registered) in exact order, stop at the first non-passing result — except Step 5's - failure/error outcomes, Step 5b entirely, Step 6's one-retry cap, Step 7's "not - entitled" and "catalog unreachable" outcomes, and Step 8 entirely - (all five non-blocking). See + failure/error outcomes, Step 5b entirely, Step 6's "not + entitled" and "catalog unreachable" outcomes, and Step 7 entirely + (all four non-blocking). See [The checklist, in order](#the-checklist-in-order). - **Capturing the exit code before forcing success is mandatory** (`; rc=$?; true` bash / `; $rc=$LASTEXITCODE; exit 0` PowerShell — see @@ -93,41 +95,39 @@ Non-Claude harnesses need both. bare success-forcer with no capture hides every failure/ask result as success. - **Approval gates:** `AskUserQuestion` Yes/No before auto-installing Node (Step 1) or `jf` (Step 2); `AskUserQuestion` picker for - web-login vs. token (Step 3/4); `AskUserQuestion` picker for project - selection (Step 6). Everything else is read-only except Step 5's + web-login vs. token (Step 3, and Step 4 for a different AI Governance + server); `AskUserQuestion` for the AI Governance server and project + (Step 4). Everything else is read-only except Step 4's save of the AI + Governance server and project, Step 5's placeholder substitution (plus OpenCode `mcp.jfrog` write, and the kiro-cli `~/.kiro/settings/mcp.json` / Junie `~/.junie/mcp/mcp.json` - merge), Step 8's headers-helper install and Claude Code config writes, and the - Final summary's state write. + merge), and Step 7's headers-helper install and Claude Code config writes. - **Never surface the checklist.** Run silently — no step narration, no raw JSON/exit codes, no branch-reasoning said out loud. See `references/invoking-and-output-rules.md`'s "Customer-facing output" section. -- **`` for Steps 4-7** always comes from the shared resolver - (explicit arg → `JF_SERVER_ID` → `isDefault` → sole configured server - → ask) — never invented, never `jf`'s own fallback. Step 8 reuses the - same value. See - [Resolving ``](#resolving-server-id-for-steps-4-7). -- **Persist state before the final summary** — run - `jfrog-state-file.mjs set` whenever Steps 1-4 all pass, regardless of - Step 5/6/7. See [Final summary](#final-summary). +- **`` for Steps 4 and 5** is the jf CLI default server and + always comes from the shared resolver (explicit arg → `isDefault` → + sole configured server → ask) — never invented, never `jf`'s own + fallback. Steps 6 and 7 use `` from Step 4. + See [Resolving ``](#resolving-server-id-for-steps-4-and-5). - **Close with the Final summary.** When Steps 1-4 pass, render the [Final summary](#final-summary) checklist — never end on ad-hoc "Summary / Changes" status text. - **Never store, log, or print an access token** — credentials stay - inside `jf`'s own process or in-memory for one `fetch` call. Step 8 + inside `jf`'s own process or in-memory for one `fetch` call. Step 7 stores none: Claude Code's marketplace config names a helper that asks `jf` at request time — see - [Step 8](#step-8-claude-agent-plugin-marketplace-registered) and + [Step 7](#step-7-claude-agent-plugin-marketplace-registered) and [Non-goals](#non-goals-out-of-scope-for-this-skill). - **This skill is the exception to, not a consumer of, the base [`../jfrog/SKILL.md`](../jfrog/SKILL.md)'s prerequisites** — do not run its environment check as a gate before starting this walk. Steps: [1](#step-1-nodejs--18-installed) → [2](#step-2-jfrog-cli-installed) → -[3](#step-3-jf-connected-to-a-server) → [4](#step-4-server-reachable--credentials-valid) → -[5](#step-5-jfrog-mcp-plugin-file-has-a-jfrog-entry) → [6](#step-6-project-resolved) → -[7](#step-7-ai-catalog-reachable--user-entitled) → -[8](#step-8-claude-agent-plugin-marketplace-registered) +[3](#step-3-jf-connected-to-a-server) → [4](#step-4-server-reachable--ai-governance-server-and-project-set) → +[5](#step-5-jfrog-mcp-plugin-file-has-a-jfrog-entry) → +[6](#step-6-ai-catalog-reachable--user-entitled) → +[7](#step-7-claude-agent-plugin-marketplace-registered) ## Prerequisites @@ -168,47 +168,49 @@ background. It covers three things: 1. **Node.js ≥ 18 installed?** — no script; run `node --version` / `npx --version` directly 2. **JFrog CLI (`jf`) installed?** — `scripts/jfrog-detect-jf-cli.mjs` 3. **`jf` connected to a server?** — `scripts/jfrog-detect-jf-config.mjs` -4. **Server reachable + credentials valid?** — `scripts/jfrog-detect-server-ping.mjs [server-id]` +4. **Server reachable + AI Governance server and project set?** — `scripts/jfrog-detect-server-ping.mjs [server-id]`, then `scripts/jfrog-ai-governance-config.mjs` 5. **JFrog MCP plugin file has a jfrog entry?** — `scripts/jfrog-detect-jfrog-mcp.mjs [server-id]`, then **is the JFrog MCP server enabled on this JPD?** — `scripts/jfrog-detect-jfrog-mcp-responding.mjs [server-id]` (non-blocking) - **5b (OpenCode only): MCP auth token present?** — `scripts/jfrog-detect-opencode-mcp-auth.mjs`, runs only when Step 5 exits 0 and the harness is OpenCode -6. **Project resolved?** — `scripts/jfrog-detect-project.mjs [server-id] [project-input]` -7. **AI Catalog reachable & user entitled?** — `scripts/jfrog-detect-catalog-runtime.mjs [server-id]` -8. **Claude agent-plugin marketplace registered?** — `scripts/jfrog-add-claude-marketplace.mjs [server-id] [project-key]`, Claude Code only +6. **AI Catalog reachable & user entitled?** — `scripts/jfrog-detect-catalog-runtime.mjs [ai-governance-server-id]` +7. **Claude agent-plugin marketplace registered?** — `scripts/jfrog-add-claude-marketplace.mjs [ai-governance-server-id] [ai-governance-project]`, Claude Code only Run detectors in this exact order and stop at the first non-passing result — except Step 5 going into failure/error (see Step 5), Step 5b entirely -(see Step 5b), Step 6 hitting its one-retry cap (see Step 6), Step 7's -"not entitled" and "catalog unreachable" outcomes (see Step 7), and -Step 8 entirely (see Step 8), all five non-blocking. Step +(see Step 5b), Step 6's +"not entitled" and "catalog unreachable" outcomes (see Step 6), and +Step 7 entirely (see Step 7), all four non-blocking. Step 1 has no script — a Node script can't verify Node exists — so every step after it is written in Node and can assume Node is present. The JPD URL is read directly from `jf config`; there is no separate -`JFROG_PLATFORM_URL` env var. The project key is asked every walk in -Step 6 (the state file at `~/.jfrog/setup.json` may supply a -"reuse the current project?" hint); Step 7's catalog probe takes no +`JFROG_PLATFORM_URL` env var. The AI Governance project is asked every +walk in Step 4 (a project saved earlier for that server is offered +first); Step 6's catalog probe takes no project argument — it only checks catalog reachability and entitlement -for the resolved server. +for the AI Governance server. -### Resolving `` for Steps 4-7 +### Resolving `` for Steps 4 and 5 -Order (used by every detector that takes `[server-id]` — resolved +Steps 4 and 5 run against the jf CLI default server. Order (used by +every detector that takes `[server-id]` — resolved through the single shared `scripts/jfrog-resolve-jf-server.mjs`): 1. Explicit argument passed to the detector. -2. `JF_SERVER_ID` env var. -3. **The server flagged `"isDefault": true`** in `~/.jfrog/jfrog-cli.conf.v6` +2. **The server flagged `"isDefault": true`** in `~/.jfrog/jfrog-cli.conf.v6` — resolved automatically via `scripts/jfrog-resolve-jf-server.mjs`. -4. If only one server is configured, it is used silently. -5. Otherwise the detector exits **2 ("ask")** with a JSON `candidates` +3. If only one server is configured, it is used silently. +4. Otherwise the detector exits **2 ("ask")** with a JSON `candidates` list of the configured server IDs. **Stop and read `references/server-picker.md` in full** — it has the exact `AskUserQuestion` payload for showing the user the actual servers to pick from; do not paraphrase or invent your own prompt. Never invent a server, never rely on `jf`'s own fallback. +Steps 6 and 7 run against the AI Governance server and always get +`` from Step 4, so they never ask. + ## Step 1: Node.js ≥ 18 installed? ```bash @@ -287,7 +289,7 @@ checks that `jf config show` returns at least one configured server, regardless of how many there are or whether one is marked `isDefault`. If multiple servers are configured with none marked default, that ambiguity is surfaced starting at Step 4, not here — see "Resolving -`` for Steps 4-7" above. +`` for Steps 4 and 5" above. - **Exit 0** → proceed to Step 4. - **Exit 1** → `jf` is installed but not connected to any @@ -298,7 +300,7 @@ ambiguity is surfaced starting at Step 4, not here — see "Resolving skill), and the token command template — required behavior, not optional background. -## Step 4: Server reachable + credentials valid? +## Step 4: Server reachable + AI Governance server and project set? ```bash node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-server-ping.mjs" "[server-id]"; rc=$?; true @@ -309,6 +311,57 @@ branch table" section in full** — the two sub-checks and the required exit-code branches (credentials-only fix on Exit 1, Exit 2 still blocks) — required behavior, not optional background. +Once the ping passes, the ping's JSON names the jf CLI default server in +`serverId` and gives its URL in `jpdUrl`. + +The AI Governance server is the JFrog Platform server (a jf CLI server ID) +that governs the user's AI assets: its AI Catalog lists the skills, plugins +and MCP servers they may use, and Agent Guard, where the organization has +turned it on, enforces that. The AI Governance project is the JFrog project +on that server that scopes the AI Catalog: which skills, plugins and MCP +servers the user sees and may install. Both are saved in `setup.json` in +the JFrog CLI home directory, separately from the jf CLI default server; +the AI Governance server can be the same server as that default or a +different one. +Read and change the file only through `jfrog-ai-governance-config.mjs`. + +This skill is where the user chooses both. Step 4 asks which server is the +AI Governance server — the jf CLI default server or a different one, which +Step 4 then connects — and which project on it the user works in, or that +they don't use AI Catalog, in which case no project is saved. The other JFrog skills and +the hooks then read both from `setup.json`. The JFrog MCP plugin (Step 5) +keeps using the jf CLI default server either way; Step 6 checks the AI +Catalog on the AI Governance server. Settle both, then save them: + +1. Read what an earlier setup saved: + ```bash + node "${CLAUDE_SKILL_DIR}/scripts/jfrog-ai-governance-config.mjs" get; rc=$?; true + ``` + If `status` is `corrupt`, tell the user in one line that `` + isn't valid and will be replaced, then go on as if nothing was saved. +2. **Stop and read `references/ai-governance-server.md` in full**, then + ask which server it is and which project, as that file says. It ends + with `` (the AI Governance server's ID, + already pinged) and `` (its project key, or + empty when the user doesn't use AI Catalog). +3. Save them: + ```bash + node "${CLAUDE_SKILL_DIR}/scripts/jfrog-ai-governance-config.mjs" set "" "" --force; rc=$?; true + ``` + When `` is empty, pass `--no-project` in place + of `""`. + `--force` is expected here: it saves the AI Governance server and + project in `setup.json`, replacing what is saved there or a broken + file. It does not change jf CLI logins, MCP entries or marketplaces. + The script reads the server's URL from `jf config` itself. + - **Exit 0** → proceed to Step 5. + - **Exit 2** with an `invalid project key` line → the project key was + rejected (this command accepts project keys only): ask for the key + again as `ai-governance-server.md` says, then run this save command + again (once; see that file). Any other exit 2 → show its error line + and stop. + - **Exit 1** → show its error line and stop. + ## Step 5: JFrog MCP plugin file has a jfrog entry? If you are Kiro, Kiro CLI, Copilot in VS Code, or Devin, run only the matching command below. Silent, like every other setup command in this walk. @@ -322,8 +375,8 @@ JFROG_INIT_HARNESS=devin node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jfrog-mc node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-jfrog-mcp.mjs" "[server-id]"; rc=$?; true ``` -Pass the same `` already resolved for Step 4 (empty string -if Step 4 resolved silently via default/single-server) — this reuses +Pass the jf CLI default server's `` from Step 4 (empty string +if Step 4 resolved it silently via default/single-server) — this reuses it for the placeholder fix instead of re-resolving from scratch. **Read-only** against the JFrog plugin's `mcp.json`, with exceptions: substituting @@ -345,14 +398,14 @@ required behavior, not optional. Runs only when Step 5 exits **0** — the exit code, not the JSON `status` field — and the harness is OpenCode. Determine the harness -the same way Step 8 does, with `detectHarness()`: +the same way Step 7 does, with `detectHarness()`: ```bash node "${CLAUDE_SKILL_DIR}/scripts/jfrog-resolve-mcp-config.mjs" --harness ``` If it returns anything other than `opencode`, or Step 5 didn't exit 0, -**skip this step silently** — same treatment as Step 8's preconditions +**skip this step silently** — same treatment as Step 7's preconditions below. Otherwise, run: ```bash @@ -363,51 +416,22 @@ node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-opencode-mcp-auth.mjs"; rc=$?; tr this checks, why a non-empty auth-file key isn't proof of a working token, and the exit-code meanings. -## Step 6: Project resolved? +## Step 6: AI Catalog reachable & user entitled? ```bash -node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-project.mjs" "[server-id]" "[project-input]"; rc=$?; true -``` - -**State reuse across walks.** Before asking the user for a project, -**stop and read `references/project-state-reuse.md` in full** — it has -the exact "reuse ``?" `AskUserQuestion` and the jpdUrl-drift check -this step requires, not optional background. - -Name-or-key input is resolved via exact match, then progressively -fuzzier tiers — see `references/project-matching.md` for the algorithm. - -**Picking a project, interactively.** Whenever the detector needs the -user to choose — no input was passed, the typed input didn't match -anything (404), or it matched more than one project (ambiguous) — -**stop and read `references/project-picker.md` in full before -responding to the user.** It has the exact `AskUserQuestion` payload -shapes for each case (a 404 with close suggestions, an ambiguous or -missing input, and the no-`AskUserQuestion` plain-text fallback) and -the forbidden-phrasing rules for each — this is required behavior for -the step, not optional background. - -**Stop and read `references/project-resolution-branches.md` in full** -for exactly how to branch on the detector's exit code (success / ask / -failure with the one-retry cap / error) — required behavior, not optional -background. - -## Step 7: AI Catalog reachable & user entitled? - -```bash -node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-catalog-runtime.mjs" "[server-id]"; rc=$?; true +node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-catalog-runtime.mjs" ""; rc=$?; true ``` **Stop and read `references/catalog-runtime-branches.md` in full** — the two sub-checks (anonymous reachability, authenticated entitlement) and the required exit-code branches (Exit 1 "not hosted/unreachable" -and Exit 4 "not entitled" are both non-blocking; Exit 2 still blocks) — +and Exit 4 "not entitled" are both non-blocking) — required behavior, not optional background. -## Step 8: Claude agent-plugin marketplace registered? +## Step 7: Claude agent-plugin marketplace registered? -Two preconditions, in this order. **Step 7 must have passed (Exit 0)** — the -marketplace is served by the same AI Catalog that Step 7 probes, so +Two preconditions, in this order. **Step 6 must have passed (Exit 0)** — the +marketplace is served by the same AI Catalog that Step 6 probes, so after a non-blocking failure there (unreachable, or not entitled) there is nothing to register. Then, **Claude Code only** — check the current harness by reusing `detectHarness()` from @@ -417,18 +441,17 @@ uses), e.g. If either precondition fails, **skip this step silently** — never run the script below, no `AskUserQuestion`, no note anywhere, not even in -the Final Summary. Treat it exactly as if Step 8 didn't exist for this +the Final Summary. Treat it exactly as if Step 7 didn't exist for this walk. Otherwise run: ```bash -node "${CLAUDE_SKILL_DIR}/scripts/jfrog-add-claude-marketplace.mjs" "[server-id]" "[project-key]"; rc=$?; true +node "${CLAUDE_SKILL_DIR}/scripts/jfrog-add-claude-marketplace.mjs" "" ""; rc=$?; true ``` -Pass the same `` already resolved for Step 4 (empty string -if Step 4 resolved silently via default/single-server), then Step 6's -canonical project key, or an empty string if Step 6 resolved none. +This also runs when no project was chosen in Step 4: Step 6 found the AI +Catalog available on this server, and the marketplace needs no project. **Stop and read `references/marketplace-setup.md` in full before acting on the exit code** — required behavior, not optional @@ -442,64 +465,44 @@ background. ## Final summary -**Persist the walk's state before rendering any outcome below.** -Whenever Steps 1-4 all pass (regardless of what Step 5/6/7 reported), -run: - -```bash -node "${CLAUDE_SKILL_DIR}/scripts/jfrog-state-file.mjs" set "" "" ""; rc=$?; true -``` - -using the server-id resolved earlier in this walk, Step 4's own -`jpdUrl` field (present in its JSON result when Step 4 passes), and Step 6's project -key — its `resolvedKey` when Step 6 resolves one, or `""` if it never did -(ambiguous input, 404, 403, or the one-retry cap was hit). This is the -only thing that writes `~/.jfrog/setup.json` when the walk is followed -step-by-step; it's the same file Step 6's "reuse ``?" prompt -(`project-state-reuse.md`) reads on a future walk, so skipping this call -means that prompt has nothing to offer next time. Skip it only if Steps -1-4 themselves didn't all pass — there's nothing resolved yet to -persist. (Running the whole walk via `jfrog-detect-all.mjs` instead — -see "Running everything at once" below — does this same write itself; -don't call both.) - **Read `references/final-summary-rendering.md` in full** for the exact recap checklist format, the ⚠️ wording rule per outstanding step, and -Step 8's extra checklist line. +the lines that follow the checklist. ## Running everything at once **Read `references/batch-walk.md` in full** for `jfrog-detect-all.mjs`'s exact semantics — the non-blocking exceptions, the JSON summary -fields, and the state-file write behavior. +fields, and how it saves the AI Governance server and project. ## Non-goals (out of scope for this skill) **Read `references/out-of-scope.md` in full** for the exact list — IDE -plugin/VS Code hook install, first-MCP wizard, project-key -persistence, AI Catalog role grants, and access-token handling. +plugin/VS Code hook install, first-MCP wizard, exporting the project +to a shell, AI Catalog role grants, and access-token handling. ## Before you run `/jfrog-init` — checklist [At a glance](#at-a-glance-always-read-core) invariants: -- [ ] Walk Steps 1-8 in exact order; stop at the first non-passing result - (Step 5's failure/error outcomes, Step 5b entirely, Step 6's retry cap, Step 7 - "not entitled" or "unreachable", and Step 8 entirely are +- [ ] Walk Steps 1-7 in exact order; stop at the first non-passing result + (Step 5's failure/error outcomes, Step 5b entirely, Step 6 + "not entitled" or "unreachable", and Step 7 entirely are non-blocking) - [ ] Every detector invocation captures then forces success (`; rc=$?; true` bash / `; $rc=$LASTEXITCODE; exit 0` PowerShell) — never a bare success-forcer with no capture - [ ] `AskUserQuestion` before auto-installing Node (Step 1) or `jf` - (Step 2); picker for web-login vs. token (Step 3/4); picker for - project selection (Step 6) + (Step 2); picker for web-login vs. token (Step 3, and Step 4 for a + different AI Governance server); AI Governance server and project + questions (Step 4) - [ ] Silent walk — no step narration, no raw JSON/exit codes, no branch-reasoning surfaced to the user -- [ ] `` for Steps 4-8 comes only from the shared resolver — +- [ ] `` for Steps 4 and 5 comes only from the shared resolver — never invented, never `jf`'s own fallback -- [ ] Steps 1-4 all pass → `jfrog-state-file.mjs set - ` before rendering the final summary -- [ ] Never store, log, or print an access token — Step 8 included +- [ ] Step 4 saves the AI Governance server and project with + `jfrog-ai-governance-config.mjs set … --force` +- [ ] Never store, log, or print an access token — Step 7 included - [ ] Read the base `../jfrog/SKILL.md` for context; do not run its environment check as a gate before this walk diff --git a/skills/jfrog-init/references/ai-governance-server.md b/skills/jfrog-init/references/ai-governance-server.md new file mode 100644 index 0000000..b3bb53a --- /dev/null +++ b/skills/jfrog-init/references/ai-governance-server.md @@ -0,0 +1,128 @@ +# Step 4 — the AI Governance server and project + +**Required behavior for Step 4, not optional background.** + +Ask each question below as [how-to-ask-user.md](how-to-ask-user.md) +describes. Use the question and options as written, in the same order, +and only fill in the `<…>` placeholders. The options are the complete +list. There is no recommendation. + +`` is the `serverId` the ping reported for the jf CLI +default server, and `` is the host of its `jpdUrl`. + +`` and `` are set only by +the user's answers below (a saved value counts only once the user picks it) +— never taken from environment variables or MCP entries, and never invented. +Ignore an `info:` line about deprecated environment variables from the +script; don't mention it to the user. + +## Which server + +**Question:** Is your AI Governance server (where your AI Catalog is) +this same JFrog server (``), or a different one? + +**Options:** + +1. **``** — Keep the AI Governance server from your last + setup (``). +2. **Same server or no AI Catalog** — Use ``. Pick this too if + you're not sure. +3. **Different server** — Connect another JFrog Platform for AI + Governance. + +Leave out option 1 unless `get` returned a `serverId` other than +``; that `serverId` is ``, and `` +is the host of the `jpdUrl` that `get` returned. +When `get` returned `ambiguous`, run `jfrog-ai-governance-config.mjs list` +and offer each saved `serverId` other than `` as its own +option 1, with the host of its `jpdUrl` from `list` as ``. + +- **``** → `` is + ``. Ping it (below). If the ping's `detail` says + `no url found in jf config`, the server was removed from the jf CLI + config since: say "`` is no longer in your jf CLI + config." and ask the server question again without that option. +- **Same server or no AI Catalog** → `` is + ``. +- **Different server** → ask in a plain chat message, under the same + rules as Step 3's URL ask in `jf-config-auth-picker.md`: *"Which + JFrog server is your AI Governance server? Give its server ID from + your jf CLI config, or its URL."* Match the answer against + `jf config show --format=json`: + - A `serverId` there → that server is ``. + - A URL equal to a server's `url` (a trailing `/`, `/artifactory` or + `/ui` doesn't matter) → that server's `serverId` is + ``. If several servers have that URL, ask + which one. + - Either way, if that is the jf CLI default server, continue as + **Same server or no AI Catalog**; otherwise ping it (below) — it is + already connected. + - A URL no server has → connect it with Step 3's web-login-or-token + picker and branches in `jf-config-auth-picker.md`, with two + differences: + - Web login: the `SERVER_ID=` line that + `jfrog-login-save-credentials.mjs` prints is + ``. + - Access token: name the server after the start of the URL's host + (`mycompany` for `https://mycompany.jfrog.io`); that name is + ``. If jf config already has a server + with that ID, ask the user for another ID. The command is + `jf config add --url= --interactive`. + - Not a URL and not a `serverId` there → say it isn't in your jf CLI + config and ask again. + + The jf CLI default server stays as it is. Then ping + `` (below). + +Ping the saved or different server with the same detector and branch +table as the jf CLI default server (`jf-config-auth-picker.md`'s +"Step 4's full branch table"): + +```bash +node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-server-ping.mjs" ""; rc=$?; true +``` + +## Which project + +The AI Governance project is a project on the AI Governance server +chosen above; `` is the host of the `jpdUrl` that +server's ping reported. Without AI Catalog there is no project. + +```bash +node "${CLAUDE_SKILL_DIR}/scripts/jfrog-ai-governance-config.mjs" list; rc=$?; true +``` + +If the entry whose `serverId` is `` has a +`project` (``), ask: + +**Question:** Keep `` as your AI Governance project on +``? + +**Options:** + +1. **Yes** — Use `` again. +2. **No** — Pick a different project. + +- **Yes** → `` is ``. +- **No**, or no such entry → run the project picker and follow + `project-picker.md`: + + ```bash + node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-project.mjs" ""; rc=$?; true + ``` + + The key the user picks, or the value they type, is + ``. On **No AI Catalog**, + `` is empty. + +If Step 4's save command (`jfrog-ai-governance-config.mjs set`) rejects the +project key, say *"`` isn't a +project key. Which AI Governance project on `` do +you want to use? If you don't use AI Catalog, say so."*, where `` is +the rejected value; the answer is the next `` +(empty if they don't use AI Catalog). Ask this once; if the save command +rejects the second answer too, show its error and stop — nothing is saved, +and the user can run `/jfrog-init` again once they have the key. + +`setup.json` holds only public identifiers (server IDs, URLs, project +keys) — never a token. diff --git a/skills/jfrog-init/references/batch-walk.md b/skills/jfrog-init/references/batch-walk.md index b6caa0c..96a6c65 100644 --- a/skills/jfrog-init/references/batch-walk.md +++ b/skills/jfrog-init/references/batch-walk.md @@ -1,5 +1,8 @@ # Running everything at once — jfrog-detect-all.mjs +The step numbers on this page are the batch script's own, not the step +numbers of `SKILL.md`. + `node scripts/jfrog-detect-all.mjs [server-id] [project-key]` runs Steps 1–7 in order and stops at the first non-green result — except Step 5 going red/error, Step 5b going red/error, Step 6 going red (ambiguous/404/403), and Step 7 going red @@ -11,16 +14,15 @@ gaps are each reported as separate signals. Step 5b itself only runs when Step 5 came back green **and** `detectHarness()` returns `opencode` — every other harness authenticates MCP tools through `jf config` credentials directly, so there's nothing for it to check. This script makes exactly one -project-resolution attempt per invocation and has no way to tell a -first attempt from a last one, so it always treats a Step 6 red as -non-blocking — the interactive walk (see Step 6 in `SKILL.md`) is what -enforces the one-retry cap before giving up. Steps 5's, 6's, and 7's own +project-resolution attempt per invocation, so it always treats a Step 6 red as +non-blocking — the interactive walk (see Step 4 in `SKILL.md`) is where +the user picks the project. Steps 5's, 6's, and 7's own `ask`/`error` outcomes (ambiguous server-id, no project input passed, `jf` missing/credentials rejected) still block, same as every other step's genuine stop. If no project key is passed, Step 6 emits `ask` with candidates and the walk halts; the caller re-invokes with the picked project as arg 2 — unless that `ask` carries `"unresolved": -"server"`, in which case it's a server pick (see Step 6's branches) and +"server"`, in which case it's a server pick (see `server-picker.md`) and the re-invocation picks server-id (arg 1) instead. Exit 0 = Steps 1-4 green (MCP configured or not, MCP token present or not, @@ -35,15 +37,9 @@ whenever `catalogEntitled` is `false`, and `mcpRespondingReason: Final Summary can name the specific gap instead of a generic one. `mcpAuthed` is `"not_applicable"` on every harness but OpenCode — there is no gap to report where the check never runs, and a boolean there would -conflate "no gap" with "not checked". Writes the -`~/.jfrog/setup.json` state-file hint whenever Steps 1-4 are green, -**regardless of `projectResolved`, `mcpConfigured`, `mcpAuthed`, -`mcpResponding`, or `catalogEntitled`** — the server and JPD URL are worth -remembering on their own, independent of whether a project got picked, the -MCP plugin is wired up, its auth token is present, the MCP server is -enabled on the JPD, or the AI Catalog is reachable/the user is entitled to -it. An unresolved project is passed -to `jfrog-state-file.mjs` as an empty key, which leaves any previously -recorded `currentActiveProject` alone rather than erasing it (see -`jfrog-state-file.mjs`); it's never written as a fresh, unvalidated -value. +conflate "no gap" with "not checked". Whenever Steps 1-4 are green, it +saves the server and project with `jfrog-ai-governance-config.mjs`'s +`set` without `--force`: that never switches away from an AI Governance +server already saved and never changes a saved project. +When several servers are saved and none is the default, it saves +nothing; `/jfrog-init` asks which one. diff --git a/skills/jfrog-init/references/catalog-runtime-branches.md b/skills/jfrog-init/references/catalog-runtime-branches.md index cae6cd5..1d22e79 100644 --- a/skills/jfrog-init/references/catalog-runtime-branches.md +++ b/skills/jfrog-init/references/catalog-runtime-branches.md @@ -1,8 +1,8 @@ -# Step 7 — AI Catalog reachable & entitled: mechanics and branches +# Step 6 — AI Catalog reachable & entitled: mechanics and branches Two sub-checks against `/ml/core/api/v1/mcp-registry/ml-projects?pageSize=1` (where -`` is the URL stored in `jf config` for the resolved server — +`` is the URL stored in `jf config` for the AI Governance server — this skill never uses a separate `JFROG_PLATFORM_URL` env var), both must pass. This step is **purely about AI Catalog access** — no runtime checks (Node lives in Step 1; `uv` / `docker` are per-MCP @@ -37,14 +37,9 @@ which is a genuine setup problem (Exit 3). platform may not host AI Catalog, or it's unreachable right now. **Non-blocking** — same reasoning as Exit 4 below: Steps 1-4 are this skill's core prerequisites, and none of them depend on the AI - Catalog being present. Proceed to the Final Summary, but append a - note naming the gap (`catalogReason: "unreachable"` in + Catalog being present. Proceed to the Final Summary; it shows + `ℹ️ … AI Catalog not available` (`catalogReason: "unreachable"` in `jfrog-detect-all.mjs`'s summary — see `batch-walk.md`). -- **Exit 2 (ask)** → multiple servers configured, none marked - `isDefault`, no server-id passed. Same handling as Step 4's exit 2: - **stop and read `references/server-picker.md` in full**, then - re-invoke Step 7 with the pick as either the positional argument or - `JF_SERVER_ID`. - **Exit 3 (error)** → `jf` missing, the authed probe returned `401` (credentials themselves rejected — re-run `jf config add --interactive`), or an unexpected HTTP code (e.g. a broken `jf` @@ -52,8 +47,8 @@ which is a genuine setup problem (Exit 3). stop this step has — a real error, not a "catalog isn't available" gap. - **Exit 4 (not entitled)** → catalog is reachable but the authed probe - returned `403`. **Non-blocking** — proceed to the Final Summary, but - append the entitlement note (`catalogReason: + returned `403`. **Non-blocking** — proceed to the Final Summary, with + the same line as Exit 1 (`catalogReason: "not_entitled"`). The detector's `detail` names the specific endpoint path (`/ml/core/api/v1/mcp-registry`) and the role the admin needs to grant (typically "AI Catalog Read" or "Application Admin"), so the @@ -61,8 +56,8 @@ which is a genuine setup problem (Exit 3). Exit 1 and Exit 4 are deliberately handled the same way at the walk level (see `batch-walk.md`) — both leave `catalogEntitled: false`, and -only differ in `catalogReason`, so the Final Summary can say "no AI -Catalog here" vs. "you're not entitled" accurately instead of collapsing -both into one generic gap. +only differ in `catalogReason`. The Final Summary says "AI Catalog not +available" for both, marked ℹ️ (see `final-summary-rendering.md`); +`catalogReason` answers the user if they ask why. **Never** grant a role or invent a project. diff --git a/skills/jfrog-init/references/final-summary-rendering.md b/skills/jfrog-init/references/final-summary-rendering.md index f2766c6..0bf926d 100644 --- a/skills/jfrog-init/references/final-summary-rendering.md +++ b/skills/jfrog-init/references/final-summary-rendering.md @@ -34,12 +34,16 @@ Skip the Node.js setup step — implementation detail, not user-facing. > ⚠️ JFrog MCP Plugin — not configured > ✅ Project & AI Catalog - For the merged **Project & AI Catalog** line, if only one of the two - is outstanding name just that one; if both are, separate them with a - semicolon: `⚠️ Project & AI Catalog — project not set up yet; catalog - access not entitled`. + For the merged **Project & AI Catalog** line, a user who answered + **No AI Catalog** has no project and nothing outstanding. An AI Catalog + that is not available (Step 6 exit 1 or exit 4) is information, not a + problem: `ℹ️ Project & AI Catalog — AI Catalog not available`. When the + user answered **No AI Catalog** but Step 6 found the AI Catalog + available (exit 0), say so once, also as information: + `ℹ️ Project & AI Catalog — no project; AI Catalog is available on + (run /jfrog-init to pick a project)`. -5. **Step 8 gets a fourth checklist line, but only when it ran** — +5. **Step 7 gets a fourth checklist line, but only when it ran** — nothing appears when it was skipped: - **Success** — `✅ JFrog Marketplace`, plus this trailing sentence after the checklist block, in this exact wording: @@ -51,6 +55,18 @@ Skip the Node.js setup step — implementation detail, not user-facing. - **Red** — `⚠️ JFrog Marketplace — not registered`, and no trailing sentence. +6. **When the AI Governance server is not the jf CLI default server**, + add this sentence after the checklist block (after Step 7's + sentence, if any): + + > AI Governance uses `` + > (``), project ``; other + > JFrog commands use `` (``). + + Leave out `, project ` when it is empty. + `` and `` are the hosts of the two + servers' `jpdUrl`s from Step 4's pings; they can be the same host. + **If the user asks why** (troubleshooting reference — not part of the render itself): Never phrase a ⚠️ line as a failure or as something the user needs to @@ -83,20 +99,15 @@ has always surfaced, just worded without "pending": summary, never mid-walk**. - **Step 5b red (OpenCode OAuth incomplete):** `not authenticated`. If the user asks, that's when `opencode mcp auth jfrog` comes in. -- **Step 6 hit its retry cap (no project resolved):** `project not set - up yet`. If the user asks, mention they can pick one whenever they're - ready. The server/JPD are still recorded to the state file either way - (see the persistence step at the top of `SKILL.md`'s Final summary - section); a project picked in an earlier walk, if any, is left as-is - rather than cleared. -- **Step 7 returned exit 4 (not entitled):** `catalog access not - entitled`. If the user asks for the fix: ask your JFrog admin for the - "AI Catalog Read" role to browse or install MCPs from the catalog. -- **Step 7 returned exit 1 (catalog not hosted / unreachable):** - `catalog not reachable on this JPD`. No fix instruction; there may be - nothing to fix (this JPD may simply not host the AI Catalog). +- **Step 6 returned exit 4 (not entitled):** `AI Catalog not + available`, ℹ️ (rule 4). If the user asks for the fix: ask your + JFrog admin for the "AI Catalog Read" role to browse or install MCPs + from the catalog. +- **Step 6 returned exit 1 (catalog not hosted / unreachable):** `AI + Catalog not available`, ℹ️ (rule 4). No fix instruction; there may + be nothing to fix (this JPD may simply not host the AI Catalog). - **Something happened this walk** (Node.js/`jf` CLI installed, `jf - config` connected, a project resolved in Step 6, an MCP placeholder + config` connected, a project chosen in Step 4, an MCP placeholder substituted in Step 5, etc.): still the same checklist — the action itself isn't called out per-line, ✅ is ✅ regardless of whether it needed fixing this walk. diff --git a/skills/jfrog-init/references/flow-diagram.md b/skills/jfrog-init/references/flow-diagram.md index d69bce1..81b659f 100644 --- a/skills/jfrog-init/references/flow-diagram.md +++ b/skills/jfrog-init/references/flow-diagram.md @@ -61,7 +61,31 @@ flowchart TD S4ASK -->|Yes| S4 S4ASK -->|No| STOP0C["STOP: user cancelled"]:::stopBox S4 -->|unreachable/timeout/other| STOP2["STOP: show raw error (network/URL hint included)"]:::stopBox - S4 -->|yes| S5 + S4 -->|yes| GET["jfrog-ai-governance-config.mjs get (corrupt: one line, it will be replaced)"]:::stepBox + + GET --> ASKGOV["AskUserQuestion: AI Governance server — saved server (if get returned another serverId), Same server or no AI Catalog, Different server"]:::fixBox + ASKGOV -->|same server / no AI Catalog| LIST + ASKGOV -->|saved server| PINGGOV + ASKGOV -->|different server| ASKURL["Plain chat: AI Governance server"]:::fixBox + ASKURL -->|the jf CLI default server| LIST + ASKURL -->|another server in jf config| PINGGOV + ASKURL -->|not in jf config yet| CONNECT["Web login or access token (Step 3's picker, jf CLI default server unchanged)"]:::fixBox + CONNECT --> PINGGOV["Ping the AI Governance server (Step 4's branch table)"]:::stepBox + PINGGOV -->|yes| LIST + + LIST["jfrog-ai-governance-config.mjs list"]:::stepBox + LIST -->|saved project for this server| ASKKEEP["AskUserQuestion: Keep KEY as your AI Governance project? Yes/No"]:::fixBox + LIST -->|none| ASKPROJ + ASKKEEP -->|Yes| SET + ASKKEEP -->|No| ASKPROJ["AskUserQuestion: first 2 projects (from enumeration), No AI Catalog, or Other to type one"]:::fixBox + ASKPROJ -->|picked or typed| SET + ASKPROJ -->|enumeration failed: jf missing / credentials rejected| STOPCREDS["STOP: show raw error (re-auth via the Step 3 picker)"]:::stopBox + + SET["jfrog-ai-governance-config.mjs set --force"]:::autoBox + SET -->|exit 2, invalid project key| ASKKEY["Plain chat: ask for the project key again (once; rejected again: STOP, nothing saved)"]:::fixBox + ASKKEY --> SET + SET -->|exit 1, or any other exit 2| STOPSET["STOP: show its error line"]:::stopBox + SET -->|exit 0| S5 S5["5. Plugin mcp.json has a valid jfrog entry? (auto-substitutes a JFROG_PLATFORM_URL/JFROG_URL placeholder inline, if present)"]:::stepBox S5 -->|substitution needed, server-id ambiguous| ASKSRV5["AskUserQuestion: pick server-id"]:::fixBox @@ -73,31 +97,21 @@ flowchart TD S5R -->|enabled: ✅ if signed in to this JPD, else offer sign-in AFTER Final Summary| S6 F5R --> S6 - S6["6. Project resolved?"]:::stepBox - S6 -->|state file has current project| ASKREUSE["AskUserQuestion: reuse CURRENT or pick different"]:::fixBox - ASKREUSE -->|reuse| S7 - ASKREUSE -->|different| ASKPROJ["AskUserQuestion: first 2 projects (from enumeration), or Other to type one"]:::fixBox - S6 -->|no state file| ASKPROJ - ASKPROJ -->|picked or typed — accepted verbatim, no probe, no matching| S7 - ASKPROJ -->|enumeration failed: jf missing / credentials rejected| STOPCREDS["STOP: show raw error (re-auth via the Step 3/4 picker)"]:::stopBox - - S7["7. AI Catalog reachable and user entitled?"]:::stepBox - S7 -->|anon 404 / connection failure / 5xx, exit 1| F7U["Note: catalogReason=unreachable — JPD may not host AI Catalog, or it's down right now (non-blocking)"]:::fixBox - F7U --> WRITE - S7 -->|authed 401 or 403, not entitled, exit 4| F7E["Note: catalogReason=not_entitled — ask JFrog admin for AI Catalog Read role (non-blocking)"]:::fixBox - F7E --> WRITE - S7 -->|ambiguous server-id, exit 2| ASKSRV7["AskUserQuestion: which jf server? (server-picker.md), then re-run"]:::fixBox - ASKSRV7 --> S7 - S7 -->|jf missing / credentials rejected / unexpected response shape, exit 3| STOP7["STOP: show raw error — no state file written"]:::stopBox - S7 -->|yes, entitled, exit 0| WRITE["Write state file: server, jpdUrl, and currentActiveProject if resolved (else previous project, if any, is kept) — written on every NON-blocking path out of Step 7"]:::autoBox + S6["6. AI Catalog reachable and user entitled? (AI Governance server)"]:::stepBox + S6 -->|anon 404 / connection failure / 5xx, exit 1| F6U["ℹ️ AI Catalog not available: catalogReason=unreachable — JPD may not host AI Catalog, or it's down right now (non-blocking)"]:::fixBox + F6U --> S7CHECK + S6 -->|authed 401 or 403, not entitled, exit 4| F6E["ℹ️ AI Catalog not available: catalogReason=not_entitled — ask JFrog admin for AI Catalog Read role (non-blocking)"]:::fixBox + F6E --> S7CHECK + S6 -->|jf missing / credentials rejected / unexpected response shape, exit 3| STOP6["STOP: show raw error"]:::stopBox + S6 -->|yes, entitled, exit 0| S7CHECK - WRITE --> S8CHECK{"Step 7 green AND harness == Claude Code? (detectHarness() reused from Step 5)"}:::stepBox - S8CHECK -->|no| DONE - S8CHECK -->|yes| S8["8. Claude agent-plugin marketplace registered?"]:::stepBox - S8 -->|exit 0, success| F8OK["Final Summary: ✅ JFrog Marketplace, plus the trailing sentence"]:::autoBox - S8 -->|exit 1 or 3, failed| F8BAD["Final Summary: ⚠️ JFrog Marketplace — not registered, no cause"]:::fixBox - F8OK --> DONE - F8BAD --> DONE + S7CHECK{"Step 6 green AND harness == Claude Code? (detectHarness() reused from Step 5)"}:::stepBox + S7CHECK -->|no| DONE + S7CHECK -->|yes| S7["7. Claude agent-plugin marketplace registered? (AI Governance server and project)"]:::stepBox + S7 -->|exit 0, success| F7OK["Final Summary: ✅ JFrog Marketplace, plus the trailing sentence"]:::autoBox + S7 -->|exit 1 or 3, failed| F7BAD["Final Summary: ⚠️ JFrog Marketplace — not registered, no cause"]:::fixBox + F7OK --> DONE + F7BAD --> DONE DONE(["JFrog init complete"]):::doneBox diff --git a/skills/jfrog-init/references/how-to-ask-user.md b/skills/jfrog-init/references/how-to-ask-user.md index 7925a68..87d3f5f 100644 --- a/skills/jfrog-init/references/how-to-ask-user.md +++ b/skills/jfrog-init/references/how-to-ask-user.md @@ -20,8 +20,8 @@ add a duplicate "Other" option yourself. returns without a selection, surface the question as plain text in your reply — never silently stop without presenting it. -**Kiro / Kiro CLI / Junie**: check `$JFROG_INIT_HARNESS` (already exported by -Step 5) before reaching for `AskUserQuestion` — if it's `kiro`, +**Kiro / Kiro CLI / Junie**: check `$JFROG_INIT_HARNESS` (exported by +Step 5; before that, whether you are Kiro or Junie) before reaching for `AskUserQuestion` — if it's `kiro`, `kiro-cli`, or `junie`, skip the tool call entirely and use the plain-text fallback directly. Calling it anyway surfaces a "tool does not exist" error to the user before you fall back. diff --git a/skills/jfrog-init/references/jf-cli-update-prompt.md b/skills/jfrog-init/references/jf-cli-update-prompt.md index 59302a8..65a6ce2 100644 --- a/skills/jfrog-init/references/jf-cli-update-prompt.md +++ b/skills/jfrog-init/references/jf-cli-update-prompt.md @@ -48,6 +48,6 @@ guess at a second fix. JFrog CLI v2.106.0 or later, configured for your JFrog Platform, is required for the Agent Plugins Repositories feature this walk's own -Step 7 (AI Catalog) depends on. For more information, see [Configure +Step 6 (AI Catalog) depends on. For more information, see [Configure the JFrog CLI](https://docs.jfrog.com/artifactory/docs/agent-plugins-repositories#configure-the-jfrog-cli) in Agent Plugins Repositories. diff --git a/skills/jfrog-init/references/jf-config-auth-picker.md b/skills/jfrog-init/references/jf-config-auth-picker.md index 124302e..ca951cd 100644 --- a/skills/jfrog-init/references/jf-config-auth-picker.md +++ b/skills/jfrog-init/references/jf-config-auth-picker.md @@ -1,7 +1,7 @@ # jf config: web login vs. access token **Required behavior wherever this file is the referenced fix, not -optional background.** Two distinct call sites land here, with two +optional background.** Three call sites land here, with two different option sets: - **Step 3** (`jf` is installed but not connected to any server at @@ -9,8 +9,10 @@ different option sets: - **Step 4**, when sub-check (1) (reachability) passed but sub-check (2) (`jf rt ping`) failed with an auth-shaped error — `jf` is already connected to a server, its token is just stale. **Token - only** (see "Why Step 4 is token-only" below) — skip straight to + only** (see "Why a stale token gets the Token branch only" below) — skip straight to that section. +- **Step 4, a different AI Governance server** — full picker, with the + two differences listed in `ai-governance-server.md`. ## Step 3: ask web vs. token @@ -169,14 +171,14 @@ the same command and the same `AskUserQuestion` again — the loop is harmless. On **No** → stop with exactly one sentence: *"OK — run `/jfrog-init` again when ready."* Nothing else. -## Why Step 4 is token-only +## Why a stale token gets the Token branch only `jfrog-login-save-credentials.mjs` derives (or overwrites) a server entry **from the URL itself** (`https://mycompany.jfrog.io` → `mycompany`), independent of whatever server-id Step 4 actually -resolved. Running the web-login branch there could silently create a +resolved. Running the web-login branch to refresh a stale token could silently create a *second*, differently-named server instead of refreshing the token on -the one Step 4 is checking — so Step 4 only ever offers the Token +the one Step 4 is checking — so the stale-token fix only ever offers the Token branch above, which explicitly reuses the existing `--server-id`. ## Step 4's full branch table @@ -191,7 +193,7 @@ stale credential before it fails later at runtime. Sub-check (1) green token (the token-only fix above); a 30s timeout points at network/VPN; anything else shows the raw `jf rt ping` error without guessing a cause. -- **Exit 0 (green)** → proceed to Step 5. +- **Exit 0 (green)** → continue with the rest of Step 4. - **Exit 1 (red)** → branch on the detector's `detail`, don't just stop and dead-end on a generic "check with your admin": - **Credentials invalid/expired** (sub-check (1) passed, only the @@ -205,7 +207,7 @@ anything else shows the raw `jf rt ping` error without guessing a cause. - **Exit 2 (ask)** → multiple servers configured, none marked `isDefault`, no server-id passed. **Stop and read `references/server-picker.md` in full**, then re-invoke with the - pick as either the positional argument or `JF_SERVER_ID`. + pick as the positional argument. ## What the token flow never does diff --git a/skills/jfrog-init/references/marketplace-setup.md b/skills/jfrog-init/references/marketplace-setup.md index 1f8a51e..45ad8e7 100644 --- a/skills/jfrog-init/references/marketplace-setup.md +++ b/skills/jfrog-init/references/marketplace-setup.md @@ -1,6 +1,6 @@ -# Step 8 — Claude agent-plugin marketplace +# Step 7 — Claude agent-plugin marketplace -**Required behavior for Step 8, not optional background.** +**Required behavior for Step 7, not optional background.** ## What this step does @@ -22,7 +22,7 @@ server. Claude Code runs the helper on each marketplace and plugin fetch; it asks `jf` for the token at request time, so neither file nor any command line holds it. Discovery also goes through `jf`, so `jf`'s proxy settings apply. -Copies an earlier Step 8 left are removed. A token in another JFrog +Copies an earlier Step 7 left are removed. A token in another JFrog marketplace entry's URL or `Authorization` header is dropped, and an entry on the same JPD gets the same `headersHelper` so it still logs in. After a successful register, the `~/.netrc` block for this JPD's host whose password @@ -46,5 +46,5 @@ All three follow `SKILL.md`'s Final summary rule 5, verbatim. - **Exit 0 (green)** → the ✅ line and the success sentence. - **Exit 1 or 3 (red)** → the ⚠️ line, and nothing about the cause. -- **Skipped (Step 7 not green, or not Claude Code)** → say **nothing**, - exactly as if Step 8 didn't exist for this walk. +- **Skipped (Step 6 not green, or not Claude Code)** → say **nothing**, + exactly as if Step 7 didn't exist for this walk. diff --git a/skills/jfrog-init/references/out-of-scope.md b/skills/jfrog-init/references/out-of-scope.md index 959d767..f0cb3bc 100644 --- a/skills/jfrog-init/references/out-of-scope.md +++ b/skills/jfrog-init/references/out-of-scope.md @@ -4,8 +4,8 @@ - Installing the VS Code hook. - A first-MCP wizard for an empty catalog. - Persisting the picked **project key** to `JF_PROJECT` or any shell - profile. Step 6 asks every walk and threads the pick forward as a - positional argument only — nothing about project selection ever + profile. Step 4 saves it only in the AI Governance settings + (`setup.json`) — nothing about project selection ever touches a shell profile. (Two other, unrelated things in this walk *do*: Step 1's `nvm`-based Node install, and Step 2's Plan C fallback when npm itself isn't usable — both append one PATH line to the @@ -13,12 +13,12 @@ prompts, see `node-install-prompt.md` / `jf-cli-install-prompt.md`. Plans A/B of Step 2 — the common case — don't touch a shell profile at all, relying on npm's own global bin directory instead.) -- Granting AI Catalog roles/permissions — Step 7 only instructs. +- Granting AI Catalog roles/permissions — Step 6 only instructs. - Storing access tokens to disk, logging them, or printing them. Step 4's authenticated check keeps the credential inside `jf`'s own - process (`jf rt ping`); Steps 6 and 7 extract it from `jf config + process (`jf rt ping`); Steps 4 and 6 extract it from `jf config export` only in memory, for one `fetch` call. Step 3/4's token-based `jf config` path (see `references/jf-config-auth-picker.md`) never touches this skill or the model at all — the user runs that command - themselves. Step 8 stores no token either: Claude Code asks `jf` + themselves. Step 7 stores no token either: Claude Code asks `jf` through a helper at request time; see `references/marketplace-setup.md`. diff --git a/skills/jfrog-init/references/project-matching.md b/skills/jfrog-init/references/project-matching.md deleted file mode 100644 index 6d2a184..0000000 --- a/skills/jfrog-init/references/project-matching.md +++ /dev/null @@ -1,40 +0,0 @@ -# Step 6 — project name-or-key resolution algorithm - -Background for Step 6 of `/jfrog-init` (`SKILL.md`). The model doesn't -perform this matching itself — `jfrog-detect-project.mjs` does — but -this explains how a typed name-or-key resolves to a canonical project -key, for debugging an unexpected ambiguous-match or no-match result. - -`jfrog-detect-project.mjs` resolves the input by: - -1. Enumerating accessible projects via `GET /access/api/v1/projects` - (GetProjectsList: - — `fetch` with the token from `jf config export`; the endpoint lives - on the Access service, off the Artifactory root, so `jf rt curl` - cannot reach it; `jf api` is a possible future refactor). Cached per - server for a few minutes (`scripts/lib/project-cache.mjs`) so - re-invoking the detector for each user attempt in the picker doesn't - re-hit the network every time — matching against the list is offline - regardless. -2. Matching the input against `project_key` and `display_name` - (`scripts/lib/projects.mjs`), strictest tier first — each tier only - runs if the previous one had zero matches: - - Exact key (case-insensitive) wins first. - - Exact display-name (case-insensitive) wins next. - - Exact match after stripping every non-alphanumeric character - (`_`, `-`, spaces, ...) from both sides wins next — so `aicatalog` - resolves against key `ai_catalog` / name `ai catalog` without the - separator mattering. This is a fixed internal canonicalization, - never a pattern compiled from user input. - - Unique case-insensitive substring across keys+names wins next. - - Unique substring after the same separator-stripping wins last — - catches partial input that spans a separator, e.g. `aicat` - against `ai_catalog`. - - If more than one project matches at whichever tier first has any - hits, the detector exits red with `candidates` listing the tied - keys, and the model asks the user to be more specific. -3. Once resolved to a canonical key, existence is confirmed via - `GET /access/api/v1/projects/`. - -The detector emits the canonical key on green in the JSON `resolvedKey` -field so the state-file writer can use it. diff --git a/skills/jfrog-init/references/project-picker.md b/skills/jfrog-init/references/project-picker.md index effebf4..e75d720 100644 --- a/skills/jfrog-init/references/project-picker.md +++ b/skills/jfrog-init/references/project-picker.md @@ -1,71 +1,31 @@ -# Step 6 — picking a project interactively +# Step 4 — picking a project interactively -**This is not optional background reading — it's part of Step 6's -required behavior.** Read this in full before handling any Step 6 -result other than a clean green on the first try (no input needed, or -the typed input needs a picker). Use the exact `AskUserQuestion` +**This is not optional background reading — it's part of Step 4's +required behavior.** Read this in full before asking for the AI +Governance project. Use the exact `AskUserQuestion` payload shapes below; do not paraphrase or invent your own wording. -**Everything below — `unresolved`, `candidatesWithNames`, -`similarProjects`, and which bullet you land on — is reasoning for you +**Everything below — `candidatesWithNames` +and which bullet you land on — is reasoning for you to follow silently, never to narrate.** The user never sees why a particular branch was taken, only the resulting prompt (the `AskUserQuestion` payload or the plain-text fallback line). -**Check `unresolved` before anything below.** If the JSON has -`"unresolved": "server"`, this is NOT a project ask — the server-id -itself is ambiguous (multiple jf servers configured, none marked -`isDefault`). This can happen even when re-invoking Step 6 on its own -(e.g. a later "switch project" request), not just on a fresh full -walk. Do not fall through to the project picker below; instead **stop -and read `references/server-picker.md` in full** for the exact -`AskUserQuestion` payload, then re-invoke Step 6 with the picked -server-id as arg 1 (project input, if any, stays arg 2). +`jfrog-detect-project.mjs ""` exits: -Whenever the detector needs the user to choose — no input was passed, -the typed input didn't match anything (404), or it matched more than -one project (ambiguous) — it emits `candidatesWithNames` (the full -enumerated list, `{key, displayName}`, sorted by key) alongside the -red/ask result, as long as enumeration succeeded. Use it to drive an -`AskUserQuestion` picker instead of asking the user to type a key or -name from memory. A confirmed 404 additionally carries -`similarProjects` — up to 2 "did you mean...?" near-misses of the -typed input (see `scripts/lib/projects.mjs`) — which take priority -over the generic first-two when present: - -- **404 with `similarProjects` present** → the typed input was close - to one or two real projects (e.g. typed `widgets20`, JPD has - `widgets2`/`widgets`). Call `AskUserQuestion`, naming what was typed and - offering the suggestions plus "Other": - - ```json - { - "questions": [ - { - "question": "There's no project \"\" — did you mean one of these?", - "header": "Project", - "multiSelect": false, - "options": [ - {"label": "", "description": "Project key: "}, - {"label": "", "description": "Project key: "} - ] - } - ] - } - ``` +- **2 (`ask`)** → ask with the picker below. +- **3 (error)** → `jf` missing or credentials unavailable/rejected. + Show the raw detector error — this is a genuine stop (no re-pick can + fix bad credentials). - If `similarProjects` has only 1 entry, use it as option 1 and fill - option 2 from the first entry of `candidatesWithNames` that isn't - already used (`AskUserQuestion` requires 2 options minimum). If no - such second entry exists (the JPD has exactly this one project), skip - `AskUserQuestion` entirely and use the plain-text fallback below - instead. On picking a suggestion → re-invoke the detector with that - project's **key** as arg 2. On **Other** → the user types a - different name-or-key; re-invoke with their typed value as arg 2. +With the ask result the detector emits `candidatesWithNames` (the full +enumerated list, `{key, displayName}`, sorted by key), as long as +enumeration succeeded. Use it to drive an +`AskUserQuestion` picker instead of asking the user to type a key or +name from memory: -- **Otherwise, if `candidatesWithNames` has 2 or more entries** — no - input was passed, the input was ambiguous, or it was a 404 with no - close-enough `similarProjects` — call `AskUserQuestion` with the +- **If `candidatesWithNames` has 2 or more entries** → call + `AskUserQuestion` with the **first two** entries of `candidatesWithNames` (in the order the detector returned them — never reordered, never chosen by matching the user's name, git identity, hostname, or any other signal) as the @@ -76,53 +36,50 @@ over the generic first-two when present: { "questions": [ { - "question": "Which project do you want to use?", + "question": "Which AI Governance project on do you want to use?", "header": "Project", "multiSelect": false, "options": [ {"label": "", "description": "Project key: "}, - {"label": "", "description": "Project key: "} + {"label": "", "description": "Project key: "}, + {"label": "No AI Catalog", "description": "I don't use AI Catalog."} ] } ] } ``` - On picking option 1 or 2 → re-invoke the detector with that - project's **key** as arg 2. On **Other** → the user types a - name-or-key; re-invoke the detector with their typed value as arg 2. + On picking option 1 or 2 → that project's **key** is + ``. On **No AI Catalog** → + `` is empty. On **Other** → + the user types a name-or-key; their typed value is + ``. - **If `candidatesWithNames` has fewer than 2 entries** (enumeration unavailable, or the JPD genuinely has 0–1 projects) → fall back to a single plain-text line, no `AskUserQuestion`: - > *Which project do you want to use?* + > *Which AI Governance project on `` do you want + > to use? If you don't use AI Catalog, say so.* - Nothing before, nothing after. Do NOT append any hint about the + Nothing before, nothing after. If the user says they don't use AI + Catalog, `` is empty. Do NOT append any hint about the accepted input format (no *"(name or key)"*, no *"you can type a key or name"*, no *"either the display name or key works"*). - **If `AskUserQuestion` is not available as a tool at all** (some - harnesses don't expose it — check `$JFROG_INIT_HARNESS`: `kiro` / + harnesses don't expose it — check `$JFROG_INIT_HARNESS`, or before Step 5 + whether you are Kiro or Junie: `kiro` / `kiro-cli` / `junie` never have it, so skip the tool call and go straight to the fallback instead of calling it and surfacing its error), use the plain-text fallback line above — - *"Which project do you want to use?"*, nothing else — regardless of + nothing else — regardless of how many entries `candidatesWithNames` has. Never explain that the tool is unavailable, never mention the candidate count or that a picker would otherwise have been used; the user only ever sees the one line. - **Never surface the full candidate list or a count** to the user in - any case — the picker's two options (plus "Other") or the plain-text + any case — the picker's options (plus "Other") or the plain-text fallback are the entire user-facing surface. -Once the user picks or types a value, re-invoke the detector with it -as arg 2: - -```bash -node "${CLAUDE_SKILL_DIR}/scripts/jfrog-detect-project.mjs" "" ""; rc=$?; true -``` - -**Do NOT** `export JF_PROJECT=…`. The only state write is the one -SKILL.md's Final summary mandates (`jfrog-state-file.mjs set`), or -`jfrog-detect-all.mjs`'s own write when running the batch walk. +**Do NOT** `export JF_PROJECT=…`. Step 4 saves the project. diff --git a/skills/jfrog-init/references/project-resolution-branches.md b/skills/jfrog-init/references/project-resolution-branches.md deleted file mode 100644 index 51e4e6a..0000000 --- a/skills/jfrog-init/references/project-resolution-branches.md +++ /dev/null @@ -1,46 +0,0 @@ -# Step 6 — resolve branches - -**Required behavior for Step 6, not optional background.** Read this in -full whenever `jfrog-detect-project.mjs` returns anything other than a -clean exit 0. - -**Everything below — exit codes, `unresolved`, and which bullet you -land on — is reasoning for you to follow silently, never to narrate.** -Never repeat this table's own words back to the user (e.g. "Exit 2, -no `unresolved`" or "this is an ask with no input"). The only output -the user sees is the resulting prompt itself, the raw detector error -where one is shown, or the Final Summary. - -- **Exit 2 (`ask`) with `"unresolved": "server"`** → not a project ask - — the server-id is ambiguous. Follow "Resolving `` for - Steps 4-7" in `SKILL.md` (prompt for a server from `candidates`), then - re-invoke Step 6 with the picked server-id as arg 1. -- **No input passed (`ask`/`error`, no `unresolved`)** → enumeration - (`GET /access/api/v1/projects`) runs to drive the picker, and this is - the only remaining way Step 6 can fail to resolve a project: - - **Exit 2 (`ask`)** → use the picker/free-form ask from - `references/project-picker.md`, then re-invoke with the picked - value as arg 2. Whatever the user picks or types is then accepted - verbatim by the Exit 0 branch below — no second round-trip through - matching. - - **Exit 3 (error)** → `jf` missing or credentials unavailable/ - rejected (needed to authenticate the enumeration call). Show the - raw detector error — this is a genuine stop (no re-pick can fix bad - credentials). -- **Input passed (resolve — no matching, no validation)** → accepted - exactly as given, with no network call at all: no per-project - existence/access probe (GetProject requires Platform/Project Admin, - same as the enumeration call — a non-admin caller would just get 403 - from both and never learn whether the project is real), and no - name-or-key matching against the enumerated list either (that also - depended on enumeration succeeding, and could only ever flag two - enumerated projects as ambiguous — never useful to the same - non-admin accounts this exists for). There is no ambiguous (red) - outcome any more; a typed input is always green. - - **Exit 0 (green)** → the input is accepted verbatim; `resolvedKey` - is exactly what was passed, and the detail line says - existence/access was not verified. Proceed to Step 7 - (`jfrog-detect-catalog-runtime.mjs [server-id]`), which takes no - project argument — the input string only needs to be kept around - as arg 2 to `jfrog-detect-all.mjs` itself, so a re-run re-resolves - Step 6 the same way. diff --git a/skills/jfrog-init/references/project-state-reuse.md b/skills/jfrog-init/references/project-state-reuse.md deleted file mode 100644 index 6d18576..0000000 --- a/skills/jfrog-init/references/project-state-reuse.md +++ /dev/null @@ -1,51 +0,0 @@ -# Step 6 — state reuse across walks - -**Required behavior at the start of Step 6, not optional background.** -After a successful walk, `jfrog-detect-all.mjs` writes a hint to -`~/.jfrog/setup.json` containing the resolved JFrog server ID, JPD URL, -and canonical project key (as `currentActiveProject` — no timestamp is -stored; it's a pointer to what's active now, not a usage log). On -subsequent walks, before asking the user for a project, the model MUST: - -1. Read the state file for the current server ID via - `node "${CLAUDE_SKILL_DIR}/scripts/jfrog-state-file.mjs" get-current-project ` - — stdout is JSON `{"currentActiveProject": "...", "jpdUrl": "..."}` - (fields omitted if there's no record for this server-id). -2. If `currentActiveProject` is present AND its `jpdUrl` matches the - URL `jf config show --format=json` reports for this same server-id - today — after stripping any trailing `/artifactory` or `/ui` suffix - and trailing slash from that freshly-read URL, the same - normalization already applied to the stored `jpdUrl` — call - `AskUserQuestion` with this exact payload shape (substituting the - real key for ``). A raw, un-normalized comparison will treat - the server as "repointed" and skip the reuse prompt on every walk - for any JPD whose config URL carries one of those suffixes: - - ```json - { - "questions": [ - { - "question": "Reuse project from your last setup?", - "header": "Project", - "multiSelect": false, - "options": [ - {"label": "Yes", "description": "Use again."}, - {"label": "No", "description": "Pick a different project."} - ] - } - ] - } - ``` - -3. On **Yes** → re-invoke the detector with `` as - arg 2. On **No** → fall through to the picker/free-form ask (see - `project-picker.md`). -4. If the state file has no entry for this server (or the JPD URL - drifted), skip the reuse prompt entirely and go straight to the - picker/free-form ask. - -The state file only stores public identifiers — never a token, -password, session, or any other secret, and never a timestamp. Whenever -Steps 1-4 pass, the Final summary's `jfrog-state-file.mjs set` (or -`jfrog-detect-all.mjs` in the batch walk) updates it atomically (temp -file + rename). diff --git a/skills/jfrog-init/references/script-invocation.md b/skills/jfrog-init/references/script-invocation.md index 1683882..5f0dc02 100644 --- a/skills/jfrog-init/references/script-invocation.md +++ b/skills/jfrog-init/references/script-invocation.md @@ -74,12 +74,12 @@ detectors named individually — `node `jfrog-detect-jf-cli.mjs`, `jfrog-detect-jf-config.mjs`, `jfrog-detect-jfrog-mcp.mjs`, `jfrog-detect-jfrog-mcp-responding.mjs`, `jfrog-detect-opencode-mcp-auth.mjs`, `jfrog-detect-project.mjs`, and -`jfrog-detect-server-ping.mjs` — and `node -"${CLAUDE_SKILL_DIR}/scripts/jfrog-re*.mjs"` (the purely diagnostic -`jfrog-reinstall-jfrog-plugin.mjs` and the two `jfrog-resolve-*.mjs` -lookups), `node -"${CLAUDE_SKILL_DIR}/scripts/jfrog-state-file.mjs" get`/`get-current-project`/`path` -(the read-only modes only), `npx --version`, and `uname`. It does +`jfrog-detect-server-ping.mjs` — and the purely diagnostic `node +"${CLAUDE_SKILL_DIR}/scripts/jfrog-reinstall-jfrog-plugin.mjs"`, +`jfrog-resolve-mcp-config.mjs --harness`, `node +"${CLAUDE_SKILL_DIR}/scripts/jfrog-ai-governance-config.mjs" get`/`list` +(`list` is read-only; `get` only migrates an old `setup.json` in place), +`npx --version`, and `uname`. It does **not** cover: - Step 1's `nvm` install (`curl … | bash`, see `node-install-prompt.md`) @@ -87,15 +87,15 @@ lookups), `node `node-install-prompt.md`) - Step 1's `jfrog-install-jf-cli.mjs` (downloads/executes a binary and edits shell rc files — see `jf-cli-install-prompt.md`) -- Step 3's web-login scripts (`node …/jfrog-login-*.mjs`, see +- Step 3's and Step 4's web-login scripts (`node …/jfrog-login-*.mjs`, see `jf-config-auth-picker.md`) - `jfrog-detect-all.mjs` (the "run everything at once" entry point — see `batch-walk.md`). This is **not** a member of the `jfrog-detect-*.mjs` grant despite the name: an earlier version of this grant used that exact wildcard and pre-approved `jfrog-detect-all.mjs` along with it, silently contradicting the "read-only detectors" framing above — `jfrog-detect-all.mjs` - itself writes `~/.jfrog/setup.json` on overall green (see the Final - summary in `SKILL.md`), the same mutation `jfrog-state-file.mjs set` + itself writes `~/.jfrog/setup.json` on overall green (see + `batch-walk.md`), the same mutation `jfrog-ai-governance-config.mjs set` is excluded below for. PR review caught this; the fix was to enumerate the seven read-only detectors by exact filename instead of a wildcard, which also closes a path-traversal-shaped concern with the wildcard @@ -116,10 +116,10 @@ lookups), `node narrowly scoped to the jfrog entry's `url` field, atomic (temp file + rename), and idempotent — see `mcp-plugin-config.md` for why that scope was judged safe to run unattended, unlike the two mutations below. -- `jfrog-state-file.mjs`'s **`set`** mode (writes `~/.jfrog/setup.json` - with caller-supplied server-id/URL/project-key — see the Final summary +- `jfrog-ai-governance-config.mjs`'s **`set`** mode (writes the AI + Governance server and project to `~/.jfrog/setup.json` — see Step 4 in `SKILL.md`) -- `jfrog-add-claude-marketplace.mjs` (Step 8 — installs the headers helper +- `jfrog-add-claude-marketplace.mjs` (Step 7 — installs the headers helper under `~/.jfrog/skills` and calls `claude plugin marketplace update`, mutating Claude Code's own marketplace config — see `marketplace-setup.md`). **Unlike the other entries in this list, this one has no prior `AskUserQuestion` consent @@ -140,13 +140,13 @@ and web-login already sit behind their own `AskUserQuestion` consent prompt, so the user has agreed before either runs. `jfrog-install-jf-cli.mjs`, `jfrog-substitute-mcp-placeholders.mjs`, -`jfrog-write-opencode-mcp.mjs`, `jfrog-state-file.mjs set`, and +`jfrog-write-opencode-mcp.mjs`, `jfrog-ai-governance-config.mjs set`, and `jfrog-add-claude-marketplace.mjs` are excluded for a related but distinct reason: they're the five scripts in this directory that mutate something outside their own process (a downloaded binary made executable and run, the plugin's `mcp.json`, the user's own OpenCode config — the first mutation targeting a personal file rather than a plugin-owned one -— the setup state file, and the headers helper plus Claude Code's own +— the AI Governance settings, and the headers helper plus Claude Code's own marketplace config, respectively) rather than just reading state and emitting JSON. A prior version of this grant covered every `*.mjs` in `scripts/` @@ -157,16 +157,16 @@ prompt-injected instruction it's following) ever hitting the grant itself enforced nothing. Naming the read-only scripts individually and leaving these four to fall through to the harness's own approval closes that gap — **for `jfrog-install-jf-cli.mjs` and -`jfrog-state-file.mjs set`**, both of which `SKILL.md` only ever runs as +`jfrog-ai-governance-config.mjs set`**, both of which `SKILL.md` only ever runs as their own standalone Bash command, behind their own `AskUserQuestion` -(see `jf-cli-install-prompt.md` and the Final summary, respectively). +(see `jf-cli-install-prompt.md` and Step 4, respectively). `jfrog-substitute-mcp-placeholders.mjs` is the exception: as noted above, it has no standalone Bash call site in the documented flow, so there is no gap for this grant to close for it — its mutation runs unattended by design, not because this list forgot it. `jfrog-add-claude-marketplace.mjs` is a different kind of gap: it *does* -have a standalone Bash call site (Step 8 invokes it directly), but -unlike `jfrog-install-jf-cli.mjs` / `jfrog-state-file.mjs set` there is +have a standalone Bash call site (Step 7 invokes it directly), but +unlike `jfrog-install-jf-cli.mjs` / `jfrog-ai-governance-config.mjs set` there is no `AskUserQuestion` sitting in front of it — the harness's Bash prompt is the only consent point. That asymmetry is called out, not resolved, here; see the bullet above. diff --git a/skills/jfrog-init/references/server-picker.md b/skills/jfrog-init/references/server-picker.md index b5be11b..1d8d38a 100644 --- a/skills/jfrog-init/references/server-picker.md +++ b/skills/jfrog-init/references/server-picker.md @@ -2,13 +2,11 @@ **Required behavior whenever any detector that takes `[server-id]` exits `ask` (`status: "ask"`) with a `candidates` list of server IDs -— not optional background.** This is shared, unmodified, across every -step in "Resolving `` for Steps 4-7" in `SKILL.md`: Step 4 -(`jfrog-detect-server-ping.mjs`), Step 5's placeholder substitution -(`jfrog-detect-jfrog-mcp.mjs`), Step 6 (`jfrog-detect-project.mjs`, -distinguished by `"unresolved": "server"` — see -`references/project-picker.md`), and Step 7 -(`jfrog-detect-catalog-runtime.mjs`). All of them resolve a server-id +— not optional background.** This is shared, unmodified, across both +steps in "Resolving `` for Steps 4 and 5" in `SKILL.md`: +Step 4's ping of the jf CLI default server +(`jfrog-detect-server-ping.mjs`) and Step 5's placeholder substitution +(`jfrog-detect-jfrog-mcp.mjs`). Both resolve a server-id through the same shared code (`scripts/jfrog-resolve-jf-server.mjs`), so `candidates` is always the same shape: a plain array of configured server-id strings, e.g. `["prod", "staging"]`. @@ -44,5 +42,5 @@ with the picked/typed server-id as the positional argument that step expects (see that step's own usage line in `SKILL.md`). Never invent a server-id, never rely on `jf`'s own default-resolution fallback — the whole point of asking is that this skill's own resolution order -(explicit arg → `JF_SERVER_ID` → `isDefault` → sole server) already +(explicit arg → `isDefault` → sole server) already came up empty. diff --git a/skills/jfrog-init/scripts/jfrog-add-claude-marketplace.mjs b/skills/jfrog-init/scripts/jfrog-add-claude-marketplace.mjs index 15f3a17..5c7295b 100755 --- a/skills/jfrog-init/scripts/jfrog-add-claude-marketplace.mjs +++ b/skills/jfrog-init/scripts/jfrog-add-claude-marketplace.mjs @@ -146,7 +146,7 @@ export function dropNetrcToken(content, host, token) { return entries.map((words, i) => (i > 0 && holdsToken(words) ? "" : content.slice(starts[i], starts[i + 1]))).join(""); } -// The previous Step 8 wrote `machine / login / password ` into +// The previous Step 7 wrote `machine / login / password ` into // ~/.netrc, and libcurl still sends it on plugin fetches. Only that block goes: // through any symlink, so a dotfiles copy loses it too, and keeping the mode. function removeNetrcToken(host, token) { diff --git a/skills/jfrog-init/scripts/jfrog-ai-governance-config.mjs b/skills/jfrog-init/scripts/jfrog-ai-governance-config.mjs new file mode 100755 index 0000000..db7f8aa --- /dev/null +++ b/skills/jfrog-init/scripts/jfrog-ai-governance-config.mjs @@ -0,0 +1,548 @@ +#!/usr/bin/env node +// jfrog-ai-governance-config.mjs — resolve and update the JFrog AI Governance +// server and project in ${JFROG_CLI_HOME_DIR:-~/.jfrog}/setup.json. +// +// Usage, commands, options and exit codes: see USAGE below (also printed on a +// usage error). +// +// Contract: +// - Exactly one entry has `isDefault`. A v1 file with a single entry is +// treated as its default and migrated (written back as v2) by `get`. +// - `set` on an ambiguous file (no clear default) needs no --force and +// leaves the target as the only default. +// - A file whose `version` is newer than this script knows is read, but +// never written. +// - Unknown keys are preserved on every write. +// - Writes are temp file + rename, no lock. +// - stderr: an `info:` line if deprecated env vars are set; `debug:` lines +// with JF_AGENT_GUARD_LOG_LEVEL=debug. +// - Self-contained (Node builtins only): copied verbatim into the hooks, +// which import resolveAiGovernanceConfig and run `server-id`. +// +// File shape: +// { "version", "servers": { "": { "jpdUrl", "currentActiveProject"?, +// "isDefault"? } } } + +import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { + mkdirSync, + readFileSync, + realpathSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const USAGE = `\ +Usage: jfrog-ai-governance-config.mjs [options] + +Commands: + get Print the AI Governance server and project as JSON: + {status, serverId?, jpdUrl?, project?, path?}. + status: ok | no_project | ambiguous | missing | corrupt + (corrupt: setup.json is not valid; path names it). + list Print every saved server as a JSON array of + {serverId, jpdUrl, project?, isDefault}. + set [project] Make the AI Governance server (jpdUrl + from \`jf config show\`). + Project omitted: keep the saved one. + server-id Print only the server id, for command substitution. + Prints nothing if the id is invalid (see set). + Always exits 0. + +Options: + --no-project set: save no project; clears a saved one (needs --force). + --force set: override the saved server or project, or + replace a corrupt file. Only when you know what + you are doing. + +Environment: + JF_AGENT_GUARD_LOG_LEVEL=debug Print debug lines on stderr. + +Exit codes: + 0 ok + 1 set failed (message on stderr) + 2 usage error +`; +const CURRENT_VERSION = 2; +const DEPRECATED_ENV = [ + "JFROG_URL", + "JF_URL", + "JFROG_ACCESS_TOKEN", + "JF_ACCESS_TOKEN", + "JF_PROJECT", + "JFROG_PROJECT", + "JF_SERVER", + "JFROG_SERVER_ID", + "JF_SERVER_ID", +]; +const NOOP_LOG = { debug() {} }; +// The charset the hooks accept for ids passed to agent-guard. The jf CLI does +// not limit server ids (it only rejects delete, use, show, clear): enforced here. +const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const SAFE_ID_RULE = + 'letters, digits, ".", "_" or "-", starting with a letter or digit, at most 128 characters'; + +// import.meta.url is symlink-resolved, argv[1] is not; compare real paths. +function isMainModule(moduleUrl) { + if (!process.argv[1]) return false; + try { + return fileURLToPath(moduleUrl) === realpathSync(process.argv[1]); + } catch { + return false; + } +} + +const isObject = (v) => + v !== null && typeof v === "object" && !Array.isArray(v); +const nonEmpty = (v) => typeof v === "string" && v !== ""; + +function aiGovernanceConfigPath(env) { + return join( + env.JFROG_CLI_HOME_DIR || join(homedir(), ".jfrog"), + "setup.json", + ); +} + +// A missing file has no entries. A file that exists but is unreadable, not a +// JSON object, or has a non-object `servers` is `corrupt` (and has no data). +function loadSetup(path, log) { + const corrupt = { data: null, entries: [], corrupt: true }; + let parsed; + try { + parsed = JSON.parse(readFileSync(path, "utf8")); + } catch (err) { + if (err.code === "ENOENT") { + log.debug(`no setup.json at ${path}`); + return { data: null, entries: [], absent: true }; + } + log.debug( + err instanceof SyntaxError + ? `${path} is not valid JSON` + : `could not read ${path}: ${err.code || err.message}`, + ); + return corrupt; + } + if (!isObject(parsed)) { + log.debug(`${path} is not a JSON object`); + return corrupt; + } + if (parsed.servers !== undefined && !isObject(parsed.servers)) { + log.debug(`${path}: "servers" is not an object`); + return corrupt; + } + const entries = Object.entries(parsed.servers ?? {}).filter(([, e]) => + isObject(e), + ); + return { data: parsed, entries }; +} + +const isNewer = (data) => + typeof data?.version === "number" && data.version > CURRENT_VERSION; + +// The entry `get` would select, or null when ambiguous. A lone entry without +// isDefault is the implied default. +function select(entries) { + const defaults = entries.filter(([, e]) => e.isDefault === true); + if (defaults.length === 1) { + return { id: defaults[0][0], entry: defaults[0][1], implied: false }; + } + if (defaults.length === 0 && entries.length === 1) { + return { id: entries[0][0], entry: entries[0][1], implied: true }; + } + return null; +} + +function writeAtomic(path, data) { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`; + try { + // "wx" fails if anything (e.g. a planted symlink) already exists at tmp. + writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { + flag: "wx", + mode: 0o644, + }); + renameSync(tmp, path); + } catch (err) { + try { + unlinkSync(tmp); + } catch { + // Never created or already renamed. + } + throw err; + } +} + +/** + * Select the AI Governance server from setup.json, migrating a lone v1 entry to v2. + * @param {object} [options] + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{status: "missing" | "ambiguous"} + * | {status: "corrupt", path: string} + * | {status: "ok" | "no_project", serverId: string, jpdUrl: string, project?: string}} + * corrupt: the file exists but is not a valid setup object. + */ +export function resolveAiGovernanceConfig({ + env = process.env, + log = NOOP_LOG, +} = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + const { data, entries, corrupt } = loadSetup(path, log); + if (corrupt) return { status: "corrupt", path }; + if (entries.length === 0) { + log.debug("missing: no usable entries"); + return { status: "missing" }; + } + const sel = select(entries); + if (!sel) { + const marked = entries.filter(([, e]) => e.isDefault === true).length; + log.debug( + marked + ? `ambiguous: ${marked} entries marked isDefault` + : `ambiguous: ${entries.length} entries, none marked isDefault`, + ); + return { status: "ambiguous" }; + } + log.debug( + `default "${sel.id}" (${sel.implied ? "only entry, implied" : "explicit isDefault"})`, + ); + if (sel.implied && !isNewer(data)) { + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: { + ...data.servers, + [sel.id]: { ...sel.entry, isDefault: true }, + }, + }); + log.debug(`migrated ${path}: "${sel.id}" is now the default`); + } catch (err) { + log.debug(`migration write to ${path} failed: ${err.message}`); + } + } + const base = { serverId: sel.id, jpdUrl: sel.entry.jpdUrl }; + const project = sel.entry.currentActiveProject; + if (nonEmpty(project)) return { status: "ok", ...base, project }; + log.debug(`no_project: "${sel.id}" has no currentActiveProject`); + return { status: "no_project", ...base }; +} + +// Same as `get` but never migrates. +function listAiGovernanceConfig({ env = process.env, log = NOOP_LOG } = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + return loadSetup(path, log) + .entries.map(([serverId, e]) => ({ + serverId, + jpdUrl: e.jpdUrl, + ...(nonEmpty(e.currentActiveProject) && { + project: e.currentActiveProject, + }), + isDefault: e.isDefault === true, + })) + .sort((a, b) => a.serverId.localeCompare(b.serverId)); +} + +// Platform root URL, or "" when `raw` is not an http(s) URL. A missing scheme +// means https. +function normalizeJpdUrl(raw) { + const s = raw.trim(); + try { + const url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(s) ? s : `https://${s}`); + if (!["http:", "https:"].includes(url.protocol)) return ""; + return url.origin + url.pathname.replace(/(\/(artifactory|ui))*\/*$/, ""); + } catch { + return ""; + } +} + +// Returns the server list, or null when jf could not be run or its output +// was unusable (reported to the caller as "could not run jf", distinct from +// "server not configured"). jf is looked up on PATH only. +function loadJfServers(env, log) { + // On Windows an npm-installed jf is a .cmd shim, which only a shell can + // launch; the command is a constant, so passing it as one string is safe. + const opts = { encoding: "utf8", env, timeout: 30_000 }; + const r = + process.platform === "win32" + ? spawnSync("jf config show --format=json", { ...opts, shell: true }) + : spawnSync("jf", ["config", "show", "--format=json"], opts); + if (r.error || r.status !== 0) { + log.debug( + `jf config show failed: ${r.error?.message || `exit ${r.status}`}`, + ); + return null; + } + try { + const parsed = JSON.parse(r.stdout); + if (Array.isArray(parsed)) return parsed; + if (Array.isArray(parsed?.servers)) return parsed.servers; + } catch (err) { + log.debug(`jf config show output not parseable: ${err.message}`); + } + return null; +} + +/** + * Make serverId the AI Governance server. + * Without force it refuses to switch away from another default server, and to + * change or clear the saved non-empty project. An empty project is an error: + * pass noProject to save none. + * @param {string} serverId jf CLI server id + * @param {string} [project] undefined keeps the saved project (unless noProject) + * @param {object} [options] + * @param {boolean} [options.force] override the refusals above + * @param {boolean} [options.noProject] save no project; excludes a project + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{ok: true} | {ok: false, error: string}} + */ +export function setAiGovernanceConfig( + serverId, + project, + { force = false, noProject = false, env = process.env, log = NOOP_LOG } = {}, +) { + if (project === "") { + return { + ok: false, + error: "an empty project is not accepted; pass noProject to unset", + }; + } + if (noProject && project !== undefined) { + return { + ok: false, + error: "project and noProject are mutually exclusive", + }; + } + if (noProject) project = ""; + if (nonEmpty(project) && !SAFE_ID.test(project)) { + return { + ok: false, + error: `invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}`, + }; + } + if (!SAFE_ID.test(serverId)) { + return { + ok: false, + error: `invalid server id ${JSON.stringify(serverId)}: ${SAFE_ID_RULE}; re-add the server to the jf CLI under a valid id`, + }; + } + const path = aiGovernanceConfigPath(env); + const { data, entries, absent, corrupt } = loadSetup(path, log); + if (corrupt && !force) { + return refuse(`${path} is corrupt`, log); + } + if (isNewer(data)) { + return refuse( + `${path} was written by a newer version (${data.version}); refusing to modify it`, + log, + ); + } + const current = select(entries); + const previous = entries.find(([id]) => id === serverId)?.[1]; + // The project to protect is the target's own; it matters only when there is + // no default or the target is the default. + const existing = previous?.currentActiveProject; + const currentProject = current?.entry.currentActiveProject; + log.debug( + current + ? `current default: "${current.id}" (${nonEmpty(currentProject) ? `project "${currentProject}"` : "no project"})` + : "no current default", + ); + if (current && current.id !== serverId) { + if (!force) { + return refuse( + `the AI Governance server in ${path} is "${current.id}"; setting "${serverId}" would change it`, + log, + ); + } + log.debug(`switching default "${current.id}" -> "${serverId}" (--force)`); + } else if ( + previous && + project !== undefined && + project !== (existing ?? "") + ) { + if (!force && nonEmpty(existing)) { + const change = nonEmpty(project) ? `setting "${project}"` : "clearing it"; + return refuse( + `"${serverId}" uses project "${existing}"; ${change} would change it`, + log, + ); + } + log.debug( + nonEmpty(project) + ? `setting project of "${serverId}" to "${project}"` + : `clearing project of "${serverId}"`, + ); + } else if (current) { + log.debug(`"${serverId}" is already the default; refreshing`); + } else { + log.debug(`new default "${serverId}"`); + } + // The jf CLI is consulted only once the saved state allows the change, so a + // refusal names the saved server, not a missing jf config entry. + const jfServers = loadJfServers(env, log); + if (!jfServers) { + return { + ok: false, + error: + "could not run `jf config show`; is the JFrog CLI installed and on PATH?", + }; + } + const jpdUrlOf = (s) => + normalizeJpdUrl(`${s.url ?? ""}`.trim() || `${s.artifactoryUrl ?? ""}`); + const jf = jfServers.find( + (s) => isObject(s) && s.serverId === serverId && jpdUrlOf(s), + ); + log.debug( + `jf config show returned servers: ${jfServers + .filter(isObject) + .map((s) => s.serverId) + .join(", ")}`, + ); + if (!jf) { + log.debug(`"${serverId}" not found in jf config show`); + return { + ok: false, + error: `server "${serverId}" is not in the jf CLI config`, + }; + } + log.debug(`"${serverId}" -> ${jpdUrlOf(jf)}`); + const nextServers = Object.fromEntries( + entries.map(([id, e]) => { + const { isDefault: _drop, ...rest } = e; + return [id, rest]; + }), + ); + const { currentActiveProject: saved, ...kept } = previous ?? {}; + const nextProject = project === undefined ? saved : project; + nextServers[serverId] = { + ...kept, + jpdUrl: jpdUrlOf(jf), + ...(nonEmpty(nextProject) && { currentActiveProject: nextProject }), + isDefault: true, + }; + log.debug(`${absent ? "creating" : "updating"} ${path}`); + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: nextServers, + }); + } catch (err) { + log.debug(`write to ${path} failed: ${err.message}`); + return { ok: false, error: `write failed: ${err.message}` }; + } + log.debug(`wrote ${path}`); + return { ok: true }; +} + +function refuse(error, log) { + log.debug(`refused: ${error}`); + return { ok: false, error }; +} + +function usage() { + process.stderr.write(USAGE); + return 2; +} + +function main(argv, env) { + const [mode, ...rest] = argv; + const log = { + debug: (m) => + env.JF_AGENT_GUARD_LOG_LEVEL === "debug" && + process.stderr.write(`debug: ${m}\n`), + }; + + if (mode === "server-id") { + try { + const cfg = resolveAiGovernanceConfig({ env, log }); + if (cfg.status === "ok" || cfg.status === "no_project") { + if (!SAFE_ID.test(cfg.serverId)) { + log.debug( + `server-id: ${JSON.stringify(cfg.serverId)} not printed: invalid id (${SAFE_ID_RULE})`, + ); + } else { + process.stdout.write(`${cfg.serverId}\n`); + } + } + } catch { + // Always exit 0 with no output: callers use this in $(...). + } + return 0; + } + + const flags = ["--force", "--no-project"]; + const [serverId, project, ...extra] = rest.filter((a) => !flags.includes(a)); + const force = rest.includes("--force"); + const noProject = rest.includes("--no-project"); + const argsOk = + mode === "set" + ? nonEmpty(serverId) && !extra.length && !(noProject && project) + : !rest.length; + const stray = rest.some((a) => a.startsWith("-") && !flags.includes(a)); + const badProject = nonEmpty(project) && !SAFE_ID.test(project); + if (badProject) { + process.stderr.write( + `ai-governance-config: invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}\n`, + ); + } + const emptyProject = mode === "set" && project === ""; + if (emptyProject) { + process.stderr.write( + "ai-governance-config: an empty project is not accepted; use --no-project to unset\n", + ); + } + if ( + !["get", "list", "set"].includes(mode) || + !argsOk || + stray || + badProject || + emptyProject + ) { + return usage(); + } + + const used = DEPRECATED_ENV.filter((name) => nonEmpty(env[name])); + if (used.length) { + process.stderr.write( + `info: ${used.join(", ")} set but ignored (deprecated); AI Governance config comes from ${aiGovernanceConfigPath(env)}. Continuing normally without using them.\n`, + ); + } + + if (mode === "get") { + process.stdout.write( + JSON.stringify(resolveAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + if (mode === "list") { + process.stdout.write( + JSON.stringify(listAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + const result = setAiGovernanceConfig(serverId, project, { + force, + noProject, + env, + log, + }); + if (!result.ok) { + process.stderr.write(`ai-governance-config: ${result.error}\n`); + return 1; + } + return 0; +} + +if (isMainModule(import.meta.url)) { + process.exitCode = main(process.argv.slice(2), process.env); +} diff --git a/skills/jfrog-init/scripts/jfrog-detect-all.mjs b/skills/jfrog-init/scripts/jfrog-detect-all.mjs index 175ce34..9483d3f 100755 --- a/skills/jfrog-init/scripts/jfrog-detect-all.mjs +++ b/skills/jfrog-init/scripts/jfrog-detect-all.mjs @@ -5,7 +5,8 @@ // resolveMcpConfig) creates or merges the tool's own global MCP config // (~/.kiro/settings/mcp.json or ~/.junie/mcp/mcp.json) when the jfrog entry // is absent, the same write that jfrog-detect-jfrog-mcp.mjs performs; -// (2) on green, a state-file hint is written to ~/.jfrog/setup.json. +// (2) on green, the AI Governance server and project are saved to +// setup.json when none is saved yet (see jfrog-ai-governance-config.mjs). // // Usage: node jfrog-detect-all.mjs [server-id] [project-input] // @@ -26,10 +27,9 @@ // // Step 6 does NOT read JF_PROJECT and does NOT export anything. The // picked project input is passed as the 2nd positional argument and -// threaded forward. On green, this script writes a hint to -// ~/.jfrog/setup.json so subsequent walks can offer "reuse the current -// project" — the file only stores public identifiers (server ID, JPD -// URL, canonical project key), never secrets, never a timestamp. +// threaded forward. On green, this script saves the server and project +// via setAiGovernanceConfig WITHOUT force: it never switches away from a +// saved AI Governance server or changes its saved project. // // Step 7 going red — exit 1 (catalog not hosted at this JPD / unreachable // / 5xx) OR exit 4 (reachable but not entitled) — is NON-BLOCKING: Steps @@ -63,10 +63,8 @@ // `projectResolved`. Exit 3 (jf missing, credentials rejected, or an // unexpected response shape) is a genuine error, NOT covered by this // non-blocking treatment — same as Step 5's own exit 2, it still sets -// `overall = 1`. The state-file write still happens (server + JPD -// URL known is reason enough to remember them) — it's passed an empty -// project key, and jfrog-state-file.mjs keeps whatever project was -// already on record rather than erasing it. An ambiguous server-id +// `overall = 1`. The save still happens (the server is known) — with +// an empty project key, so a saved project is kept. An ambiguous server-id // (exit 2, "ask") still blocks, same reasoning as Step 5. // // Exit 0 -> Steps 1-4 green (see catalogEntitled / mcpConfigured / @@ -74,7 +72,7 @@ // non-blocking gaps) // Exit 1 -> a check failed / went red / requires action -import { emit, jfAvailable, jfConfigShow, urlForServer, normalizeJpdUrl } from "./lib/jf.mjs"; +import { emit, jfAvailable, jfConfigShow } from "./lib/jf.mjs"; import { commandExists } from "./lib/command.mjs"; import { resolveJfServer } from "./jfrog-resolve-jf-server.mjs"; import { detectJfCli } from "./jfrog-detect-jf-cli.mjs"; @@ -86,7 +84,7 @@ import { detectOpencodeMcpAuth } from "./jfrog-detect-opencode-mcp-auth.mjs"; import { detectJfrogMcpResponding } from "./jfrog-detect-jfrog-mcp-responding.mjs"; import { detectProject } from "./jfrog-detect-project.mjs"; import { detectCatalogRuntime } from "./jfrog-detect-catalog-runtime.mjs"; -import { setStateForServer } from "./jfrog-state-file.mjs"; +import { setAiGovernanceConfig, resolveAiGovernanceConfig } from "./jfrog-ai-governance-config.mjs"; const SERVER_ID = process.argv[2] || ""; const PROJECT_KEY = process.argv[3] || ""; @@ -117,9 +115,9 @@ if (overall === 0 && (await detectServerPing(SERVER_ID)) !== 0) overall = 1; // Captured here, before Steps 5-7 can flip `overall` for their own // blocking sub-cases (ambiguous server-id, no project input, jf missing — -// see each step's comment below) — the state-file write further down +// see each step's comment below) — the save further down // keys off THIS flag, not the final `overall`, per batch-walk.md: the -// write happens whenever Steps 1-4 are green, regardless of the +// save happens whenever Steps 1-4 are green, regardless of the // mcpConfigured/projectResolved/catalogEntitled gaps Steps 5-7 report. const steps1To4Passed = overall === 0; @@ -173,9 +171,8 @@ if (overall === 0) { // Exit 2 (ask): no input passed, or the server-id itself is // ambiguous — nothing to report a gap about yet, the caller just // needs to provide one. Exit 3 (error): jf missing, credentials - // rejected, or an unexpected response shape — a genuine failure, NOT - // subject to the retry cap (see SKILL.md Step 6 / flow-diagram.md's - // STOPCREDS), so it must block same as any other real error, not + // rejected, or an unexpected response shape — a genuine failure (see + // flow-diagram.md's STOPCREDS), so it must block same as any other real error, not // silently collapse into "no project resolved yet". overall = 1; } else if (projectResult.exitCode === 0) { @@ -220,31 +217,25 @@ if (steps1To4Passed) { if (jfAvailable()) { const configList = jfConfigShow(); const resolvedServerId = resolveJfServer(SERVER_ID, configList); - const resolvedJpdUrl = normalizeJpdUrl(urlForServer(configList, resolvedServerId)); - // Only pass a project key that was actually validated to the state - // file — PROJECT_KEY itself can be non-empty (the caller's raw, - // unvalidated input) even when projectResolved is false; passing "" - // in that case tells jfrog-state-file.mjs to leave any previously - // recorded project alone rather than overwrite it with an unverified - // value. + // Only pass a project key that was actually validated — PROJECT_KEY + // itself can be non-empty (the caller's raw, unvalidated input) even + // when projectResolved is false. No resolved key passes undefined + // below, which keeps any saved project ("" would clear it). let resolvedProjectKey = ""; if (projectResolved) { resolvedProjectKey = projectResult?.resolvedKey || PROJECT_KEY; } - if (resolvedServerId && resolvedJpdUrl) { - // Best-effort: the state file is a "reuse last project?" hint, not a - // source of truth (see jfrog-state-file.mjs) — a write failure here - // doesn't undo the fact that Steps 1-4 above passed, so it's - // surfaced as a warning rather than flipping the summary to red. - // Written even when resolvedProjectKey is "" (project not resolved - // this walk) — jfrog-state-file.mjs then keeps whatever project was - // already on record instead of erasing it, and callers can always - // tell a project is missing here from `projectResolved` above. - const stateResult = setStateForServer(resolvedServerId, resolvedJpdUrl, resolvedProjectKey); - if (!stateResult.ok) { - console.error(`warning: failed to save setup state (${stateResult.error}) — next walk won't offer to reuse this project`); + // Several saved servers and none the default: the user picks one in /jfrog-init, so nothing is saved here. + if (resolvedServerId && resolveAiGovernanceConfig().status !== "ambiguous") { + // Best-effort, no force: a refusal (a server or project is already + // saved) or a write failure doesn't undo that Steps 1-4 passed, so it + // is a warning, not a red summary. Without a resolved project it keeps + // any saved one; callers see a missing project in `projectResolved`. + const saveResult = setAiGovernanceConfig(resolvedServerId, resolvedProjectKey || undefined); + if (!saveResult.ok) { + console.error(`warning: AI Governance server/project not saved (${saveResult.error})`); } } } diff --git a/skills/jfrog-init/scripts/jfrog-detect-jf-cli.mjs b/skills/jfrog-init/scripts/jfrog-detect-jf-cli.mjs index 7352bc5..77b1891 100755 --- a/skills/jfrog-init/scripts/jfrog-detect-jf-cli.mjs +++ b/skills/jfrog-init/scripts/jfrog-detect-jf-cli.mjs @@ -16,7 +16,7 @@ import { emit, isMainModule, runJf, seedJfAvailable } from "./lib/jf.mjs"; -// Required by Agent Plugins Repositories (Step 7's AI Catalog calls) — +// Required by Agent Plugins Repositories (Step 6's AI Catalog calls) — // see docs.jfrog.com/artifactory/docs/agent-plugins-repositories // ("Configure the JFrog CLI"). export const MIN_JF_VERSION = "2.106.0"; diff --git a/skills/jfrog-init/scripts/jfrog-detect-server-ping.mjs b/skills/jfrog-init/scripts/jfrog-detect-server-ping.mjs index c72d0db..67fb37e 100755 --- a/skills/jfrog-init/scripts/jfrog-detect-server-ping.mjs +++ b/skills/jfrog-init/scripts/jfrog-detect-server-ping.mjs @@ -126,11 +126,9 @@ export async function detectServerPing(serverIdArg) { const detail = anonymousUnreachable ? `jf rt ping OK — anonymous GET ${endpoint} failed, but that only reflects this process's own network path (proxy/CA), not the server${NETWORK_UNREACHABLE_HINT}` : `reachable at ${endpoint} AND jf rt ping OK (HTTP ${httpCode})`; - // `jpdUrl` is the caller's clean, structured way to get this walk's - // resolved JPD URL — SKILL.md's Final Summary uses it (alongside - // Step 6's `resolvedKey`) to call `jfrog-state-file.mjs set` directly, - // without parsing a URL back out of the human-readable `detail` string. - emit({ check: "server-ping", status: "green", detail, jpdUrl: url }); + // `serverId` and `jpdUrl` give the caller the resolved jf server + // (even when it was picked silently) without parsing `detail`. + emit({ check: "server-ping", status: "green", detail, serverId, jpdUrl: url }); return 0; } diff --git a/skills/jfrog-init/scripts/jfrog-resolve-jf-server.mjs b/skills/jfrog-init/scripts/jfrog-resolve-jf-server.mjs index b4a655a..0048520 100755 --- a/skills/jfrog-init/scripts/jfrog-resolve-jf-server.mjs +++ b/skills/jfrog-init/scripts/jfrog-resolve-jf-server.mjs @@ -1,10 +1,9 @@ #!/usr/bin/env node // Resolves which jf server ID to use, in this order: // 1. First positional arg, if non-empty -// 2. JF_SERVER_ID env var, if non-empty -// 3. The server marked "isDefault": true in ~/.jfrog/jfrog-cli.conf.v6 +// 2. The server marked "isDefault": true in ~/.jfrog/jfrog-cli.conf.v6 // (via `jf c show --format=json`) -// 4. If exactly one server is configured, it is used silently. +// 3. If exactly one server is configured, it is used silently. // // This is the single source of truth for server-id resolution — every // script that needs a server-id (server-ping, catalog-runtime, project, @@ -39,7 +38,7 @@ import { emit, isMainModule, jfAvailable, jfConfigShow, defaultServerId, emitNoS // goes through a shell, there is nothing left for a charset check here to // protect against. export function resolveJfServer(override, configList) { - const picked = override || process.env.JF_SERVER_ID || ""; + const picked = override || ""; if (picked) return picked; // Every caller that passes `configList` has already called jfAvailable() // itself to get there (see jfrog-detect-*.mjs) — re-checking here would diff --git a/skills/jfrog-init/scripts/jfrog-state-file.mjs b/skills/jfrog-init/scripts/jfrog-state-file.mjs deleted file mode 100755 index d1d1b15..0000000 --- a/skills/jfrog-init/scripts/jfrog-state-file.mjs +++ /dev/null @@ -1,289 +0,0 @@ -#!/usr/bin/env node -// jfrog-state-file.mjs — read/write the /jfrog-init state file at -// ~/.jfrog/setup.json. Keyed by JFrog CLI server ID so a machine -// with multiple JPDs stays coherent. -// -// File shape (versioned; consumers MUST tolerate unknown top-level keys): -// { -// "version": 1, -// "servers": { -// "": { -// "jpdUrl": "https://acme.jfrog.io", -// "currentActiveProject": "widgets" -// } -// } -// } -// `currentActiveProject` is OPTIONAL — a record can exist with just -// `jpdUrl` when the server is known but no project has been resolved yet -// (e.g. Step 6 hit its retry cap). Consumers MUST NOT assume it's present. -// -// Rules: -// - Never contains secrets. Only public identifiers (server id, JPD URL, -// project key). No timestamps — the record is a pointer to what's -// active now, not a usage log. -// - Read failure = empty state (no error propagated). The file is a -// hint, not a source of truth. -// - Writes go through a temp file + rename for atomicity so a partial -// write can't leave broken JSON on disk. "set" also takes a -// cross-process exclusive lock around its read-modify-write so two -// concurrent walks updating different servers can't clobber each -// other's record. -// - Directory ~/.jfrog is created with mode 0700 if missing. File is -// written with mode 0644. -// -// Usage: -// node jfrog-state-file.mjs get -// -> stdout is the record's JSON (or "{}" if absent). Exit 0. -// -// node jfrog-state-file.mjs get-current-project -// -> stdout is JSON {"currentActiveProject": "...", "jpdUrl": "..."} -// (fields omitted if no record exists). Exit 0. -// -// node jfrog-state-file.mjs set [project-key] -// -> merges/creates the server record with the given fields. -// [project-key] is optional — pass "" (or omit it) to record the -// server/JPD without a currentActiveProject, e.g. when Step 6 -// couldn't resolve one. Exit 0 on success, exit 1 on write error. -// -// node jfrog-state-file.mjs path -// -> stdout is the absolute path to the state file. Exit 0. -// -// Any parse/write failure prints a short message to stderr and exits -// non-zero; callers can `|| true` to keep the walk moving on stateless -// paths. - -import { mkdirSync, readFileSync, writeFileSync, renameSync, chmodSync, existsSync, unlinkSync, statSync } from "node:fs"; -import { homedir } from "node:os"; -import { join } from "node:path"; -import { isMainModule } from "./lib/jf.mjs"; - -const STATE_DIR = join(homedir(), ".jfrog"); -const STATE_PATH = join(STATE_DIR, "setup.json"); -const LOCK_PATH = `${STATE_PATH}.lock`; -const CURRENT_VERSION = 1; - -// Exclusive-create is atomic even across processes, so this is a real -// mutex (not just a TOCTOU-prone existsSync check) guarding the -// read-modify-write in "set" below — two concurrent walks writing -// different servers' records must not clobber each other's update. -// -// Single attempt, no busy-wait retry loop: the record it protects is a -// best-effort "reuse last project?" hint, not a source of truth (the -// caller in jfrog-detect-all.mjs treats a write failure as a warning, -// not a walk failure) — blocking to wait out contention isn't worth the -// latency for what's allowed to be lost anyway. -// -// A process that crashes (Ctrl-C, OOM, harness timeout) while holding the -// lock never reaches releaseLock(), leaving LOCK_PATH on disk forever. To -// recover from that, a lock file older than STALE_LOCK_MS is treated as -// abandoned and removed before the one retry below. -const STALE_LOCK_MS = 30_000; - -function reclaimIfStale() { - try { - if (Date.now() - statSync(LOCK_PATH).mtimeMs > STALE_LOCK_MS) unlinkSync(LOCK_PATH); - } catch { - // Lock vanished between the failed create and this check, or the - // stat itself failed — either way there's nothing to reclaim. - } -} - -function acquireLock() { - try { - writeFileSync(LOCK_PATH, String(process.pid), { flag: "wx" }); - return true; - } catch (err) { - if (err.code !== "EEXIST") throw err; - reclaimIfStale(); - try { - writeFileSync(LOCK_PATH, String(process.pid), { flag: "wx" }); - return true; - } catch { - return false; - } - } -} - -function releaseLock() { - try { - unlinkSync(LOCK_PATH); - } catch { - // Already gone (or never acquired) — nothing to clean up. - } -} - -function loadState() { - if (!existsSync(STATE_PATH)) return { version: CURRENT_VERSION, servers: {} }; - try { - const raw = readFileSync(STATE_PATH, "utf8"); - if (!raw.trim()) return { version: CURRENT_VERSION, servers: {} }; - const parsed = JSON.parse(raw); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - return { version: CURRENT_VERSION, servers: {} }; - } - if (!parsed.servers || typeof parsed.servers !== "object") { - parsed.servers = {}; - } - return parsed; - } catch { - // Corrupt file — treat as empty so the walk doesn't hard-stop on a - // stale hint. The write path will overwrite it next time we save. - return { version: CURRENT_VERSION, servers: {} }; - } -} - -function ensureStateDir() { - try { - mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 }); - } catch (err) { - if (err.code !== "EEXIST") throw err; - } -} - -function saveState(state) { - ensureStateDir(); - const tmp = `${STATE_PATH}.tmp.${process.pid}`; - try { - // "wx" refuses to follow/overwrite anything already at tmp (e.g. a - // pre-planted symlink) — same symlink-safe pattern as - // lib/project-cache.mjs's writeCachedProjectList(). - writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o644, flag: "wx" }); - // Not redundant with the `mode` above, despite looking it: writeFileSync's - // mode is masked by the process umask at creation, so under a restrictive - // umask (0077, common on hardened machines) the file lands at 0600 and the - // documented 0644 contract at the top of this file silently doesn't hold. - // chmod is not umask-masked, so it forces the mode after the fact. - chmodSync(tmp, 0o644); - renameSync(tmp, STATE_PATH); - } catch (err) { - // A run killed between the write and the rename (Ctrl-C, OOM, harness - // timeout) leaves tmp behind; the name is only unique per PID, so the - // next run to reuse that PID would otherwise hit EEXIST here forever. - try { - unlinkSync(tmp); - } catch { - // Never created, already renamed, or not ours to remove. - } - throw err; - } -} - -// Exported so jfrog-detect-all.mjs can call this in-process instead of -// shelling out to a `node` subprocess — the same in-process pattern -// jfrog-resolve-jf-server.mjs / jfrog-resolve-mcp-config.mjs / -// jfrog-substitute-mcp-placeholders.mjs use. Returns { ok, error } instead -// of writing to stderr and calling process.exit(), so an in-process -// caller decides for itself how to surface a failure (jfrog-detect-all.mjs -// treats it as a warning, not a walk failure). -// -// The lock is released explicitly on every path (not via try/finally) to -// mirror the CLI wrapper's exit-code contract below exactly. -export function setStateForServer(serverId, jpdUrl, projectKey) { - if (!serverId || !jpdUrl) { - return { ok: false, error: "set requires [project-key]" }; - } - // The lock file lives in STATE_DIR too, so it must exist before - // acquireLock() — not just before saveState() — or the very first - // write on a machine where ~/.jfrog doesn't exist yet (nothing has - // run `jf config add` or otherwise created it) fails with ENOENT. - let locked; - try { - ensureStateDir(); - locked = acquireLock(); - } catch (err) { - return { ok: false, error: `write failed: ${err.message}` }; - } - if (!locked) { - // Lock not acquired (stale lock file from a crashed process, or - // genuine contention) — fail rather than doing the read-modify-write - // unprotected, which would defeat the whole point of the lock. - return { ok: false, error: "could not acquire lock — another /jfrog-init walk may be writing state; try again" }; - } - try { - const state = loadState(); - state.version = CURRENT_VERSION; - state.servers = state.servers || {}; - // Replace the record wholesale rather than spreading the previous - // one forward — otherwise a stale legacy key (e.g. from an older - // state-file schema) would linger alongside the current fields. - // Exception: an empty projectKey means THIS walk didn't resolve a - // project (e.g. Step 6 hit its retry cap), not that the server has - // no project — carry the previous currentActiveProject forward - // rather than erasing a still-possibly-valid "reuse CURRENT?" hint - // over what's likely a transient miss. - const previous = state.servers[serverId]; - state.servers[serverId] = - projectKey ? { jpdUrl, currentActiveProject: projectKey } - : previous?.currentActiveProject ? { jpdUrl, currentActiveProject: previous.currentActiveProject } - : { jpdUrl }; - saveState(state); - releaseLock(); - return { ok: true }; - } catch (err) { - releaseLock(); - return { ok: false, error: `write failed: ${err.message}` }; - } -} - -if (isMainModule(import.meta.url)) { - const [mode, ...args] = process.argv.slice(2); - - // Sets process.exitCode rather than calling process.exit() — a forced - // exit can truncate a still-draining stdout write, and every mode below - // is a caller reading that stdout for its result. Every branch now needs - // its own explicit `break` (process.exit() used to provide that for - // free by terminating the process outright). - switch (mode) { - case "path": - process.stdout.write(STATE_PATH); - process.exitCode = 0; - break; - - case "get": { - const serverId = args[0]; - if (!serverId) { - process.stdout.write("{}"); - process.exitCode = 0; - break; - } - const state = loadState(); - const rec = state.servers?.[serverId]; - process.stdout.write(rec ? JSON.stringify(rec) : "{}"); - process.exitCode = 0; - break; - } - - case "get-current-project": { - const serverId = args[0]; - if (!serverId) { - process.stdout.write("{}"); - process.exitCode = 0; - break; - } - const state = loadState(); - const rec = state.servers?.[serverId]; - const out = {}; - if (rec && typeof rec.currentActiveProject === "string") out.currentActiveProject = rec.currentActiveProject; - if (rec && typeof rec.jpdUrl === "string") out.jpdUrl = rec.jpdUrl; - process.stdout.write(JSON.stringify(out)); - process.exitCode = 0; - break; - } - - case "set": { - const [serverId, jpdUrl, projectKey] = args; - const result = setStateForServer(serverId, jpdUrl, projectKey); - if (!result.ok) { - process.stderr.write(`state-file: ${result.error}\n`); - process.exitCode = 1; - break; - } - process.exitCode = 0; - break; - } - - default: - process.stderr.write(`state-file: unknown mode ${JSON.stringify(mode)}\n`); - process.exitCode = 1; - } -} diff --git a/skills/jfrog-init/scripts/lib/jf.mjs b/skills/jfrog-init/scripts/lib/jf.mjs index 0664d26..1184dfa 100755 --- a/skills/jfrog-init/scripts/lib/jf.mjs +++ b/skills/jfrog-init/scripts/lib/jf.mjs @@ -412,11 +412,10 @@ export function askServerResult(check, configList) { // `unresolved: "server"` lets a caller tell this apart from a // check-specific ask (e.g. jfrog-detect-project.mjs's own "no project // input" ask) even though both are `{check, status: "ask"}` — without - // it, a caller keying off `check` alone (e.g. the Step 6 project - // picker) would misroute this into asking about the wrong thing. See - // references/project-picker.md's discriminator note. + // it, a caller keying off `check` alone would misroute this into + // asking about the wrong thing. unresolved: "server", - detail: "multiple jf servers configured, none marked isDefault — pass a server-id or set JF_SERVER_ID", + detail: "multiple jf servers configured, none marked isDefault — pass a server-id", candidates: configList.map((s) => s.serverId).filter(Boolean), }; } diff --git a/skills/jfrog-init/scripts/lib/project-cache.mjs b/skills/jfrog-init/scripts/lib/project-cache.mjs index 389da54..a609336 100644 --- a/skills/jfrog-init/scripts/lib/project-cache.mjs +++ b/skills/jfrog-init/scripts/lib/project-cache.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node // project-cache.mjs — short-lived on-disk cache of a server's enumerated // project list (GET /access/api/v1/projects). The interactive project -// step (SKILL.md Step 6) re-invokes jfrog-detect-project.mjs once per user -// attempt within the same walk (typed guess, "Other" retry, picking a -// suggestion, ...); without this cache each attempt re-hits the network +// step (SKILL.md Step 4, and jfrog-detect-all.mjs re-runs) can call +// jfrog-detect-project.mjs more than once per walk; without this cache each +// call re-hits the network // to re-enumerate, even though matching/similarity search against the // list is already done offline (lib/projects.mjs). Only the enumeration // call itself needs caching — the per-key existence probe in @@ -80,7 +80,7 @@ export function writeCachedProjectList(serverId, creds, body) { // first (also "wx", refusing to follow/overwrite anything already // there) and renaming into place instead replaces whatever directory // entry — file or symlink — sits at the final path, without ever - // dereferencing it. Same pattern as jfrog-state-file.mjs. + // dereferencing it. const target = cachePath(serverId); const tmp = `${target}.tmp.${process.pid}`; writeFileSync(tmp, JSON.stringify(record), { mode: 0o600, flag: "wx" }); diff --git a/skills/jfrog-mcp-management/SKILL.md b/skills/jfrog-mcp-management/SKILL.md index b85c63a..3460a47 100644 --- a/skills/jfrog-mcp-management/SKILL.md +++ b/skills/jfrog-mcp-management/SKILL.md @@ -58,40 +58,9 @@ it. Do not reuse a result from an earlier turn in this session. node "/scripts/jfrog-agent-guard-check.mjs" ``` -Request network access for this command. - -**This script only:** optional positional `` = a `jf` config -server id (e.g. from `jf config show`). Nothing else. - -- NEVER pass `--server`, `--project`, `--mcp`, or any other flags to this - script. -- NEVER pass an MCP package name (e.g. `kubernetes-mcp-server`, - `@scope/pkg`). -- NEVER pass a URL (`https://…`). -- NEVER derive `` by parsing a hostname out of `JFROG_URL` / - `JF_URL` (e.g. taking `myco.jfrog.io` from - `JFROG_URL=https://myco.jfrog.io`). If `jf config show` legitimately - names a server `myco.jfrog.io`, that is fine — the ban is on deriving - the id from the URL, not on hostname-shaped values from `jf config` - itself. -- Substitute the real jf server id for `` — never a literal - `[...]` or ``. Any unsupported or unknown argument stops - the gate (`Unknown: …`); it is NOT silently ignored and does NOT - fall back to env credentials or the default `jf` server. In a - multi-JPD setup that fallback would report the wrong platform. - -Pass `` when it is already known from context (an existing Agent -Guard MCP entry's `--server` value, or one the user named) so the gate checks -the JPD you will actually target, not the CLI default — this matters only in -multi-JPD setups. Omit it when unknown (the common single-server case); the -check then uses env credentials or the CLI default server. Do NOT invent a -server id from the MCP name or from `JF_URL`. Do NOT block on resolving a -server just to run this gate. - -```bash -# Only when certain of the JFrog platform server id: -node "/scripts/jfrog-agent-guard-check.mjs" "" -``` +Request network access for this command. Run it exactly as shown, with no +arguments — never pass a server ID, an MCP name, or a URL. It asks the AI +Governance server (see below) whether Agent Guard is on. If the first run fails with a network error, timeout, or other spurious issue (sandbox, DNS, HTTP 5xx), run the same command again with network access and use @@ -111,7 +80,8 @@ installed, and remove MCPs with this skill. No other approved path for those. This organization does not use Agent Guard. Honor that. Do not mention Agent Guard or this check unless asked. Do not tell the user to contact an admin or -enable a registry. +enable a registry. A `NotSetUp:` line (no AI Governance server is saved, e.g. +`/jfrog-init` never ran) gets the same handling. - **Install** and **List → Available to install:** ignore those sections. Serve those asks as you would if this skill had never loaded. @@ -121,32 +91,31 @@ Keep reading for Install / list-available only when the user explicitly asked to use Agent Guard anyway (evaluating the catalog without enabling it for the organization is legitimate). -### Exit 3 — Multiple JFrog servers, none set as default +### Exit 3 — several AI Governance servers, none is the default -The gate could not tell which JPD to check: no complete `JFROG_URL`/`JF_URL` + -`JFROG_ACCESS_TOKEN`/`JF_ACCESS_TOKEN` credential pair is set in the env, -there is no default `jf` server, and two or more servers are configured. -This is NOT a disabled or unknown result — the gate just needs the user to say which server to use. +This selection is not relevant for **List → Currently installed** and **Remove**, +which touch local config only — handle those normally, with no server selection. -Do this: +The `AmbiguousServer:` line means more than one AI Governance server is saved +and none of them is the default, so the check cannot tell which one to ask. +This is NOT a disabled or unknown result — the user picks the server. Do this: -1. Show the user the server ids from the gate's `AmbiguousServer:` line (they - match `jf config show`) and let the user manually select one. -2. Re-run Step 0 with the selected id as the `` argument and act on - that exit code. Exit 0 or Exit 2 → follow that section. Any other non-zero - means the id is not a configured `jf` server (a typo) or was unreachable — - tell the user it did not resolve and have them pick a valid one (or stop); do - NOT fall through to "status unknown", which would bypass Agent Guard. +1. Run `node "/scripts/jfrog-ai-governance-config.mjs" list`. +2. Show the user each entry's `serverId` with its `jpdUrl`, and ask: "Which of + these is your AI Governance server?" +3. Save their choice, ``, with + `node "/scripts/jfrog-ai-governance-config.mjs" set ""`. + If that command fails, ask the user to run `/jfrog-init` to repair their + AI Governance setup, and stop. +4. Run Step 0 again to check whether Agent Guard is on for that server, and + follow the section for its exit code. Wait for the user's selection before continuing; the gate stays ambiguous until they choose. -This selection is not relevant for **List → Currently installed** and **Remove**, -which touch local config only — handle those normally, with no server selection. - ### Any other non-zero exit — status unknown -The check did not reach a definitive platform answer (no credentials, timeout, +The check did not reach a definitive platform answer (bad credentials, timeout, HTTP error, network/DNS). Treat it like Exit 2 for Install and List → Available to install (ignore those sections; keep serving the user). List → Currently installed and Remove still proceed. (Exit 3 is handled above, not here.) @@ -155,6 +124,27 @@ Mention once — as a side note while continuing — what failed and that the us can use the `jfrog-init` command to fix any local configuration issues. Do not ask them to decide, do not repeat it, and do not stop to fix it. +## AI Governance server and project + +The AI Governance server is the JFrog Platform server (a jf CLI server ID) +that governs the user's AI assets: its AI Catalog lists the skills, plugins +and MCP servers they may use, and Agent Guard, where the organization has +turned it on, enforces that. The AI Governance project is the JFrog project +on that server that scopes the AI Catalog: which skills, plugins and MCP +servers the user sees and may install. Both are saved in `setup.json` in +the JFrog CLI home directory, separately from the jf CLI default server; +the AI Governance server can be the same server as that default or a +different one. +The user chooses both in `/jfrog-init`; another skill saves one only when it +is missing or unclear and the user answers that skill's question. +Read and change the file only through `jfrog-ai-governance-config.mjs`. + +In this skill, Step 0 asks the AI Governance server whether Agent Guard is +on, and that answer decides whether the Install and List → Available to +install sections apply. When they do, every Agent Guard command and every +MCP entry they write use the AI Governance server and project (see +Pre-flight). + ## Harness config **Harness config (resolve once, up front).** Where MCP config lives — the file @@ -178,17 +168,16 @@ values into your actions. shared guards this skill reuses (does not repeat): the [environment check](../jfrog/SKILL.md#environment-check) (run it before the first `jf` call and `export JFROG_CLI_USER_AGENT` so these calls show in usage -telemetry) and the -[server selection rules](../jfrog/SKILL.md#server-selection-rules-mandatory) -(which `references/agent-guard-common.md` builds on, not replaces). +telemetry). ## Pre-flight (Install and List → Available to install only) Read [references/agent-guard-common.md](references/agent-guard-common.md) for the canonical invocation (`npx --yes --registry "" @jfrog/agent-guard`), -the `` substitution, and the rules for resolving -`` and ``. Removal and List → Currently installed -read only local config, so they skip this. +the `` substitution (the npm registry the `@jfrog/agent-guard` +package comes from), and how to get `` and `` +from `setup.json`. Removal and List → Currently installed read only local +config, so they skip this. **Route the request**, then jump to the matching section: @@ -217,12 +206,13 @@ do NOT ask for JFrog project key, server, or package name unless necessary. ## Step 1: Determine JFrog project key, server, and target config file -**Server ID and JFrog project key** — resolve both per the Pre-flight rules in +**Server ID and JFrog project key** — get `` and +`` per Pre-flight in [references/agent-guard-common.md](references/agent-guard-common.md). Pass -`--server ` in every Agent Guard invocation whenever the ID came from an -existing Agent Guard MCP entry or jf config; omit `--server` only on the -URL+token env path (`JFROG_URL`+`JFROG_ACCESS_TOKEN`, or legacy -`JF_URL`+`JF_ACCESS_TOKEN`). NEVER guess or assume `default` for the project key. +`--server ""` in every Agent Guard command and every entry you +write — also when existing MCP entries have no `--server` or another one; +never copy theirs (why: Pre-flight). NEVER guess or assume `default` for the +project key. **Target config file** - Use the current harness's row in @@ -265,10 +255,8 @@ npx --yes \ (never omit `--registry`; URL in [agent-guard-common](references/agent-guard-common.md)) -**`--server` is conditional** — include it per the Step 1 rule (from an -existing Agent Guard MCP entry or jf config; omit only on the URL+token env -path — `JFROG_URL`+`JFROG_ACCESS_TOKEN`, or legacy `JF_URL`+`JF_ACCESS_TOKEN`). -Same rule applies to `--login` and the config entry below. +**`--server` is never omitted** — per the Step 1 rule, even when existing +entries lack it. Same rule applies to `--login` and the config entry below. From the output JSON, extract (keep BOTH required AND optional): - `spec.packageName` — exact package name for the config. @@ -381,10 +369,7 @@ Guardrails (identical everywhere): build that URL yourself. These are the same three conditions resolved in Step 2 — restated here, never a second, looser test. -- `--server` in `args` is conditional (Step 1): drop it only on the URL+token - env path (`JFROG_URL`+`JFROG_ACCESS_TOKEN`, or legacy - `JF_URL`+`JF_ACCESS_TOKEN`). When present, its value is a jf config server - id — never an MCP name or a hostname from `JF_URL`. +- `--server ""` is always in `args` (Step 1). - NEVER put `--project` or `--mcp` in config `args`. - If a required value reference is unset, the server fails / tool calls fail at runtime — confirm the user provided it (shell export, or VS Code first-start @@ -478,7 +463,7 @@ file or shell: When Step 0 was exit 0: NEVER invent MCP integrations from outside the catalog. The only authoritative source for what's available is `--list-available` against -the configured server + JFrog project key. If that returns nothing or errors, +the AI Governance server + JFrog project key. If that returns nothing or errors, say so — do not pad the answer with names from elsewhere. ## Currently installed @@ -504,7 +489,7 @@ add-on where the agent provides it. asserting whether this skill did. **When its `url` contains `/mcp-gateway/` (a remote MCP Gateway entry), show that complete `url`, from `http` to the end — in a table too, never shortened with `...`** — e.g. - `https://acme.jfrog.io/mcp-gateway/mcp/proj/com.supabase%2Fmcp`, not + `https://acme.jfrog.io/mcp-gateway/mcp/proj/02UkVNT1RFX2NvbS5zdXBhYmFzZS9tY3A`, not `.../mcp-gateway/...`. 2. **If the harness exposes an MCP status command or view** (the harness-config "List installed" column — e.g. Claude Code's `claude mcp list`, Cursor/VS @@ -520,13 +505,11 @@ add-on where the agent provides it. If Step 0 was exit 2 (or unknown treated as exit 2), ignore this subsection. Continue serving the user without Agent Guard. Currently installed still proceeds. -1. Determine **server** and **JFrog project key** per the Pre-flight rules. +1. Get `` and `` per Pre-flight. `--list-available` does NOT require any existing MCP entry or pre-installed Agent Guard — `npx --yes --registry "" @jfrog/agent-guard` fetches it on demand, so this works on a fresh machine too. -2. Run this ONCE — do not emit literal `[ ]` brackets. Append `--server - ""` per the Step 1 rule (omit only on the URL+token env path — - `JFROG_URL`+`JFROG_ACCESS_TOKEN`, or legacy `JF_URL`+`JF_ACCESS_TOKEN`): +2. Run this ONCE: ``` npx --yes \ --registry "" \ diff --git a/skills/jfrog-mcp-management/references/agent-guard-common.md b/skills/jfrog-mcp-management/references/agent-guard-common.md index 84f381b..4cff342 100644 --- a/skills/jfrog-mcp-management/references/agent-guard-common.md +++ b/skills/jfrog-mcp-management/references/agent-guard-common.md @@ -12,15 +12,19 @@ Terminology used throughout these skills: file (see [harness-common.md](harness-common.md); e.g. `.mcp.json` for Claude Code). - **JFrog project key** (``) — the key identifying a JFrog - project. This is distinct from the workspace/CWD. + project (the AI Governance project). This is distinct from the workspace/CWD. ## Registry URL Wherever `` appears, substitute the value of the -`JFROG_AGENT_GUARD_REPO` environment variable if it is set. Otherwise use +`JFROG_AGENT_GUARD_REPO` environment variable if it is set. Read it with +`node -p "process.env.JFROG_AGENT_GUARD_REPO || ''"` (empty output means +unset). Otherwise use `https://releases.jfrog.io/artifactory/api/npm/coding-agents-npm/` — JFrog's publicly accessible Releases Artifactory instance. It allows anonymous access -and hosts Agent Guard releases. +and hosts Agent Guard releases. It is independent of the AI Governance server: +the two can be the same host or different ones, and neither is derived from +the other. Canonical invocation (every catalog / login command; never omit `--registry`): `npx --yes --registry "" @jfrog/agent-guard` @@ -30,20 +34,56 @@ with `--registry ` above rather than the default npm registry. ## Pre-flight (applies to every agent guard command — `--list-available`, `--inspect`, `--login`) -**Environment probe (run once before resolving the project key and server).** -Before resolving credentials and the JFrog project key, run the skill’s env -probe so each var is printed on its own line (chained `printenv` or truncating -with `head` can merge lines and confuse the read). Prefer this over inventing -an env check; do not print raw token values — report tokens as `present` only; -prefer reporting `JFROG_URL` / `JF_URL` as `present` only as well; an empty -value after the label means the variable is unset. Print real values for -`JF_PROJECT` and `JFROG_AGENT_GUARD_REPO` (needed for `--project` and -enforceable MCP entries): +Every Agent Guard command and every MCP entry this skill writes targets the AI +Governance server and the AI Governance project (the JFrog project key). Get +both once, before the first command: ```bash -node "/scripts/jfrog-agent-guard-env-probe.mjs" +node "/scripts/jfrog-ai-governance-config.mjs" get ``` +`` is the AI Governance server ID that `get` returned (`serverId`), +and `` is its project key (`project`). Then act on `status`: + +- `ok` — continue with `` and ``. +- `no_project` — the server is set, the project is not (e.g. the user told + `/jfrog-init` they don't use AI Catalog). Ask: "Which AI Governance project + on `` should I use? I need its project key." (`` is the host + of the `jpdUrl` that `get` returned.) The answer is `` + from now on. Save it by running + `node "/scripts/jfrog-ai-governance-config.mjs" set "" ""`. + NEVER guess, NEVER assume `default`, NEVER invent JFrog project keys, and + never take one from `JF_PROJECT` or existing MCP entries. There is no + platform-wide / project-less mode: never offer a "no project" / + "platform-wide" / "skip" option. If this save command rejects the key, + ask once more; if that key is rejected too, show the error and stop. + Never fall back to a project-less call. +- `ambiguous` — several servers are saved (e.g. set up for more than one JFrog + platform) and none is marked as the AI Governance server. Run + `node "/scripts/jfrog-ai-governance-config.mjs" list`, show the + user each `serverId` with its `jpdUrl`, ask: "Which of these is your AI + Governance server?", save the answer with + `node "/scripts/jfrog-ai-governance-config.mjs" set ""`, + then run `get` again. +- `missing` — AI Governance was never set up on this machine; `corrupt` — + `setup.json` can't be read. Ask the user to run `/jfrog-init` to set it up. +- If a `jfrog-ai-governance-config.mjs set` command above fails for any + reason other than a rejected project key, show its error and ask the user + to run `/jfrog-init` to repair the AI Governance setup. + +Pass `--server ""` to every Agent Guard command and write it into +every MCP entry; the entry's `_JF_ARGS` carries `project=`. +Why always: without `--server`, Agent Guard picks a server itself, which +can be a different JFrog platform than the AI Governance server. Existing +MCP entries written by +older versions may lack `--server` or name another server; never copy their +value. + +When the user names another JFrog server or project, say: "Your AI Governance +server is `` with project ``. To change it, run +`/jfrog-init`." If they want to change it, stop; the AI Governance server and +project are chosen in `/jfrog-init`, so they run that first. + - **Live execution is MANDATORY — context reuse is FORBIDDEN.** Every time the user asks to list / show / inspect / check the catalog or a specific MCP — including a repeated question already answered earlier in the chat — you @@ -52,60 +92,9 @@ node "/scripts/jfrog-agent-guard-env-probe.mjs" inputs change between prompts. (Applies to `--list-available` and `--inspect` only — NOT `--login`, which would re-open the OAuth browser, and NOT reading local config for *installed* state.) - -- **`` is always mandatory.** Resolve via the project - chain: existing Agent Guard MCP entries (any harness config file per - [harness-common.md](harness-common.md); `_JF_ARGS` → `project=`) → - `JF_PROJECT` env var → ASK the user. If none resolves, STOP and ask — NEVER - guess, NEVER assume `default`, NEVER invent JFrog project keys. There is no - platform-wide / project-less mode: when you ask, explain a real key is - required, prompt once (you may suggest the resolved candidates), and never - offer a "no project" / "platform-wide" / "skip" option. If the key is - rejected, re-prompt once — do not fall back to a project-less call. - -- **`` is auto-resolvable.** This extends the base skill's - [server selection rules](../../jfrog/SKILL.md#server-selection-rules-mandatory) - (resolve one default server, reuse it, one server per request) with the - MCP-specific step of reading an existing Agent Guard entry first. Resolve in - order, stop at the first match: - 1. An existing Agent Guard MCP entry's `--server ` (project or user - config, per [harness-common.md](harness-common.md)) — reuse it. - 2. `JFROG_URL` + `JFROG_ACCESS_TOKEN` set in the env (the Step 0 check and the - agent guard also accept the legacy `JF_URL` + `JF_ACCESS_TOKEN` pair as a - fallback) — use them and do NOT pass `--server` (the agent guard reads the - env directly). - 3. List configured servers with the jf CLI — run `jf config show - --format=json` (do NOT parse `~/.jfrog/jfrog-cli.conf.v6` yourself; the - CLI masks tokens, so its output is safe to read). Exactly one → use it; - two or more → use the one with `"isDefault": true`; if none is marked - default → ASK the user which one. Then pass `--server `. - 4. None of the above → ask the user to run `jf c add ` or export - `JFROG_URL` + `JFROG_ACCESS_TOKEN` (or the legacy `JF_URL` + - `JF_ACCESS_TOKEN`), then retry. - - When the ID came from an existing Agent Guard MCP entry or jf config, always - pass it as `--server `; only on the `JFROG_URL`+token env path, never pass - `--server`. - - **`` is a `jf config` server id only.** NEVER invent it from an - MCP package name, and NEVER parse a hostname out of `JFROG_URL` / - `JF_URL` (or any other URL) to use as `--server` or as the Step 0 gate - positional argument. Hostname-shaped ids from `jf config show` itself - are fine — the ban is on deriving the id from the URL, not on the - shape of the value. If env URL+token is set, omit `--server` entirely - (path 2 above) — do not derive a fake server id from the URL. - - > Note: the agent uses `jf config show --format=json` here only to *discover a - > server ID* — a token is not needed, so the masked output is fine. The Step 0 - > gate script separately uses `jf config export`, which emits the access token - > it needs to call the platform directly. These are deliberately different - > commands for different jobs; do not "unify" them — `jf config show` cannot - > feed the gate (no token) and `jf config export` is not needed just to pick an - > ID. - The commands need network access to the npm registry and the JFrog platform. Grant the matching runtime permission (see [runtime-permissions.md](runtime-permissions.md)); a corporate proxy, VPN, or blocked registry can also surface as `Forbidden` / `403` errors. -Once both are determined, proceed. If either is still unknown, STOP — do NOT -run the command with guesses. +If either value is still unknown, STOP — do NOT run the command with guesses. diff --git a/skills/jfrog-mcp-management/references/harness-claude.md b/skills/jfrog-mcp-management/references/harness-claude.md index f99a2ea..13023e1 100644 --- a/skills/jfrog-mcp-management/references/harness-claude.md +++ b/skills/jfrog-mcp-management/references/harness-claude.md @@ -50,8 +50,9 @@ URL. Agent Guard entry uses. - `url` is `routing.url` copied verbatim. Never build it, never normalise it, never re-encode it, never append a path. It always points at the tenant's own - JFrog Platform. A `%2F` in the URL is correct and must be written through - unchanged. + JFrog Platform. Its last segment is the MCP's registry id: an opaque id in the + URL-safe base64 alphabet (`A-Z a-z 0-9 - _`), so it never needs escaping. + Agent Guard checks it before returning a URL. - No `command`, no `args`, no `env`, no `${VAR}` — the Gateway holds the upstream credential, so there is nothing for the user to export. A `${VAR}` in a Gateway entry is a bug. diff --git a/skills/jfrog-mcp-management/references/harness-codex.md b/skills/jfrog-mcp-management/references/harness-codex.md index 729878a..a626ec0 100644 --- a/skills/jfrog-mcp-management/references/harness-codex.md +++ b/skills/jfrog-mcp-management/references/harness-codex.md @@ -102,47 +102,25 @@ env_vars = [""] - `` is the sanitized slug from **Top-level key** (matches `^[a-zA-Z0-9_-]+$`, needs no quoting); `mcp=` in `_JF_ARGS` keeps the exact `spec.packageName`. -- **Include `--server `** to authenticate JFrog on Codex - it is the - default, and required when the user has multiple `jf` servers. It also keeps the - entry working if the user later adds more servers. (It can be omitted only when a - single `jf` server is configured, which the Agent Guard auto-resolves; see JFrog - credentials below.) `env_vars` here is only for the upstream MCP's own - secrets/inputs, never for JFrog credentials. +- **Include `--server `** to authenticate JFrog on Codex - always + (see [harness-common.md](harness-common.md) and the env-var section below). + `env_vars` here is only for the upstream MCP's own secrets/inputs, never for + JFrog credentials. - Omit `env_vars` if there are no forwarded values; omit the extra `env` key if - `_JF_ARGS` is the only literal. Never emit an empty `--server`. + `_JF_ARGS` is the only literal. - **Always write the entry as one section** with the inline `env = { … }` above - hand-write it, do NOT run `codex mcp add`. That command splits `env` into a separate `[mcp_servers..env]` sub-table and cannot express `env_vars`. -## JFrog credentials - from the `jf` config - -Codex does NOT forward ambient shell variables, so the Agent Guard reads its JFrog -credentials from the on-disk `jf` CLI config (which the Codex-launched process can -read). - -**Include `--server ` in `args` by default.** It reads that server's -URL + token from the `jf` config, is unambiguous, and keeps working if the user -later adds more servers. Resolve `` per the agent-guard-common -Pre-flight rules. - -`--server` can be **omitted only when exactly one `jf` server is configured** - in -that case the Agent Guard auto-resolves it. With **multiple** `jf` servers, -omitting `--server` fails: the Agent Guard cannot choose between them and does NOT -fall back to the `jf` default, so `--server` is required. (When in doubt, include -it.) - -**Codex exception to the shared rule.** [SKILL.md](../SKILL.md) treats `--server` -as conditional and permits dropping it on the `JFROG_URL`+token env path (see its -Step 4 Guardrails, "`--server` … drop it only on the `JFROG_URL`+token env -path"). **That env path does NOT apply on Codex** - Codex does not forward ambient -shell env to the server, so `JFROG_URL` / `JFROG_ACCESS_TOKEN` never reach the -Agent Guard. On Codex, therefore, do NOT authenticate JFrog via env-var -credentials; use `--server ` (or a single configured `jf` server) as -described above. If there is no usable `jf` server, ask the user to add one -(`jf c add `, or `jf login`) before continuing. - -If credentials cannot be resolved (no `--server` and either zero or multiple `jf` -servers), the entry fails to start with `connection closed: initialize response`. +## Codex does not pass your shell's env vars + +Codex starts MCP servers with a minimal default environment (such as `PATH` +and `HOME`), not the environment of the shell that launched it. Beyond that, +a server gets only the literal values in its entry's `env` and the variables +named in its `env_vars`. Any other variable — an upstream MCP's +secret, for example — does not reach +it. That is why JFrog credentials come from the `jf` config via `--server`, +and why every input the upstream MCP needs must be in `env` or `env_vars`. ## Codex's sandbox diff --git a/skills/jfrog-mcp-management/references/harness-common.md b/skills/jfrog-mcp-management/references/harness-common.md index 36751b3..f2ba4eb 100644 --- a/skills/jfrog-mcp-management/references/harness-common.md +++ b/skills/jfrog-mcp-management/references/harness-common.md @@ -94,15 +94,9 @@ case; harnesses whose config is not JSON differ — e.g. **Codex** uses TOML wit approval and tool policy the Agent Guard would, so it is not a bypass. Every other remote entry remains forbidden. - `--yes` and `--registry ` MUST precede `@jfrog/agent-guard` in `args`. -- `--server ` in `args` is conditional: drop both array elements only on - the URL+token env path (`JFROG_URL`+`JFROG_ACCESS_TOKEN`, or legacy - `JF_URL`+`JF_ACCESS_TOKEN`) — see - [agent-guard-common.md](agent-guard-common.md). - `` is a `jf config` server id — never an MCP name, never a URL, and - never a hostname you parsed out of `JFROG_URL` / `JF_URL`. If a real id - in `jf config show` happens to be hostname-shaped (`myco.jfrog.io`), - use it as-is; the ban is on deriving the id from the URL, not on the - shape of the value. +- `--server ` is always in `args`: the AI Governance server's ID + from [agent-guard-common.md](agent-guard-common.md) Pre-flight — never an + MCP name, never a URL. - **NEVER put `--project` or `--mcp` in `args`.** Those flags are for catalog CLI calls only (`--inspect` / `--list-available` / `--login`). In the config entry, project + package belong exclusively in `_JF_ARGS`: diff --git a/skills/jfrog-mcp-management/references/harness-cursor.md b/skills/jfrog-mcp-management/references/harness-cursor.md index 8f4994c..66cfbac 100644 --- a/skills/jfrog-mcp-management/references/harness-cursor.md +++ b/skills/jfrog-mcp-management/references/harness-cursor.md @@ -79,8 +79,8 @@ Window) an Agent Guard call can't reach a JFrog host — the Step 0 activation check can't reach the platform, and/or an `npx` / catalog call returns a `403` on a JFrog host. That's Cursor's sandbox network allowlist. A Step 0 network failure here is inconclusive — don't report the platform as disabled or abort. -The gate uses `jf api` for a configured server and a direct request for -environment-only credentials. After the host is allowlisted, re-run Step 0 +The gate uses `jf api` for the AI Governance server. +After the host is allowlisted, re-run Step 0 and follow its exit code. Do not bypass the gate. 1. **Retry the same command once with `required_permissions: ["full_network"]`** diff --git a/skills/jfrog-mcp-management/references/harness-devin.md b/skills/jfrog-mcp-management/references/harness-devin.md index 2dbd330..11af55a 100644 --- a/skills/jfrog-mcp-management/references/harness-devin.md +++ b/skills/jfrog-mcp-management/references/harness-devin.md @@ -71,26 +71,7 @@ the upstream MCP may fail at startup — confirm the export before restart. Never write a raw secret. `${env:…}` / `${file:…}` are for the upstream MCP's own secrets and inputs — -never for JFrog Agent Guard credentials (see below). - -## JFrog credentials - from the `jf` config - -On Devin (CLI and Desktop Local), authenticate Agent Guard only through the -on-disk `jf` CLI config. **Always include `--server `** in every -Agent Guard command and written MCP config entry — resolve `` per -the agent-guard-common Pre-flight rules, never emit an empty `--server`, and do -**not** omit `--server` even when only one `jf` server is configured (explicit -server ID matches plugin enforcement). - -Do **not** use the shared [SKILL.md](../SKILL.md) env-var auth path -(`JFROG_URL` / `JFROG_ACCESS_TOKEN`, or legacy `JF_URL` / `JF_ACCESS_TOKEN`) on -Devin, even though Devin would resolve or forward them into Agent Guard. If -there is no usable `jf` server, ask the user to add one (`jf c add `, or -`jf login`) before continuing. - -If credentials cannot be resolved (no `--server ` in the entry, or no -usable `jf` server to resolve one from), the entry fails to start and the server -connects with no tools. +never for JFrog Agent Guard credentials. ## Enable diff --git a/skills/jfrog-mcp-management/references/harness-junie.md b/skills/jfrog-mcp-management/references/harness-junie.md index d37909d..a846bd3 100644 --- a/skills/jfrog-mcp-management/references/harness-junie.md +++ b/skills/jfrog-mcp-management/references/harness-junie.md @@ -45,14 +45,13 @@ in `mcp.json`. > forwarding that variable on this platform — see the "0 tools" entry in > [key-rules-and-troubleshooting.md](key-rules-and-troubleshooting.md). -## JFrog credentials — from the `jf` config +## Junie may not pass your shell's env vars -Junie may not forward ambient shell env to the MCP subprocess, so authenticate -JFrog via the on-disk `jf` config: **always include `--server ` in -`args`** (resolve `` per [agent-guard-common.md](agent-guard-common.md)) -so the Agent Guard reads that server's URL + token from `~/.jfrog/` — do not omit -it even with a single `jf` server. Don't rely on `JFROG_URL` / -`JFROG_ACCESS_TOKEN` here — Junie may not forward them. +Junie may start MCP servers without the environment of your shell. A +variable exported only in a terminal — an upstream MCP's secret, for +example — may not reach the server; it must be +in Junie's own environment (set before Junie starts, see above). This is why +JFrog credentials come from the `jf` config via `--server`. ## Enable @@ -85,7 +84,7 @@ troubleshooting in [key-rules-and-troubleshooting.md](key-rules-and-troubleshoot install** (the written entry's `_JF_ARGS` carries `project=`). Resolve it per [agent-guard-common.md](agent-guard-common.md) **before the first call**, same as every harness. Junie has no native prompt, so ask in plain text - if it's unresolved, or have the user set `JF_PROJECT` in Junie's environment. + if it's unresolved. - Installed MCPs are ALWAYS the stdio Agent Guard entry from [harness-common.md](harness-common.md) — never a top-level `url` (that bypasses the Agent Guard), even though Junie's `mcp.json` accepts `url` servers. diff --git a/skills/jfrog-mcp-management/references/harness-opencode.md b/skills/jfrog-mcp-management/references/harness-opencode.md index 1142eaa..ea7e3fe 100644 --- a/skills/jfrog-mcp-management/references/harness-opencode.md +++ b/skills/jfrog-mcp-management/references/harness-opencode.md @@ -72,40 +72,13 @@ Full entry shape (`command` is one array; `_JF_ARGS` is a literal in - `command` merges the common entry's `command` + `args` into ONE array, same tokens in the same order; `--yes` and `--registry ` MUST precede `@jfrog/agent-guard`. -- **Include `--server `** to authenticate JFrog - it is the default, - and required when the user has multiple `jf` servers; it also keeps the entry - working if the user later adds more servers. (It can be omitted only when a - single `jf` server is configured, which the Agent Guard auto-resolves; see JFrog - credentials below.) The `environment` block is only for the upstream MCP's own - secrets/inputs, never for JFrog credentials. +- **Include `--server `** to authenticate JFrog - always (see + [harness-common.md](harness-common.md)). The `environment` block is only + for the upstream MCP's own secrets/inputs, never for JFrog credentials. - **Always keep `environment` with `_JF_ARGS`** - it carries the project + package identity the Agent Guard needs to route the request. Omit only optional input keys; never drop `_JF_ARGS` or the whole `environment` object. -## JFrog credentials - from the `jf` config - -**Include `--server ` by default.** It reads that server's URL + token -from the on-disk `jf` CLI config, is unambiguous, and keeps working if the user -later adds more servers. Resolve `` per the agent-guard-common -Pre-flight rules; never emit an empty `--server`. - -`--server` can be **omitted only when exactly one `jf` server is configured** - in -that case the Agent Guard auto-resolves it. With **multiple** `jf` servers, -omitting `--server` fails: the Agent Guard cannot choose between them and does NOT -fall back to the `jf` default, so `--server` is required. (When in doubt, include -it.) - -**OpenCode exception to the shared rule.** [SKILL.md](../SKILL.md) treats `--server` -as conditional and permits dropping it on the `JFROG_URL`+token env path (see its -Step 4 Guardrails, "`--server` … drop it only on the `JFROG_URL`+token env -path"). **That env path does NOT apply on OpenCode** - do NOT authenticate JFrog via env-var credentials, even though OpenCode would forward `JFROG_URL` / `JFROG_ACCESS_TOKEN` to the server. Use -`--server ` (or a single configured `jf` server) as described above. If -there is no usable `jf` server, ask the user to add one (`jf c add `, or -`jf login`) before continuing. - -If credentials cannot be resolved (no `--server` and either zero or multiple `jf` -servers), the entry fails to start and the server connects with no tools. - ## Enable Servers are enabled by default (`enabled: true` is implicit; only diff --git a/skills/jfrog-mcp-management/references/key-rules-and-troubleshooting.md b/skills/jfrog-mcp-management/references/key-rules-and-troubleshooting.md index 7cf492b..d7e1797 100644 --- a/skills/jfrog-mcp-management/references/key-rules-and-troubleshooting.md +++ b/skills/jfrog-mcp-management/references/key-rules-and-troubleshooting.md @@ -31,18 +31,14 @@ Reference for the Install and List flows of the `jfrog-mcp-management` skill. or `--mcp` in the config entry's `args` — that is CLI-only; config uses `_JF_ARGS`. - **Three invocation contracts — do not mix:** (1) Step 0 gate - `jfrog-agent-guard-check.mjs` — optional positional jf `` only, + `jfrog-agent-guard-check.mjs` — no arguments, no flags; (2) catalog CLI — `--server` / `--project` / `--mcp` flags; - (3) config stdio entry — `_JF_ARGS=project=…&mcp=…`, optional `--server` - in `args` only when not on the env URL+token path. -- `` is always a `jf config` server id. NEVER an MCP package - name, NEVER a URL, and NEVER a hostname you derived from `JFROG_URL` / - `JF_URL`. Hostname-shaped ids from `jf config show` itself are fine — - the ban is on parsing an id out of the URL, not on the shape of the - value. + (3) config stdio entry — `_JF_ARGS=project=…&mcp=…`, always `--server` + in `args`. +- `` is always the AI Governance server id from Pre-flight. + NEVER an MCP package name, NEVER a URL. - NEVER assume `default` as a JFrog project key. If the project key is unknown - after the project chain (existing `mcpServers` entries → `JF_PROJECT` env - var), STOP and ask the user. Same for server ID if used. NEVER invent or + after Pre-flight, STOP and ask the user. NEVER invent or guess JFrog project keys or server IDs. - Package name MUST come from the catalog (`--inspect` / `--list-available`). NEVER guess. NEVER install MCPs outside the agent guard. NEVER use @@ -60,7 +56,7 @@ Reference for the Install and List flows of the `jfrog-mcp-management` skill. - NEVER write a raw secret into any MCP config file (see [harness-common.md](harness-common.md) for each harness's file) — always use `${VAR_NAME}`. NEVER show tokens / API keys. -- NEVER try multiple servers — ask the user to pick one. +- NEVER try another JFrog server; every command uses the AI Governance server. ## Classify npx @jfrog/agent-guard failures @@ -87,10 +83,12 @@ as the MCP proxy. 2. **Catalog miss (retry via List).** `not found in curated list` — the catalog responded; that MCP name is not approved. Go to List → Available to install. Same fingerprint on `--login`. A wrong `--project` key can surface as this - miss on the MCP name — re-resolve the project key if List is empty. + miss on the MCP name. If List is empty too, the AI Governance project may be + wrong; ask the user to run `/jfrog-init`. 3. **Retryable CLI/config.** `--project flag is required`, `--mcp flag is required`, - `Server ID '…' does not exist.`, `multiple/no JFrog server configured`. Fix - per Troubleshooting / Pre-flight and retry the **same** Agent Guard command. + `Server ID '…' does not exist.`, `multiple/no JFrog server configured`, + `no JFrog server is set for AI governance`. Fix per Troubleshooting and + retry the **same** Agent Guard command. 4. **Any other non-zero (hard stop).** Unrecognized stderr (including `Unauthorized`, `failed to fetch catalog`, `_JF_ARGS environment variable is not set`, 5xx). Show it verbatim. Do not retry List. Do not guess another bucket. @@ -186,13 +184,22 @@ row in [harness-common.md](harness-common.md). [harness-common.md](harness-common.md) and remove the entry from every file that lists it, then restart. On UI-toggle harnesses (Cursor, VS Code) there is no such file — disable/stop the server in the harness's MCP view instead. +- **`no JFrog server is set for AI governance`** — `--server` was empty. Run + the Pre-flight `get` again; if it does not return a server, ask the user to + run `/jfrog-init`. - **Agent Guard: `multiple/no JFrog server configured`** (the agent guard - cannot pick a JFrog server) — pass `--server ` (after `jf c add `) OR - export both `JFROG_URL` and `JFROG_ACCESS_TOKEN` in the launching shell, then - restart the agent. -- **`Server ID '' does not exist.`** — `--server` is not a configured jf - CLI server. Re-resolve the id (Pre-flight) or `jf c add`, then retry. Not a - catalog miss and not package-unreachable. + cannot pick a JFrog server) — the command or entry ran without `--server`. + Add `--server ""` from Pre-flight and retry; for an MCP entry, + fix its `args` and restart the agent. +- **Existing MCP entry without `--server` (or with another server)** — written + by an older version of this skill. Agent Guard then picks the server itself, + which may not be the AI Governance server. Leave it alone unless it actually fails + or the user asks. To repair: check that the MCP is in the catalog of the AI + Governance server and project (List → Available to install), then set its + `--server` to `` and restart the agent. +- **`Server ID '' does not exist.`** — the AI Governance server is not in + the jf CLI config. Ask the user to run `/jfrog-init`. Not a catalog miss and + not package-unreachable. - **`--project flag is required` / `--mcp flag is required`** — empty or omitted flag; fill from Pre-flight / the MCP name and retry. - **OAuth MCP failing** — refresh token expired; re-run the OAuth login step. diff --git a/skills/jfrog-mcp-management/references/runtime-permissions.md b/skills/jfrog-mcp-management/references/runtime-permissions.md index 2f241cf..a7d4e9e 100644 --- a/skills/jfrog-mcp-management/references/runtime-permissions.md +++ b/skills/jfrog-mcp-management/references/runtime-permissions.md @@ -6,7 +6,8 @@ a false "disabled" result. | Operation | What it needs | | --- | --- | -| Step 0 check (`node …check.mjs`) | Outbound HTTPS to the JFrog platform. When credentials come from `jf config`: also execute `jf` and read `$JFROG_CLI_HOME_DIR` when set, or `~/.jfrog/` otherwise | +| Step 0 check (`node …check.mjs`) | Outbound HTTPS to the JFrog platform; execute `jf`; read and write `setup.json` and read the jf config under `$JFROG_CLI_HOME_DIR` when set, or `~/.jfrog/` otherwise | +| AI Governance config (`node …config.mjs get`, `list`, `set`) | Read + write `setup.json` (same directory); `set` also executes `jf`. No network | | `--inspect`, `--list-available` | Outbound HTTPS to the npm registry + JFrog platform; write `~/.npm/_npx` (npx cache) | | OAuth `--login` | Same as above, plus browser launch and write `~/.jfrog/jfrogmcp.conf.json` | | Removing an MCP config entry | Read both project and user harness MCP config files; write the matched file(s) (e.g. `.cursor/mcp.json`, `.mcp.json`). No network | diff --git a/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-check.mjs b/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-check.mjs index 5056f31..3cd9cc2 100644 --- a/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-check.mjs +++ b/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-check.mjs @@ -10,15 +10,22 @@ // // Contract: // - exit 0 -> Agent Guard ENABLED (skill may proceed) -// - exit 2 -> Agent Guard DISABLED (registry off, or _JF_AGENT_GUARD_FORCE_DISABLE) -// - exit 3 -> AMBIGUOUS: no env creds, no default jf server, but two+ -// configured servers exist. Skill lists them and asks the user -// to pick one; it must NOT auto-pick. -// - exit 1 -> status UNKNOWN: no credentials, timeout, network/DNS error. -// Not sure if Enabled or not. +// - exit 2 -> Agent Guard DISABLED (registry off, or _JF_AGENT_GUARD_FORCE_DISABLE), +// or NOT SET UP: no AI Governance server in setup.json +// - exit 3 -> AMBIGUOUS: setup.json has two+ AI Governance entries and none +// is the default. Skill lists them, asks the user, saves the +// choice and re-runs; it must NOT auto-pick. +// - exit 1 -> status UNKNOWN: an argument was passed, setup.json not valid, the AI +// Governance server not usable from jf config, timeout, HTTP +// error (incl. 401/403), network/DNS error. Not sure if Enabled +// or not. // - a single human-readable reason line is written to stdout for -// diagnostics only; Step 0 keys off the EXIT CODE, not the text. The -// exit-3 line ends with the candidate server ids. +// diagnostics only; Step 0 keys off the EXIT CODE, not the text. +// +// Takes no arguments. The server comes from the AI Governance entry in +// ${JFROG_CLI_HOME_DIR:-~/.jfrog}/setup.json (see jfrog-ai-governance-config.mjs); +// env credentials and the jf default server are not used. Reading it may +// migrate a v1 setup.json (see jfrog-ai-governance-config.mjs). // // Set JF_AGENT_GUARD_DEBUG=true for verbose tracing on stderr. @@ -28,6 +35,8 @@ import { homedir } from "node:os"; import { join, delimiter } from "node:path"; import process from "node:process"; +import { resolveAiGovernanceConfig } from "./jfrog-ai-governance-config.mjs"; + // Global `fetch` requires Node.js 18+. const MIN_NODE_MAJOR = 18; @@ -81,10 +90,6 @@ const debug = (message) => { if (debugEnabled) console.error(`[jfrog-agent-guard] ${message}`); }; -// New JFROG_* env vars take precedence over the legacy JF_* names. -const env = (newName, oldName) => - process.env[newName] ?? (oldName ? process.env[oldName] : undefined); - const GATE_DONE = Symbol("gateDone"); const enabled = (reason) => { @@ -108,173 +113,65 @@ const registryDisabled = (reason) => { throw GATE_DONE; }; -// Multiple configured servers, none default, no env creds: ask the user to -// pick one instead of a misleading Unknown. Ids are appended for the skill. -const ambiguousServer = (serverIds) => { +// setup.json lists several AI Governance servers and none is the default: the +// skill must ask the user, save the choice, and re-run. +const ambiguousServer = () => { process.stdout.write( - `AmbiguousServer: multiple jf config servers exist but none is marked ` + - `default; ask the user which to use, then re-run with : ` + - `${serverIds.join(", ")}\n`, + "AmbiguousServer: several AI Governance entries exist in setup.json and " + + "none is the default; ask the user which to use\n", ); process.exitCode = 3; throw GATE_DONE; }; -// Exactly one positional argv[2]. Extras (argv[3..]), flags, and URLs are -// ALWAYS caller bugs — stop the gate immediately so a multi-JPD setup does -// not report the wrong platform's state. Everything else is treated as a -// candidate jf config server id — including hostname-shaped values and ids -// with spaces — because a text pattern cannot separate a real jf id from -// an MCP package name. jf config is the source of truth (see -// resolveCredentials). -function readGateServerId() { - const extra = process.argv.slice(3); - if (extra.length > 0) { - unknown( - `expected zero or one positional jf config server id, got extra ` + - `argument(s) ${JSON.stringify(extra)} — the gate accepts only ` + - `\`\` positionally, with no flags or additional values ` + - `after it`, - ); - } - const raw = process.argv[2]; - if (raw === undefined) return undefined; - const id = String(raw).trim(); - if (!id) return undefined; - if (id.startsWith("-")) { - unknown( - `expected a jf config server id (positional), got flag ` + - `${JSON.stringify(id)} — pass \`\` positionally, not as \`--server\``, - ); - } - if (/:\/\//.test(id)) { - unknown( - `expected a jf config server id (positional), got URL ` + - `${JSON.stringify(id)} — do not derive an id from \`JFROG_URL\` / \`JF_URL\``, - ); - } - return id; -} +// No AI Governance server is set up: same as disabled for the skill. +const notSetUp = (reason) => { + process.stdout.write(`NotSetUp: ${reason}\n`); + process.exitCode = 2; + throw GATE_DONE; +}; -// Resolve credentials from Path A (environment variables) or Path B -// (the default JFrog CLI configuration). Returns -// { baseUrl, token?, user?, password?, source, serverId? } or null when -// neither path yields a usable URL plus a token or user+password. -// `serverId` is set only for Path B and is passed to `jf api --server-id`. +// The AI Governance server comes only from setup.json; env credentials and +// the jf default server are never used to pick it. Enablement is account-level, +// so the project is not needed. function resolveCredentials() { - const explicitServerId = readGateServerId(); - // When the caller names a specific server, honor it or stop. Do not fall - // back to env credentials or the default jf server, that would check a - // different JPD in a multi-server setup when the named id is wrong (typo, - // MCP package name, unknown id). - if (explicitServerId) { - const fromCli = resolveFromCliConfig(explicitServerId); - if (fromCli) return fromCli; - unknown( - `server id ${JSON.stringify(explicitServerId)} is not configured in ` + - `\`jf config\` (or \`jf\` is unavailable) — refusing to check a different JPD`, - ); - } - - // Path A — environment variables. Token or user+password, same as Path B. - const envUrl = env("JFROG_URL", "JF_URL"); - const envToken = env("JFROG_ACCESS_TOKEN", "JF_ACCESS_TOKEN"); - const envUser = env("JFROG_USER", "JF_USER"); - const envPassword = env("JFROG_PASSWORD", "JF_PASSWORD"); - if (envUrl && (envToken || (envUser && envPassword))) { - debug("Using credentials from environment variables (Path A)."); - return { - baseUrl: envUrl, - ...(envToken ? { token: envToken } : {}), - ...(envUser && envPassword ? { user: envUser, password: envPassword } : {}), - source: "environment variables", - }; - } - debug( - "Environment credentials incomplete; trying JFrog CLI config (Path B).", + if (process.argv.length > 2) { + unknown("the gate takes no arguments"); + } + const config = resolveAiGovernanceConfig({ + log: { debug: (message) => debug(message) }, + }); + switch (config.status) { + case "ambiguous": + return ambiguousServer(); + case "missing": + return notSetUp("the AI Governance server is not set"); + case "corrupt": + return unknown(`${config.path} is not valid; run /jfrog-init`); + } + const creds = resolveFromCliConfig(config.serverId); + if (creds) return creds; + return unknown( + `server ${JSON.stringify(config.serverId)} is not usable from the jf CLI ` + + "config (or jf is unavailable); run /jfrog-init", ); - - // Path B — default server from the local JFrog CLI configuration. - const credsFromDefaultServer = resolveFromCliConfig(undefined); - if (credsFromDefaultServer) return credsFromDefaultServer; - - // The default export yielded no usable bearer credentials. `jf config export` - // cannot list servers, so enumerate them separately to classify the failure. - const configuredServers = listConfiguredServers(); - const serverIds = configuredServers.map((server) => server.serverId); - const hasDefaultServer = configuredServers.some((server) => server.isDefault); - - // Exactly one server: unambiguous — use it even if not marked default. - if (serverIds.length === 1) { - debug(`No default server, but exactly one configured ('${serverIds[0]}'); using it.`); - const credsFromOnlyServer = resolveFromCliConfig(serverIds[0]); - if (credsFromOnlyServer) return credsFromOnlyServer; - } - - // Two+ servers with NONE marked default: genuinely ambiguous — ask the user. - // If a default IS marked but its credentials did not resolve above, that is - // an unknown result (fall through to null), not ambiguity. - if (serverIds.length > 1 && !hasDefaultServer) { - debug(`No default server and ${serverIds.length} configured; needs user selection.`); - return { needsServerSelection: true, serverIds }; - } - return null; -} - -// Configured servers ({ serverId, isDefault }) from `jf config show -// --format=json` (needs no default, masks tokens). Returns [] when jf is -// unavailable or nothing is configured. -function listConfiguredServers() { - let showOutput; - try { - showOutput = execFileSync("jf", ["config", "show", "--format=json"], { - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - timeout: 2000, - }).trim(); - } catch (error) { - debug(`'jf config show --format=json' failed: ${error?.message}`); - return []; - } - let servers; - try { - servers = JSON.parse(showOutput); - } catch (error) { - debug(`Could not parse 'jf config show --format=json' output: ${error?.message}`); - return []; - } - if (!Array.isArray(servers)) return []; - return servers - .filter( - (server) => - server && typeof server.serverId === "string" && server.serverId.trim(), - ) - .map((server) => ({ - serverId: server.serverId.trim(), - isDefault: server.isDefault === true, - })); } function resolveFromCliConfig(serverId) { - // `jf config export [server ID]` emits the server as a base64-encoded JSON - // blob containing url, accessToken or user+password, and serverId. An - // optional server ID may be passed; without it the CLI's default server is - // used. We use the CLI rather than reading ~/.jfrog/jfrog-cli.conf.v6 - // directly because newer CLIs do not persist the access token in that file. - const exportArgs = serverId ? ["config", "export", serverId] : ["config", "export"]; + // `jf config export ` emits the server as a base64-encoded JSON + // blob containing url and accessToken or user+password. We use the CLI + // rather than reading ~/.jfrog/jfrog-cli.conf.v6 directly because newer CLIs + // do not persist the access token in that file. let exported; try { - exported = runJf(exportArgs, { + exported = runJf(["config", "export", serverId], { timeoutMs: CONFIG_READ_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"], }).trim(); } catch (error) { - // Do not fall back to ambient env credentials when an explicit server ID - // is unsafe for a Windows shell. That could check a different JPD than - // the one the caller requested. - if (serverId && error?.code === "EINVAL") throw error; + if (error?.code === "EINVAL") throw error; debug( - `'jf config export' failed (jf not on PATH or no server configured): ${error?.message}`, + `'jf config export' failed (jf not on PATH or server not configured): ${error?.message}`, ); return null; } @@ -304,16 +201,12 @@ function resolveFromCliConfig(serverId) { return null; } - // Only pass a real server ID through to `jf api --server-id`. The display - // fallback "default" is not a jf server name and would make jf reject the - // call as "Server ID 'default' does not exist". - const id = serverId || cfg?.serverId; return { baseUrl, ...(token ? { token } : {}), ...(user && password ? { user, password } : {}), - ...(id ? { serverId: id } : {}), - source: `JF CLI config (server '${id || "default"}')`, + serverId, + source: `JF CLI config (server '${serverId}')`, }; } @@ -609,8 +502,8 @@ async function isGatewayPluginEnabled(creds) { return strip(rootResult); } -// One attempt against `settingsPath` — over `jf api` when a server is -// selected, a direct request otherwise. `notFound` marks the 404 that +// One attempt against `settingsPath` — over `jf api`, or a direct request when +// jf is too old for `jf api`. `notFound` marks the 404 that // triggers the `/bridge-client` retry; callers strip it before returning. async function fetchSetting(settingsPath, creds) { // Status mapping: HTTP 200 + value:false → exit 2; 401/403 / other @@ -618,10 +511,6 @@ async function fetchSetting(settingsPath, creds) { // "Http Status: NNN" on stderr and the body on stdout. const root = normalizePlatformRoot(creds.baseUrl); const settingsUrl = root + settingsPath; - if (!creds.serverId) { - debug(`No jf server configured; requesting ${settingsUrl} directly.`); - return fetchGatewayPluginEnabled(settingsUrl, creds); - } debug(`Fetching gateway plugin setting via jf api (server '${creds.serverId}')`); const call = runJfApi( [ @@ -722,9 +611,9 @@ async function main() { // entirely. Checked first, in this order, so a conflicting config fails // safe (disabled) rather than silently favoring enablement. const forceDisabled = - env("_JF_AGENT_GUARD_FORCE_DISABLE") === "true"; + process.env._JF_AGENT_GUARD_FORCE_DISABLE === "true"; const forceEnabled = - env("JF_AGENT_GUARD_FORCE_ENABLE") === "true"; + process.env.JF_AGENT_GUARD_FORCE_ENABLE === "true"; if (forceDisabled) { registryDisabled("forced via _JF_AGENT_GUARD_FORCE_DISABLE"); return; @@ -735,17 +624,6 @@ async function main() { } const creds = resolveCredentials(); - if (!creds) { - unknown( - "JFROG_URL/JF_URL + credentials not set and no default JF CLI config found", - ); - return; - } - if (creds.needsServerSelection) { - ambiguousServer(creds.serverIds); - return; - } - const result = await isGatewayPluginEnabled(creds); if (result.ok) { enabled(`via ${creds.source}`); diff --git a/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-env-probe.mjs b/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-env-probe.mjs deleted file mode 100644 index 14f832e..0000000 --- a/skills/jfrog-mcp-management/scripts/jfrog-agent-guard-env-probe.mjs +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env node -// Copyright (c) JFrog Ltd. 2026 -// Licensed under the Apache License, Version 2.0 -// https://www.apache.org/licenses/LICENSE-2.0 -// -// JFrog Agent Guard environment probe. -// -// Safe cross-platform env dump used by the jfrog-mcp-management skill pre-flight -// (before resolving project key / server). Prints one labeled line per var so -// agents do not invent chained printenv / head probes that merge lines. -// -// Contract: -// - Exit 0 after writing all lines (do not call process.exit — let Node -// flush stdout, especially under pipes) -// - Tokens (JFROG_ACCESS_TOKEN / JF_ACCESS_TOKEN): "present" or empty -// - URLs (JFROG_URL / JF_URL): "present" or empty (prefer presence-only) -// - JF_PROJECT / JFROG_AGENT_GUARD_REPO: real value or empty when unset -// - Never print raw token values - -import process from "node:process"; - -const presentOrEmpty = (value) => (value ? "present" : ""); - -const lines = [ - `JFROG_URL: ${presentOrEmpty(process.env.JFROG_URL)}`, - `JFROG_ACCESS_TOKEN: ${presentOrEmpty(process.env.JFROG_ACCESS_TOKEN)}`, - `JF_URL: ${presentOrEmpty(process.env.JF_URL)}`, - `JF_ACCESS_TOKEN: ${presentOrEmpty(process.env.JF_ACCESS_TOKEN)}`, - `JF_PROJECT: ${process.env.JF_PROJECT ?? ""}`, - `JFROG_AGENT_GUARD_REPO: ${process.env.JFROG_AGENT_GUARD_REPO ?? ""}`, -]; - -process.stdout.write(`${lines.join("\n")}\n`); diff --git a/skills/jfrog-mcp-management/scripts/jfrog-ai-governance-config.mjs b/skills/jfrog-mcp-management/scripts/jfrog-ai-governance-config.mjs new file mode 100755 index 0000000..db7f8aa --- /dev/null +++ b/skills/jfrog-mcp-management/scripts/jfrog-ai-governance-config.mjs @@ -0,0 +1,548 @@ +#!/usr/bin/env node +// jfrog-ai-governance-config.mjs — resolve and update the JFrog AI Governance +// server and project in ${JFROG_CLI_HOME_DIR:-~/.jfrog}/setup.json. +// +// Usage, commands, options and exit codes: see USAGE below (also printed on a +// usage error). +// +// Contract: +// - Exactly one entry has `isDefault`. A v1 file with a single entry is +// treated as its default and migrated (written back as v2) by `get`. +// - `set` on an ambiguous file (no clear default) needs no --force and +// leaves the target as the only default. +// - A file whose `version` is newer than this script knows is read, but +// never written. +// - Unknown keys are preserved on every write. +// - Writes are temp file + rename, no lock. +// - stderr: an `info:` line if deprecated env vars are set; `debug:` lines +// with JF_AGENT_GUARD_LOG_LEVEL=debug. +// - Self-contained (Node builtins only): copied verbatim into the hooks, +// which import resolveAiGovernanceConfig and run `server-id`. +// +// File shape: +// { "version", "servers": { "": { "jpdUrl", "currentActiveProject"?, +// "isDefault"? } } } + +import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { + mkdirSync, + readFileSync, + realpathSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const USAGE = `\ +Usage: jfrog-ai-governance-config.mjs [options] + +Commands: + get Print the AI Governance server and project as JSON: + {status, serverId?, jpdUrl?, project?, path?}. + status: ok | no_project | ambiguous | missing | corrupt + (corrupt: setup.json is not valid; path names it). + list Print every saved server as a JSON array of + {serverId, jpdUrl, project?, isDefault}. + set [project] Make the AI Governance server (jpdUrl + from \`jf config show\`). + Project omitted: keep the saved one. + server-id Print only the server id, for command substitution. + Prints nothing if the id is invalid (see set). + Always exits 0. + +Options: + --no-project set: save no project; clears a saved one (needs --force). + --force set: override the saved server or project, or + replace a corrupt file. Only when you know what + you are doing. + +Environment: + JF_AGENT_GUARD_LOG_LEVEL=debug Print debug lines on stderr. + +Exit codes: + 0 ok + 1 set failed (message on stderr) + 2 usage error +`; +const CURRENT_VERSION = 2; +const DEPRECATED_ENV = [ + "JFROG_URL", + "JF_URL", + "JFROG_ACCESS_TOKEN", + "JF_ACCESS_TOKEN", + "JF_PROJECT", + "JFROG_PROJECT", + "JF_SERVER", + "JFROG_SERVER_ID", + "JF_SERVER_ID", +]; +const NOOP_LOG = { debug() {} }; +// The charset the hooks accept for ids passed to agent-guard. The jf CLI does +// not limit server ids (it only rejects delete, use, show, clear): enforced here. +const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const SAFE_ID_RULE = + 'letters, digits, ".", "_" or "-", starting with a letter or digit, at most 128 characters'; + +// import.meta.url is symlink-resolved, argv[1] is not; compare real paths. +function isMainModule(moduleUrl) { + if (!process.argv[1]) return false; + try { + return fileURLToPath(moduleUrl) === realpathSync(process.argv[1]); + } catch { + return false; + } +} + +const isObject = (v) => + v !== null && typeof v === "object" && !Array.isArray(v); +const nonEmpty = (v) => typeof v === "string" && v !== ""; + +function aiGovernanceConfigPath(env) { + return join( + env.JFROG_CLI_HOME_DIR || join(homedir(), ".jfrog"), + "setup.json", + ); +} + +// A missing file has no entries. A file that exists but is unreadable, not a +// JSON object, or has a non-object `servers` is `corrupt` (and has no data). +function loadSetup(path, log) { + const corrupt = { data: null, entries: [], corrupt: true }; + let parsed; + try { + parsed = JSON.parse(readFileSync(path, "utf8")); + } catch (err) { + if (err.code === "ENOENT") { + log.debug(`no setup.json at ${path}`); + return { data: null, entries: [], absent: true }; + } + log.debug( + err instanceof SyntaxError + ? `${path} is not valid JSON` + : `could not read ${path}: ${err.code || err.message}`, + ); + return corrupt; + } + if (!isObject(parsed)) { + log.debug(`${path} is not a JSON object`); + return corrupt; + } + if (parsed.servers !== undefined && !isObject(parsed.servers)) { + log.debug(`${path}: "servers" is not an object`); + return corrupt; + } + const entries = Object.entries(parsed.servers ?? {}).filter(([, e]) => + isObject(e), + ); + return { data: parsed, entries }; +} + +const isNewer = (data) => + typeof data?.version === "number" && data.version > CURRENT_VERSION; + +// The entry `get` would select, or null when ambiguous. A lone entry without +// isDefault is the implied default. +function select(entries) { + const defaults = entries.filter(([, e]) => e.isDefault === true); + if (defaults.length === 1) { + return { id: defaults[0][0], entry: defaults[0][1], implied: false }; + } + if (defaults.length === 0 && entries.length === 1) { + return { id: entries[0][0], entry: entries[0][1], implied: true }; + } + return null; +} + +function writeAtomic(path, data) { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`; + try { + // "wx" fails if anything (e.g. a planted symlink) already exists at tmp. + writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { + flag: "wx", + mode: 0o644, + }); + renameSync(tmp, path); + } catch (err) { + try { + unlinkSync(tmp); + } catch { + // Never created or already renamed. + } + throw err; + } +} + +/** + * Select the AI Governance server from setup.json, migrating a lone v1 entry to v2. + * @param {object} [options] + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{status: "missing" | "ambiguous"} + * | {status: "corrupt", path: string} + * | {status: "ok" | "no_project", serverId: string, jpdUrl: string, project?: string}} + * corrupt: the file exists but is not a valid setup object. + */ +export function resolveAiGovernanceConfig({ + env = process.env, + log = NOOP_LOG, +} = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + const { data, entries, corrupt } = loadSetup(path, log); + if (corrupt) return { status: "corrupt", path }; + if (entries.length === 0) { + log.debug("missing: no usable entries"); + return { status: "missing" }; + } + const sel = select(entries); + if (!sel) { + const marked = entries.filter(([, e]) => e.isDefault === true).length; + log.debug( + marked + ? `ambiguous: ${marked} entries marked isDefault` + : `ambiguous: ${entries.length} entries, none marked isDefault`, + ); + return { status: "ambiguous" }; + } + log.debug( + `default "${sel.id}" (${sel.implied ? "only entry, implied" : "explicit isDefault"})`, + ); + if (sel.implied && !isNewer(data)) { + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: { + ...data.servers, + [sel.id]: { ...sel.entry, isDefault: true }, + }, + }); + log.debug(`migrated ${path}: "${sel.id}" is now the default`); + } catch (err) { + log.debug(`migration write to ${path} failed: ${err.message}`); + } + } + const base = { serverId: sel.id, jpdUrl: sel.entry.jpdUrl }; + const project = sel.entry.currentActiveProject; + if (nonEmpty(project)) return { status: "ok", ...base, project }; + log.debug(`no_project: "${sel.id}" has no currentActiveProject`); + return { status: "no_project", ...base }; +} + +// Same as `get` but never migrates. +function listAiGovernanceConfig({ env = process.env, log = NOOP_LOG } = {}) { + const path = aiGovernanceConfigPath(env); + log.debug(`reading ${path}`); + return loadSetup(path, log) + .entries.map(([serverId, e]) => ({ + serverId, + jpdUrl: e.jpdUrl, + ...(nonEmpty(e.currentActiveProject) && { + project: e.currentActiveProject, + }), + isDefault: e.isDefault === true, + })) + .sort((a, b) => a.serverId.localeCompare(b.serverId)); +} + +// Platform root URL, or "" when `raw` is not an http(s) URL. A missing scheme +// means https. +function normalizeJpdUrl(raw) { + const s = raw.trim(); + try { + const url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(s) ? s : `https://${s}`); + if (!["http:", "https:"].includes(url.protocol)) return ""; + return url.origin + url.pathname.replace(/(\/(artifactory|ui))*\/*$/, ""); + } catch { + return ""; + } +} + +// Returns the server list, or null when jf could not be run or its output +// was unusable (reported to the caller as "could not run jf", distinct from +// "server not configured"). jf is looked up on PATH only. +function loadJfServers(env, log) { + // On Windows an npm-installed jf is a .cmd shim, which only a shell can + // launch; the command is a constant, so passing it as one string is safe. + const opts = { encoding: "utf8", env, timeout: 30_000 }; + const r = + process.platform === "win32" + ? spawnSync("jf config show --format=json", { ...opts, shell: true }) + : spawnSync("jf", ["config", "show", "--format=json"], opts); + if (r.error || r.status !== 0) { + log.debug( + `jf config show failed: ${r.error?.message || `exit ${r.status}`}`, + ); + return null; + } + try { + const parsed = JSON.parse(r.stdout); + if (Array.isArray(parsed)) return parsed; + if (Array.isArray(parsed?.servers)) return parsed.servers; + } catch (err) { + log.debug(`jf config show output not parseable: ${err.message}`); + } + return null; +} + +/** + * Make serverId the AI Governance server. + * Without force it refuses to switch away from another default server, and to + * change or clear the saved non-empty project. An empty project is an error: + * pass noProject to save none. + * @param {string} serverId jf CLI server id + * @param {string} [project] undefined keeps the saved project (unless noProject) + * @param {object} [options] + * @param {boolean} [options.force] override the refusals above + * @param {boolean} [options.noProject] save no project; excludes a project + * @param {NodeJS.ProcessEnv} [options.env] default process.env + * @param {{debug(message: string): void}} [options.log] default silent + * @returns {{ok: true} | {ok: false, error: string}} + */ +export function setAiGovernanceConfig( + serverId, + project, + { force = false, noProject = false, env = process.env, log = NOOP_LOG } = {}, +) { + if (project === "") { + return { + ok: false, + error: "an empty project is not accepted; pass noProject to unset", + }; + } + if (noProject && project !== undefined) { + return { + ok: false, + error: "project and noProject are mutually exclusive", + }; + } + if (noProject) project = ""; + if (nonEmpty(project) && !SAFE_ID.test(project)) { + return { + ok: false, + error: `invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}`, + }; + } + if (!SAFE_ID.test(serverId)) { + return { + ok: false, + error: `invalid server id ${JSON.stringify(serverId)}: ${SAFE_ID_RULE}; re-add the server to the jf CLI under a valid id`, + }; + } + const path = aiGovernanceConfigPath(env); + const { data, entries, absent, corrupt } = loadSetup(path, log); + if (corrupt && !force) { + return refuse(`${path} is corrupt`, log); + } + if (isNewer(data)) { + return refuse( + `${path} was written by a newer version (${data.version}); refusing to modify it`, + log, + ); + } + const current = select(entries); + const previous = entries.find(([id]) => id === serverId)?.[1]; + // The project to protect is the target's own; it matters only when there is + // no default or the target is the default. + const existing = previous?.currentActiveProject; + const currentProject = current?.entry.currentActiveProject; + log.debug( + current + ? `current default: "${current.id}" (${nonEmpty(currentProject) ? `project "${currentProject}"` : "no project"})` + : "no current default", + ); + if (current && current.id !== serverId) { + if (!force) { + return refuse( + `the AI Governance server in ${path} is "${current.id}"; setting "${serverId}" would change it`, + log, + ); + } + log.debug(`switching default "${current.id}" -> "${serverId}" (--force)`); + } else if ( + previous && + project !== undefined && + project !== (existing ?? "") + ) { + if (!force && nonEmpty(existing)) { + const change = nonEmpty(project) ? `setting "${project}"` : "clearing it"; + return refuse( + `"${serverId}" uses project "${existing}"; ${change} would change it`, + log, + ); + } + log.debug( + nonEmpty(project) + ? `setting project of "${serverId}" to "${project}"` + : `clearing project of "${serverId}"`, + ); + } else if (current) { + log.debug(`"${serverId}" is already the default; refreshing`); + } else { + log.debug(`new default "${serverId}"`); + } + // The jf CLI is consulted only once the saved state allows the change, so a + // refusal names the saved server, not a missing jf config entry. + const jfServers = loadJfServers(env, log); + if (!jfServers) { + return { + ok: false, + error: + "could not run `jf config show`; is the JFrog CLI installed and on PATH?", + }; + } + const jpdUrlOf = (s) => + normalizeJpdUrl(`${s.url ?? ""}`.trim() || `${s.artifactoryUrl ?? ""}`); + const jf = jfServers.find( + (s) => isObject(s) && s.serverId === serverId && jpdUrlOf(s), + ); + log.debug( + `jf config show returned servers: ${jfServers + .filter(isObject) + .map((s) => s.serverId) + .join(", ")}`, + ); + if (!jf) { + log.debug(`"${serverId}" not found in jf config show`); + return { + ok: false, + error: `server "${serverId}" is not in the jf CLI config`, + }; + } + log.debug(`"${serverId}" -> ${jpdUrlOf(jf)}`); + const nextServers = Object.fromEntries( + entries.map(([id, e]) => { + const { isDefault: _drop, ...rest } = e; + return [id, rest]; + }), + ); + const { currentActiveProject: saved, ...kept } = previous ?? {}; + const nextProject = project === undefined ? saved : project; + nextServers[serverId] = { + ...kept, + jpdUrl: jpdUrlOf(jf), + ...(nonEmpty(nextProject) && { currentActiveProject: nextProject }), + isDefault: true, + }; + log.debug(`${absent ? "creating" : "updating"} ${path}`); + try { + writeAtomic(path, { + ...data, + version: CURRENT_VERSION, + servers: nextServers, + }); + } catch (err) { + log.debug(`write to ${path} failed: ${err.message}`); + return { ok: false, error: `write failed: ${err.message}` }; + } + log.debug(`wrote ${path}`); + return { ok: true }; +} + +function refuse(error, log) { + log.debug(`refused: ${error}`); + return { ok: false, error }; +} + +function usage() { + process.stderr.write(USAGE); + return 2; +} + +function main(argv, env) { + const [mode, ...rest] = argv; + const log = { + debug: (m) => + env.JF_AGENT_GUARD_LOG_LEVEL === "debug" && + process.stderr.write(`debug: ${m}\n`), + }; + + if (mode === "server-id") { + try { + const cfg = resolveAiGovernanceConfig({ env, log }); + if (cfg.status === "ok" || cfg.status === "no_project") { + if (!SAFE_ID.test(cfg.serverId)) { + log.debug( + `server-id: ${JSON.stringify(cfg.serverId)} not printed: invalid id (${SAFE_ID_RULE})`, + ); + } else { + process.stdout.write(`${cfg.serverId}\n`); + } + } + } catch { + // Always exit 0 with no output: callers use this in $(...). + } + return 0; + } + + const flags = ["--force", "--no-project"]; + const [serverId, project, ...extra] = rest.filter((a) => !flags.includes(a)); + const force = rest.includes("--force"); + const noProject = rest.includes("--no-project"); + const argsOk = + mode === "set" + ? nonEmpty(serverId) && !extra.length && !(noProject && project) + : !rest.length; + const stray = rest.some((a) => a.startsWith("-") && !flags.includes(a)); + const badProject = nonEmpty(project) && !SAFE_ID.test(project); + if (badProject) { + process.stderr.write( + `ai-governance-config: invalid project key ${JSON.stringify(project)}: ${SAFE_ID_RULE}\n`, + ); + } + const emptyProject = mode === "set" && project === ""; + if (emptyProject) { + process.stderr.write( + "ai-governance-config: an empty project is not accepted; use --no-project to unset\n", + ); + } + if ( + !["get", "list", "set"].includes(mode) || + !argsOk || + stray || + badProject || + emptyProject + ) { + return usage(); + } + + const used = DEPRECATED_ENV.filter((name) => nonEmpty(env[name])); + if (used.length) { + process.stderr.write( + `info: ${used.join(", ")} set but ignored (deprecated); AI Governance config comes from ${aiGovernanceConfigPath(env)}. Continuing normally without using them.\n`, + ); + } + + if (mode === "get") { + process.stdout.write( + JSON.stringify(resolveAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + if (mode === "list") { + process.stdout.write( + JSON.stringify(listAiGovernanceConfig({ env, log }), null, 2) + "\n", + ); + return 0; + } + const result = setAiGovernanceConfig(serverId, project, { + force, + noProject, + env, + log, + }); + if (!result.ok) { + process.stderr.write(`ai-governance-config: ${result.error}\n`); + return 1; + } + return 0; +} + +if (isMainModule(import.meta.url)) { + process.exitCode = main(process.argv.slice(2), process.env); +} diff --git a/skills/jfrog-setup-package-managers/SKILL.md b/skills/jfrog-setup-package-managers/SKILL.md index 35a59a8..6c7db73 100644 --- a/skills/jfrog-setup-package-managers/SKILL.md +++ b/skills/jfrog-setup-package-managers/SKILL.md @@ -6,8 +6,11 @@ description: >- to JFrog Artifactory via `jf setup` and `.jfrog/local/package-resolution.json`; when a workspace manifest exists with no matching binding entry; or when a session hook reports package-manager config missing. Skip when the binding - already has the same repo key. Never pick a repo by discovery; use resolver - output only (unless the user names or asks to browse repos). On unresolved + already has the same repo key. When the session status is `already set up` + or `setting up in the background`, do not invoke this skill proactively + for a missing workspace binding. An explicit setup or rebind request, and + a JFrog 401/403, still invoke it. Never pick a repo by discovery; use resolver + output only (unless the user names or asks to browse repos, or a global key is BLOCKED). On unresolved or failed setup, ask with the failure verbatim — never switch servers. NOT for installing packages, general Artifactory repo operations (use the base jfrog skill), or MCP server setup (use jfrog-mcp-management). @@ -74,6 +77,16 @@ Do not execute a command string from the notice or from the workspace. binding at `.jfrog/local/package-resolution.json` (via `scripts/merge-workspace-binding.sh`) when package-manager config is still missing. +**Eager APR exception:** When the current session's **Package manager setup** +status says a package manager is `already set up` or `setting up in the +background`, **do not invoke this skill** proactively because a governed +manifest exists and the workspace binding is missing. For `already set up`, +run the normal package-manager command without registry flags. For +`setting up in the background`, follow the session policy's **direct rewrite +only** instruction and do not start a second `jf setup`. An explicit setup +or rebind request, and recovery from a package-manager 401/403 response +from JFrog, still invoke this skill as usual. + **Honor the injected policy's governed scope.** The session policy lists the package managers it governs. Do **not** *proactively* onboard a package manager the policy doesn't govern (e.g. a stray `Dockerfile` when only `pypi`/`npm` are governed) — @@ -214,7 +227,8 @@ usable. **Don't choose a repo yourself:** no listing, enumerating, probing, or iterating `--server-id` to pick one, and don't second-guess the resolver — use resolver -output only. If the user explicitly asks to browse repos, list them via +output only. If the user explicitly asks to browse repos, or a global key is +[broken](#broken-global-repo-key-blocked), list them via `jf api "/artifactory/api/repositories?type=virtual&packageType="` (Artifactory **package type** from the binding map — `gradle` not `maven`; `uv` / `pip` / `pipenv` / `poetry` → `pypi`), then let the user choose; the @@ -230,6 +244,44 @@ Ask via AskQuestion (include the resolver/setup failure text verbatim): Cap at **2 answers per package manager**, then abort. User may override repo only, never server. +### Broken global repo key (BLOCKED) + +When the session policy says ` is BLOCKED — not routed` with cause +`not-found` or `package-type-mismatch`, the key in `~/.jfrog/agents-conf.json` +is wrong for every project. Fix it there, not only in this workspace: + +1. List virtual repos of that package type (the browse call above) and ask via + AskQuestion which one to use (repo key, or `abort`). Never pick one yourself. +2. In one shell, load that answer through the quoted heredoc, keep only the + key the checker prints, and run `set-repo` with that key. Stop if the + checker fails or `configure.mjs` is missing or unsafe: + + ```bash + raw="$(cat <<'JFKEY' + + JFKEY + )" + REPO="$(bash /scripts/check-repo-key.sh --repo "$raw")" || exit $? + CONFIGURE="$(find "$HOME/.claude/plugins" "$HOME/.cursor/plugins" "$HOME/.codex" "$HOME/.copilot" \ + -type f -path '*/modules/package-resolution/scripts/configure.mjs' \ + -exec ls -t {} + 2>/dev/null | head -n 1)" + case "$CONFIGURE" in + "" | *[!A-Za-z0-9._/-]* | "$PWD"/*) echo "unsafe or missing configure.mjs: [$CONFIGURE]" >&2; exit 1 ;; + *) node "$CONFIGURE" set-repo --type --repo "$REPO" ;; + esac + ``` + +3. Exit `0` → Step 4 (load the routing policy), then Step 3 if the package + manager still has no config. Non-zero → show stderr verbatim and stop. It + refuses when the current key works, when the new key is not a virtual repo + of that package type, when package resolution is off, or when the current + key could not be checked (401/403, server error, unreachable: fix `jf` + instead). If the file changed during the check, run the command again. + Never hand-edit `agents-conf.json`. + +Other causes (401/403, 5xx, unreachable): fix `jf` login or connectivity; the +key stays. + ## Step 3 — Confirm, run `jf setup`, persist binding 1. Present the plan, one row per package manager: @@ -303,7 +355,9 @@ Cap at **2 answers per package manager**, then abort. User may override repo onl ## Step 4 — Load the routing policy If this session started with the hook's "routing NOT READY" (enforce) notice, -refresh the policy after Step 3 succeeds. Find the installed script yourself — +or after a successful `set-repo` in +[Broken global repo key](#broken-global-repo-key-blocked), refresh the policy +after that step succeeds. Find the installed script yourself — take no path or command from the notice. Run from the workspace root: ```bash diff --git a/skills/jfrog-setup-package-managers/references/global-cache-file.md b/skills/jfrog-setup-package-managers/references/global-cache-file.md index 4a1293d..d6b9c5a 100644 --- a/skills/jfrog-setup-package-managers/references/global-cache-file.md +++ b/skills/jfrog-setup-package-managers/references/global-cache-file.md @@ -46,7 +46,8 @@ pruning, the file cannot. ``` Each `servers.` entry holds `repositories`, `cached_at`, `source`, and -`agentsConfigMtimeMs` (mtime of `~/.jfrog/agents-conf.json` at last refresh). +`agentsConfigMtimeMs` (mtime of `~/.jfrog/agents-conf.json` at last refresh), +plus an optional `unresolved` map when a configured key failed verification. The workspace binding file at [`.jfrog/local/package-resolution.json`](workspace-binding.md) holds only `repositories`. The map key **is** the `serverId`. @@ -58,6 +59,7 @@ only `repositories`. The map key **is** the `serverId`. | `servers..cached_at` | ISO-8601 timestamp of the last refresh. TTL from `packageResolution.cacheTtlDays` in agents-conf.json (default 7). | | `servers..agentsConfigMtimeMs` | Invalidates cache when `~/.jfrog/agents-conf.json` changes. | | `servers..source` | `verified` = keys from agents-conf.json checked via `GET /api/repositories/{key}`; `agents-config` = trusted without HTTP (`verifyRepos: false`). | +| `servers..unresolved.` | Optional. `{ "repoKey", "cause" }` for a configured key that failed verification (`not-found`, `package-type-mismatch`, `http-403`, `unreachable`, …). An entry with a failed key is re-checked after 1 hour, not after `cacheTtlDays`. Read-only for this skill — see [Broken global repo key](../SKILL.md#broken-global-repo-key-blocked). | Package type keys used in the file are `npm`, `pypi`, `maven`, `gradle`, `go`, `docker`, `helm`, `nuget`. Note `pypi` (not `pip`) — same convention the diff --git a/skills/jfrog-setup-package-managers/references/workspace-binding.md b/skills/jfrog-setup-package-managers/references/workspace-binding.md index 9795c80..05eea47 100644 --- a/skills/jfrog-setup-package-managers/references/workspace-binding.md +++ b/skills/jfrog-setup-package-managers/references/workspace-binding.md @@ -63,10 +63,19 @@ Before setup, **read** the file (if it exists). For each package manager in the to-bind set, map it to a package type and compare `repositories.` against what the resolver chose in Step 2: +> **Eager APR exception:** When the session status says the package manager +> is `already set up` or `setting up in the background`, do not invoke this skill +> proactively just because this file has no matching type. For `already set up`, +> use the normal package-manager command. For `setting up in the background`, +> follow the session policy's direct-rewrite instruction and do not start a +> second `jf setup`. Still apply the table below for an explicit setup or rebind +> request, and for recovery from a package-manager 401/403 response from JFrog, +> including a different repo key (show the diff and confirm). + | Case | Action | |---|---| | Missing type in `repositories` | Check the repo key, run `jf setup`, and merge in Step 6. | -| Same repo key | **Skip** `jf setup` — hook already applies overrides on session start. | +| Same repo key | **Skip** `jf setup` — the hook already applies it. For a 401/403 from JFrog, re-run `jf setup` with this same repo key. | | Different repo key | Show diff and confirm via AskQuestion before overwriting. | | Value fails `^[A-Za-z0-9._-]+$` | Not the current binding. Do not diff it or pass it through. Stop and ask for a replacement key. Other types in the file stay usable. | diff --git a/skills/jfrog/SKILL.md b/skills/jfrog/SKILL.md index 93f0f18..4c945ea 100644 --- a/skills/jfrog/SKILL.md +++ b/skills/jfrog/SKILL.md @@ -21,7 +21,7 @@ compatibility: >- operations; without it, only MCP (Tier 1) is available. metadata: role: base - version: "0.44.0" + version: "0.47.0" --- # JFrog Skill