Skip to content
This repository was archived by the owner on Nov 8, 2026. It is now read-only.

Add CodePair developer setup CLI - #607

Closed
taejs wants to merge 1 commit into
yorkie-team:mainfrom
taejs:feature/codepair-cli
Closed

taejs wants to merge 1 commit into
yorkie-team:mainfrom
taejs:feature/codepair-cli

Conversation

@taejs

@taejs taejs commented Jul 15, 2026 •

Copy link
Copy Markdown

What this PR does / why we need it:

This PR adds a typed, repository-local CLI for setting up and diagnosing a CodePair development environment.

The primary contributor workflows are:

pnpm cli setup yorkie --yes
pnpm cli doctor

setup yorkie creates or reuses the selected Yorkie project, configures the DocumentRootChanged webhook, writes the Yorkie addresses and project keys to the development environment files, and verifies the resulting state. Missing environment files are seeded from checked-in examples. Re-running the command is idempotent.

doctor provides read-only checks for the supported toolchain, environment configuration, local services, and Yorkie project state. Both commands support structured JSON output and stable exit codes for automation.

The previous webhook script was difficult to extend safely because setup, process execution, environment-file mutation, and output handling were coupled in one untyped file. The new package separates argument parsing, process execution, Yorkie access, environment-file handling, diagnostics, networking, prompting, and output formatting into focused modules.

The CLI is intentionally:

  • Private and repository-scoped; it is not an npm release or a production deployment tool.
  • Dependency-free at runtime.
  • Limited to contributor setup and diagnostics.
  • Independent of the NestJS and frontend application lifecycles.

Compatibility and application boundaries:

  • pnpm setup:webhook remains available and delegates to the new implementation.
  • The compatibility path preserves its existing localhost RPC and webhook defaults, plaintext-remote behavior, and keys-only environment-file updates.
  • The modern setup path updates only YORKIE_API_ADDR, YORKIE_PROJECT_SECRET_KEY, VITE_YORKIE_API_ADDR, and VITE_YORKIE_API_KEY. Existing comments, OAuth credentials, JWT settings, AI provider settings, storage configuration, and other values are preserved.
  • No backend, frontend, CodeMirror, or UI runtime source files are changed.
  • The only Compose behavior change is an additive host.docker.internal host-gateway mapping for local development, allowing the Yorkie container to reach the host backend.
  • Frontend-only mode and docker-compose-full.yml are unchanged.

Which issue(s) this PR fixes:

NONE

Special notes for your reviewer:

Security and failure handling:

  • External commands receive explicit argument arrays without interpolating user input into a shell command.
  • Plaintext Yorkie login to a non-loopback address is rejected unless the caller explicitly opts in; TLS is supported through --secure.
  • Non-interactive mutations require --yes, and --dry-run validates prerequisites and reports the plan without changing state.
  • Passwords and known secret fields are redacted from human-readable and JSON diagnostics.
  • Webhook URLs containing embedded credentials are rejected.
  • Environment files are replaced atomically and use owner-only permissions where supported.
  • Setup verifies Yorkie and local file postconditions before reporting success.

Yorkie currently accepts its password through yorkie login -p. --password-stdin keeps the password out of the CodePair command line, but the child Yorkie process may expose it briefly to same-host process inspection. This is documented, and setup should only be run on a trusted development machine.

Validation completed:

  • pnpm --filter=@codepair/cli verify
    • Formatting, linting, and type checking passed.
    • 18 unit tests passed.
    • 35 deterministic end-to-end tests passed.
    • The E2E suite packs the package from a clean build, installs the tarball into a temporary prefix, executes the installed codepair binary, validates package contents, and confirms internal deep imports are blocked.
  • Pinned real-Yorkie integration: 1 test passed, covering project setup, webhook configuration, an idempotent second run, and doctor verification from the written environment files.
  • Backend and frontend formatting and builds passed.
  • Frontend lint completed with no errors and one pre-existing Fast Refresh warning.
  • CodeMirror and UI type checks passed.
  • Both backend Docker Compose configurations passed docker compose config.

