Files
ruflo/v3/@claude-flow/cli/__tests__/validate-input-agent-spawn.test.ts
T
9456ae1eb5 integrate: zod 4 migration (#4535) (#5021)
* fix(deps): migrate @claude-flow packages from zod 3 to zod 4

zod 3.25.76 is affected by GHSA-mrhx-c7xc-m3w5 (memory exhaustion while
validating oversized constrained collections, High). The fix exists only
in zod 4.6.6+, so downstream lockfiles cannot clear it while
@claude-flow/{cli,security,shared,hooks,claims} require zod ^3.

Forcing zod 4 onto the current releases breaks them at runtime, which is
what this migration fixes:

- security/input-validator: z.string().ip() was removed. It threw at module
  load, so importing @claude-flow/memory failed and the AgentDB bridge
  silently degraded (memory_store returned "Database not initialized").
  Use z.ipv4() and z.union([z.ipv4(), z.ipv6()]).
- security/input-validator: the global error map used the zod 3 signature
  and returned ctx.defaultError. zod 4 calls the map without ctx, so every
  unmapped issue raised a TypeError instead of a ZodError, process-wide.
  Port it to z.config({ customError }) and map invalid_format by format.
- shared/config/validator: ZodError.errors was removed; use .issues.
  Invalid configs threw a TypeError instead of returning errors.
- z.record(valueSchema) -> z.record(z.string(), valueSchema), and the
  removed ZodTypeDef / SafeParseReturnType types.
- Root claude-flow package: zod 3.25.76 -> 4.6.7 (root CI resolves zod
  from here). fastmcp's nested zod 4.3.5 now dedupes onto 4.6.7.

New tests fail on main with zod 4 installed and pass after:
security/__tests__/zod4-compat.test.ts, shared/__tests__/zod4-config-validator.test.ts.

Still on zod 3 after this change: agentic-flow (separate repo, ^3.25.76)
and the published @claude-flow/plugin-gastown-bridge 0.1.4.

Claude-Session: https://claude.ai/code/session_0157fpfsb1SsSv3XAL3oxF1E

* fix(zod4): keep custom agent types, foreign ZodErrors and UUID parity

Follow-ups from an adversarial review of the zod 4 migration:

- cli-core validateAgentSpawn swallowed only `invalid_enum_value`. zod 4
  reports an out-of-enum value as `invalid_value`, so wherever
  @claude-flow/security resolves (any hoisted install) every custom agent
  type would be rejected. Extract isUnknownAgentTypeIssue(), accept both
  codes, and only for the `type` path. The existing "custom type" test used
  memory-specialist, which is in the enum, so it never reached this branch;
  the new test drives the rule with real SpawnAgentSchema issues.
- shared ConfigValidator: recognise a ZodError from another zod copy by
  shape (callers may pass zod 3 schemas), and stringify path segments so a
  symbol key cannot make path.join() throw.
- security UUIDSchema: zod 4's uuid() is strict RFC 9562 and rejected ids
  zod 3 accepted (e.g. 00000000-0000-0000-0000-000000000001). Use z.guid(),
  which keeps zod 3's 8-4-4-4-12 hex check.

Each new assertion fails when its fix is reverted.

Claude-Session: https://claude.ai/code/session_0157fpfsb1SsSv3XAL3oxF1E

* fix(zod4): report a missing agent type; reject impostor ZodErrors

Second adversarial round on the zod 4 migration:

- zod 4 raises `invalid_value` at ['type'] for a missing, null or
  non-string agent type, where zod 3 raised `invalid_type`. The previous
  fix suppressed every `invalid_value` at that path, so
  validateAgentSpawn({}) passed. Suppress only when the submitted type is
  a string and the issue path is exactly ['type'] (zod 3 parity).
- isZodErrorLike now requires a non-empty issues array of {path, message,
  code} objects, so an operational Error that happens to be named
  ZodError still propagates.

Each new assertion fails when its guard is removed.

Claude-Session: https://claude.ai/code/session_0157fpfsb1SsSv3XAL3oxF1E

* fix(plugins): build and run the v3 plugins under zod 3 and zod 4

The install-safety job builds v3/plugins against the repo-root zod, which this
branch moves to 4. Six plugins failed to typecheck, and two also broke at runtime:

- z.record(v) -> z.record(z.string(), v). zod 4 needs the key schema; the
  one-argument form also fails at parse time, not only in tsc.
- z.ZodTypeDef is gone in zod 4. ZodType<TInput, any, any> is valid under both
  majors (zod 3 reads <Output, Def, Input>, zod 4 <Output, Input, Internals>).
- prime-radiant: zod 4 returns a .default() value without parsing it, so
  .default({}) dropped every nested config default. Default to Schema.parse({}).
- gastown-bridge: ZodError.errors no longer exists (use .issues, present in
  both), and zodToJsonSchema called _def.shape(), which is an object in zod 4.
  It threw inside a try and returned an empty schema for every MCP tool.

The plugins keep their declared zod ranges and lockfiles; the code now
typechecks and passes under zod 3.25.76 and zod 4.6.7. New tests fail
against the previous source.

Claude-Session: https://claude.ai/code/session_0157fpfsb1SsSv3XAL3oxF1E

* chore(leaves): bump cli-core to 3.7.6 and shared to 3.0.7 for the zod 4 change

Both are non-bundled leaves, so the zod 4 source changes reach nobody until
they are published (audit-leaf-package-publish). Bumped the CLI's pins and the
pnpm-lock specifiers to match, as in b0bd254ec. The root claude-flow pins stay
on the published 3.7.5 / 3.0.6 until these two are published, because pinning
an unpublished version breaks `npm install` at the root.

Claude-Session: https://claude.ai/code/session_0157fpfsb1SsSv3XAL3oxF1E

* chore(root): pin claude-flow to cli-core 3.7.6 and shared 3.0.7

audit-wrapper-dep-ranges requires the umbrella's pins to include the
workspace versions bumped in the previous commit. Requested by the
maintainer on #4535.

Until both versions are on npm, root `npm ci` fails with ETARGET and
package-lock.json cannot be regenerated, so it is left unchanged here.
After the standalone publish, run `npm install --package-lock-only` at
the root and commit the lockfile.

Claude-Session: https://claude.ai/code/session_0157fpfsb1SsSv3XAL3oxF1E

* chore(leaves): cli-core 3.7.8 for the zod 4 agent-type fix; cli on zod ^4.6.7

validate-input.ts changed (isUnknownAgentTypeIssue), and cli-core is a
non-bundled leaf of @claude-flow/cli, so it needs its own version and a
standalone publish before this merges:

- @claude-flow/cli-core 3.7.7 -> 3.7.8; cli and claude-flow pins follow.
- @claude-flow/cli zod ^3.22.0 -> ^4.6.7.

Lockfiles are hand-edited to the minimum: v3/pnpm-lock.yaml moves only the
cli importer's cli-core/zod specifiers and the zod peer suffix of the
memory/agentdb/ruvector entries it already resolves to; package-lock.json
moves only the cli-core entry. Its integrity is left blank until 3.7.8 is
on the registry (npm fills it on the next install).

Co-Authored-By: RuFlo <ruv@ruv.net>

---------

Co-authored-by: Dragan Spiridonov <spiridonovdragan@gmail.com>
Co-authored-by: r <r@x>
2026-11-17 22:49:51 -05:00

82 lines
3.6 KiB
TypeScript

/**
* Regression test for #1567: validateAgentSpawn's Zod call was passing
* `{ agentType, name }` to `@claude-flow/security`'s SpawnAgentSchema, which
* expects `{ type, id }` — so every call failed with "type: Required" and
* the MCP agent_spawn tool returned an input validation error for every
* possible input. The fix aligns the field names AND swallows
* `invalid_enum_value` errors so custom agent types (beyond the 15-type
* hardcoded enum) continue to work.
*/
import { describe, it, expect } from 'vitest';
import { validateAgentSpawn, isUnknownAgentTypeIssue } from '../src/mcp-tools/validate-input.js';
describe('validateAgentSpawn (#1567)', () => {
it('accepts a built-in agent type like "tester"', async () => {
const r = await validateAgentSpawn({ agentType: 'tester', agentId: 'tester-1' });
expect(r.valid).toBe(true);
expect(r.errors).toEqual([]);
});
it('accepts a custom agent type not in the SpawnAgentSchema enum', async () => {
// "memory-specialist" is not one of the 15 types that
// @claude-flow/security's AgentTypeSchema enumerates, but it's a valid
// Claude Flow agent type and should NOT be rejected.
const r = await validateAgentSpawn({ agentType: 'memory-specialist', agentId: 'mem-1' });
expect(r.valid).toBe(true);
expect(r.errors).toEqual([]);
});
it('accepts an agent type that is genuinely outside the enum', async () => {
// "memory-specialist" above IS in AgentTypeSchema, so it never reached the
// enum-suppression branch.
const r = await validateAgentSpawn({ agentType: 'qe-flaky-hunter', agentId: 'qe-1' });
expect(r.errors).toEqual([]);
expect(r.valid).toBe(true);
});
// validateAgentSpawn loads @claude-flow/security dynamically and falls back
// to inline checks when it cannot resolve it (as under pnpm's strict
// layout here), so the cases above may never reach the Zod branch. Drive
// the suppression rule with real SpawnAgentSchema issues instead.
it('ignores only the unknown-agent-type issue from SpawnAgentSchema', async () => {
const { SpawnAgentSchema } = await import('@claude-flow/security');
const issuesFor = (type: unknown, id = 'qe-1') => {
const r = SpawnAgentSchema.safeParse({ type, id });
expect(r.success).toBe(false);
return r.error!.issues;
};
const custom = issuesFor('qe-flaky-hunter');
expect(custom.length).toBeGreaterThan(0);
expect(custom.every((i) => isUnknownAgentTypeIssue(i, 'qe-flaky-hunter'))).toBe(true);
// A missing or non-string type must still be reported. zod 4 raises
// `invalid_value` at ['type'] for these too (zod 3: `invalid_type`).
for (const missing of [undefined, null, 0, false]) {
expect(issuesFor(missing).some((i) => isUnknownAgentTypeIssue(i, missing))).toBe(false);
}
const badId = issuesFor('tester', 'has spaces');
expect(badId.some((i) => isUnknownAgentTypeIssue(i, 'tester'))).toBe(false);
// Only the top-level `type` field is exempt.
expect(isUnknownAgentTypeIssue({ code: 'invalid_value', path: ['type', 'nested'] }, 'x')).toBe(false);
expect(isUnknownAgentTypeIssue({ code: 'invalid_enum_value', path: ['priority'] }, 'x')).toBe(false);
});
it('still rejects an agentId with invalid characters', async () => {
const r = await validateAgentSpawn({
agentType: 'tester',
agentId: 'has spaces and $pecials',
});
expect(r.valid).toBe(false);
expect(r.errors.length).toBeGreaterThan(0);
});
it('does not require the domain field', async () => {
const r = await validateAgentSpawn({ agentType: 'coder', agentId: 'c1' });
expect(r.valid).toBe(true);
});
});