mastra-ai/mastra · error · Error

KnowledgeRecord when must be a valid date.

Error message

KnowledgeRecord when must be a valid date.

What it means

knowledge_append accepts an optional `when` string that is converted with new Date(value.when) to stamp the record's event time. If the string is present but not parseable (NaN getTime), the handler throws this error instead of persisting a bogus timestamp. The JSON schema only enforces type string, so this runtime check is authoritative.

Source

Thrown at packages/memory/src/processors/observational-memory/subconscious/knowledge-write-tools.ts:75

        type: 'object',
        properties: {
          node: { type: 'string', minLength: 1 },
          text: { type: 'string', minLength: 1 },
          scope: scopeLevelSchema,
          when: { type: 'string' },
        },
        required: ['node', 'text'],
        additionalProperties: false,
      } satisfies JSONSchema7,
      execute: async input => {
        const value = input as { node: string; text: string; scope?: KnowledgeScopeLevel; when?: string };
        const store = await getStore(memory);
        const parent = await store.getNode(value.node);
        if (!parent || parent.mergedInto) throw new Error(`Knowledge node not found: ${value.node}`);
        requireVisible(parent.scope, options, 'Knowledge node');
        const scope = resolveWriteScope(options, value.scope);
        const when = value.when ? new Date(value.when) : undefined;
        if (when && Number.isNaN(when.getTime())) throw new Error('KnowledgeRecord when must be a valid date.');
        return store.appendKnowledge({
          node: parent.id,
          text: value.text,
          scope,
          sourceThreadId: options.sourceThreadId,
          when,
          maxScope: options.maxScope,
          resolutionScope: options.scope,
          defaultScope: expandKnowledgeScope(options.scope, options.defaultScope),
        });
      },
    }),
    knowledge_remove: createTool({
      id: 'knowledge_remove',
      description: 'Soft-delete a visible record. Curators cannot restore or physically erase knowledge records.',
      inputSchema: {
        type: 'object',
        properties: { recordId: { type: 'string', minLength: 1 } },

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Supply `when` as an ISO 8601 string (e.g. '2026-08-29T12:00:00.000Z') or omit it entirely to use the capture time.
  2. Normalize dates to ISO format in the agent pipeline before invoking the tool.
  3. Strengthen the tool description or prompt to state the required ISO 8601 format.
  4. In programmatic callers, validate with !Number.isNaN(new Date(when).getTime()) before execute().

Example fix

// before
await tools.knowledge_append.execute({ node: id, text: 'x', when: 'last Friday' }, ctx);
// after
await tools.knowledge_append.execute({ node: id, text: 'x', when: '2026-08-28T17:30:00.000Z' }, ctx);
Defensive patterns

Strategy: validation

Validate before calling

function toIsoOrUndefined(when?: string): string | undefined {
  if (when === undefined) return undefined;
  const d = new Date(when);
  if (Number.isNaN(d.getTime())) throw new Error(`Invalid when: ${when}`);
  return d.toISOString();
}
const safeWhen = toIsoOrUndefined(args.when);

Type guard

function isParseableDate(s: unknown): s is string {
  return typeof s === 'string' && !Number.isNaN(new Date(s).getTime());
}

Try / catch

try {
  return await curatorTools.knowledge_append.execute(args, {} as any);
} catch (e) {
  if (e instanceof Error && e.message === 'KnowledgeRecord when must be a valid date.') {
    return curatorTools.knowledge_append.execute({ ...args, when: undefined }, {} as any); // fall back to capture time
  }
  throw e;
}

Prevention

When it happens

Trigger: LLM passes a non-ISO string such as 'last Tuesday', '2024-13-45', 'yesterday', or a locale-formatted date in the knowledge_append `when` field.

Common situations: Models emitting natural-language dates; users' free-text dates relayed into tool args; timezone-formatted strings not accepted by the JS Date parser in the runtime environment.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/451d57b1799a5a47. Report an issue: GitHub.