diff --git a/README.md b/README.md index 9dc37913..3d883d5e 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,28 @@ npx -y mottainai list npx -y mottainai inspect codegraph ``` +### Git workflow task lifecycle (early exposure, Issue #34) + +Behind `gateway.workflowTasks: true` in `mottainai.config.json`, the MCP +tools `mottainai_workflow_policy_explain`, `mottainai_workflow_task_start`, +and `mottainai_workflow_task_status` expose the Git workflow engine +(`src/workflow/*`, Issue #28) for early dogfooding. `task start` always +creates a dedicated worktree and branch off the current branch — never the +current branch itself, even on `main`. This is observation/dogfooding only: +no commit/push/PR/cleanup exposure and no protected-branch write-blocking +yet (see `docs/workflow-policy.md`). `mottainai_worktree_new` remains +available but is deprecated in favor of `mottainai_workflow_task_start`. + +The same three operations are available from the CLI, independent of +`mottainai.config.json` (they act on a Git repository, given by `--workspace` +or the current Git repository's top level): + +```bash +npx -y mottainai policy explain [--workspace path] +npx -y mottainai task start [--issue ref] [--workspace path] +npx -y mottainai task status [--workspace path] +``` + Initialization options include `--workspace`, `--scope personal|project`, `--client claude|codex|none`, `--import claude|codex|none`, `--force`, `--dry-run`, `--json`, `--no-register`, and `--no-doctor`. The default client diff --git a/docs/workflow-policy.md b/docs/workflow-policy.md index d9cb5d22..67c4fba0 100644 --- a/docs/workflow-policy.md +++ b/docs/workflow-policy.md @@ -204,9 +204,26 @@ reconciliation reporting of detected hook-bypass events is Child Issue 8. Task/worktree lifecycle, commit/push execution, provider integration, -cleanup, reconciliation, and MCP/CLI exposure remain separate child -Issues under the Issue #28 Epic and land incrementally. See Issue #28 -for the full child-Issue sequence. +cleanup, and reconciliation remain separate child Issues under the +Issue #28 Epic and land incrementally. See Issue #28 for the full +child-Issue sequence. + +Issue #34 added a thin, early-dogfooding MCP/CLI exposure of three +read-heavy/low-blast-radius operations — `policy explain`, `task +start`, `task status` (`src/workflow/commands/mcp-tools.ts`, gated by +`gateway.workflowTasks`) — ahead of the full exposure in Child Issue +9a-1/9a-2. `policy explain` resolves only the genuine `RuleMode` +fields (`protectedBranchRule.*` / `worktree.{required,issueRequired, +multipleActiveTasksPerIssue,multipleWorktreesPerTask,staleBaseBranch}` +/ `cleanup.*`) through `resolveRule()`; `protectedBranches`, +`controlPlaneRole`, `stagingMode`, and `worktree.bootstrapMode` are +returned as plain descriptive values since the schema has no +associated mode for them yet. `task start`/`task status` still consult +the effective policy document directly (`resolveEffectiveWorkflowPolicy`), +not the authority-resolved view `policy explain` shows — the +resolution/weakening-guard engine is not yet wired into task-start +enforcement itself. Full write-path enforcement remains Child Issue +9a-2. ## Rollout status diff --git a/src/cli.ts b/src/cli.ts index 9905f951..12796b04 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,8 +1,14 @@ +import { execFileSync } from "node:child_process"; +import path from "node:path"; import { collectDoctorReport, formatDoctorHuman } from "./commands/doctor.js"; import { loadMottainaiConfig, loadRawConfig, resolveConfigPath, saveRawConfig } from "./config.js"; import type { MottainaiConfig } from "./config.js"; import { formatInitHuman, runInit } from "./init.js"; import { runServer } from "./server.js"; +import { startTask, getTaskStatusForWorkspace } from "./workflow/domain/task.js"; +import { explainWorkflowPolicy } from "./workflow/policy/explain.js"; +import { resolveEffectiveWorkflowPolicy } from "./workflow/policy/load.js"; +import type { WorkflowStateStore } from "./workflow/state/store.js"; /** * upstream と profile の管理 CLI。 @@ -25,6 +31,9 @@ const USAGE = `usage: mottainai profile use set gateway.activeProfile mottainai profile clear unset gateway.activeProfile mottainai doctor [--json] validate the local installation + mottainai policy explain [--workspace path] resolved Git workflow policy (Issue #34) + mottainai task start [options] start a Git workflow task (dedicated worktree/branch) + mottainai task status [--workspace path] active Git workflow task for the current worktree add options: --transport streamableHttp remote transport; inferred from --url @@ -51,6 +60,10 @@ init options: --no-register do not change MCP client registrations --no-doctor skip post-initialization diagnostics --latest register the unpinned npm package + +policy/task options: + --workspace path Git repository root; defaults to the current Git repository's top level + --issue ref issue reference for "task start" (omit for an ad-hoc, non-issue-bound task) `; function flag(argv: string[], name: string): string | undefined { @@ -62,6 +75,37 @@ function hasFlag(argv: string[], name: string): boolean { return argv.includes(`--${name}`); } +function gitTopLevel(cwd: string): string | undefined { + try { + return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" }).trim(); + } catch { + return undefined; + } +} + +/** `--workspace` 明示時はそれを、無ければ現在の Git リポジトリの top level を、 + * どちらも無ければ cwd をそのまま使う(`init` の `--workspace` 既定と同じ考え方)。 */ +function resolveWorkflowWorkspace(argv: string[]): string { + const explicit = flag(argv, "workspace"); + if (explicit !== undefined) return path.resolve(process.cwd(), explicit); + return gitTopLevel(process.cwd()) ?? process.cwd(); +} + +/** + * `task start`/`task status` が使う `WorkflowStateStore`。MCP 面(`mottainai_workflow_task_*`) + * と同じ既定 DB ファイルを開く(`src/workflow/state/sqlite-store.ts` の + * `resolveStateDbPath` 共有)ため、CLI から始めた task を MCP 経由でも見える。 + * `node:sqlite` の import は `ExperimentalWarning` を stderr に出す副作用があるため、 + * `policy`/`list`/`init` 等このコマンドを使わない CLI 呼び出しに static import で + * 持ち込まない — 実際に `task` サブコマンドが呼ばれたときだけ dynamic import する。 + */ +async function openWorkflowStateStore(): Promise { + const { WorkflowSqliteStateStore } = await import("./workflow/state/sqlite-store.js"); + const store = new WorkflowSqliteStateStore(); + store.init(); + return store; +} + function print(value: unknown): void { console.log(JSON.stringify(value, null, 2)); } @@ -219,6 +263,51 @@ export async function runCli(args: string[]): Promise { if (hasFlag(argv, "json")) print(report); else console.log(formatDoctorHuman(report)); return report.ok ? 0 : 1; +} else if (command === "policy" && argv[0] === "explain") { + const workspace = resolveWorkflowWorkspace(argv); + const result = explainWorkflowPolicy(workspace); + if (!result.ok) { + print({ ok: false, workspace, error: result.reason }); + return 1; + } + print({ ok: true, workspace, ...result.explained }); +} else if (command === "task" && argv[0] === "start") { + const taskSlug = argv[1]; + if (taskSlug === undefined || taskSlug.startsWith("--")) fail(USAGE); + const workspace = resolveWorkflowWorkspace(argv); + const issueRef = flag(argv, "issue"); + const policyResult = resolveEffectiveWorkflowPolicy(workspace); + if (!policyResult.ok) { + print({ ok: false, workspace, error: policyResult.reason }); + return 1; + } + const store = await openWorkflowStateStore(); + try { + // `skipWorktree` を渡さない — task lifecycle は常に専用 worktree/branch を作る + // (main を含む現在の branch がそのまま work branch になることはない)。 + const started = await startTask({ workspaceRoot: workspace, store, policy: policyResult.document, taskSlug, issueRef }); + if (!started.ok) { + print({ ok: false, workspace, reason: started.reason, error: started.detail }); + return 1; + } + print({ ok: true, workspace, task: started.task, worktree: started.worktree, warnings: started.warnings }); + } finally { + store.close(); + } +} else if (command === "task" && argv[0] === "status") { + const workspace = resolveWorkflowWorkspace(argv); + const store = await openWorkflowStateStore(); + try { + const result = await getTaskStatusForWorkspace(workspace, store); + if (!result.ok) { + print({ ok: false, workspace, error: result.reason }); + return 1; + } + const { ok: _ok, ...rest } = result; + print({ ok: true, workspace, ...rest }); + } finally { + store.close(); + } } else { fail(USAGE); } diff --git a/src/code-search.test.ts b/src/code-search.test.ts index e8751fd1..5325c9c4 100644 --- a/src/code-search.test.ts +++ b/src/code-search.test.ts @@ -17,7 +17,7 @@ function gatewayConfig(root: string): ResolvedGatewayConfig { return { workspaceRoot: root, defaultTimeoutMs: 5_000, maxTimeoutMs: 5_000, maxOutputBytes: 1024 * 1024, execTargetTokens: 1_000, resultTtlMs: 10_000, resultMaxEntries: 10, - capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, + capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, workflowTasks: false, }; } diff --git a/src/config.test.ts b/src/config.test.ts index 67fefa40..af2f577b 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -347,6 +347,32 @@ test("resolveGatewayConfig defaults tokenBudgets to empty maps (opt-in: no confi assert.equal(resolved.activeProfile, undefined); }); +test("resolveGatewayConfig defaults workflowTasks to false (mottainai_task_start/status stay unpublished)", () => { + assert.equal(resolveGatewayConfig(undefined).workflowTasks, false); + assert.equal(resolveGatewayConfig({ workflowTasks: true }).workflowTasks, true); + assert.equal(resolveGatewayConfig({ workflowTasks: false }).workflowTasks, false); +}); + +test("loadMottainaiConfig rejects a non-boolean gateway.workflowTasks", () => { + assert.throws( + () => loadMottainaiConfig(writeConfig({ + version: 2, + mcpServers: { one: { command: "node" } }, + gateway: { workflowTasks: "yes" }, + })), + /invalid gateway workflowTasks/, + ); +}); + +test("loadMottainaiConfig round-trips gateway.workflowTasks=true", () => { + const configPath = writeConfig({ + version: 2, + mcpServers: { one: { command: "node" } }, + gateway: { workflowTasks: true }, + }); + assert.equal(loadMottainaiConfig(configPath).gateway?.workflowTasks, true); +}); + test("config snapshot resolves MOTTAINAI_CONFIG once from its startup cwd (#59)", () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-config-snapshot-")); const configDirectory = path.join(directory, "config"); diff --git a/src/config.ts b/src/config.ts index 775cfc3c..0d7b1034 100644 --- a/src/config.ts +++ b/src/config.ts @@ -119,6 +119,9 @@ export interface GatewayConfig { tokenBudgets?: TokenBudgetsConfig; /** `mottainai_worktree_new` の許可 prefix・起点ブランチ設定。省略時はツールを非公開にする。 */ worktree?: WorktreeConfig; + /** `mottainai_task_start`/`mottainai_task_status`(Git workflow task lifecycle)の公開可否。 + * worktree 作成等の副作用を持つため、`worktree` 同様に既定 false(非公開)。 */ + workflowTasks?: boolean; } export interface ResolvedGatewayConfig { @@ -136,6 +139,7 @@ export interface ResolvedGatewayConfig { oauthProviderModule?: string; tokenBudgets: ResolvedTokenBudgets; worktree?: ResolvedWorktreeConfig; + workflowTasks: boolean; } /** 起動時に一度だけ解決した設定。以後の各層は同じ絶対パス基準を共有する。 */ @@ -155,6 +159,7 @@ const DEFAULT_GATEWAY_CONFIG: Omit = { capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, + workflowTasks: false, }; export function loadMottainaiConfig(configPath?: string): MottainaiConfig { @@ -184,6 +189,7 @@ export function resolveGatewayConfig( activeProfile: config?.activeProfile, tokenBudgets: resolveTokenBudgets(config?.tokenBudgets), worktree: resolveWorktreeConfig(config?.worktree), + workflowTasks: config?.workflowTasks === true, }; } @@ -297,6 +303,9 @@ function normalizeGateway(value: unknown): GatewayConfig | undefined { if (value === undefined) return undefined; if (!isRecord(value)) throw new Error("invalid gateway config"); const workspaceRoot = optionalString(value.workspaceRoot, "invalid gateway workspaceRoot"); + if (value.workflowTasks !== undefined && typeof value.workflowTasks !== "boolean") { + throw new Error("invalid gateway workflowTasks"); + } return { workspaceRoot, defaultTimeoutMs: positiveIntegerConfig(value.defaultTimeoutMs, "invalid gateway defaultTimeoutMs"), @@ -311,6 +320,7 @@ function normalizeGateway(value: unknown): GatewayConfig | undefined { toolMetadata: toolMetadataRecord(value.toolMetadata, "invalid gateway toolMetadata"), tokenBudgets: tokenBudgetsConfig(value.tokenBudgets, "invalid gateway tokenBudgets"), worktree: worktreeConfig(value.worktree, "invalid gateway worktree"), + workflowTasks: value.workflowTasks as boolean | undefined, }; } diff --git a/src/local-tools.test.ts b/src/local-tools.test.ts index 13df0bb4..962cbd56 100644 --- a/src/local-tools.test.ts +++ b/src/local-tools.test.ts @@ -15,7 +15,7 @@ async function workspace(): Promise<{ root: string; config: ResolvedGatewayConfi await fs.writeFile(path.join(root, "src", "sample.ts"), "export function useful() {\n return 1;\n}\nexport const value = 2;\n"); await fs.writeFile(path.join(root, "needle.txt"), "one\nneedle here\nthree\n"); await fs.writeFile(path.join(root, "node_modules", "ignored.txt"), "needle ignored"); - return { root, config: { workspaceRoot: root, defaultTimeoutMs: 1_000, maxTimeoutMs: 2_000, maxOutputBytes: 1024, execTargetTokens: 1_000, resultTtlMs: 10_000, resultMaxEntries: 10, capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} } } }; + return { root, config: { workspaceRoot: root, defaultTimeoutMs: 1_000, maxTimeoutMs: 2_000, maxOutputBytes: 1024, execTargetTokens: 1_000, resultTtlMs: 10_000, resultMaxEntries: 10, capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, workflowTasks: false } }; } function structured(result: Awaited>): Record { @@ -351,15 +351,32 @@ test("worktree_new tool is only listed when a worktree config is present", () => const bareConfig: ResolvedGatewayConfig = { workspaceRoot: "/tmp", defaultTimeoutMs: 1_000, maxTimeoutMs: 2_000, maxOutputBytes: 1024, execTargetTokens: 1_000, resultTtlMs: 10_000, resultMaxEntries: 10, capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, + workflowTasks: false, }; assert.equal(localToolsFor(bareConfig).some((tool) => tool.name === "mottainai_worktree_new"), false); const withWorktree: ResolvedGatewayConfig = { ...bareConfig, worktree: { allowedBranchPrefixes: ["docs"], baseBranch: "main", worktreeDir: ".worktrees" } }; - const names = localToolsFor(withWorktree).map((tool) => tool.name); + const tools = localToolsFor(withWorktree); + const names = tools.map((tool) => tool.name); assert.ok(names.includes("mottainai_worktree_new")); assert.ok(names.includes("mottainai_issue_view")); }); +test("worktree_new is annotated as deprecated in favor of mottainai_workflow_task_start (Issue #34), without changing its behavior", () => { + const withWorktree: ResolvedGatewayConfig = { + workspaceRoot: "/tmp", defaultTimeoutMs: 1_000, maxTimeoutMs: 2_000, maxOutputBytes: 1024, execTargetTokens: 1_000, + resultTtlMs: 10_000, resultMaxEntries: 10, capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, + workflowTasks: false, worktree: { allowedBranchPrefixes: ["docs"], baseBranch: "main", worktreeDir: ".worktrees" }, + }; + const tool = localToolsFor(withWorktree).find((candidate) => candidate.name === "mottainai_worktree_new"); + assert.ok(tool !== undefined); + assert.match(tool!.description ?? "", /Deprecated/); + assert.match(tool!.description ?? "", /mottainai_workflow_task_start/); + // behavior/schema unchanged: still a required prefix+task worktree-creation tool. + assert.deepEqual(tool!.inputSchema.required, ["prefix", "task"]); + assert.equal(tool!.annotations?.destructiveHint, false); +}); + test("worktree_new creates a branch and worktree under the configured directory", async () => { const { root, config } = await gitWorkspace(); const store = new InMemoryArtifactStore(); @@ -429,16 +446,17 @@ test("the advertised tool surface matches the executable tool surface for worktr worktree: { allowedBranchPrefixes: ["docs"], baseBranch: "main", worktreeDir: ".worktrees" }, }; const store = new InMemoryArtifactStore(); - const guardedTools: Array<{ name: string; args: Record }> = [ - { name: "mottainai_worktree_new", args: { prefix: "docs", task: "example" } }, - { name: "mottainai_issue_view", args: { number: 1 } }, + const guardedTools: Array<{ name: string; args: Record; enabled: (config: ResolvedGatewayConfig) => boolean }> = [ + { name: "mottainai_worktree_new", args: { prefix: "docs", task: "example" }, enabled: (config) => config.worktree !== undefined }, + { name: "mottainai_issue_view", args: { number: 1 }, enabled: (config) => config.worktree !== undefined }, ]; + const configs = [bareConfig, withWorktree]; - for (const config of [bareConfig, withWorktree]) { + for (const config of configs) { const advertisedNames = new Set(localToolsFor(config).map((tool) => tool.name)); for (const tool of guardedTools) { const isAdvertised = advertisedNames.has(tool.name); - assert.equal(isAdvertised, config.worktree !== undefined, `${tool.name} advertised state must track config.worktree`); + assert.equal(isAdvertised, tool.enabled(config), `${tool.name} advertised state must track its gating config field`); if (!isAdvertised) { // hidden from localToolsFor: calling it directly by name must still be rejected by the // same runtime guard, so the advertised and executable surfaces stay in lockstep. @@ -450,7 +468,7 @@ test("the advertised tool surface matches the executable tool surface for worktr } } // every tool in allLocalTools is reachable through localToolsFor under some configuration. - const everAdvertised = new Set([...localToolsFor(bareConfig), ...localToolsFor(withWorktree)].map((tool) => tool.name)); + const everAdvertised = new Set(configs.flatMap((config) => localToolsFor(config).map((tool) => tool.name))); for (const tool of allLocalTools) assert.ok(everAdvertised.has(tool.name), `${tool.name} must be advertised under some configuration`); await fs.rm(root, { recursive: true, force: true }); }); diff --git a/src/local-tools.ts b/src/local-tools.ts index fad8ab6c..510b9354 100644 --- a/src/local-tools.ts +++ b/src/local-tools.ts @@ -72,9 +72,16 @@ export const localTools: Tool[] = [ }, ]; +/** + * Deprecated (Issue #34): superseded by `mottainai_workflow_task_start` + * (`src/workflow/commands/mcp-tools.ts`), which reserves the same kind of + * dedicated worktree/branch under Mottainai's tracked task lifecycle (task + * id, lifecycle state, guardrail policy) instead of a bare `git worktree + * add`. Kept in place, unchanged, for existing callers — not removed. + */ const worktreeNewTool: Tool = { name: "mottainai_worktree_new", - description: "Create a git worktree on a new branch, using the workspace's allowed branch prefixes.", + description: "Deprecated: superseded by mottainai_workflow_task_start. Create a git worktree on a new branch, using the workspace's allowed branch prefixes.", inputSchema: { type: "object", properties: { prefix: { type: "string" }, task: { type: "string" }, }, required: ["prefix", "task"] }, outputSchema: OUTPUT_SCHEMA, diff --git a/src/mcp-cli.test.ts b/src/mcp-cli.test.ts index 27a14ee4..00dada46 100644 --- a/src/mcp-cli.test.ts +++ b/src/mcp-cli.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -263,6 +263,124 @@ test("server entry points report configuration failures without an unhandled rej fs.rmSync(directory, { recursive: true, force: true }); }); +function gitWorkspace(): string { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-cli-workflow-")); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: directory }); + execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: directory }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: directory }); + fs.writeFileSync(path.join(directory, "file.txt"), "hello\n"); + execFileSync("git", ["add", "."], { cwd: directory }); + execFileSync("git", ["commit", "-q", "-m", "initial"], { cwd: directory }); + return directory; +} + +/** `task`/`policy` サブコマンドは git repo を対象にする(`config.json` は使わない)。 + * `MOTTAINAI_STATE_DIR` を使い捨てディレクトリへ向け、実 state と分離する。 */ +function runWorkflow(...argv: string[]): Run { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-cli-workflow-state-")); + try { + const result = spawnSync( + process.execPath, + ["--import", "tsx", publicCliPath, ...argv], + { encoding: "utf8", env: { ...process.env, MOTTAINAI_STATE_DIR: stateDir } }, + ); + let json: Record = {}; + try { + json = JSON.parse(result.stdout) as Record; + } catch { + json = {}; + } + return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr, json }; + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +} + +test("public CLI policy explain reports the standard preset for a plain repository", () => { + const directory = gitWorkspace(); + const result = runWorkflow("policy", "explain", "--workspace", directory); + assert.equal(result.status, 0); + assert.equal(result.json.ok, true); + assert.equal(result.json.preset, "standard"); + assert.equal(result.json.policySourceAuthority, "preset"); + const rules = result.json.rules as { protectedBranchRule: { directPush: { mode: string; authority: string } } }; + assert.equal(rules.protectedBranchRule.directPush.mode, "enforce"); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +test("public CLI task start creates a dedicated worktree/branch, and task status reports it from inside that worktree", () => { + const directory = gitWorkspace(); + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-cli-workflow-state-")); + const env = { ...process.env, MOTTAINAI_STATE_DIR: stateDir }; + const spawn = (...argv: string[]): Run => { + const result = spawnSync(process.execPath, ["--import", "tsx", publicCliPath, ...argv], { encoding: "utf8", env }); + let json: Record = {}; + try { + json = JSON.parse(result.stdout) as Record; + } catch { + json = {}; + } + return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr, json }; + }; + + const before = spawn("task", "status", "--workspace", directory); + assert.equal(before.status, 0); + assert.equal(before.json.active, false); + assert.equal(before.json.branch, "main"); + + const started = spawn("task", "start", "my-task", "--issue", "9", "--workspace", directory); + assert.equal(started.status, 0); + assert.equal(started.json.ok, true); + const worktree = started.json.worktree as { branchName: string; canonicalPath: string }; + assert.equal(worktree.branchName, "issue-9/my-task"); + assert.notEqual(worktree.branchName, "main"); + + const statusInWorktree = spawn("task", "status", "--workspace", worktree.canonicalPath); + assert.equal(statusInWorktree.status, 0); + assert.equal(statusInWorktree.json.active, true); + + fs.rmSync(stateDir, { recursive: true, force: true }); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +test("public CLI task start rejects starting a second task from inside its own already-active worktree", () => { + const directory = gitWorkspace(); + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-cli-workflow-state-")); + const env = { ...process.env, MOTTAINAI_STATE_DIR: stateDir }; + const spawn = (...argv: string[]): Run => { + const result = spawnSync(process.execPath, ["--import", "tsx", publicCliPath, ...argv], { encoding: "utf8", env }); + let json: Record = {}; + try { + json = JSON.parse(result.stdout) as Record; + } catch { + json = {}; + } + return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr, json }; + }; + + const outer = spawn("task", "start", "outer", "--workspace", directory); + assert.equal(outer.status, 0); + const worktree = outer.json.worktree as { canonicalPath: string }; + + const inner = spawn("task", "start", "inner", "--workspace", worktree.canonicalPath); + assert.equal(inner.status, 1); + assert.equal(inner.json.ok, false); + assert.equal(inner.json.reason, "active-task-in-workspace"); + + fs.rmSync(stateDir, { recursive: true, force: true }); + fs.rmSync(directory, { recursive: true, force: true }); +}); + +test("public CLI policy explain fails closed on a corrupted .mottainai/workflow.json", () => { + const directory = gitWorkspace(); + fs.mkdirSync(path.join(directory, ".mottainai"), { recursive: true }); + fs.writeFileSync(path.join(directory, ".mottainai", "workflow.json"), "{ not json"); + const result = runWorkflow("policy", "explain", "--workspace", directory); + assert.equal(result.status, 1); + assert.equal(result.json.ok, false); + fs.rmSync(directory, { recursive: true, force: true }); +}); + test("public CLI init emits one JSON document and creates the workspace configuration", () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-public-init-")); const result = runPublic(directory, "init", "--yes", "--workspace", directory, "--scope", "project", "--client", "none", "--no-doctor", "--json"); diff --git a/src/proxy.test.ts b/src/proxy.test.ts index aaa5bed5..0581a081 100644 --- a/src/proxy.test.ts +++ b/src/proxy.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -1140,3 +1141,53 @@ test("mottainai_telemetry_summary reports disabled state when telemetry is off, await onClient.close(); }); + +test("mottainai_workflow_task_start/status/policy_explain are only listed and callable when gateway.workflowTasks is enabled (Issue #34)", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-proxy-workflow-")); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: root }); + execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: root }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: root }); + fs.writeFileSync(path.join(root, "file.txt"), "hello\n"); + execFileSync("git", ["add", "."], { cwd: root }); + execFileSync("git", ["commit", "-q", "-m", "initial"], { cwd: root }); + + const disabledClient = await connectedClient([], undefined, undefined, undefined, { + gateway: resolveGatewayConfig({ workspaceRoot: root }), + }); + const { tools: disabledTools } = await disabledClient.listTools(); + assert.equal(disabledTools.some((tool) => tool.name.startsWith("mottainai_workflow_")), false); + await assert.rejects(() => disabledClient.callTool({ name: "mottainai_workflow_task_status", arguments: {} })); + await disabledClient.close(); + + // `mottainai_workflow_task_status` goes through the default (non-injected) WorkflowStateStore + // singleton at this layer, so it opens a real sqlite file — point it at a throwaway + // directory rather than the real per-user state dir. + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-proxy-workflow-state-")); + const originalStateDir = process.env.MOTTAINAI_STATE_DIR; + process.env.MOTTAINAI_STATE_DIR = stateDir; + try { + const enabledClient = await connectedClient([], undefined, undefined, undefined, { + gateway: resolveGatewayConfig({ workspaceRoot: root, workflowTasks: true }), + }); + const { tools: enabledTools } = await enabledClient.listTools(); + const names = enabledTools.map((tool) => tool.name); + assert.ok(names.includes("mottainai_workflow_policy_explain")); + assert.ok(names.includes("mottainai_workflow_task_start")); + assert.ok(names.includes("mottainai_workflow_task_status")); + + const status = await enabledClient.callTool({ name: "mottainai_workflow_task_status", arguments: {} }); + const statusContent = status.structuredContent as Record; + assert.equal(statusContent.status, "success"); + assert.equal(statusContent.active, false); + + const explain = await enabledClient.callTool({ name: "mottainai_workflow_policy_explain", arguments: {} }); + assert.equal((explain.structuredContent as Record).status, "success"); + + await enabledClient.close(); + } finally { + if (originalStateDir === undefined) delete process.env.MOTTAINAI_STATE_DIR; + else process.env.MOTTAINAI_STATE_DIR = originalStateDir; + fs.rmSync(stateDir, { recursive: true, force: true }); + } + fs.rmSync(root, { recursive: true, force: true }); +}); diff --git a/src/proxy.ts b/src/proxy.ts index 1171cc71..9294a0c6 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -20,6 +20,7 @@ import { compressToolDefinition } from "./compress/tool-description.js"; import { resolveGatewayConfig } from "./config.js"; import type { ProfileConfig, ResolvedGatewayConfig } from "./config.js"; import { allLocalTools, callLocalTool, localToolsFor } from "./local-tools.js"; +import { callWorkflowCommandTool, workflowCommandTools, workflowCommandToolsFor } from "./workflow/commands/mcp-tools.js"; import type { Logger } from "./logging.js"; import { InMemoryArtifactStore } from "./retrieve.js"; import type { ArtifactStore } from "./retrieve.js"; @@ -71,7 +72,7 @@ function prepareUpstreamToolDefinition(upstreamName: string, tool: Tool): Tool { } function gatewayToolRisk(name: string): ToolRisk { - const definition = [...allLocalTools, ...adaptiveTools, ...brokerTools, ...codeSearchTools, retrieveTool] + const definition = [...allLocalTools, ...workflowCommandTools, ...adaptiveTools, ...brokerTools, ...codeSearchTools, retrieveTool] .find((tool) => tool.name === name); return riskOf(definition?.annotations); } @@ -128,7 +129,7 @@ export function registerProxyHandlers( const entries = (await catalog()).tools().filter((entry) => profileAllows(entry, activeProfile)); const tools = entries.map((entry) => prepareUpstreamToolDefinition(entry.provider, entry.definition)); // brokered tool は profile に関わらず常に出す。絞り込みは既定の面を減らすためで、到達手段を奪わない。 - const gatewayTools = [...localToolsFor(gatewayConfig), ...adaptiveTools, ...brokerTools, ...codeSearchTools, retrieveTool] + const gatewayTools = [...localToolsFor(gatewayConfig), ...workflowCommandToolsFor(gatewayConfig), ...adaptiveTools, ...brokerTools, ...codeSearchTools, retrieveTool] .map(compressVisibleToolDefinition); return { tools: [...tools, ...gatewayTools] }; }); @@ -157,6 +158,7 @@ export function registerProxyHandlers( const toolName = request.params.name; const { metadata, forwardedArguments } = extractCallerMetadata(request.params.arguments); const isLocal = toolName === RETRIEVE_TOOL_NAME || localToolsFor(gatewayConfig).some((tool) => tool.name === toolName); + const isWorkflowCommand = workflowCommandToolsFor(gatewayConfig).some((tool) => tool.name === toolName); const isAdaptive = isAdaptiveTool(toolName); const requestId = metadata === undefined ? undefined : await openRequest(metadata); const capability = metadata === undefined @@ -179,11 +181,11 @@ export function registerProxyHandlers( }); } - await authorize(toolName, isLocal, isAdaptive); + await authorize(toolName, isLocal || isWorkflowCommand, isAdaptive); let dispatched: ExecutionOutcome; try { - dispatched = await dispatch(toolName, forwardedArguments, isLocal, isAdaptive, capability); + dispatched = await dispatch(toolName, forwardedArguments, isLocal, isWorkflowCommand, isAdaptive, capability); } catch (error) { const selected = toolName.includes(SEP) ? splitPrefixedName(toolName) : undefined; await record(selected === undefined @@ -222,7 +224,7 @@ export function registerProxyHandlers( // brokered search/describe は structured を返し、brokered call は upstream 結果をそのまま返す。 return requestId === undefined ? finalOutcome.result - : withRequestId(finalOutcome.result, requestId, isLocal || isAdaptive || isBrokerTool(toolName) || isCodeSearchTool(toolName)); + : withRequestId(finalOutcome.result, requestId, isLocal || isWorkflowCommand || isAdaptive || isBrokerTool(toolName) || isCodeSearchTool(toolName)); }); async function authorize(toolName: string, isLocal: boolean, isAdaptive: boolean): Promise { @@ -245,6 +247,7 @@ export function registerProxyHandlers( toolName: string, args: Record | undefined, isLocal: boolean, + isWorkflowCommand: boolean, isAdaptive: boolean, capability: string | undefined, ): Promise { @@ -291,6 +294,17 @@ export function registerProxyHandlers( }); } + if (isWorkflowCommand) { + const result = await callWorkflowCommandTool(toolName, args, gatewayConfig); + return normalizeExecutionOutcome({ + result, + selectedProvider: "local", + selectedTool: toolName, + capability: capability ?? "local", + risk: gatewayToolRisk(toolName), + }); + } + if (isBrokerTool(toolName)) { const dispatched = await dispatchBrokerTool(toolName, args, { ...upstreamCall, catalog, activeProfile, gatewayConfig }); if (dispatched.outcome !== undefined) return dispatched.outcome; diff --git a/src/workflow/commands/mcp-tools.test.ts b/src/workflow/commands/mcp-tools.test.ts new file mode 100644 index 00000000..97f9f673 --- /dev/null +++ b/src/workflow/commands/mcp-tools.test.ts @@ -0,0 +1,203 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { ResolvedGatewayConfig } from "../../config.js"; +import { callWorkflowCommandTool, workflowCommandTools, workflowCommandToolsFor } from "./mcp-tools.js"; +import { WorkflowSqliteStateStore } from "../state/sqlite-store.js"; + +function structured(result: CallToolResult): Record { + assert.ok(result.structuredContent); + return result.structuredContent as Record; +} + +async function gitWorkspace(): Promise<{ root: string; config: ResolvedGatewayConfig }> { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "mottainai-workflow-mcp-tools-")); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: root }); + execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: root }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: root }); + await fs.writeFile(path.join(root, "file.txt"), "hello\n"); + execFileSync("git", ["add", "."], { cwd: root }); + execFileSync("git", ["commit", "-q", "-m", "initial"], { cwd: root }); + const config: ResolvedGatewayConfig = { + workspaceRoot: root, defaultTimeoutMs: 1_000, maxTimeoutMs: 2_000, maxOutputBytes: 1024, execTargetTokens: 1_000, + resultTtlMs: 10_000, resultMaxEntries: 10, capabilityMap: {}, toolMetadata: {}, tokenBudgets: { tools: {}, capabilities: {}, profiles: {} }, + workflowTasks: false, + }; + return { root, config }; +} + +function enabled(config: ResolvedGatewayConfig): ResolvedGatewayConfig { + return { ...config, workflowTasks: true }; +} + +function openWorkflowStore(): WorkflowSqliteStateStore { + const store = new WorkflowSqliteStateStore({ dbPath: ":memory:" }); + store.init(); + return store; +} + +// --- gating: the whole family is hidden and rejected unless workflowTasks is set --- + +test("workflowCommandToolsFor returns nothing unless workflowTasks is configured", async () => { + const { root, config } = await gitWorkspace(); + assert.deepEqual(workflowCommandToolsFor(config), []); + const names = workflowCommandToolsFor(enabled(config)).map((tool) => tool.name); + assert.deepEqual(names.sort(), [ + "mottainai_workflow_policy_explain", + "mottainai_workflow_task_start", + "mottainai_workflow_task_status", + ].sort()); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("every tool in workflowCommandTools is reachable through workflowCommandToolsFor once enabled", async () => { + const { root, config } = await gitWorkspace(); + const advertised = new Set(workflowCommandToolsFor(enabled(config)).map((tool) => tool.name)); + for (const tool of workflowCommandTools) assert.ok(advertised.has(tool.name)); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("each workflow command tool throws when workflowTasks is not configured", async () => { + const { root, config } = await gitWorkspace(); + await assert.rejects( + () => callWorkflowCommandTool("mottainai_workflow_policy_explain", {}, config), + /workflow command tools are not configured/, + ); + await assert.rejects( + () => callWorkflowCommandTool("mottainai_workflow_task_start", { taskSlug: "example" }, config), + /workflow command tools are not configured/, + ); + await assert.rejects( + () => callWorkflowCommandTool("mottainai_workflow_task_status", {}, config), + /workflow command tools are not configured/, + ); + await fs.rm(root, { recursive: true, force: true }); +}); + +// --- mottainai_workflow_policy_explain --- + +test("policy_explain reports the standard preset by default, with authority=preset on its rules", async () => { + const { root, config } = await gitWorkspace(); + const result = structured(await callWorkflowCommandTool("mottainai_workflow_policy_explain", {}, enabled(config))); + assert.equal(result.status, "success"); + assert.equal(result.preset, "standard"); + assert.equal(result.policySourceAuthority, "preset"); + const rules = result.rules as { protectedBranchRule: { directPush: { mode: string; authority: string } } }; + assert.equal(rules.protectedBranchRule.directPush.mode, "enforce"); + assert.equal(rules.protectedBranchRule.directPush.authority, "preset"); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("policy_explain fails closed on a corrupted .mottainai/workflow.json", async () => { + const { root, config } = await gitWorkspace(); + await fs.mkdir(path.join(root, ".mottainai"), { recursive: true }); + await fs.writeFile(path.join(root, ".mottainai", "workflow.json"), "{ not json"); + const result = structured(await callWorkflowCommandTool("mottainai_workflow_policy_explain", {}, enabled(config))); + assert.equal(result.status, "failed"); + await fs.rm(root, { recursive: true, force: true }); +}); + +// --- mottainai_workflow_task_start / mottainai_workflow_task_status --- + +test("task_start rejects an invalid taskSlug at the MCP boundary", async () => { + const { root, config } = await gitWorkspace(); + const store = openWorkflowStore(); + await assert.rejects( + () => callWorkflowCommandTool("mottainai_workflow_task_start", { taskSlug: "Bad Slug" }, enabled(config), store), + /invalid taskSlug/, + ); + store.close(); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("task_start rejects an invalid issueRef at the MCP boundary", async () => { + const { root, config } = await gitWorkspace(); + const store = openWorkflowStore(); + await assert.rejects( + () => callWorkflowCommandTool("mottainai_workflow_task_start", { taskSlug: "ok", issueRef: "../evil" }, enabled(config), store), + /invalid issueRef/, + ); + store.close(); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("task_start always creates a dedicated worktree/branch (never main itself), and task_status reports it only from inside that worktree", async () => { + const { root, config } = await gitWorkspace(); + const store = openWorkflowStore(); + + const started = structured(await callWorkflowCommandTool( + "mottainai_workflow_task_start", { taskSlug: "example", issueRef: "9" }, enabled(config), store, + )); + assert.equal(started.status, "success"); + const worktree = started.worktree as { branchName: string; canonicalPath: string }; + assert.equal(worktree.branchName, "issue-9/example"); + assert.notEqual(worktree.branchName, "main"); + + const statusFromMainCheckout = structured(await callWorkflowCommandTool( + "mottainai_workflow_task_status", {}, enabled(config), store, + )); + assert.equal(statusFromMainCheckout.status, "success"); + assert.equal(statusFromMainCheckout.active, false); + + const statusFromWorktree = structured(await callWorkflowCommandTool( + "mottainai_workflow_task_status", {}, enabled({ ...config, workspaceRoot: worktree.canonicalPath }), store, + )); + assert.equal(statusFromWorktree.active, true); + assert.equal((statusFromWorktree.task as { taskId: string }).taskId, (started.task as { taskId: string }).taskId); + + store.close(); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("task_status reports no active task as a normal, structured outcome (not an error)", async () => { + const { root, config } = await gitWorkspace(); + const store = openWorkflowStore(); + const status = structured(await callWorkflowCommandTool("mottainai_workflow_task_status", {}, enabled(config), store)); + assert.equal(status.status, "success"); + assert.equal(status.active, false); + assert.deepEqual(status.warnings, []); + store.close(); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("task_start rejects starting a second task from inside its own already-active worktree (policy-driven rejection path)", async () => { + const { root, config } = await gitWorkspace(); + const store = openWorkflowStore(); + const started = structured(await callWorkflowCommandTool( + "mottainai_workflow_task_start", { taskSlug: "outer" }, enabled(config), store, + )); + const worktree = started.worktree as { canonicalPath: string }; + + const second = structured(await callWorkflowCommandTool( + "mottainai_workflow_task_start", { taskSlug: "inner" }, enabled({ ...config, workspaceRoot: worktree.canonicalPath }), store, + )); + assert.equal(second.status, "failed"); + assert.equal(second.reason, "active-task-in-workspace"); + + store.close(); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("task_start fails closed on a corrupted .mottainai/workflow.json instead of silently falling back to a preset", async () => { + const { root, config } = await gitWorkspace(); + await fs.mkdir(path.join(root, ".mottainai"), { recursive: true }); + await fs.writeFile(path.join(root, ".mottainai", "workflow.json"), "{ not json"); + const store = openWorkflowStore(); + const result = structured(await callWorkflowCommandTool( + "mottainai_workflow_task_start", { taskSlug: "example" }, enabled(config), store, + )); + assert.equal(result.status, "failed"); + assert.equal(result.reason, "invalid-policy"); + store.close(); + await fs.rm(root, { recursive: true, force: true }); +}); + +test("unknown tool name throws", async () => { + const { root, config } = await gitWorkspace(); + await assert.rejects(() => callWorkflowCommandTool("mottainai_workflow_nonexistent", {}, enabled(config))); + await fs.rm(root, { recursive: true, force: true }); +}); diff --git a/src/workflow/commands/mcp-tools.ts b/src/workflow/commands/mcp-tools.ts new file mode 100644 index 00000000..feb2197d --- /dev/null +++ b/src/workflow/commands/mcp-tools.ts @@ -0,0 +1,185 @@ +import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js"; +import type { ResolvedGatewayConfig } from "../../config.js"; +import { OUTPUT_SCHEMA, output } from "../../envelope.js"; +import { getTaskStatusForWorkspace, startTask } from "../domain/task.js"; +import { explainWorkflowPolicy } from "../policy/explain.js"; +import { resolveEffectiveWorkflowPolicy } from "../policy/load.js"; +import type { WorkflowStateStore } from "../state/store.js"; + +/** + * Early dogfooding exposure of the Git workflow engine (Issue #34, Child Issue 9a-1's + * thin precursor). `mottainai_workflow_policy_explain` / `mottainai_workflow_task_start` / + * `mottainai_workflow_task_status` — following the same `Tool[]` + dispatch-function + * pattern as `src/local-tools.ts`, but kept in their own module since this family has + * its own gating (`config.workflowTasks`) and its own state dependency + * (`WorkflowStateStore`) that the rest of `src/local-tools.ts` doesn't need. + * + * No enforcement is wired to these tools beyond what `src/workflow/domain/task.ts` + * itself already does — this is observation/dogfooding only, per Issue #34's Non-goals + * (no commit/push/PR/cleanup exposure, no protected-branch write-blocking here). + */ + +const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }; + +const policyExplainTool: Tool = { + name: "mottainai_workflow_policy_explain", + description: "Explain the effective Git workflow policy for this workspace: for each protected-branch/worktree/cleanup rule, the resolved mode, which authority (preset vs. repository) set it, and whether it can still be weakened. Side-effect free.", + inputSchema: { type: "object", properties: {} }, + outputSchema: OUTPUT_SCHEMA, + annotations: readOnly, +}; + +const taskStartTool: Tool = { + name: "mottainai_workflow_task_start", + description: "Start a Git workflow task: reserve it under Mottainai's task lifecycle, always create a dedicated worktree and branch off the current branch (never the current branch itself), and activate it.", + inputSchema: { type: "object", properties: { + taskSlug: { type: "string" }, issueRef: { type: "string" }, + }, required: ["taskSlug"] }, + outputSchema: OUTPUT_SCHEMA, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, +}; + +const taskStatusTool: Tool = { + name: "mottainai_workflow_task_status", + description: "Report the active Git workflow task (if any) for the current worktree: task id, lifecycle state, repository/worktree identity, branch, and guardrail warnings. Side-effect free.", + inputSchema: { type: "object", properties: {} }, + outputSchema: OUTPUT_SCHEMA, + annotations: readOnly, +}; + +export const workflowCommandTools: Tool[] = [policyExplainTool, taskStartTool, taskStatusTool]; + +/** `config.workflowTasks` 未設定のワークスペースではこのファミリー全体を公開しない + * (worktree 作成等の副作用を持つため既定非公開。`mottainai_worktree_new` と同じ姿勢)。 */ +export function workflowCommandToolsFor(config: ResolvedGatewayConfig): Tool[] { + return config.workflowTasks ? workflowCommandTools : []; +} + +export function isWorkflowCommandTool(name: string): boolean { + return workflowCommandTools.some((tool) => tool.name === name); +} + +type Args = Record | undefined; + +function value(args: Args, key: string): unknown { + return args?.[key]; +} +function stringArg(args: Args, key: string, required = false): string | undefined { + const candidate = value(args, key); + if (candidate === undefined && !required) return undefined; + if (typeof candidate !== "string" || (required && candidate.length === 0)) throw new Error(`${key} must be a non-empty string`); + return candidate; +} + +const TASK_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]*$/; +const ISSUE_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +function requireWorkflowTasksConfigured(config: ResolvedGatewayConfig): void { + if (!config.workflowTasks) throw new Error("workflow command tools are not configured for this workspace"); +} + +function policyExplainToolImpl(config: ResolvedGatewayConfig): CallToolResult { + requireWorkflowTasksConfigured(config); + const result = explainWorkflowPolicy(config.workspaceRoot); + if (!result.ok) { + const summary = `FAIL policy_explain: invalid workflow policy (${result.reason})`; + return output("workflow_policy_explain", "failed", summary, "", { diagnostics: [{ severity: "error", message: result.reason }] }, true); + } + const summary = `OK preset=${result.explained.preset ?? "(none)"} authority=${result.explained.policySourceAuthority}`; + return output("workflow_policy_explain", "success", summary, "", { + policySourceAuthority: result.explained.policySourceAuthority, + policyFilePath: result.explained.policyFilePath, + preset: result.explained.preset, + descriptive: result.explained.descriptive, + rules: result.explained.rules, + }); +} + +async function taskStartToolImpl(args: Args, config: ResolvedGatewayConfig, store: WorkflowStateStore): Promise { + requireWorkflowTasksConfigured(config); + const taskSlug = stringArg(args, "taskSlug", true)!; + if (!TASK_SLUG_PATTERN.test(taskSlug)) throw new Error(`invalid taskSlug: ${taskSlug} (use lowercase, digits, hyphens)`); + const issueRef = stringArg(args, "issueRef"); + if (issueRef !== undefined && !ISSUE_REF_PATTERN.test(issueRef)) throw new Error(`invalid issueRef: ${issueRef}`); + + const policyResult = resolveEffectiveWorkflowPolicy(config.workspaceRoot); + if (!policyResult.ok) { + const summary = `FAIL task_start: invalid workflow policy (${policyResult.reason})`; + return output("workflow_task_start", "failed", summary, "", { reason: "invalid-policy", diagnostics: [{ severity: "error", message: policyResult.reason }] }, true); + } + + // `skipWorktree` を渡さない — policy.worktree.required に関わらず常に専用 worktree/branch + // を作らせる(task lifecycle の目的そのものが「今どの worktree/branch にいるか」の追跡であり、 + // 現在の branch(main を含む)をそのまま work branch にすることは決して起きない)。 + const result = await startTask({ workspaceRoot: config.workspaceRoot, store, policy: policyResult.document, taskSlug, issueRef }); + if (!result.ok) { + const summary = `FAIL task_start (${result.reason}): ${result.detail}`; + return output("workflow_task_start", "failed", summary, "", { reason: result.reason, diagnostics: [{ severity: "error", message: result.detail }] }, true); + } + + const summary = `OK task=${result.task.taskId} state=${result.task.lifecycleState} branch=${result.worktree?.branchName ?? "(none)"}`; + return output("workflow_task_start", "success", summary, "", { + task: result.task, + worktree: result.worktree, + warnings: result.warnings, + }); +} + +async function taskStatusToolImpl(config: ResolvedGatewayConfig, store: WorkflowStateStore): Promise { + requireWorkflowTasksConfigured(config); + const result = await getTaskStatusForWorkspace(config.workspaceRoot, store); + if (!result.ok) { + const summary = `FAIL task_status: ${result.reason}`; + return output("workflow_task_status", "failed", summary, "", { diagnostics: [{ severity: "error", message: result.reason }] }, true); + } + + const repository = { instanceId: result.instanceId, worktreePath: result.worktreePath, branch: result.branch, repoStateKind: result.repoStateKind }; + if (!result.active) { + const summary = `OK no active task at ${result.worktreePath}`; + return output("workflow_task_status", "success", summary, "", { active: false, repository, warnings: result.warnings }); + } + + const summary = `OK task=${result.status.task.taskId} state=${result.status.task.lifecycleState} branch=${result.branch ?? "(detached)"}`; + return output("workflow_task_status", "success", summary, "", { + active: true, + repository, + task: result.status.task, + worktrees: result.status.worktrees, + allowedNextTransitions: result.status.allowedNextTransitions, + warnings: result.warnings, + }); +} + +/** + * 既定の `WorkflowStateStore`。プロセス内で一度だけ生成する module-level singleton + * (lazy — 呼ばれるまで DB ファイルを開かない)。`src/state/*` の SqliteStateStore と + * 同じ DB ファイル・パス解決を共有する(`src/workflow/state/sqlite-store.ts` 参照)。 + * テストは `callWorkflowCommandTool` の `workflowStore` 引数に独自インスタンス + * (`:memory:` 等)を渡すことでこの singleton を迂回できる。 + * + * `node:sqlite` の import は Node が `ExperimentalWarning` を stderr に一度だけ出す副作用を + * 持つため、`workflowTasks` を使わない起動(CLI init 等、stdout/stderr の厳密な契約がある + * 経路を含む)にまで static import で持ち込まない — 実際にこのツールが呼ばれたときだけ + * dynamic import する。 + */ +let defaultWorkflowStoreInstance: WorkflowStateStore | undefined; +export async function defaultWorkflowStore(): Promise { + if (defaultWorkflowStoreInstance === undefined) { + const { WorkflowSqliteStateStore } = await import("../state/sqlite-store.js"); + const created = new WorkflowSqliteStateStore(); + created.init(); + defaultWorkflowStoreInstance = created; + } + return defaultWorkflowStoreInstance; +} + +export async function callWorkflowCommandTool( + name: string, args: Args, config: ResolvedGatewayConfig, workflowStore?: WorkflowStateStore, +): Promise { + switch (name) { + case "mottainai_workflow_policy_explain": return policyExplainToolImpl(config); + case "mottainai_workflow_task_start": return taskStartToolImpl(args, config, workflowStore ?? await defaultWorkflowStore()); + case "mottainai_workflow_task_status": return taskStatusToolImpl(config, workflowStore ?? await defaultWorkflowStore()); + default: throw new Error(`Unknown workflow command tool: ${name}`); + } +} diff --git a/src/workflow/domain/task.test.ts b/src/workflow/domain/task.test.ts index f6b5f268..e6b01e77 100644 --- a/src/workflow/domain/task.test.ts +++ b/src/workflow/domain/task.test.ts @@ -8,7 +8,7 @@ import { test } from "node:test"; import { BUILTIN_PRESETS } from "../policy/presets.js"; import type { WorkflowPolicyDocument } from "../policy/schema.js"; import { WorkflowSqliteStateStore } from "../state/sqlite-store.js"; -import { checkStaleBaseBranch, getTaskStatus, startTask, transitionTask } from "./task.js"; +import { checkStaleBaseBranch, getTaskStatus, getTaskStatusForWorkspace, startTask, transitionTask } from "./task.js"; function git(args: string[], cwd: string): string { return execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); @@ -248,6 +248,130 @@ test("getTaskStatus returns undefined for an unknown task id", (t) => { assert.equal(getTaskStatus(store, "does-not-exist" as never), undefined); }); +test("startTask rejects starting a second task from inside an already-active task worktree", async (t) => { + const root = initRepo(t); + const store = openStore(t); + const policy = standardPolicy(); + const outer = await startTask({ workspaceRoot: root, store, policy, taskSlug: "outer" }); + assert.equal(outer.ok, true); + if (!outer.ok) return; + assert.ok(outer.worktree !== undefined); + + const inner = await startTask({ workspaceRoot: outer.worktree!.canonicalPath, store, policy, taskSlug: "inner" }); + assert.equal(inner.ok, false); + if (inner.ok) return; + assert.equal(inner.reason, "active-task-in-workspace"); + assert.match(inner.detail, new RegExp(outer.task.taskId)); +}); + +test("getTaskStatusForWorkspace reports no active task for a plain repository", async (t) => { + const root = initRepo(t); + const store = openStore(t); + const status = await getTaskStatusForWorkspace(root, store); + assert.equal(status.ok, true); + if (!status.ok) return; + assert.equal(status.active, false); + assert.equal(status.branch, "main"); + assert.deepEqual(status.warnings, []); +}); + +test("getTaskStatusForWorkspace reports the active task from inside its own worktree", async (t) => { + const root = initRepo(t); + const store = openStore(t); + const started = await startTask({ workspaceRoot: root, store, policy: standardPolicy(), taskSlug: "status-ws" }); + assert.equal(started.ok, true); + if (!started.ok) return; + + const status = await getTaskStatusForWorkspace(started.worktree!.canonicalPath, store); + assert.equal(status.ok, true); + if (!status.ok) return; + assert.equal(status.active, true); + if (!status.active) return; + assert.equal(status.status.task.taskId, started.task.taskId); + assert.equal(status.branch, started.worktree?.branchName); +}); + +test("getTaskStatusForWorkspace surfaces detached HEAD as a warning instead of failing (no active task is a normal outcome)", async (t) => { + const root = initRepo(t); + const headCommit = git(["rev-parse", "HEAD"], root); + git(["checkout", "--quiet", headCommit], root); + const store = openStore(t); + const status = await getTaskStatusForWorkspace(root, store); + assert.equal(status.ok, true); + if (!status.ok) return; + assert.equal(status.active, false); + assert.equal(status.warnings.length, 1); + assert.match(status.warnings[0].code, /detached-head/); +}); + +test("getTaskStatusForWorkspace fails closed for a non-git directory", async (t) => { + const dir = tmpDir(t, "mottainai-task-test-nongit-"); + const store = openStore(t); + const status = await getTaskStatusForWorkspace(dir, store); + assert.equal(status.ok, false); +}); + +test("getTaskStatusForWorkspace keeps two repositories' active tasks separate in a shared store", async (t) => { + const rootA = initRepo(t); + const rootB = initRepo(t); + const store = openStore(t); + const startedA = await startTask({ workspaceRoot: rootA, store, policy: standardPolicy(), taskSlug: "repo-a-task" }); + assert.equal(startedA.ok, true); + if (!startedA.ok) return; + + const statusB = await getTaskStatusForWorkspace(rootB, store); + assert.equal(statusB.ok, true); + if (!statusB.ok) return; + assert.equal(statusB.active, false); + + const statusA = await getTaskStatusForWorkspace(startedA.worktree!.canonicalPath, store); + assert.equal(statusA.ok, true); + if (!statusA.ok) return; + assert.equal(statusA.active, true); +}); + +test("getTaskStatusForWorkspace distinguishes between two active worktrees of the same repository", async (t) => { + const root = initRepo(t); + const store = openStore(t); + const policy = standardPolicy({ multipleActiveTasksPerIssue: "advisory" }); + const first = await startTask({ workspaceRoot: root, store, policy, taskSlug: "multi-a" }); + const second = await startTask({ workspaceRoot: root, store, policy, taskSlug: "multi-b" }); + assert.equal(first.ok, true); + assert.equal(second.ok, true); + if (!first.ok || !second.ok) return; + + const statusFirst = await getTaskStatusForWorkspace(first.worktree!.canonicalPath, store); + const statusSecond = await getTaskStatusForWorkspace(second.worktree!.canonicalPath, store); + assert.equal(statusFirst.ok, true); + assert.equal(statusSecond.ok, true); + if (!statusFirst.ok || !statusSecond.ok || !statusFirst.active || !statusSecond.active) return; + assert.equal(statusFirst.status.task.taskId, first.task.taskId); + assert.equal(statusSecond.status.task.taskId, second.task.taskId); + assert.notEqual(statusFirst.status.task.taskId, statusSecond.status.task.taskId); +}); + +test("getTaskStatusForWorkspace survives a store restart against a file-backed database", async (t) => { + const root = initRepo(t); + const dbDir = tmpDir(t, "mottainai-task-test-db-"); + const dbPath = path.join(dbDir, "state.sqlite3"); + const store1 = new WorkflowSqliteStateStore({ dbPath }); + store1.init(); + const started = await startTask({ workspaceRoot: root, store: store1, policy: standardPolicy(), taskSlug: "restart-check" }); + assert.equal(started.ok, true); + if (!started.ok) return; + store1.close(); + + const store2 = new WorkflowSqliteStateStore({ dbPath }); + store2.init(); + t.after(() => store2.close()); + const status = await getTaskStatusForWorkspace(started.worktree!.canonicalPath, store2); + assert.equal(status.ok, true); + if (!status.ok) return; + assert.equal(status.active, true); + if (!status.active) return; + assert.equal(status.status.task.taskId, started.task.taskId); +}); + test("transitionTask applies a valid transition and rejects an invalid one with structured blocker info", async (t) => { const root = initRepo(t); const store = openStore(t); diff --git a/src/workflow/domain/task.ts b/src/workflow/domain/task.ts index 1c93db63..da0a9663 100644 --- a/src/workflow/domain/task.ts +++ b/src/workflow/domain/task.ts @@ -6,7 +6,9 @@ import type { WorkflowStateStore, TaskId, TaskRecord, WorktreeRecord } from "../ import { buildWorktreeNaming, createWorktree, decideBootstrap, detectWorktreeCollisions, runBootstrap } from "../git/worktree.js"; import type { BootstrapDecision, RunBootstrapResult } from "../git/worktree.js"; import { resolveRepositoryIdentity } from "./identity.js"; +import type { RepositoryInstanceId } from "./identity.js"; import { resolveRepoState } from "./repo-state.js"; +import type { RepoStateKind } from "./repo-state.js"; import { validateTransition, allowedNextTransitions } from "./lifecycle.js"; import type { LifecycleState, TransitionBlockedInfo } from "./lifecycle.js"; @@ -96,6 +98,7 @@ export type StartTaskFailureReason = | "issue-already-claimed" | "branch-collision" | "path-collision" + | "active-task-in-workspace" | "git-worktree-add-failed"; export interface StartTaskWarning { @@ -133,6 +136,23 @@ function allowsMultipleActiveTasksPerIssue(policy: WorkflowPolicyDocument): bool * 予約した行を補償削除する。二重の補償(worktree だけ、または worktree+task の両方)を * 呼び出し順の逆順で行うことで、途中失敗でも DB に reserved のまま取り残さない。 */ +/** instanceId+canonicalWorktreePath に一致する active worktree とその task を探す。 + * 「今いる物理 worktree はすでに別 task が使っているか」を判定する唯一の入口 — + * `startTask` の重複開始拒否と `getTaskStatusForWorkspace` の現在地解決で共有する。 */ +function findActiveTaskAtWorktreePath( + store: WorkflowStateStore, + instanceId: RepositoryInstanceId, + canonicalWorktreePath: string, +): { task: TaskRecord; worktree: WorktreeRecord } | undefined { + const worktree = store + .listWorktreesForInstance(instanceId) + .find((candidate) => candidate.status === "active" && candidate.canonicalPath === canonicalWorktreePath); + if (worktree === undefined) return undefined; + const task = store.getTask(worktree.taskId); + if (task === undefined) return undefined; + return { task, worktree }; +} + export async function startTask(input: StartTaskInput): Promise { const { workspaceRoot, store, policy, taskSlug, issueRef } = input; @@ -148,6 +168,19 @@ export async function startTask(input: StartTaskInput): Promise return { ok: false, reason: "unsupported-repo-state", detail: repoStateResult.state.reason }; } + // 呼び出し元の cwd がそれ自体すでに別 task の active worktree である場合、ここで + // 新規 task を予約すると同じ物理 worktree に矛盾する2つの active task が + // 存在しうる(ネストした worktree を作る、または no-worktree task を重ねる)。 + // policy 判定より前に、無条件で fail-closed に拒否する。 + const conflicting = findActiveTaskAtWorktreePath(store, identityResult.identity.instanceId, identityResult.identity.worktreePath); + if (conflicting !== undefined) { + return { + ok: false, + reason: "active-task-in-workspace", + detail: `this worktree already has an active task (taskId=${conflicting.task.taskId}, worktreeId=${conflicting.worktree.worktreeId}); finish or abandon it before starting another task here`, + }; + } + if ((policy.worktree.issueRequired === "enforce" || policy.worktree.issueRequired === "confirm") && issueRef === undefined) { return { ok: false, reason: "issue-required", detail: `policy.worktree.issueRequired=${policy.worktree.issueRequired} but no issueRef was provided` }; } @@ -323,3 +356,66 @@ export function transitionTask(store: WorkflowStateStore, taskId: TaskId, to: Li if (!validation.allowed) return { ok: false, blocked: validation.blocked }; return { ok: true, task: store.updateTaskLifecycleState(taskId, to) }; } + +export interface WorkspaceGuardrailWarning { + code: string; + detail: string; +} + +/** `getTaskStatusForWorkspace` の cwd 解決結果。task の有無に関わらず常に埋まる、 + * 「今どこにいるか」の基本情報(MCP/CLI 側が task id を知らなくても呼べるための土台)。 */ +interface WorkspaceLocation { + instanceId: RepositoryInstanceId; + worktreePath: string; + branch: string | undefined; + repoStateKind: RepoStateKind; + warnings: WorkspaceGuardrailWarning[]; +} + +export type WorkspaceTaskStatusResult = + | ({ ok: true; active: true; status: TaskStatusResult } & WorkspaceLocation) + | ({ ok: true; active: false } & WorkspaceLocation) + | { ok: false; reason: string }; + +/** + * taskId を持たない呼び出し側(MCP/CLI)のための入口。cwd から repository + * identity・repo state・「この物理 worktree に active task があるか」を副作用なく + * 解決する(`observeRepositoryInstance` は呼ばない — instance/path の観測記録は + * `startTask` の責務であり、`status` は読み取り専用のまま保つ)。 + * + * git/repository の検出自体が失敗した場合(非 git ディレクトリ、git 呼び出しが + * 完走しない等)は `ok: false` で fail-closed にする — 「たぶんこの repository」で + * 推測して続行しない。detached HEAD 等の未サポート状態は `ok: true` のまま + * `warnings` に記録する(task が無いこと自体は正常系のため)。 + */ +export async function getTaskStatusForWorkspace(workspaceRoot: string, store: WorkflowStateStore): Promise { + const identityResult = resolveRepositoryIdentity(workspaceRoot); + if (!identityResult.ok) return { ok: false, reason: identityResult.reason }; + + const repoStateResult = await resolveRepoState(workspaceRoot); + if (!repoStateResult.ok) return { ok: false, reason: repoStateResult.reason }; + + const warnings: WorkspaceGuardrailWarning[] = []; + if (!repoStateResult.state.supported) { + warnings.push({ code: `unsupported-repo-state:${repoStateResult.state.kind}`, detail: repoStateResult.state.reason }); + } + + const location: WorkspaceLocation = { + instanceId: identityResult.identity.instanceId, + worktreePath: identityResult.identity.worktreePath, + branch: repoStateResult.state.branch, + repoStateKind: repoStateResult.state.kind, + warnings, + }; + + const found = findActiveTaskAtWorktreePath(store, identityResult.identity.instanceId, identityResult.identity.worktreePath); + if (found === undefined) { + return { ok: true, active: false, ...location }; + } + + const status = getTaskStatus(store, found.task.taskId); + if (status === undefined) { + return { ok: false, reason: `active worktree ${found.worktree.worktreeId} references task ${found.task.taskId}, which is missing from the store` }; + } + return { ok: true, active: true, status, ...location }; +} diff --git a/src/workflow/policy/explain.test.ts b/src/workflow/policy/explain.test.ts new file mode 100644 index 00000000..c4b3c43c --- /dev/null +++ b/src/workflow/policy/explain.test.ts @@ -0,0 +1,81 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { explainWorkflowPolicy } from "./explain.js"; +import { getPreset } from "./presets.js"; +import { resolveWorkflowPolicyPath } from "./load.js"; + +function workspaceWithPolicy(content: string | undefined): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-policy-explain-test-")); + if (content !== undefined) { + const filePath = resolveWorkflowPolicyPath(root); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, content); + } + return root; +} + +test("explainWorkflowPolicy falls back to the standard preset when no file exists, with authority=preset throughout", () => { + const root = workspaceWithPolicy(undefined); + const result = explainWorkflowPolicy(root); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.explained.policySourceAuthority, "preset"); + assert.equal(result.explained.preset, "standard"); + const standard = getPreset("standard"); + assert.equal(result.explained.rules.protectedBranchRule.directPush.mode, standard.protectedBranchRule.directPush); + assert.equal(result.explained.rules.protectedBranchRule.directPush.authority, "preset"); + assert.deepEqual(result.explained.descriptive.protectedBranches, standard.protectedBranches); + assert.equal(result.explained.descriptive.stagingMode, standard.stagingMode); + assert.equal(result.explained.descriptive.bootstrapMode, standard.worktree.bootstrapMode); +}); + +test("explainWorkflowPolicy without a declared preset treats the file as the sole repository-authority source", () => { + const document = { ...getPreset("minimal"), preset: undefined }; + const root = workspaceWithPolicy(JSON.stringify(document)); + const result = explainWorkflowPolicy(root); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.explained.policySourceAuthority, "repository"); + assert.equal(result.explained.rules.cleanup.forceCleanup.authority, "repository"); + assert.equal(result.explained.rules.cleanup.forceCleanup.mode, "off"); +}); + +test("explainWorkflowPolicy strengthening a declared preset's rule is reflected with authority=repository", () => { + const document = { + ...getPreset("standard"), + protectedBranchRule: { ...getPreset("standard").protectedBranchRule, sourceWrite: "enforce" }, + }; + const root = workspaceWithPolicy(JSON.stringify(document)); + const result = explainWorkflowPolicy(root); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(getPreset("standard").protectedBranchRule.sourceWrite, "advisory"); + assert.equal(result.explained.rules.protectedBranchRule.sourceWrite.mode, "enforce"); + assert.equal(result.explained.rules.protectedBranchRule.sourceWrite.authority, "repository"); +}); + +test("explainWorkflowPolicy rejects weakening a declared preset's enforce rule (no humanApproval channel exists yet)", () => { + const document = { + ...getPreset("strict-worktree"), + worktree: { ...getPreset("strict-worktree").worktree, required: "off" }, + }; + const root = workspaceWithPolicy(JSON.stringify(document)); + const result = explainWorkflowPolicy(root); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(getPreset("strict-worktree").worktree.required, "enforce"); + // ファイル自身は "off" を指定しているが、宣言した preset (strict-worktree) の enforce は + // human approval なしに弱体化できないため、resolveRule() は preset 側を採用したままになる。 + assert.equal(result.explained.rules.worktree.required.mode, "enforce"); + assert.equal(result.explained.rules.worktree.required.authority, "preset"); +}); + +test("explainWorkflowPolicy fails closed on a corrupted policy file instead of silently falling back to a preset", () => { + const root = workspaceWithPolicy("{not valid json"); + const result = explainWorkflowPolicy(root); + assert.equal(result.ok, false); + assert.match(result.ok === false ? result.reason : "", /invalid JSON/); +}); diff --git a/src/workflow/policy/explain.ts b/src/workflow/policy/explain.ts new file mode 100644 index 00000000..39f274f4 --- /dev/null +++ b/src/workflow/policy/explain.ts @@ -0,0 +1,139 @@ +import { loadWorkflowPolicy } from "./load.js"; +import { getPreset } from "./presets.js"; +import { resolveRule } from "./resolve.js"; +import type { PolicySource, ResolvedRule } from "./resolve.js"; +import type { RuleMode, WorkflowPolicyDocument, WorktreeRule } from "./schema.js"; + +/** + * `policy explain`(Issue #34)。`resolve.ts`(Child Issue 1)の resolveRule() を、 + * schema.ts の実際の RuleMode フィールド(protectedBranchRule.* / worktree.{required, + * issueRequired,multipleActiveTasksPerIssue,multipleWorktreesPerTask,staleBaseBranch} / + * cleanup.*)だけに適用する。これらは値そのものが RuleMode("off"/"advisory"/ + * "enforce"/"confirm")で、強さも兼ねる — resolveRule() の Value=RuleMode としてそのまま + * 解決できる。 + * + * `protectedBranches`(string[])・`controlPlaneRole`・`stagingMode`・ + * `worktree.bootstrapMode` は設定値であって RuleMode を持たない + * (schema.ts にも対応する mode フィールドが存在しない)。`ResolvedPolicy` の型は + * 全フィールドを `ResolvedRule` として扱える形をしているが、無理に + * authority/weakening を捏造せず `descriptive` として値だけ返す — 実在しない + * 意味論を作らない。将来これらにも authority/weakening が schema に追加された時点で + * `rules` 側に昇格する。 + * + * authority: `.mottainai/workflow.json` が `preset` を宣言していれば、その preset の + * 値を "preset" authority、ファイル自身の値を "repository" authority として渡す + * (宣言した preset からの弱体化は、humanApproval を記録する仕組みが schema に無いため + * 常に拒否される — resolveRule() の設計通り)。`preset` 未宣言ならファイル自身のみを + * "repository" として扱う。ファイルが無ければ built-in `standard` preset のみを + * "preset" として使う(`resolveEffectiveWorkflowPolicy` と同じ既定 fallback)。 + * + * 注意: `startTask`/`getTaskStatusForWorkspace` はこの解決結果を使わず、実効 + * document(`resolveEffectiveWorkflowPolicy`)をそのまま渡す。ここでの + * authority/weakening 判定は現時点では `policy explain` の表示専用であり、 + * task 開始の実際の許可判定を変更するものではない。 + */ + +const PROTECTED_BRANCH_RULE_KEYS = ["sourceWrite", "stage", "commit", "directPush", "forcePush", "destructiveBranchOp"] as const; +const CLEANUP_RULE_KEYS = ["worktreeRemoval", "localBranchDeletion", "remoteBranchDeletion", "worktreePrune", "forceCleanup"] as const; + +export interface ExplainedRuleGroups { + protectedBranchRule: Record<(typeof PROTECTED_BRANCH_RULE_KEYS)[number], ResolvedRule>; + worktree: Record<"required" | "issueRequired" | "multipleActiveTasksPerIssue" | "multipleWorktreesPerTask" | "staleBaseBranch", ResolvedRule>; + cleanup: Record<(typeof CLEANUP_RULE_KEYS)[number], ResolvedRule>; +} + +export interface ExplainedPolicy { + /** どの authority から実効 document が来たか(`preset`宣言が無ければ repository=preset と同値)。 */ + policySourceAuthority: "preset" | "repository"; + policyFilePath: string; + preset: WorkflowPolicyDocument["preset"]; + descriptive: { + protectedBranches: string[]; + controlPlaneRole: WorkflowPolicyDocument["controlPlaneRole"]; + stagingMode: WorkflowPolicyDocument["stagingMode"]; + bootstrapMode: WorktreeRule["bootstrapMode"]; + }; + rules: ExplainedRuleGroups; +} + +export type ExplainWorkflowPolicyResult = { ok: true; explained: ExplainedPolicy } | { ok: false; reason: string }; + +function resolveModeField( + presetDocument: WorkflowPolicyDocument | undefined, + repositoryDocument: WorkflowPolicyDocument | undefined, + select: (document: WorkflowPolicyDocument) => RuleMode, +): ResolvedRule { + const sources: PolicySource[] = []; + if (presetDocument !== undefined) { + const mode = select(presetDocument); + sources.push({ authority: "preset", value: mode, mode }); + } + if (repositoryDocument !== undefined) { + const mode = select(repositoryDocument); + sources.push({ authority: "repository", value: mode, mode }); + } + return resolveRule(sources); +} + +export function explainWorkflowPolicy(workspaceRoot: string): ExplainWorkflowPolicyResult { + const loaded = loadWorkflowPolicy(workspaceRoot); + + let presetDocument: WorkflowPolicyDocument | undefined; + let repositoryDocument: WorkflowPolicyDocument | undefined; + let policySourceAuthority: "preset" | "repository"; + let effective: WorkflowPolicyDocument; + + if (loaded.ok) { + repositoryDocument = loaded.document; + presetDocument = loaded.document.preset === undefined ? undefined : getPreset(loaded.document.preset); + policySourceAuthority = "repository"; + effective = loaded.document; + } else if (loaded.reason === "not-found") { + presetDocument = getPreset("standard"); + policySourceAuthority = "preset"; + effective = presetDocument; + } else { + return { ok: false, reason: loaded.reason }; + } + + const protectedBranchRule = { + sourceWrite: resolveModeField(presetDocument, repositoryDocument, (d) => d.protectedBranchRule.sourceWrite), + stage: resolveModeField(presetDocument, repositoryDocument, (d) => d.protectedBranchRule.stage), + commit: resolveModeField(presetDocument, repositoryDocument, (d) => d.protectedBranchRule.commit), + directPush: resolveModeField(presetDocument, repositoryDocument, (d) => d.protectedBranchRule.directPush), + forcePush: resolveModeField(presetDocument, repositoryDocument, (d) => d.protectedBranchRule.forcePush), + destructiveBranchOp: resolveModeField(presetDocument, repositoryDocument, (d) => d.protectedBranchRule.destructiveBranchOp), + } satisfies ExplainedRuleGroups["protectedBranchRule"]; + + const worktree = { + required: resolveModeField(presetDocument, repositoryDocument, (d) => d.worktree.required), + issueRequired: resolveModeField(presetDocument, repositoryDocument, (d) => d.worktree.issueRequired), + multipleActiveTasksPerIssue: resolveModeField(presetDocument, repositoryDocument, (d) => d.worktree.multipleActiveTasksPerIssue), + multipleWorktreesPerTask: resolveModeField(presetDocument, repositoryDocument, (d) => d.worktree.multipleWorktreesPerTask), + staleBaseBranch: resolveModeField(presetDocument, repositoryDocument, (d) => d.worktree.staleBaseBranch), + } satisfies ExplainedRuleGroups["worktree"]; + + const cleanup = { + worktreeRemoval: resolveModeField(presetDocument, repositoryDocument, (d) => d.cleanup.worktreeRemoval), + localBranchDeletion: resolveModeField(presetDocument, repositoryDocument, (d) => d.cleanup.localBranchDeletion), + remoteBranchDeletion: resolveModeField(presetDocument, repositoryDocument, (d) => d.cleanup.remoteBranchDeletion), + worktreePrune: resolveModeField(presetDocument, repositoryDocument, (d) => d.cleanup.worktreePrune), + forceCleanup: resolveModeField(presetDocument, repositoryDocument, (d) => d.cleanup.forceCleanup), + } satisfies ExplainedRuleGroups["cleanup"]; + + return { + ok: true, + explained: { + policySourceAuthority, + policyFilePath: loaded.filePath, + preset: effective.preset, + descriptive: { + protectedBranches: effective.protectedBranches, + controlPlaneRole: effective.controlPlaneRole, + stagingMode: effective.stagingMode, + bootstrapMode: effective.worktree.bootstrapMode, + }, + rules: { protectedBranchRule, worktree, cleanup }, + }, + }; +} diff --git a/src/workflow/policy/load.test.ts b/src/workflow/policy/load.test.ts index 9aceafa3..435c037d 100644 --- a/src/workflow/policy/load.test.ts +++ b/src/workflow/policy/load.test.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import { test } from "node:test"; import { getPreset } from "./presets.js"; -import { loadWorkflowPolicy, resolveWorkflowPolicyPath } from "./load.js"; +import { loadWorkflowPolicy, resolveEffectiveWorkflowPolicy, resolveWorkflowPolicyPath } from "./load.js"; function workspaceWithPolicy(content: string | undefined): string { const root = fs.mkdtempSync(path.join(os.tmpdir(), "mottainai-workflow-policy-test-")); @@ -67,3 +67,28 @@ test("missing schemaVersion fails closed", () => { assert.equal(result.ok, false); assert.match(result.ok === false ? result.reason : "", /missing schemaVersion/); }); + +test("resolveEffectiveWorkflowPolicy falls back to the standard preset when no file exists", () => { + const root = workspaceWithPolicy(undefined); + const result = resolveEffectiveWorkflowPolicy(root); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.source, "preset"); + assert.deepEqual(result.document, getPreset("standard")); +}); + +test("resolveEffectiveWorkflowPolicy uses the repository file when present", () => { + const root = workspaceWithPolicy(JSON.stringify(getPreset("strict-worktree"))); + const result = resolveEffectiveWorkflowPolicy(root); + assert.equal(result.ok, true); + if (!result.ok) return; + assert.equal(result.source, "repository"); + assert.equal(result.document.preset, "strict-worktree"); +}); + +test("resolveEffectiveWorkflowPolicy fails closed on a corrupted file instead of silently falling back to a preset", () => { + const root = workspaceWithPolicy("{not valid json"); + const result = resolveEffectiveWorkflowPolicy(root); + assert.equal(result.ok, false); + assert.match(result.ok === false ? result.reason : "", /invalid JSON/); +}); diff --git a/src/workflow/policy/load.ts b/src/workflow/policy/load.ts index f6e366a4..98d16fd1 100644 --- a/src/workflow/policy/load.ts +++ b/src/workflow/policy/load.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +import { getPreset } from "./presets.js"; import { POLICY_SCHEMA_VERSION, workflowPolicySchema } from "./schema.js"; import type { WorkflowPolicyDocument } from "./schema.js"; @@ -55,3 +56,27 @@ export function loadWorkflowPolicy(workspaceRoot: string): LoadWorkflowPolicyRes return { ok: true, document: result.data, filePath }; } + +export type ResolveEffectiveWorkflowPolicyResult = + | { ok: true; document: WorkflowPolicyDocument; source: "preset" | "repository"; filePath: string } + | { ok: false; filePath: string; reason: string }; + +/** + * `loadWorkflowPolicy` の「ファイルが無ければ呼び出し側が fallback する」を、実際の + * fallback 先(built-in `standard` preset)まで含めて一箇所に集約したもの。 + * task.start/task.status/CLI 等、素朴に「今使うべき1つの document」だけが欲しい + * 呼び出し側はこちらを使う(`docs/workflow-policy.md` の既定 fallback と同じ)。 + * + * JSON 破損・schemaVersion 不一致等("not-found" 以外の失敗)は fallback せず + * fail-closed で返す — 壊れた policy ファイルを黙って無視して preset で続行しない。 + * + * `policy explain`(`./explain.ts`)は repository の値と、それが宣言した preset の + * 値を別々の authority として resolveRule() に通す必要があるため、この関数は使わず + * `loadWorkflowPolicy` + `getPreset` を直接組み合わせる。 + */ +export function resolveEffectiveWorkflowPolicy(workspaceRoot: string): ResolveEffectiveWorkflowPolicyResult { + const loaded = loadWorkflowPolicy(workspaceRoot); + if (loaded.ok) return { ok: true, document: loaded.document, source: "repository", filePath: loaded.filePath }; + if (loaded.reason === "not-found") return { ok: true, document: getPreset("standard"), source: "preset", filePath: loaded.filePath }; + return { ok: false, filePath: loaded.filePath, reason: loaded.reason }; +}