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 ed1d6e5b50907bb3b9159cfdce2e5410fb432710 Author: Luigi De Masi <[email protected]> AuthorDate: Mon Nov 23 15:05:10 2026 +0100 Fix #193: Upgrade shared assistant workspaces without claiming personal files Recognize released catalogs at their installed paths across assistant switches. Codex and Antigravity can upgrade either rendering in their shared skills directory. Record first adoption before writing the workspace configuration so a retry preserves copies of released files the project already had. Keep unrecorded personal skills out of the retirement report and remove the obsolete Claude command directory when its last stock stub is gone. Co-authored-by: OpenAI Codex <[email protected]> --- CHANGELOG.md | 7 +- docs/architecture.md | 12 ++- docs/modules/ROOT/pages/agents.adoc | 1 + docs/modules/ROOT/pages/getting-started.adoc | 20 ++-- docs/security-model.md | 6 +- docs/security-model.yaml | 2 +- .../apache/camel/kit/generator/ManagedFiles.java | 38 +++++++- .../camel/kit/generator/ReleasedCatalog.java | 40 +++++--- .../org/apache/camel/kit/service/InitService.java | 1 + .../camel/kit/generator/CatalogUpdateTest.java | 14 +++ .../camel/kit/service/InitSafeAdoptionTest.java | 108 +++++++++++++++++++-- 11 files changed, 202 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5685744..689c6d24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,9 +31,10 @@ 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). - Upgrades from pre-ledger releases refresh stock assets and remove stock retired commands. Preview changed paths - with `--dry-run`, compare `.proposed` copies under `.camel-kit/conflicts/catalog/`, and accept files or catalog - directories with `--replace <path>`. Doctor identifies edited retired entry points still installed. + Upgrades from pre-ledger releases refresh stock assets and remove stock retired commands for each assistant in + a shared workspace. Preview changed paths with `--dry-run`, compare `.proposed` copies under + `.camel-kit/conflicts/catalog/`, and accept files or catalog directories with `--replace <path>`. Doctor + identifies retired entry points and accepts personal skills that reuse a historical name. - 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 ab9fad20..dd20b967 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -930,11 +930,15 @@ that decides what happens to them: 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. Without a record, a known pre-ledger -hash for the installed assistant and path identifies the stock file. A file already matching the new rendering is -recorded in place. Other selected files receive an inert `.proposed` copy under `.camel-kit/conflicts/catalog/`. Text hashes normalize LF and CRLF for the formats listed in the contributor guide. Opaque resources use +with its ledger record before publishing the finished file or retiring it. In a pre-ledger Kit workspace, a known +release hash identifies a stock file at its installed path. Assistants that share a skills +directory can recognize either rendering there. The config names only the most recently initialized assistant. +First-time adoption records `catalog.tracked-from-init=true` in the ledger before writing the Kit config, +so a retry preserves pre-existing copies of released files. Init records a file that already matches the new +rendering in place. For a selected file with unfamiliar or edited content, it saves a `.proposed` copy under +`.camel-kit/conflicts/catalog/`. 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. +between a file and a directory stages the new content and requires every displaced file to match its recorded or released hash. Init checks write access before switching. If a run leaves staged content or a backup, subsequent previews, initializations and Doctor identify the recovery directory under the selected assistant's skills. diff --git a/docs/modules/ROOT/pages/agents.adoc b/docs/modules/ROOT/pages/agents.adoc index 6225aaa5..12e59c70 100644 --- a/docs/modules/ROOT/pages/agents.adoc +++ b/docs/modules/ROOT/pages/agents.adoc @@ -65,6 +65,7 @@ camel-kit init --here --ai claude --force Run with `--dry-run` first to see which skills and commands will change. * From 0.4.0 or 0.4.1, the command above updates stock skills and removes the nine stock command stubs. + Kit removes `.claude/commands/` if deleting the last stock stub leaves it empty. A customized skill stays in place. Compare its `.proposed` file under `.camel-kit/conflicts/catalog/claude/skills/`. To accept the selected skills as a group, add `--replace .claude/skills`. * Kit reports edited retired stubs. Claude Code gives a skill precedence over a command with the same name. diff --git a/docs/modules/ROOT/pages/getting-started.adoc b/docs/modules/ROOT/pages/getting-started.adoc index b070bcf6..3237e381 100644 --- a/docs/modules/ROOT/pages/getting-started.adoc +++ b/docs/modules/ROOT/pages/getting-started.adoc @@ -266,9 +266,13 @@ the project. ==== Upgrading from 0.4.1 and earlier From the project root, run `camel-kit init --here --ai claude --force`, substituting your assistant's name. -Kit recognizes stock catalog files from pre-ledger releases by their installed path and content for that assistant. +In a shared workspace, run this command once for each assistant, in any order. +Kit recognizes stock catalog files from pre-ledger releases by their installed path and content for the selected assistant. It upgrades them and removes recognized stock files the new catalog retired. A file already equal to the new -rendering is recorded in place, even when its ledger entry is missing or stale. Run `camel-kit doctor` after the upgrade. +rendering is recorded in place, even when its ledger entry is missing or stale. Run `camel-kit doctor` after each +init to check the assistant you just updated. +When adopting a project for the first time, Kit records that ownership tracking began with this init. +Copies from older releases that differ from the new rendering stay in place on this and later runs. ==== Reviewing catalog changes @@ -286,17 +290,17 @@ rendering is recorded in place, even when its ledger entry is missing or stale. 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 see changed paths and a count of catalog files already current. - 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. + Codex and Antigravity share `.agents/skills/`. Updating either one recognizes both assistants' stock files + there and installs the selected assistant's rendering. * Switching between a file and a directory requires write access to the directories holding the old files. Restore write access and retry if the preview reports a read-only directory. If an interrupted switch left 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. -* 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 retained `SKILL.md` or command stub can still be discovered by the assistant. Doctor reports retired entry + points with an ownership record or matching release content, and recognized legacy command stubs. Review these + files and move them outside the assistant's discovery directories to retire them. An unrecorded skill with + different content can keep using a historical skill name. * For shared files in a pre-ledger workspace, init appends the managed block to unmarked instructions and preserves unfamiliar content in the other shared files. Use `--replace <path>` to accept a shared file. diff --git a/docs/security-model.md b/docs/security-model.md index 364b3f6a..4a8a0b78 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -562,7 +562,11 @@ violation warrants coordinated disclosure and a CVE; **hardening** means it is f 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. A ledger record takes precedence. For a missing record, Kit can recognize the - installed assistant's stock file by path and a bundled release fingerprint. Review ledger changes alongside the files they track. Kit checks confinement and compares installed content before refresh or removal. + selected assistant's stock file by path and a bundled release fingerprint in a pre-ledger Kit workspace. In a + shared skills directory this includes fingerprints from assistants that install to the same path. First-time + adoption records its origin in the ledger before writing the config, so retries preserve pre-existing copies. An + unrecorded skill with different content can reuse a historical name. Review ledger changes alongside the files they + track. Kit checks confinement and compares installed content before refresh or removal. An identical catalog file is adopted. An unfamiliar or edited file receives a rendered proposal outside assistant discovery directories unless the operator selects it for replacement. Hashes normalize LF and CRLF for recognized UTF-8 text. Opaque resources are compared byte for byte. Layout replacements diff --git a/docs/security-model.yaml b/docs/security-model.yaml index 35551c0a..640e7fc3 100644 --- a/docs/security-model.yaml +++ b/docs/security-model.yaml @@ -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 updates use the committed ownership ledger or, for a missing catalog record, known release fingerprints for the installed assistant an [...] + 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 use the committed ownership ledger or, for a missing catalog record, known release fingerprints at the installed path in a pre [...] - 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/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 643a4632..7b094c77 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 @@ -55,6 +55,7 @@ public final class ManagedFiles { /** Project-relative ledger of shared files and installed catalog assets. */ public static final String LEDGER = ".camel-kit/managed-files.properties"; private static final String CATALOG = "catalog/"; + private static final String TRACKED_FROM_INIT = "catalog.tracked-from-init"; private static final Pattern CATALOG_TEXT = Pattern.compile( "(?i).+\\.(?:md|adoc|txt|ya?ml|json|xml|xsl|sh|toml|properties)"); @@ -126,20 +127,23 @@ public final class ManagedFiles { private final Set<String> usedReplacements = new HashSet<>(); private final Properties ledger; private final Map<String, Set<String>> released; + private final boolean startsCatalogTracking; private final Map<String, Change> changes = new LinkedHashMap<>(); private ManagedFiles(Path projectDir, boolean unrestricted, Set<String> replace, Properties ledger, - Map<String, Set<String>> released) { + Map<String, Set<String>> released, boolean startsCatalogTracking) { this.projectDir = projectDir; this.unrestricted = unrestricted; this.replace = replace; this.ledger = ledger; this.released = released; + this.startsCatalogTracking = startsCatalogTracking; } /** Rewrites every file in full, as initialization did before shared files were protected. */ public static ManagedFiles unrestricted(Path projectDir) { - return new ManagedFiles(projectDir.toAbsolutePath().normalize(), true, Set.of(), new Properties(), Map.of()); + return new ManagedFiles( + projectDir.toAbsolutePath().normalize(), true, Set.of(), new Properties(), Map.of(), false); } /** @@ -194,7 +198,24 @@ public final class ManagedFiles { } catch (IOException | IllegalArgumentException e) { throw new InvalidAgentConfigurationException("Cannot read " + ledgerFile + ": " + e.getMessage(), e); } - return new ManagedFiles(root, false, replacements, ledger, ReleasedCatalog.forWorkspace(root, agentName)); + Map<String, Set<String>> released = Map.of(); + boolean startsTracking = false; + if (agentName != null && !Boolean.parseBoolean(ledger.getProperty(TRACKED_FROM_INIT))) { + if (ReleasedCatalog.hasWorkspaceConfiguration(root)) { + released = ReleasedCatalog.forAgent(agentName); + } else { + startsTracking = true; + } + } + return new ManagedFiles(root, false, replacements, ledger, released, startsTracking); + } + + /** Remember first adoption before init creates the configuration that identifies an older workspace. */ + public void beginCatalogTracking() throws IOException { + if (startsCatalogTracking) { + ledger.setProperty(TRACKED_FROM_INIT, "true"); + save(); + } } /** What {@link #write} would do to this file. Reads only: nothing is written or recorded. */ @@ -331,7 +352,8 @@ public final class ManagedFiles { Map<String, String> spellings = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); installed.forEach(path -> spellings.put(path, path)); List<String> obsolete = new ArrayList<>(); - Set<String> previous = new TreeSet<>(legacyCatalogPaths(agentName)); + Set<String> legacy = legacyCatalogPaths(agentName); + Set<String> previous = new TreeSet<>(legacy); previous.addAll(released.keySet()); ledger.stringPropertyNames().stream().filter(entry -> entry.startsWith(CATALOG)) .map(entry -> entry.substring(CATALOG.length())).forEach(previous::add); @@ -347,7 +369,10 @@ public final class ManagedFiles { && Files.isSameFile(target, projectDir.resolve(spelling))) { continue; } - obsolete.add(path); + // A historical filename can also belong to a personal skill. + if (legacy.contains(path) || ledger.containsKey(CATALOG + path) || matchesCatalogFile(path, target)) { + obsolete.add(path); + } } } return obsolete; @@ -405,6 +430,9 @@ public final class ManagedFiles { Files.delete(target); Path skills = ctx.skillsDir().toAbsolutePath().normalize(); Path root = target.startsWith(skills) ? skills : projectDir.resolve(ctx.agent().commandDirectory()); + if (!root.equals(skills) && !ctx.agent().generatesCommandStubs()) { + root = root.getParent(); + } pruneEmptyParents(target.getParent(), root); ctx.printer().println(" Removed retired catalog file " + change.path()); } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ReleasedCatalog.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ReleasedCatalog.java index 9deeaf6d..0284c66a 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ReleasedCatalog.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/ReleasedCatalog.java @@ -7,11 +7,13 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; +import java.util.stream.Collectors; import org.apache.camel.kit.config.AgentRegistry; import org.apache.camel.kit.util.ConfinedPaths; @@ -20,43 +22,49 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -/** Known installed bytes from before init recorded ownership, scoped to the project's previous assistant. */ +/** Known pre-ledger files for the selected assistant in an existing Camel Kit workspace. */ final class ReleasedCatalog { private ReleasedCatalog() { } - static Map<String, Set<String>> forWorkspace(Path root, String agentName) throws IOException { - if (agentName == null) { - return Map.of(); - } + static boolean hasWorkspaceConfiguration(Path root) throws IOException { Path config = root.resolve(".camel-kit/config.properties"); ConfinedPaths.requirePath(root, config); - String previous; + String configuredAgent; if (Files.isRegularFile(config, LinkOption.NOFOLLOW_LINKS)) { var settings = new Properties(); try (var in = Files.newBufferedReader(config)) { settings.load(in); } catch (IllegalArgumentException malformed) { - return Map.of(); + return false; } - previous = settings.getProperty("agent.name"); + configuredAgent = settings.getProperty("agent.name"); } else { Path yaml = root.resolve(".camel-kit/config.yaml"); if (!Files.isRegularFile(yaml, LinkOption.NOFOLLOW_LINKS)) { - return Map.of(); + return false; } ConfinedPaths.requirePath(root, yaml); try (var in = Files.newInputStream(yaml)) { var settings = new ObjectMapper(new YAMLFactory()).readTree(in); - previous = settings == null ? null : settings.path("agent").path("name").asText(); + configuredAgent = settings == null ? null : settings.path("agent").path("name").textValue(); } catch (JsonProcessingException malformed) { - return Map.of(); + return false; } } - if (!agentName.equals(previous) && !("bob2".equals(agentName) && "bob".equals(previous))) { + // A shared workspace records only the last assistant initialized. + return configuredAgent != null && !configuredAgent.isBlank(); + } + + static Map<String, Set<String>> forAgent(String agentName) throws IOException { + var agent = AgentRegistry.get(agentName); + if (agent == null) { return Map.of(); } - var agent = AgentRegistry.get(agentName); + Set<String> skillWriters = AgentRegistry.names().stream() + .filter(name -> agent.skillsDirectory().equals(AgentRegistry.get(name).skillsDirectory())) + .collect(Collectors.toSet()); + Set<String> commandWriters = Set.of(agentName); Map<String, Set<String>> hashes = new HashMap<>(); try (var in = ReleasedCatalog.class.getResourceAsStream("/workflow/pre-ledger-catalog.tsv")) { if (in == null) { @@ -68,9 +76,11 @@ final class ReleasedCatalog { continue; } String[] fields = line.split("\t"); - if (fields[2].equals("*") || Set.of(fields[2].split(",")).contains(agentName)) { + boolean skill = fields[0].startsWith("skills/"); + Set<String> writers = skill ? skillWriters : commandWriters; + if (fields[2].equals("*") || Arrays.stream(fields[2].split(",")).anyMatch(writers::contains)) { int slash = fields[0].indexOf('/'); - String dir = fields[0].startsWith("skills/") ? agent.skillsDirectory() : agent.commandDirectory(); + String dir = skill ? agent.skillsDirectory() : agent.commandDirectory(); hashes.computeIfAbsent(dir + fields[0].substring(slash), ignored -> new HashSet<>()).add(fields[1]); } } 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 e8422d65..43d27e27 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 @@ -167,6 +167,7 @@ public class InitService { try { progress.startTask("\uD83D\uDCDD", "Writing configuration"); + files.beginCatalogTracking(); createConfigFile(camelKitDir, request.projectName(), request.agentName(), agent, request, createdPaths, isExistingProject); createConstitution(docsDir, request, files, createdPaths); 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 7fbd3756..85dc7365 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 @@ -23,6 +23,20 @@ import static org.junit.jupiter.api.Assertions.*; class CatalogUpdateTest { + @Test + @Tag("cli-compat") + void releaseHashesFollowTheSharedSkillsDirectory() throws Exception { + String shared = ".agents/skills/camel-test/SKILL.md"; + var hashes = ReleasedCatalog.forAgent("codex").get(shared); + assertEquals(hashes, ReleasedCatalog.forAgent("antigravity").get(shared)); + // The three released 0.4.1 renderings of the same skill. + assertTrue(hashes.contains("7382de1bc3eac55b2169371d80bf11714a9a06bccac3d4e7b0b42736bab5a230")); + assertTrue(hashes.contains("f1c3e3ca8409e28665ada0527f8eb0ea2ceae491318dbd849700b735cb28ad61")); + String claudeHash = "b55574a4b7717bfe730ec71daf8aa5e75d6ed855b1a9dc3a5a86f01b25d0d970"; + assertTrue(ReleasedCatalog.forAgent("claude").get(".claude/skills/camel-test/SKILL.md").contains(claudeHash)); + assertFalse(hashes.contains(claudeHash)); + } + @Test @Tag("cli-compat") void queryingRetiredCaseAliasesDoesNotAlterTheLedger(@TempDir Path project) throws Exception { 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 60a26004..20aeae85 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 @@ -22,6 +22,7 @@ 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; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; @@ -129,18 +130,11 @@ class InitSafeAdoptionTest { String guide = ".claude/skills/camel-implement/guides/run-script.md"; String retired = ".claude/skills/camel-ship/guides/auto-fix-loop.md"; // Exact installed 0.4.1 guide and the Ship guide from the last revision that shipped it. - for (String path : List.of(guide, retired)) { - Path file = tempDir.resolve(path); - Files.createDirectories(file.getParent()); - try (var in = getClass().getResourceAsStream("/pre-ledger/" + file.getFileName())) { - Files.copy(in, file); - } - } + copyReleasedFixture(tempDir.resolve(guide)); + copyReleasedFixture(tempDir.resolve(retired)); String release = Files.readString(tempDir.resolve(guide)); String stub = ".claude/commands/camel-validate.md"; - Path commands = Files.createDirectories(tempDir.resolve(".claude/commands")); - Files.writeString(tempDir.resolve(stub), - "Read .claude/skills/camel-validate/SKILL.md and follow those instructions. Requested input: $ARGUMENTS"); + Path commands = writeReleasedClaudeStub(tempDir).getParent(); Files.writeString(commands.resolve("camel-start.md"), "My launch instructions"); Files.writeString(commands.resolve("team.md"), "Team command"); var original = snapshot(tempDir); @@ -165,6 +159,100 @@ class InitSafeAdoptionTest { assertEquals(release, Files.readString(tempDir.resolve(guide))); } + @ParameterizedTest + @CsvSource({"claude, codex", "codex, claude"}) + @Tag("cli-compat") + void releasedWorkspaceUpgradesBothAssistantsInEitherOrder(String first, String second) throws Exception { + Path project = tempDir.resolve("released"); + Path fresh = tempDir.resolve("fresh"); + Files.createDirectories(project.resolve(".camel-kit")); + Files.writeString(project.resolve(".camel-kit/config.properties"), "agent.name=codex\n"); + Path commands = writeReleasedClaudeStub(project).getParent(); + var service = new InitService(); + for (String host : List.of(first, second)) { + String skills = AgentRegistry.get(host).skillsDirectory(); + copyReleasedFixture(project.resolve(skills).resolve("camel-implement/guides/run-script.md")); + service.initialize(request(fresh, host)); + } + for (String host : List.of(first, second)) { + var init = request(project, host); + String guide = AgentRegistry.get(host).skillsDirectory() + "/camel-implement/guides/run-script.md"; + assertTrue(service.preview(init).stream() + .anyMatch(c -> c.path().equals(guide) && c.action() == Action.REFRESH)); + service.initialize(init); + } + var expected = catalogRecords(fresh); + assertEquals(expected, catalogRecords(project)); + for (String path : expected.keySet()) { + assertEquals(-1L, Files.mismatch(fresh.resolve(path), project.resolve(path)), path); + } + assertFalse(Files.exists(commands)); + assertFalse(Files.exists(project.resolve(ManagedFiles.PROPOSALS + "/catalog"))); + } + + @Test + void adoptingAnExistingProjectPreservesCopiesOfReleasedFilesAcrossRetries() throws Exception { + String path = ".claude/skills/camel-implement/guides/run-script.md"; + Path guide = tempDir.resolve(path); + copyReleasedFixture(guide); + Path stub = writeReleasedClaudeStub(tempDir); + String originalGuide = Files.readString(guide); + String originalStub = Files.readString(stub); + var service = new InitService(); + service.preview(request(tempDir, "claude")); + assertFalse(Files.exists(tempDir.resolve(ManagedFiles.LEDGER))); + for (int run = 0; run < 2; run++) { + service.initialize(request(tempDir, "claude")); + assertEquals(originalGuide, Files.readString(guide)); + assertEquals(originalStub, Files.readString(stub)); + } + service.initialize(request(tempDir, "claude", List.of(path))); + assertNotEquals(originalGuide, Files.readString(guide)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @Tag("cli-compat") + void historicalSkillNameAloneDoesNotMakeAPersonalSkillRetired(boolean existingKitWorkspace) throws Exception { + if (existingKitWorkspace) { + Files.createDirectories(tempDir.resolve(".camel-kit")); + Files.writeString(tempDir.resolve(".camel-kit/config.properties"), "agent.name=claude\n"); + } + String path = ".claude/skills/camel-flow/SKILL.md"; + Path skill = tempDir.resolve(path); + Files.createDirectories(skill.getParent()); + String content = "---\nname: camel-flow\ndescription: Team inventory checklist\n---\nRun the team checklist.\n"; + Files.writeString(skill, content); + var init = request(tempDir, "claude"); + var service = new InitService(); + service.initialize(init); + var doctor = new DoctorService().inspect(new DoctorRequest(tempDir)); + assertFalse(doctor.hasFailures(), doctor.findings().toString()); + assertTrue(service.preview(init).stream().noneMatch(c -> c.path().equals(path))); + assertTrue(service.initialize(init).conflicts().stream().noneMatch(c -> c.path().equals(path))); + assertEquals(content, Files.readString(skill)); + assertFalse(ledger(tempDir).containsKey("catalog/" + path)); + } + + private static void copyReleasedFixture(Path file) throws Exception { + Files.createDirectories(file.getParent()); + try (var in = InitSafeAdoptionTest.class.getResourceAsStream("/pre-ledger/" + file.getFileName())) { + Files.copy(in, file); + } + } + + private static Path writeReleasedClaudeStub(Path project) throws Exception { + Path commands = Files.createDirectories(project.resolve(".claude/commands")); + return Files.writeString(commands.resolve("camel-validate.md"), + "Read .claude/skills/camel-validate/SKILL.md and follow those instructions. Requested input: $ARGUMENTS"); + } + + private static Map<String, String> catalogRecords(Path project) throws Exception { + var records = ledger(project); + return records.stringPropertyNames().stream().filter(key -> key.startsWith("catalog/")) + .collect(Collectors.toMap(key -> key.substring("catalog/".length()), records::getProperty)); + } + @ParameterizedTest @MethodSource("agents") @Tag("cli-compat")
