Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion src/code-search.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}

Expand Down
26 changes: 26 additions & 0 deletions src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
10 changes: 10 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -136,6 +139,7 @@ export interface ResolvedGatewayConfig {
oauthProviderModule?: string;
tokenBudgets: ResolvedTokenBudgets;
worktree?: ResolvedWorktreeConfig;
workflowTasks: boolean;
}

/** 起動時に一度だけ解決した設定。以後の各層は同じ絶対パス基準を共有する。 */
Expand All @@ -155,6 +159,7 @@ const DEFAULT_GATEWAY_CONFIG: Omit<ResolvedGatewayConfig, "workspaceRoot"> = {
capabilityMap: {},
toolMetadata: {},
tokenBudgets: { tools: {}, capabilities: {}, profiles: {} },
workflowTasks: false,
};

export function loadMottainaiConfig(configPath?: string): MottainaiConfig {
Expand Down Expand Up @@ -184,6 +189,7 @@ export function resolveGatewayConfig(
activeProfile: config?.activeProfile,
tokenBudgets: resolveTokenBudgets(config?.tokenBudgets),
worktree: resolveWorktreeConfig(config?.worktree),
workflowTasks: config?.workflowTasks === true,
};
}

Expand Down Expand Up @@ -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"),
Expand All @@ -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,
};
}

Expand Down
153 changes: 145 additions & 8 deletions src/local-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { test } from "node:test";
import { allLocalTools, callLocalTool, localTools, localToolsFor, parseIssueViewOutput, parseRgJson } from "./local-tools.js";
import type { ResolvedGatewayConfig } from "./config.js";
import { InMemoryArtifactStore } from "./retrieve.js";
import { WorkflowSqliteStateStore } from "./workflow/state/sqlite-store.js";

async function workspace(): Promise<{ root: string; config: ResolvedGatewayConfig }> {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "mottainai-local-tools-"));
Expand All @@ -15,7 +16,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<ReturnType<typeof callLocalTool>>): Record<string, unknown> {
Expand Down Expand Up @@ -351,6 +352,7 @@ 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);

Expand Down Expand Up @@ -420,25 +422,160 @@ test("issue_view throws when the workspace has no worktree config, matching work
await fs.rm(root, { recursive: true, force: true });
});

// --- G: mottainai_task_start / mottainai_task_status (Git workflow task lifecycle) ---

function workflowConfig(base: ResolvedGatewayConfig): ResolvedGatewayConfig {
return { ...base, workflowTasks: true };
}

function openWorkflowStore(): WorkflowSqliteStateStore {
const store = new WorkflowSqliteStateStore({ dbPath: ":memory:" });
store.init();
return store;
}

test("task_start throws when workflowTasks is not configured", async () => {
const { root, config } = await gitWorkspace();
const store = new InMemoryArtifactStore();
await assert.rejects(
() => callLocalTool("mottainai_task_start", { taskSlug: "example" }, config, store),
/task lifecycle tools are not configured/,
);
await fs.rm(root, { recursive: true, force: true });
});

test("task_status throws when workflowTasks is not configured", async () => {
const { root, config } = await gitWorkspace();
const store = new InMemoryArtifactStore();
await assert.rejects(
() => callLocalTool("mottainai_task_status", {}, config, store),
/task lifecycle tools are not configured/,
);
await fs.rm(root, { recursive: true, force: true });
});

test("task_start rejects an invalid taskSlug at the MCP boundary", async () => {
const { root, config } = await gitWorkspace();
const store = new InMemoryArtifactStore();
const wfStore = openWorkflowStore();
await assert.rejects(
() => callLocalTool("mottainai_task_start", { taskSlug: "Bad Slug" }, workflowConfig(config), store, undefined, undefined, wfStore),
/invalid taskSlug/,
);
wfStore.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 = new InMemoryArtifactStore();
const wfStore = openWorkflowStore();
await assert.rejects(
() => callLocalTool("mottainai_task_start", { taskSlug: "ok", issueRef: "../evil" }, workflowConfig(config), store, undefined, undefined, wfStore),
/invalid issueRef/,
);
wfStore.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 = new InMemoryArtifactStore();
const wfStore = openWorkflowStore();

const started = structured(await callLocalTool(
"mottainai_task_start", { taskSlug: "example", issueRef: "9" }, workflowConfig(config), store, undefined, undefined, wfStore,
));
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 callLocalTool(
"mottainai_task_status", {}, workflowConfig(config), store, undefined, undefined, wfStore,
));
assert.equal(statusFromMainCheckout.status, "success");
assert.equal(statusFromMainCheckout.active, false);

const statusFromWorktree = structured(await callLocalTool(
"mottainai_task_status", {}, workflowConfig({ ...config, workspaceRoot: worktree.canonicalPath }), store, undefined, undefined, wfStore,
));
assert.equal(statusFromWorktree.active, true);
assert.equal((statusFromWorktree.task as { taskId: string }).taskId, (started.task as { taskId: string }).taskId);

wfStore.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 = new InMemoryArtifactStore();
const wfStore = openWorkflowStore();
const status = structured(await callLocalTool("mottainai_task_status", {}, workflowConfig(config), store, undefined, undefined, wfStore));
assert.equal(status.status, "success");
assert.equal(status.active, false);
assert.deepEqual(status.warnings, []);
wfStore.close();
await fs.rm(root, { recursive: true, force: true });
});

