← Files Flows by plugin.spaceARCHIVED FILE

lib/document.mjs

17.5 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { validateRoleAudit } from './user-roles.mjs';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { validateCaptureSettings } from './capture-settings.mjs';
import { isProjectIcon } from './project-icon-data.mjs';

export const MAX_DOCUMENT_BYTES = 1024 * 1024;
const kinds = new Set(['screen', 'action', 'decision', 'state']);
const provenances = new Set(['proposed', 'inferred', 'observed']);
const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isText = (value, max = 8000) => typeof value === 'string' && value.length <= max;
const isId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,100}$/.test(value);
const isImagePath = value => isText(value, 1000) && value.length > 0 && !value.startsWith('/') && !value.includes('\\') && !value.split('/').some(part => part === '..' || part === '.') && !/^[a-z]+:/i.test(value);
const isList = (value, item) => Array.isArray(value) && value.every(item);
const isPrompt = value => isText(value, 1000) && value.trim().length > 0;
const qualityFocus = new Set(['comprehension', 'decision', 'recovery', 'feedback', 'effort', 'output-quality']);
const qualitySource = value => isRecord(value) && ['provided', 'inferred'].includes(value.kind) && (value.reference === undefined || isPrompt(value.reference));
const textList = value => isList(value, isPrompt);
const idList = value => isList(value, isId);
const uniqueIds = value => new Set(value.map(item => item.id)).size === value.length;

function validateGeneratedRoles(value, prefix, errors) {
  if (value === undefined) return undefined;
  if (!isList(value, role => isRecord(role) && isId(role.id) && isText(role.name, 100) && role.name.trim()) || !uniqueIds(value)) {
    errors.push(`${prefix} userRoles must contain unique valid role ids and names (up to 100 characters).`);
    return undefined;
  }
  return new Set(value.map(role => role.id));
}

function validateGeneratedRoleIds(value, known, prefix, errors) {
  // Derived suites can lag behind source edits; validate references against the
  // suite's own snapshot, then let the normal writer regenerate current roles.
  if (value !== undefined && (!idList(value) || new Set(value).size !== value.length || (known && value.some(id => !known.has(id))))) errors.push(`${prefix} userRoleIds must contain unique valid ids from the generated role summary.`);
}

function validateUserStories(value, nodeIds, edgeIds, errors) {
  if (value === undefined) return;
  if (!isList(value, isRecord)) { errors.push('userStories must be a list of mapped user stories.'); return; }
  if (!uniqueIds(value)) errors.push('User stories need unique ids.');
  for (const [index, story] of value.entries()) {
    const prefix = `User story ${index + 1}`;
    if (!isId(story.id)) errors.push(`${prefix} needs a valid id.`);
    if (!isText(story.actor, 100) || !story.actor.trim()) errors.push(`${prefix} needs an actor (up to 100 characters).`);
    if (!isPrompt(story.goal) || !isPrompt(story.benefit) || (story.context !== undefined && !isPrompt(story.context))) errors.push(`${prefix} needs a goal, benefit and optional context as non-empty text (up to 1000 characters).`);
    if (!qualitySource(story.source)) errors.push(`${prefix} needs a provided or inferred source and optional non-empty reference (up to 1000 characters).`);
    if (!idList(story.nodeIds) || !story.nodeIds.length || story.nodeIds.some(id => !nodeIds.has(id))) errors.push(`${prefix} nodeIds must reference at least one existing node.`);
    if (story.edgeIds !== undefined && (!idList(story.edgeIds) || story.edgeIds.some(id => !edgeIds.has(id)))) errors.push(`${prefix} edgeIds must reference existing connections.`);
    if (story.acceptanceCriteria !== undefined && !textList(story.acceptanceCriteria)) errors.push(`${prefix} acceptanceCriteria must be non-empty text items (up to 1000 characters each).`);
  }
}

function validateEvaluations(value, prefix, errors) {
  if (value === undefined) return;
  if (!isList(value, isRecord)) { errors.push(`${prefix} evaluations must be a list.`); return; }
  if (!uniqueIds(value)) errors.push(`${prefix} evaluations need unique ids within the node.`);
  for (const evaluation of value) {
    if (!isId(evaluation.id) || !qualityFocus.has(evaluation.focus) || !isPrompt(evaluation.expectation) || ['task', 'rationale'].some(key => evaluation[key] !== undefined && !isPrompt(evaluation[key])) || !qualitySource(evaluation.source)) errors.push(`${prefix} evaluation needs a valid id, focus, expectation, provided or inferred source and optional task/rationale (non-empty text up to 1000 characters).`);
  }
}

