Skip to content

Feat/cli implementation - #5

Closed
mostafamm44 wants to merge 2 commits into
yallma3:mainfrom
mostafamm44:feat/cli-implementation
Closed

mostafamm44 wants to merge 2 commits into
yallma3:mainfrom
mostafamm44:feat/cli-implementation

Conversation

@mostafamm44

@mostafamm44 mostafamm44 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added an interactive CLI setup command for selecting agents, modes, workflows, and project files.
    • Added remote file downloading with version-aware updates and overwrite confirmations.
    • Added automatic generation of agent configuration files and shared skill-directory links.
    • Added clear progress, status, navigation, and error feedback during setup.
  • Documentation

    • Updated quick-start instructions, requirements, CLI workflow, and development guidance.
  • Chores

    • Added standard ignore rules and removed legacy shell and PowerShell setup scripts.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The project replaces shell-based setup scripts with a Bun/TypeScript CLI. It adds interactive initialization, manifest parsing, downloads, agent configuration generation, symlink handling, CLI documentation, TypeScript configuration, and repository defaults.

Changes

TypeScript CLI migration

Layer / File(s) Summary
CLI package and interaction foundation
package.json, tsconfig.json, src/utils/ui.ts, src/utils/prompts.ts, src/index.ts
Adds the Bun CLI package, terminal UI and prompt abstractions, agent/mode/workflow selection, cancellation handling, and the executable entrypoint.
Manifest-driven initialization flow
src/utils/manifest.ts, src/utils/download.ts, src/commands/init.ts
Parses supported manifest layouts, resolves selected files and skills, downloads content, compares SKILL.md versions, and runs the interactive initialization steps.
Generated configurations and agent links
src/utils/generate-configs.ts, src/utils/symlinks.ts
Creates agent-specific configuration files and execution protocol content, then establishes junctions or symbolic links with copy fallbacks.
Repository transition and documentation
.gitignore, AGENTS.md, README.md, codewiser.sh, codewiser.ps1
Adds ignore rules, removes the former setup scripts and protocol section, and documents CLI usage, development setup, and module responsibilities.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the PR, but it is generic and does not clearly describe the specific CLI implementation work. Rename it to a more specific summary, such as "Add interactive codewiser CLI initialization flow".
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 11

🧹 Nitpick comments (6)
src/utils/generate-configs.ts (1)

87-111: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent no-op when AGENTS.md is missing.

If the download step failed to fetch AGENTS.md, this returns without any signal and the user ends up with a mode selected but no execution protocol. A warn() would make the gap visible.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/generate-configs.ts` around lines 87 - 111, Update
addExecutionProtocolToAgentsMD so the missing AGENTS.md case emits a warning
before returning, while preserving the existing no-op behavior when the file
exists and the protocol is already present.
src/utils/manifest.ts (2)

3-14: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

versionLt silently mis-compares non-numeric version parts.

Number("1-beta") → NaN, and every NaN comparison is false, so versionLt returns false and the file is treated as up to date. A prerelease or malformed manifest version would silently skip updates.

♻️ Coerce invalid segments
 export function versionLt(v1: string, v2: string): boolean {
-  const p1 = v1.split(".").map(Number);
-  const p2 = v2.split(".").map(Number);
+  const parse = (v: string) => v.split(".").map((s) => {
+    const n = Number.parseInt(s, 10);
+    return Number.isNaN(n) ? 0 : n;
+  });
+  const p1 = parse(v1);
+  const p2 = parse(v2);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/manifest.ts` around lines 3 - 14, Update versionLt to explicitly
handle non-numeric segments instead of allowing NaN comparisons to fall through.
Coerce invalid version components to a defined numeric value consistent with the
intended prerelease/malformed-version ordering, while preserving the existing
segment-by-segment comparison and missing-segment defaults.

24-52: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Truthiness check drops legitimately falsy version entries.

