← Files Flows by plugin.spaceARCHIVED FILE

lib/quality-suggestions.mjs

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

↓ Download file

// Browser-safe proposals grounded in mapped locations. This module never runs or grades an eval.
import { flowUserRoles } from './user-roles.mjs';

const text = value => typeof value === 'string' ? value.trim() : '';
const list = value => Array.isArray(value) ? value : [];
const unique = values => [...new Set(values)];
const sorted = values => [...values].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
const validId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,100}$/.test(value);
const provenance = source => source?.kind === 'provided' ? 'provided' : 'inferred';
function systemActor(value) {
  const actor = text(value).toLowerCase();
  if (/^(ai|automated|autonomous|software|system) agent$/.test(actor)) return true;
  if (/\b(owner|agent|admin|administrator|user|customer|operator|employee|staff|buyer|seller|merchant|manager|developer|engineer|representative)\b/.test(actor)) return false;
  return /(^|\s)(system|application|backend|back-end|server|service|api|automation)$/.test(actor)
    || /^(worker|background|background worker|job worker|queue worker)$/.test(actor)
    || /(^|\s)(payment|email|identity|authentication|auth|sms|storage|cloud|notification) provider$/.test(actor);
}
function qualityId(prefix, ...parts) {
  const value = JSON.stringify(parts);
  let a = 2166136261, b = 5381;
  for (let index = 0; index < value.length; index += 1) {
    const code = value.charCodeAt(index);
    a = Math.imul(a ^ code, 16777619);
    b = Math.imul(b, 33) ^ code;
  }
  return `${prefix}-${(a >>> 0).toString(16).padStart(8, '0')}${(b >>> 0).toString(16).padStart(8, '0')}`;
}
const criterion = (id, question, meetsExpectation, needsWork) => ({ id, question, meetsExpectation, needsWork });

const focuses = {
  comprehension: {
    label: 'Understanding the next step',
    expectation: 'The person understands what this step is for and can work out how to continue toward their goal.',
    criteria: [criterion('understanding', 'Can the person explain what they can do here in their own words?', 'Their explanation matches the purpose and they continue without a hint.', 'They misinterpret the purpose, hesitate because of unclear wording, or need a hint.')],
  },
  decision: {
    label: 'Confidence in a choice',
    expectation: 'The person can choose an option that fits their situation and understands its consequences.',
    criteria: [criterion('choice', 'Can the person explain why an option fits their needs and what follows?', 'They distinguish the alternatives and choose for a reason consistent with their needs.', 'They guess, misunderstand the trade-off, or encounter a consequence they did not expect.')],
  },
  recovery: {
    label: 'Recovering and trying again',
    expectation: 'The person understands why they returned to an earlier step and can continue without losing track of their goal.',
    criteria: [criterion('recovery', 'Can the person understand the interruption and work out a useful next attempt?', 'They explain what happened and resume with a clear next action.', 'They repeat an ineffective attempt, believe progress was lost, or need help to continue.')],
  },
  feedback: {
    label: 'Understanding the outcome',
    expectation: 'The person knows what happened, whether their goal was met and what remains to be done.',
    criteria: [criterion('outcome', 'Does the person interpret the outcome and its next steps correctly?', 'Their description matches the actual outcome and they know whether further action is needed.', 'They mistake an intermediate state for completion or are unsure what happened or what to do next.')],
  },
  effort: {
    label: 'Effort and control',
    expectation: 'The person can complete this action without avoidable confusion or unnecessary work.',
    criteria: [criterion('effort', 'Where does this action create unnecessary effort or loss of control?', 'The person completes the action, understands its consequences and reports no unresolved obstacle.', 'They repeat work, lose entered information, or cannot correct an action they did not intend.')],
  },
  'output-quality': {
    label: 'Usefulness of the output',
    expectation: 'The output satisfies the intended use and the explicitly agreed quality requirements.',
    criteria: [criterion('usefulness', 'Does the output address the actual request in its context?', 'A reviewer can point to evidence that the output meets each agreed requirement.', 'The output misses an important requirement, adds unsupported claims, or needs substantial correction.'), criterion('grounding', 'Are material claims supported by the supplied sources or reference examples?', 'Material claims are supported; uncertainty and missing information are handled as agreed.', 'Material claims are unsupported or missing information is concealed.')],
  },
};

