Skip to content

fix: add oh-my-opencode-slim schema support (closes #2)#3

Merged
Poorgramer-Zack merged 3 commits intomainfrom
fix/issue-2-omos-schema-missing
Mar 2, 2026
Merged

fix: add oh-my-opencode-slim schema support (closes #2)#3
Poorgramer-Zack merged 3 commits intomainfrom
fix/issue-2-omos-schema-missing

Conversation

@Poorgramer-Zack
Copy link
Owner

@Poorgramer-Zack Poorgramer-Zack commented Mar 2, 2026

Summary

  • Add oh-my-opencode-slim.schema.json (converted from upstream Zod schema)
  • Fix readBundledAsset path resolution in downloader.ts
  • Add slim mode support to init and add commands
  • Fix validator method (validatePreset → validate)
  • Add bundled fallback for schema resolution

Closes #2

Summary by CodeRabbit

  • New Features

    • Added a slim-mode configuration schema with validation and built-in rules.
    • Bundled-asset fallback for schema resolution when downloads are unavailable.
    • Automatic slim profile creation with clearer handling when a slim config already exists.
    • Improved preset handling and validation in slim flows.
  • Tests

    • Added comprehensive tests for slim-mode init and add scenarios, schema fallback, and preset conflict behavior.

- Add slim schema JSON file (converted from Zod schema)
- Fix readBundledAsset path resolution (../../ instead of ../../../)
- Add slim mode support to init command
- Add slim preset validation to add command
- Fix validator method (validate vs validatePreset)
- Add bundled fallback for schema resolution

Closes #2
@coderabbitai
Copy link

coderabbitai bot commented Mar 2, 2026

Warning

Rate limit exceeded

@Poorgramer-Zack has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 8 minutes and 51 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 266c310 and bc3badb.

📒 Files selected for processing (2)
  • src/commands/add.test.ts
  • src/commands/init.ts
📝 Walkthrough

Walkthrough

Adds a new oh-my-opencode-slim JSON Schema asset and extends init/add flows to handle "slim" mode with GitHub download, cache, and bundled-asset fallback, plus associated validator usage and expanded tests and mocks.

Changes

Cohort / File(s) Summary
Slim Mode Schema
shared/assets/oh-my-opencode-slim.schema.json
New JSON Schema describing the oh-my-opencode-slim configuration (root properties, nested definitions, types, required fields, patterns, enums, defaults).
Init Command & Tests
src/commands/init.ts, src/commands/init.test.ts
Introduces slim-mode path: download slim schema (GitHub) with bundled fallback, cache writes, default-template-slim handling, OmosConfigManager usage for config existence/save; tests and mocks updated (SettingsManager, OmosConfigManager, omos-config-path mock).
Add Command & Tests
src/commands/add.ts, src/commands/add.test.ts
Switches schema retrieval to use cache or bundled asset fallback (no direct download), uses validator.validate for OMOS preset validation, adjusts error messages and slim-mode test scenarios; test mocks extended (OmosValidator, getTargetPath).
Bundled Asset Resolution
src/utils/downloader.ts
Adjusted readBundledAsset path computation (reduced upward traversal) to resolve shared/assets correctly.

Sequence Diagram

sequenceDiagram
    participant User
    participant InitCmd as Init Command
    participant SettingsMgr as SettingsManager
    participant GitHub as GitHub API
    participant BundledAssets as Bundled Assets
    participant Cache as Local Cache
    participant ConfigMgr as OmosConfigManager

    User->>InitCmd: omo-switch init
    InitCmd->>SettingsMgr: getEffectiveType()
    SettingsMgr-->>InitCmd: "slim"

    rect rgba(100, 200, 100, 0.5)
    Note over InitCmd: Slim mode schema retrieval
    InitCmd->>Cache: check cached slim schema
    alt Cached
        Cache-->>InitCmd: schema
    else Not cached
        InitCmd->>GitHub: download slim schema
        alt Download succeeds
            GitHub-->>InitCmd: schema
            InitCmd->>Cache: save schema
        else Download fails
            InitCmd->>BundledAssets: read bundled slim schema
            BundledAssets-->>InitCmd: schema
            InitCmd->>Cache: save schema
        end
    end
    end

    InitCmd->>ConfigMgr: new OmosConfigManager("user")
    InitCmd->>ConfigMgr: configExists()
    alt Exists
        ConfigMgr-->>InitCmd: true
        InitCmd->>User: log existing config path
    else Not exists
        ConfigMgr-->>InitCmd: false
        InitCmd->>BundledAssets: load default-template-slim.json
        BundledAssets-->>InitCmd: template
        InitCmd->>ConfigMgr: saveConfig(template)
        ConfigMgr-->>User: config created at path
    end

    InitCmd-->>User: initialization complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰
A slim schema hopped into the stash,
From GitHub or bundled when networks clash.
Tests and validators tidy the trail,
Configs now save without fail.
Hooray — a hop, a patch, a tail!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding oh-my-opencode-slim schema support, which directly addresses the primary objective of the PR.
Linked Issues check ✅ Passed The PR addresses all coding objectives from issue #2: includes the slim schema in shared assets, updates init and add commands to support slim mode with bundled fallback, and enables schema validation for slim profiles.
Out of Scope Changes check ✅ Passed All changes are directly related to resolving issue #2: schema file addition, slim mode support in init/add commands, validator method correction, and downloader path fix are all necessary for the stated objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/issue-2-omos-schema-missing

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai bot added a commit that referenced this pull request Mar 2, 2026
Docstrings generation was requested by @Poorgramer-Zack.

* #3 (comment)

The following files were modified:

* `src/commands/add.ts`
* `src/utils/downloader.ts`
Repository owner deleted a comment from coderabbitai bot Mar 2, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/add.test.ts (1)

230-235: ⚠️ Potential issue | 🟠 Major

Default slim test setup doesn’t provide the slim schema fallback asset.

Slim tests fail early with “Slim schema not found in cache...” before reaching the actual preset assertions.

Proposed baseline mock alignment
     vi.mocked(readBundledAsset).mockImplementation((name: string) => {
       if (name === "oh-my-opencode.schema.json") {
         return '{"$schema":"test"}';
       }
+      if (name === "oh-my-opencode-slim.schema.json") {
+        return '{"$schema":"test-slim"}';
+      }
       return null;
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/add.test.ts` around lines 230 - 235, The test's mocked
readBundledAsset (vi.mocked(readBundledAsset)) doesn't return the slim schema
fallback, causing tests to error out early; update the mockImplementation in
src/commands/add.test.ts so that when readBundledAsset is called with the slim
fallback asset name used by the code (the filename your runtime tries to load
for the slim schema) it returns a valid slim schema JSON string (e.g.,
'{"$schema":"slim"}') while preserving the existing "oh-my-opencode.schema.json"
branch, ensuring the slim fallback is available for the preset assertions to
run.
🧹 Nitpick comments (1)
src/commands/init.ts (1)

28-58: Extract shared schema fetch/fallback logic to one helper.

The OMO and slim branches duplicate almost identical download→cache→bundled fallback flow.

Refactor sketch
+async function ensureSchema(
+  store: StoreManager,
+  spinner: ReturnType<typeof ora>,
+  schemaUrl: string,
+  schemaFile: string,
+  bundledFile: string,
+  label: string
+): Promise<void> {
+  const cachePath = path.join(store.getCacheSchemaPath(), schemaFile);
+  try {
+    await downloadFile(schemaUrl, store.getCacheSchemaPath(), schemaFile, { source: "github" });
+    spinner.succeed(`${label} downloaded from GitHub`);
+  } catch (err) {
+    if (fs.existsSync(cachePath)) {
+      spinner.warn(`Failed to download ${label.toLowerCase()}: ${err instanceof Error ? err.message : "Unknown error"}`);
+      spinner.succeed(`Using cached ${label.toLowerCase()}`);
+      return;
+    }
+    const bundled = readBundledAsset(bundledFile);
+    if (!bundled) throw new Error(`Failed to download or find bundled ${label.toLowerCase()}`);
+    store.saveCacheFile(store.getCacheSchemaPath(), schemaFile, bundled, { source: "bundled" });
+    spinner.succeed(`Using bundled ${label.toLowerCase()}`);
+  }
+}

Also applies to: 61-90

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/init.ts` around lines 28 - 58, The schema
download/caching/fallback flow in init (around downloadFile, schemaCachePath,
readBundledAsset, store.saveCacheFile, and spinner usage) is duplicated; extract
that logic into a single helper (e.g., fetchSchemaOrFallback) that attempts
downloadFile(SCHEMA_URL,...), checks fs.existsSync(schemaCachePath) for cache,
falls back to readBundledAsset and store.saveCacheFile when needed, and returns
the resolved schema path or throws; replace both duplicated blocks with calls to
this helper and propagate spinner updates and thrown errors from the helper back
to the caller.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/commands/add.test.ts`:
- Around line 519-543: The test still asserts that downloadFile was called for
the slim schema even though add.ts now uses a bundled asset fallback; update the
test around runAdd so it no longer expects downloadFile to be invoked for
"oh-my-opencode-slim.schema.json" (remove or replace those
expect(downloadFile)... assertions) and instead assert the bundled fallback
behavior — e.g., expect(downloadFile).not.toHaveBeenCalled() and/or assert that
fs.readFileSync (or the code path that reads bundled assets) was called with the
bundled slim schema filename or that runAdd completed by invoking
OmosConfigManager.addPreset/getPreset as appropriate; update the same pattern
for the similar assertions in the 545-575 block as well.
- Around line 59-67: The test mock for OmosValidator exposes validatePreset but
the command under test calls validator.validate; update the mock in the test to
match the real API by adding a validate method (or alias validate to the
existing mockValidatePreset) on the mocked OmosValidator class so that calls to
validator.validate(...) succeed; reference the OmosValidator class and the mock
function __mockValidatePreset/ mockValidatePreset to keep behavior identical to
current tests.

---

Outside diff comments:
In `@src/commands/add.test.ts`:
- Around line 230-235: The test's mocked readBundledAsset
(vi.mocked(readBundledAsset)) doesn't return the slim schema fallback, causing
tests to error out early; update the mockImplementation in
src/commands/add.test.ts so that when readBundledAsset is called with the slim
fallback asset name used by the code (the filename your runtime tries to load
for the slim schema) it returns a valid slim schema JSON string (e.g.,
'{"$schema":"slim"}') while preserving the existing "oh-my-opencode.schema.json"
branch, ensuring the slim fallback is available for the preset assertions to
run.

---

Nitpick comments:
In `@src/commands/init.ts`:
- Around line 28-58: The schema download/caching/fallback flow in init (around
downloadFile, schemaCachePath, readBundledAsset, store.saveCacheFile, and
spinner usage) is duplicated; extract that logic into a single helper (e.g.,
fetchSchemaOrFallback) that attempts downloadFile(SCHEMA_URL,...), checks
fs.existsSync(schemaCachePath) for cache, falls back to readBundledAsset and
store.saveCacheFile when needed, and returns the resolved schema path or throws;
replace both duplicated blocks with calls to this helper and propagate spinner
updates and thrown errors from the helper back to the caller.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66e41df and 0bb7a2a.

📒 Files selected for processing (6)
  • shared/assets/oh-my-opencode-slim.schema.json
  • src/commands/add.test.ts
  • src/commands/add.ts
  • src/commands/init.test.ts
  • src/commands/init.ts
  • src/utils/downloader.ts

- Rename validatePreset to validate in OmosValidator mock (matches add.ts usage)
- Fix error message assertion to match actual 'Slim schema not found' string
- Add schema cache mock for 'exits when preset exists without --force' test
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/commands/add.test.ts (1)

522-536: Strengthen cache-miss slim test to assert bundled fallback was attempted.

Right now this test only checks failure output. Add an assertion that readBundledAsset("oh-my-opencode-slim.schema.json") was called so the test verifies fallback flow, not just failure text.

Proposed test hardening
-it("fails when slim schema not in cache", async () => {
+it("fails when slim schema is missing in both cache and bundled assets", async () => {
   const storeModule = await import("../store");
   vi.spyOn(storeModule.SettingsManager.prototype, "getEffectiveType").mockReturnValue("slim");
+  vi.mocked(readBundledAsset).mockReturnValue(null);
   vi.mocked(fs.existsSync).mockImplementation((p: any) => {
     const s = path.normalize(String(p || ""));
     const base = path.basename(s).toLowerCase();
     if (base === "preset.json") return true;
     return false;
   });
   vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ orchestrator: { model: "test/model" } }));

   await runAdd("/path/to/preset.json", { scope: "user" });

+  expect(readBundledAsset).toHaveBeenCalledWith("oh-my-opencode-slim.schema.json");
   expect(mockSpinner.fail).toHaveBeenCalledWith(expect.stringContaining("schema not found in cache"));
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/add.test.ts` around lines 522 - 536, The test "fails when slim
schema not in cache" currently only asserts failure text; add an assertion that
the bundled-fallback loader was attempted by spying/mocking readBundledAsset and
expecting it was called for the slim schema (e.g.
expect(readBundledAsset).toHaveBeenCalledWith("oh-my-opencode-slim.schema.json")
) after calling runAdd; ensure you set up the spy/mock on readBundledAsset
before invoking runAdd and restore any mocks if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/commands/add.test.ts`:
- Around line 522-536: The test "fails when slim schema not in cache" currently
only asserts failure text; add an assertion that the bundled-fallback loader was
attempted by spying/mocking readBundledAsset and expecting it was called for the
slim schema (e.g.
expect(readBundledAsset).toHaveBeenCalledWith("oh-my-opencode-slim.schema.json")
) after calling runAdd; ensure you set up the spy/mock on readBundledAsset
before invoking runAdd and restore any mocks if needed.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0bb7a2a and 266c310.

📒 Files selected for processing (1)
  • src/commands/add.test.ts

- Add readBundledAsset slim schema fallback in test mock
- Extract ensureSchema helper to reduce duplication in init.ts
- Override readBundledAsset in 'fails when slim schema not in cache' test
- Remove unused STORE_VERSION import
@Poorgramer-Zack Poorgramer-Zack merged commit a7b4752 into main Mar 2, 2026
5 checks passed
@Poorgramer-Zack Poorgramer-Zack deleted the fix/issue-2-omos-schema-missing branch March 2, 2026 03:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Oh-My-opencode-slim schema missing.

1 participant