All files / scripts extend-artifacts.js

98.11% Statements 52/53
98.27% Branches 57/58
100% Functions 6/6
97.95% Lines 48/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370                                                                                                                                        34x     34x 2x     32x   8x     8x 7x 7x 7x 3x       5x                                                           30x 2x                         28x 28x   2x                     26x 30x     30x 30x 1x                         25x 25x   25x 8x 8x   8x 2x                             23x   3x 3x 20x 17x     3x 3x     23x 23x   23x 19x 19x 19x                             23x                                                           7x 1x                 11x 11x 11x   6x                                                                                                                                                                                                                
#!/usr/bin/env node
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module scripts/extend-artifacts
 * @description Batch artifact-extension helper for Stage B analysis runs.
 *
 * The check-then-extend pattern (write short stub → wc -l check → cat >> extend)
 * wastes 2+ LLM invocations per artifact. This script processes a batch of
 * artifact extensions in a single Node.js execution, eliminating the per-
 * artifact shell-heredoc overhead that costs ~38 invocations per run.
 *
 * Each spec entry can:
 *   - `append`  — append content to an existing file (or create it)
 *   - `create`  — create a new file (fails if it exists unless `overwrite: true`)
 *   - `prepend` — prepend content to an existing file
 *
 * The spec is read from a JSON file (--spec-file) or from stdin (--stdin).
 *
 * Input spec schema (JSON array):
 *   [
 *     {
 *       "path": "relative/or/absolute/path.md",   // required
 *       "content": "Text to write",               // required
 *       "mode": "append" | "create" | "prepend",  // optional, default: "append"
 *       "overwrite": false                        // optional, default: false
 *     },
 *     ...
 *   ]
 *
 * Output: JSON summary on stdout listing each file written, line counts, and
 *   any errors. Exits 0 when all specs were applied; exits 1 if any failed.
 *
 * Invocation:
 *   node scripts/extend-artifacts.js --spec-file /path/to/spec.json \
 *     [--base-dir analysis/daily/2026-05-14/breaking] \
 *     [--dry-run]
 *
 *   cat spec.json | node scripts/extend-artifacts.js --stdin \
 *     [--base-dir analysis/daily/2026-05-14/breaking]
 *
 * Exports (for unit testing):
 *   extendArtifact(spec, baseDir)
 *   extendArtifacts(specs, baseDir, dryRun)
 *   resolveArtifactPath(specPath, baseDir)
 */
 
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
 
// ---------------------------------------------------------------------------
// Path resolution
// ---------------------------------------------------------------------------
 
/**
 * Resolve a spec path against an optional base directory.
 *
 * Absolute paths are used as-is. Relative paths are joined with `baseDir`
 * (if provided) or resolved against `process.cwd()`.
 *
 * @param {string} specPath - Path from the spec entry
 * @param {string} [baseDir] - Optional base directory override
 * @returns {string} Resolved absolute path
 */
export function resolveArtifactPath(specPath, baseDir) {
  const base = baseDir ?? process.cwd();
 
  // Reject absolute paths when baseDir is provided — forces confinement
  if (baseDir && path.isAbsolute(specPath)) {
    throw new Error(`Absolute paths are not allowed when --base-dir is set: ${specPath}`);
  }
 
  if (path.isAbsolute(specPath)) return specPath;
 
  const resolved = path.resolve(base, specPath);
 
  // Prevent path traversal: resolved path must be within baseDir
  if (baseDir) {
    const normalizedBase = path.resolve(base);
    const normalizedResolved = path.resolve(resolved);
    if (!normalizedResolved.startsWith(normalizedBase + '/') && normalizedResolved !== normalizedBase) {
      throw new Error(`Path traversal detected: "${specPath}" resolves outside base-dir "${baseDir}"`);
    }
  }
 
  return resolved;
}
 
// ---------------------------------------------------------------------------
// Single-artifact extension
// ---------------------------------------------------------------------------
 
/**
 * Apply a single spec entry (extend/create/prepend one artifact file).
 *
 * @param {{
 *   path: string,
 *   content: string,
 *   mode?: 'append'|'create'|'prepend',
 *   overwrite?: boolean
 * }} spec
 * @param {string} [baseDir]
 * @param {boolean} [dryRun]
 * @returns {{
 *   path: string,
 *   resolvedPath: string,
 *   mode: string,
 *   ok: boolean,
 *   linesBefore: number,
 *   linesAfter: number,
 *   bytesWritten: number,
 *   error?: string
 * }}
 */
