Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

- **fix(cli): 规范语言默认跟随系统语言**. 未安装规范时优先读操作系统语言(macOS `AppleLanguages`/`AppleLocale`,Windows `PreferredUILanguages`/`LocaleName`),再回退终端 locale;`update` 自更新后的重执行保留 `--lang`;旧版无锚点中文块按 `## 0. 适用范围` / `## 一、代码质量` 两种旧标题兜底识别,不再被翻成英文。
- `src/shared/standards-language.ts`、`src/commands/update.ts`、`src/index.ts`、`tests/shared/standards-language.test.ts`、`tests/update.test.ts`、`README.md`、`README.zh-CN.md`、`CHANGELOG.md`

## [0.3.120] - 2026-11-18
- **docs(standards): 压缩规范到 200 行目标内**. 中文版 213→187 行、英文版 194→171 行:删掉与 §1 重复的「修复预算」条款,成组子条目并入主条;§7 的 DO「先确认数据量级」经删条款对照实验确认与同节 🔴 无界读取条重复后删除;§1 的临时方案条款压成一句,并把「升级触发条件」并入同节 `debt:` 规则——盲评 A/B 显示删整行会失去「先跑通最小端到端」(PASS 2/6→0/6),故保留该句。新增 `tests/standards-length.test.ts` 把 SSOT 锁在 190 行内,安装进 `AGENTS.md` 后中英分别 190/174 行,不再触发 Claude Code 的启动超长警告。
- `standards/employee-standards.md`、`standards/employee-standards.en.md`、`docs/script.js`、`tests/{docs-sync,standards-length}.test.ts`、`CHANGELOG.md`
Expand Down
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,12 @@ for them.

**Standards language.** The employee-standards block in `AGENTS.md` is
written in Chinese or English. `init --lang zh|en` selects it explicitly;
without the flag, an installed block's language wins, then the system locale
(`LANGUAGE` > `LC_ALL` > `LC_MESSAGES` > `LANG`), then English. `update --lang`
switches an installed block; without a block the flag has no effect. Only the
locale is read — the region is never detected.
without the flag, an installed block's language wins, then the operating
system's language (macOS `AppleLanguages`/`AppleLocale`, Windows
`PreferredUILanguages`/`LocaleName`), then the terminal locale (`LANGUAGE` >
`LC_ALL` > `LC_MESSAGES` > `LANG`), then English. `update --lang` switches an
installed block; without a block the flag has no effect. Neither IP nor region
is detected.

Init prints two output signals: the pre-select hint line (only when
`--tools` is not given) — `Configured (pre-select):` on projects with
Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ openspec-pw init --tools none # 不配置编辑器,只生成脚手

init 打印两种输出信号:预选提示行(仅未传 `--tools` 时出现)——有 openspec-pw 状态的项目是 `Configured (pre-select):`,首次运行回退则是 `Detected (pre-select):`——**不是**实际安装集;`Selected editors:` 行(总是打印,位于任何编辑器配置之前)才是实际安装集。判断装了什么,看 `Selected editors`。

**规范语言。** `AGENTS.md` 里的员工级规范块以中文或英文写入。`init --lang zh|en` 显式选择;未传时优先沿用已安装块的语言,其次看系统 locale(`LANGUAGE` > `LC_ALL` > `LC_MESSAGES` > `LANG`),最后回退英文。`update --lang` 切换已安装块的语言;没有规范块时该参数不生效。只读取 locale,不判断所在地区。
**规范语言。** `AGENTS.md` 里的员工级规范块以中文或英文写入。`init --lang zh|en` 显式选择;未传时优先沿用已安装块的语言,其次看操作系统语言(macOS `AppleLanguages`/`AppleLocale`,Windows `PreferredUILanguages`/`LocaleName`),再回退终端 locale(`LANGUAGE` > `LC_ALL` > `LC_MESSAGES` > `LANG`),最后英文。`update --lang` 切换已安装块的语言;没有规范块时该参数不生效。不判断 IP 或地区。

**取消勾选 = 移除**。交互式多选里,*已被探测但你取消勾选的*编辑器的 openspec-pw 产物会被移除——命令/技能文件、该编辑器的 openspec-pw MCP 条目(含 claude 的 wrapper 块与 legacy 技能目录,以及归本工具所有的 vendored agents),前置一次列出全部待移除项的确认(拒绝则保持旧行为:本次仅跳过写入)。只动 openspec-pw 自有领土——同一文件中你自有的配置条目不受影响;你手改过的 vendored agent 文件会被保留并报告,绝不删除。共享规则:AGENTS.md 的 openspec-pw 块仅在**没有任何编辑器保留**时移除;symlink 的 CLAUDE.md 永不穿透写入。MCP 条目按**配置文件**判定:Claude Code / CodeBuddy CLI / MiniMax Code 共用项目根 `.mcp.json`,只要仍有被选中的编辑器读取该文件,共享条目即保留(确认清单中标注为「保留」)——该文件是这几个编辑器运行时直接读取的,删掉会连带切断仍被选中编辑器的 Playwright MCP;把三者全部取消勾选时条目照常移除。`--tools` 与非 TTY 运行不做任何移除(`--tools` 是显式授权清单)。移除直接反哺预选:被移除的编辑器下次 init 不再预勾选(预选读 openspec-pw 清单——保留的 `mcp.json`、你自己的文件、全局目录都不再重要);*全部*取消并确认的项目下次 init 重置回首-运行预选语义。

Expand Down
5 changes: 3 additions & 2 deletions src/commands/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,12 @@ export async function update(options: UpdateOptions) {
);
try {
// Re-run with --no-cli (avoid re-updating the just-updated CLI) and
// forward the user's other skip flags so the restarted process honors
// them too (e.g. --no-mcp must still skip the MCP phase).
// forward the user's other flags so the restarted process honors them
// too (e.g. --no-mcp must still skip the MCP phase, --lang must switch).
const reExecArgs = ["update", "--no-cli"];
if (options.mcp === false) reExecArgs.push("--no-mcp");
if (options.skill === false) reExecArgs.push("--no-skill");
if (options.lang) reExecArgs.push("--lang", options.lang);
execFileSync("openspec-pw", reExecArgs, {
stdio: "inherit",
cwd: projectRoot,
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ program
)
.option(
"--lang <lang>",
'employee standards language: "zh" or "en" (default: system locale)',
'employee standards language: "zh" or "en" (default: keep installed, else system language)',
)
.action(async (opts) => {
// Raw-argv check, before any import or write: commander's .conflicts()
Expand Down Expand Up @@ -156,7 +156,7 @@ program
.option("--no-mcp", "skip Playwright MCP install")
.option(
"--lang <lang>",
'employee standards language: "zh" or "en" (default: keep installed, else system locale)',
'employee standards language: "zh" or "en" (default: keep installed, else system language)',
)
.action(async (opts) => {
const langError = validateLanguageFlag(opts.lang);
Expand Down
112 changes: 106 additions & 6 deletions src/shared/standards-language.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { execFileSync } from "./exec.js";

export type StandardsLanguage = "zh" | "en";

/** Stable content anchors used to tell which language an installed block holds.
* These strings are load-bearing: rewording either one requires updating the
* other side's detection and its tests. */
const ZH_ANCHOR = "这份代码库是你的";
const EN_ANCHOR = "This codebase is yours";
/** Pre-anchor Chinese blocks used either this §0 heading or the older
* `## 一、代码质量` §1 heading; current blocks contain the former too, so
* these only apply when neither current anchor matches. */
const LEGACY_ZH_HEADINGS = ["## 0. 适用范围", "## 一、代码质量"];

/** Returns null for a valid value (or no value), or an error message. */
export function validateLanguageFlag(value: string | undefined): string | null {
Expand Down Expand Up @@ -37,20 +43,107 @@ function languageOf(raw: string | undefined): StandardsLanguage | null {
return normalized.startsWith("zh") ? "zh" : "en";
}

/** First quoted entry of `defaults read -g AppleLanguages`. */
function firstAppleLanguage(output: string): string | null {
const match = output.match(/"([^"]+)"/);
return match?.[1]?.trim() || null;
}

/** Value of a `reg query` line (`REG_SZ` / `REG_MULTI_SZ`, first entry). */
function firstRegValue(output: string): string | null {
const match = output.match(/\bREG_(?:MULTI_)?SZ\s+([^\r\n]+)/);
const value = match?.[1]?.trim().split(/\\0/)[0]?.trim();
return value || null;
}

/** A missing preference value or command is the normal "unavailable" case. */
function tryRead(
run: (command: string, args: string[]) => string,
command: string,
args: string[],
): string | null {
try {
const output = run(command, args);
return typeof output === "string" ? output : null;
} catch {
return null;
}
}

function runCommand(command: string, args: string[]): string {
const output: unknown = execFileSync(command, args, {
encoding: "utf-8",
timeout: 2_000,
});
return typeof output === "string" ? output : "";
}

/**
* Locale tag of the operating system's UI language, or null when it cannot be
* read. macOS keeps it in AppleLanguages; Windows in the user's preferred UI
* languages, with the format locale as the fallback. The runner is injectable
* so tests never spawn a process.
*/
export function readOsLocale(
platform: NodeJS.Platform = process.platform,
run: (command: string, args: string[]) => string = runCommand,
): string | null {
if (platform === "darwin") {
const languages = tryRead(run, "defaults", [
"read",
"-g",
"AppleLanguages",
]);
const language = languages ? firstAppleLanguage(languages) : null;
if (language) return language;
const locale = tryRead(run, "defaults", ["read", "-g", "AppleLocale"]);
return locale?.trim() || null;
}
if (platform === "win32") {
const ui = tryRead(run, "reg", [
"query",
"HKCU\\Control Panel\\Desktop",
"/v",
"PreferredUILanguages",
]);
const preferred = ui ? firstRegValue(ui) : null;
if (preferred) return preferred;
const locale = tryRead(run, "reg", [
"query",
"HKCU\\Control Panel\\International",
"/v",
"LocaleName",
]);
return locale ? firstRegValue(locale) : null;
}
return null;
}

export interface SystemLanguageOptions {
/** Injected for tests; defaults to process.env. */
env?: Record<string, string | undefined>;
/** Injected for tests; defaults to Intl's resolved locale. */
intlLocale?: string;
/** Injected for tests; null disables the OS source. Defaults to readOsLocale(platform). */
osLocale?: string | null;
/** Injected for tests; defaults to process.platform. */
platform?: NodeJS.Platform;
}

/**
* Resolve the terminal's language. GNU gettext gives LANGUAGE the highest
* priority, so follow the same order; C/POSIX and unknown values mean English.
* Resolve the system's language: the OS UI language first (macOS/Windows),
* then the terminal locale in gettext order; C/POSIX and unknown values mean
* English.
*/
export function detectSystemLanguage(
options: SystemLanguageOptions = {},
): StandardsLanguage {
const osLocale =
options.osLocale !== undefined
? options.osLocale
: readOsLocale(options.platform ?? process.platform);
const osLanguage = languageOf(osLocale ?? undefined);
if (osLanguage) return osLanguage;
const env = options.env ?? process.env;
for (const key of ["LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"] as const) {
const language = languageOf(env[key]);
Expand All @@ -61,23 +154,30 @@ export function detectSystemLanguage(
return languageOf(intl) ?? "en";
}

/** null when the content is missing, has neither anchor, or has both. */
/**
* null when the content is missing, has both current anchors, or matches
* neither; pre-anchor Chinese blocks fall back to the legacy §0 heading.
*/
export function detectInstalledLanguage(
content: string | null | undefined,
): StandardsLanguage | null {
if (!content) return null;
const zh = content.includes(ZH_ANCHOR);
const en = content.includes(EN_ANCHOR);
if (zh === en) return null;
return zh ? "zh" : "en";
if (zh && en) return null;
if (zh) return "zh";
if (en) return "en";
return LEGACY_ZH_HEADINGS.some((heading) => content.includes(heading))
? "zh"
: null;
}

export interface ResolveLanguageOptions extends SystemLanguageOptions {
flag?: string;
installed?: StandardsLanguage | null;
}

/** Explicit flag > installed block > system locale > English. */
/** Explicit flag > installed block > system language (OS first) > English. */
export function resolveStandardsLanguage(
options: ResolveLanguageOptions = {},
): StandardsLanguage {
Expand Down
3 changes: 2 additions & 1 deletion tests/commands/init-language.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ describe("init employee-standards language selection", () => {
return logSpy.mock.calls.map((c) => c.join(" ")).join("\n");
}

// The exec mock makes the OS probe unavailable, so this pins the fallback path.
function setSystemLocale(value: string): void {
for (const key of ["LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"]) {
delete process.env[key];
Expand All @@ -83,7 +84,7 @@ describe("init employee-standards language selection", () => {
expect(logText()).toContain("installed in English");
});

it("follows a Chinese system locale when --lang is omitted", async () => {
it("falls back to a Chinese terminal locale when the OS language is unavailable", async () => {
setSystemLocale("zh_CN.UTF-8");

await runInit();
Expand Down
6 changes: 3 additions & 3 deletions tests/editors-codebuddy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,20 +274,20 @@ describe("syncEmployeeStandards codebuddy gating", () => {

it("refreshes an authorized stale CODEBUDDY.md wrapper, preserving block-external content", () => {
writeFileSync(join(tmpRoot, "CODEBUDDY.md"), "preamble\n<!-- OPENSPEC-PW:START -->\noutdated\n<!-- OPENSPEC-PW:END -->\n");
syncEmployeeStandards(bundle(), tmpRoot, false, true, true);
syncEmployeeStandards(bundle(), tmpRoot, false, true, true, "zh");
const refreshed = readFileSync(join(tmpRoot, "CODEBUDDY.md"), "utf-8");
expect(refreshed).toContain("preamble\n");
expect(refreshed).toContain(claudeWrapperStandardsContent().trim());
expect(refreshed).not.toContain("outdated");
});

it("never creates CODEBUDDY.md when codebuddy is not authorized", () => {
syncEmployeeStandards(bundle(), tmpRoot, false, true, false);
syncEmployeeStandards(bundle(), tmpRoot, false, true, false, "zh");
expect(existsSync(join(tmpRoot, "CODEBUDDY.md"))).toBe(false);
});

it("creates the wrapper when authorized but missing (partial-install drift)", () => {
syncEmployeeStandards(bundle(), tmpRoot, false, true, true);
syncEmployeeStandards(bundle(), tmpRoot, false, true, true, "zh");
const content = readFileSync(join(tmpRoot, "CODEBUDDY.md"), "utf-8");
expect(content).toContain(claudeWrapperStandardsContent().trim());
});
Expand Down
Loading
Loading