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
53 changes: 53 additions & 0 deletions packages/cli/src/repositories/project-settings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { mkdtemp, writeFile, rm, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { readRawProjectSettings } from "./project-settings.js";

let tmpDir: string;

beforeEach(async () => {
tmpDir = await mkdtemp(join(tmpdir(), "reqord-settings-test-"));
// .reqord/settings/ ディレクトリを作成
await mkdir(join(tmpDir, ".reqord", "settings"), { recursive: true });
});

afterEach(async () => {
if (tmpDir) {
await rm(tmpDir, { recursive: true, force: true });
}
});

describe("readRawProjectSettings", () => {
it("setting.yamlが存在しない場合は空オブジェクトを返す", async () => {
const result = await readRawProjectSettings(tmpDir);
expect(result).toEqual({});
});

it("有効なYAMLファイルの場合はパース結果を返す", async () => {
const settingPath = join(tmpDir, ".reqord", "settings", "setting.yaml");
await writeFile(settingPath, "approvalPrerequisites:\n designMdCheck: false\n", "utf-8");

const result = await readRawProjectSettings(tmpDir);

expect(result).toEqual({
approvalPrerequisites: { designMdCheck: false },
});
});

it("空ファイルの場合は空オブジェクトを返す", async () => {
const settingPath = join(tmpDir, ".reqord", "settings", "setting.yaml");
await writeFile(settingPath, "", "utf-8");

const result = await readRawProjectSettings(tmpDir);

expect(result).toEqual({});
});

it("YAML構文エラーの場合はエラーをそのまま投げる", async () => {
const settingPath = join(tmpDir, ".reqord", "settings", "setting.yaml");
await writeFile(settingPath, "key: [\ninvalid yaml", "utf-8");

await expect(readRawProjectSettings(tmpDir)).rejects.toThrow("YAML syntax error");
});
});
20 changes: 20 additions & 0 deletions packages/cli/src/repositories/project-settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { SETTINGS_DIR } from "@reqord/shared";
import * as fs from "./file-system.js";

const SETTING_FILENAME = "setting.yaml";

function getSettingPath(cwd: string): string {
return fs.joinPath(fs.getReqordDir(cwd, SETTINGS_DIR), SETTING_FILENAME);
}

export async function readRawProjectSettings(cwd: string): Promise<unknown> {
const settingPath = getSettingPath(cwd);
if (!(await fs.exists(settingPath))) {
return {};
}
const raw = await fs.readYAML<unknown>(settingPath);
if (raw === null || raw === undefined) {
return {};
}
return raw;
}
88 changes: 88 additions & 0 deletions packages/cli/src/services/project-settings-service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";

vi.mock("../repositories/project-settings.js", () => ({
readRawProjectSettings: vi.fn(),
}));

import * as projectSettingsRepo from "../repositories/project-settings.js";
import { loadProjectSettings, getDefaultProjectSettings } from "./project-settings-service.js";

const mockRepo = vi.mocked(projectSettingsRepo);

beforeEach(() => {
vi.clearAllMocks();
});

afterEach(() => {
vi.restoreAllMocks();
});

describe("loadProjectSettings", () => {
it("リポジトリが空オブジェクトを返す場合はデフォルト設定を返す", async () => {
mockRepo.readRawProjectSettings.mockResolvedValue({});

const result = await loadProjectSettings("/cwd");

expect(result.invariants.versioning).toBe(true);
expect(result.approvalPrerequisites.designMdCheck).toBe(true);
expect(result.autoRevert.onContentChange).toBe("always");
});

it("正常なデータの場合はパース結果を返す", async () => {
mockRepo.readRawProjectSettings.mockResolvedValue({
approvalPrerequisites: { designMdCheck: false },
autoRevert: { onContentChange: "never" },
});

const result = await loadProjectSettings("/cwd");

expect(result.approvalPrerequisites.designMdCheck).toBe(false);
expect(result.autoRevert.onContentChange).toBe("never");
});

it("部分定義の場合はデフォルトとマージされた結果を返す", async () => {
mockRepo.readRawProjectSettings.mockResolvedValue({
statusTransitionPr: { draftToApproved: false },
});

const result = await loadProjectSettings("/cwd");

expect(result.statusTransitionPr.draftToApproved).toBe(false);
expect(result.statusTransitionPr.approvedToImplemented).toBe(false); // デフォルト
expect(result.statusTransitionPr.toDraft).toBe(true); // デフォルト
});

it("リポジトリがエラーを投げる場合はconsole.warnを呼びデフォルト設定を返す", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
mockRepo.readRawProjectSettings.mockRejectedValue(new Error("YAML syntax error"));

const result = await loadProjectSettings("/cwd");

expect(result.invariants.versioning).toBe(true); // デフォルト
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining("Could not read setting.yaml"),
);
});

it("バリデーション失敗の場合はconsole.warnを呼びデフォルト設定を返す", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
mockRepo.readRawProjectSettings.mockResolvedValue({
invariants: { versioning: false }, // z.literal(true)違反
});

const result = await loadProjectSettings("/cwd");

expect(result.invariants.versioning).toBe(true); // デフォルト
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining("Invalid setting.yaml"),
);
});
});

