Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

10.2 KB
Raw Blame
#!/usr/bin/env node
'use strict';

// Captures a /genpage working directory into an eval fixture folder.
//
// Copies the agent-produced artifacts (.tsx, RuntimeTypes.ts, workflow-log.md,
// genpage-plan.md, genpage-edit-plan.md, genpage-entity-creation-log.md) into
// evals/model-apps/genpage/fixtures/<eval-id>-<slug>/, skipping local-dev
// scaffolding (package.json, genpage.d.ts) and build artifacts (node_modules,
// dist, *.log).
//
// After copying, runs both Layer 1 and Layer 2 against the new fixture and
// prints the pass/fail counts. Capture exit code stays 0 regardless of runner
// results — drift detection is diagnostic, not failure.
//
// Usage:
//   node capture-fixture.js --working-dir <path> --eval <id> --slug <slug> [--force] [--skip-verify]
//
// Flags:
//   --working-dir <path>  Absolute or relative path to the /genpage working dir
//   --eval <id>           Numeric eval id (must exist in evals.json)
//   --slug <slug>         Kebab-case slug for the fixture folder name
//   --force               Overwrite an existing fixture directory
//   --skip-verify         Skip running Layer 1 / Layer 2 after capture
//
// Exit codes:
//   0 success (capture written; runner results are informational only)
//   1 invalid arguments
//   2 I/O error (working dir missing, etc.)

const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { makeWritesBlocking } = require('./lib/output-redaction.js');

const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');
const FIXTURES_DIR = path.join(
  REPO_ROOT,
  'evals',
  'model-apps',
  'genpage',
  'fixtures',
);
const EVALS_JSON = path.join(
  REPO_ROOT,
  'evals',
  'model-apps',
  'genpage',
  'evals.json',
);
const LAYER1_SCRIPT = path.join(
  REPO_ROOT,
  'evals',
  'model-apps',
  'genpage',
  'run-layer-1.js',
);
const LAYER2_SCRIPT = path.join(
  REPO_ROOT,
  'evals',
  'model-apps',
  'genpage',
  'run-layer-2.js',
);

const COPY_ALLOWLIST = [
  /\.tsx$/,
  /\.md$/,
  /^RuntimeTypes\.ts$/i,
];

// Files we never want in fixtures — they're either local-dev scaffolding
// generated by Phase 0.5 (not the agent's output) or build artifacts.
const DENYLIST_FILES = new Set([
  'package.json',
  'package-lock.json',
  'genpage.d.ts',
  '.DS_Store',
  'Thumbs.db',
]);
const DENYLIST_DIRS = new Set([
  'node_modules',
  'dist',
  'build',
  '.cache',
  '.tmp',
  '.next',
]);

function parseArgs(argv) {
  const args = {
    workingDir: null,
    eval: null,
    slug: null,
    force: false,
    skipVerify: false,
  };
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    switch (a) {
      case '--working-dir':
        args.workingDir = argv[++i];
        break;
      case '--eval':
        args.eval = parseInt(argv[++i], 10);
        if (Number.isNaN(args.eval)) throw new Error('--eval requires a numeric id');
        break;
      case '--slug':
        args.slug = argv[++i];
        break;
      case '--force':
        args.force = true;
        break;
      case '--skip-verify':
        args.skipVerify = true;
        break;
      case '--help':
      case '-h':
        printHelp();
        process.exit(0);
      default:
        throw new Error(`Unknown argument: ${a}`);
    }
  }
  if (!args.workingDir) throw new Error('--working-dir is required');
  if (args.eval === null) throw new Error('--eval is required');
  if (!args.slug) throw new Error('--slug is required');
  if (!/^[a-z][a-z0-9-]*$/.test(args.slug)) {
    throw new Error(`--slug must be kebab-case (got: ${args.slug})`);
  }
  return args;
}

function printHelp() {
  console.log(`Usage: capture-fixture.js --working-dir <path> --eval <id> --slug <slug> [options]

Required:
  --working-dir <path>  Path to a /genpage working dir
  --eval <id>           Numeric eval id (must exist in evals.json)
  --slug <slug>         Kebab-case slug for the fixture folder

Options:
  --force               Overwrite an existing fixture
  --skip-verify         Skip running Layer 1 / Layer 2 after capture
  --help                Show this message

Copies agent-produced artifacts (.tsx, RuntimeTypes.ts, *.md files) into:
  evals/model-apps/genpage/fixtures/<eval-id>-<slug>/

Excluded automatically: package.json, genpage.d.ts (Phase 0.5 scaffolding),
node_modules/, dist/, build/, *.log files.
`);
}

function evalExists(evalId) {
  const data = JSON.parse(fs.readFileSync(EVALS_JSON, 'utf8'));
  return data.evals.some((e) => e.id === evalId);
}

function shouldCopyFile(name) {
  if (DENYLIST_FILES.has(name)) return false;
  if (name.endsWith('.log')) return false;
  return COPY_ALLOWLIST.some((re) => re.test(name));
}