The real-Yorkie test validates the control-plane workflow. It does not start the complete CodePair application or assert delivery of an actual document-change webhook through the backend.

The dedicated CLI workflow covers Ubuntu/Node.js 22, macOS/Node.js 20, and Windows/Node.js 24. This covers every supported operating system and Node.js major without a nine-job Cartesian matrix. The Linux job additionally verifies both Compose files and runs against a checksum-verified Yorkie CLI archive and digest-pinned Yorkie server image.

Does this PR introduce a user-facing change?:

Added a private contributor CLI for configuring and diagnosing CodePair's local Yorkie development environment.

Additional documentation:

- [Getting started]: README.md#command-line-interface
- [CLI usage and automation contract]: packages/cli/README.md
- [Design]: docs/design/cli.md

Checklist:

  • Added relevant tests or not required
  • Didn't break anything

🤖 Generated with OpenAI Codex.

Summary by CodeRabbit

  • New Features

    • Added the CodePair command-line interface with Yorkie setup and diagnostic commands.
    • Added machine-readable JSON output, safety checks, environment configuration, and secure secret handling.
    • Added local development environment templates and a CLI development command.
    • Added automated cross-platform validation for formatting, linting, tests, packaging, and integrations.
  • Documentation

    • Documented CLI installation, commands, options, setup behavior, diagnostics, and design details.
    • Updated development and release instructions.
  • Bug Fixes

    • Preserved the existing webhook setup command through a compatibility wrapper.
    • Improved local Docker connectivity and environment-file updates.

Replace the webhook setup script with a typed workspace CLI.

Preserve the legacy entry point for existing automation.

Add deterministic black-box and package-installation coverage.

Test the control-plane flow against a pinned Yorkie release.

Generated with OpenAI Codex.
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds the @codepair/cli package with setup yorkie and doctor commands, shared environment and security utilities, Yorkie integration, comprehensive tests, repository documentation, legacy-script delegation, and cross-platform CI coverage.

Changes

CodePair CLI