describe("getDefaultProjectSettings", () => {
it("全フィールドがデフォルト値の設定を返す", () => {
const result = getDefaultProjectSettings();
expect(result.invariants.versioning).toBe(true);
expect(result.feedbackValidation.severityThreshold).toBe("critical");
});
});
27 changes: 27 additions & 0 deletions packages/cli/src/services/project-settings-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ProjectSettingsSchema, formatZodError } from "@reqord/shared";
import type { ProjectSettings } from "@reqord/shared";
import * as projectSettingsRepo from "../repositories/project-settings.js";

export async function loadProjectSettings(cwd: string): Promise<ProjectSettings> {
let raw: unknown;
try {
raw = await projectSettingsRepo.readRawProjectSettings(cwd);
} catch (error) {
console.warn(
`[reqord] Could not read setting.yaml: ${error instanceof Error ? error.message : String(error)}. Using default settings.`,
);
return getDefaultProjectSettings();
}
const result = ProjectSettingsSchema.safeParse(raw);
if (!result.success) {
console.warn(
`[reqord] Invalid setting.yaml:\n${formatZodError(result.error)}\nUsing default settings.`,
);
Comment on lines +16 to +19

Copilot AI Mar 2, 2026

Copy link

Choose a reason for hiding this comment

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

The warning for invalid settings uses result.error.message, which is often hard to read for nested Zod objects. The repo already exports formatZodError from @reqord/shared and uses it in other validation errors; consider using it here (even in warnings) so users can quickly pinpoint the invalid field/path.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

@copilot 良い指摘です。formatZodError を使うよう修正しました (a13a804)。既存パターンとの一貫性も向上しています。

return getDefaultProjectSettings();
Comment on lines +7 to +20

Copilot AI Mar 2, 2026

Copy link

Choose a reason for hiding this comment

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

loadProjectSettings falls back to default settings on both read errors and schema validation failures. This makes a misconfigured setting.yaml (e.g. invariants.versioning: false) easy to miss and conflicts with the success criterion that setting invariants to false should result in a validation error. Consider throwing (or returning a typed error) on validation failures at least, and only defaulting when the file is missing/empty.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

@copilot ありがとうございます。

これは design.md セクション4.3の仕様通りの実装です(「パース失敗時は警告を出しデフォルト設定を返す」)。setting.yaml の欠損・破損でも CLI が動作継続できることを意図しています。

invariants 違反時にエラーとして伝播させるかどうかは、将来の spec で検討する余地がありますが、現時点では spec-000035 のスコープ外として対応を見送ります。

}
return result.data;
}

export function getDefaultProjectSettings(): ProjectSettings {
return ProjectSettingsSchema.parse({});
}
19 changes: 19 additions & 0 deletions packages/shared/src/schemas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,22 @@ export {
type TaskEntry,
type TasksIndex,
} from "./task.js";

export {
InvariantsSchema,
ApprovalPrerequisitesSchema,
StatusTransitionPrSchema,
BranchNamingSchema,
FeedbackValidationSchema,
AutoRevertSchema,
ConsistencyCheckSchema,
ProjectSettingsSchema,
type ProjectSettings,
type ApprovalPrerequisites,
type StatusTransitionPr,
type BranchNaming,
type FeedbackValidation,
type AutoRevert,
type Invariants,
type ConsistencyCheck,
} from "./project-settings.js";
140 changes: 140 additions & 0 deletions packages/shared/src/schemas/project-settings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { describe, it, expect } from "vitest";
import { ProjectSettingsSchema } from "./project-settings.js";