function validateQualitySuggestions(value, errors) {
  if (value === undefined) return;
  if (!isRecord(value) || value.version !== 1 || value.status !== 'draft') { errors.push('testScenarios quality needs version 1 and draft status; suggestions are not evaluation results.'); return; }
  const generatedText = text => isText(text, 4000) && text.trim().length > 0;
  const generatedTexts = texts => isList(texts, generatedText);
  const roleIds = validateGeneratedRoles(value.userRoles, 'testScenarios quality', errors);
  if (!generatedTexts(value.warnings)) errors.push('testScenarios quality warnings must be a list of text.');
  for (const key of ['useCases', 'evaluations']) {
    const suggestions = value[key];
    if (!isList(suggestions, isRecord)) { errors.push(`testScenarios quality ${key} must be a list.`); continue; }
    if (!uniqueIds(suggestions)) errors.push(`testScenarios quality ${key} need unique ids.`);
    for (const suggestion of suggestions) {
      const prefix = `Quality ${key} suggestion`;
      validateGeneratedRoleIds(suggestion.userRoleIds, roleIds, prefix, errors);
      if (!isId(suggestion.id) || !isText(suggestion.title, 1200) || !suggestion.title.trim() || !['provided', 'inferred'].includes(suggestion.source) || (suggestion.sourceReference !== undefined && !generatedText(suggestion.sourceReference))) errors.push(`${prefix} needs a valid id, title and provided or inferred source.`);
      if (!['nodeIds', 'edgeIds', 'scenarioIds'].every(field => idList(suggestion[field])) || !generatedTexts(suggestion.questions)) errors.push(`${prefix} needs node, edge and scenario ID lists and review questions.`);
      if (key === 'useCases') {
        const story = suggestion.story;
        if (!isRecord(story) || !isText(story.actor, 100) || !story.actor.trim() || !generatedText(story.goal) || !generatedText(story.benefit) || (story.context !== undefined && !generatedText(story.context)) || !generatedTexts(suggestion.acceptanceCriteria)) errors.push(`${prefix} needs actor, goal, benefit, optional context and acceptance criteria.`);
      } else {
        if (suggestion.status !== 'draft' || !qualityFocus.has(suggestion.focus) || !['usability-session', 'expert-review'].includes(suggestion.method) || !idList(suggestion.useCaseIds) || !['rationale', 'task', 'expectation'].every(field => generatedText(suggestion[field])) || !generatedTexts(suggestion.evidenceToCollect)) errors.push(`${prefix} needs draft status, focus, method, use case IDs, rationale, task, expectation and evidence to collect.`);
        if (suggestion.focus === 'output-quality' && suggestion.method !== 'expert-review') errors.push(`${prefix} output-quality suggestions require human expert review.`);
        if (!isList(suggestion.criteria, criterion => isRecord(criterion) && isId(criterion.id) && ['question', 'meetsExpectation', 'needsWork'].every(field => generatedText(criterion[field]))) || !uniqueIds(suggestion.criteria)) errors.push(`${prefix} needs uniquely identified rubric questions and expectation anchors.`);
      }
    }
  }
}

function validateTestHints(value, keys, prefix, errors, assignedRoleIds) {
  if (value === undefined) return;
  if (!isRecord(value)) { errors.push(`${prefix} test instructions must be an object.`); return; }
  for (const key of keys) if (value[key] !== undefined && !isPrompt(value[key])) errors.push(`${prefix} test ${key} must be non-empty text (up to 1000 characters).`);
  if (value.userRoleIds !== undefined && (!idList(value.userRoleIds) || !value.userRoleIds.length || new Set(value.userRoleIds).size !== value.userRoleIds.length || value.userRoleIds.some(id => !assignedRoleIds.has(id)))) errors.push(`${prefix} test userRoleIds must contain unique roles assigned to this flow; omit the field to inherit all flow roles.`);
}