mode.files?.[filePath] skips entries whose value is "" or 0, falling through to null and then to "0.0.0" at the call site in src/commands/init.ts line 193. Prefer a key-presence check.

♻️ Use key presence
-        if (mode.files?.[filePath]) return extractVersion(mode.files[filePath]);
+        if (mode.files && filePath in mode.files) return extractVersion(mode.files[filePath]);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/manifest.ts` around lines 24 - 52, Update getManifestVersion to
detect file entries by key presence rather than truthiness in the modes,
workflows/stages, and top-level files lookups, so values such as "" or 0 are
passed to extractVersion instead of falling back to null. Preserve the existing
traversal and return behavior for missing keys.
src/commands/init.ts (1)

216-216: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Manifest write result ignored.

If this download fails, the local manifest is stale or missing and every subsequent run reports 0.0.0 for local versions, silently re-prompting overwrites. Surface a warning at minimum.

♻️ Suggested change
-        await download(manifestUrl, localManifestPath);
+        if (!(await download(manifestUrl, localManifestPath))) {
+          warn("Failed to save local manifest; version tracking may be inaccurate.");
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/init.ts` at line 216, Handle failures from the manifest download
in the init flow around download(manifestUrl, localManifestPath) instead of
ignoring its result. Surface a warning when the download fails, while preserving
the existing initialization flow and ensuring stale or missing manifests are not
treated as successfully updated.
src/utils/download.ts (1)

9-17: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

No timeout on fetch; failures are also indistinguishable from HTTP errors.

A stalled connection hangs the CLI indefinitely since there is no AbortSignal. Consider AbortSignal.timeout(...) and, optionally, returning the error so callers can report why a download failed rather than just Failed: <path>.