describe("ProjectSettingsSchema", () => {
describe("デフォルト値補完", () => {
it("空オブジェクトを渡すと全フィールドがデフォルト値で補完される", () => {
const result = ProjectSettingsSchema.parse({});
// invariants
expect(result.invariants.versioning).toBe(true);
expect(result.invariants.cyclicDependencyCheck).toBe(true);
expect(result.invariants.statusTransitionRules).toBe(true);
expect(result.invariants.schemaValidation).toBe(true);
// approvalPrerequisites
expect(result.approvalPrerequisites.designMdCheck).toBe(true);
expect(result.approvalPrerequisites.descriptionMdCheck).toBe(false);
expect(result.approvalPrerequisites.customFiles).toEqual([]);
// statusTransitionPr
expect(result.statusTransitionPr.draftToApproved).toBe(true);
expect(result.statusTransitionPr.approvedToImplemented).toBe(false);
expect(result.statusTransitionPr.toDraft).toBe(true);
// branchNaming
expect(result.branchNaming.toApprovedPrefix).toBe("reqord");
expect(result.branchNaming.toImplementedPrefix).toBe("reqord");
expect(result.branchNaming.toDraftPrefix).toBe("reqord");
// feedbackValidation
expect(result.feedbackValidation.blockOnUnresolved).toBe(false);
expect(result.feedbackValidation.severityThreshold).toBe("critical");
// autoRevert
expect(result.autoRevert.onContentChange).toBe("always");
// consistencyCheck
expect(result.consistencyCheck.specNotImplementedLevel).toBe("warning");
});

it("部分定義の場合は未指定フィールドのみデフォルト値で補完される", () => {
const result = ProjectSettingsSchema.parse({
approvalPrerequisites: { designMdCheck: false },
});
expect(result.approvalPrerequisites.designMdCheck).toBe(false);
expect(result.approvalPrerequisites.descriptionMdCheck).toBe(false);
expect(result.approvalPrerequisites.customFiles).toEqual([]);
});

it("invariantsに空オブジェクトを渡すと全項目がtrueで補完される", () => {
const result = ProjectSettingsSchema.parse({ invariants: {} });
expect(result.invariants.versioning).toBe(true);
expect(result.invariants.cyclicDependencyCheck).toBe(true);
expect(result.invariants.statusTransitionRules).toBe(true);
expect(result.invariants.schemaValidation).toBe(true);
});
});

describe("全フィールド指定", () => {
it("全フィールドを指定するとそのまま通過する", () => {
const input = {
invariants: {
versioning: true,
cyclicDependencyCheck: true,
statusTransitionRules: true,
schemaValidation: true,
},
approvalPrerequisites: {
designMdCheck: false,
descriptionMdCheck: true,
customFiles: ["CHANGELOG.md"],
},
statusTransitionPr: {
draftToApproved: false,
approvedToImplemented: true,
toDraft: false,
},
branchNaming: {
toApprovedPrefix: "custom",
toImplementedPrefix: "impl",
toDraftPrefix: "draft",
},
feedbackValidation: {
blockOnUnresolved: true,
severityThreshold: "high" as const,
},
autoRevert: { onContentChange: "never" as const },
consistencyCheck: { specNotImplementedLevel: "error" as const },
};
const result = ProjectSettingsSchema.parse(input);
expect(result).toEqual(input);
});
});

describe("不明キーのstrip", () => {
it("不明なキーが含まれる場合はstripされて正常に通過する", () => {
const result = ProjectSettingsSchema.parse({
unknownKey: "value",
approvalPrerequisites: { unknownNested: true },
});
expect((result as Record<string, unknown>).unknownKey).toBeUndefined();
});
});

describe("バリデーションエラー", () => {
it.each([
["versioning"],
["cyclicDependencyCheck"],
["statusTransitionRules"],
["schemaValidation"],
])("invariants.%sにfalseを設定するとZodErrorになる", (field) => {
expect(() =>
ProjectSettingsSchema.parse({ invariants: { [field]: false } })
).toThrow();
});

it("branchNaming.toApprovedPrefixに空文字を設定するとZodErrorになる", () => {
expect(() =>
ProjectSettingsSchema.parse({ branchNaming: { toApprovedPrefix: "" } })
).toThrow();
});

it("autoRevert.onContentChangeに無効な値を設定するとZodErrorになる", () => {
expect(() =>
ProjectSettingsSchema.parse({ autoRevert: { onContentChange: "sometimes" } })
).toThrow();
});

it("consistencyCheck.specNotImplementedLevelに無効な値を設定するとZodErrorになる", () => {
expect(() =>
ProjectSettingsSchema.parse({ consistencyCheck: { specNotImplementedLevel: "info" } })
).toThrow();
});

it("feedbackValidation.severityThresholdに無効な値を設定するとZodErrorになる", () => {
expect(() =>
ProjectSettingsSchema.parse({ feedbackValidation: { severityThreshold: "urgent" } })
).toThrow();
});

it("customFilesに文字列以外が含まれるとZodErrorになる", () => {
expect(() =>
ProjectSettingsSchema.parse({ approvalPrerequisites: { customFiles: [123] } })
).toThrow();
});
});
});
Loading
Loading