function validateTestScenarios(value, errors) {
  if (value === undefined) return;
  if (!isRecord(value) || value.version !== 1 || value.source !== 'flow-map') { errors.push('testScenarios needs version 1 and source flow-map.'); return; }
  const ids = new Set();
  const roleIds = validateGeneratedRoles(value.userRoles, 'testScenarios', errors);
  validateQualitySuggestions(value.quality, errors);
  if (!textList(value.warnings)) errors.push('testScenarios warnings must be a list of text.');
  if (!isList(value.cases, isRecord)) { errors.push('testScenarios cases must be a list of scenarios.'); return; }
  for (const [index, scenario] of value.cases.entries()) {
    const prefix = `Test scenario ${index + 1}`;
    validateGeneratedRoleIds(scenario.userRoleIds, roleIds, prefix, errors);
    if (!isId(scenario.id) || ids.has(scenario.id)) errors.push(`${prefix} needs a unique valid id.`);
    ids.add(scenario.id);
    if (!isText(scenario.name, 200) || !scenario.name.trim()) errors.push(`${prefix} needs a name (up to 200 characters).`);
    if (scenario.status !== 'draft') errors.push(`${prefix} status must be draft; generation is not test execution.`);
    if (!isList(scenario.nodeIds, isId) || !isList(scenario.edgeIds, isId)) errors.push(`${prefix} needs nodeIds and edgeIds lists.`);
    if (!textList(scenario.preconditions) || !textList(scenario.warnings)) errors.push(`${prefix} needs preconditions and warnings lists.`);
    if (scenario.termination !== undefined && !['terminal', 'cycle', 'depth-limit'].includes(scenario.termination)) errors.push(`${prefix} has an unsupported termination.`);
    if (!isList(scenario.steps, step => isRecord(step) && ['action', 'assertion'].includes(step.kind) && isPrompt(step.prompt) && ['mapped', 'derived'].includes(step.source) && (step.nodeId === undefined || isId(step.nodeId)) && (step.edgeId === undefined || isId(step.edgeId)))) errors.push(`${prefix} steps need an action or assertion, prompt and mapped or derived source.`);
  }
  const coverage = value.coverage;
  if (!isRecord(coverage) || !isList(coverage.coveredEdgeIds, isId) || !isList(coverage.uncoveredEdgeIds, isId) || !isList(coverage.unreachableNodeIds, isId) || typeof coverage.truncated !== 'boolean') errors.push('testScenarios coverage needs edge/node lists and a truncated boolean.');
}