test("task_start rejects starting a second task from inside its own already-active worktree", async () => {
const { root, config } = await gitWorkspace();
const store = new InMemoryArtifactStore();
const wfStore = openWorkflowStore();
const started = structured(await callLocalTool(
"mottainai_task_start", { taskSlug: "outer" }, workflowConfig(config), store, undefined, undefined, wfStore,
));
const worktree = started.worktree as { canonicalPath: string };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Assert that the first task_start succeeded before reading its worktree.

The cast on Line 529 hides a failure. If task_start returns status: "failed", started.worktree is undefined, and Line 532 passes workspaceRoot: undefined into the second call. The test then fails somewhere downstream with an unrelated message instead of at the real cause.

💚 Proposed fix
   const started = structured(await callLocalTool(
     "mottainai_task_start", { taskSlug: "outer" }, workflowConfig(config), store, undefined, undefined, wfStore,
   ));
+  assert.equal(started.status, "success");
   const worktree = started.worktree as { canonicalPath: string };
📝 Committable suggestion

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

Suggested change
const started = structured(await callLocalTool(
"mottainai_task_start", { taskSlug: "outer" }, workflowConfig(config), store, undefined, undefined, wfStore,
));
const worktree = started.worktree as { canonicalPath: string };
const started = structured(await callLocalTool(
"mottainai_task_start", { taskSlug: "outer" }, workflowConfig(config), store, undefined, undefined, wfStore,
));
assert.equal(started.status, "success");
const worktree = started.worktree as { canonicalPath: string };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/local-tools.test.ts` around lines 526 - 529, Assert that the initial
`mottainai_task_start` result in the test succeeds before accessing
`started.worktree`; validate its success status and fail immediately with the
returned failure details when it is not successful. Only then cast or read the
worktree and pass its canonical path to the second call.


const second = structured(await callLocalTool(
"mottainai_task_start", { taskSlug: "inner" }, workflowConfig({ ...config, workspaceRoot: worktree.canonicalPath }), store, undefined, undefined, wfStore,
));
assert.equal(second.status, "failed");
assert.equal(second.reason, "active-task-in-workspace");

wfStore.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 = new InMemoryArtifactStore();
const wfStore = openWorkflowStore();
const result = structured(await callLocalTool(
"mottainai_task_start", { taskSlug: "example" }, workflowConfig(config), store, undefined, undefined, wfStore,
));
assert.equal(result.status, "failed");
assert.equal(result.reason, "invalid-policy");
wfStore.close();
await fs.rm(root, { recursive: true, force: true });
});

// --- F: advertised tool surface == executable tool surface, table-driven over both configurations ---

test("the advertised tool surface matches the executable tool surface for worktree-dependent tools", async () => {
test("the advertised tool surface matches the executable tool surface for worktree-dependent and workflow-task tools", async () => {
const { root, config: bareConfig } = await workspace();
const withWorktree: ResolvedGatewayConfig = {
...bareConfig,
worktree: { allowedBranchPrefixes: ["docs"], baseBranch: "main", worktreeDir: ".worktrees" },
};
const withWorkflowTasks: ResolvedGatewayConfig = { ...bareConfig, workflowTasks: true };
const store = new InMemoryArtifactStore();
const guardedTools: Array<{ name: string; args: Record<string, unknown> }> = [
{ name: "mottainai_worktree_new", args: { prefix: "docs", task: "example" } },
{ name: "mottainai_issue_view", args: { number: 1 } },
const guardedTools: Array<{ name: string; args: Record<string, unknown>; 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 },
{ name: "mottainai_task_start", args: { taskSlug: "example" }, enabled: (config) => config.workflowTasks },
{ name: "mottainai_task_status", args: {}, enabled: (config) => config.workflowTasks },
];
const configs = [bareConfig, withWorktree, withWorkflowTasks];

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.
Expand All @@ -450,7 +587,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 });
});
Expand Down
Loading
Loading