♻️ Suggested change
-export async function download(url: string, dest: string): Promise<boolean> {
+export async function download(url: string, dest: string, timeoutMs = 30_000): Promise<boolean> {
   const dir = dirname(dest);
   if (!existsSync(dir)) {
     mkdirSync(dir, { recursive: true });
   }
   try {
-    const res = await fetch(url);
+    const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
     if (!res.ok) return false;
     await Bun.write(dest, res);
     return true;
   } catch {
     return false;
   }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/download.ts` around lines 9 - 17, Update the download function
around fetch to supply an AbortSignal.timeout-based deadline, ensuring stalled
connections terminate; preserve successful writes and distinguish
timeout/network exceptions from non-OK HTTP responses by returning or
propagating the underlying failure in the function’s existing result contract.
src/utils/symlinks.ts (1)

22-34: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Swallowed errors hide a destructive path.

The catch {} wraps copyDirContents + rmSync; if the copy throws partway the removal is skipped (good), but if rmSync throws the user gets no feedback and the subsequent symlinkSync fails for an unexplained reason. Log the failure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/symlinks.ts` around lines 22 - 34, Update the catch block around
the non-symbolic-link handling in the symlink replacement flow to log the caught
error, including context that the source cleanup or replacement failed. Preserve
the existing behavior of skipping further handling after an error while ensuring
failures from rmSync are visible before symlinkSync reports a secondary error.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.gitignore:
- Around line 13-16: Update the log patterns in .gitignore: replace the
literal-underscore _.log entry with a wildcard pattern matching all .log files,
and revise the report pattern to use wildcards for each intended numeric segment
so standard report filenames are ignored.

In `@README.md`:
- Around line 101-105: Update the README setup command to clone the actual
repository, yallma3/codewiser, instead of yallma3/codewiser-cli.git; leave the
subsequent directory change and installation commands consistent with the
corrected repository name.
- Around line 51-53: Update the README’s npm/npx and Node.js guidance
consistently with the CLI’s runtime support: either replace the Bun-only APIs in
the download and symlink paths, including Bun.write() and Bun.file(), with
Node-compatible implementations so the advertised path works, or remove the
Node.js/npx instructions and declare Bun required throughout.

In `@src/commands/init.ts`:
- Around line 80-88: Make the init flow cross-platform: in src/commands/init.ts
at lines 80-88, 170, 184-185, and 241-244, replace backslash-interpolated paths
with path.join; in src/utils/symlinks.ts at lines 45-52, only use the
powershell.exe elevation fallback on Windows and handle spawnSync error/status
to report failure appropriately.
- Around line 153-159: Update the “files” case in the initialization flow to use
the existing extractVersion helper when assigning remoteFiles versions, and add
extractVersion to the manifest utility import. Preserve direct string versions
while correctly extracting versions from structured file entries instead of
defaulting them to “0.0.0”.

In `@src/index.ts`:
- Line 28: Update the targetDir assignment to resolve the project name directly
from process.cwd(), removing the parent-directory segment so commands such as
codewiser demo initialize the project under the current directory.

In `@src/utils/download.ts`:
- Around line 4-8: Validate manifest-derived paths in the init flow before
calling download: resolve filePath against targetDir and skip with a warning
when the result is outside targetDir, including traversal and sibling-prefix
cases. Only pass validated destinations to download, leaving download’s
directory creation behavior unchanged.

In `@src/utils/symlinks.ts`:
- Around line 60-74: Make copyDirContents asynchronous and await each Bun.write
operation so file copies complete and failures propagate. Update every caller,
including the flows around lines 28 and 55, to await copyDirContents before
removing or otherwise using the source directory.
- Around line 45-52: Update the symbolic-link fallback around spawnSync to avoid
interpolating srcPath and destPath into a PowerShell command; pass them as
safely escaped or parameterized arguments instead. Restrict this PowerShell
fallback to Windows, and validate spawnSync’s result so nonzero exits or
execution errors are surfaced rather than silently ignored.
- Line 43: Update the cancellation handling around confirm() and
isCancel(result) so cancel("Cancelled") exits the current flow immediately.
Ensure the retry branch cannot run when the prompt returns Clack’s cancellation
Symbol, while preserving normal retry behavior for non-cancelled results.
- Around line 19-20: Update the symlink path construction around srcPath and
destPath to resolve relativeDest from the directory containing the destination
link, using path resolve and dirname rather than joining it directly to
targetDir. Also ensure the relativeSrc and relativeDest values passed by init
remain POSIX-safe so the generated link resolves to the project’s actual skills
directory.

---

Nitpick comments:
In `@src/commands/init.ts`:
- Line 216: Handle failures from the manifest download in the init flow around
download(manifestUrl, localManifestPath) instead of ignoring its result. Surface
a warning when the download fails, while preserving the existing initialization
flow and ensuring stale or missing manifests are not treated as successfully
updated.

In `@src/utils/download.ts`:
- Around line 9-17: Update the download function around fetch to supply an
AbortSignal.timeout-based deadline, ensuring stalled connections terminate;
preserve successful writes and distinguish timeout/network exceptions from
non-OK HTTP responses by returning or propagating the underlying failure in the
function’s existing result contract.

In `@src/utils/generate-configs.ts`:
- Around line 87-111: Update addExecutionProtocolToAgentsMD so the missing
AGENTS.md case emits a warning before returning, while preserving the existing
no-op behavior when the file exists and the protocol is already present.

In `@src/utils/manifest.ts`:
- Around line 3-14: Update versionLt to explicitly handle non-numeric segments
instead of allowing NaN comparisons to fall through. Coerce invalid version
components to a defined numeric value consistent with the intended
prerelease/malformed-version ordering, while preserving the existing
segment-by-segment comparison and missing-segment defaults.
- Around line 24-52: Update getManifestVersion to detect file entries by key
presence rather than truthiness in the modes, workflows/stages, and top-level
files lookups, so values such as "" or 0 are passed to extractVersion instead of
falling back to null. Preserve the existing traversal and return behavior for
missing keys.

In `@src/utils/symlinks.ts`:
- Around line 22-34: Update the catch block around the non-symbolic-link
handling in the symlink replacement flow to log the caught error, including
context that the source cleanup or replacement failed. Preserve the existing
behavior of skipping further handling after an error while ensuring failures
from rmSync are visible before symlinkSync reports a secondary error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7d30da81-8535-415d-9443-e744a7542e6d

📥 Commits

Reviewing files that changed from the base of the PR and between dffbb35 and 9c410ce.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (15)
  • .gitignore
  • AGENTS.md
  • README.md
  • codewiser.ps1
  • codewiser.sh
  • package.json
  • src/commands/init.ts
  • src/index.ts
  • src/utils/download.ts
  • src/utils/generate-configs.ts
  • src/utils/manifest.ts
  • src/utils/prompts.ts
  • src/utils/symlinks.ts
  • src/utils/ui.ts
  • tsconfig.json
💤 Files with no reviewable changes (3)
  • AGENTS.md
  • codewiser.sh
  • codewiser.ps1

Comment thread .gitignore
Comment on lines +13 to +16
# logs
logs
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fix the log ignore globs.

_.log and the underscore-separated report... pattern use literal _ characters, so ordinary log and report files will not be ignored. Use wildcard syntax such as *.log and the intended report filename pattern.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.gitignore around lines 13 - 16, Update the log patterns in .gitignore:
replace the literal-underscore _.log entry with a wildcard pattern matching all
.log files, and revise the report pattern to use wildcards for each intended
numeric segment so standard report filenames are ignored.

Comment thread README.md
Comment on lines +51 to 53
# Or via npm (after publishing)
npx codewiser my-project

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | sed -n '1,120p'

echo "== README relevant =="
if [ -f README.md ]; then
  nl -ba README.md | sed -n '1,160p'
fi

echo "== download.ts =="
fd -a 'download\.ts$' . | while read -r f; do
  echo "--- $f"
  nl -ba "$f" | sed -n '1,220p'
done

echo "== package/scripts/imports =="
if [ -f package.json ]; then
  nl -ba package.json | sed -n '1,200p'
fi

echo "== search Bun/Cli usage =="
rg -n "Bun\.write|npx codewiser|node\s+|require\(|import \".*download|from \".*download|download" package.json src .github README.md 2>/dev/null || true

Repository: yallma3/codewiser

Length of output: 1306


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== README lines 1-160 =="
awk '{printf "%5d\t%s\n", NR, $0}' README.md | sed -n '1,160p'

echo "== package.json =="
awk '{printf "%5d\t%s\n", NR, $0}' package.json

echo "== src/utils/download.ts =="
awk '{printf "%5d\t%s\n", NR, $0}' src/utils/download.ts

echo "== CLI and download call sites =="
for f in src/commands/init.ts src/index.ts src/utils/*.ts package.json README.md; do
  echo "--- $f"
  awk '{printf "%5d\t%s\n", NR, $0}' "$f" | rg -n "download|npx|node|Bun\.write|fs\.|write" -C 3 || true
done

Repository: yallma3/codewiser

Length of output: 17762


Do not advertise Node.js/npx until the CLI avoids Bun-only APIs.

The README advertises npx codewiser and Node.js 18+, but src/utils/download.ts writes with Bun.write(), which makes the download step fail under Node.js and breaks the advertised npm path. Replace the download write path with Node-compatible APIs, or remove the Node.js/npx instructions and present Bun as required (while also removing the other Bun.file()/Bun.write() symlink path).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 51 - 53, Update the README’s npm/npx and Node.js
guidance consistently with the CLI’s runtime support: either replace the
Bun-only APIs in the download and symlink paths, including Bun.write() and
Bun.file(), with Node-compatible implementations so the advertised path works,
or remove the Node.js/npx instructions and declare Bun required throughout.

Comment thread README.md
Comment on lines +101 to +105
```bash
# Clone and install
git clone https://github.com/yallma3/codewiser-cli.git
cd codewiser-cli
bun install

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the actual repository URL in the setup instructions.

The PR repository is yallma3/codewiser, but the documented command clones yallma3/codewiser-cli.git; following these instructions can fail or check out a different project.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 101 - 105, Update the README setup command to clone
the actual repository, yallma3/codewiser, instead of yallma3/codewiser-cli.git;
leave the subsequent directory change and installation commands consistent with
the corrected repository name.

Comment thread src/commands/init.ts
Comment on lines +80 to +88
mkdirSync(`${targetDir}\\.agents\\skills`, { recursive: true });
mkdirSync(`${targetDir}\\.agents\\specs`, { recursive: true });
mkdirSync(`${targetDir}\\.agents\\plans`, { recursive: true });
mkdirSync(`${targetDir}\\.agents\\research`, { recursive: true });

if (agents.claude) mkdirSync(`${targetDir}\\.claude`, { recursive: true });
if (agents.cursor) mkdirSync(`${targetDir}\\.cursor`, { recursive: true });
if (agents.antigravity) mkdirSync(`${targetDir}\\.antigravity`, { recursive: true });
if (agents.kilo) mkdirSync(`${targetDir}\\.kilo`, { recursive: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

The CLI is Windows-only, but ships as a cross-platform Bun package. Path construction and the elevation fallback both assume Windows; on macOS/Linux the init flow produces literally-named .agents\skills directories and the symlink recovery path is a no-op.

  • src/commands/init.ts#L80-L88: replace all \\-interpolated paths (here and at lines 170, 184-185, 241-244) with join() from path.
  • src/utils/symlinks.ts#L45-L52: gate the powershell.exe fallback on process.platform === "win32" and check spawnSync's error/status instead of ignoring it.

Alternatively, if Windows-only is intentional for this release, document it in README.md and fail fast with a clear message on other platforms.

📍 Affects 2 files
  • src/commands/init.ts#L80-L88 (this comment)
  • src/utils/symlinks.ts#L45-L52
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/init.ts` around lines 80 - 88, Make the init flow
cross-platform: in src/commands/init.ts at lines 80-88, 170, 184-185, and
241-244, replace backslash-interpolated paths with path.join; in
src/utils/symlinks.ts at lines 45-52, only use the powershell.exe elevation
fallback on Windows and handle spawnSync error/status to report failure
appropriately.

Comment thread src/commands/init.ts
Comment on lines +153 to +159
case "files": {
for (const [path, val] of Object.entries(format.files)) {
remoteFiles[path] = typeof val === "string" ? val : "0.0.0";
}
current = "download";
break;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

files format discards structured versions.

extractVersion in src/utils/manifest.ts already handles both "1.2.3" and { version: "1.2.3" }; this branch collapses the object form to "0.0.0", so those files never register as needing an update.

🐛 Proposed fix
             for (const [path, val] of Object.entries(format.files)) {
-              remoteFiles[path] = typeof val === "string" ? val : "0.0.0";
+              remoteFiles[path] = extractVersion(val);
             }

Add extractVersion to the ../utils/manifest import.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case "files": {
for (const [path, val] of Object.entries(format.files)) {
remoteFiles[path] = typeof val === "string" ? val : "0.0.0";
}
current = "download";
break;
}
case "files": {
for (const [path, val] of Object.entries(format.files)) {
remoteFiles[path] = extractVersion(val);
}
current = "download";
break;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/init.ts` around lines 153 - 159, Update the “files” case in the
initialization flow to use the existing extractVersion helper when assigning
remoteFiles versions, and add extractVersion to the manifest utility import.
Preserve direct string versions while correctly extracting versions from
structured file entries instead of defaulting them to “0.0.0”.

Comment thread src/utils/download.ts
Comment on lines +4 to +8
export async function download(url: string, dest: string): Promise<boolean> {
const dir = dirname(dest);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

dest is derived from remote manifest keys without containment checks.

In src/commands/init.ts line 185 the destination is built from manifest-supplied paths; a key containing ../ would write outside targetDir (and mkdirSync here would happily create the parent). The manifest is repo-owned today, but a cheap guard makes this safe against a compromised/forked source.

🛡️ Suggested guard (in init.ts, before calling download)
const dest = resolve(targetDir, filePath);
if (!dest.startsWith(targetDir + sep)) { warn(`Skipping unsafe path: ${filePath}`); continue; }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/download.ts` around lines 4 - 8, Validate manifest-derived paths in
the init flow before calling download: resolve filePath against targetDir and
skip with a warning when the result is outside targetDir, including traversal
and sibling-prefix cases. Only pass validated destinations to download, leaving
download’s directory creation behavior unchanged.

Comment thread src/utils/symlinks.ts
Comment on lines +19 to +20
const srcPath = join(targetDir, cfg.relativeSrc);
const destPath = join(targetDir, cfg.relativeDest);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

relativeDest is resolved against the wrong base, pointing the link outside the project.

src/commands/init.ts line 241 passes relativeDest: "..\\.agents\\skills" — a path relative to .claude/, not to targetDir. Here it is joined with targetDir, producing <parent-of-targetDir>/.agents/skills. The link target is a sibling of the project directory, so it will never resolve to the real skills folder.

🐛 Proposed fix
   const srcPath = join(targetDir, cfg.relativeSrc);
-  const destPath = join(targetDir, cfg.relativeDest);
+  const destPath = resolve(dirname(srcPath), cfg.relativeDest);

Import resolve and dirname from path. Note the separators in relativeSrc/relativeDest also need to be POSIX-safe (see the src/commands/init.ts comment).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const srcPath = join(targetDir, cfg.relativeSrc);
const destPath = join(targetDir, cfg.relativeDest);
const srcPath = join(targetDir, cfg.relativeSrc);
const destPath = resolve(dirname(srcPath), cfg.relativeDest);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/symlinks.ts` around lines 19 - 20, Update the symlink path
construction around srcPath and destPath to resolve relativeDest from the
directory containing the destination link, using path resolve and dirname rather
than joining it directly to targetDir. Also ensure the relativeSrc and
relativeDest values passed by init remain POSIX-safe so the generated link
resolves to the project’s actual skills directory.

Comment thread src/utils/symlinks.ts
message: `Symlink failed for ${cfg.label}. Retry as admin?`,
initialValue: false,
});
if (isCancel(result)) cancel("Cancelled");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

@clack/prompts isCancel cancel symbol return value behavior

💡 Result:

In @clack/prompts, prompt functions (such as text, select, or multiselect) return a Promise that resolves to either the user's input (typically a string, array, or other data type) or a specific cancellation symbol when the user triggers a cancellation (e.g., by pressing CTRL + C) [1][2][3]. The isCancel function acts as a type guard to detect this cancellation symbol [4][3]. Its behavior and usage are summarized below: 1. Identification: When a user cancels a prompt, the function returns a unique internal symbol [1][2]. You use isCancel(value) to check if the returned value is this cancellation symbol [4][5]. 2. Usage: You should always handle the cancellation case after calling a prompt [4][6]. If isCancel returns true, the prompt has been cancelled [4][3]. import { isCancel, cancel, text } from '@clack/prompts'; const value = await text({ message: 'Enter your name' }); if (isCancel(value)) { cancel('Operation cancelled.'); process.exit(0); } 3. Symbol Export: Recent updates have exported the underlying symbol as CANCEL_SYMBOL and the corresponding type as CancelSymbol from @clack/prompts [2]. This allows for more precise type narrowing compared to the generic symbol type used previously [2][7]. If you are using TypeScript, utilizing the exported CancelSymbol type allows for better type safety when handling the prompt result [2][7].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg '(^|/)symlinks\.ts$|package\.json|pnpm-lock.yaml|yarn.lock|package-lock.json' || true

echo "== symlinks outline =="
file="$(git ls-files | rg '(^|/)symlinks\.ts$' | head -n1)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  ast-grep outline "$file" || true
  echo "== relevant symlinks.ts =="
  cat -n "$file" | sed -n '1,140p'
fi

echo "== package clack version =="
if [ -f package.json ]; then
  cat package.json | sed -n '1,220p'
fi
for f in pnpm-lock.yaml package-lock.json yarn.lock; do
  [ -f "$f" ] && { echo "== $f =="; rg -n '`@clack/prompts`|clack' "$f" | head -n 20 || true; }
done

echo "== search symlinks import/usages =="
rg -n "symlinks|createSymlink|run.*PowerShell|powerShell|Powershell|process\.exit|isCancel|cancel\\(" . --glob '!node_modules' --glob '!dist' --glob '!build' || true

Repository: yallma3/codewiser

Length of output: 5311


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg '(^|/)symlinks\.ts$|package\.json|pnpm-lock.yaml|yarn.lock|package-lock.json' || true

echo "== sympaths outline =="
file="$(git ls-files | rg '(^|/)symlinks\.ts$' | head -n1)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  ast-grep outline "$file" || true
  echo "== relevant symlinks.ts =="
  cat -n "$file" | sed -n '1,140p'
fi

echo "== package clack version =="
if [ -f package.json ]; then
  cat package.json | sed -n '1,220p'
fi
for f in pnpm-lock.yaml package-lock.json yarn.lock; do
  [ -f "$f" ] && { echo "== $f =="; rg -n '`@clack/prompts`|clack' "$f" | head -n 20 || true; }
done

echo "== search symlinks import/usages =="
rg -n "symlinks|createSymlink|run.*PowerShell|powerShell|Powershell|process\.exit|isCancel|cancel\\(" . --glob '!node_modules' --glob '!dist' --glob '!build' || true

Repository: yallma3/codewiser

Length of output: 5311


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== init callers of createAllSymlinks =="
cat -n src/commands/init.ts | sed -n '30,80p;220,260p'

echo "== Node truthiness probe for `@clack/prompts` cancel symbol behavior =="
node - <<'JS'
const CANCEL = Symbol.for('clack.cancel');
const result = CANCEL;
console.log(JSON.stringify({
  isCancelEquivalent: true,
  truthyValue: Boolean(result),
  truthyBranches: [result && "powershellBranch", (!result) || false],
  nextSymbol: result && Symbol("next") // demonstrates truthy result cannot be reinterpreted as final next truthy value without extra checks
}));
JS

Repository: yallma3/codewiser

Length of output: 3801


Handle prompt cancellation before continuing.

confirm() returns Clack’s internal cancel Symbol on cancellation, but this only calls cancel("Cancelled") and then falls through. Since the symbol is truthy, the retry branch still runs; skip the retry flow when the prompt is cancelled.

🐛 Proposed fix
-    if (isCancel(result)) cancel("Cancelled");
+    if (isCancel(result)) {
+      cancel("Cancelled");
+      process.exit(0);
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isCancel(result)) cancel("Cancelled");
if (isCancel(result)) {
cancel("Cancelled");
process.exit(0);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/symlinks.ts` at line 43, Update the cancellation handling around
confirm() and isCancel(result) so cancel("Cancelled") exits the current flow
immediately. Ensure the retry branch cannot run when the prompt returns Clack’s
cancellation Symbol, while preserving normal retry behavior for non-cancelled
results.

Comment thread src/utils/symlinks.ts
Comment on lines +45 to +52
if (result) {
const { spawnSync } = await import("child_process");
spawnSync("powershell.exe", [
"-NoProfile",
"-Command",
`New-Item -ItemType SymbolicLink -Path '${srcPath}' -Target '${destPath}' -Force`,
], { stdio: "inherit" });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

PowerShell fallback is unquoted-safe only by luck, and is Windows-only.

srcPath/destPath derive from the user-supplied target directory; a single quote in any path component terminates the PowerShell literal and lets the rest execute as commands. Also, powershell.exe does not exist on macOS/Linux, so this branch silently does nothing there (spawnSync error is unchecked).

🛡️ Proposed fix
     if (result) {
+      if (process.platform !== "win32") {
+        return;
+      }
       const { spawnSync } = await import("child_process");
-      spawnSync("powershell.exe", [
-        "-NoProfile",
-        "-Command",
-        `New-Item -ItemType SymbolicLink -Path '${srcPath}' -Target '${destPath}' -Force`,
-      ], { stdio: "inherit" });
+      const esc = (p: string) => p.replace(/'/g, "''");
+      const r = spawnSync("powershell.exe", [
+        "-NoProfile",
+        "-Command",
+        `New-Item -ItemType SymbolicLink -Path '${esc(srcPath)}' -Target '${esc(destPath)}' -Force`,
+      ], { stdio: "inherit" });
+      if (r.error) warn(`Elevated symlink attempt failed: ${r.error.message}`);
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (result) {
const { spawnSync } = await import("child_process");
spawnSync("powershell.exe", [
"-NoProfile",
"-Command",
`New-Item -ItemType SymbolicLink -Path '${srcPath}' -Target '${destPath}' -Force`,
], { stdio: "inherit" });
}
if (result) {
if (process.platform !== "win32") {
return;
}
const { spawnSync } = await import("child_process");
const esc = (p: string) => p.replace(/'/g, "''");
const r = spawnSync("powershell.exe", [
"-NoProfile",
"-Command",
`New-Item -ItemType SymbolicLink -Path '${esc(srcPath)}' -Target '${esc(destPath)}' -Force`,
], { stdio: "inherit" });
if (r.error) warn(`Elevated symlink attempt failed: ${r.error.message}`);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/symlinks.ts` around lines 45 - 52, Update the symbolic-link
fallback around spawnSync to avoid interpolating srcPath and destPath into a
PowerShell command; pass them as safely escaped or parameterized arguments
instead. Restrict this PowerShell fallback to Windows, and validate spawnSync’s
result so nonzero exits or execution errors are surfaced rather than silently
ignored.

Comment thread src/utils/symlinks.ts
Comment on lines +60 to +74
function copyDirContents(src: string, dest: string): void {
if (!existsSync(src)) return;
mkdirSync(dest, { recursive: true });
const entries = readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const s = join(src, entry.name);
const d = join(dest, entry.name);
if (entry.isDirectory()) {
copyDirContents(s, d);
} else {
const content = Bun.file(s);
Bun.write(d, content);
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Bun.write is not awaited — copies can be incomplete or silently fail.

copyDirContents is synchronous but fires off unawaited promises; the caller at line 29 then rmSyncs the source directory, which can race with in-flight writes and lose data. Any rejection is also unhandled.

🐛 Proposed fix
-function copyDirContents(src: string, dest: string): void {
+async function copyDirContents(src: string, dest: string): Promise<void> {
   if (!existsSync(src)) return;
   mkdirSync(dest, { recursive: true });
   const entries = readdirSync(src, { withFileTypes: true });
   for (const entry of entries) {
     const s = join(src, entry.name);
     const d = join(dest, entry.name);
     if (entry.isDirectory()) {
-      copyDirContents(s, d);
+      await copyDirContents(s, d);
     } else {
-      const content = Bun.file(s);
-      Bun.write(d, content);
+      await Bun.write(d, Bun.file(s));
     }
   }
 }

Callers at lines 28 and 55 must await.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/symlinks.ts` around lines 60 - 74, Make copyDirContents
asynchronous and await each Bun.write operation so file copies complete and
failures propagate. Update every caller, including the flows around lines 28 and
55, to await copyDirContents before removing or otherwise using the source
directory.

@coderabbitai coderabbitai Bot mentioned this pull request Jul 28, 2026
@mostafamm44 mostafamm44 closed this Aug 2, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Aug 2, 2026
This was referenced Aug 13, 2026
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.

1 participant