export function validateDocument(value) {
  const errors = [];
  if (!isRecord(value)) return { valid: false, errors: ['Document must be an object.'] };
  if (value.version !== 1) errors.push('version must be 1.');
  if (!isId(value.id)) errors.push('id must contain letters, numbers, hyphens or underscores.');
  if (!isText(value.name, 200) || !value.name.trim()) errors.push('name must be a non-empty string (up to 200 characters).');
  if (value.description !== undefined && !isText(value.description)) errors.push('description must be text.');
  if (value.application !== undefined && (!isRecord(value.application) || !isId(value.application.id) || !isText(value.application.name, 200) || !value.application.name.trim())) errors.push('application needs a valid id and name.');
  if (value.application?.icon !== undefined && !isProjectIcon(value.application.icon)) errors.push('application icon must be a safe inline favicon up to 64 KB.');
  if (value.captureSettings !== undefined) errors.push(...validateCaptureSettings(value.captureSettings));
  validateTestScenarios(value.testScenarios, errors);
  if (!Array.isArray(value.nodes) || value.nodes.length < 1 || value.nodes.length > 500) {
    errors.push('nodes must contain 1–500 nodes.');
    return { valid: false, errors };
  }
  if (!Array.isArray(value.edges) || value.edges.length > 2000) {
    errors.push('edges must be an array of up to 2000 connections.');
    return { valid: false, errors };
  }
  const ids = new Set();
  const assignedRoleIds = new Set(idList(value.userRoleIds) ? value.userRoleIds : []);
  for (const [index, node] of value.nodes.entries()) {
    const prefix = `Node ${index + 1}`;
    if (!isRecord(node)) { errors.push(`${prefix} must be an object.`); continue; }
    if (!isId(node.id) || ids.has(node.id)) errors.push(`${prefix} needs a unique valid id.`);
    ids.add(node.id);
    if (!kinds.has(node.type)) errors.push(`${prefix} has an unsupported type.`);
    if (!isText(node.title, 200) || !node.title.trim()) errors.push(`${prefix} needs a title.`);
    if (node.description !== undefined && !isText(node.description)) errors.push(`${prefix} description must be text.`);
    if (node.actor !== undefined && !isText(node.actor, 100)) errors.push(`${prefix} actor must be text.`);
    validateTestHints(node.test, ['action', 'assertion'], prefix, errors, assignedRoleIds);
    validateEvaluations(node.evaluations, prefix, errors);
    if (!isRecord(node.position) || !['x', 'y'].every(axis => Number.isFinite(node.position[axis]) && Math.abs(node.position[axis]) <= 100000)) errors.push(`${prefix} needs finite x/y coordinates within ±100000.`);
    if (!isRecord(node.source) || !provenances.has(node.source.kind)) errors.push(`${prefix} needs proposed, inferred or observed source provenance.`);
    else if (node.source.reference !== undefined && !isText(node.source.reference)) errors.push(`${prefix} source reference must be text.`);
    if (node.screenshot !== undefined && !isImagePath(node.screenshot)) errors.push(`${prefix} screenshot must be a relative image path inside the document directory.`);
    if (node.screenshots !== undefined) {
      if (!isRecord(node.screenshots) || Object.keys(node.screenshots).length > 32) errors.push(`${prefix} screenshots must map up to 32 profile IDs to captures.`);
      else for (const [profileId, shot] of Object.entries(node.screenshots)) {
        if (!isId(profileId) || !isRecord(shot) || !isImagePath(shot.path) || !['width', 'height'].every(key => Number.isInteger(shot[key]) && shot[key] > 0 && shot[key] <= 30000) || !isRecord(shot.viewport) || !['width', 'height'].every(key => Number.isInteger(shot.viewport[key]) && shot.viewport[key] >= 240 && shot.viewport[key] <= 3840) || !['playwright', 'browser', 'import'].includes(shot.method) || typeof shot.capturedAt !== 'string' || !Number.isFinite(Date.parse(shot.capturedAt)) || (shot.url !== undefined && (!isText(shot.url, 2000) || !/^https?:\/\//.test(shot.url)))) errors.push(`${prefix} screenshot ${profileId} needs an image path, dimensions, viewport, capture date and method.`);
      }
    }
    if (node.preview !== undefined) {
      if (!isRecord(node.preview)) { errors.push(`${prefix} preview must be an object.`); continue; }
      for (const key of ['brand', 'actionLabel', 'title', 'eyebrow', 'description']) if (node.preview[key] !== undefined && !isText(node.preview[key], 1000)) errors.push(`${prefix} preview ${key} must be text.`);
      if (node.preview.variant !== undefined && !['default', 'commerce', 'success'].includes(node.preview.variant)) errors.push(`${prefix} preview variant must be default, commerce or success.`);
      for (const key of ['fields', 'items']) if (node.preview[key] !== undefined && (!Array.isArray(node.preview[key]) || node.preview[key].length > 20 || node.preview[key].some(item => !isRecord(item) || !isText(item.label, 200) || !isText(item.value, 500)))) errors.push(`${prefix} preview ${key} must contain up to 20 label/value objects.`);
    }
  }
  if (!ids.has(value.startNode)) errors.push('startNode must refer to an existing node.');
  const edgeIds = new Set();
  for (const [index, edge] of value.edges.entries()) {
    if (!isRecord(edge)) { errors.push(`Connection ${index + 1} must be an object.`); continue; }
    if (!isId(edge.id) || edgeIds.has(edge.id)) errors.push(`Connection ${index + 1} needs a unique valid id.`);
    edgeIds.add(edge.id);
    if (!ids.has(edge.source) || !ids.has(edge.target)) errors.push(`Connection ${index + 1} references a missing node.`);
    if (!isText(edge.label, 200) || !edge.label.trim()) errors.push(`Connection ${index + 1} needs a label.`);
    if (edge.condition !== undefined && !isText(edge.condition, 1000)) errors.push(`Connection ${index + 1} condition must be text.`);
    if (edge.parallel !== undefined && typeof edge.parallel !== 'boolean') errors.push(`Connection ${index + 1} parallel must be a boolean.`);
    validateTestHints(edge.test, ['action'], `Connection ${index + 1}`, errors, assignedRoleIds);
  }
  validateUserStories(value.userStories, ids, edgeIds, errors);
  errors.push(...validateRoleAudit(value, ids, edgeIds));
  return { valid: errors.length === 0, errors };
}

// The generated suite repeats mapped paths and can exceed the source graph's
// budget without making that graph any larger. Keep every generated scenario.
export const documentSourceBytes = document => Buffer.byteLength(JSON.stringify(isRecord(document) ? { ...document, testScenarios: undefined } : document));

export async function readDocument(path) {
  const content = await readFile(path, 'utf8');
  let document;
  try { document = JSON.parse(content); } catch { throw new Error('Flow document contains invalid JSON.'); }
  if (documentSourceBytes(document) > MAX_DOCUMENT_BYTES) throw new Error('Flow source document exceeds 1 MB.');
  const result = validateDocument(document);
  if (!result.valid) throw new Error(result.errors.join('\n'));
  return { document, revision: createHash('sha256').update(content).digest('hex').slice(0,16) };
}

SHA-256: 89859938c246703dd7b687416eb44586f41b700477df778694c9d99192dc05a4