export function extendArtifact(spec, baseDir, dryRun = false) {
  if (!spec || typeof spec.path !== 'string' || typeof spec.content !== 'string') {
    return {
      path: spec?.path ?? '(missing)',
      resolvedPath: '',
      mode: 'unknown',
      ok: false,
      linesBefore: 0,
      linesAfter: 0,
      bytesWritten: 0,
      error: 'Invalid spec: path and content are required strings',
    };
  }
 
  let resolvedPath;
  try {
    resolvedPath = resolveArtifactPath(spec.path, baseDir);
  } catch (err) {
    return {
      path: spec.path,
      resolvedPath: '',
      mode: spec.mode ?? 'append',
      ok: false,
      linesBefore: 0,
      linesAfter: 0,
      bytesWritten: 0,
      error: String(err.message ?? err),
    };
  }
  const mode = spec.mode ?? 'append';
  const overwrite = spec.overwrite ?? false;
 
  // Reject unknown mode values
  const VALID_MODES = ['append', 'create', 'prepend'];
  if (!VALID_MODES.includes(mode)) {
    return {
      path: spec.path,
      resolvedPath,
      mode,
      ok: false,
      linesBefore: 0,
      linesAfter: 0,
      bytesWritten: 0,
      error: `Invalid mode "${mode}": must be one of ${VALID_MODES.join(', ')}`,
    };
  }
 
  // --- pre-flight ---
  let linesBefore = 0;
  let existingContent = '';
 
  if (fs.existsSync(resolvedPath)) {
    existingContent = fs.readFileSync(resolvedPath, 'utf8');
    linesBefore = existingContent.split('\n').length;
 
    if (mode === 'create' && !overwrite) {
      return {
        path: spec.path,
        resolvedPath,
        mode,
        ok: false,
        linesBefore,
        linesAfter: linesBefore,
        bytesWritten: 0,
        error: `File already exists and overwrite=false: ${resolvedPath}`,
      };
    }
  }
 
  // --- compute new content ---
  let newContent;
  if (mode === 'prepend') {
    // Ensure a newline separator between prepended content and existing content.
    const needsNewline = spec.content.length > 0 && !spec.content.endsWith('\n') && existingContent.length > 0;
    newContent = spec.content + (needsNewline ? '\n' : '') + existingContent;
  } else if (mode === 'create' || !fs.existsSync(resolvedPath)) {
    newContent = spec.content;
  } else {
    // append
    const needsNewline = existingContent.length > 0 && !existingContent.endsWith('\n');
    newContent = existingContent + (needsNewline ? '\n' : '') + spec.content;
  }
 
  const linesAfter = newContent.split('\n').length;
  const bytesWritten = Buffer.byteLength(newContent, 'utf8');
 
  if (!dryRun) {
    try {
      fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
      fs.writeFileSync(resolvedPath, newContent, 'utf8');
    } catch (err) {
      return {
        path: spec.path,
        resolvedPath,
        mode,
        ok: false,
        linesBefore,
        linesAfter: linesBefore,
        bytesWritten: 0,
        error: String(err),
      };
    }
  }
 
  return {
    path: spec.path,
    resolvedPath,
    mode,
    ok: true,
    linesBefore,
    linesAfter,
    bytesWritten,
  };
}
 
// ---------------------------------------------------------------------------
// Batch runner
// ---------------------------------------------------------------------------
 
/**
 * Apply a batch of spec entries and return a summary.
 *
 * @param {object[]} specs  - Array of spec entries
 * @param {string} [baseDir] - Optional base directory for relative paths
 * @param {boolean} [dryRun] - When true, validate but do not write files
 * @returns {{
 *   totalSpecs: number,
 *   succeeded: number,
 *   failed: number,
 *   results: object[],
 *   ok: boolean
 * }}
 */
export function extendArtifacts(specs, baseDir, dryRun = false) {
  if (!Array.isArray(specs)) {
    return {
      totalSpecs: 0,
      succeeded: 0,
      failed: 1,
      results: [{ ok: false, error: 'specs must be a JSON array' }],
      ok: false,
    };
  }
 
  const results = specs.map((spec) => extendArtifact(spec, baseDir, dryRun));
  const succeeded = results.filter((r) => r.ok).length;
  const failed = results.filter((r) => !r.ok).length;
 
  return {
    totalSpecs: specs.length,
    succeeded,
    failed,
    results,
    ok: failed === 0,
  };
}
 
// ---------------------------------------------------------------------------
// CLI entry point
// ---------------------------------------------------------------------------
 
/**
 * Parse minimalist `--key value` CLI args.
 *
 * @param {string[]} argv
 * @returns {Record<string, string|boolean>}
 */
/* c8 ignore start */
function parseArgs(argv) {
  const out = {};
  let i = 0;
  while (i < argv.length) {
    const arg = argv[i];
    if (arg.startsWith('--')) {
      const key = arg.slice(2);
      const next = argv[i + 1];
      if (next === undefined || next.startsWith('--')) {
        out[key] = true;
        i += 1;
      } else {
        out[key] = next;
        i += 2;
      }
    } else {
      i += 1;
    }
  }
  return out;
}
 
/**
 * CLI main entry point.
 *
 * @param {string[]} [argv]
 * @returns {Promise<void>}
 */
export async function main(argv = process.argv.slice(2)) {
  const args = parseArgs(argv);
 
  if (!args['spec-file'] && !args.stdin) {
    process.stderr.write(
      'Usage: node scripts/extend-artifacts.js --spec-file <path> [--base-dir <dir>] [--dry-run]\n' +
        '       cat spec.json | node scripts/extend-artifacts.js --stdin [--base-dir <dir>]\n',
    );
    process.exit(2);
  }
 
  const baseDir = args['base-dir'] ? String(args['base-dir']) : undefined;
  const dryRun = args['dry-run'] === true;
 
  let specs;
  try {
    let raw;
    if (args['spec-file']) {
      raw = fs.readFileSync(String(args['spec-file']), 'utf8');
    } else {
      // Read from stdin
      const chunks = [];
      for await (const chunk of process.stdin) {
        chunks.push(chunk);
      }
      raw = Buffer.concat(chunks).toString('utf8');
    }
    specs = JSON.parse(raw);
  } catch (err) {
    process.stderr.write(`Error reading/parsing spec: ${err}\n`);
    process.exit(1);
  }
 
  const summary = extendArtifacts(specs, baseDir, dryRun);
 
  process.stdout.write(JSON.stringify(summary, null, 2) + '\n');
 
  if (!summary.ok) {
    process.exit(1);
  }
}
 
// Standard ESM CLI guard
const isMain =
  typeof process !== 'undefined' &&
  process.argv[1] !== undefined &&
  (process.argv[1] === fileURLToPath(import.meta.url) ||
    process.argv[1].endsWith('/extend-artifacts.js'));
 
if (isMain) {
  main().catch((err) => {
    process.stderr.write(`Fatal: ${err}\n`);
    process.exit(1);
  });
}
/* c8 ignore stop */