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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/domain/models/method_execution_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,13 @@ export class DefaultMethodExecutionService implements MethodExecutionService {
rawGlobalArgs,
modelDef.globalArguments,
);
const globalArgsResult = modelDef.globalArguments.safeParse(
const globalArgsSchema = modelDef.globalArguments;
const strictGlobalArgs = (
globalArgsSchema as unknown as {
strict?(): typeof globalArgsSchema;
}
).strict?.() ?? globalArgsSchema;
const globalArgsResult = strictGlobalArgs.safeParse(
coercedGlobalArgs,
);
if (!globalArgsResult.success) {
Expand Down
72 changes: 70 additions & 2 deletions src/domain/models/method_execution_service_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,10 +349,12 @@ Deno.test("execute with empty message throws error", async () => {

Deno.test("execute error message includes Zod details", async () => {
const service = new DefaultMethodExecutionService();
// Pass an empty argument set — missing required 'message' field, no unknown keys.
// This exercises the Zod validation error path (not the unknown-key path).
const definition = Definition.create({
name: "test-definition",
globalArguments: { wrongField: "value" },
methods: { write: { arguments: { wrongField: "value" } } },
globalArguments: {},
methods: { write: { arguments: {} } },
});

const { context } = createTestContext();
Expand Down Expand Up @@ -2751,3 +2753,69 @@ Deno.test(
assertEquals(capturedDriverConfig, { image: "alpine:latest" });
},
);

// ---------- Unknown method input key rejection ----------

Deno.test("execute - accepts known method input key", async () => {
const service = new DefaultMethodExecutionService();

let received: Record<string, unknown> = {};
const model: ModelDefinition = {
type: ModelType.create("test/strict-inputs"),
version: "1",
methods: {
run: {
description: "Test method",
arguments: z.object({ count: z.number() }),
execute: (args) => {
received = args as Record<string, unknown>;
return Promise.resolve({});
},
},
},
};

const definition = Definition.create({
name: "test-definition",
globalArguments: {},
methods: { run: { arguments: { count: "5" } } },
});

const { context } = createTestContext({
modelType: model.type,
methodName: "run",
});

await service.execute(definition, model.methods.run, context);
assertEquals(received.count, 5);
});

Deno.test("executeWorkflow - rejects unknown global arg key", async () => {
const service = new DefaultMethodExecutionService();

const model: ModelDefinition = {
type: ModelType.create("test/strict-global"),
version: "1",
globalArguments: z.object({ name: z.string() }),
methods: {
run: {
description: "Test method",
arguments: z.object({}),
execute: () => Promise.resolve({}),
},
},
};

const definition = Definition.create({
name: "test-definition",
globalArguments: { name: "hello", unknownKey: "oops" },
});

const { context } = createTestContext({ modelType: model.type });

await assertRejects(
() => service.executeWorkflow(definition, model, "run", context),
Error,
"Global arguments validation failed",
);
});
14 changes: 11 additions & 3 deletions src/domain/models/validation_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,10 +482,14 @@ export class DefaultModelValidationService implements ModelValidationService {
return Promise.resolve(ValidationResult.pass("Global arguments"));
}

// All fields are static, validate normally
// All fields are static, validate with strict mode to reject unknown keys
const globalArgsSchema = modelDef.globalArguments;
const strictGlobalArgs = (
globalArgsSchema as unknown as { strict?(): typeof globalArgsSchema }
).strict?.() ?? globalArgsSchema;
return this.validateWithSchema(
"Global arguments",
modelDef.globalArguments,
strictGlobalArgs,
staticArgs,
);
}
Expand All @@ -510,7 +514,11 @@ export class DefaultModelValidationService implements ModelValidationService {
continue;
}

const result = methodDef.arguments.safeParse(staticArgs);
const methodArgsSchema = methodDef.arguments;
const strictMethodArgs = (
methodArgsSchema as unknown as { strict?(): typeof methodArgsSchema }
).strict?.() ?? methodArgsSchema;
const result = strictMethodArgs.safeParse(staticArgs);
if (!result.success) {
errors.push(
`Method "${methodName}": ${formatZodError(result.error)}`,
Expand Down
32 changes: 32 additions & 0 deletions src/domain/models/validation_service_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1560,3 +1560,35 @@ Deno.test("validateModel warns when appliesTo is empty array", async () => {
assertStringIncludes(selResult?.error ?? "", "empty appliesTo");
assertStringIncludes(selResult?.error ?? "", "will never run");
});

// ---------- Strict schema validation tests ----------

Deno.test("validateModel rejects unknown global argument key", async () => {
const service = new DefaultModelValidationService();
const definition = Definition.create({
name: "test-definition",
globalArguments: { message: "hello", unknownKey: "oops" },
methods: { write: { arguments: { message: "hello" } } },
});

const { results } = await service.validateModel(definition, testExprModel);

const globalResult = results.find((r) => r.name === "Global arguments");
assertEquals(globalResult?.passed, false);
assertStringIncludes(globalResult?.error ?? "", "unknownKey");
});

Deno.test("validateModel rejects unknown method argument key", async () => {
const service = new DefaultModelValidationService();
const definition = Definition.create({
name: "test-definition",
globalArguments: { message: "hello" },
methods: { write: { arguments: { message: "hello", typo: "oops" } } },
});

const { results } = await service.validateModel(definition, testExprModel);

const methodResult = results.find((r) => r.name === "Method arguments");
assertEquals(methodResult?.passed, false);
assertStringIncludes(methodResult?.error ?? "", "typo");
});
3 changes: 2 additions & 1 deletion src/domain/repo/repo_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ const INSTRUCTIONS_FILES: Partial<Record<AiTool, string>> = {
};

const GITIGNORE_TOOL_ENTRIES: Partial<Record<AiTool, string>> = {
claude: "# Claude Code configuration (managed by swamp)\n.claude/",
claude:
"# Claude Code configuration (managed by swamp)\n.claude/worktrees/\n.claude/settings.local.json\n.claude/scheduled_tasks.lock\n.claude/scheduled_tasks.json",
cursor: "# Cursor skills (managed by swamp)\n.cursor/skills/",
opencode: "# Agent skills (managed by swamp)\n.agents/skills/",
codex: "# Agent skills (managed by swamp)\n.agents/skills/",
Expand Down
35 changes: 27 additions & 8 deletions src/domain/repo/repo_service_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,11 @@ Deno.test("RepoService.init always creates .gitignore with managed section", asy
assertStringIncludes(content, "# END swamp managed section");
assertStringIncludes(content, ".swamp/");
assertStringIncludes(content, ".swamp-sources.yaml");
assertStringIncludes(content, ".claude/");
assertStringIncludes(content, ".claude/worktrees/");
assertStringIncludes(content, ".claude/settings.local.json");
assertStringIncludes(content, ".claude/scheduled_tasks.lock");
assertStringIncludes(content, ".claude/scheduled_tasks.json");
assertEquals(content.split("\n").includes(".claude/"), false);

// Check marker persists the preference
const marker = await service.getMarker(repoPath);
Expand Down Expand Up @@ -931,7 +935,7 @@ Deno.test("RepoService.upgrade creates .gitignore when marker has gitignoreManag
"# BEGIN swamp managed section - DO NOT EDIT",
);
assertStringIncludes(content, ".swamp/");
assertStringIncludes(content, ".claude/");
assertStringIncludes(content, ".claude/worktrees/");
assertStringIncludes(content, "# END swamp managed section");
});
});
Expand Down Expand Up @@ -971,7 +975,7 @@ Deno.test("RepoService.init cursor instructions have MDC frontmatter", async ()

Deno.test("RepoService.init includes tool-specific gitignore entries", async () => {
const toolGitignoreEntries: Partial<Record<AiTool, string>> = {
claude: ".claude/",
claude: ".claude/worktrees/",
cursor: ".cursor/skills/",
opencode: ".agents/skills/",
codex: ".agents/skills/",
Expand Down Expand Up @@ -1005,6 +1009,20 @@ Deno.test("RepoService.init includes tool-specific gitignore entries", async ()
assertStringIncludes(content, "# END swamp managed section");
});
}

// Claude specifically: .claude/skills/ must NOT be gitignored so extension
// authors can commit skill sources to their extension repo.
await withTempDir(async (tempDir) => {
const service = new RepoService("0.1.0");
const repoPath = RepoPath.create(tempDir);
await service.init(repoPath, { tools: ["claude"] });
const content = await Deno.readTextFile(join(tempDir, ".gitignore"));
assertStringIncludes(content, ".claude/worktrees/");
assertStringIncludes(content, ".claude/settings.local.json");
assertStringIncludes(content, ".claude/scheduled_tasks.lock");
assertStringIncludes(content, ".claude/scheduled_tasks.json");
assertEquals(content.split("\n").includes(".claude/"), false);
});
});

// Managed .gitignore section tests
Expand Down Expand Up @@ -1039,7 +1057,7 @@ Deno.test("RepoService.init replaces managed section on tool switch", async () =
await service.init(repoPath);
const gitignorePath = join(tempDir, ".gitignore");
let content = await Deno.readTextFile(gitignorePath);
assertStringIncludes(content, ".claude/");
assertStringIncludes(content, ".claude/worktrees/");

// Re-init with cursor (force)
const result = await service.init(repoPath, {
Expand All @@ -1050,8 +1068,9 @@ Deno.test("RepoService.init replaces managed section on tool switch", async () =
assertEquals(result.gitignoreAction, "updated");
content = await Deno.readTextFile(gitignorePath);
assertStringIncludes(content, ".cursor/skills/");
// Old tool entry should be replaced
assertEquals(content.includes(".claude/"), false);
// Old tool entries should be replaced
assertEquals(content.includes(".claude/worktrees/"), false);
assertEquals(content.includes(".claude/settings.local.json"), false);
});
});

Expand Down Expand Up @@ -1140,7 +1159,7 @@ Deno.test("RepoService.init migrates legacy gitignore format", async () => {
);
assertStringIncludes(content, "# END swamp managed section");
assertStringIncludes(content, ".swamp/");
assertStringIncludes(content, ".claude/");
assertStringIncludes(content, ".claude/worktrees/");
});
});

Expand Down Expand Up @@ -2289,7 +2308,7 @@ Deno.test("RepoService.init with multiple tools writes scaffolding for each", as

// .gitignore should contain entries for both tools
const gitignore = await Deno.readTextFile(join(tempDir, ".gitignore"));
assertStringIncludes(gitignore, ".claude/");
assertStringIncludes(gitignore, ".claude/worktrees/");
assertStringIncludes(gitignore, ".kiro/skills/");
});
});
Expand Down
8 changes: 7 additions & 1 deletion src/libswamp/models/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,13 @@ export async function* modelCreate(
globalArguments,
jsonSchema as Record<string, unknown>,
);
const result = modelDef.globalArguments.safeParse(globalArguments);
const globalArgsSchema = modelDef.globalArguments;
const strictGlobalArgs = (
globalArgsSchema as unknown as {
strict?(): typeof globalArgsSchema;
}
).strict?.() ?? globalArgsSchema;
const result = strictGlobalArgs.safeParse(globalArguments);
if (!result.success) {
const issues = result.error.issues.map((i) =>
` ${i.path.join(".")}: ${i.message}`
Expand Down
68 changes: 68 additions & 0 deletions src/libswamp/models/create_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,74 @@ Deno.test("modelCreate: coerces string global arguments to match schema types",
assertEquals(completed.kind, "completed");
});

Deno.test("modelCreate: yields error when unknown global arg key is passed", async () => {
const globalArgsSchema = z.object({
name: z.string(),
});

const deps = makeDeps({
getModelDef: () => ({
type: { normalized: "test/strict" },
version: "1.0.0",
globalArguments: globalArgsSchema,
methods: {},
resources: {},
} as unknown as ModelDefinition),
});

const events = await collect<ModelCreateEvent>(
modelCreate(createLibSwampContext(), deps, {
typeArg: "test/strict",
name: "my-model",
globalArguments: { name: "hello", typoKey: "whatever" },
}),
);

assertEquals(events.length, 2);
assertEquals(events[0], { kind: "creating" });
const last = events[1] as Extract<ModelCreateEvent, { kind: "error" }>;
assertEquals(last.kind, "error");
assertEquals(last.error.code, "validation_failed");
});

Deno.test("modelCreate: accepts all known global arg keys", async () => {
const globalArgsSchema = z.object({
name: z.string(),
count: z.number(),
});

const deps = makeDeps({
getModelDef: () => ({
type: { normalized: "test/strict" },
version: "1.0.0",
globalArguments: globalArgsSchema,
methods: {},
resources: {},
} as unknown as ModelDefinition),
createAndSave: () =>
Promise.resolve({
id: "def-1",
name: "my-model",
} as unknown as Awaited<
ReturnType<ModelCreateDeps["createAndSave"]>
>),
});

const events = await collect<ModelCreateEvent>(
modelCreate(createLibSwampContext(), deps, {
typeArg: "test/strict",
name: "my-model",
globalArguments: { name: "hello", count: "3" },
}),
);

const last = events[events.length - 1] as Extract<
ModelCreateEvent,
{ kind: "completed" }
>;
assertEquals(last.kind, "completed");
});

Deno.test("modelCreate: yields error when name already exists", async () => {
const deps = makeDeps({
findByNameGlobal: () => Promise.resolve(true),
Expand Down
Loading
Loading