function scenarioIndex(cases, field) {
  const index = new Map();
  for (const scenario of cases) for (const id of list(scenario[field])) {
    if (!index.has(id)) index.set(id, new Set());
    index.get(id).add(scenario.id);
  }
  return index;
}

const scenarioRoles = (scenarioIds, casesById) => unique(scenarioIds.flatMap(id => list(casesById.get(id)?.userRoleIds).filter(validId))).sort();
const matchesRole = (item, userRoleId) => userRoleId === null ? !list(item.userRoleIds).length : list(item.userRoleIds).includes(userRoleId);

/** One proposal per mapped opportunity, not one duplicate for every route through it. */
export function generateQualitySuggestions(document, cases = []) {
  const nodes = new Map(), edges = new Map();
  for (const node of sorted(list(document?.nodes).filter(node => validId(node?.id)))) if (!nodes.has(node.id)) nodes.set(node.id, node);
  for (const edge of sorted(list(document?.edges).filter(edge => validId(edge?.id)))) if (nodes.has(edge.source) && nodes.has(edge.target) && !edges.has(edge.id)) edges.set(edge.id, edge);
  const outgoing = new Map([...nodes.keys()].map(id => [id, []]));
  for (const edge of edges.values()) outgoing.get(edge.source).push(edge);
  const byNode = scenarioIndex(cases, 'nodeIds'), byEdge = scenarioIndex(cases, 'edgeIds');
  // Explicit transition scope narrows the related routes; a shared entry screen
  // must not pull an excluded alternative back into a story.
  const related = (nodeIds, edgeIds) => unique(edgeIds.length ? edgeIds.flatMap(id => [...(byEdge.get(id) ?? [])]) : nodeIds.flatMap(id => [...(byNode.get(id) ?? [])])).sort();
  const reached = new Set(), queue = nodes.has(document?.startNode) ? [document.startNode] : [];
  while (queue.length) {
    const id = queue.pop();
    if (reached.has(id)) continue;
    reached.add(id);
    for (const edge of outgoing.get(id)) queue.push(edge.target);
  }
  const foreground = new Set(), visibleQueue = nodes.has(document?.startNode) ? [document.startNode] : [];
  while (visibleQueue.length) {
    const id = visibleQueue.pop();
    if (foreground.has(id)) continue;
    foreground.add(id);
    for (const edge of outgoing.get(id)) if (edge.parallel !== true) visibleQueue.push(edge.target);
  }
  const backgroundOnly = id => reached.has(id) && !foreground.has(id);
  const useCases = [], storyIds = new Set();
  for (const story of sorted(list(document?.userStories).filter(story => validId(story?.id)))) {
    if (storyIds.has(story.id)) continue;
    storyIds.add(story.id);
    const nodeIds = unique(list(story.nodeIds).filter(id => nodes.has(id)));
    const edgeIds = unique(list(story.edgeIds).filter(id => edges.has(id)));
    if (!nodeIds.length || !text(story.goal)) continue;
    const source = provenance(story.source);
    useCases.push({
      id: qualityId('story', document?.id, story.id), title: text(story.goal), source,
      ...(text(story.source?.reference) ? { sourceReference: text(story.source.reference) } : {}),
      story: { actor: text(story.actor), goal: text(story.goal), benefit: text(story.benefit), ...(text(story.context) ? { context: text(story.context) } : {}) },
      nodeIds, edgeIds, scenarioIds: related(nodeIds, edgeIds), acceptanceCriteria: list(story.acceptanceCriteria).map(text).filter(Boolean),
      questions: [source === 'inferred' ? 'Confirm this candidate need with representative users before treating it as a requirement.' : 'Confirm that this supplied requirement reflects the needs of the intended users; a requirement is not research evidence.', ...(!text(story.context) ? ['What realistic situation, constraints and prepared data should the task use?'] : []), ...(!list(story.acceptanceCriteria).length ? ['Which observable outcomes would demonstrate that this need has been met?'] : [])],
    });
  }
  // Outcome candidates retain the map label for reviewer orientation, not as an invented participant task.
  const candidates = [...nodes.values()].filter(node => !systemActor(node.actor) && !backgroundOnly(node.id) && (!outgoing.get(node.id).some(edge => edge.parallel !== true) || node.type === 'state'));
  if (!candidates.length && nodes.has(document?.startNode) && !systemActor(nodes.get(document.startNode).actor)) candidates.push(nodes.get(document.startNode));
  for (const node of candidates) {
    if (useCases.some(useCase => useCase.nodeIds.includes(node.id))) continue;
    const edgeIds = [...edges.values()].filter(edge => edge.target === node.id).map(edge => edge.id);
    useCases.push({ id: qualityId('candidate', document?.id, node.id), title: `Candidate outcome: ${text(node.title) || node.id}`, source: 'inferred',
      story: { actor: text(node.actor) || 'User role to confirm', goal: `Confirm the user goal behind: ${text(node.title) || node.id}`, benefit: 'The benefit to the user has not been supplied.' },
      nodeIds: [node.id], edgeIds, scenarioIds: related([node.id], []), acceptanceCriteria: [],
      questions: ['Is this a desired outcome, an intermediate state, or an exception the person needs to recover from?', 'Who needs this outcome, in what situation, and why does it matter?', 'Write a realistic task in the user’s language without naming controls or revealing the route.', 'Agree observable acceptance criteria using user research or supplied requirements.'],
    });
  }
  const cycleTargets = new Set(cases.filter(scenario => scenario.termination === 'cycle').map(scenario => edges.get(scenario.edgeIds.at(-1))?.target).filter(Boolean));
  const evaluations = [];
  for (const node of nodes.values()) {
    const hints = sorted(list(node.evaluations).filter(hint => validId(hint?.id) && Object.hasOwn(focuses, hint.focus) && text(hint.expectation))).map(hint => ({ ...hint, mapped: true }));
    const baseFocus = node.type === 'decision' || outgoing.get(node.id).filter(edge => edge.parallel !== true).length > 1 ? 'decision' : node.type === 'state' ? 'feedback' : node.type === 'action' ? 'effort' : 'comprehension';
    const inferred = systemActor(node.actor) || backgroundOnly(node.id) ? [] : unique([baseFocus, ...(cycleTargets.has(node.id) ? ['recovery'] : []), ...(outgoing.get(node.id).some(edge => edge.parallel === true) ? ['feedback'] : [])]).filter(focus => !hints.some(hint => hint.focus === focus)).map(focus => ({ id: `inferred-${focus}`, focus }));
    const hintIds = new Set();
    for (const hint of [...hints, ...inferred]) {
      const hintKey = `${hint.mapped ? 'mapped' : 'derived'}-${hint.id}`;
      if (hintIds.has(hintKey)) continue;
      hintIds.add(hintKey);
      const template = focuses[hint.focus], source = provenance(hint.source);
      const linked = useCases.filter(useCase => useCase.nodeIds.includes(node.id));
      const supplied = linked.filter(useCase => !useCase.id.startsWith('candidate-'));
      const story = supplied.length === 1 ? supplied[0] : undefined;
      const edgeIds = [...edges.values()].filter(edge => edge.source === node.id || edge.target === node.id).map(edge => edge.id);
      const scenarioIds = related([node.id], []);
      const criteria = template.criteria.map(item => ({ ...item }));
      if (text(hint.expectation)) criteria.unshift(criterion('mapped-expectation', `Does the observed experience meet this requirement: ${text(hint.expectation)}`, 'Observed evidence supports this requirement in the agreed context.', 'Observed evidence contradicts the requirement or the outcome needs assistance.'));
      evaluations.push({
        id: qualityId('eval', document?.id, node.id, hintKey), title: `${template.label} — ${text(node.title) || node.id}`, focus: hint.focus, status: 'draft', source,
        ...(text(hint.source?.reference) ? { sourceReference: text(hint.source.reference) } : {}),
        nodeIds: [node.id], edgeIds, scenarioIds, useCaseIds: linked.map(useCase => useCase.id),
        rationale: text(hint.rationale) || `The mapped ${text(node.type) || 'step'} “${text(node.title) || node.id}” is a place to check ${template.label.toLowerCase()} beyond functional completion.`,
        task: text(hint.task) || (hint.focus === 'output-quality'
          ? `Review brief to prepare: assess representative outputs against ${story ? `the user goal “${story.story.goal}”` : 'the agreed user goal'}, the supplied context and task-specific reference examples.`
          : story ? `${story.story.context ? `${story.story.context} ` : ''}Your goal: ${story.story.goal}. Work toward it in your own way and stop when you believe you have finished.` : 'Task to prepare: agree a realistic user goal and situation, then ask the participant to work toward that goal in their own way.'),
        expectation: text(hint.expectation) || template.expectation,
        method: hint.focus === 'output-quality' ? 'expert-review' : 'usability-session',
        criteria,
        evidenceToCollect: hint.focus === 'output-quality' ? ['Representative inputs with their context, expected requirements and source material.', 'The actual output and a reviewer’s evidence for each criterion; include typical and difficult examples.', 'Examples of acceptable and unacceptable outputs agreed by reviewers.'] : ['Observed behavior, hesitation, mistaken choices and any assistance needed.', 'The participant’s explanation of the outcome and whether it met their original goal.', 'Concrete observations or quotes for each criterion; record inconclusive evidence separately.'],
        questions: [
          ...(source === 'inferred' ? ['Confirm that this suggested quality expectation matters to the intended users.'] : ['Check this supplied expectation against user evidence before making it a release criterion.']),
          ...(hint.focus === 'output-quality' ? ['Prepare a reviewer brief with the intended use, input context and task-specific reference examples.'] : !text(hint.task) && !story ? ['Prepare a participant task: the map alone does not establish user motivation or context.'] : ['Review the task for realistic context and remove UI labels or instructions that reveal how to complete it.']),
          ...(supplied.length > 1 ? ['Several user stories touch this step; run a separate task for each distinct goal and context.'] : []),
          ...(!reached.has(node.id) ? ['This step is unreachable from the mapped start; establish its entry point before a session.'] : []),
          ...(!scenarioIds.length ? ['No related functional scenario is available; check entry conditions or background behavior separately.'] : []),
          ...(node.source?.kind !== 'observed' ? ['Confirm the mapped behavior against the application; its evidence is proposed, inferred or unspecified.'] : []),
          ...(hint.focus === 'output-quality' ? ['Agree task-specific examples and rating anchors with human reviewers. If scoring is automated later, calibrate it against human judgments.'] : ['Recruit people who represent the intended users, including relevant access needs; avoid coaching during the task.']),
          'These are suggested criteria. No evaluation has been run and no pass/fail result is assigned.',
        ],
      });
    }
  }
  // Role membership follows explicit functional routes, never actor wording or
  // flow-wide membership alone. Unlinked opportunities remain unclassified.
  const casesById = new Map(cases.map(scenario => [scenario.id, scenario]));
  for (const item of [...useCases, ...evaluations]) item.userRoleIds = scenarioRoles(item.scenarioIds, casesById);
  const usedRoles = new Set([...useCases, ...evaluations].flatMap(item => item.userRoleIds));
  const userRoles = sorted(flowUserRoles(document).filter(role => usedRoles.has(role.id)));
  return { version: 1, status: 'draft', userRoles, useCases, evaluations, warnings: ['Suggestions complement functional tests; route coverage does not measure user satisfaction or quality.', 'Provided requirements and inferred suggestions both need review. Observed UI behavior alone does not prove a user need.', 'Agree realistic tasks, participants, evidence and rating anchors before evaluation. No scores or results are generated.'] };
}

/** Select a role without leaving references to scenarios or use cases outside the selection. */
export function filterQualitySuggestions(suite, userRoleId, cases) {
  if (userRoleId === undefined) return suite;
  const casesById = cases === undefined ? undefined : new Map(cases.filter(scenario => matchesRole(scenario, userRoleId)).map(scenario => [scenario.id, scenario]));
  const filterItems = items => items.map(item => {
    const scenarioIds = casesById ? item.scenarioIds.filter(id => casesById.has(id)) : item.scenarioIds;
    return { ...item, scenarioIds, userRoleIds: casesById ? scenarioRoles(scenarioIds, casesById) : list(item.userRoleIds) };
  }).filter((item, index) => casesById
    ? item.scenarioIds.length > 0 || (userRoleId === null && matchesRole(items[index], null) && items[index].scenarioIds.length === 0)
    : matchesRole(item, userRoleId));
  const useCases = filterItems(suite.useCases);
  const useCaseIds = new Set(useCases.map(item => item.id));
  const evaluations = filterItems(suite.evaluations).map(item => ({ ...item, useCaseIds: item.useCaseIds.filter(id => useCaseIds.has(id)) }));
  const usedRoles = new Set([...useCases, ...evaluations].flatMap(item => item.userRoleIds));
  return { ...suite, userRoles: list(suite.userRoles).filter(role => usedRoles.has(role.id)), useCases, evaluations };
}

