This is an automated email from the ASF dual-hosted git repository. luigidemasi pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel-kit.git
commit 73d47f9c94dd1cf2fed86e823188d584bc75042e Author: Luigi De Masi <[email protected]> AuthorDate: Mon Nov 23 10:56:10 2026 +0100 Fix #193: Reconcile installed skills and commands by ownership Co-authored-by: OpenAI Codex <[email protected]> --- CHANGELOG.md | 3 + docs/architecture.md | 15 +- docs/commands.md | 12 +- docs/modules/ROOT/pages/agents.adoc | 10 +- docs/modules/ROOT/pages/commands.adoc | 20 +- docs/modules/ROOT/pages/existing-project.adoc | 7 +- docs/modules/ROOT/pages/getting-started.adoc | 27 ++- docs/modules/ROOT/pages/skills.adoc | 5 + docs/security-model.md | 10 +- docs/security-model.yaml | 4 +- docs/user-guide.md | 2 +- .../org/apache/camel/kit/command/InitCommand.java | 12 +- .../apache/camel/kit/generator/CatalogUpdate.java | 60 +++-- .../camel/kit/generator/ClaudeGenerator.java | 20 +- .../camel/kit/generator/CommandStubGenerator.java | 6 +- .../camel/kit/generator/DefaultGenerator.java | 8 +- .../apache/camel/kit/generator/ManagedFiles.java | 249 ++++++++++++++++----- .../kit/generator/SkillResourceInstaller.java | 19 +- .../apache/camel/kit/service/DoctorService.java | 14 +- .../org/apache/camel/kit/service/InitService.java | 4 +- .../camel/kit/generator/CatalogUpdateTest.java | 64 ++++++ .../camel/kit/service/InitSafeAdoptionTest.java | 85 ++++++- .../apache/camel/kit/service/InitServiceTest.java | 79 +++---- .../camel/kit/workflow/SkillPackCompilerTest.java | 88 +++++++- 24 files changed, 611 insertions(+), 212 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2c7cfe6..5c9d79b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Preserve local changes to catalog skills, guides and command stubs during initialization and upgrades (#193). + Preview conflicts with `--dry-run`, compare host-specific proposals under `.camel-kit/conflicts/`, and accept + individual files with `--replace <path>`. Doctor identifies retired catalog entry points still installed. - Align Main environment probes, recovery guidance, direct migration and generated `AGENTS.md` with the JBang alias and the project's Camel version, matching generated `run.sh` (#110). Report incompatible local JBang plugins as environment failures. Correct the environment probe's YAML step nesting so its sample route can start. diff --git a/docs/architecture.md b/docs/architecture.md index 14c7e163..95cba0a2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -922,16 +922,16 @@ that decides what happens to them: only files named for replacement are written. Preview and execution share that plan. - A preserved file is reported and the generated version is saved under `.camel-kit/conflicts/`. A preserved Maven wrapper file is the exception: it is reported without a saved version, so no partial wrapper is offered for - merging; `--replace-wrapper` replaces the whole wrapper. `--replace <path>` rewrites one shared file in full; + merging; `--replace-wrapper` replaces the whole wrapper. `--replace <path>` rewrites one shared file or selected catalog asset in full; `--dry-run` reports the outcome per file without writing. - Existing MCP configurations, JSON and `.codex/config.toml`, are merged, not replaced. One that cannot be merged is rejected before anything is written, by `--dry-run` as well as by initialization; for Codex both build and validate the same merged candidate. -Each run regenerates the selected skills, subagents, personas, hooks and `.camel-kit/templates/`, including the -restricted Ship worker definitions. The ledger also records the final content of catalog skills, guides and -command stubs. On a catalog switch, init checks the old records in the selected host directories before retiring -files. Text hashes normalize LF and CRLF for the formats listed in the contributor guide. Opaque resources use +Each run regenerates subagents, personas, hooks and `.camel-kit/templates/`, including restricted Ship workers. +Catalog files are rendered with their host traits and invocation metadata in staging. Init compares each destination +with its ledger record before publishing the finished file or retiring it. Edited or unrecorded selected files +receive a proposal. Their live content never becomes the recorded installation merely by rerunning init. Text hashes normalize LF and CRLF for the formats listed in the contributor guide. Opaque resources use SHA-256 of their exact bytes. An edited retired file keeps its record so later runs can report it. A switch between a file and a directory stages the new content and requires all files it displaces to match the ledger. Init checks write access before switching. If a run leaves staged content or a backup, subsequent previews, @@ -947,9 +947,8 @@ Rejected alternatives: from one the user wrote, so generated files would never be refreshed on reinitialization. - **Hash-track the instruction files too.** A preserved `AGENTS.md` would lack the skill routing until merged by hand. - **Use marked blocks for every shared file.** JSON, YAML and shell files cannot carry a reliable marker. -- **Track every generated file, including skills.** Skills are rewritten several times in one run (install, agent - adaptation, traits, dispatch block, version resolution), and preserving a locally edited Ship worker would weaken - its restrictions. +- **Track every generated file.** Catalog skills are tracked after rendering. Restricted Ship worker definitions + must still be regenerated to enforce the current restrictions. Missing provenance is unknown ownership, never Camel-Kit ownership. A workspace initialized before the ledger existed is treated like any other existing project: unmarked instruction files get the block appended, and other shared files diff --git a/docs/commands.md b/docs/commands.md index 61b5bbe1..f59c1b7e 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -70,9 +70,9 @@ camel kit init --here [options] | `--replace-wrapper` | `false` | Replace the complete Maven wrapper; use `--replace <path>` to replace only one shared file | | `--record-baseline` | `false` | Run the existing project's build and tests once to record baseline results; never runs during `--dry-run` | | `--source-platform` | `auto` | Source platform for migration: `mulesoft`, `camel`, `biztalk`, `auto` | -| `--force` | `false` | Reinitialize a project that already has `.camel-kit/`. Your content in shared files is kept | -| `--replace <path>` | none | Replace one existing shared file in full (for example `AGENTS.md` or `mvnw`) instead of merging or preserving it; repeatable | -| `--dry-run` | `false` | Preview which shared files init would create, replace, merge or preserve and which retired catalog files it would remove or preserve | +| `--force` | `false` | Reinitialize a project that already has `.camel-kit/`. Preserves edits to shared files and catalog assets | +| `--replace <path>` | none | Accept the generated version of one shared file or catalog file selected for this assistant. Repeat for each path | +| `--dry-run` | `false` | Preview create, replace, merge, preserve and remove actions for shared and catalog files | | `--silent` | `false` | Suppress all output (no banner, no TUI, no progress, no summary) -- useful for CI/scripted environments | | `-V`, `--version` | -- | Print camel-kit version and exit | @@ -162,7 +162,7 @@ If the target directory already contains `.camel-kit/`, init warns and exits: Directory: /path/to/my-integration Found: .camel-kit/ - To reinitialize: --force (refreshes selected assets and preserves edits to shared files) + To reinitialize: --force (preserves edits to shared files and catalog assets) Example: camel-kit init my-integration --ai claude --force ``` @@ -173,8 +173,8 @@ file and later replaces only that block. An existing `docs/constitution.md`, `.c untouched and listed at the end of the run; the version Camel-Kit would have written is saved under `.camel-kit/conflicts/`, except for Maven wrapper files, which are listed without a saved version; use `--replace-wrapper` to replace the whole wrapper. Pass `--replace <path>` to replace a file in full, or `--dry-run` to preview; -the preview runs the same validation as init and rejects an existing MCP configuration that cannot be merged. Shipped -skills and other selected `camel-*` assets are regenerated. When switching distributions, `init --force` removes +the preview runs the same validation as init and rejects an existing MCP configuration that cannot be merged. For a selected skill, guide or command stub with local edits or no recorded +hash, compare the generated proposal under `.camel-kit/conflicts/` or accept it with `--force --replace <path>`. When switching distributions, `init --force` removes recorded skills, guides and command stubs that the new catalog omits and that still match the last installation. Run init for each assistant installation you want to update. Codex and Antigravity share the same skills directory. A retained `SKILL.md` remains discoverable. Review edited and unrecorded skills and move or remove those you want to retire. diff --git a/docs/modules/ROOT/pages/agents.adoc b/docs/modules/ROOT/pages/agents.adoc index 4fc5f8ce..91d5e32d 100644 --- a/docs/modules/ROOT/pages/agents.adoc +++ b/docs/modules/ROOT/pages/agents.adoc @@ -62,11 +62,13 @@ Regenerate a workspace created by an earlier Camel Kit from the project root, th camel-kit init --here --ai claude --force ---- -Commit or back up your own edits to generated files first: the `camel-*` skills are rewritten on every run. +Run with `--dry-run` first to see which skills and commands will change. -* Regeneration removes only the command files Camel Kit itself used to generate in `.claude/commands/`: one - `<command>.md` for each of the nine public commands. Every other file in that directory is preserved, including - your own commands and custom files whose names start with `camel-`. +* If you customized a selected skill, compare the copy under `.camel-kit/conflicts/` and use `--replace <path>` + to accept the generated version. +* For the nine former public command stubs in `.claude/commands/`, Kit removes a file that matches its ownership + record. It reports an edited or unrecorded stub for manual review. Move the old stub out of `.claude/commands/` + to let Claude discover the native skill. Your other commands stay in place. * `init` stops before it writes anything when `.claude`, one of the Claude directories it manages or the legacy `.claude/commands` path is a symbolic link. The error names the link; replace it with a real directory and run `init` again. diff --git a/docs/modules/ROOT/pages/commands.adoc b/docs/modules/ROOT/pages/commands.adoc index 9ad061b8..e0bcd7ca 100644 --- a/docs/modules/ROOT/pages/commands.adoc +++ b/docs/modules/ROOT/pages/commands.adoc @@ -38,13 +38,11 @@ camel-kit init --here [options] | `--ai`, `-a` | `bob2` | Coding agent to configure: `bob2`, `antigravity`, `claude`, `codex`, `copilot`, `pi`, `qwen` or `opencode` | `--here` | `false` | Initialize in the current directory -| `--force` | `false` | Reinitialize a project that already has `.camel-kit/`. Your content in shared files is - kept; see xref:getting-started.adoc#existing-project[Existing projects] -| `--replace <path>` | none | Replace one existing shared file in full, such as `AGENTS.md` or `mvnw`, instead of - merging or preserving it. Repeatable; a path that is not a shared file written by `init` is rejected before - anything is written -| `--dry-run` | `false` | Preview which shared files `init` would create, replace, merge or preserve and which retired - catalog files it would remove or preserve. Runs the same validation as `init`, so an existing MCP configuration that cannot be merged is +| `--force` | `false` | Reinitialize a project that already has `.camel-kit/`. Preserves edits to shared files and catalog assets. + See xref:getting-started.adoc#existing-project[Existing projects] +| `--replace <path>` | none | Accept the generated version of one shared file or one catalog file selected for this assistant. + Repeat the option to select more files. An ineligible path is rejected before generation +| `--dry-run` | `false` | List the create, replace, merge, preserve and remove actions for shared and catalog files. Runs the same validation as `init`, so an existing MCP configuration that cannot be merged is rejected here too | `--replace-wrapper` | `false` | Replace the complete Maven wrapper; use `--replace <path>` to replace only one shared file | `--record-baseline` | `false` | Run the existing project's build and tests once to record baseline results; never runs during `--dry-run` @@ -65,8 +63,10 @@ report the link and exit with code 1. If `init` reports `Cannot inspect`, restor the directory named in the message. When a new distribution drops a skill, guide or command stub, `init --force` removes the recorded, unmodified -file in the selected assistant's directories. Git line-ending conversion is recognized for text resources. -An edited or unrecorded skill can remain discoverable until you move or remove it manually. +file in the selected assistant's directories. An edited or unrecorded file at a selected path stays in place. +Compare it with `.camel-kit/conflicts/<path>`, or accept the generated version with `--force --replace <path>`. +Git line-ending conversion is recognized for text resources. A retired entry point can remain discoverable until +you move or remove it manually. See xref:getting-started.adoc#existing-project[reinitializing existing projects]. Configuration is read in three layers, the later overriding the earlier: the built-in `distribution.properties`, @@ -107,7 +107,7 @@ current filter and permission fields produce upgrade warnings; malformed current exist as skills but must not be exposed as command stubs. A missing catalog-selected file produces a `FAIL` finding that names its path and an exit code of 1. Doctor also fails if a symbolic link lies on the path from the workspace to the selected assistant's skills directory. It reports the recovery directory of -an interrupted catalog update. See xref:getting-started.adoc#existing-project[recovery instructions]. +an interrupted catalog update and identifies retained, recorded skill entry points and legacy command stubs. See xref:getting-started.adoc#existing-project[recovery instructions]. In the development snapshot, Citrus MCP configuration is optional. When the project has not opted in, `doctor` accepts a missing `citrus` entry; when opted in, a missing entry is a failure. Any existing Citrus diff --git a/docs/modules/ROOT/pages/existing-project.adoc b/docs/modules/ROOT/pages/existing-project.adoc index a76f0f63..2ce51d9a 100644 --- a/docs/modules/ROOT/pages/existing-project.adoc +++ b/docs/modules/ROOT/pages/existing-project.adoc @@ -52,8 +52,9 @@ Camel Kit `init` is **safe to run over existing projects** with these protection | Use managed blocks - customizations preserved on reinit | Skill files -| Files Camel Kit ships are refreshed on reinit so they match the installed version. Edit a copy, or add your own file - next to them: files Camel Kit does not ship are never touched +| Reinitialization refreshes files that match their recorded hashes. Local edits and files without an ownership + record stay in place. Review the host-specific proposal under `.camel-kit/conflicts/` and use `--replace <path>` + to accept it. You can also keep your own skills and guides alongside the installed ones | Existing routes | Never modified unless explicitly listed in design spec @@ -68,7 +69,7 @@ Preview changes before writing files: camel-kit init --here --ai claude --dry-run ---- -The preview lists shared files with a `create`, `replace`, `merge` or `preserve` action, using the same +The preview lists shared and selected catalog files with a `create`, `replace`, `merge` or `preserve` action, using the same ownership and replacement rules as initialization. It also lists retired catalog files with a `remove` or `preserve` action. It does not write files or run baseline tests, even when `--record-baseline` is also supplied. It also runs the validation of initialization: an existing MCP configuration diff --git a/docs/modules/ROOT/pages/getting-started.adoc b/docs/modules/ROOT/pages/getting-started.adoc index db436f08..f804053d 100644 --- a/docs/modules/ROOT/pages/getting-started.adoc +++ b/docs/modules/ROOT/pages/getting-started.adoc @@ -173,9 +173,8 @@ integrations. All pins live in `distribution.properties`. == Upgrading Reinstall the standalone CLI with `jbang app install --force` and the release alias above, or run the plugin -installation again. To apply updated generated assets to an existing project, commit or back up customized generated -files, then run `camel-kit init --here --ai <your-agent> --force` from the project root. This rewrites the generated -assets, except shared files you changed (see <<existing-project>>). +installation again. From the project root, preview the upgrade with `camel-kit init --here --ai <your-agent> --dry-run`, +then use `--force` to apply it. Review any preserved skills, guides or commands using the procedure in <<existing-project>>. From 0.4.0:: Camel Main, Camel Spring Boot and Camel MCP default to Camel {camel-version}; the supported older LTS patch is @@ -264,11 +263,17 @@ regular file. On reinitialization, properties you added to `.camel-kit/config.pr Camel Kit records the hash of each tracked file it wrote in `.camel-kit/managed-files.properties`; commit it with the project. Known limits: -* Each run regenerates the selected skills, subagents, personas and `.camel-kit/templates/`. - When switching distributions, `init --force` removes unmodified, recorded skills, guides and command stubs from - the selected assistant's directories after generating the replacement assets. Git conversions between LF and CRLF +* For each selected skill, guide, binary resource or command stub, `init` creates a missing file and refreshes a + file that matches the last installation. If you edited it or its ownership record is missing, your file stays + in place. Compare it with the host-specific version under `.camel-kit/conflicts/<path>`. Merge changes by hand + to keep your customization, or accept the distribution's version for that path, for example + `camel-kit init --here --ai claude --force --replace .claude/skills/camel-validate/SKILL.md`. + This also records the accepted version for future upgrades. If an old file or directory blocks the proposal path, + preview and init identify it. Review it, move it aside, and retry. Subagents, personas and `.camel-kit/templates/` are regenerated. +* When the distribution moves or drops a file, Kit removes the old copy only if it still matches its record. + An edited retired file stays in place and has no new version to merge. Git conversions between LF and CRLF count as the same content for the xref:contributing.adoc#skill-packs[supported text formats]. - Use `--dry-run` to preview removals. + Use `--dry-run` to see the action for each path. Run init for each assistant you want to update. Codex and Antigravity share `.agents/skills/`, so updating either one also updates the skills the other discovers. * Switching between a file and a directory requires write access to the directories holding the old files. @@ -276,10 +281,10 @@ the project. Known limits: a recovery directory, `init`, `--dry-run` and Doctor report its path. After any running init has finished, inspect its `previous` and `new` contents when present, move the directory outside the skills tree, and retry. If the directory cannot be inspected, restore read and search permissions first. -* Older installations may have no catalog ownership record. Kit also keeps and reports edited retired files. - A retained `SKILL.md` remains discoverable even when Doctor passes. Review the skill folder and any associated - command stub, then move them outside the assistant's discovery directories or delete them if you want to retire - the skill. On hosts that use command stubs, Doctor reports any retained `camel-*` stub outside the selected command list. +* A retained `SKILL.md` or command stub can still be discovered by the assistant. Doctor reports recorded retired + entry points and recognized legacy command stubs. Review the files and move them outside the assistant's discovery + directories to retire them. In an older workspace without a catalog ledger, review any additional skill folders + yourself. * A workspace initialized by an earlier Camel Kit has no ledger, and a missing record never counts as ownership. On its first reinitialization the unmarked instruction files get the block appended and the other shared files are preserved and reported, even if Camel Kit generated them. Replace those you want refreshed with diff --git a/docs/modules/ROOT/pages/skills.adoc b/docs/modules/ROOT/pages/skills.adoc index 1258c4c1..6e39cfba 100644 --- a/docs/modules/ROOT/pages/skills.adoc +++ b/docs/modules/ROOT/pages/skills.adoc @@ -5,6 +5,11 @@ demand. Skills are not code: they are structured prompts with step-by-step proce and shared guide imports. They live in `kit/camel-kit-core/src/main/resources/skills/` and `init` copies them, adapted to the agent, into the project. +During an upgrade, `init --dry-run` lists the selected and retired files for that assistant. `init --force` refreshes +unmodified skills and guides. For each local conflict it keeps your file and saves the proposed version under +`.camel-kit/conflicts/`, including the assistant's invocation metadata and traits. See +xref:getting-started.adoc#existing-project[how to compare or accept a proposed file]. + [[tiers]] == Thirteen skills in four tiers diff --git a/docs/security-model.md b/docs/security-model.md index be28e356..14b740d7 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -407,7 +407,7 @@ The knobs that move the security envelope: | Generated MCP tool lists (`enabled_tools`, `tools`, `directTools`, `includeTools`, `alwaysAllow`/`autoApprove`, OpenCode `permission`) and the Claude `settings.json` MCP rules | the workflow manifest's `allowed_tools` — "the read-only and generation helpers used by the skills", with "runtime mutation/control tools" left out *(documented — `docs/architecture.md` §6)* | **Availability filter** (only the listed tools exist for the agent): Codex `enabled_tools`, Copilot `tools`, Pi `direct [...] | `camel.mcp.repos`, `knowledge.mcp.repos`, `citrus.mcp.repos`, `camel.catalog.repos`; JBang launcher `//REPOS` | Maven Central, ASF public, **ASF snapshots, Central snapshots** *(documented — `distribution.properties`, `CamelKit.java`)* | Snapshot repositories serve mutable artifacts: "hosted snapshots are mutable and may lag `main`" *(documented — README)*. `-p` can repoint every list. | **Ruled 2026-10-27 (Q4):** snapshots are retained for development with their mutability documented; [...] | `camel-kit init --no-fetch` | off | Skips every `init`-time download; the workspace relies on pre-populated `.camel-kit/.cache`. | Documented; no security effect beyond removing network access. | -| `camel-kit init --force` | off | Reinitializes an initialized project. Regenerates Camel-Kit's own assets (shipped skills, subagents, personas), replaces only its marked block in instruction files, and preserves other shared files it did not write or that were changed, including a customised Claude `settings.json` allow-list; `--replace <path>` rewrites one shared file in full *(documented — `docs/commands.md`)*. | Data-loss, not security. A preserved `settings.json` keeps the operator [...] +| `camel-kit init --force` | off | Reinitializes an initialized project. Regenerates subagents and personas, updates the marked block in instruction files, and preserves edited or unrecorded shared and catalog files, including a customised Claude `settings.json` allow-list. `--replace <path>` accepts a shared file or one selected catalog asset *(documented — `docs/commands.md`)*. | Data-loss, not security. A preserved `settings.json` keeps the operator's grants, not the generated ones. | | `-p key=value`, `-c path` | none | Override any distribution property, including Camel/Quarkus/Spring Boot versions and repository lists. | Trusted input (`OUT-OF-MODEL: trusted-input`). | | `camel-kit ship --ask always\|smart\|never` | `smart` | `never` removes pauses for material ambiguity but "still stops for missing tools, failed mandatory checks, or authority the user has not granted; a default does not grant permission" *(documented — `docs/commands.md`)*. | Documented; `never` is not a safety mode (§4.9). | | `camel-kit ship --backend` | `pi` | Pi worker: `--tools read,grep,find,ls` for read-only stages and `read,bash,edit,write,grep,find,ls` for EXECUTE, launched with `--no-approve`, `--no-extensions`, `--no-skills`, `--no-context-files` and `--offline` inside the staging cwd *(documented — `PiWorker` argument list)*; it inherits the controller's environment *(maintainer, 2026-10-27 — Q8)*. Native backends (`bob2-native`, `copilot-native`, `claude-native`, `codex-native`) use the host's re [...] @@ -559,11 +559,13 @@ violation warrants coordinated disclosure and a CVE; **hardening** means it is f `GeneratedAssetCleaner`)*; generated file replacements use atomic writes *(documented — `AtomicFileWriter`)*; existing `.codex/config.toml` / `opencode.json` are merged, not replaced *(documented — `docs/architecture.md`)*. `InitService` preflights the exact generated leaves and their ancestors, plus Camel-owned skill, shared-guide and template subtrees before writing. `ConfinedPaths` refuses links in these managed - paths; unrelated worktrees, custom skills and existing data may contain links. Catalog retirement reads + paths; unrelated worktrees, custom skills and existing data may contain links. Catalog updates and retirements read the previous installation's SHA-256 records only for valid resource or stub paths under the selected agent's generated directories. The committed ledger supplies the ownership claim. Review its changes along - with the files it tracks. Kit checks confinement and compares installed content before removal, normalizing - LF and CRLF for recognized UTF-8 text and comparing opaque resources byte for byte. Layout replacements + with the files it tracks. Kit checks confinement and compares installed content before refresh or removal. + An edited or unrecorded selected file receives a rendered proposal unless the operator names it for replacement. + Hashes normalize + LF and CRLF for recognized UTF-8 text. Opaque resources are compared byte for byte. Layout replacements displace only recorded, matching files and their directories. Init and Doctor report interrupted catalog work directories for inspection. Kit leaves their contents for recovery. Other retirements prune only empty parents. New atomic writes use umask-default permissions and replacements retain existing POSIX modes. diff --git a/docs/security-model.yaml b/docs/security-model.yaml index 156ff2c2..63f960bd 100644 --- a/docs/security-model.yaml +++ b/docs/security-model.yaml @@ -224,7 +224,7 @@ configuration_variants: security_relevant: false - knob: camel-kit init --force default: false - effect: Regenerates Camel-Kit's own assets; preserves shared files it did not write or that were changed unless named with --replace (data loss, not security). + effect: Regenerates subagents and personas. Preserves edited or unrecorded shared and catalog files unless explicitly selected with --replace. security_relevant: false - knob: -p key=value, -c path default: none @@ -299,7 +299,7 @@ claimed_properties: property: init confines its writes to the operator-selected target directory and removes only what it generated, through no symlink. An untrusted tree or a symbolic link that redirects a write outside the target is in scope; an intentionally operator-selected destination is authorized. violation_symptom: File created, replaced or deleted outside the operator-selected target, or a write or deletion redirected through a symbolic link. severity: security-critical when reachable from an attacker-controllable input (analysed tree, registry data); otherwise correctness - provenance: "Contract: maintainer (2026-10-27, Q9). InitService/ConfinedPaths preflight generated leaves/ancestors and Camel-owned skill/shared/template subtrees; unrelated worktrees and data links are allowed; new atomic files use umask-default modes and replacements preserve existing POSIX modes; GeneratedAssetCleaner guards legacy deletion; catalog retirement trusts the committed ownership ledger and verifies host-scoped paths, confinement and SHA-256 of regular files (normalized [...] + provenance: "Contract: maintainer (2026-10-27, Q9). InitService/ConfinedPaths preflight generated leaves/ancestors and Camel-owned skill/shared/template subtrees; unrelated worktrees and data links are allowed; new atomic files use umask-default modes and replacements preserve existing POSIX modes; GeneratedAssetCleaner guards legacy deletion; catalog updates trust the committed ownership ledger and verify host-scoped paths, confinement and SHA-256 of regular files (normalized line e [...] - id: P4 property: Pinned, named-repository supply chain for everything fetched or configured; Ship resolver uses fixed HTTPS Maven Central, checksum fail, no redirects, exact coordinates, size caps, SHA-256 content identity, isolated URLClassLoader payloads. Kit's own handling of what it downloads is in scope - catalog JSON is read from the JAR stream in memory, Citrus schema entries are written only inside the cache directory after lexical containment and descendant-link checks; Catalog/Cit [...] violation_symptom: Unpinned coordinate, repository outside the named lists, download accepted on checksum mismatch (Ship), artifact outside its exact path, payload class loaded from elsewhere, or a downloaded artifact that escapes the cache directory or executes code through Kit's parsing or extraction. diff --git a/docs/user-guide.md b/docs/user-guide.md index 7a6daf8b..526b6ab2 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -202,7 +202,7 @@ camel-kit init --here --ai bob2 --force camel kit init --here --ai bob2 --force ``` -Commit or back up customized skills first: `--force` regenerates them. Your content in shared files such as `AGENTS.md` is kept. +Preview the update with `--dry-run`. Edited skills stay in place. Compare their generated proposals under `.camel-kit/conflicts/` or use `--force --replace <path>` to accept one. Restart Bob after regeneration. Earlier `0.4.0-SNAPSHOT` builds can still contain the defect. Until you upgrade, set both invocation fields to `true` only in the nine public skills listed above, then restart Bob; leave internal helpers unchanged. diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java index 1e9f6b58..d37aedee 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java @@ -62,17 +62,17 @@ public class InitCommand extends CamelKitCommand { public boolean noFetch; @Option(parser = KitOptionParser.class, name = "force", - description = "Reinitialize an existing workspace, refreshing selected assets and preserving edits to shared files", + description = "Reinitialize an existing workspace, preserving edits to shared files and catalog assets", hasValue = false) public boolean force; @Option(parser = KitOptionParser.class, name = "dry-run", - description = "Preview changes to shared files and retired catalog assets without writing anything", + description = "Preview changes to shared files and catalog assets without writing anything", hasValue = false) public boolean dryRun; @OptionList(parser = KitOptionParser.class, name = "replace", - description = "Replace this existing shared file (for example AGENTS.md or mvnw) instead of " + description = "Replace this shared file or selected catalog asset instead of " + "preserving it (repeatable)", valueSeparator = OptionList.NO_SEPARATOR) public List<String> replace; @@ -162,7 +162,7 @@ public class InitCommand extends CamelKitCommand { printer().println(dim(" Found: ") + ".camel-kit/"); printer().println(); printer().println(dim(" To reinitialize: ") + bold("--force") - + dim(" (refreshes selected assets and preserves edits to shared files)")); + + dim(" (preserves edits to shared files and catalog assets)")); printer().println(dim(" Example: ") + "camel-kit init " + projectName + " --ai " + ai + " --force"); printer().println(); return 1; @@ -215,9 +215,9 @@ public class InitCommand extends CamelKitCommand { } printer().println(dim(" merge: Camel Kit's block or servers are added and your content is kept.")); printer().println( - dim(" preserve: the file stays as it is. Use --replace <path> to overwrite an eligible shared file.")); + dim(" preserve: the file stays as it is. Use --replace <path> to accept a shared file or selected catalog asset.")); printer().println(dim( - " remove: an unchanged catalog file is retired. Selected skills and other Kit assets are regenerated.")); + " remove: an unchanged catalog file is retired.")); return 0; } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CatalogUpdate.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CatalogUpdate.java index f1245bfb..e7b1982e 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CatalogUpdate.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CatalogUpdate.java @@ -30,7 +30,8 @@ public final class CatalogUpdate { private final InitContext ctx; private final Path project; private final List<ManagedFiles.Change> retirements; - private final Set<Path> selected = new HashSet<>(); + private final List<ManagedFiles.Change> changes; + private final Set<Path> selected = new TreeSet<>(); private final Set<Path> removable = new HashSet<>(); private final Set<Path> removableDirs; private final Set<Path> shapeChanges = new TreeSet<>(); @@ -57,6 +58,13 @@ public final class CatalogUpdate { for (Path root : shapeChanges) { removableTree(root, root); } + List<ManagedFiles.Change> planned = new ArrayList<>(retirements); + for (Path target : selected) { + planned.add(shapeChanges.contains(target) + ? new ManagedFiles.Change(ctx.files().key(target), ManagedFiles.Action.REFRESH, null) + : ctx.files().planCatalogFile(target)); + } + changes = List.copyOf(planned); } private Set<Path> parents(Set<Path> files) { @@ -74,6 +82,10 @@ public final class CatalogUpdate { return retirements; } + public List<ManagedFiles.Change> changes() { + return changes; + } + /** A previous run may already have installed the new layout when removal of its backup failed. */ public static void checkInterruptedUpdate(Path project, Path skillsDir) throws IOException { ConfinedPaths.requirePath(project, skillsDir); @@ -141,10 +153,12 @@ public final class CatalogUpdate { } } - /** Only resources changing between a file and a directory need a temporary destination. */ + /** Render skills, traits and stubs away from live files, then publish the final host-specific bytes. */ public void generate(AgentGenerator generator) throws Exception { List<Replacement> replacements = new ArrayList<>(); - try (Closeable cleanup = () -> discardStaging(replacements)) { + Path rendered = Files.createTempDirectory(project.resolve(".camel-kit"), STAGING_PREFIX); + try (Closeable cleanupRendered = () -> deleteGeneratedTree(rendered); + Closeable cleanup = () -> discardStaging(replacements)) { Map<Path, Path> outputs = new HashMap<>(); for (Path root : shapeChanges) { ConfinedPaths.requirePath(project, root); @@ -158,11 +172,21 @@ public final class CatalogUpdate { } } } + for (Path file : selected) { + outputs.putIfAbsent(file, rendered.resolve(project.relativize(file))); + } ctx.files().stageCatalog(outputs); generator.generate(ctx); try { for (Replacement replacement : replacements) { removableTree(replacement.target(), replacement.target()); + for (Path file : selected) { + if (file.startsWith(replacement.target())) { + var action = file.equals(replacement.target()) + ? ManagedFiles.Action.REFRESH : ManagedFiles.Action.CREATE; + ctx.files().recordCatalogFile(file, Files.readAllBytes(outputs.get(file)), action); + } + } Files.move(replacement.target(), replacement.previous()); Files.move(replacement.next(), replacement.target()); } @@ -182,6 +206,12 @@ public final class CatalogUpdate { } ctx.printer().println(" Replaced catalog layout at " + ctx.files().key(replacement.target())); } + for (Path file : selected) { + Path candidate = outputs.get(file); + if (candidate.startsWith(rendered)) { + ctx.files().installCatalogFile(file, candidate); + } + } } finally { ctx.files().stageCatalog(Map.of()); } @@ -205,21 +235,25 @@ public final class CatalogUpdate { } } + private void deleteGeneratedTree(Path root) throws IOException { + ConfinedPaths.requireTree(project, root); + if (Files.exists(root, LinkOption.NOFOLLOW_LINKS)) { + List<Path> entries; + try (var tree = Files.walk(root)) { + entries = tree.sorted(Comparator.reverseOrder()).toList(); + } + for (Path entry : entries) { + Files.delete(entry); + } + } + } + private void discardStaging(List<Replacement> replacements) throws IOException { IOException failure = null; for (Replacement replacement : replacements) { try { Path generated = replacement.scratch().resolve("new"); - ConfinedPaths.requireTree(project, generated); - if (Files.exists(generated, LinkOption.NOFOLLOW_LINKS)) { - List<Path> entries; - try (var tree = Files.walk(generated)) { - entries = tree.sorted(Comparator.reverseOrder()).toList(); - } - for (Path entry : entries) { - Files.delete(entry); - } - } + deleteGeneratedTree(generated); // If restoration failed, leave the original in its recovery directory. Files.delete(replacement.scratch()); } catch (IOException e) { diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ClaudeGenerator.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ClaudeGenerator.java index d1f15514..71e3b34d 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ClaudeGenerator.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ClaudeGenerator.java @@ -6,6 +6,7 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import org.apache.camel.kit.config.AgentDescriptor; import org.apache.camel.kit.config.AgentRegistry; @@ -22,9 +23,9 @@ public class ClaudeGenerator extends DefaultGenerator { private static final String LEGACY_COMMAND_DIR = ".claude/commands"; // These files were generated before Claude switched to native skills. New commands have never owned this path. - private static final Set<String> LEGACY_COMMAND_STUBS = Set.of("camel-start.md", "camel-brainstorm.md", - "camel-migrate.md", "camel-plan.md", "camel-execute.md", "camel-validate.md", "camel-debug.md", - "camel-knowledge.md", "camel-ship.md"); + static final Set<String> LEGACY_COMMAND_STUBS = Set.of("camel-start", "camel-brainstorm", "camel-migrate", + "camel-plan", "camel-execute", "camel-validate", "camel-debug", "camel-knowledge", "camel-ship") + .stream().map(name -> LEGACY_COMMAND_DIR + "/" + name + ".md").collect(Collectors.toUnmodifiableSet()); @Override public void preflight(InitContext ctx) throws Exception { @@ -48,24 +49,11 @@ public class ClaudeGenerator extends DefaultGenerator { @Override public void generate(InitContext ctx) throws Exception { super.generate(ctx); - removeLegacyCommandStubs(ctx); generateClaudeMd(ctx); generateSettings(ctx); generateSubagents(ctx); } - private void removeLegacyCommandStubs(InitContext ctx) throws IOException { - Path legacyDir = ctx.projectDir().resolve(LEGACY_COMMAND_DIR); - if (!Files.isDirectory(legacyDir)) { - return; - } - try (var files = Files.list(legacyDir)) { - for (Path file : files.filter(f -> LEGACY_COMMAND_STUBS.contains(f.getFileName().toString())).toList()) { - GeneratedAssetCleaner.deleteRegularFile(ctx, file); - } - } - } - /** Installs the registry-declared project subagents, currently the read-only Ship worker. */ private void generateSubagents(InitContext ctx) throws Exception { int subagents = 0; diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CommandStubGenerator.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CommandStubGenerator.java index 96f4c15e..da235710 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CommandStubGenerator.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CommandStubGenerator.java @@ -1,5 +1,7 @@ package org.apache.camel.kit.generator; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Locale; @@ -16,7 +18,9 @@ class CommandStubGenerator { for (WorkflowCommand command : commands) { String content = commandContent(ctx, command); - AtomicFileWriter.write(ctx.commandStub(command.name()), content); + Path target = ctx.files().catalogOutput(ctx.commandStub(command.name())); + Files.createDirectories(target.getParent()); + AtomicFileWriter.write(target, content); } ctx.printer().println(AnsiColors.green("✓") + " Created " + commands.size() + " command stubs"); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java index c834e388..7d0dc19d 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/DefaultGenerator.java @@ -50,13 +50,7 @@ public class DefaultGenerator implements AgentGenerator { @Override public void generate(InitContext ctx) throws Exception { WorkflowManifest workflow = WorkflowManifestLoader.loadDefault(); - skillResourceInstaller.removeRetiredShipGuides(ctx); - for (WorkflowManifest.WorkflowCommand command : workflow.generatedCommandStubs()) { - if (command.isSkillOnly(ctx.agentName())) { - GeneratedAssetCleaner.deleteRegularFile( - ctx, ctx.commandStub(command.name())); - } - } + ctx.files().cleanLegacyCatalogFiles(ctx); generateBaseAssets(ctx, workflow); beforeApplyTraits(ctx); applyTraits(ctx, workflow); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ManagedFiles.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ManagedFiles.java index f5ff25e3..f043f304 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ManagedFiles.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ManagedFiles.java @@ -5,6 +5,7 @@ import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; +import java.nio.file.AccessDeniedException; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.Files; import java.nio.file.LinkOption; @@ -25,6 +26,7 @@ import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.camel.kit.config.AgentRegistry; import org.apache.camel.kit.util.ConfinedPaths; import org.apache.camel.kit.workflow.SkillCatalog; @@ -45,8 +47,8 @@ import org.apache.camel.kit.workflow.SkillCatalog; * A shared file named explicitly for replacement is always rewritten in full. * * <p> - * Files under Camel-Kit's own names (skills, personas, subagents, {@code .camel-kit/}) are not protected and are always - * regenerated. + * Catalog skills, resources and command stubs are tracked after host-specific rendering. Personas, subagents and + * templates under {@code .camel-kit/} are regenerated. */ public final class ManagedFiles { @@ -108,7 +110,7 @@ public final class ManagedFiles { */ public record Change(String path, Action action, Path proposal) { public boolean preservedRetiredFile() { - return action == Action.PRESERVE && !isShared(path); + return action == Action.PRESERVE && proposal == null && !isShared(path); } } @@ -145,26 +147,41 @@ public final class ManagedFiles { * @throws IllegalArgumentException when a replacement is not a shared file Camel-Kit writes */ public static ManagedFiles open(Path projectDir, Collection<String> replace) throws IOException { + return open(projectDir, replace, Set.of()); + } + + public static ManagedFiles open(Path projectDir, Collection<String> replace, String agentName) throws IOException { + return open(projectDir, replace, replace.isEmpty() ? Set.of() : catalogPaths(agentName)); + } + + private static ManagedFiles open(Path projectDir, Collection<String> replace, Set<String> selected) + throws IOException { Path root = projectDir.toAbsolutePath().normalize(); Set<String> replacements = new HashSet<>(); for (String requested : replace) { Path resolved = root.resolve(requested).normalize(); String key = resolved.startsWith(root) ? key(root, resolved) : requested; - if (!isShared(key)) { + if (!isShared(key) && !selected.contains(key)) { Set<String> shared = new TreeSet<>(MERGED); shared.addAll(TRACKED); throw new IllegalArgumentException( - "Cannot replace '" + requested + "': not a shared file written by init. Replaceable files: " + "Cannot replace '" + requested + + "': not a shared file or selected catalog asset. Shared files: " + String.join(", ", shared)); } replacements.add(key); } Properties ledger = new Properties(); Path ledgerFile = root.resolve(LEDGER); - if (Files.isRegularFile(ledgerFile, LinkOption.NOFOLLOW_LINKS)) { - try (var in = Files.newBufferedReader(ledgerFile)) { - ledger.load(in); + try { + ConfinedPaths.requirePath(root, ledgerFile); + if (Files.isRegularFile(ledgerFile, LinkOption.NOFOLLOW_LINKS)) { + try (var in = Files.newBufferedReader(ledgerFile)) { + ledger.load(in); + } } + } catch (IOException | IllegalArgumentException e) { + throw new InvalidAgentConfigurationException("Cannot read " + ledgerFile + ": " + e.getMessage(), e); } return new ManagedFiles(root, false, replacements, ledger); } @@ -239,43 +256,70 @@ public final class ManagedFiles { changes.putIfAbsent(key, new Change(key, Action.PRESERVE, null)); } - private Set<String> catalogPaths(InitContext ctx) throws IOException { + private static Set<String> catalogPaths(String agentName) throws IOException { + var agent = AgentRegistry.get(agentName); var catalog = SkillCatalog.bundled(); - Set<String> installed = new HashSet<>(); - catalog.paths().forEach(path -> installed.add(key(ctx.skillsDir().resolve(path)))); - if (ctx.agent().generatesCommandStubs()) { + Set<String> installed = new TreeSet<>(); + catalog.paths().forEach(path -> installed.add(agent.skillsDirectory() + "/" + path)); + if (agent.generatesCommandStubs()) { catalog.manifest().workflow().generatedCommandStubs().stream() - .filter(command -> !command.isSkillOnly(ctx.agentName())) - .forEach(command -> installed.add(key(ctx.commandStub(command.name())))); + .filter(command -> !command.isSkillOnly(agentName)) + .forEach(command -> installed + .add(agent.commandDirectory() + "/" + command.name() + "." + agent.fileFormat())); } return installed; } - private boolean catalogPath(InitContext ctx, String path) { - String skills = key(ctx.skillsDir()) + "/"; + private static boolean catalogPath(String agentName, String path) { + var agent = AgentRegistry.get(agentName); + String skills = agent.skillsDirectory() + "/"; if (path.startsWith(skills)) { String resource = path.substring(skills.length()); return resource.contains("/") && SkillCatalog.safePath(resource); } - String commands = key(ctx.commandsDir()) + "/"; - return ctx.agent().generatesCommandStubs() && path.startsWith(commands) + if ("claude".equals(agentName) && ClaudeGenerator.LEGACY_COMMAND_STUBS.contains(path)) { + return true; + } + String commands = agent.commandDirectory() + "/"; + return agent.generatesCommandStubs() && path.startsWith(commands) && path.substring(commands.length()) - .matches("[a-z][a-z0-9-]*\\." + Pattern.quote(ctx.agent().fileFormat())); + .matches("[a-z][a-z0-9-]*\\." + Pattern.quote(agent.fileFormat())); } /** Plan retirements before init writes anything. Only this host's catalog roots are eligible. */ public CatalogUpdate planCatalog(InitContext ctx) throws IOException { CatalogUpdate.checkInterruptedUpdate(ctx.projectDir(), ctx.skillsDir()); - Set<String> installed = catalogPaths(ctx); + Set<String> installed = catalogPaths(ctx.agentName()); + List<Change> retired = new ArrayList<>(); + for (String path : obsoleteCatalogPaths(ctx.agentName(), installed)) { + Action action = matchesCatalogFile(path, projectDir.resolve(path)) ? Action.REMOVE : Action.PRESERVE; + retired.add(new Change(path, action, null)); + } + return new CatalogUpdate(ctx, installed, retired); + } + + /** + * Retired entry points still visible to the host. A personal skill without an ownership record is outside the + * catalog. + */ + public List<String> retiredEntryPoints(String agentName) throws IOException { + var agent = AgentRegistry.get(agentName); + String skills = agent.skillsDirectory() + "/"; + return obsoleteCatalogPaths(agentName, catalogPaths(agentName)).stream() + .filter(path -> !path.startsWith(skills) || path.substring(skills.length()).matches("[^/]+/SKILL\\.md")) + .filter(path -> Files.isRegularFile(projectDir.resolve(path), LinkOption.NOFOLLOW_LINKS)) + .toList(); + } + + private List<String> obsoleteCatalogPaths(String agentName, Set<String> installed) throws IOException { Map<String, String> spellings = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); installed.forEach(path -> spellings.put(path, path)); - List<Change> retired = new ArrayList<>(); - for (String entry : new TreeSet<>(ledger.stringPropertyNames())) { - if (!entry.startsWith(CATALOG)) { - continue; - } - String path = entry.substring(CATALOG.length()); - if (installed.contains(path) || !catalogPath(ctx, path)) { + List<String> obsolete = new ArrayList<>(); + Set<String> previous = new TreeSet<>(legacyCatalogPaths(agentName)); + ledger.stringPropertyNames().stream().filter(entry -> entry.startsWith(CATALOG)) + .map(entry -> entry.substring(CATALOG.length())).forEach(previous::add); + for (String path : previous) { + if (installed.contains(path) || !catalogPath(agentName, path)) { continue; } Path target = projectDir.resolve(path); @@ -284,13 +328,43 @@ public final class ManagedFiles { String spelling = spellings.get(path); if (spelling != null && Files.exists(projectDir.resolve(spelling), LinkOption.NOFOLLOW_LINKS) && Files.isSameFile(target, projectDir.resolve(spelling))) { + String previousHash = ledger.getProperty(CATALOG + path); + if (previousHash != null) { + ledger.putIfAbsent(CATALOG + spelling, previousHash); + } continue; } - boolean unchanged = matchesCatalogFile(path, target); - retired.add(new Change(path, unchanged ? Action.REMOVE : Action.PRESERVE, null)); + obsolete.add(path); + } + } + return obsolete; + } + + private static Set<String> legacyCatalogPaths(String agentName) throws IOException { + var agent = AgentRegistry.get(agentName); + Set<String> paths = new HashSet<>(); + for (String guide : List.of("auto-fix-loop.md", "oversight-matrix.md", "state-management.md")) { + paths.add(agent.skillsDirectory() + "/camel-ship/guides/" + guide); + } + if (agent.generatesCommandStubs()) { + SkillCatalog.bundled().manifest().workflow().generatedCommandStubs().stream() + .filter(command -> command.isSkillOnly(agentName)) + .forEach(command -> paths + .add(agent.commandDirectory() + "/" + command.name() + "." + agent.fileFormat())); + } + if ("claude".equals(agentName)) { + paths.addAll(ClaudeGenerator.LEGACY_COMMAND_STUBS); + } + return paths; + } + + // Standalone generator callers opt into the old unconditional writer. Init retires files after generation. + void cleanLegacyCatalogFiles(InitContext ctx) throws IOException { + if (unrestricted) { + for (String path : legacyCatalogPaths(ctx.agentName())) { + GeneratedAssetCleaner.deleteRegularFile(ctx, projectDir.resolve(path)); } } - return new CatalogUpdate(ctx, installed, retired); } void stageCatalog(Map<Path, Path> outputs) { @@ -303,7 +377,7 @@ public final class ManagedFiles { void retireCatalogFiles(InitContext ctx, List<Change> retired) throws IOException { for (Change change : retired) { - if (!catalogPath(ctx, change.path())) { + if (!catalogPath(ctx.agentName(), change.path())) { throw new IOException("Invalid retired catalog path: " + change.path()); } Path target = projectDir.resolve(change.path()); @@ -317,24 +391,36 @@ public final class ManagedFiles { } Files.delete(target); Path skills = ctx.skillsDir().toAbsolutePath().normalize(); - Path root = target.startsWith(skills) ? skills : ctx.commandsDir().toAbsolutePath().normalize(); - for (Path dir = target.getParent(); !dir.equals(root); dir = dir.getParent()) { - try { - Files.delete(dir); - } catch (DirectoryNotEmptyException e) { - break; - } - } + Path root = target.startsWith(skills) ? skills : projectDir.resolve(ctx.agent().commandDirectory()); + pruneEmptyParents(target.getParent(), root); ctx.printer().println(" Removed retired catalog file " + change.path()); } } + private static void pruneEmptyParents(Path directory, Path root) throws IOException { + for (Path dir = directory; !dir.equals(root); dir = dir.getParent()) { + try { + Files.delete(dir); + } catch (DirectoryNotEmptyException e) { + break; + } + } + } + boolean matchesCatalogFile(String path, Path target) throws IOException { String recorded = ledger.getProperty(CATALOG + path); if (recorded == null || !Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) { return false; } - byte[] bytes = Files.readAllBytes(target); + byte[] bytes; + try { + bytes = Files.readAllBytes(target); + } catch (AccessDeniedException e) { + throw new InvalidAgentConfigurationException( + "Cannot read catalog file " + target + + ". Restore read permission and retry.", + e); + } if (recorded.equals(digest(bytes))) { return true; } @@ -360,24 +446,87 @@ public final class ManagedFiles { } } - /** Record the final content after traits are applied. Keep entries for other host directories. */ + Change planCatalogFile(Path target) throws IOException { + String path = key(target); + if (!Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + return new Change(path, Action.CREATE, null); + } + if (unrestricted || replace.contains(path) || matchesCatalogFile(path, target)) { + return new Change(path, Action.REFRESH, null); + } + Path proposals = projectDir.resolve(PROPOSALS); + Path proposal = proposals.resolve(path); + ConfinedPaths.requirePath(projectDir, proposal); + for (Path entry = proposal; entry.startsWith(proposals); entry = entry.getParent()) { + if (!Files.exists(entry, LinkOption.NOFOLLOW_LINKS)) { + continue; + } + boolean valid = entry.equals(proposal) + ? Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS) + : Files.isDirectory(entry, LinkOption.NOFOLLOW_LINKS); + if (!valid) { + throw new InvalidAgentConfigurationException( + "Cannot save catalog proposal for " + path + + ". Review and move " + entry + " aside, then retry."); + } + break; + } + return new Change(path, Action.PRESERVE, proposal); + } + + /** Publish only finished host output. A proposal never establishes ownership of the user's copy. */ + void installCatalogFile(Path target, Path generated) throws IOException { + ConfinedPaths.requirePath(projectDir, target); + String path = key(target); + Path proposal = projectDir.resolve(PROPOSALS).resolve(path); + ConfinedPaths.requirePath(projectDir, proposal); + Change change = planCatalogFile(target); + byte[] bytes = Files.readAllBytes(generated); + if (change.action() == Action.PRESERVE) { + Files.createDirectories(proposal.getParent()); + AtomicFileWriter.write(proposal, bytes); + changes.put(path, change); + return; + } + Files.createDirectories(target.getParent()); + AtomicFileWriter.write(target, bytes); + recordCatalogFile(target, bytes, change.action()); + if (change.action() == Action.REFRESH && replace.contains(path)) { + usedReplacements.add(path); + } + if (Files.isRegularFile(proposal, LinkOption.NOFOLLOW_LINKS)) { + Files.delete(proposal); + pruneEmptyParents(proposal.getParent(), projectDir.resolve(PROPOSALS)); + } + } + + void recordCatalogFile(Path target, byte[] bytes, Action action) { + String path = key(target); + String text = catalogText(target, bytes); + ledger.setProperty(CATALOG + path, text == null ? digest(bytes) : hash(text)); + changes.put(path, new Change(path, action, null)); + } + + /** Finish the host ledger, including final output from callers that run the generator directly. */ public void recordCatalogFiles(InitContext ctx) throws IOException { - Map<String, String> current = new LinkedHashMap<>(); - for (String path : catalogPaths(ctx)) { - Path target = projectDir.resolve(path); - byte[] bytes = Files.readAllBytes(target); - String text = catalogText(target, bytes); - current.put(CATALOG + path, text == null ? digest(bytes) : hash(text)); + String agentName = ctx.agentName(); + Set<String> installed = catalogPaths(agentName); + for (String path : installed) { + if (!changes.containsKey(path)) { + Path target = projectDir.resolve(path); + ConfinedPaths.requirePath(projectDir, target); + recordCatalogFile(target, Files.readAllBytes(target), Action.REFRESH); + } } for (String entry : ledger.stringPropertyNames()) { if (entry.startsWith(CATALOG)) { String path = entry.substring(CATALOG.length()); - if (catalogPath(ctx, path) && !changes.containsKey(path)) { + if (catalogPath(agentName, path) && !installed.contains(path) + && !changes.containsKey(path)) { ledger.remove(entry); } } } - ledger.putAll(current); } /** The outcome for every shared file handled so far, in the order it was handled. */ @@ -403,7 +552,7 @@ public final class ManagedFiles { ledger.store(raw, null); StringBuilder content = new StringBuilder( "# Shared files and catalog assets written by camel-kit init and their content hashes.\n" - + "# Edited shared and retired catalog files are preserved. Selected catalog files are regenerated.\n"); + + "# Edited shared files and catalog assets are preserved.\n"); raw.toString().lines().filter(line -> !line.startsWith("#")).sorted() .forEach(line -> content.append(line).append('\n')); Path ledgerFile = projectDir.resolve(LEDGER); diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java index 30a1ec86..b005a1ce 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/SkillResourceInstaller.java @@ -23,11 +23,6 @@ class SkillResourceInstaller { private static final Pattern EMPHASIS_TOKENS = Pattern.compile("\\\\[\\\\*]|\\*++|\\R"); - private static final List<String> RETIRED_SHIP_GUIDES = List.of( - "auto-fix-loop.md", - "oversight-matrix.md", - "state-management.md"); - /** Agents whose generated Ship entry point relays controller tasks to a read-only native subagent. */ static final Set<String> NATIVE_SHIP_AGENTS = Set.of( AgentGeneratorStrategy.BOB2.descriptorValue(), @@ -67,10 +62,9 @@ class SkillResourceInstaller { if (!failures.isEmpty()) { throw new IOException("Failed to copy skill resources: " + String.join("; ", failures)); } - try (var stream = Files.list(ctx.skillsDir())) { - ctx.printer().println(AnsiColors.green("✓") + " Copied " + catalog.paths().size() + " files in " - + stream.filter(Files::isDirectory).count() + " skill folders"); - } + long folders = catalog.paths().stream().map(path -> path.substring(0, path.indexOf('/'))).distinct().count(); + ctx.printer().println(AnsiColors.green("✓") + " Copied " + catalog.paths().size() + " files in " + + folders + " skill folders"); } private void copySkillFile( @@ -125,13 +119,6 @@ class SkillResourceInstaller { } } - void removeRetiredShipGuides(InitContext ctx) throws IOException { - Path guides = ctx.skillsDir().resolve("camel-ship/guides"); - for (String guide : RETIRED_SHIP_GUIDES) { - GeneratedAssetCleaner.deleteRegularFile(ctx, guides.resolve(guide)); - } - } - private static Pattern codexInvocationPattern(WorkflowManifest workflow) { String skills = workflow.skills().stream().map(s -> Pattern.quote(s.name())).collect(Collectors.joining("|")); // Possessive runs keep long labels and nested quote/list prefixes off the Java regex stack. diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java index d064da28..02869646 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java @@ -24,6 +24,7 @@ import org.apache.camel.kit.config.AgentRegistry; import org.apache.camel.kit.config.OpenCodeProjectConfig; import org.apache.camel.kit.doc.FrontmatterHandler; import org.apache.camel.kit.generator.CatalogUpdate; +import org.apache.camel.kit.generator.ManagedFiles; import org.apache.camel.kit.graph.GraphBuildResult; import org.apache.camel.kit.graph.GraphBuilder; import org.apache.camel.kit.graph.ParserDiagnostic; @@ -179,6 +180,14 @@ public class DoctorService { try { CatalogUpdate.checkInterruptedUpdate(root, skillsDir); + for (String path : ManagedFiles.open(root, Set.of()).retiredEntryPoints(agentKey(agent))) { + // The command directory check already reports unexpected camel-* stubs on stub-based hosts. + if (agent.generatesCommandStubs() && path.startsWith(agent.commandDirectory() + "/camel-")) { + continue; + } + findings.add(DoctorFinding.fail("workspace", path, "Retired catalog entry point is still installed", + "Review this file and move it outside the assistant's discovery directories to retire it.")); + } } catch (IOException e) { findings.add(DoctorFinding.fail("skills", relativize(root, skillsDir), e.getMessage(), "Review the reported path before re-running init.")); @@ -219,14 +228,13 @@ public class DoctorService { } private void checkBobSkillVisibility(Path root, AgentConfig agent, List<DoctorFinding> findings) { - String remediation = "Use a build containing the Bob skill discovery fix, back up generated customizations, " - + "then run camel-kit init --here --ai bob2 --force " - + "(or camel kit init --here --ai bob2 --force)."; for (String skill : expectations.publicSkills()) { Path skillFile = root.resolve(agent.skillsDirectory()).resolve(skill).resolve("SKILL.md"); if (!Files.isRegularFile(skillFile)) { continue; // Missing files are already reported by checkGeneratedWorkspace. } + String remediation = "Review the local file, then run camel-kit init --here --ai bob2 --force --replace " + + relativize(root, skillFile) + " to restore the public entry."; try { String content = Files.readString(skillFile); if (content.isBlank()) { diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java index 59967429..05dac1fb 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/InitService.java @@ -74,7 +74,7 @@ public class InitService { shared.add(targetDir.resolve(template.target())); } shared.add(targetDir.resolve("docs/constitution.md")); - List<ManagedFiles.Change> changes = new ArrayList<>(prepared.catalog().retirements()); + List<ManagedFiles.Change> changes = new ArrayList<>(prepared.catalog().changes()); for (Path file : shared) { if (files.isShared(file)) { changes.add(change(targetDir, file, files.plan(file))); @@ -98,7 +98,7 @@ public class InitService { } } } - return ManagedFiles.open(request.targetDir(), replacements); + return ManagedFiles.open(request.targetDir(), replacements, request.agentName()); } private static ManagedFiles.Change change(Path targetDir, Path file, ManagedFiles.Action action) { diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/CatalogUpdateTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/CatalogUpdateTest.java index 5d916b93..815e0d49 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/CatalogUpdateTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/CatalogUpdateTest.java @@ -12,6 +12,7 @@ import java.util.Set; import org.apache.camel.kit.config.AgentRegistry; import org.apache.camel.kit.config.DistributionConfig; import org.apache.camel.kit.output.Printer; +import org.apache.camel.kit.output.SystemPrinter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -20,6 +21,69 @@ import static org.junit.jupiter.api.Assertions.*; class CatalogUpdateTest { + @Test + void editDuringRenderingPreservesLiveBytesAndProposesTheCompletedBinary(@TempDir Path project) throws Exception { + var agent = AgentRegistry.get("bob2"); + String path = agent.skillsDirectory() + "/shared/example.bin"; + Path target = project.resolve(path); + Files.createDirectories(target.getParent()); + Path ledger = project.resolve(ManagedFiles.LEDGER); + Files.createDirectories(ledger.getParent()); + var files = ManagedFiles.open(project, Set.of()); + var ctx = new InitContext( + agent, "bob2", project.resolve(agent.commandDirectory()), project.resolve(agent.skillsDirectory()), + project, "camel-kit", DistributionConfig.loadFromClasspathOrDefaults(), false, Printer.noop(), files); + var update = new CatalogUpdate(ctx, Set.of(path), List.of()); + byte[] incoming = {0, (byte) 0xff, '\r', '\n'}; + byte[] personal = {0, (byte) 0xfe, '\n'}; + assertEquals(ManagedFiles.Action.CREATE, update.changes().getFirst().action()); + update.generate(install -> { + Path rendered = install.skillFile("shared/example.bin"); + Files.createDirectories(rendered.getParent()); + Files.write(rendered, incoming); + Files.write(target, personal); + }); + files.save(); + assertArrayEquals(personal, Files.readAllBytes(target)); + assertArrayEquals(incoming, Files.readAllBytes(project.resolve(ManagedFiles.PROPOSALS).resolve(path))); + assertFalse(Files.readString(ledger).contains("catalog/" + path)); + } + + @Test + void editAfterLayoutSwapKeepsTheGeneratedOwnershipHash(@TempDir Path project) throws Exception { + var agent = AgentRegistry.get("bob2"); + Path skills = project.resolve(agent.skillsDirectory()); + String path = agent.skillsDirectory() + "/shared/layout"; + Path old = project.resolve(path).resolve("old.md"); + Files.createDirectories(old.getParent()); + Files.writeString(old, "Before"); + Files.createDirectories(project.resolve(".camel-kit")); + var files = ManagedFiles.open(project, Set.of()); + files.recordCatalogFile(old, Files.readAllBytes(old), ManagedFiles.Action.CREATE); + var printer = new SystemPrinter() { + @Override + public void println(String line) { + if (line.contains("Replaced catalog layout")) { + assertDoesNotThrow(() -> Files.writeString(project.resolve(path), "Team edit")); + } + } + }; + var ctx = new InitContext( + agent, "bob2", project.resolve(agent.commandDirectory()), skills, project, + "camel-kit", DistributionConfig.loadFromClasspathOrDefaults(), false, printer, files); + var update = new CatalogUpdate( + ctx, Set.of(path), + List.of(new ManagedFiles.Change(files.key(old), ManagedFiles.Action.REMOVE, null))); + update.generate(install -> { + Path target = install.skillFile("shared/layout"); + Files.createDirectories(target.getParent()); + Files.writeString(target, "After"); + }); + + assertEquals("Team edit", Files.readString(project.resolve(path))); + assertEquals(ManagedFiles.Action.PRESERVE, files.planCatalogFile(project.resolve(path)).action()); + } + @Test void aFailedSecondLayoutReplacementRestoresBothOriginals(@TempDir Path project) throws Exception { var agent = AgentRegistry.get("bob2"); diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java index b077262c..0e6c9c95 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java @@ -3,6 +3,7 @@ package org.apache.camel.kit.service; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -17,6 +18,7 @@ import org.apache.camel.kit.generator.ManagedFiles; import org.apache.camel.kit.generator.ManagedFiles.Action; import org.apache.camel.kit.output.Printer; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; @@ -93,6 +95,83 @@ class InitSafeAdoptionTest { assertTrue(ledger(project).containsKey("mvnw")); } + @Test + void obstructedCatalogProposalIsReportedBeforeAnyWrites() throws Exception { + Path project = tempDir.resolve("orders"); + var service = new InitService(); + var init = request(project, "claude"); + service.initialize(init); + String path = ".claude/skills/camel-validate/SKILL.md"; + Files.writeString(project.resolve(path), "My validation rules"); + Path proposal = project.resolve(ManagedFiles.PROPOSALS).resolve(path); + Files.createDirectories(proposal.getParent().getParent()); + Files.writeString(proposal.getParent(), "Previous proposal at this path"); + var before = snapshot(project); + for (var failure : List.of( + assertThrows(InvalidAgentConfigurationException.class, () -> service.preview(init)), + assertThrows(InvalidAgentConfigurationException.class, () -> service.initialize(init)))) { + assertTrue(failure.getMessage().contains(proposal.getParent().toString()), failure::getMessage); + } + assertEquals(before, snapshot(project)); + Files.move(proposal.getParent(), project.resolve("previous-proposal")); + service.initialize(init); + assertEquals("My validation rules", Files.readString(project.resolve(path))); + assertTrue(Files.isRegularFile(proposal)); + } + + @ParameterizedTest + @MethodSource("agents") + @Tag("cli-compat") + void selectedCatalogFilesRequireOwnershipOrExplicitReplacement(String agentName) throws Exception { + Path project = tempDir.resolve(agentName); + var agent = AgentRegistry.get(agentName); + String skill = agent.skillsDirectory() + "/camel-validate/SKILL.md"; + String guide = agent.skillsDirectory() + "/shared/iron-laws.md"; + var paths = new ArrayList<>(List.of(skill, guide)); + if (agent.generatesCommandStubs()) { + paths.add(agent.commandDirectory() + "/camel-validate." + agent.fileFormat()); + } + var service = new InitService(); + service.initialize(request(project, agentName)); + var generated = new HashMap<String, String>(); + for (String path : paths) { + generated.put(path, Files.readString(project.resolve(path))); + Files.writeString(project.resolve(path), "My " + path); + } + // This guide predates catalog tracking, so even subsequent runs must not claim it. + Properties original = ledger(project); + original.remove("catalog/" + guide); + try (var out = Files.newBufferedWriter(project.resolve(ManagedFiles.LEDGER))) { + original.store(out, null); + } + var before = snapshot(project); + var preview = service.preview(request(project, agentName)); + assertEquals(before, snapshot(project)); + for (String path : paths) { + assertTrue(preview.stream().anyMatch(c -> c.path().equals(path) && c.action() == Action.PRESERVE), path); + } + + for (int run = 0; run < 2; run++) { + var result = service.initialize(request(project, agentName)); + assertEquals(Set.copyOf(paths), result.conflicts().stream().map(ManagedFiles.Change::path) + .collect(Collectors.toSet())); + for (String path : paths) { + assertEquals("My " + path, Files.readString(project.resolve(path))); + assertEquals(generated.get(path), + Files.readString(project.resolve(ManagedFiles.PROPOSALS).resolve(path))); + assertEquals(original.getProperty("catalog/" + path), ledger(project).getProperty("catalog/" + path)); + } + } + var replacement = request(project, agentName, List.of(skill)); + assertTrue(service.preview(replacement).stream() + .anyMatch(c -> c.path().equals(skill) && c.action() == Action.REFRESH)); + assertTrue( + service.initialize(replacement).warnings().stream().noneMatch(w -> w.message().contains("--replace"))); + assertEquals(generated.get(skill), Files.readString(project.resolve(skill))); + assertFalse(Files.exists(project.resolve(ManagedFiles.PROPOSALS).resolve(skill))); + assertEquals("My " + guide, Files.readString(project.resolve(guide))); + } + @ParameterizedTest @MethodSource("agents") void reinitializationIsIdempotentForSharedFiles(String agentName) throws Exception { @@ -415,7 +494,7 @@ class InitSafeAdoptionTest { } @Test - void userFilesNextToShippedSkillsSurviveWhileShippedSkillsAreRefreshed() throws Exception { + void editedSkillsAndNeighboringProjectFilesSurviveReinitialization() throws Exception { Path project = tempDir.resolve("orders"); new InitService().initialize(request(project, "claude")); Path skills = project.resolve(".claude/skills"); @@ -428,7 +507,9 @@ class InitSafeAdoptionTest { new InitService().initialize(request(project, "claude")); - assertEquals(generated, Files.readString(shipped)); + assertEquals("edited shipped skill\n", Files.readString(shipped)); + assertEquals(generated, + Files.readString(project.resolve(ManagedFiles.PROPOSALS).resolve(project.relativize(shipped)))); assertEquals("our notes\n", Files.readString(skills.resolve("camel-start/team-notes.md"))); assertEquals("our own skill\n", Files.readString(skills.resolve("deploy-orders/SKILL.md"))); } diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java index b814b247..b251f368 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitServiceTest.java @@ -3,7 +3,9 @@ package org.apache.camel.kit.service; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.security.MessageDigest; import java.util.ArrayList; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Properties; @@ -12,6 +14,7 @@ import org.apache.camel.kit.CamelKitMain; import org.apache.camel.kit.config.AgentRegistry; import org.apache.camel.kit.config.DistributionConfig; import org.apache.camel.kit.generator.InvalidAgentConfigurationException; +import org.apache.camel.kit.generator.ManagedFiles; import org.apache.camel.kit.output.Printer; import org.junit.jupiter.api.Test; @@ -1551,52 +1554,29 @@ class InitServiceTest { } @Test - void reinitUpdatesSkillManifestsAndGuides() throws Exception { - // Setup: Init once + void reinitPreservesEditedSkillManifestsAndGuides() throws Exception { Path targetDir = tempDir.resolve("skill-update-test"); - Files.createDirectories(targetDir); - new InitService().initialize(request(targetDir, "claude", InitProgress.noop(), InitReporter.noop())); - - // Find a SKILL.md file - Path skillManifest = targetDir.resolve(".claude/skills/camel-start/SKILL.md"); - assertTrue(Files.exists(skillManifest), "SKILL.md should exist after first init"); - String originalSkillContent = Files.readString(skillManifest); - - // Find a guide file - Path guideFile = targetDir.resolve(".claude/skills/camel-brainstorm/guides/version-selection.md"); - if (Files.exists(guideFile)) { - String originalGuideContent = Files.readString(guideFile); - - // Modify both files to simulate old versions - Files.writeString(skillManifest, "# OLD VERSION\n" + originalSkillContent); - Files.writeString(guideFile, "# OLD GUIDE\n" + originalGuideContent); - - // Act: Reinit - new InitService().initialize(request(targetDir, "claude", InitProgress.noop(), InitReporter.noop())); - - // Assert: SKILL.md and guide files are updated (not preserved) - String updatedSkillContent = Files.readString(skillManifest); - assertFalse(updatedSkillContent.contains("# OLD VERSION"), - "SKILL.md should be updated on reinit, not preserved"); - - String updatedGuideContent = Files.readString(guideFile); - assertFalse(updatedGuideContent.contains("# OLD GUIDE"), - "Guide files should be updated on reinit, not preserved"); - } - - // Create a custom file in skills directory (not SKILL.md or guide) + var init = request(targetDir, "claude", InitProgress.noop(), InitReporter.noop()); + var service = new InitService(); + service.initialize(init); + + Path manifest = Path.of(".claude/skills/camel-start/SKILL.md"); + Path guide = Path.of(".claude/skills/camel-brainstorm/guides/version-selection.md"); + String shippedManifest = Files.readString(targetDir.resolve(manifest)); + String shippedGuide = Files.readString(targetDir.resolve(guide)); + Files.writeString(targetDir.resolve(manifest), "# Team skill\n" + shippedManifest); + Files.writeString(targetDir.resolve(guide), "# Team guide\n" + shippedGuide); Path customFile = targetDir.resolve(".claude/skills/camel-start/my-custom-notes.md"); - String customContent = "# My Custom Notes\n\nThese are my project-specific notes."; - Files.writeString(customFile, customContent); + Files.writeString(customFile, "Project notes"); - // Act: Reinit again - new InitService().initialize(request(targetDir, "claude", InitProgress.noop(), InitReporter.noop())); + service.initialize(init); - // Assert: Custom files are preserved (not overwritten) - assertTrue(Files.exists(customFile), "Custom skill file should be preserved on reinit"); - String preservedCustomContent = Files.readString(customFile); - assertEquals(customContent, preservedCustomContent, - "Custom skill files should be preserved exactly, not overwritten on reinit"); + assertEquals("# Team skill\n" + shippedManifest, Files.readString(targetDir.resolve(manifest))); + assertEquals("# Team guide\n" + shippedGuide, Files.readString(targetDir.resolve(guide))); + assertEquals("Project notes", Files.readString(customFile)); + Path proposals = targetDir.resolve(ManagedFiles.PROPOSALS); + assertEquals(shippedManifest, Files.readString(proposals.resolve(manifest))); + assertEquals(shippedGuide, Files.readString(proposals.resolve(guide))); } /** @@ -1635,7 +1615,7 @@ class InitServiceTest { } @Test - void reinitRefreshesSharedSkillResourcesAndKeepsUserOwnedFiles() throws Exception { + void reinitRefreshesRecordedSharedSkillResourcesAndKeepsUserOwnedFiles() throws Exception { Path targetDir = tempDir.resolve("shared-refresh"); Files.createDirectories(targetDir); new InitService().initialize(request(targetDir, "claude", InitProgress.noop(), InitReporter.noop())); @@ -1643,7 +1623,18 @@ class InitServiceTest { Path shared = targetDir.resolve(".claude/skills/shared/context-authority.md"); assertTrue(Files.exists(shared), "the shared resource must be installed"); String shipped = Files.readString(shared); - Files.writeString(shared, "# STALE SHARED COPY\n" + shipped); + Files.writeString(shared, "Previous distribution's context guide."); + Path ledger = targetDir.resolve(ManagedFiles.LEDGER); + var records = new Properties(); + try (var in = Files.newInputStream(ledger)) { + records.load(in); + } + String previousHash + = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(shared))); + records.setProperty("catalog/.claude/skills/shared/context-authority.md", previousHash); + try (var out = Files.newOutputStream(ledger)) { + records.store(out, null); + } Path userFile = targetDir.resolve(".claude/skills/shared/my-team-notes.md"); Files.writeString(userFile, "# mine\n"); diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java index 012e7823..b6c929c5 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/workflow/SkillPackCompilerTest.java @@ -73,11 +73,15 @@ class SkillPackCompilerTest { Path workspace = Files.createDirectory(temp.resolve("workspace")); Path commands = Files.createDirectories(workspace.resolve(".claude/commands")); Files.writeString(commands.resolve("camel-inspect.md"), "My project command."); - Files.writeString(commands.resolve("camel-start.md"), "Retired Kit stub."); + Files.writeString(commands.resolve("camel-start.md"), "My command at a former Kit path."); assertCli(0, distribution, workspace, "init", "--here", "--ai", "claude", "--no-fetch"); assertEquals("My project command.", Files.readString(commands.resolve("camel-inspect.md"))); - assertFalse(Files.exists(commands.resolve("camel-start.md"))); + assertEquals("My command at a former Kit path.", Files.readString(commands.resolve("camel-start.md"))); assertTrue(Files.isRegularFile(workspace.resolve(".claude/skills/camel-inspect/SKILL.md"))); + String doctor = assertCli(1, distribution, workspace, "doctor"); + assertTrue(doctor.contains(".claude/commands/camel-start.md"), doctor); + Files.delete(commands.resolve("camel-start.md")); + assertCli(0, distribution, workspace, "doctor"); } @ParameterizedTest @@ -314,12 +318,63 @@ class SkillPackCompilerTest { assertTrue(Files.isRegularFile(temp.resolve("bob2/.bob/agents/camel-ship-worker.md"))); } + @Test + @Tag("cli-compat") + void allHostsReconcilePublicAndInternalPackEntriesOnUpgrade() throws Exception { + String entries = """ + add: + skill/camel-inspect: {contract: 1, resource: entry.md} + skill/camel-reader: {contract: 1, resource: reader.md} + resource/camel-reader/guides/GUIDE.md: {contract: 1, resource: guide.md} + """; + for (String version : List.of("first", "second")) { + Path pack = pack(version, entries.replace("GUIDE", version)); + write(version, "entry.md", SKILL.replace("Original", version)); + write(version, "reader.md", SKILL.replace("camel-inspect", "camel-reader").replace("true", "false")); + write(version, "guide.md", version); + Path distribution = distribution(pack, version); + assertJava(0, distribution, temp, InstallAgents.class.getName(), "--force"); + for (String name : AgentRegistry.names()) { + var agent = AgentRegistry.get(name); + Path workspace = temp.resolve(name); + Path skills = workspace.resolve(agent.skillsDirectory()); + assertTrue( + Files.readString(skills.resolve("camel-inspect/SKILL.md")).contains(version + " instructions."), + name); + assertEquals(version, Files.readString(skills.resolve("camel-reader/guides/" + version + ".md")), name); + if (version.equals("second")) { + assertFalse(Files.exists(skills.resolve("camel-reader/guides/first.md")), name); + } + var header = SkillPack.YAML.readTree(FrontmatterHandler.extractFrontmatterYaml( + Files.readString(skills.resolve("camel-reader/SKILL.md")))); + assertTrue(header.has("user_invocable") && !header.get("user_invocable").booleanValue(), name); + if (Set.of("claude", "copilot", "pi").contains(name)) { + assertFalse(header.get("user-invocable").booleanValue(), name); + assertTrue(header.get("disable-model-invocation").booleanValue(), name); + } + if (agent.generatesCommandStubs()) { + Path commands = workspace.resolve(agent.commandDirectory()); + String stub = Files.readString(commands.resolve("camel-inspect." + agent.fileFormat())); + assertTrue(stub.contains(agent.skillsDirectory() + "/camel-inspect/SKILL.md"), name); + if (agent.argPlaceholder() != null) { + assertTrue(stub.contains(agent.argPlaceholder()), name); + } + assertFalse(Files.exists(commands.resolve("camel-reader." + agent.fileFormat())), name); + } + } + } + } + /** All hosts use one JVM and one assembled catalog, isolated from the default catalog in the test runner. */ public static class InstallAgents { public static void main(String[] args) { for (String agent : AgentRegistry.names()) { - String[] init = {"init", agent, "--ai", agent, "--no-fetch"}; + var options = new ArrayList<>(List.of("init", agent, "--ai", agent, "--no-fetch")); + options.addAll(List.of(args)); + String[] init = options.toArray(String[]::new); assertEquals(0, CamelKitMain.commandLine(new CamelKitMain(), init).execute(init), agent); + String[] doctor = {"doctor", "--project-dir", agent}; + assertEquals(0, CamelKitMain.commandLine(new CamelKitMain(), doctor).execute(doctor), agent); } } } @@ -427,6 +482,33 @@ class SkillPackCompilerTest { assertCli(0, after, workspace, "doctor"); } + @Test + @Tag("cli-compat") + void doctorIdentifiesARetainedRetiredNativeSkillAlongsidePersonalSkills() throws Exception { + Path pack = pack("inspect", "add: {skill/camel-inspect: {contract: 1, resource: inspect.md}}"); + write("inspect", "inspect.md", SKILL); + Path before = distribution(pack, "inspect"); + Path workspace = Files.createDirectory(temp.resolve("workspace")); + assertCli(0, before, workspace, "init", "--here", "--ai", "claude", "--no-fetch"); + String retired = ".claude/skills/camel-inspect/SKILL.md"; + Path entry = workspace.resolve(retired); + Files.writeString(entry, Files.readString(entry) + "Team instructions."); + Path personal = Files.createDirectories(workspace.resolve(".claude/skills/team")).resolve("SKILL.md"); + Files.writeString(personal, "Our team skill."); + String init = assertCli(0, temp, workspace, "init", "--here", "--ai", "claude", "--force", "--no-fetch"); + assertTrue(init.contains(retired), init); + String doctor = assertCli(1, temp, workspace, "doctor"); + assertTrue(doctor.contains(retired), doctor); + assertTrue(doctor.contains("Retired catalog entry point"), doctor); + String invalid + = assertCli(1, temp, workspace, "init", "--here", "--ai", "claude", "--force", "--replace", retired); + assertTrue(invalid.contains(retired), invalid); + assertTrue(Files.readString(entry).endsWith("Team instructions.")); + Files.move(entry, workspace.resolve("archived-skill.md")); + assertCli(0, temp, workspace, "doctor"); + assertEquals("Our team skill.", Files.readString(personal)); + } + private static void assertPreview(String preview, String action, String path) { assertTrue(preview.replaceAll("\u001B\\[[0-9;]*m", "").lines().map(String::strip) .anyMatch(line -> List.of(line.split("\\s+", 2)).equals(List.of(action, path))), preview);