function copyAllowedFiles(srcDir, dstDir) {
  fs.mkdirSync(dstDir, { recursive: true });
  const entries = fs.readdirSync(srcDir, { withFileTypes: true });
  const copied = [];
  const skipped = [];
  for (const entry of entries) {
    const srcPath = path.join(srcDir, entry.name);
    if (entry.isDirectory()) {
      if (DENYLIST_DIRS.has(entry.name)) {
        skipped.push({ name: entry.name + '/', reason: 'denylisted directory' });
        continue;
      }
      // Don't recurse — /genpage working dirs are flat.
      // Exception: edit-flow downloads put files under <page-id>/, but we
      // capture those separately if needed by passing the page-id dir directly.
      skipped.push({ name: entry.name + '/', reason: 'subdirectory (not captured)' });
      continue;
    }
    if (!shouldCopyFile(entry.name)) {
      skipped.push({ name: entry.name, reason: 'not in allowlist or denylisted' });
      continue;
    }
    const dstPath = path.join(dstDir, entry.name);
    fs.copyFileSync(srcPath, dstPath);
    copied.push(entry.name);
  }
  return { copied, skipped };
}

function runRunner(scriptPath, evalId) {
  const result = spawnSync(
    process.execPath,
    [scriptPath, '--eval', String(evalId)],
    { encoding: 'utf8' },
  );
  return {
    exitCode: result.status,
    stdout: result.stdout || '',
    stderr: result.stderr || '',
  };
}

function parseTapSummary(stdout) {
  const m = {
    tests: stdout.match(/^# tests\s+(\d+)/m)?.[1],
    pass: stdout.match(/^# pass\s+(\d+)/m)?.[1],
    fail: stdout.match(/^# fail\s+(\d+)/m)?.[1],
    skip: stdout.match(/^# skip\s+(\d+)/m)?.[1],
  };
  return {
    tests: Number(m.tests ?? 0),
    pass: Number(m.pass ?? 0),
    fail: Number(m.fail ?? 0),
    skip: Number(m.skip ?? 0),
  };
}

function extractFailures(stdout) {
  // Pull only indented assertion failures ("    not ok N - <text>"), excluding
  // the non-indented fixture-level result lines emitted by the TAP reporter.
  const lines = stdout.split('\n');
  return lines
    .filter((l) => /^\s{4}not ok \d+ - /.test(l))
    .map((l) => l.trim());
}

// One layer's verdict for the summary. The documented review rule is "both `failures` arrays empty → the fixture is
// good to commit", so a runner that produced NO verdict has to put something into `failures` itself. Two cases used to
// leave it empty and read as a clean capture:
//   - the runner exited nonzero without reporting a failing assertion — a crash, or its own refusal (exit 2 when the
//     eval id matches no fixture). Its counts, if any, are not a result. Its exit code was read and then dropped.
//   - the runner exited 0 but reported no assertions, so nothing was verified.
// The process itself still exits 0: the files were captured, and a capture of a run with real failures is still a
// capture — the summary is how the caller judges it.
function layerSummary(run) {
  const counts = parseTapSummary(run.stdout);
  const failures = extractFailures(run.stdout);
  if (run.exitCode !== 0 && failures.length === 0) {
    const detail = String(run.stderr || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean).slice(-3).join(' | ');
    failures.push(`runner exited ${run.exitCode === null ? 'without an exit code' : run.exitCode} without reporting a failing assertion — its result is not verified${detail ? `: ${detail.slice(0, 300)}` : ''}`);
  } else if (run.exitCode === 0 && counts.tests === 0) {
    failures.push('runner reported no assertions for this eval — nothing was verified');
  }
  return { ...counts, exitCode: run.exitCode, failures };
}

function main() {
  let args;
  try {
    args = parseArgs(process.argv.slice(2));
  } catch (err) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: ${err.message}`);
    process.exit(1);
  }

  const workingDir = path.resolve(args.workingDir);
  if (!fs.existsSync(workingDir) || !fs.statSync(workingDir).isDirectory()) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: working directory does not exist or is not a directory: ${workingDir}`);
    process.exit(2);
  }

  if (!evalExists(args.eval)) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: no eval with id ${args.eval} in evals.json`);
    process.exit(1);
  }

  const fixtureName = `${args.eval}-${args.slug}`;
  const fixtureDir = path.join(FIXTURES_DIR, fixtureName);

  if (fs.existsSync(fixtureDir)) {
    if (!args.force) {
      makeWritesBlocking(process.stdout, process.stderr);
      console.error(
        `error: fixture already exists: ${fixtureDir}\n` +
          `       pass --force to overwrite, or pick a different --slug`,
      );
      process.exit(2);
    }
    fs.rmSync(fixtureDir, { recursive: true, force: true });
  }

  const { copied, skipped } = copyAllowedFiles(workingDir, fixtureDir);

  if (copied.length === 0) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(
      `error: no allowlisted files found in ${workingDir}\n` +
        `       expected at least one of: *.tsx, *.md, RuntimeTypes.ts`,
    );
    fs.rmSync(fixtureDir, { recursive: true, force: true });
    process.exit(2);
  }

  const summary = {
    eval: args.eval,
    slug: args.slug,
    fixtureDir,
    copied,
    skipped,
  };

  if (!args.skipVerify) {
    summary.layer1 = layerSummary(runRunner(LAYER1_SCRIPT, args.eval));
    summary.layer2 = layerSummary(runRunner(LAYER2_SCRIPT, args.eval));
  }

  console.log(JSON.stringify(summary, null, 2));
}

if (require.main === module) main();

module.exports = {
  parseArgs,
  shouldCopyFile,
  copyAllowedFiles,
  parseTapSummary,
  extractFailures,
  COPY_ALLOWLIST,
  DENYLIST_FILES,
  DENYLIST_DIRS,
};