export function exportQualitySuggestionsJson(document, cases = [], options = {}) {
  return `${JSON.stringify(filterQualitySuggestions(generateQualitySuggestions(document, cases), options.userRoleId, cases), null, 2)}\n`;
}

// Source text stays literal in a portable research brief (no HTML or active Markdown links).
const markdown = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/[\\`*_{}\[\]()#+.!|~-]/g, '\\$&').replace(/[\r\n]+/g, ' ');
export function exportQualitySuggestionsMarkdown(document, cases = [], options = {}) {
  const suite = filterQualitySuggestions(generateQualitySuggestions(document, cases), options.userRoleId, cases);
  const rolesById = new Map(suite.userRoles.map(role => [role.id, role.name]));
  const roleNames = item => item.userRoleIds.map(id => markdown(rolesById.get(id) || id)).join(', ') || 'Unclassified';
  const lines = [`# Quality suggestions: ${markdown(document?.name || 'Flow')}`, '', 'Draft research brief — no evaluations have been run.', '', ...suite.warnings.map(value => `- ${markdown(value)}`), '', '## Use cases', ''];
  for (const useCase of suite.useCases) {
    lines.push(`### ${markdown(useCase.title)}`, '', `Source: ${useCase.source === 'provided' ? 'Provided requirement' : 'Inferred suggestion'}`, ...(useCase.sourceReference ? [`Reference: ${markdown(useCase.sourceReference)}`] : []), `User roles: ${roleNames(useCase)}`, `Actor: ${markdown(useCase.story.actor)}`, `Goal: ${markdown(useCase.story.goal)}`, `Benefit: ${markdown(useCase.story.benefit)}`, ...(useCase.story.context ? [`Context: ${markdown(useCase.story.context)}`] : []), `Mapped steps: ${useCase.nodeIds.map(markdown).join(', ')}`, `Related functional scenarios: ${useCase.scenarioIds.map(markdown).join(', ') || 'None'}`, '', 'Acceptance criteria:', ...useCase.acceptanceCriteria.map(value => `- ${markdown(value)}`), '', 'Questions to resolve:', ...useCase.questions.map(value => `- ${markdown(value)}`), '');
  }
  lines.push('## Quality eval opportunities', '');
  for (const evaluation of suite.evaluations) {
    lines.push(`### ${markdown(evaluation.title)}`, '', `Source: ${evaluation.source === 'provided' ? 'Provided requirement' : 'Inferred suggestion'}`, ...(evaluation.sourceReference ? [`Reference: ${markdown(evaluation.sourceReference)}`] : []), `User roles: ${roleNames(evaluation)}`, `Mapped steps: ${evaluation.nodeIds.map(markdown).join(', ')}`, `Related functional scenarios: ${evaluation.scenarioIds.map(markdown).join(', ') || 'None'}`, `Method: ${evaluation.method === 'expert-review' ? 'Expert review' : 'Usability session'}`, `Why here: ${markdown(evaluation.rationale)}`, `Participant task / review brief: ${markdown(evaluation.task)}`, `Expected experience: ${markdown(evaluation.expectation)}`, '', 'Suggested rubric:', '');
    for (const item of evaluation.criteria) lines.push(`- ${markdown(item.question)}`, `  - Meets expectation: ${markdown(item.meetsExpectation)}`, `  - Needs work: ${markdown(item.needsWork)}`);
    lines.push('', 'Evidence to collect:', ...evaluation.evidenceToCollect.map(value => `- ${markdown(value)}`), '', 'Questions to resolve:', ...evaluation.questions.map(value => `- ${markdown(value)}`), '');
  }
  return `${lines.join('\n')}\n`;
}

SHA-256: 45a6ddd827e315b2e585527ddbf94a3491cf609ef6da3a79695cb269af4f8216