Layer / File(s) Summary
CLI contracts and core utilities
packages/cli/src/types.ts, packages/cli/src/core/*, packages/cli/src/adapters/*
Defines typed results, errors, argument parsing, command execution, environment-file handling, URL validation, redaction, networking, and Yorkie command adapters.
Yorkie setup workflow
packages/cli/src/commands/setup-yorkie.ts, scripts/setup-yorkie-webhook.js, packages/*/.env.example
Implements Yorkie project/webhook setup, environment seeding and atomic updates, verification, dry-run and transport controls, while converting the legacy script into a CLI wrapper.
Doctor diagnostics
packages/cli/src/commands/doctor.ts, packages/cli/src/checks/*
Adds scoped environment, service, toolchain, and Yorkie checks with structured summaries and strict-mode exit behavior.
CLI dispatch and packaging
packages/cli/src/{cli,main,help}.ts, packages/cli/package.json, package.json
Adds the executable entrypoint, help/version and result output handling, package metadata, and the root development command.
Validation and repository integration
packages/cli/test/*, .github/workflows/ci_cli.yaml, .husky/pre-commit, README.md, docs/design/*
Adds unit, end-to-end, packaging, and real-Yorkie integration tests, cross-platform CI, CLI pre-commit linting, documentation, and maintenance updates.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested reviewers: hackerwins

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant CodePairCLI
  participant YorkieCLI
  participant EnvFiles
  User->>CodePairCLI: setup yorkie
  CodePairCLI->>YorkieCLI: login and inspect project
  YorkieCLI-->>CodePairCLI: project and webhook state
  CodePairCLI->>YorkieCLI: create or update project webhook
  CodePairCLI->>EnvFiles: atomically write Yorkie values
  EnvFiles-->>CodePairCLI: persisted configuration
  CodePairCLI-->>User: structured setup result
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately describes the main change: adding a CodePair developer setup CLI.
✨ 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 (1)
packages/cli/LICENSE (1)

189-189: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Update the copyright placeholders.

The boilerplate text in the appendix still contains the [yyyy] and [name of copyright owner] placeholders. Consider replacing these with the actual copyright details or removing the appendix if it's unnecessary.

📝 Proposed fix to update the copyright
-   Copyright [yyyy] [name of copyright owner]
+   Copyright 2026 CodePair Authors
🤖 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 `@packages/cli/LICENSE` at line 189, Update the copyright notice in the LICENSE
appendix by replacing the [yyyy] and [name of copyright owner] placeholders with
the project’s actual copyright year and owner, or remove the unnecessary
appendix section entirely.
🤖 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 @.github/workflows/ci_cli.yaml:
- Around line 51-52: Update the `actions/checkout@v4` step in the workflow to
set `persist-credentials` to false, while leaving the existing checkout behavior
unchanged.

In `@packages/cli/src/adapters/yorkie-cli.ts`:
- Around line 38-43: Update unwrapProjectRecords to reject the entire array when
any entry is not a non-null, non-array object, rather than filtering invalid
entries out; preserve the valid-array conversion and fail-closed behavior for
malformed responses. Add a regression test covering a mixed valid/invalid array
and verifying it is rejected without allowing project creation to proceed.

In `@packages/cli/src/checks/yorkie.ts`:
- Around line 127-139: Update the error handling around cli.listProjects() so
INVALID_YORKIE_PROJECT_JSON and INVALID_YORKIE_PROJECT_OUTPUT are reported as
incompatible Yorkie CLI/server output rather than connection failures. Preserve
the existing connection/login failure response for other errors, and provide
remediation directing users to check Yorkie CLI/server compatibility.

In `@packages/cli/src/core/env-file.ts`:
- Around line 14-27: Update decodeEnvValue to recognize and decode quoted values
before trailing inline comments, so inputs such as FOO="bar" # comment return
bar without surrounding quotes. Preserve the existing handling for single-quoted
and unquoted values, and ensure comments are ignored only after the quoted value
is extracted.

In `@packages/cli/src/core/output.ts`:
- Around line 19-25: Update writeResult so redactValue(result, secrets) is
computed and used before both the JSON and human-readable output branches.
Ensure doctor messages, setup actions, remediation text, and errors are rendered
from the redacted result while preserving the existing formatting behavior.

In `@packages/cli/src/core/redact.ts`:
- Around line 61-76: Update redactValueInternal’s traversal tracking so seen
only contains the current ancestor chain: after recursively processing an array
or object branch, remove the current value from seen before returning. Preserve
"[Circular]" for objects encountered while already in the active ancestor path,
while allowing repeated shared references in separate branches to be processed
normally.

In `@packages/cli/src/main.ts`:
- Around line 26-31: Keep the fallback error command label initialized to the
default command and do not derive it from raw argv or unparsed options when
extractGlobalOptions fails. Only update the command after successful global
parsing using recognized command tokens, preserving the default label for inputs
such as --json --root.
- Around line 33-50: Update the early version and help response branches in the
CLI entry flow to honor parsed.options.json. When --json is present, emit
exactly one valid structured JSON document for packageVersion(), helpFor(), or
MAIN_HELP; otherwise preserve the existing plain-text output. Ensure all
relevant branches—version, positional help, option help, and empty
arguments—follow this behavior.

In `@packages/cli/test/e2e/fixtures/fake-tool-bootstrap.cjs`:
- Around line 144-146: Update the event handling near
project.event_webhook_events so --event-webhook-events-add preserves existing
subscriptions and appends the requested event rather than replacing the list.
Ensure the event is added only once, while retaining the current empty-list
behavior when no event is provided.

In `@README.md`:
- Around line 34-37: Update the “Node.js Version Support” section to list only
the supported major versions, removing the “LTS,” “Active LTS,” and “Current”
lifecycle parentheticals while preserving the supported and dropped version
entries.

In `@scripts/setup-yorkie-webhook.js`:
- Around line 14-25: The legacy webhook wrapper must not unconditionally enable
insecure remote authentication. In scripts/setup-yorkie-webhook.js lines 14-25,
remove --allow-insecure-remote from the default delegation and require an
explicit user-controlled opt-in instead; in
packages/cli/test/e2e/package.test.mjs lines 25-64, update the successful legacy
delegation to use loopback and add coverage verifying non-loopback plaintext
login is refused.

---

Nitpick comments:
In `@packages/cli/LICENSE`:
- Line 189: Update the copyright notice in the LICENSE appendix by replacing the
[yyyy] and [name of copyright owner] placeholders with the project’s actual
copyright year and owner, or remove the unnecessary appendix section entirely.
🪄 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

Run ID: 7a278cd3-e0af-4c73-9e2e-2fbdf5eaa2d3

📥 Commits

Reviewing files that changed from the base of the PR and between dded7f6 and 4897c9b.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (52)
  • .github/workflows/ci_cli.yaml
  • .husky/pre-commit
  • MAINTAINING.md
  • README.md
  • docs/design/README.md
  • docs/design/cli.md
  • package.json
  • packages/backend/.env.example
  • packages/backend/docker/docker-compose.yml
  • packages/cli/.prettierignore
  • packages/cli/.prettierrc
  • packages/cli/LICENSE
  • packages/cli/README.md
  • packages/cli/eslint.config.mjs
  • packages/cli/package.json
  • packages/cli/src/adapters/network.ts
  • packages/cli/src/adapters/yorkie-cli.ts
  • packages/cli/src/checks/context.ts
  • packages/cli/src/checks/env.ts
  • packages/cli/src/checks/services.ts
  • packages/cli/src/checks/toolchain.ts
  • packages/cli/src/checks/yorkie.ts
  • packages/cli/src/cli.ts
  • packages/cli/src/commands/doctor.ts
  • packages/cli/src/commands/setup-yorkie.ts
  • packages/cli/src/core/args.ts
  • packages/cli/src/core/env-file.ts
  • packages/cli/src/core/errors.ts
  • packages/cli/src/core/output.ts
  • packages/cli/src/core/process.ts
  • packages/cli/src/core/project-root.ts
  • packages/cli/src/core/prompt.ts
  • packages/cli/src/core/redact.ts
  • packages/cli/src/core/url.ts
  • packages/cli/src/help.ts
  • packages/cli/src/main.ts
  • packages/cli/src/types.ts
  • packages/cli/test/e2e/cli.test.mjs
  • packages/cli/test/e2e/fixtures/fake-tool-bootstrap.cjs
  • packages/cli/test/e2e/helpers/cli-harness.mjs
  • packages/cli/test/e2e/package.test.mjs
  • packages/cli/test/e2e/setup.test.mjs
  • packages/cli/test/helpers/environment.mjs
  • packages/cli/test/integration/yorkie.test.mjs
  • packages/cli/test/unit/env-file.test.mjs
  • packages/cli/test/unit/options.test.mjs
  • packages/cli/test/unit/process-services.test.mjs
  • packages/cli/test/unit/url-redact.test.mjs
  • packages/cli/test/unit/yorkie-cli.test.mjs
  • packages/cli/tsconfig.json
  • packages/frontend/.env.example
  • scripts/setup-yorkie-webhook.js

Comment on lines +51 to +52
- name: Checkout 🛎️
uses: actions/checkout@v4

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 | 🟡 Minor | ⚡ Quick win

Disable credential persistence in the checkout action.

By default, the actions/checkout action persists the GitHub token in the local git configuration. Because this workflow only runs tests and builds—and does not push commits back to the repository—setting persist-credentials: false improves the pipeline's security posture by preventing potential credential leakage in the event of compromised dependencies or downstream command injection.

🔒️ Proposed fix to disable credential persistence
       - name: Checkout 🛎️
         uses: actions/checkout@v4
+        with:
+          persist-credentials: false
📝 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
- name: Checkout 🛎️
uses: actions/checkout@v4
- name: Checkout 🛎️
uses: actions/checkout@v4
with:
persist-credentials: false
🧰 Tools
🪛 zizmor (1.26.1)

[warning] 51-52: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)

🤖 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 @.github/workflows/ci_cli.yaml around lines 51 - 52, Update the
`actions/checkout@v4` step in the workflow to set `persist-credentials` to
false, while leaving the existing checkout behavior unchanged.

Source: Linters/SAST tools

Comment on lines +38 to +43
function unwrapProjectRecords(value: unknown): Record<string, unknown>[] {
if (Array.isArray(value)) {
return value.filter(
(entry): entry is Record<string, unknown> =>
typeof entry === "object" && entry !== null && !Array.isArray(entry)
);

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 | 🟠 Major | ⚡ Quick win

Reject malformed project entries instead of silently dropping them.

A partially malformed Yorkie response becomes an incomplete valid list. Setup may then treat an existing project as absent and issue a mutating project create command. Validate every array entry and fail closed; add a mixed valid/invalid-array regression test.

Proposed fix
 	if (Array.isArray(value)) {
-		return value.filter(
-			(entry): entry is Record<string, unknown> =>
-				typeof entry === "object" && entry !== null && !Array.isArray(entry)
-		);
+		const records: Record<string, unknown>[] = [];
+		for (const entry of value) {
+			if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
+				throw new OperationalError(
+					"Yorkie project list contains an invalid project entry.",
+					"INVALID_YORKIE_PROJECT_OUTPUT"
+				);
+			}
+			records.push(entry as Record<string, unknown>);
+		}
+		return records;
 	}
📝 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
function unwrapProjectRecords(value: unknown): Record<string, unknown>[] {
if (Array.isArray(value)) {
return value.filter(
(entry): entry is Record<string, unknown> =>
typeof entry === "object" && entry !== null && !Array.isArray(entry)
);
function unwrapProjectRecords(value: unknown): Record<string, unknown>[] {
if (Array.isArray(value)) {
const records: Record<string, unknown>[] = [];
for (const entry of value) {
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
throw new OperationalError(
"Yorkie project list contains an invalid project entry.",
"INVALID_YORKIE_PROJECT_OUTPUT"
);
}
records.push(entry as Record<string, unknown>);
}
return records;
}
🤖 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 `@packages/cli/src/adapters/yorkie-cli.ts` around lines 38 - 43, Update
unwrapProjectRecords to reject the entire array when any entry is not a
non-null, non-array object, rather than filtering invalid entries out; preserve
the valid-array conversion and fail-closed behavior for malformed responses. Add
a regression test covering a mixed valid/invalid array and verifying it is
rejected without allowing project creation to proceed.

Comment on lines +127 to +139
let projects;
try {
projects = await cli.listProjects();
} catch {
return [
{
id: "yorkie.connection",
scope: "yorkie",
status: "fail",
message: `Could not list Yorkie projects at ${endpoint.rpcAddress}.`,
remediation: "Run codepair setup yorkie or log in with Yorkie CLI.",
},
];

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 | 🟡 Minor | ⚡ Quick win

Preserve incompatible-output failures instead of reporting them as connection errors.

listProjects() can throw INVALID_YORKIE_PROJECT_JSON or INVALID_YORKIE_PROJECT_OUTPUT, but this catch reports both as connectivity/login failures. Distinguish parser errors and recommend checking Yorkie CLI/server compatibility.

🤖 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 `@packages/cli/src/checks/yorkie.ts` around lines 127 - 139, Update the error
handling around cli.listProjects() so INVALID_YORKIE_PROJECT_JSON and
INVALID_YORKIE_PROJECT_OUTPUT are reported as incompatible Yorkie CLI/server
output rather than connection failures. Preserve the existing connection/login
failure response for other errors, and provide remediation directing users to
check Yorkie CLI/server compatibility.

Comment on lines +14 to +27
function decodeEnvValue(raw: string): string {
const trimmed = raw.trim();
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
try {
return JSON.parse(trimmed) as string;
} catch {
return trimmed.slice(1, -1);
}
}
if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
return trimmed.slice(1, -1);
}
return trimmed.replace(/\s+#.*$/, "").trim();
}

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 | 🟡 Minor | ⚡ Quick win

Handle trailing comments on quoted values.

The decodeEnvValue function incorrectly retains the surrounding quotes if a quoted value includes a trailing inline comment (e.g., FOO="bar" # comment). Because the trimmed string ends with # comment rather than ", the endsWith('"') check fails, causing it to fall through to the bare-value handler which returns the literal string "bar".

Consider using a regular expression to cleanly extract the quoted section independently of any trailing comments.

🐛 Proposed fix to handle quotes and comments correctly
 function decodeEnvValue(raw: string): string {
 	const trimmed = raw.trim();
-	if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
+
+	const doubleQuoteMatch = trimmed.match(/^"((?:[^"\\]|\\.)*)"(?:\s+#.*)?$/);
+	if (doubleQuoteMatch) {
 		try {
-			return JSON.parse(trimmed) as string;
+			return JSON.parse(`"${doubleQuoteMatch[1]}"`) as string;
 		} catch {
-			return trimmed.slice(1, -1);
+			return doubleQuoteMatch[1];
 		}
 	}
-	if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
-		return trimmed.slice(1, -1);
+
+	const singleQuoteMatch = trimmed.match(/^'([^']*)'(?:\s+#.*)?$/);
+	if (singleQuoteMatch) {
+		return singleQuoteMatch[1];
 	}
+
 	return trimmed.replace(/\s+#.*$/, "").trim();
 }
📝 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
function decodeEnvValue(raw: string): string {
const trimmed = raw.trim();
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
try {
return JSON.parse(trimmed) as string;
} catch {
return trimmed.slice(1, -1);
}
}
if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
return trimmed.slice(1, -1);
}
return trimmed.replace(/\s+#.*$/, "").trim();
}
function decodeEnvValue(raw: string): string {
const trimmed = raw.trim();
const doubleQuoteMatch = trimmed.match(/^"((?:[^"\\]|\\.)*)"(?:\s+#.*)?$/);
if (doubleQuoteMatch) {
try {
return JSON.parse(`"${doubleQuoteMatch[1]}"`) as string;
} catch {
return doubleQuoteMatch[1];
}
}
const singleQuoteMatch = trimmed.match(/^'([^']*)'(?:\s+#.*)?$/);
if (singleQuoteMatch) {
return singleQuoteMatch[1];
}
return trimmed.replace(/\s+#.*$/, "").trim();
}
🤖 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 `@packages/cli/src/core/env-file.ts` around lines 14 - 27, Update
decodeEnvValue to recognize and decode quoted values before trailing inline
comments, so inputs such as FOO="bar" # comment return bar without surrounding
quotes. Preserve the existing handling for single-quoted and unquoted values,
and ensure comments are ignored only after the quoted value is extracted.

Comment on lines +19 to +25
export function writeResult(
result: ResultEnvelope,
json: boolean,
secrets: Iterable<string> = []
): void {
if (json) {
process.stdout.write(`${JSON.stringify(redactValue(result, secrets), null, 2)}\n`);

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

Apply redaction to human-readable output too.

secrets is only used by the JSON branch. Doctor messages, setup actions, remediation text, and errors can therefore print a supplied secret verbatim in normal mode. Redact the result before either output path.

Also applies to: 29-56

🤖 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 `@packages/cli/src/core/output.ts` around lines 19 - 25, Update writeResult so
redactValue(result, secrets) is computed and used before both the JSON and
human-readable output branches. Ensure doctor messages, setup actions,
remediation text, and errors are rendered from the redacted result while
preserving the existing formatting behavior.

Comment thread packages/cli/src/main.ts
Comment on lines +26 to +31
let json = argv.includes("--json");
let remaining: string[] = [...argv];
try {
const parsed = extractGlobalOptions(argv);
json = parsed.options.json;
remaining = parsed.remaining;

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 | 🟡 Minor | ⚡ Quick win

Do not derive the error command from unparsed options.

When global parsing fails, remaining still contains raw arguments. For example, --json --root produces an error envelope whose command is "--json" rather than "codepair". Keep the fallback label until parsing succeeds or derive it from recognized command tokens.

Also applies to: 74-83

🤖 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 `@packages/cli/src/main.ts` around lines 26 - 31, Keep the fallback error
command label initialized to the default command and do not derive it from raw
argv or unparsed options when extractGlobalOptions fails. Only update the
command after successful global parsing using recognized command tokens,
preserving the default label for inputs such as --json --root.

Comment thread packages/cli/src/main.ts
Comment on lines +33 to +50
if (parsed.options.version || remaining[0] === "version") {
process.stdout.write(`${await packageVersion()}\n`);
return 0;
}

if (remaining[0] === "help") {
process.stdout.write(helpFor(remaining.slice(1)));
return 0;
}

if (parsed.options.help) {
process.stdout.write(helpFor(remaining));
return 0;
}

if (remaining.length === 0) {
process.stdout.write(MAIN_HELP);
return 0;

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

Honor --json for help and version responses.

These early branches emit plain text even when --json is present, violating the documented “one structured JSON document” contract and breaking automation expecting valid JSON.

🤖 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 `@packages/cli/src/main.ts` around lines 33 - 50, Update the early version and
help response branches in the CLI entry flow to honor parsed.options.json. When
--json is present, emit exactly one valid structured JSON document for
packageVersion(), helpFor(), or MAIN_HELP; otherwise preserve the existing
plain-text output. Ensure all relevant branches—version, positional help, option
help, and empty arguments—follow this behavior.

Comment on lines +144 to +146
project.event_webhook_url = flagValue(args, "--event-webhook-url") || "";
const event = flagValue(args, "--event-webhook-events-add");
project.event_webhook_events = event ? [event] : [];

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

rg -n -C4 -- \
  '--event-webhook-events-add|event_webhook_events' \
  packages/cli/src packages/cli/test

Repository: yorkie-team/codepair

Length of output: 5711


🏁 Script executed:

#!/bin/bash
set -eu

# Inspect the relevant fixture and the tests that depend on its webhook behavior.
sed -n '1,260p' packages/cli/test/e2e/fixtures/fake-tool-bootstrap.cjs
printf '\n--- setup.test.mjs ---\n'
sed -n '1,180p' packages/cli/test/e2e/setup.test.mjs
printf '\n--- cli-harness.mjs ---\n'
sed -n '150,230p' packages/cli/test/e2e/helpers/cli-harness.mjs
printf '\n--- yorkie-cli.ts excerpt ---\n'
sed -n '110,170p' packages/cli/src/adapters/yorkie-cli.ts

Repository: yorkie-team/codepair

Length of output: 15872


🏁 Script executed:

#!/bin/bash
set -eu

# Find the setup flow that decides when webhook configuration runs.
rg -n -C4 -- 'configureEventWebhook|event_webhook_events|event-webhook-events-add|yorkie\.webhook|webhook' packages/cli/src packages/cli/test

Repository: yorkie-team/codepair

Length of output: 41660


🌐 Web query:

Yorkie CLI project update --event-webhook-events-add additive preserve existing webhook events

💡 Result:

Yes, the --event-webhook-events-add flag in the Yorkie CLI is designed to be additive, meaning it preserves existing webhook events while adding new ones to the configuration [1][2]. When you run the yorkie project update command with the --event-webhook-events-add flag, the specified events are appended to the project's current list of active webhook events [3][1]. Similarly, the CLI provides a corresponding --event-webhook-events-rm flag if you need to explicitly remove specific events from the configuration [1][2]. For example, to add an event to an existing configuration without affecting the ones already set, you can use: yorkie project update [project-name] --event-webhook-events-add "DocumentRootChanged" This behavior is consistent across similar CLI operations in Yorkie, such as managing authentication webhook methods with the --auth-webhook-method-add and --auth-webhook-method-rm flags [1].

Citations:


Model --event-webhook-events-add as additive. packages/cli/test/e2e/fixtures/fake-tool-bootstrap.cjs:144-146 currently overwrites event_webhook_events with a single item, which drops any preexisting subscriptions. Preserve the existing list and append the requested event once so the fixture matches Yorkie’s behavior.

🤖 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 `@packages/cli/test/e2e/fixtures/fake-tool-bootstrap.cjs` around lines 144 -
146, Update the event handling near project.event_webhook_events so
--event-webhook-events-add preserves existing subscriptions and appends the
requested event rather than replacing the list. Ensure the event is added only
once, while retaining the current empty-list behavior when no event is provided.

Comment thread README.md
Comment on lines 34 to 37
## Node.js Version Support

- **Supported:** **20.x (LTS)**, **22.x (Active LTS)**, **24.x (Current)**
- **Dropped:** **18.x** (End-of-life)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
jq '.engines.node // empty' package.json packages/cli/package.json

Repository: yorkie-team/codepair

Length of output: 178


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\nREADME excerpt:\n'
sed -n '30,42p' README.md

printf '\nPackage engine constraints:\n'
jq -r '.engines.node // empty' package.json packages/cli/package.json

Repository: yorkie-team/codepair

Length of output: 795


Remove the Node.js lifecycle labels
The supported majors already match the package engine range, but the (LTS)/(Active LTS)/(Current) parentheticals are time-sensitive and will drift; list the supported versions without lifecycle labels instead.

🤖 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 34 - 37, Update the “Node.js Version Support” section
to list only the supported major versions, removing the “LTS,” “Active LTS,” and
“Current” lifecycle parentheticals while preserving the supported and dropped
version entries.

Comment on lines +14 to +25
const cliArguments = [
"cli",
"setup",
"yorkie",
"--yes",
"--allow-insecure-remote",
];
const command =
process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "pnpm";
const commandArguments =
process.platform === "win32"
? ["/d", "/s", "/c", "pnpm cli setup yorkie --yes --allow-insecure-remote"]

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

The legacy compatibility path bypasses remote transport safety. The wrapper silently opts into insecure remote authentication, and its E2E test makes that behavior mandatory.

  • scripts/setup-yorkie-webhook.js#L14-L25: remove unconditional --allow-insecure-remote; require an explicit user-controlled opt-in.
  • packages/cli/test/e2e/package.test.mjs#L25-L64: use loopback for successful legacy delegation and test that non-loopback plaintext login is refused.
📍 Affects 2 files
  • scripts/setup-yorkie-webhook.js#L14-L25 (this comment)
  • packages/cli/test/e2e/package.test.mjs#L25-L64
🤖 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 `@scripts/setup-yorkie-webhook.js` around lines 14 - 25, The legacy webhook
wrapper must not unconditionally enable insecure remote authentication. In
scripts/setup-yorkie-webhook.js lines 14-25, remove --allow-insecure-remote from
the default delegation and require an explicit user-controlled opt-in instead;
in packages/cli/test/e2e/package.test.mjs lines 25-64, update the successful
legacy delegation to use loopback and add coverage verifying non-loopback
plaintext login is refused.

@taejs taejs changed the title Add CodePair setup and diagnostics CLI Add CodePair developer setup CLI Jul 15, 2026
@taejs

taejs commented Jul 15, 2026

Copy link
Copy Markdown
Author

Closing this in favor of a product-facing CLI that operates through CodePair's application API. The current contributor setup CLI does not match the intended user workflow.

@taejs taejs closed this Jul 15, 2026
@github-project-automation github-project-automation Bot moved this to Done in CodePair Jul 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants