@microsoft/agentrc 2.0.1-10 → 2.0.1-100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3052,7 +3052,7 @@ var require_main = __commonJS({
3052
3052
  exports.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0;
3053
3053
  var ril_1 = require_ril();
3054
3054
  ril_1.default.install();
3055
- var path23 = __require("path");
3055
+ var path26 = __require("path");
3056
3056
  var os2 = __require("os");
3057
3057
  var crypto_1 = __require("crypto");
3058
3058
  var net_1 = __require("net");
@@ -3188,9 +3188,9 @@ var require_main = __commonJS({
3188
3188
  }
3189
3189
  let result;
3190
3190
  if (XDG_RUNTIME_DIR) {
3191
- result = path23.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);
3191
+ result = path26.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);
3192
3192
  } else {
3193
- result = path23.join(os2.tmpdir(), `vscode-${randomSuffix}.sock`);
3193
+ result = path26.join(os2.tmpdir(), `vscode-${randomSuffix}.sock`);
3194
3194
  }
3195
3195
  const limit = safeIpcPathLengths.get(process.platform);
3196
3196
  if (limit !== void 0 && result.length > limit) {
@@ -5653,6 +5653,27 @@ function stripJsonComments(text) {
5653
5653
  if (i < text.length) i += 2;
5654
5654
  continue;
5655
5655
  }
5656
+ if (text[i] === ",") {
5657
+ let j = i + 1;
5658
+ while (j < text.length) {
5659
+ if (text[j] === " " || text[j] === " " || text[j] === "\n" || text[j] === "\r") {
5660
+ j++;
5661
+ } else if (text[j] === "/" && text[j + 1] === "/") {
5662
+ j += 2;
5663
+ while (j < text.length && text[j] !== "\n") j++;
5664
+ } else if (text[j] === "/" && text[j + 1] === "*") {
5665
+ j += 2;
5666
+ while (j < text.length && !(text[j] === "*" && text[j + 1] === "/")) j++;
5667
+ if (j < text.length) j += 2;
5668
+ } else {
5669
+ break;
5670
+ }
5671
+ }
5672
+ if (j < text.length && (text[j] === "}" || text[j] === "]")) {
5673
+ i++;
5674
+ continue;
5675
+ }
5676
+ }
5656
5677
  result += text[i];
5657
5678
  i++;
5658
5679
  }
@@ -6991,7 +7012,7 @@ async function checkReposForInstructions(token, repos, onProgress) {
6991
7012
  }
6992
7013
 
6993
7014
  // packages/core/src/services/batch.ts
6994
- import path10 from "path";
7015
+ import path13 from "path";
6995
7016
 
6996
7017
  // packages/core/src/utils/pr.ts
6997
7018
  function buildInstructionsPrBody() {
@@ -7303,10 +7324,8 @@ async function assertCopilotCliReady() {
7303
7324
  const desc = config.cliArgs ? `${config.cliPath} ${config.cliArgs.join(" ")}` : config.cliPath;
7304
7325
  logCopilotDebug(`validating CLI compatibility with ${desc}`);
7305
7326
  try {
7306
- const isNpx = config.cliArgs?.includes("@github/copilot") ?? false;
7307
- const timeout = isNpx ? 3e4 : 5e3;
7308
7327
  const [cmd, args2] = buildExecArgs(config, ["--headless", "--version"]);
7309
- await execFileAsync2(cmd, args2, { timeout });
7328
+ await execFileAsync2(cmd, args2, { timeout: 5e3 });
7310
7329
  } catch {
7311
7330
  cachedCliConfig = null;
7312
7331
  throw new Error(
@@ -7406,18 +7425,6 @@ async function findCopilotCliConfig() {
7406
7425
  }
7407
7426
  } catch {
7408
7427
  }
7409
- try {
7410
- const { stdout } = await execFileAsync2(whichCmd, ["npx"], { timeout: 5e3 });
7411
- const npxPath = stdout.trim().split(/\r?\n/)[0];
7412
- if (npxPath) {
7413
- candidates.push({
7414
- config: { cliPath: npxPath, cliArgs: ["--yes", "@github/copilot"] },
7415
- source: "npx @github/copilot"
7416
- });
7417
- logCopilotDebug(`discovered candidate from npx: ${npxPath} --yes @github/copilot`);
7418
- }
7419
- } catch {
7420
- }
7421
7428
  const staticLocations = [];
7422
7429
  if (process.platform === "darwin") {
7423
7430
  staticLocations.push(
@@ -7499,11 +7506,9 @@ async function findFirstCompatibleCandidate(candidates) {
7499
7506
  return null;
7500
7507
  }
7501
7508
  async function isHeadlessCompatible(config) {
7502
- const isNpx = config.cliArgs?.includes("@github/copilot") ?? false;
7503
- const timeout = isNpx ? 3e4 : 5e3;
7504
7509
  try {
7505
7510
  const [cmd, args2] = buildExecArgs(config, ["--headless", "--version"]);
7506
- await execFileAsync2(cmd, args2, { timeout });
7511
+ await execFileAsync2(cmd, args2, { timeout: 5e3 });
7507
7512
  return true;
7508
7513
  } catch {
7509
7514
  return false;
@@ -7585,6 +7590,8 @@ async function startExternalServer(cliConfig) {
7585
7590
  clearTimeout(timer);
7586
7591
  cliProcess.stdout?.removeAllListeners("data");
7587
7592
  cliProcess.stderr?.removeAllListeners("data");
7593
+ cliProcess.stdout?.resume();
7594
+ cliProcess.stderr?.resume();
7588
7595
  resolve({
7589
7596
  cliProcess,
7590
7597
  cliUrl: `localhost:${port}`
@@ -7604,8 +7611,7 @@ async function startExternalServer(cliConfig) {
7604
7611
  const lines = chunk.split("\n");
7605
7612
  for (const line of lines) {
7606
7613
  if (line.trim()) {
7607
- process.stderr.write(`[CLI subprocess] ${line}
7608
- `);
7614
+ logCopilotDebug(`CLI subprocess: ${line}`);
7609
7615
  }
7610
7616
  }
7611
7617
  });
@@ -7628,11 +7634,11 @@ ${details}` : `External CLI server exited with code ${code}`
7628
7634
  });
7629
7635
  }
7630
7636
  function attachDefaultPermissionHandler(client) {
7631
- const approveAll2 = () => ({ kind: "approved" });
7637
+ const readOnly = (request) => request.kind === "read" ? { kind: "approved" } : { kind: "denied-no-approval-rule-and-could-not-request-from-user" };
7632
7638
  const originalCreateSession = client.createSession.bind(client);
7633
7639
  client.createSession = (config) => originalCreateSession({
7634
7640
  ...config,
7635
- onPermissionRequest: config.onPermissionRequest ?? approveAll2
7641
+ onPermissionRequest: config.onPermissionRequest ?? readOnly
7636
7642
  });
7637
7643
  }
7638
7644
  function killProcessTree(cliProcess) {
@@ -7653,9 +7659,11 @@ function killProcessTree(cliProcess) {
7653
7659
  function attachExternalServerCleanup(client, cliProcess) {
7654
7660
  const originalStop = client.stop.bind(client);
7655
7661
  client.stop = (async () => {
7656
- const errors = await originalStop();
7657
- killProcessTree(cliProcess);
7658
- return errors;
7662
+ try {
7663
+ return await originalStop();
7664
+ } finally {
7665
+ killProcessTree(cliProcess);
7666
+ }
7659
7667
  });
7660
7668
  }
7661
7669
  async function loadCopilotSdk() {
@@ -7708,9 +7716,7 @@ async function createCopilotClient(cliConfig) {
7708
7716
  try {
7709
7717
  await fallbackClient.start();
7710
7718
  } catch (fallbackError) {
7711
- if (!external.cliProcess.killed) {
7712
- external.cliProcess.kill();
7713
- }
7719
+ killProcessTree(external.cliProcess);
7714
7720
  throw normalizeError(fallbackError);
7715
7721
  }
7716
7722
  attachExternalServerCleanup(fallbackClient, external.cliProcess);
@@ -7822,6 +7828,31 @@ function buildExistingInstructionsSection(ctx) {
7822
7828
  ];
7823
7829
  return lines.join("\n");
7824
7830
  }
7831
+ function buildRootContextSection(rootContent) {
7832
+ const trimmed = rootContent?.trim();
7833
+ if (!trimmed) return "";
7834
+ return [
7835
+ "",
7836
+ "## Root instructions already cover",
7837
+ "The root instruction file already covers the following workspace-wide content. Do NOT repeat or restate it in this file; cover only this area/crate's unique details:",
7838
+ "",
7839
+ trimmed,
7840
+ ""
7841
+ ].join("\n");
7842
+ }
7843
+ function normalizeAgentsHeading(content, componentName) {
7844
+ const headingRe = /^(?:\uFEFF)?#\s+Copilot Instructions(?:\s*:\s*(.*))?\s*$/iu;
7845
+ const firstLineEnd = content.indexOf("\n");
7846
+ const firstLine = (firstLineEnd === -1 ? content : content.slice(0, firstLineEnd)).trimEnd();
7847
+ const match = headingRe.exec(firstLine);
7848
+ if (!match) return content;
7849
+ const fallback = match[1]?.trim();
7850
+ const heading = componentName?.trim() || fallback;
7851
+ if (!heading) return content;
7852
+ const replacedFirstLine = firstLine.replace(headingRe, `# ${heading}`);
7853
+ return firstLineEnd === -1 ? replacedFirstLine : `${replacedFirstLine}
7854
+ ${content.slice(firstLineEnd + 1)}`;
7855
+ }
7825
7856
  function stripMarkdownFences(content) {
7826
7857
  const trimmed = content.trim();
7827
7858
  const fenceRe = /^```(?:markdown|md)?[ \t]*\n([\s\S]*?)\n```[ \t]*$/;
@@ -8213,12 +8244,13 @@ ${options.childAreas.map((c) => `- ${c.name} (${c.path ?? "unknown path"})`).joi
8213
8244
  Include a "## Sub-Projects" section with links to each child's AGENTS.md.` : "";
8214
8245
  const parentContext = options.area?.parentArea ? `
8215
8246
  This is a sub-project of "${options.area.parentArea}". Include a note linking back to the parent area.` : "";
8247
+ const rootContextSection = buildRootContextSection(options.rootContent);
8216
8248
  const prompt = `/nested-hub Generate a lean AGENTS.md hub file (~90-120 lines).${areaContext}${parentContext}
8217
8249
 
8218
8250
  Detail files go in \`${options.detailDir}/\`.${childContext}
8219
8251
 
8220
8252
  Recommend 3-5 topics for deep-dive detail files. Each slug becomes: \`${options.detailDir}/{slug}.md\`.
8221
- ${existingSection ? `
8253
+ ${rootContextSection}${existingSection ? `
8222
8254
  Do NOT duplicate content from existing instruction files
8223
8255
  ${existingSection}` : ""}`;
8224
8256
  let sendError;
@@ -8278,8 +8310,9 @@ async function generateNestedDetail(client, options) {
8278
8310
  }
8279
8311
  });
8280
8312
  const areaContext = options.area ? `Focus on the "${options.area.name}" area (files matching: ${Array.isArray(options.area.applyTo) ? options.area.applyTo.join(", ") : options.area.applyTo}).` : "Focus on the entire repository.";
8313
+ const rootContextSection = buildRootContextSection(options.rootContent);
8281
8314
  const prompt = `/nested-detail Generate a deep-dive instruction file about "${options.topic.title}" for this codebase.
8282
- ${areaContext}
8315
+ ${areaContext}${rootContextSection}
8283
8316
 
8284
8317
  Topic: ${options.topic.title}
8285
8318
  Description: ${options.topic.description}`;
@@ -8314,15 +8347,18 @@ async function generateNestedInstructions(options) {
8314
8347
  area: options.area,
8315
8348
  childAreas: options.childAreas,
8316
8349
  model: options.model,
8317
- onProgress: options.onProgress
8350
+ onProgress: options.onProgress,
8351
+ rootContent: options.rootContent
8318
8352
  });
8319
8353
  const basePath = options.area?.path ?? ".";
8320
8354
  const hubRelativePath = path7.join(basePath, "AGENTS.md");
8321
- let finalHubContent = hubContent;
8355
+ const componentName = options.area?.name ?? path7.basename(options.repoPath);
8356
+ const normalizedHubContent = normalizeAgentsHeading(hubContent, componentName);
8357
+ let finalHubContent = normalizedHubContent;
8322
8358
  if (options.area) {
8323
8359
  finalHubContent = `${buildAreaFrontmatter(options.area)}
8324
8360
 
8325
- ${hubContent}`;
8361
+ ${normalizedHubContent}`;
8326
8362
  }
8327
8363
  const result = {
8328
8364
  hub: { relativePath: hubRelativePath, content: finalHubContent },
@@ -8337,7 +8373,8 @@ ${hubContent}`;
8337
8373
  topic,
8338
8374
  area: options.area,
8339
8375
  model: options.model,
8340
- onProgress: options.onProgress
8376
+ onProgress: options.onProgress,
8377
+ rootContent: options.rootContent
8341
8378
  });
8342
8379
  if (detailContent) {
8343
8380
  result.details.push({
@@ -8373,17 +8410,223 @@ async function generateNestedAreaInstructions(options) {
8373
8410
  model: options.model,
8374
8411
  onProgress: options.onProgress,
8375
8412
  detailDir: options.detailDir,
8376
- claudeMd: options.claudeMd
8413
+ claudeMd: options.claudeMd,
8414
+ rootContent: options.rootContent
8377
8415
  });
8378
8416
  }
8379
8417
 
8380
- // packages/core/src/services/readiness.ts
8381
- import fs7 from "fs/promises";
8382
- import path9 from "path";
8418
+ // packages/core/src/services/readiness/index.ts
8419
+ import path12 from "path";
8383
8420
 
8384
8421
  // packages/core/src/services/policy.ts
8385
8422
  import fs6 from "fs/promises";
8386
8423
  import path8 from "path";
8424
+ import { pathToFileURL } from "url";
8425
+
8426
+ // packages/core/src/services/policy/types.ts
8427
+ function isNativePlugin(obj) {
8428
+ if (typeof obj !== "object" || obj === null) return false;
8429
+ const record = obj;
8430
+ if (typeof record.meta !== "object" || record.meta === null) return false;
8431
+ if (typeof record.name === "string") return false;
8432
+ const meta = record.meta;
8433
+ if (typeof meta.name !== "string" || meta.name.trim().length === 0) return false;
8434
+ if (meta.sourceType !== void 0 && !["module", "json", "builtin"].includes(meta.sourceType))
8435
+ return false;
8436
+ if (meta.trust !== void 0 && !["trusted-code", "safe-declarative"].includes(meta.trust))
8437
+ return false;
8438
+ return true;
8439
+ }
8440
+ function validateNativePlugin(obj, source) {
8441
+ const { meta } = obj;
8442
+ if (!meta.name?.trim()) {
8443
+ throw new Error(`Native plugin "${source}" is invalid: meta.name is required`);
8444
+ }
8445
+ if (obj.afterDetect !== void 0 && typeof obj.afterDetect !== "function") {
8446
+ throw new Error(`Native plugin "${source}" is invalid: afterDetect must be a function`);
8447
+ }
8448
+ if (obj.beforeRecommend !== void 0 && typeof obj.beforeRecommend !== "function") {
8449
+ throw new Error(`Native plugin "${source}" is invalid: beforeRecommend must be a function`);
8450
+ }
8451
+ if (obj.afterRecommend !== void 0 && typeof obj.afterRecommend !== "function") {
8452
+ throw new Error(`Native plugin "${source}" is invalid: afterRecommend must be a function`);
8453
+ }
8454
+ if (obj.onError !== void 0 && typeof obj.onError !== "function") {
8455
+ throw new Error(`Native plugin "${source}" is invalid: onError must be a function`);
8456
+ }
8457
+ if (obj.detectors !== void 0) {
8458
+ if (!Array.isArray(obj.detectors)) {
8459
+ throw new Error(`Native plugin "${source}" is invalid: detectors must be an array`);
8460
+ }
8461
+ for (const [i, d] of obj.detectors.entries()) {
8462
+ if (typeof d !== "object" || d === null) {
8463
+ throw new Error(`Native plugin "${source}" is invalid: detectors[${i}] must be an object`);
8464
+ }
8465
+ if (typeof d.id !== "string" || !d.id.trim()) {
8466
+ throw new Error(
8467
+ `Native plugin "${source}" is invalid: detectors[${i}].id must be a non-empty string`
8468
+ );
8469
+ }
8470
+ if (typeof d.detect !== "function") {
8471
+ throw new Error(
8472
+ `Native plugin "${source}" is invalid: detectors[${i}].detect must be a function`
8473
+ );
8474
+ }
8475
+ }
8476
+ }
8477
+ if (obj.recommenders !== void 0) {
8478
+ if (!Array.isArray(obj.recommenders)) {
8479
+ throw new Error(`Native plugin "${source}" is invalid: recommenders must be an array`);
8480
+ }
8481
+ for (const [i, r] of obj.recommenders.entries()) {
8482
+ if (typeof r !== "object" || r === null) {
8483
+ throw new Error(
8484
+ `Native plugin "${source}" is invalid: recommenders[${i}] must be an object`
8485
+ );
8486
+ }
8487
+ if (typeof r.id !== "string" || !r.id.trim()) {
8488
+ throw new Error(
8489
+ `Native plugin "${source}" is invalid: recommenders[${i}].id must be a non-empty string`
8490
+ );
8491
+ }
8492
+ if (typeof r.recommend !== "function") {
8493
+ throw new Error(
8494
+ `Native plugin "${source}" is invalid: recommenders[${i}].recommend must be a function`
8495
+ );
8496
+ }
8497
+ }
8498
+ }
8499
+ const hasHooks = obj.detectors?.length || obj.afterDetect || obj.beforeRecommend || obj.recommenders?.length || obj.afterRecommend;
8500
+ if (!hasHooks) {
8501
+ throw new Error(
8502
+ `Native plugin "${source}" is invalid: must implement at least one hook (detectors, afterDetect, beforeRecommend, recommenders, or afterRecommend)`
8503
+ );
8504
+ }
8505
+ }
8506
+ var IMPACT_WEIGHTS = {
8507
+ critical: 5,
8508
+ high: 4,
8509
+ medium: 3,
8510
+ low: 2,
8511
+ info: 0
8512
+ };
8513
+ function calculateScore(signals, recommendations) {
8514
+ const activeSignals = signals.filter((s) => s.status !== "not-detected");
8515
+ if (activeSignals.length === 0) {
8516
+ return { score: 1, grade: "A" };
8517
+ }
8518
+ const maxWeight = activeSignals.length * IMPACT_WEIGHTS.critical;
8519
+ const deductions = recommendations.reduce((sum, rec) => sum + IMPACT_WEIGHTS[rec.impact], 0);
8520
+ const score = Math.max(0, Math.min(1, 1 - deductions / maxWeight));
8521
+ return { score, grade: scoreToGrade(score) };
8522
+ }
8523
+ function scoreToGrade(score) {
8524
+ if (score >= 0.9) return "A";
8525
+ if (score >= 0.8) return "B";
8526
+ if (score >= 0.7) return "C";
8527
+ if (score >= 0.6) return "D";
8528
+ return "F";
8529
+ }
8530
+ function applySignalPatch(signals, patch, pluginName) {
8531
+ let result = [...signals];
8532
+ if (patch.remove?.length) {
8533
+ const removeSet = new Set(patch.remove);
8534
+ result = result.filter((s) => !removeSet.has(s.id));
8535
+ }
8536
+ if (patch.modify?.length) {
8537
+ for (const mod of patch.modify) {
8538
+ const idx = result.findIndex((s) => s.id === mod.id);
8539
+ if (idx >= 0) {
8540
+ const existing = result[idx];
8541
+ const changes = { ...mod.changes };
8542
+ if (changes.metadata && existing.metadata) {
8543
+ changes.metadata = { ...existing.metadata, ...changes.metadata };
8544
+ }
8545
+ result[idx] = {
8546
+ ...existing,
8547
+ ...changes,
8548
+ origin: {
8549
+ ...existing.origin,
8550
+ modifiedBy: [...existing.origin.modifiedBy ?? [], pluginName]
8551
+ }
8552
+ };
8553
+ }
8554
+ }
8555
+ }
8556
+ if (patch.add?.length) {
8557
+ result.push(
8558
+ ...patch.add.map((s) => ({
8559
+ ...s,
8560
+ evidence: s.evidence ? [...s.evidence] : void 0,
8561
+ metadata: s.metadata ? { ...s.metadata } : void 0
8562
+ }))
8563
+ );
8564
+ }
8565
+ return result;
8566
+ }
8567
+ function applyRecommendationPatch(recommendations, patch, pluginName) {
8568
+ let result = [...recommendations];
8569
+ if (patch.remove?.length) {
8570
+ const removeSet = new Set(patch.remove);
8571
+ result = result.filter((r) => !removeSet.has(r.id));
8572
+ }
8573
+ if (patch.modify?.length) {
8574
+ for (const mod of patch.modify) {
8575
+ const idx = result.findIndex((r) => r.id === mod.id);
8576
+ if (idx >= 0) {
8577
+ const existing = result[idx];
8578
+ result[idx] = {
8579
+ ...existing,
8580
+ ...mod.changes,
8581
+ origin: {
8582
+ ...existing.origin,
8583
+ modifiedBy: [...existing.origin.modifiedBy ?? [], pluginName]
8584
+ }
8585
+ };
8586
+ }
8587
+ }
8588
+ }
8589
+ if (patch.add?.length) {
8590
+ result.push(
8591
+ ...patch.add.map((r) => ({
8592
+ ...r,
8593
+ supersedes: r.supersedes ? [...r.supersedes] : void 0,
8594
+ metadata: r.metadata ? { ...r.metadata } : void 0
8595
+ }))
8596
+ );
8597
+ }
8598
+ return result;
8599
+ }
8600
+ function resolveSupersedes(recommendations) {
8601
+ const supersededIds = /* @__PURE__ */ new Set();
8602
+ const recIds = new Set(recommendations.map((r) => r.id));
8603
+ for (const rec of recommendations) {
8604
+ if (rec.supersedes?.length) {
8605
+ for (const id of rec.supersedes) {
8606
+ if (recIds.has(id)) {
8607
+ supersededIds.add(id);
8608
+ }
8609
+ }
8610
+ }
8611
+ }
8612
+ return recommendations.filter((r) => !supersededIds.has(r.id)).map((r) => {
8613
+ if (!r.supersedes?.length) return r;
8614
+ const actuallySuperseded = r.supersedes.filter((id) => supersededIds.has(id));
8615
+ if (actuallySuperseded.length === 0) return r;
8616
+ return {
8617
+ ...r,
8618
+ origin: {
8619
+ ...r.origin,
8620
+ modifiedBy: [
8621
+ ...r.origin.modifiedBy ?? [],
8622
+ ...actuallySuperseded.map((id) => `superseded:${id}`)
8623
+ ]
8624
+ }
8625
+ };
8626
+ });
8627
+ }
8628
+
8629
+ // packages/core/src/services/policy.ts
8387
8630
  var DEFAULT_PASS_RATE = 0.8;
8388
8631
  function validatePolicyConfig(obj, source, format = "module") {
8389
8632
  if (typeof obj !== "object" || obj === null) {
@@ -8474,6 +8717,16 @@ function parsePolicySources(raw) {
8474
8717
  const sources = raw.split(",").map((s) => s.trim()).filter(Boolean);
8475
8718
  return sources.length ? sources : void 0;
8476
8719
  }
8720
+ function normalizeNativePlugin(plugin) {
8721
+ return {
8722
+ ...plugin,
8723
+ meta: {
8724
+ ...plugin.meta,
8725
+ sourceType: "module",
8726
+ trust: "trusted-code"
8727
+ }
8728
+ };
8729
+ }
8477
8730
  async function loadPolicy(source, options) {
8478
8731
  const jsonOnly = options?.jsonOnly ?? false;
8479
8732
  if (source.startsWith(".") || path8.isAbsolute(source)) {
@@ -8492,8 +8745,12 @@ async function loadPolicy(source, options) {
8492
8745
  );
8493
8746
  }
8494
8747
  try {
8495
- const mod = await import(resolved);
8748
+ const mod = await import(pathToFileURL(resolved).href);
8496
8749
  const config = mod.default ?? mod;
8750
+ if (isNativePlugin(config)) {
8751
+ validateNativePlugin(config, source);
8752
+ return normalizeNativePlugin(config);
8753
+ }
8497
8754
  return validatePolicyConfig(config, source);
8498
8755
  } catch (err) {
8499
8756
  if (err instanceof Error && (err.message.includes("Cannot find module") || err.message.includes("MODULE_NOT_FOUND"))) {
@@ -8520,6 +8777,10 @@ async function loadPolicy(source, options) {
8520
8777
  try {
8521
8778
  const mod = await import(source);
8522
8779
  const config = mod.default ?? mod;
8780
+ if (isNativePlugin(config)) {
8781
+ validateNativePlugin(config, source);
8782
+ return normalizeNativePlugin(config);
8783
+ }
8523
8784
  return validatePolicyConfig(config, source);
8524
8785
  } catch (err) {
8525
8786
  const message = err instanceof Error ? err.message : typeof err === "object" && err !== null && "message" in err ? String(err.message) : String(err);
@@ -8583,148 +8844,24 @@ function resolveChain(baseCriteria, baseExtras, policies) {
8583
8844
  return { chain, criteria, extras, thresholds: { passRate } };
8584
8845
  }
8585
8846
 
8586
- // packages/core/src/services/policy/types.ts
8587
- var IMPACT_WEIGHTS = {
8588
- critical: 5,
8589
- high: 4,
8590
- medium: 3,
8591
- low: 2,
8592
- info: 0
8593
- };
8594
- function calculateScore(signals, recommendations) {
8595
- const activeSignals = signals.filter((s) => s.status !== "not-detected");
8596
- if (activeSignals.length === 0) {
8597
- return { score: 1, grade: "A" };
8598
- }
8599
- const maxWeight = activeSignals.length * IMPACT_WEIGHTS.critical;
8600
- const deductions = recommendations.reduce((sum, rec) => sum + IMPACT_WEIGHTS[rec.impact], 0);
8601
- const score = Math.max(0, Math.min(1, 1 - deductions / maxWeight));
8602
- return { score, grade: scoreToGrade(score) };
8603
- }
8604
- function scoreToGrade(score) {
8605
- if (score >= 0.9) return "A";
8606
- if (score >= 0.8) return "B";
8607
- if (score >= 0.7) return "C";
8608
- if (score >= 0.6) return "D";
8609
- return "F";
8610
- }
8611
- function applySignalPatch(signals, patch, pluginName) {
8612
- let result = [...signals];
8613
- if (patch.remove?.length) {
8614
- const removeSet = new Set(patch.remove);
8615
- result = result.filter((s) => !removeSet.has(s.id));
8616
- }
8617
- if (patch.modify?.length) {
8618
- for (const mod of patch.modify) {
8619
- const idx = result.findIndex((s) => s.id === mod.id);
8620
- if (idx >= 0) {
8621
- const existing = result[idx];
8622
- const changes = { ...mod.changes };
8623
- if (changes.metadata && existing.metadata) {
8624
- changes.metadata = { ...existing.metadata, ...changes.metadata };
8625
- }
8626
- result[idx] = {
8627
- ...existing,
8628
- ...changes,
8629
- origin: {
8630
- ...existing.origin,
8631
- modifiedBy: [...existing.origin.modifiedBy ?? [], pluginName]
8632
- }
8633
- };
8634
- }
8635
- }
8636
- }
8637
- if (patch.add?.length) {
8638
- result.push(
8639
- ...patch.add.map((s) => ({
8640
- ...s,
8641
- evidence: s.evidence ? [...s.evidence] : void 0,
8642
- metadata: s.metadata ? { ...s.metadata } : void 0
8643
- }))
8644
- );
8645
- }
8646
- return result;
8647
- }
8648
- function applyRecommendationPatch(recommendations, patch, pluginName) {
8649
- let result = [...recommendations];
8650
- if (patch.remove?.length) {
8651
- const removeSet = new Set(patch.remove);
8652
- result = result.filter((r) => !removeSet.has(r.id));
8653
- }
8654
- if (patch.modify?.length) {
8655
- for (const mod of patch.modify) {
8656
- const idx = result.findIndex((r) => r.id === mod.id);
8657
- if (idx >= 0) {
8658
- const existing = result[idx];
8659
- result[idx] = {
8660
- ...existing,
8661
- ...mod.changes,
8662
- origin: {
8663
- ...existing.origin,
8664
- modifiedBy: [...existing.origin.modifiedBy ?? [], pluginName]
8665
- }
8666
- };
8667
- }
8668
- }
8669
- }
8670
- if (patch.add?.length) {
8671
- result.push(
8672
- ...patch.add.map((r) => ({
8673
- ...r,
8674
- supersedes: r.supersedes ? [...r.supersedes] : void 0,
8675
- metadata: r.metadata ? { ...r.metadata } : void 0
8676
- }))
8677
- );
8678
- }
8679
- return result;
8680
- }
8681
- function resolveSupersedes(recommendations) {
8682
- const supersededIds = /* @__PURE__ */ new Set();
8683
- const recIds = new Set(recommendations.map((r) => r.id));
8684
- for (const rec of recommendations) {
8685
- if (rec.supersedes?.length) {
8686
- for (const id of rec.supersedes) {
8687
- if (recIds.has(id)) {
8688
- supersededIds.add(id);
8689
- }
8690
- }
8691
- }
8692
- }
8693
- return recommendations.filter((r) => !supersededIds.has(r.id)).map((r) => {
8694
- if (!r.supersedes?.length) return r;
8695
- const actuallySuperseded = r.supersedes.filter((id) => supersededIds.has(id));
8696
- if (actuallySuperseded.length === 0) return r;
8697
- return {
8698
- ...r,
8699
- origin: {
8700
- ...r.origin,
8701
- modifiedBy: [
8702
- ...r.origin.modifiedBy ?? [],
8703
- ...actuallySuperseded.map((id) => `superseded:${id}`)
8704
- ]
8705
- }
8706
- };
8707
- });
8708
- }
8709
-
8710
- // packages/core/src/services/policy/engine.ts
8711
- async function executePlugins(plugins, ctx, options) {
8712
- const warnings = [];
8713
- const disabledIds = options?.disabledRuleIds ?? /* @__PURE__ */ new Set();
8714
- let signals = [];
8715
- for (const plugin of plugins) {
8716
- if (!plugin.detectors?.length) continue;
8717
- for (const detector of plugin.detectors) {
8718
- if (disabledIds.has(detector.id)) continue;
8719
- try {
8720
- const result = await detector.detect(ctx);
8721
- const emitted = Array.isArray(result) ? result : [result];
8722
- signals.push(...emitted);
8723
- } catch (err) {
8724
- const cont = handleError(plugin, err, "detect", ctx, warnings);
8725
- if (!cont) break;
8726
- }
8727
- }
8847
+ // packages/core/src/services/policy/engine.ts
8848
+ async function executePlugins(plugins, ctx, options) {
8849
+ const warnings = [];
8850
+ const disabledIds = options?.disabledRuleIds ?? /* @__PURE__ */ new Set();
8851
+ let signals = [];
8852
+ for (const plugin of plugins) {
8853
+ if (!plugin.detectors?.length) continue;
8854
+ for (const detector of plugin.detectors) {
8855
+ if (disabledIds.has(detector.id)) continue;
8856
+ try {
8857
+ const result = await detector.detect(ctx);
8858
+ const emitted = Array.isArray(result) ? result : [result];
8859
+ signals.push(...emitted);
8860
+ } catch (err) {
8861
+ const cont = handleError(plugin, err, "detect", ctx, warnings);
8862
+ if (!cont) break;
8863
+ }
8864
+ }
8728
8865
  }
8729
8866
  for (const plugin of plugins) {
8730
8867
  if (!plugin.afterDetect) continue;
@@ -9012,9 +9149,21 @@ async function loadPluginChain(policySources, options) {
9012
9149
  const allDisabledIds = [];
9013
9150
  let passRateThreshold = 0.8;
9014
9151
  for (const source of policySources) {
9015
- const policyConfig = await loadPolicy(source, {
9152
+ const loaded = await loadPolicy(source, {
9016
9153
  jsonOnly: options?.jsonOnly
9017
9154
  });
9155
+ if (isNativePlugin(loaded)) {
9156
+ plugins.push({
9157
+ ...loaded,
9158
+ meta: {
9159
+ ...loaded.meta,
9160
+ sourceType: "module",
9161
+ trust: "trusted-code"
9162
+ }
9163
+ });
9164
+ continue;
9165
+ }
9166
+ const policyConfig = loaded;
9018
9167
  if (isImperativePlugin(policyConfig)) {
9019
9168
  const { plugin: imperativePlugin, compiled } = wrapImperativePolicy(
9020
9169
  policyConfig,
@@ -9060,252 +9209,581 @@ function wrapImperativePolicy(config, baseCriteria) {
9060
9209
  return { plugin, compiled };
9061
9210
  }
9062
9211
 
9063
- // packages/core/src/services/readiness.ts
9064
- var PILLAR_GROUPS = {
9065
- "style-validation": "repo-health",
9066
- "build-system": "repo-health",
9067
- testing: "repo-health",
9068
- documentation: "repo-health",
9069
- "dev-environment": "repo-health",
9070
- "code-quality": "repo-health",
9071
- observability: "repo-health",
9072
- "security-governance": "repo-health",
9073
- "ai-tooling": "ai-setup"
9074
- };
9075
- var PILLAR_GROUP_NAMES = {
9076
- "repo-health": "Repo Health",
9077
- "ai-setup": "AI Setup"
9078
- };
9079
- function groupPillars(pillars) {
9080
- const groups = ["repo-health", "ai-setup"];
9081
- return groups.map((group) => ({
9082
- group,
9083
- label: PILLAR_GROUP_NAMES[group],
9084
- pillars: pillars.filter((p) => PILLAR_GROUPS[p.id] === group)
9085
- }));
9212
+ // packages/core/src/services/readiness/checkers.ts
9213
+ import fs7 from "fs/promises";
9214
+ import path9 from "path";
9215
+ import fg3 from "fast-glob";
9216
+ var AGENT_PLUGINS_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json";
9217
+ var AGENT_PLUGIN_NAME_PATTERN = /^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u;
9218
+ var AGENT_PLUGIN_SCAN_IGNORES = [
9219
+ "**/.git/**",
9220
+ "**/.agentrc-cache/**",
9221
+ "**/.primer-cache/**",
9222
+ "**/coverage/**",
9223
+ "**/dist/**",
9224
+ "**/node_modules/**",
9225
+ "**/out/**"
9226
+ ];
9227
+ var COPILOT_REPO_SETTINGS_FILES = [
9228
+ ".claude/settings.json",
9229
+ ".claude/settings.local.json",
9230
+ ".github/copilot/settings.json",
9231
+ ".github/copilot/settings.local.json"
9232
+ ];
9233
+ function hasAnyFile(files, candidates) {
9234
+ return candidates.some((candidate) => files.includes(candidate));
9086
9235
  }
9087
- function getLevelName(level) {
9088
- const names = {
9089
- 1: "Functional",
9090
- 2: "Documented",
9091
- 3: "Standardized",
9092
- 4: "Optimized",
9093
- 5: "Autonomous"
9236
+ async function hasReadme(repoPath) {
9237
+ const files = await safeReadDir(repoPath);
9238
+ return files.some(
9239
+ (file) => file.toLowerCase() === "readme.md" || file.toLowerCase() === "readme"
9240
+ );
9241
+ }
9242
+ async function hasLintConfig(repoPath) {
9243
+ return hasAnyFile(await safeReadDir(repoPath), [
9244
+ "eslint.config.js",
9245
+ "eslint.config.mjs",
9246
+ ".eslintrc",
9247
+ ".eslintrc.js",
9248
+ ".eslintrc.cjs",
9249
+ ".eslintrc.json",
9250
+ ".eslintrc.yml",
9251
+ ".eslintrc.yaml",
9252
+ "biome.json",
9253
+ "biome.jsonc",
9254
+ ".prettierrc",
9255
+ ".prettierrc.json",
9256
+ ".prettierrc.js",
9257
+ ".prettierrc.cjs",
9258
+ "prettier.config.js",
9259
+ "prettier.config.cjs"
9260
+ ]);
9261
+ }
9262
+ async function hasFormatterConfig(repoPath) {
9263
+ return hasAnyFile(await safeReadDir(repoPath), [
9264
+ "biome.json",
9265
+ "biome.jsonc",
9266
+ ".prettierrc",
9267
+ ".prettierrc.json",
9268
+ ".prettierrc.js",
9269
+ ".prettierrc.cjs",
9270
+ "prettier.config.js",
9271
+ "prettier.config.cjs"
9272
+ ]);
9273
+ }
9274
+ async function hasTypecheckConfig(repoPath) {
9275
+ return hasAnyFile(await safeReadDir(repoPath), [
9276
+ "tsconfig.json",
9277
+ "tsconfig.base.json",
9278
+ "pyproject.toml",
9279
+ "mypy.ini"
9280
+ ]);
9281
+ }
9282
+ async function hasGithubWorkflows(repoPath) {
9283
+ return fileExists(path9.join(repoPath, ".github", "workflows"));
9284
+ }
9285
+ async function hasCodeowners(repoPath) {
9286
+ const root = await fileExists(path9.join(repoPath, "CODEOWNERS"));
9287
+ const github = await fileExists(path9.join(repoPath, ".github", "CODEOWNERS"));
9288
+ return root || github;
9289
+ }
9290
+ async function hasLicense(repoPath) {
9291
+ const files = await safeReadDir(repoPath);
9292
+ return files.some((file) => file.toLowerCase().startsWith("license"));
9293
+ }
9294
+ async function hasPullRequestTemplate(repoPath) {
9295
+ const direct = await fileExists(path9.join(repoPath, ".github", "PULL_REQUEST_TEMPLATE.md"));
9296
+ if (direct) return true;
9297
+ const dir = path9.join(repoPath, ".github", "PULL_REQUEST_TEMPLATE");
9298
+ try {
9299
+ const entries = await fs7.readdir(dir);
9300
+ return entries.some((entry) => entry.toLowerCase().endsWith(".md"));
9301
+ } catch {
9302
+ return false;
9303
+ }
9304
+ }
9305
+ async function hasPrecommitConfig(repoPath) {
9306
+ const precommit = await fileExists(path9.join(repoPath, ".pre-commit-config.yaml"));
9307
+ if (precommit) return true;
9308
+ return fileExists(path9.join(repoPath, ".husky"));
9309
+ }
9310
+ async function hasArchitectureDoc(repoPath) {
9311
+ const files = await safeReadDir(repoPath);
9312
+ if (files.some((file) => file.toLowerCase() === "architecture.md")) return true;
9313
+ return fileExists(path9.join(repoPath, "docs", "architecture.md"));
9314
+ }
9315
+ function validateAndNormalize(raw) {
9316
+ const trimmed = raw.trim();
9317
+ if (!trimmed || path9.isAbsolute(trimmed)) return void 0;
9318
+ const segments = trimmed.split(/[/\\]+/u);
9319
+ if (segments.some((s) => s === "..")) return void 0;
9320
+ let normalized = path9.normalize(trimmed).replace(/\\/gu, "/");
9321
+ normalized = normalized.replace(/\/+$/u, "");
9322
+ if (!normalized || normalized === ".") return void 0;
9323
+ return normalized;
9324
+ }
9325
+ function extractLocationPaths(entries) {
9326
+ if (!entries || typeof entries !== "object") return [];
9327
+ const paths = [];
9328
+ if (Array.isArray(entries)) {
9329
+ for (const entry of entries) {
9330
+ let raw;
9331
+ if (typeof entry === "string") {
9332
+ raw = entry;
9333
+ } else if (entry && typeof entry === "object" && !Array.isArray(entry)) {
9334
+ const obj = entry;
9335
+ if (typeof obj.path === "string") {
9336
+ raw = obj.path;
9337
+ }
9338
+ }
9339
+ if (raw) {
9340
+ const normalized = validateAndNormalize(raw);
9341
+ if (normalized) paths.push(normalized);
9342
+ }
9343
+ }
9344
+ return paths;
9345
+ }
9346
+ for (const [key, value] of Object.entries(entries)) {
9347
+ if (value !== true) continue;
9348
+ const normalized = validateAndNormalize(key);
9349
+ if (normalized) paths.push(normalized);
9350
+ }
9351
+ return paths;
9352
+ }
9353
+ function extractLocationsFromSettings(settings) {
9354
+ return {
9355
+ instructionsLocations: extractLocationPaths(settings["chat.instructionsFilesLocations"]),
9356
+ agentLocations: extractLocationPaths(settings["chat.agentFilesLocations"]),
9357
+ skillsLocations: extractLocationPaths(settings["chat.agentSkillsLocations"])
9094
9358
  };
9095
- return names[level] || "Unknown";
9096
9359
  }
9097
- function getLevelDescription(level) {
9098
- const descriptions = {
9099
- 1: "Repo builds, tests run, and basic tooling (linter, lockfile) is in place. AI agents can clone and get started.",
9100
- 2: "README, CONTRIBUTING guide, and custom instructions exist. Agents understand project context and conventions.",
9101
- 3: "CI/CD, security policies, CODEOWNERS, and observability are configured. Agents operate within well-defined guardrails.",
9102
- 4: "MCP servers, custom agents, and AI skills are set up. Agents have deep integration with project-specific tools and workflows.",
9103
- 5: "Full AI-native development: agents can independently plan, implement, test, and ship changes with minimal human oversight."
9360
+ function mergeLocations(a, b) {
9361
+ return {
9362
+ instructionsLocations: [...a.instructionsLocations, ...b.instructionsLocations],
9363
+ agentLocations: [...a.agentLocations, ...b.agentLocations],
9364
+ skillsLocations: [...a.skillsLocations, ...b.skillsLocations]
9104
9365
  };
9105
- return descriptions[level] || "";
9106
9366
  }
9107
- async function runReadinessReport(options) {
9108
- const repoPath = options.repoPath;
9109
- const analysis = await analyzeRepo(repoPath);
9110
- const rootFiles = await safeReadDir(repoPath);
9111
- const rootPackageJson = await readJson(path9.join(repoPath, "package.json"));
9112
- const apps = analysis.apps?.length ? analysis.apps : [];
9113
- const context = {
9114
- repoPath,
9115
- analysis,
9116
- apps,
9117
- rootFiles,
9118
- rootPackageJson
9367
+ async function parseVscodeLocations(repoPath, rootFiles) {
9368
+ const empty = {
9369
+ instructionsLocations: [],
9370
+ agentLocations: [],
9371
+ skillsLocations: []
9119
9372
  };
9120
- let policySources = options.policies;
9121
- let isConfigSourced = false;
9122
- if (!policySources?.length) {
9123
- const agentrcConfig = await loadAgentrcConfig(repoPath);
9124
- if (agentrcConfig?.policies?.length) {
9125
- policySources = agentrcConfig.policies;
9126
- isConfigSourced = true;
9373
+ let result = { ...empty };
9374
+ const settings = await readJson(path9.join(repoPath, ".vscode", "settings.json"));
9375
+ if (settings) {
9376
+ result = mergeLocations(result, extractLocationsFromSettings(settings));
9377
+ }
9378
+ const workspaceFiles = rootFiles.filter((f) => f.endsWith(".code-workspace"));
9379
+ for (const wsFile of workspaceFiles) {
9380
+ const ws = await readJson(path9.join(repoPath, wsFile));
9381
+ if (ws?.settings && typeof ws.settings === "object" && !Array.isArray(ws.settings)) {
9382
+ result = mergeLocations(
9383
+ result,
9384
+ extractLocationsFromSettings(ws.settings)
9385
+ );
9127
9386
  }
9128
9387
  }
9129
- const baseCriteria = buildCriteria();
9130
- const baseExtras = buildExtras();
9131
- let resolvedCriteria;
9132
- let resolvedExtras;
9133
- let passRateThreshold = 0.8;
9134
- let policyInfo;
9135
- if (policySources?.length) {
9136
- const policyConfigs = [];
9137
- for (const source of policySources) {
9138
- policyConfigs.push(await loadPolicy(source, { jsonOnly: isConfigSourced }));
9388
+ return {
9389
+ instructionsLocations: [...new Set(result.instructionsLocations)],
9390
+ agentLocations: [...new Set(result.agentLocations)],
9391
+ skillsLocations: [...new Set(result.skillsLocations)]
9392
+ };
9393
+ }
9394
+ async function hasCustomInstructions(repoPath) {
9395
+ const found = [];
9396
+ const candidates = [
9397
+ ".github/copilot-instructions.md",
9398
+ "CLAUDE.md",
9399
+ ".claude/CLAUDE.md",
9400
+ "AGENTS.md",
9401
+ "GEMINI.md",
9402
+ ".github/AGENTS.md",
9403
+ ".cursorrules",
9404
+ ".cursorignore",
9405
+ ".windsurfrules",
9406
+ ".github/instructions.md",
9407
+ "copilot-instructions.md"
9408
+ ];
9409
+ for (const candidate of candidates) {
9410
+ if (await fileExists(path9.join(repoPath, candidate))) {
9411
+ found.push(candidate);
9139
9412
  }
9140
- const resolved = resolveChain(baseCriteria, baseExtras, policyConfigs);
9141
- resolvedCriteria = resolved.criteria;
9142
- resolvedExtras = resolved.extras;
9143
- passRateThreshold = resolved.thresholds.passRate;
9144
- policyInfo = { chain: resolved.chain, criteriaCount: resolved.criteria.length };
9145
- } else {
9146
- resolvedCriteria = baseCriteria;
9147
- resolvedExtras = baseExtras;
9148
9413
  }
9149
- const criteriaResults = [];
9150
- for (const criterion of resolvedCriteria) {
9151
- if (criterion.scope === "repo") {
9152
- const result = await criterion.check(context);
9153
- criteriaResults.push({
9154
- id: criterion.id,
9155
- title: criterion.title,
9156
- pillar: criterion.pillar,
9157
- level: criterion.level,
9158
- scope: criterion.scope,
9159
- impact: criterion.impact,
9160
- effort: criterion.effort,
9161
- status: result.status,
9162
- reason: result.reason,
9163
- evidence: result.evidence
9164
- });
9165
- continue;
9414
+ return found;
9415
+ }
9416
+ async function hasAgentPluginInstructions(repoPath) {
9417
+ const pluginComponents = await discoverAgentPluginComponents(repoPath);
9418
+ return [...new Set(pluginComponents.instructions)];
9419
+ }
9420
+ async function hasNestedCopilotInstructions(repoPath) {
9421
+ const matches = await fg3(
9422
+ ["**/.github/copilot-instructions.md", "**/AGENTS.md", "**/CLAUDE.md", "**/GEMINI.md"],
9423
+ {
9424
+ cwd: repoPath,
9425
+ onlyFiles: true,
9426
+ dot: true,
9427
+ followSymbolicLinks: false,
9428
+ ignore: AGENT_PLUGIN_SCAN_IGNORES,
9429
+ unique: true
9166
9430
  }
9167
- if (criterion.scope === "area") {
9168
- if (!options.perArea) continue;
9169
- const areas2 = analysis.areas ?? [];
9170
- if (areas2.length === 0) continue;
9171
- criteriaResults.push({
9172
- id: criterion.id,
9173
- title: criterion.title,
9174
- pillar: criterion.pillar,
9175
- level: criterion.level,
9176
- scope: criterion.scope,
9177
- impact: criterion.impact,
9178
- effort: criterion.effort,
9179
- status: "skip",
9180
- reason: "Run with --per-area for area breakdown."
9181
- });
9431
+ );
9432
+ return matches.map((entry) => entry.replace(/\\/gu, "/")).sort();
9433
+ }
9434
+ async function hasCopilotPluginSetting(repoPath, key) {
9435
+ const found = [];
9436
+ for (const settingsPath of COPILOT_REPO_SETTINGS_FILES) {
9437
+ const settings = await readJson(path9.join(repoPath, settingsPath));
9438
+ const value = settings?.[key];
9439
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
9182
9440
  continue;
9183
9441
  }
9184
- const appResults = await Promise.all(
9185
- apps.map(async (app) => ({
9186
- app,
9187
- result: await criterion.check(context, app)
9188
- }))
9189
- );
9190
- if (!appResults.length) {
9191
- criteriaResults.push({
9192
- id: criterion.id,
9193
- title: criterion.title,
9194
- pillar: criterion.pillar,
9195
- level: criterion.level,
9196
- scope: criterion.scope,
9197
- impact: criterion.impact,
9198
- effort: criterion.effort,
9199
- status: "skip",
9200
- reason: "No application packages detected."
9201
- });
9202
- continue;
9442
+ const entries = Object.values(value);
9443
+ const configured = key === "enabledPlugins" ? entries.some((entry) => entry === true) : entries.length > 0;
9444
+ if (configured) {
9445
+ found.push(`${settingsPath} (${key})`);
9203
9446
  }
9204
- const passed = appResults.filter((entry) => entry.result.status === "pass").length;
9205
- const total = appResults.length;
9206
- const passRate = total ? passed / total : 0;
9207
- const status = passRate >= passRateThreshold ? "pass" : "fail";
9208
- const failures = appResults.filter((entry) => entry.result.status !== "pass").map((entry) => entry.app.name);
9209
- criteriaResults.push({
9210
- id: criterion.id,
9211
- title: criterion.title,
9212
- pillar: criterion.pillar,
9213
- level: criterion.level,
9214
- scope: criterion.scope,
9215
- impact: criterion.impact,
9216
- effort: criterion.effort,
9217
- status,
9218
- reason: status === "pass" ? void 0 : `Only ${passed}/${total} apps pass this check.`,
9219
- passRate,
9220
- appSummary: { passed, total },
9221
- appFailures: failures
9447
+ }
9448
+ return found;
9449
+ }
9450
+ async function hasFileBasedInstructions(repoPath, extraDirs) {
9451
+ const found = [];
9452
+ const instructionDirs = [".github/instructions", ...extraDirs ?? []];
9453
+ for (const dir of instructionDirs) {
9454
+ const normalizedDir = dir.replace(/\\/gu, "/").replace(/\/+$/u, "");
9455
+ const entries = await fg3("**/*.instructions.md", {
9456
+ cwd: path9.join(repoPath, dir),
9457
+ onlyFiles: true,
9458
+ dot: true,
9459
+ followSymbolicLinks: false,
9460
+ suppressErrors: true
9222
9461
  });
9462
+ found.push(...entries.map((entry) => `${normalizedDir}/${entry.replace(/\\/gu, "/")}`));
9223
9463
  }
9224
- let areaReports;
9225
- const areas = analysis.areas ?? [];
9226
- if (options.perArea && areas.length > 0) {
9227
- const areaCriteria = resolvedCriteria.filter((c) => c.scope === "area");
9228
- areaReports = [];
9229
- for (const area of areas) {
9230
- if (!area.path) continue;
9231
- const areaFiles = await safeReadDir(area.path);
9232
- const areaContext = {
9233
- ...context,
9234
- areaPath: area.path,
9235
- areaFiles
9236
- };
9237
- const areaResults = [];
9238
- for (const criterion of areaCriteria) {
9239
- const result = await criterion.check(areaContext, void 0, area);
9240
- areaResults.push({
9241
- id: criterion.id,
9242
- title: criterion.title,
9243
- pillar: criterion.pillar,
9244
- level: criterion.level,
9245
- scope: criterion.scope,
9246
- impact: criterion.impact,
9247
- effort: criterion.effort,
9248
- status: result.status,
9249
- reason: result.reason,
9250
- evidence: result.evidence
9251
- });
9252
- }
9253
- const areaPillars = summarizePillars(areaResults);
9254
- areaReports.push({ area, criteria: areaResults, pillars: areaPillars });
9464
+ return [...new Set(found)];
9465
+ }
9466
+ function contentSimilarity(a, b) {
9467
+ const normalize = (s) => new Set(
9468
+ s.toLowerCase().split("\n").map((l) => l.trim().replace(/\s+/gu, " ")).filter((l) => l.length > 0)
9469
+ );
9470
+ const setA = normalize(a);
9471
+ const setB = normalize(b);
9472
+ if (setA.size === 0 && setB.size === 0) return 1;
9473
+ let intersection = 0;
9474
+ for (const line of setA) {
9475
+ if (setB.has(line)) intersection++;
9476
+ }
9477
+ const union = (/* @__PURE__ */ new Set([...setA, ...setB])).size;
9478
+ return union === 0 ? 1 : intersection / union;
9479
+ }
9480
+ async function checkInstructionConsistency(repoPath, foundFiles) {
9481
+ if (foundFiles.length <= 1) {
9482
+ return { unified: true, files: foundFiles };
9483
+ }
9484
+ const realPathMap = /* @__PURE__ */ new Map();
9485
+ for (const file of foundFiles) {
9486
+ const fullPath = path9.join(repoPath, file);
9487
+ try {
9488
+ const real = await fs7.realpath(fullPath);
9489
+ const group = realPathMap.get(real) ?? [];
9490
+ group.push(file);
9491
+ realPathMap.set(real, group);
9492
+ } catch {
9493
+ realPathMap.set(fullPath, [file]);
9255
9494
  }
9256
- for (const criterion of criteriaResults) {
9257
- if (criterion.scope !== "area") continue;
9258
- const perAreaResults = areaReports.map((ar) => ar.criteria.find((c) => c.id === criterion.id)).filter(Boolean);
9259
- if (!perAreaResults.length) continue;
9260
- const passed = perAreaResults.filter((r) => r.status === "pass").length;
9261
- const total = perAreaResults.length;
9262
- const passRate = total ? passed / total : 0;
9263
- criterion.status = passRate >= passRateThreshold ? "pass" : "fail";
9264
- criterion.reason = criterion.status === "pass" ? void 0 : `Only ${passed}/${total} areas pass this check.`;
9265
- criterion.passRate = passRate;
9266
- criterion.areaSummary = { passed, total };
9267
- criterion.areaFailures = areaReports.filter((ar) => ar.criteria.find((c) => c.id === criterion.id)?.status !== "pass").map((ar) => ar.area.name);
9495
+ }
9496
+ const groups = [...realPathMap.values()];
9497
+ if (groups.length <= 1) {
9498
+ return { unified: true, files: foundFiles };
9499
+ }
9500
+ const contents = [];
9501
+ for (const group of groups) {
9502
+ try {
9503
+ contents.push(await fs7.readFile(path9.join(repoPath, group[0]), "utf8"));
9504
+ } catch {
9505
+ contents.push("");
9268
9506
  }
9269
9507
  }
9270
- const pillars = summarizePillars(criteriaResults);
9271
- const levels = summarizeLevels(criteriaResults, passRateThreshold);
9272
- const achievedLevel = levels.filter((level) => level.achieved).reduce((acc, level) => Math.max(acc, level.level), 0);
9273
- const extras = options.includeExtras === false ? [] : await runExtras(context, resolvedExtras);
9274
- let engine;
9275
- if (options.shadow) {
9276
- const policyCtx = {
9277
- repoPath,
9278
- rootFiles,
9279
- rootPackageJson,
9280
- cache: /* @__PURE__ */ new Map(),
9281
- analysis,
9282
- apps
9283
- };
9284
- const engineChain = await loadPluginChain(policySources ?? [], { jsonOnly: isConfigSourced });
9285
- const engineReport = await executePlugins(engineChain.plugins, policyCtx, engineChain.options);
9286
- engine = {
9287
- signals: engineReport.signals,
9288
- recommendations: engineReport.recommendations,
9289
- policyWarnings: engineReport.policyWarnings,
9290
- score: engineReport.score,
9291
- grade: engineReport.grade
9292
- };
9508
+ let minSimilarity = 1;
9509
+ for (let i = 0; i < contents.length; i++) {
9510
+ for (let j = i + 1; j < contents.length; j++) {
9511
+ minSimilarity = Math.min(minSimilarity, contentSimilarity(contents[i], contents[j]));
9512
+ }
9293
9513
  }
9294
9514
  return {
9295
- repoPath,
9296
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
9297
- isMonorepo: analysis.isMonorepo ?? false,
9298
- apps: apps.map((app) => ({ name: app.name, path: app.path })),
9299
- pillars,
9300
- levels,
9301
- achievedLevel,
9302
- criteria: criteriaResults,
9303
- extras,
9304
- areaReports,
9305
- policies: policyInfo,
9306
- engine
9515
+ unified: minSimilarity >= 0.9,
9516
+ files: foundFiles,
9517
+ similarity: Math.round(minSimilarity * 100) / 100
9307
9518
  };
9308
9519
  }
9520
+ function isAgentPluginsManifest(value) {
9521
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
9522
+ return false;
9523
+ }
9524
+ const manifest = value;
9525
+ const name = manifest.name;
9526
+ return manifest.$schema === AGENT_PLUGINS_SCHEMA && typeof name === "string" && name.length <= 64 && AGENT_PLUGIN_NAME_PATTERN.test(name);
9527
+ }
9528
+ function isUnavailablePathError(error) {
9529
+ const code = error.code;
9530
+ return code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP";
9531
+ }
9532
+ async function isRegularFile(filePath) {
9533
+ try {
9534
+ return (await fs7.lstat(filePath)).isFile();
9535
+ } catch (error) {
9536
+ if (isUnavailablePathError(error)) {
9537
+ return false;
9538
+ }
9539
+ throw error;
9540
+ }
9541
+ }
9542
+ async function hasAgentPluginSkills(skillsDir) {
9543
+ try {
9544
+ if (!(await fs7.lstat(skillsDir)).isDirectory()) {
9545
+ return false;
9546
+ }
9547
+ const entries = await fs7.readdir(skillsDir, { withFileTypes: true });
9548
+ for (const entry of entries) {
9549
+ if (entry.isDirectory() && await isRegularFile(path9.join(skillsDir, entry.name, "SKILL.md"))) {
9550
+ return true;
9551
+ }
9552
+ }
9553
+ return false;
9554
+ } catch (error) {
9555
+ if (isUnavailablePathError(error)) {
9556
+ return false;
9557
+ }
9558
+ throw error;
9559
+ }
9560
+ }
9561
+ async function hasMarkdownFiles(directory) {
9562
+ const files = await fg3("**/*.md", {
9563
+ cwd: directory,
9564
+ onlyFiles: true,
9565
+ dot: true,
9566
+ followSymbolicLinks: false,
9567
+ suppressErrors: true
9568
+ });
9569
+ return files.length > 0;
9570
+ }
9571
+ function relativeEvidencePath(repoPath, absolutePath) {
9572
+ return path9.relative(repoPath, absolutePath).replace(/\\/gu, "/");
9573
+ }
9574
+ function resolveAgentPluginRoot(manifestPath) {
9575
+ const manifestDir = path9.dirname(manifestPath);
9576
+ const manifestDirName = path9.basename(manifestDir);
9577
+ if (manifestDirName === ".plugin" || manifestDirName === ".claude-plugin") {
9578
+ return path9.dirname(manifestDir);
9579
+ }
9580
+ if (manifestDirName === "plugin" && path9.basename(path9.dirname(manifestDir)) === ".github") {
9581
+ return path9.dirname(path9.dirname(manifestDir));
9582
+ }
9583
+ return manifestDir;
9584
+ }
9585
+ async function discoverAgentPluginComponents(repoPath) {
9586
+ const manifestPaths = await fg3(["plugin.json", "**/plugin.json"], {
9587
+ cwd: repoPath,
9588
+ absolute: true,
9589
+ onlyFiles: true,
9590
+ dot: true,
9591
+ followSymbolicLinks: false,
9592
+ ignore: AGENT_PLUGIN_SCAN_IGNORES,
9593
+ unique: true
9594
+ });
9595
+ const components = {
9596
+ agents: [],
9597
+ instructions: [],
9598
+ skills: [],
9599
+ mcp: []
9600
+ };
9601
+ for (const manifestPath of manifestPaths.sort()) {
9602
+ let rawManifest;
9603
+ try {
9604
+ rawManifest = JSON.parse(await fs7.readFile(manifestPath, "utf8"));
9605
+ } catch (error) {
9606
+ if (error instanceof SyntaxError || isUnavailablePathError(error)) {
9607
+ continue;
9608
+ }
9609
+ throw error;
9610
+ }
9611
+ if (!isAgentPluginsManifest(rawManifest)) {
9612
+ continue;
9613
+ }
9614
+ const pluginRoot = resolveAgentPluginRoot(manifestPath);
9615
+ const skillsDir = path9.join(pluginRoot, "skills");
9616
+ if (await hasAgentPluginSkills(skillsDir)) {
9617
+ components.skills.push(relativeEvidencePath(repoPath, skillsDir));
9618
+ }
9619
+ const mcpPath = path9.join(pluginRoot, "mcp.json");
9620
+ if (await isRegularFile(mcpPath)) {
9621
+ components.mcp.push(relativeEvidencePath(repoPath, mcpPath));
9622
+ }
9623
+ const copilotExtensionDir = path9.join(pluginRoot, "com.github.copilot");
9624
+ const agentsDir = path9.join(copilotExtensionDir, "agents");
9625
+ if (await hasMarkdownFiles(agentsDir)) {
9626
+ components.agents.push(relativeEvidencePath(repoPath, agentsDir));
9627
+ }
9628
+ const rulesDir = path9.join(copilotExtensionDir, "rules");
9629
+ if (await hasMarkdownFiles(rulesDir)) {
9630
+ components.instructions.push(relativeEvidencePath(repoPath, rulesDir));
9631
+ }
9632
+ }
9633
+ return components;
9634
+ }
9635
+ async function hasMcpConfig(repoPath) {
9636
+ const found = [];
9637
+ if (await fileExists(path9.join(repoPath, ".vscode", "mcp.json"))) {
9638
+ found.push(".vscode/mcp.json");
9639
+ }
9640
+ found.push(
9641
+ ...(await fg3([".mcp.json", ".github/mcp.json", "**/.mcp.json", "**/.github/mcp.json"], {
9642
+ cwd: repoPath,
9643
+ onlyFiles: true,
9644
+ dot: true,
9645
+ followSymbolicLinks: false,
9646
+ ignore: AGENT_PLUGIN_SCAN_IGNORES,
9647
+ unique: true
9648
+ })).map((entry) => entry.replace(/\\/gu, "/")).sort()
9649
+ );
9650
+ if (await fileExists(path9.join(repoPath, "mcp.json"))) {
9651
+ found.push("mcp.json");
9652
+ }
9653
+ const settings = await readJson(path9.join(repoPath, ".vscode", "settings.json"));
9654
+ if (settings && (settings["mcp"] || settings["github.copilot.chat.mcp.enabled"])) {
9655
+ found.push(".vscode/settings.json (mcp section)");
9656
+ }
9657
+ if (await fileExists(path9.join(repoPath, ".claude", "mcp.json"))) {
9658
+ found.push(".claude/mcp.json");
9659
+ }
9660
+ const pluginComponents = await discoverAgentPluginComponents(repoPath);
9661
+ return [.../* @__PURE__ */ new Set([...found, ...pluginComponents.mcp])];
9662
+ }
9663
+ async function hasCustomAgents(repoPath, extraDirs) {
9664
+ const found = [];
9665
+ found.push(
9666
+ ...(await fg3([".github/agents", ".claude/agents", "**/.github/agents", "**/.claude/agents"], {
9667
+ cwd: repoPath,
9668
+ onlyDirectories: true,
9669
+ dot: true,
9670
+ followSymbolicLinks: false,
9671
+ ignore: AGENT_PLUGIN_SCAN_IGNORES,
9672
+ unique: true
9673
+ })).map((entry) => entry.replace(/\\/gu, "/")).sort()
9674
+ );
9675
+ const agentDirs = [".copilot/agents", ".github/copilot/agents"];
9676
+ for (const dir of agentDirs) {
9677
+ if (await fileExists(path9.join(repoPath, dir))) {
9678
+ found.push(dir);
9679
+ }
9680
+ }
9681
+ const agentFiles = [".github/copilot-agents.yml", ".github/copilot-agents.yaml"];
9682
+ for (const agentFile of agentFiles) {
9683
+ if (await fileExists(path9.join(repoPath, agentFile))) {
9684
+ found.push(agentFile);
9685
+ }
9686
+ }
9687
+ for (const dir of extraDirs ?? []) {
9688
+ if (await fileExists(path9.join(repoPath, dir))) {
9689
+ found.push(dir);
9690
+ }
9691
+ }
9692
+ const pluginComponents = await discoverAgentPluginComponents(repoPath);
9693
+ return [.../* @__PURE__ */ new Set([...found, ...pluginComponents.agents])];
9694
+ }
9695
+ async function hasCopilotSkills(repoPath, extraDirs) {
9696
+ const found = [];
9697
+ found.push(
9698
+ ...(await fg3(
9699
+ [
9700
+ ".github/skills",
9701
+ ".agents/skills",
9702
+ ".claude/skills",
9703
+ "**/.github/skills",
9704
+ "**/.agents/skills",
9705
+ "**/.claude/skills"
9706
+ ],
9707
+ {
9708
+ cwd: repoPath,
9709
+ onlyDirectories: true,
9710
+ dot: true,
9711
+ followSymbolicLinks: false,
9712
+ ignore: AGENT_PLUGIN_SCAN_IGNORES,
9713
+ unique: true
9714
+ }
9715
+ )).map((entry) => entry.replace(/\\/gu, "/")).sort()
9716
+ );
9717
+ const skillDirs = [".copilot/skills", ".github/copilot/skills"];
9718
+ for (const dir of skillDirs) {
9719
+ if (await fileExists(path9.join(repoPath, dir))) {
9720
+ found.push(dir);
9721
+ }
9722
+ }
9723
+ for (const dir of extraDirs ?? []) {
9724
+ if (await fileExists(path9.join(repoPath, dir))) {
9725
+ found.push(dir);
9726
+ }
9727
+ }
9728
+ const pluginComponents = await discoverAgentPluginComponents(repoPath);
9729
+ return [.../* @__PURE__ */ new Set([...found, ...pluginComponents.skills])];
9730
+ }
9731
+ async function hasApmConfig(repoPath) {
9732
+ return fileExists(path9.join(repoPath, "apm.yml"));
9733
+ }
9734
+ async function hasApmLockfile(repoPath) {
9735
+ return fileExists(path9.join(repoPath, "apm.lock.yaml"));
9736
+ }
9737
+ async function hasApmInWorkflows(repoPath) {
9738
+ const workflowDir = path9.join(repoPath, ".github", "workflows");
9739
+ let files;
9740
+ try {
9741
+ files = await fs7.readdir(workflowDir);
9742
+ } catch {
9743
+ return false;
9744
+ }
9745
+ for (const file of files) {
9746
+ if (!file.endsWith(".yml") && !file.endsWith(".yaml")) continue;
9747
+ try {
9748
+ const content = await fs7.readFile(path9.join(workflowDir, file), "utf8");
9749
+ if (/\bmicrosoft\/apm-action\b/.test(content) || /\bapm\s+(audit|install)\b/.test(content)) {
9750
+ return true;
9751
+ }
9752
+ } catch {
9753
+ }
9754
+ }
9755
+ return false;
9756
+ }
9757
+ async function readAllDependencies(context) {
9758
+ const dependencies = [];
9759
+ const apps = context.apps.length ? context.apps : [];
9760
+ for (const app of apps) {
9761
+ if (!app.packageJsonPath) continue;
9762
+ const pkg = await readJson(app.packageJsonPath);
9763
+ const deps = pkg?.dependencies ?? {};
9764
+ const devDeps = pkg?.devDependencies ?? {};
9765
+ dependencies.push(
9766
+ ...Object.keys({
9767
+ ...deps,
9768
+ ...devDeps
9769
+ })
9770
+ );
9771
+ }
9772
+ if (!apps.length && context.rootPackageJson) {
9773
+ const rootDeps = context.rootPackageJson.dependencies ?? {};
9774
+ const rootDevDeps = context.rootPackageJson.devDependencies ?? {};
9775
+ dependencies.push(
9776
+ ...Object.keys({
9777
+ ...rootDeps,
9778
+ ...rootDevDeps
9779
+ })
9780
+ );
9781
+ }
9782
+ return Array.from(new Set(dependencies));
9783
+ }
9784
+
9785
+ // packages/core/src/services/readiness/criteria.ts
9786
+ import path10 from "path";
9309
9787
  function buildCriteria() {
9310
9788
  return [
9311
9789
  {
@@ -9338,7 +9816,7 @@ function buildCriteria() {
9338
9816
  return {
9339
9817
  status: found ? "pass" : "fail",
9340
9818
  reason: found ? void 0 : "Missing type checking config (tsconfig or equivalent).",
9341
- evidence: ["tsconfig.json", "pyproject.toml", "mypy.ini"]
9819
+ evidence: ["tsconfig.json", "tsconfig.base.json", "pyproject.toml", "mypy.ini"]
9342
9820
  };
9343
9821
  }
9344
9822
  },
@@ -9417,7 +9895,7 @@ function buildCriteria() {
9417
9895
  impact: "medium",
9418
9896
  effort: "low",
9419
9897
  check: async (context) => {
9420
- const found = await fileExists(path9.join(context.repoPath, "CONTRIBUTING.md"));
9898
+ const found = await fileExists(path10.join(context.repoPath, "CONTRIBUTING.md"));
9421
9899
  return {
9422
9900
  status: found ? "pass" : "fail",
9423
9901
  reason: found ? void 0 : "Missing CONTRIBUTING.md for contributor workflows."
@@ -9518,7 +9996,7 @@ function buildCriteria() {
9518
9996
  impact: "high",
9519
9997
  effort: "low",
9520
9998
  check: async (context) => {
9521
- const found = await fileExists(path9.join(context.repoPath, "SECURITY.md"));
9999
+ const found = await fileExists(path10.join(context.repoPath, "SECURITY.md"));
9522
10000
  return {
9523
10001
  status: found ? "pass" : "fail",
9524
10002
  reason: found ? void 0 : "Missing SECURITY.md policy."
@@ -9534,7 +10012,7 @@ function buildCriteria() {
9534
10012
  impact: "medium",
9535
10013
  effort: "medium",
9536
10014
  check: async (context) => {
9537
- const found = await fileExists(path9.join(context.repoPath, ".github", "dependabot.yml"));
10015
+ const found = await fileExists(path10.join(context.repoPath, ".github", "dependabot.yml"));
9538
10016
  return {
9539
10017
  status: found ? "pass" : "fail",
9540
10018
  reason: found ? void 0 : "Missing .github/dependabot.yml configuration."
@@ -9570,33 +10048,62 @@ function buildCriteria() {
9570
10048
  effort: "low",
9571
10049
  check: async (context) => {
9572
10050
  const rootFound = await hasCustomInstructions(context.repoPath);
9573
- if (rootFound.length === 0) {
10051
+ const pluginInstructions = await hasAgentPluginInstructions(context.repoPath);
10052
+ const nestedInstructions = (await hasNestedCopilotInstructions(context.repoPath)).filter(
10053
+ (instruction) => !rootFound.includes(instruction)
10054
+ );
10055
+ const fileBasedInstructions = await hasFileBasedInstructions(
10056
+ context.repoPath,
10057
+ context.vscodeLocations?.instructionsLocations
10058
+ );
10059
+ const found = [
10060
+ .../* @__PURE__ */ new Set([
10061
+ ...rootFound,
10062
+ ...nestedInstructions,
10063
+ ...fileBasedInstructions,
10064
+ ...pluginInstructions
10065
+ ])
10066
+ ];
10067
+ if (found.length === 0) {
9574
10068
  return {
9575
10069
  status: "fail",
9576
- reason: "Missing custom instructions (e.g. copilot-instructions.md, CLAUDE.md, AGENTS.md, .cursorrules).",
10070
+ reason: "Missing custom instructions (e.g. copilot-instructions.md, AGENTS.md, CLAUDE.md, GEMINI.md, or *.instructions.md).",
9577
10071
  evidence: [
9578
- "copilot-instructions.md",
10072
+ ".github/copilot-instructions.md",
9579
10073
  "CLAUDE.md",
9580
10074
  "AGENTS.md",
9581
- ".cursorrules",
9582
- ".github/copilot-instructions.md"
10075
+ "GEMINI.md",
10076
+ ".github/instructions/*.instructions.md"
9583
10077
  ]
9584
10078
  };
9585
10079
  }
9586
- const fileBasedInstructions = await hasFileBasedInstructions(context.repoPath);
9587
10080
  const areas = context.analysis.areas ?? [];
9588
10081
  if (areas.length > 0) {
9589
10082
  if (fileBasedInstructions.length === 0) {
9590
10083
  return {
9591
10084
  status: "pass",
9592
- reason: `Root instructions found, but no area instructions for ${areas.length} detected areas. Run \`agentrc instructions --areas\` to generate.`,
9593
- evidence: [...rootFound, ...areas.map((a) => `${a.name}: missing .instructions.md`)]
10085
+ reason: rootFound.length > 0 || nestedInstructions.length > 0 ? `Repository instructions found, but no area instructions for ${areas.length} detected areas. Run \`agentrc instructions --areas\` to generate.` : `${pluginInstructions.length} Agent Plugin rule source(s) found, but no repository or area instructions.`,
10086
+ evidence: [...found, ...areas.map((a) => `${a.name}: missing .instructions.md`)]
10087
+ };
10088
+ }
10089
+ if (rootFound.length === 0) {
10090
+ return {
10091
+ status: "pass",
10092
+ reason: `${fileBasedInstructions.length} file-based instruction(s) found, but no repository-wide instructions.`,
10093
+ evidence: [...fileBasedInstructions, ...pluginInstructions]
9594
10094
  };
9595
10095
  }
9596
10096
  return {
9597
10097
  status: "pass",
9598
10098
  reason: `Root + ${fileBasedInstructions.length} area instruction(s) found.`,
9599
- evidence: [...rootFound, ...fileBasedInstructions]
10099
+ evidence: found
10100
+ };
10101
+ }
10102
+ if (fileBasedInstructions.length > 0) {
10103
+ return {
10104
+ status: "pass",
10105
+ reason: rootFound.length > 0 ? `Root + ${fileBasedInstructions.length} file-based instruction(s) found.` : `${fileBasedInstructions.length} file-based instruction(s) found, but no repository-wide instructions.`,
10106
+ evidence: found
9600
10107
  };
9601
10108
  }
9602
10109
  if (context.analysis.isMonorepo && context.apps.length > 1) {
@@ -9620,7 +10127,8 @@ function buildCriteria() {
9620
10127
  }
9621
10128
  return {
9622
10129
  status: "pass",
9623
- evidence: rootFound
10130
+ reason: rootFound.length === 0 && pluginInstructions.length > 0 ? `${pluginInstructions.length} Agent Plugin rule source(s) found, but no repository-wide instructions.` : void 0,
10131
+ evidence: found
9624
10132
  };
9625
10133
  }
9626
10134
  },
@@ -9664,8 +10172,14 @@ function buildCriteria() {
9664
10172
  const found = await hasMcpConfig(context.repoPath);
9665
10173
  return {
9666
10174
  status: found.length > 0 ? "pass" : "fail",
9667
- reason: "Missing MCP (Model Context Protocol) configuration (e.g. .vscode/mcp.json).",
9668
- evidence: found.length > 0 ? found : [".vscode/mcp.json", ".vscode/settings.json (mcp section)", "mcp.json"]
10175
+ reason: found.length > 0 ? void 0 : "Missing MCP (Model Context Protocol) configuration (e.g. .vscode/mcp.json or an Agent Plugin mcp.json).",
10176
+ evidence: found.length > 0 ? found : [
10177
+ ".vscode/mcp.json",
10178
+ ".vscode/settings.json (mcp section)",
10179
+ ".mcp.json",
10180
+ ".github/mcp.json",
10181
+ "<agent-plugin>/mcp.json"
10182
+ ]
9669
10183
  };
9670
10184
  }
9671
10185
  },
@@ -9678,28 +10192,127 @@ function buildCriteria() {
9678
10192
  impact: "medium",
9679
10193
  effort: "medium",
9680
10194
  check: async (context) => {
9681
- const found = await hasCustomAgents(context.repoPath);
10195
+ const found = await hasCustomAgents(
10196
+ context.repoPath,
10197
+ context.vscodeLocations?.agentLocations
10198
+ );
9682
10199
  return {
9683
10200
  status: found.length > 0 ? "pass" : "fail",
9684
- reason: "No custom AI agents configured (e.g. .github/agents/, .copilot/agents/).",
9685
- evidence: found.length > 0 ? found : [".github/agents/", ".copilot/agents/", ".github/copilot/agents/"]
10201
+ reason: found.length > 0 ? void 0 : "No custom AI agents configured (e.g. .github/agents/, .claude/agents/, or an Agent Plugin agents/ directory).",
10202
+ evidence: found.length > 0 ? found : [".github/agents/", ".claude/agents/", "<agent-plugin>/com.github.copilot/agents/"]
9686
10203
  };
9687
10204
  }
9688
10205
  },
9689
10206
  {
9690
10207
  id: "copilot-skills",
9691
- title: "Copilot/Claude skills present",
10208
+ title: "AI skills present",
9692
10209
  pillar: "ai-tooling",
9693
10210
  level: 3,
9694
10211
  scope: "repo",
9695
10212
  impact: "medium",
9696
10213
  effort: "medium",
9697
10214
  check: async (context) => {
9698
- const found = await hasCopilotSkills(context.repoPath);
10215
+ const found = await hasCopilotSkills(
10216
+ context.repoPath,
10217
+ context.vscodeLocations?.skillsLocations
10218
+ );
9699
10219
  return {
9700
10220
  status: found.length > 0 ? "pass" : "fail",
9701
- reason: "No Copilot or Claude skills found (e.g. .copilot/skills/, .github/skills/).",
9702
- evidence: found.length > 0 ? found : [".copilot/skills/", ".github/skills/", ".claude/skills/"]
10221
+ reason: found.length > 0 ? void 0 : "No AI skills found (e.g. .github/skills/, .agents/skills/, .claude/skills/, or an Agent Plugin skills/ directory).",
10222
+ evidence: found.length > 0 ? found : [".github/skills/", ".agents/skills/", ".claude/skills/", "<agent-plugin>/skills/"]
10223
+ };
10224
+ }
10225
+ },
10226
+ {
10227
+ id: "plugin-marketplaces",
10228
+ title: "Additional Copilot plugin marketplaces configured",
10229
+ pillar: "ai-tooling",
10230
+ level: 3,
10231
+ scope: "repo",
10232
+ impact: "low",
10233
+ effort: "low",
10234
+ check: async (context) => {
10235
+ const found = await hasCopilotPluginSetting(context.repoPath, "extraKnownMarketplaces");
10236
+ return {
10237
+ status: found.length > 0 ? "pass" : "skip",
10238
+ reason: found.length > 0 ? void 0 : "No repository-scoped extraKnownMarketplaces setting found.",
10239
+ evidence: found
10240
+ };
10241
+ }
10242
+ },
10243
+ {
10244
+ id: "enabled-plugins",
10245
+ title: "Copilot plugins enabled in repository settings",
10246
+ pillar: "ai-tooling",
10247
+ level: 3,
10248
+ scope: "repo",
10249
+ impact: "low",
10250
+ effort: "low",
10251
+ check: async (context) => {
10252
+ const found = await hasCopilotPluginSetting(context.repoPath, "enabledPlugins");
10253
+ return {
10254
+ status: found.length > 0 ? "pass" : "skip",
10255
+ reason: found.length > 0 ? void 0 : "No repository-scoped enabledPlugins setting found.",
10256
+ evidence: found
10257
+ };
10258
+ }
10259
+ },
10260
+ {
10261
+ id: "apm-config",
10262
+ title: "APM package manifest present",
10263
+ pillar: "ai-tooling",
10264
+ level: 2,
10265
+ scope: "repo",
10266
+ impact: "medium",
10267
+ effort: "low",
10268
+ check: async (context) => {
10269
+ const found = await hasApmConfig(context.repoPath);
10270
+ return {
10271
+ status: found ? "pass" : "fail",
10272
+ reason: found ? void 0 : "No apm.yml found. Use APM to install shared agent packages and keep instructions in sync across repos. See: https://github.com/microsoft/apm",
10273
+ evidence: ["apm.yml"]
10274
+ };
10275
+ }
10276
+ },
10277
+ {
10278
+ id: "apm-locked-deps",
10279
+ title: "APM dependencies locked",
10280
+ pillar: "ai-tooling",
10281
+ level: 3,
10282
+ scope: "repo",
10283
+ impact: "medium",
10284
+ effort: "low",
10285
+ check: async (context) => {
10286
+ const hasConfig = await hasApmConfig(context.repoPath);
10287
+ if (!hasConfig) {
10288
+ return { status: "skip", reason: "No apm.yml found \u2014 skipping lockfile check." };
10289
+ }
10290
+ const found = await hasApmLockfile(context.repoPath);
10291
+ return {
10292
+ status: found ? "pass" : "fail",
10293
+ reason: found ? void 0 : "apm.yml found but dependencies are not locked. Run `apm install` to generate apm.lock.yaml.",
10294
+ evidence: ["apm.lock.yaml"]
10295
+ };
10296
+ }
10297
+ },
10298
+ {
10299
+ id: "apm-ci-integration",
10300
+ title: "APM integrated in CI pipeline",
10301
+ pillar: "ai-tooling",
10302
+ level: 4,
10303
+ scope: "repo",
10304
+ impact: "high",
10305
+ effort: "medium",
10306
+ check: async (context) => {
10307
+ const hasConfig = await hasApmConfig(context.repoPath);
10308
+ if (!hasConfig) {
10309
+ return { status: "skip", reason: "No apm.yml found \u2014 skipping CI check." };
10310
+ }
10311
+ const found = await hasApmInWorkflows(context.repoPath);
10312
+ return {
10313
+ status: found ? "pass" : "fail",
10314
+ reason: found ? void 0 : "No APM step found in CI. Add `microsoft/apm-action` to your workflow to audit agent packages on every PR. See: https://github.com/microsoft/apm-action",
10315
+ evidence: [".github/workflows/*.{yml,yaml}"]
9703
10316
  };
9704
10317
  }
9705
10318
  },
@@ -9740,7 +10353,7 @@ function buildCriteria() {
9740
10353
  if (area?.scripts?.build) {
9741
10354
  return { status: "pass" };
9742
10355
  }
9743
- const pkgPath = path9.join(context.areaPath, "package.json");
10356
+ const pkgPath = path10.join(context.areaPath, "package.json");
9744
10357
  const pkg = await readJson(pkgPath);
9745
10358
  const scripts = pkg?.scripts ?? {};
9746
10359
  const found = Boolean(scripts.build);
@@ -9765,7 +10378,7 @@ function buildCriteria() {
9765
10378
  if (area?.scripts?.test) {
9766
10379
  return { status: "pass" };
9767
10380
  }
9768
- const pkgPath = path9.join(context.areaPath, "package.json");
10381
+ const pkgPath = path10.join(context.areaPath, "package.json");
9769
10382
  const pkg = await readJson(pkgPath);
9770
10383
  const scripts = pkg?.scripts ?? {};
9771
10384
  const found = Boolean(scripts.test);
@@ -9788,7 +10401,7 @@ function buildCriteria() {
9788
10401
  return { status: "skip", reason: "No area context." };
9789
10402
  }
9790
10403
  const sanitized = sanitizeAreaName(area.name);
9791
- const instructionPath = path9.join(
10404
+ const instructionPath = path10.join(
9792
10405
  context.repoPath,
9793
10406
  ".github",
9794
10407
  "instructions",
@@ -9803,13 +10416,16 @@ function buildCriteria() {
9803
10416
  }
9804
10417
  ];
9805
10418
  }
10419
+
10420
+ // packages/core/src/services/readiness/extras.ts
10421
+ import path11 from "path";
9806
10422
  function buildExtras() {
9807
10423
  return [
9808
10424
  {
9809
10425
  id: "agents-doc",
9810
10426
  title: "AGENTS.md present",
9811
10427
  check: async (context) => {
9812
- const found = await fileExists(path9.join(context.repoPath, "AGENTS.md"));
10428
+ const found = await fileExists(path11.join(context.repoPath, "AGENTS.md"));
9813
10429
  return {
9814
10430
  status: found ? "pass" : "fail",
9815
10431
  reason: found ? void 0 : "Missing AGENTS.md to guide coding agents."
@@ -9851,18 +10467,65 @@ function buildExtras() {
9851
10467
  }
9852
10468
  ];
9853
10469
  }
9854
- async function runExtras(context, extraDefs) {
9855
- const results = [];
9856
- for (const def of extraDefs) {
9857
- const result = await def.check(context);
9858
- results.push({
9859
- id: def.id,
9860
- title: def.title,
9861
- status: result.status,
9862
- reason: result.reason
9863
- });
9864
- }
9865
- return results;
10470
+ async function runExtras(context, extraDefs) {
10471
+ const results = [];
10472
+ for (const def of extraDefs) {
10473
+ const result = await def.check(context);
10474
+ results.push({
10475
+ id: def.id,
10476
+ title: def.title,
10477
+ status: result.status,
10478
+ reason: result.reason
10479
+ });
10480
+ }
10481
+ return results;
10482
+ }
10483
+
10484
+ // packages/core/src/services/readiness/types.ts
10485
+ var PILLAR_GROUPS = {
10486
+ "style-validation": "repo-health",
10487
+ "build-system": "repo-health",
10488
+ testing: "repo-health",
10489
+ documentation: "repo-health",
10490
+ "dev-environment": "repo-health",
10491
+ "code-quality": "repo-health",
10492
+ observability: "repo-health",
10493
+ "security-governance": "repo-health",
10494
+ "ai-tooling": "ai-setup"
10495
+ };
10496
+ var PILLAR_GROUP_NAMES = {
10497
+ "repo-health": "Repo Health",
10498
+ "ai-setup": "AI Setup"
10499
+ };
10500
+
10501
+ // packages/core/src/services/readiness/scoring.ts
10502
+ function groupPillars(pillars) {
10503
+ const groups = ["repo-health", "ai-setup"];
10504
+ return groups.map((group) => ({
10505
+ group,
10506
+ label: PILLAR_GROUP_NAMES[group],
10507
+ pillars: pillars.filter((p) => PILLAR_GROUPS[p.id] === group)
10508
+ }));
10509
+ }
10510
+ function getLevelName(level) {
10511
+ const names = {
10512
+ 1: "Functional",
10513
+ 2: "Documented",
10514
+ 3: "Standardized",
10515
+ 4: "Optimized",
10516
+ 5: "Autonomous"
10517
+ };
10518
+ return names[level] || "Unknown";
10519
+ }
10520
+ function getLevelDescription(level) {
10521
+ const descriptions = {
10522
+ 1: "Repo builds, tests run, and basic tooling (linter, lockfile) is in place. AI agents can clone and get started.",
10523
+ 2: "README, CONTRIBUTING guide, and custom instructions exist. Agents understand project context and conventions.",
10524
+ 3: "CI/CD, security policies, CODEOWNERS, and observability are configured. Agents operate within well-defined guardrails.",
10525
+ 4: "MCP servers, custom agents, and AI skills are set up. Agents have deep integration with project-specific tools and workflows.",
10526
+ 5: "Full AI-native development: agents can independently plan, implement, test, and ship changes with minimal human oversight."
10527
+ };
10528
+ return descriptions[level] || "";
9866
10529
  }
9867
10530
  function summarizePillars(criteria) {
9868
10531
  const pillarNames = {
@@ -9924,246 +10587,225 @@ function countStatus(items) {
9924
10587
  const passed = relevant.filter((item) => item.status === "pass").length;
9925
10588
  return { passed, total: relevant.length };
9926
10589
  }
9927
- function hasAnyFile(files, candidates) {
9928
- return candidates.some((candidate) => files.includes(candidate));
9929
- }
9930
- async function hasReadme(repoPath) {
9931
- const files = await safeReadDir(repoPath);
9932
- return files.some(
9933
- (file) => file.toLowerCase() === "readme.md" || file.toLowerCase() === "readme"
9934
- );
9935
- }
9936
- async function hasLintConfig(repoPath) {
9937
- return hasAnyFile(await safeReadDir(repoPath), [
9938
- "eslint.config.js",
9939
- "eslint.config.mjs",
9940
- ".eslintrc",
9941
- ".eslintrc.js",
9942
- ".eslintrc.cjs",
9943
- ".eslintrc.json",
9944
- ".eslintrc.yml",
9945
- ".eslintrc.yaml",
9946
- "biome.json",
9947
- "biome.jsonc",
9948
- ".prettierrc",
9949
- ".prettierrc.json",
9950
- ".prettierrc.js",
9951
- ".prettierrc.cjs",
9952
- "prettier.config.js",
9953
- "prettier.config.cjs"
9954
- ]);
9955
- }
9956
- async function hasFormatterConfig(repoPath) {
9957
- return hasAnyFile(await safeReadDir(repoPath), [
9958
- "biome.json",
9959
- "biome.jsonc",
9960
- ".prettierrc",
9961
- ".prettierrc.json",
9962
- ".prettierrc.js",
9963
- ".prettierrc.cjs",
9964
- "prettier.config.js",
9965
- "prettier.config.cjs"
9966
- ]);
9967
- }
9968
- async function hasTypecheckConfig(repoPath) {
9969
- return hasAnyFile(await safeReadDir(repoPath), [
9970
- "tsconfig.json",
9971
- "tsconfig.base.json",
9972
- "pyproject.toml",
9973
- "mypy.ini"
9974
- ]);
9975
- }
9976
- async function hasGithubWorkflows(repoPath) {
9977
- return fileExists(path9.join(repoPath, ".github", "workflows"));
9978
- }
9979
- async function hasCodeowners(repoPath) {
9980
- const root = await fileExists(path9.join(repoPath, "CODEOWNERS"));
9981
- const github = await fileExists(path9.join(repoPath, ".github", "CODEOWNERS"));
9982
- return root || github;
9983
- }
9984
- async function hasLicense(repoPath) {
9985
- const files = await safeReadDir(repoPath);
9986
- return files.some((file) => file.toLowerCase().startsWith("license"));
9987
- }
9988
- async function hasPullRequestTemplate(repoPath) {
9989
- const direct = await fileExists(path9.join(repoPath, ".github", "PULL_REQUEST_TEMPLATE.md"));
9990
- if (direct) return true;
9991
- const dir = path9.join(repoPath, ".github", "PULL_REQUEST_TEMPLATE");
9992
- try {
9993
- const entries = await fs7.readdir(dir);
9994
- return entries.some((entry) => entry.toLowerCase().endsWith(".md"));
9995
- } catch {
9996
- return false;
9997
- }
9998
- }
9999
- async function hasPrecommitConfig(repoPath) {
10000
- const precommit = await fileExists(path9.join(repoPath, ".pre-commit-config.yaml"));
10001
- if (precommit) return true;
10002
- return fileExists(path9.join(repoPath, ".husky"));
10003
- }
10004
- async function hasArchitectureDoc(repoPath) {
10005
- const files = await safeReadDir(repoPath);
10006
- if (files.some((file) => file.toLowerCase() === "architecture.md")) return true;
10007
- return fileExists(path9.join(repoPath, "docs", "architecture.md"));
10008
- }
10009
- async function hasCustomInstructions(repoPath) {
10010
- const found = [];
10011
- const candidates = [
10012
- ".github/copilot-instructions.md",
10013
- "CLAUDE.md",
10014
- ".claude/CLAUDE.md",
10015
- "AGENTS.md",
10016
- ".github/AGENTS.md",
10017
- ".cursorrules",
10018
- ".cursorignore",
10019
- ".windsurfrules",
10020
- ".github/instructions.md",
10021
- "copilot-instructions.md"
10022
- ];
10023
- for (const candidate of candidates) {
10024
- if (await fileExists(path9.join(repoPath, candidate))) {
10025
- found.push(candidate);
10590
+
10591
+ // packages/core/src/services/readiness/index.ts
10592
+ async function runReadinessReport(options) {
10593
+ const repoPath = options.repoPath;
10594
+ const analysis = await analyzeRepo(repoPath);
10595
+ const rootFiles = await safeReadDir(repoPath);
10596
+ const rootPackageJson = await readJson(path12.join(repoPath, "package.json"));
10597
+ const apps = analysis.apps?.length ? analysis.apps : [];
10598
+ const vscodeLocations = await parseVscodeLocations(repoPath, rootFiles);
10599
+ const context = {
10600
+ repoPath,
10601
+ analysis,
10602
+ apps,
10603
+ rootFiles,
10604
+ rootPackageJson,
10605
+ vscodeLocations
10606
+ };
10607
+ let policySources = options.policies;
10608
+ let isConfigSourced = false;
10609
+ if (!policySources?.length) {
10610
+ const agentrcConfig = await loadAgentrcConfig(repoPath);
10611
+ if (agentrcConfig?.policies?.length) {
10612
+ policySources = agentrcConfig.policies;
10613
+ isConfigSourced = true;
10026
10614
  }
10027
10615
  }
10028
- return found;
10029
- }
10030
- async function hasFileBasedInstructions(repoPath) {
10031
- const instructionsDir = path9.join(repoPath, ".github", "instructions");
10032
- try {
10033
- const entries = await fs7.readdir(instructionsDir);
10034
- return entries.filter((e) => e.endsWith(".instructions.md")).map((e) => `.github/instructions/${e}`);
10035
- } catch {
10036
- return [];
10037
- }
10038
- }
10039
- function contentSimilarity(a, b) {
10040
- const normalize = (s) => new Set(
10041
- s.toLowerCase().split("\n").map((l) => l.trim().replace(/\s+/gu, " ")).filter((l) => l.length > 0)
10042
- );
10043
- const setA = normalize(a);
10044
- const setB = normalize(b);
10045
- if (setA.size === 0 && setB.size === 0) return 1;
10046
- let intersection = 0;
10047
- for (const line of setA) {
10048
- if (setB.has(line)) intersection++;
10049
- }
10050
- const union = (/* @__PURE__ */ new Set([...setA, ...setB])).size;
10051
- return union === 0 ? 1 : intersection / union;
10052
- }
10053
- async function checkInstructionConsistency(repoPath, foundFiles) {
10054
- if (foundFiles.length <= 1) {
10055
- return { unified: true, files: foundFiles };
10056
- }
10057
- const realPathMap = /* @__PURE__ */ new Map();
10058
- for (const file of foundFiles) {
10059
- const fullPath = path9.join(repoPath, file);
10060
- try {
10061
- const real = await fs7.realpath(fullPath);
10062
- const group = realPathMap.get(real) ?? [];
10063
- group.push(file);
10064
- realPathMap.set(real, group);
10065
- } catch {
10066
- realPathMap.set(fullPath, [file]);
10616
+ const baseCriteria = buildCriteria();
10617
+ const baseExtras = buildExtras();
10618
+ let resolvedCriteria;
10619
+ let resolvedExtras;
10620
+ let passRateThreshold = 0.8;
10621
+ let policyInfo;
10622
+ if (policySources?.length) {
10623
+ const policyConfigs = [];
10624
+ let hasNativePlugin = false;
10625
+ for (const source of policySources) {
10626
+ const loaded = await loadPolicy(source, { jsonOnly: isConfigSourced });
10627
+ if (isNativePlugin(loaded)) {
10628
+ hasNativePlugin = true;
10629
+ continue;
10630
+ }
10631
+ policyConfigs.push(loaded);
10067
10632
  }
10068
- }
10069
- const groups = [...realPathMap.values()];
10070
- if (groups.length <= 1) {
10071
- return { unified: true, files: foundFiles };
10072
- }
10073
- const contents = [];
10074
- for (const group of groups) {
10075
- try {
10076
- contents.push(await fs7.readFile(path9.join(repoPath, group[0]), "utf8"));
10077
- } catch {
10078
- contents.push("");
10633
+ if (policyConfigs.length > 0) {
10634
+ const resolved = resolveChain(baseCriteria, baseExtras, policyConfigs);
10635
+ resolvedCriteria = resolved.criteria;
10636
+ resolvedExtras = resolved.extras;
10637
+ passRateThreshold = resolved.thresholds.passRate;
10638
+ policyInfo = { chain: resolved.chain, criteriaCount: resolved.criteria.length };
10639
+ } else {
10640
+ resolvedCriteria = baseCriteria;
10641
+ resolvedExtras = baseExtras;
10079
10642
  }
10643
+ if (hasNativePlugin && !options.shadow) {
10644
+ options = { ...options, shadow: true };
10645
+ }
10646
+ } else {
10647
+ resolvedCriteria = baseCriteria;
10648
+ resolvedExtras = baseExtras;
10080
10649
  }
10081
- let minSimilarity = 1;
10082
- for (let i = 0; i < contents.length; i++) {
10083
- for (let j = i + 1; j < contents.length; j++) {
10084
- minSimilarity = Math.min(minSimilarity, contentSimilarity(contents[i], contents[j]));
10650
+ const criteriaResults = [];
10651
+ for (const criterion of resolvedCriteria) {
10652
+ if (criterion.scope === "repo") {
10653
+ const result = await criterion.check(context);
10654
+ criteriaResults.push({
10655
+ id: criterion.id,
10656
+ title: criterion.title,
10657
+ pillar: criterion.pillar,
10658
+ level: criterion.level,
10659
+ scope: criterion.scope,
10660
+ impact: criterion.impact,
10661
+ effort: criterion.effort,
10662
+ status: result.status,
10663
+ reason: result.reason,
10664
+ evidence: result.evidence
10665
+ });
10666
+ continue;
10667
+ }
10668
+ if (criterion.scope === "area") {
10669
+ if (!options.perArea) continue;
10670
+ const areas2 = analysis.areas ?? [];
10671
+ if (areas2.length === 0) continue;
10672
+ criteriaResults.push({
10673
+ id: criterion.id,
10674
+ title: criterion.title,
10675
+ pillar: criterion.pillar,
10676
+ level: criterion.level,
10677
+ scope: criterion.scope,
10678
+ impact: criterion.impact,
10679
+ effort: criterion.effort,
10680
+ status: "skip",
10681
+ reason: "Run with --per-area for area breakdown."
10682
+ });
10683
+ continue;
10085
10684
  }
10086
- }
10087
- return {
10088
- unified: minSimilarity >= 0.9,
10089
- files: foundFiles,
10090
- similarity: Math.round(minSimilarity * 100) / 100
10091
- };
10092
- }
10093
- async function hasMcpConfig(repoPath) {
10094
- const found = [];
10095
- if (await fileExists(path9.join(repoPath, ".vscode", "mcp.json"))) {
10096
- found.push(".vscode/mcp.json");
10097
- }
10098
- if (await fileExists(path9.join(repoPath, "mcp.json"))) {
10099
- found.push("mcp.json");
10100
- }
10101
- const settings = await readJson(path9.join(repoPath, ".vscode", "settings.json"));
10102
- if (settings && (settings["mcp"] || settings["github.copilot.chat.mcp.enabled"])) {
10103
- found.push(".vscode/settings.json (mcp section)");
10104
- }
10105
- if (await fileExists(path9.join(repoPath, ".claude", "mcp.json"))) {
10106
- found.push(".claude/mcp.json");
10107
- }
10108
- return found;
10109
- }
10110
- async function hasCustomAgents(repoPath) {
10111
- const found = [];
10112
- const agentDirs = [".github/agents", ".copilot/agents", ".github/copilot/agents"];
10113
- for (const dir of agentDirs) {
10114
- if (await fileExists(path9.join(repoPath, dir))) {
10115
- found.push(dir);
10685
+ const appResults = await Promise.all(
10686
+ apps.map(async (app) => ({
10687
+ app,
10688
+ result: await criterion.check(context, app)
10689
+ }))
10690
+ );
10691
+ if (!appResults.length) {
10692
+ criteriaResults.push({
10693
+ id: criterion.id,
10694
+ title: criterion.title,
10695
+ pillar: criterion.pillar,
10696
+ level: criterion.level,
10697
+ scope: criterion.scope,
10698
+ impact: criterion.impact,
10699
+ effort: criterion.effort,
10700
+ status: "skip",
10701
+ reason: "No application packages detected."
10702
+ });
10703
+ continue;
10116
10704
  }
10705
+ const passed = appResults.filter((entry) => entry.result.status === "pass").length;
10706
+ const total = appResults.length;
10707
+ const passRate = total ? passed / total : 0;
10708
+ const status = passRate >= passRateThreshold ? "pass" : "fail";
10709
+ const failures = appResults.filter((entry) => entry.result.status !== "pass").map((entry) => entry.app.name);
10710
+ criteriaResults.push({
10711
+ id: criterion.id,
10712
+ title: criterion.title,
10713
+ pillar: criterion.pillar,
10714
+ level: criterion.level,
10715
+ scope: criterion.scope,
10716
+ impact: criterion.impact,
10717
+ effort: criterion.effort,
10718
+ status,
10719
+ reason: status === "pass" ? void 0 : `Only ${passed}/${total} apps pass this check.`,
10720
+ passRate,
10721
+ appSummary: { passed, total },
10722
+ appFailures: failures
10723
+ });
10117
10724
  }
10118
- const agentFiles = [".github/copilot-agents.yml", ".github/copilot-agents.yaml"];
10119
- for (const agentFile of agentFiles) {
10120
- if (await fileExists(path9.join(repoPath, agentFile))) {
10121
- found.push(agentFile);
10725
+ let areaReports;
10726
+ const areas = analysis.areas ?? [];
10727
+ if (options.perArea && areas.length > 0) {
10728
+ const areaCriteria = resolvedCriteria.filter((c) => c.scope === "area");
10729
+ areaReports = [];
10730
+ for (const area of areas) {
10731
+ if (!area.path) continue;
10732
+ const areaFiles = await safeReadDir(area.path);
10733
+ const areaContext = {
10734
+ ...context,
10735
+ areaPath: area.path,
10736
+ areaFiles
10737
+ };
10738
+ const areaResults = [];
10739
+ for (const criterion of areaCriteria) {
10740
+ const result = await criterion.check(areaContext, void 0, area);
10741
+ areaResults.push({
10742
+ id: criterion.id,
10743
+ title: criterion.title,
10744
+ pillar: criterion.pillar,
10745
+ level: criterion.level,
10746
+ scope: criterion.scope,
10747
+ impact: criterion.impact,
10748
+ effort: criterion.effort,
10749
+ status: result.status,
10750
+ reason: result.reason,
10751
+ evidence: result.evidence
10752
+ });
10753
+ }
10754
+ const areaPillars = summarizePillars(areaResults);
10755
+ areaReports.push({ area, criteria: areaResults, pillars: areaPillars });
10122
10756
  }
10123
- }
10124
- return found;
10125
- }
10126
- async function hasCopilotSkills(repoPath) {
10127
- const found = [];
10128
- const skillDirs = [
10129
- ".copilot/skills",
10130
- ".github/skills",
10131
- ".claude/skills",
10132
- ".github/copilot/skills"
10133
- ];
10134
- for (const dir of skillDirs) {
10135
- if (await fileExists(path9.join(repoPath, dir))) {
10136
- found.push(dir);
10757
+ for (const criterion of criteriaResults) {
10758
+ if (criterion.scope !== "area") continue;
10759
+ const perAreaResults = areaReports.map((ar) => ar.criteria.find((c) => c.id === criterion.id)).filter(Boolean);
10760
+ if (!perAreaResults.length) continue;
10761
+ const passed = perAreaResults.filter((r) => r.status === "pass").length;
10762
+ const total = perAreaResults.length;
10763
+ const passRate = total ? passed / total : 0;
10764
+ criterion.status = passRate >= passRateThreshold ? "pass" : "fail";
10765
+ criterion.reason = criterion.status === "pass" ? void 0 : `Only ${passed}/${total} areas pass this check.`;
10766
+ criterion.passRate = passRate;
10767
+ criterion.areaSummary = { passed, total };
10768
+ criterion.areaFailures = areaReports.filter((ar) => ar.criteria.find((c) => c.id === criterion.id)?.status !== "pass").map((ar) => ar.area.name);
10137
10769
  }
10138
10770
  }
10139
- return found;
10140
- }
10141
- async function readAllDependencies(context) {
10142
- const dependencies = [];
10143
- const apps = context.apps.length ? context.apps : [];
10144
- for (const app of apps) {
10145
- if (!app.packageJsonPath) continue;
10146
- const pkg = await readJson(app.packageJsonPath);
10147
- const deps = pkg?.dependencies ?? {};
10148
- const devDeps = pkg?.devDependencies ?? {};
10149
- dependencies.push(
10150
- ...Object.keys({
10151
- ...deps,
10152
- ...devDeps
10153
- })
10154
- );
10155
- }
10156
- if (!apps.length && context.rootPackageJson) {
10157
- const rootDeps = context.rootPackageJson.dependencies ?? {};
10158
- const rootDevDeps = context.rootPackageJson.devDependencies ?? {};
10159
- dependencies.push(
10160
- ...Object.keys({
10161
- ...rootDeps,
10162
- ...rootDevDeps
10163
- })
10164
- );
10771
+ const pillars = summarizePillars(criteriaResults);
10772
+ const levels = summarizeLevels(criteriaResults, passRateThreshold);
10773
+ const achievedLevel = levels.filter((level) => level.achieved).reduce((acc, level) => Math.max(acc, level.level), 0);
10774
+ const extras = options.includeExtras === false ? [] : await runExtras(context, resolvedExtras);
10775
+ let engine;
10776
+ if (options.shadow) {
10777
+ const policyCtx = {
10778
+ repoPath,
10779
+ rootFiles,
10780
+ rootPackageJson,
10781
+ cache: /* @__PURE__ */ new Map(),
10782
+ analysis,
10783
+ apps
10784
+ };
10785
+ const engineChain = await loadPluginChain(policySources ?? [], { jsonOnly: isConfigSourced });
10786
+ const engineReport = await executePlugins(engineChain.plugins, policyCtx, engineChain.options);
10787
+ engine = {
10788
+ signals: engineReport.signals,
10789
+ recommendations: engineReport.recommendations,
10790
+ policyWarnings: engineReport.policyWarnings,
10791
+ score: engineReport.score,
10792
+ grade: engineReport.grade
10793
+ };
10165
10794
  }
10166
- return Array.from(new Set(dependencies));
10795
+ return {
10796
+ repoPath,
10797
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
10798
+ isMonorepo: analysis.isMonorepo ?? false,
10799
+ apps: apps.map((app) => ({ name: app.name, path: app.path })),
10800
+ pillars,
10801
+ levels,
10802
+ achievedLevel,
10803
+ criteria: criteriaResults,
10804
+ extras,
10805
+ areaReports,
10806
+ policies: policyInfo,
10807
+ engine
10808
+ };
10167
10809
  }
10168
10810
 
10169
10811
  // packages/core/src/services/batch.ts
@@ -10185,7 +10827,7 @@ async function processRepo(params) {
10185
10827
  } = params;
10186
10828
  try {
10187
10829
  progress?.update(`${label}: Cloning...`);
10188
- const cacheRoot = path10.join(process.cwd(), ".agentrc-cache");
10830
+ const cacheRoot = path13.join(process.cwd(), ".agentrc-cache");
10189
10831
  const repoPath = validateCachePath(cacheRoot, ...cacheParts);
10190
10832
  await ensureDir(repoPath);
10191
10833
  if (!await isGitRepo(repoPath)) {
@@ -10211,8 +10853,8 @@ async function processRepo(params) {
10211
10853
  if (!instructions.trim()) {
10212
10854
  throw new Error("Generated instructions were empty");
10213
10855
  }
10214
- const instructionsPath = path10.join(repoPath, ".github", "copilot-instructions.md");
10215
- await ensureDir(path10.dirname(instructionsPath));
10856
+ const instructionsPath = path13.join(repoPath, ".github", "copilot-instructions.md");
10857
+ await ensureDir(path13.dirname(instructionsPath));
10216
10858
  const { wrote, reason } = await safeWriteFile(instructionsPath, instructions, true);
10217
10859
  if (!wrote) {
10218
10860
  throw new Error(
@@ -10349,7 +10991,7 @@ async function processBatchReadinessRepo(options) {
10349
10991
  try {
10350
10992
  progress(`Cloning ${repo.fullName}...`);
10351
10993
  const authedUrl = buildAuthedUrl(repo.cloneUrl, token, "github");
10352
- await ensureDir(path10.dirname(repoDir));
10994
+ await ensureDir(path13.dirname(repoDir));
10353
10995
  await cloneRepo(authedUrl, repoDir, { shallow: true });
10354
10996
  await setRemoteUrl(repoDir, repo.cloneUrl).catch(() => {
10355
10997
  });
@@ -11399,7 +12041,7 @@ import { render as render2 } from "ink";
11399
12041
  // src/ui/BatchReadinessTui.tsx
11400
12042
  import fs8 from "fs/promises";
11401
12043
  import os from "os";
11402
- import path11 from "path";
12044
+ import path14 from "path";
11403
12045
 
11404
12046
  // packages/core/src/services/visualReport.ts
11405
12047
  function generateVisualReport(options) {
@@ -12425,7 +13067,7 @@ function BatchReadinessTui({ token, outputPath, policies }) {
12425
13067
  setStatus("processing");
12426
13068
  const selectedRepos = Array.from(selectedRepoIndices).map((i) => repos[i]);
12427
13069
  const results2 = [];
12428
- const tmpDir = path11.join(os.tmpdir(), `agentrc-batch-readiness-${Date.now()}`);
13070
+ const tmpDir = path14.join(os.tmpdir(), `agentrc-batch-readiness-${Date.now()}`);
12429
13071
  try {
12430
13072
  await ensureDir(tmpDir);
12431
13073
  for (let i = 0; i < selectedRepos.length; i++) {
@@ -12462,7 +13104,7 @@ function BatchReadinessTui({ token, outputPath, policies }) {
12462
13104
  title: "Batch Readiness Report",
12463
13105
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
12464
13106
  });
12465
- const finalOutputPath = outputPath ?? path11.join(process.cwd(), "batch-readiness-report.html");
13107
+ const finalOutputPath = outputPath ?? path14.join(process.cwd(), "batch-readiness-report.html");
12466
13108
  const { wrote, reason } = await safeWriteFile(finalOutputPath, html, true);
12467
13109
  if (!wrote) throw new Error(reason === "symlink" ? "Path is a symlink" : "Write failed");
12468
13110
  setStatus("complete");
@@ -12644,7 +13286,7 @@ async function batchReadinessCommand(options) {
12644
13286
  }
12645
13287
 
12646
13288
  // src/commands/eval.ts
12647
- import path13 from "path";
13289
+ import path16 from "path";
12648
13290
 
12649
13291
  // packages/core/src/services/evalScaffold.ts
12650
13292
  var EVAL_SCAFFOLD_TIMEOUT_MS = 6e5;
@@ -12839,17 +13481,16 @@ function normalizeExpectation(value) {
12839
13481
 
12840
13482
  // packages/core/src/services/evaluator.ts
12841
13483
  import fs9 from "fs/promises";
12842
- import path12 from "path";
13484
+ import path15 from "path";
12843
13485
  var DEFAULT_SYSTEM_MESSAGE = "Research using read-only tools and make a plan for the given task, including concrete implementation steps and verification steps.";
12844
13486
  async function runEval(options) {
12845
13487
  const config = await loadConfig(options.configPath);
12846
13488
  const instructionFile = config.instructionFile ?? ".github/copilot-instructions.md";
12847
- const instructionPath = path12.resolve(options.repoPath, instructionFile);
12848
- const instructionText = await readOptionalFile(instructionPath);
13489
+ const instructionText = await readRepoFile(options.repoPath, instructionFile);
12849
13490
  const baseSystemMessage = config.systemMessage ?? DEFAULT_SYSTEM_MESSAGE;
12850
13491
  const progress = options.onProgress ?? (() => {
12851
13492
  });
12852
- const defaultOutputPath = path12.resolve(
13493
+ const defaultOutputPath = path15.resolve(
12853
13494
  options.repoPath,
12854
13495
  ".agentrc",
12855
13496
  "evals",
@@ -12867,17 +13508,10 @@ async function runEval(options) {
12867
13508
  const id = testCase.id ?? `case-${index + 1}`;
12868
13509
  const prompt = buildPrompt(options.repoPath, testCase.prompt);
12869
13510
  const caseStartedAt = Date.now();
12870
- let caseWorkingDir;
12871
- if (testCase.workingDirectory) {
12872
- const resolved = path12.resolve(options.repoPath, testCase.workingDirectory);
12873
- const root = path12.resolve(options.repoPath);
12874
- if (resolved !== root && !resolved.startsWith(root + path12.sep)) {
12875
- throw new Error(
12876
- `Invalid workingDirectory "${testCase.workingDirectory}": escapes repo boundary`
12877
- );
12878
- }
12879
- caseWorkingDir = resolved;
12880
- }
13511
+ const caseWorkingDir = await resolveRepoDirectory(
13512
+ options.repoPath,
13513
+ testCase.workingDirectory
13514
+ );
12881
13515
  progress(`Running eval ${index + 1}/${total}: ${id} (without instructions)...`);
12882
13516
  const withoutResult = await askOnce(client, {
12883
13517
  prompt,
@@ -12943,10 +13577,10 @@ async function runEval(options) {
12943
13577
  };
12944
13578
  let viewerPath;
12945
13579
  if (outputPath) {
12946
- await fs9.mkdir(path12.dirname(outputPath), { recursive: true });
12947
- await safeWriteFile(outputPath, JSON.stringify(output, null, 2), true);
13580
+ await fs9.mkdir(path15.dirname(outputPath), { recursive: true });
13581
+ await writeEvalArtifact(outputPath, JSON.stringify(output, null, 2));
12948
13582
  viewerPath = buildViewerPath(outputPath);
12949
- await safeWriteFile(viewerPath, buildTrajectoryViewerHtml(output), true);
13583
+ await writeEvalArtifact(viewerPath, buildTrajectoryViewerHtml(output));
12950
13584
  }
12951
13585
  const summary = formatSummary(results, runFinishedAt - runStartedAt);
12952
13586
  return { summary, results, viewerPath };
@@ -12992,7 +13626,8 @@ async function judge(client, options) {
12992
13626
  infiniteSessions: { enabled: false },
12993
13627
  systemMessage: {
12994
13628
  content: "You are a strict evaluator. Return JSON with keys: verdict (pass|fail|unknown), score (0-100), rationale. Do not include any other text."
12995
- }
13629
+ },
13630
+ availableTools: []
12996
13631
  });
12997
13632
  let content = "";
12998
13633
  const telemetry = createTelemetry("judge");
@@ -13036,10 +13671,16 @@ function parseJudge(content) {
13036
13671
  const match = content.match(/\{[\s\S]*\}/);
13037
13672
  if (!match) throw new Error("No JSON detected");
13038
13673
  const parsed = JSON.parse(match[0]);
13039
- if (!parsed.verdict) throw new Error("Missing verdict");
13674
+ if (!["pass", "fail", "unknown"].includes(parsed.verdict)) {
13675
+ throw new Error("Invalid verdict");
13676
+ }
13677
+ const score = Number(parsed.score);
13678
+ if (!Number.isFinite(score) || score < 0 || score > 100) {
13679
+ throw new Error("Invalid score");
13680
+ }
13040
13681
  return {
13041
13682
  verdict: parsed.verdict,
13042
- score: Number(parsed.score ?? 0),
13683
+ score,
13043
13684
  rationale: String(parsed.rationale ?? "")
13044
13685
  };
13045
13686
  } catch {
@@ -13058,12 +13699,44 @@ async function loadConfig(configPath) {
13058
13699
  }
13059
13700
  return parsed;
13060
13701
  }
13061
- async function readOptionalFile(filePath) {
13702
+ async function readRepoFile(repoPath, relativePath) {
13703
+ const repoRoot = path15.resolve(repoPath);
13704
+ const filePath = path15.resolve(repoRoot, relativePath);
13705
+ if (!isWithinRoot(repoRoot, filePath)) {
13706
+ throw new Error(`Invalid instructionFile "${relativePath}": escapes repo boundary`);
13707
+ }
13708
+ let realFilePath;
13062
13709
  try {
13063
- return await fs9.readFile(filePath, "utf8");
13064
- } catch {
13065
- return "";
13710
+ realFilePath = await fs9.realpath(filePath);
13711
+ } catch (error) {
13712
+ if (error.code === "ENOENT") {
13713
+ throw new Error(`Instruction file not found: ${relativePath}`);
13714
+ }
13715
+ throw error;
13716
+ }
13717
+ const realRepoRoot = await fs9.realpath(repoRoot);
13718
+ if (!isWithinRoot(realRepoRoot, realFilePath)) {
13719
+ throw new Error(`Invalid instructionFile "${relativePath}": resolves outside repo boundary`);
13720
+ }
13721
+ return fs9.readFile(realFilePath, "utf8");
13722
+ }
13723
+ async function resolveRepoDirectory(repoPath, relativePath) {
13724
+ const repoRoot = path15.resolve(repoPath);
13725
+ const directoryPath = path15.resolve(repoRoot, relativePath ?? ".");
13726
+ if (!isWithinRoot(repoRoot, directoryPath)) {
13727
+ throw new Error(`Invalid workingDirectory "${relativePath}": escapes repo boundary`);
13066
13728
  }
13729
+ const [realRepoRoot, realDirectoryPath] = await Promise.all([
13730
+ fs9.realpath(repoRoot),
13731
+ fs9.realpath(directoryPath)
13732
+ ]);
13733
+ if (!isWithinRoot(realRepoRoot, realDirectoryPath)) {
13734
+ throw new Error(`Invalid workingDirectory "${relativePath}": resolves outside repo boundary`);
13735
+ }
13736
+ return realDirectoryPath;
13737
+ }
13738
+ function isWithinRoot(root, candidate) {
13739
+ return candidate === root || candidate.startsWith(root + path15.sep);
13067
13740
  }
13068
13741
  function buildPrompt(repoPath, userPrompt) {
13069
13742
  return [
@@ -13256,9 +13929,22 @@ function formatTokenUsage(usage) {
13256
13929
  return `prompt ${prompt}, completion ${completion}, total ${total}`;
13257
13930
  }
13258
13931
  function resolveOutputPath(repoPath, override, configValue) {
13259
- const chosen = override ?? configValue;
13260
- if (!chosen) return void 0;
13261
- return path12.isAbsolute(chosen) ? chosen : path12.resolve(repoPath, chosen);
13932
+ if (override) {
13933
+ return path15.isAbsolute(override) ? override : path15.resolve(repoPath, override);
13934
+ }
13935
+ if (!configValue) return void 0;
13936
+ const repoRoot = path15.resolve(repoPath);
13937
+ const outputPath = path15.resolve(repoRoot, configValue);
13938
+ if (!isWithinRoot(repoRoot, outputPath)) {
13939
+ throw new Error(`Invalid outputPath "${configValue}": escapes repo boundary`);
13940
+ }
13941
+ return outputPath;
13942
+ }
13943
+ async function writeEvalArtifact(filePath, content) {
13944
+ const result = await safeWriteFile(filePath, content, true);
13945
+ if (!result.wrote) {
13946
+ throw new Error(`Failed to write ${filePath}: ${result.reason ?? "unknown reason"}`);
13947
+ }
13262
13948
  }
13263
13949
  function buildViewerPath(outputPath) {
13264
13950
  if (outputPath.endsWith(".json")) {
@@ -13613,7 +14299,7 @@ function sanitizeValue(value, depth) {
13613
14299
 
13614
14300
  // src/commands/eval.ts
13615
14301
  async function evalCommand(configPathArg, options) {
13616
- const repoPath = path13.resolve(options.repo ?? process.cwd());
14302
+ const repoPath = path16.resolve(options.repo ?? process.cwd());
13617
14303
  if (options.listModels) {
13618
14304
  try {
13619
14305
  const models = await listCopilotModels();
@@ -13649,7 +14335,7 @@ async function evalCommand(configPathArg, options) {
13649
14335
  return;
13650
14336
  }
13651
14337
  if (options.init) {
13652
- const outputPath = path13.join(repoPath, "agentrc.eval.json");
14338
+ const outputPath = path16.join(repoPath, "agentrc.eval.json");
13653
14339
  const desiredCount = Math.max(1, Number.parseInt(options.count ?? "5", 10) || 5);
13654
14340
  try {
13655
14341
  const progress = createProgressReporter(!shouldLog(options));
@@ -13691,7 +14377,7 @@ async function evalCommand(configPathArg, options) {
13691
14377
  }
13692
14378
  return;
13693
14379
  }
13694
- const configPath = path13.resolve(configPathArg ?? path13.join(repoPath, "agentrc.eval.json"));
14380
+ const configPath = path16.resolve(configPathArg ?? path16.join(repoPath, "agentrc.eval.json"));
13695
14381
  try {
13696
14382
  const progress = createProgressReporter(!shouldLog(options));
13697
14383
  const { summary, results, viewerPath } = await runEval({
@@ -13738,12 +14424,12 @@ async function evalCommand(configPathArg, options) {
13738
14424
  }
13739
14425
 
13740
14426
  // src/commands/generate.ts
13741
- import path16 from "path";
14427
+ import path19 from "path";
13742
14428
 
13743
14429
  // packages/core/src/services/generator.ts
13744
- import path14 from "path";
14430
+ import path17 from "path";
13745
14431
  async function writeOrPreview(filePath, content, opts) {
13746
- const relPath = path14.relative(process.cwd(), filePath);
14432
+ const relPath = path17.relative(process.cwd(), filePath);
13747
14433
  if (opts.dryRun) {
13748
14434
  const wouldWrite = await canSafeWrite(filePath, opts.force);
13749
14435
  return {
@@ -13752,7 +14438,7 @@ async function writeOrPreview(filePath, content, opts) {
13752
14438
  bytes: Buffer.byteLength(content, "utf8")
13753
14439
  };
13754
14440
  }
13755
- await ensureDir(path14.dirname(filePath));
14441
+ await ensureDir(path17.dirname(filePath));
13756
14442
  const { wrote } = await safeWriteFile(filePath, content, opts.force);
13757
14443
  return { path: relPath, action: wrote ? "wrote" : "skipped" };
13758
14444
  }
@@ -13761,7 +14447,7 @@ async function generateConfigs(options) {
13761
14447
  const files = [];
13762
14448
  if (selections.includes("mcp")) {
13763
14449
  files.push(
13764
- await writeOrPreview(path14.join(repoPath, ".vscode", "mcp.json"), renderMcp(), {
14450
+ await writeOrPreview(path17.join(repoPath, ".vscode", "mcp.json"), renderMcp(), {
13765
14451
  dryRun,
13766
14452
  force
13767
14453
  })
@@ -13770,8 +14456,8 @@ async function generateConfigs(options) {
13770
14456
  if (selections.includes("vscode")) {
13771
14457
  files.push(
13772
14458
  await writeOrPreview(
13773
- path14.join(repoPath, ".vscode", "settings.json"),
13774
- renderVscodeSettings(analysis),
14459
+ path17.join(repoPath, ".vscode", "settings.json"),
14460
+ renderVscodeSettings(analysis, options.instructionFile),
13775
14461
  { dryRun, force }
13776
14462
  )
13777
14463
  );
@@ -13806,13 +14492,11 @@ function renderMcp() {
13806
14492
  2
13807
14493
  );
13808
14494
  }
13809
- function renderVscodeSettings(analysis) {
14495
+ function renderVscodeSettings(analysis, instructionFile = ".github/copilot-instructions.md") {
13810
14496
  const reviewFocus = analysis.frameworks.length ? `Focus on ${analysis.frameworks.join(", ")} best practices and repo conventions.` : "Focus on repo conventions and maintainability.";
13811
14497
  return JSON.stringify(
13812
14498
  {
13813
- "github.copilot.chat.codeGeneration.instructions": [
13814
- { file: ".github/copilot-instructions.md" }
13815
- ],
14499
+ "github.copilot.chat.codeGeneration.instructions": [{ file: instructionFile }],
13816
14500
  "github.copilot.chat.reviewSelection.instructions": [{ text: reviewFocus }],
13817
14501
  "chat.promptFiles": true,
13818
14502
  "chat.mcp.enabled": true
@@ -13823,16 +14507,17 @@ function renderVscodeSettings(analysis) {
13823
14507
  }
13824
14508
 
13825
14509
  // src/commands/instructions.ts
13826
- import path15 from "path";
14510
+ import fs10 from "fs/promises";
14511
+ import path18 from "path";
13827
14512
  function skipReason(action) {
13828
14513
  if (action === "symlink") return "symlink";
13829
14514
  if (action === "empty") return "empty content";
13830
14515
  return "exists, use --force";
13831
14516
  }
13832
14517
  async function instructionsCommand(options) {
13833
- const repoPath = path15.resolve(options.repo ?? process.cwd());
13834
- const outputPath = path15.resolve(
13835
- options.output ?? path15.join(repoPath, ".github", "copilot-instructions.md")
14518
+ const repoPath = path18.resolve(options.repo ?? process.cwd());
14519
+ const outputPath = path18.resolve(
14520
+ options.output ?? path18.join(repoPath, ".github", "copilot-instructions.md")
13836
14521
  );
13837
14522
  const progress = createProgressReporter(!shouldLog(options));
13838
14523
  const wantAreas = options.areas || options.areasOnly || options.area;
@@ -13856,6 +14541,7 @@ async function instructionsCommand(options) {
13856
14541
  }
13857
14542
  try {
13858
14543
  const dryRunFiles = [];
14544
+ let rootContent;
13859
14545
  if (!options.areasOnly && !options.area) {
13860
14546
  if (strategy === "nested") {
13861
14547
  try {
@@ -13868,6 +14554,7 @@ async function instructionsCommand(options) {
13868
14554
  claudeMd
13869
14555
  });
13870
14556
  if (options.dryRun) {
14557
+ rootContent = nestedResult.hub.content;
13871
14558
  const dryFiles = [
13872
14559
  { path: nestedResult.hub.relativePath, content: nestedResult.hub.content },
13873
14560
  ...nestedResult.details.map((d) => ({ path: d.relativePath, content: d.content })),
@@ -13879,7 +14566,7 @@ async function instructionsCommand(options) {
13879
14566
  ] : []
13880
14567
  ];
13881
14568
  for (const file of dryFiles) {
13882
- const relPath = path15.relative(process.cwd(), path15.join(repoPath, file.path));
14569
+ const relPath = path18.relative(process.cwd(), path18.join(repoPath, file.path));
13883
14570
  if (shouldLog(options)) {
13884
14571
  progress.update(
13885
14572
  `[dry-run] Would write ${relPath} (${Buffer.byteLength(file.content, "utf8")} bytes)`
@@ -13899,8 +14586,14 @@ async function instructionsCommand(options) {
13899
14586
  }
13900
14587
  } else {
13901
14588
  const actions = await writeNestedInstructions(repoPath, nestedResult, options.force);
14589
+ const hubAction = actions[0];
14590
+ if (hubAction?.action === "wrote") {
14591
+ rootContent = nestedResult.hub.content;
14592
+ } else if (hubAction?.action === "skipped") {
14593
+ rootContent = await fs10.readFile(hubAction.path, "utf8").catch(() => void 0);
14594
+ }
13902
14595
  for (const action of actions) {
13903
- const relPath = path15.relative(process.cwd(), action.path);
14596
+ const relPath = path18.relative(process.cwd(), action.path);
13904
14597
  if (action.action === "wrote") {
13905
14598
  if (shouldLog(options)) progress.succeed(`Wrote ${relPath}`);
13906
14599
  } else if (shouldLog(options)) {
@@ -13943,8 +14636,8 @@ async function instructionsCommand(options) {
13943
14636
  }
13944
14637
  if (content) {
13945
14638
  if (options.dryRun) {
13946
- const relPath = path15.relative(repoPath, outputPath);
13947
- const displayPath = path15.relative(process.cwd(), outputPath);
14639
+ const relPath = path18.relative(repoPath, outputPath);
14640
+ const displayPath = path18.relative(process.cwd(), outputPath);
13948
14641
  const byteCount = Buffer.byteLength(content, "utf8");
13949
14642
  if (shouldLog(options)) {
13950
14643
  progress.update(`[dry-run] Would write ${displayPath} (${byteCount} bytes)`);
@@ -13953,14 +14646,14 @@ async function instructionsCommand(options) {
13953
14646
  dryRunFiles.push({ path: relPath, bytes: byteCount });
13954
14647
  }
13955
14648
  } else {
13956
- await ensureDir(path15.dirname(outputPath));
14649
+ await ensureDir(path18.dirname(outputPath));
13957
14650
  const { wrote, reason } = await safeWriteFile(
13958
14651
  outputPath,
13959
14652
  content,
13960
14653
  Boolean(options.force)
13961
14654
  );
13962
14655
  if (!wrote) {
13963
- const relPath = path15.relative(process.cwd(), outputPath);
14656
+ const relPath = path18.relative(process.cwd(), outputPath);
13964
14657
  const why = reason === "symlink" ? "path is a symlink" : "file exists (use --force)";
13965
14658
  if (options.json) {
13966
14659
  const result = {
@@ -13982,7 +14675,7 @@ async function instructionsCommand(options) {
13982
14675
  };
13983
14676
  outputResult(result, true);
13984
14677
  } else if (shouldLog(options)) {
13985
- progress.succeed(`Updated ${path15.relative(process.cwd(), outputPath)}`);
14678
+ progress.succeed(`Updated ${path18.relative(process.cwd(), outputPath)}`);
13986
14679
  }
13987
14680
  }
13988
14681
  }
@@ -14035,7 +14728,8 @@ async function instructionsCommand(options) {
14035
14728
  model: options.model,
14036
14729
  onProgress: shouldLog(options) ? (msg) => progress.update(msg) : void 0,
14037
14730
  detailDir,
14038
- claudeMd
14731
+ claudeMd,
14732
+ rootContent
14039
14733
  });
14040
14734
  if (options.dryRun) {
14041
14735
  const dryFiles = [
@@ -14049,7 +14743,7 @@ async function instructionsCommand(options) {
14049
14743
  ] : []
14050
14744
  ];
14051
14745
  for (const file of dryFiles) {
14052
- const relPath = path15.relative(process.cwd(), path15.join(repoPath, file.path));
14746
+ const relPath = path18.relative(process.cwd(), path18.join(repoPath, file.path));
14053
14747
  if (shouldLog(options)) {
14054
14748
  progress.update(
14055
14749
  `[dry-run] Would write ${relPath} (${Buffer.byteLength(file.content, "utf8")} bytes)`
@@ -14067,7 +14761,7 @@ async function instructionsCommand(options) {
14067
14761
  } else {
14068
14762
  const actions = await writeNestedInstructions(repoPath, nestedResult, options.force);
14069
14763
  for (const action of actions) {
14070
- const relPath = path15.relative(process.cwd(), action.path);
14764
+ const relPath = path18.relative(process.cwd(), action.path);
14071
14765
  if (action.action === "wrote") {
14072
14766
  if (shouldLog(options)) progress.succeed(`Wrote ${relPath}`);
14073
14767
  } else if (shouldLog(options)) {
@@ -14099,7 +14793,7 @@ async function instructionsCommand(options) {
14099
14793
  }
14100
14794
  if (options.json) {
14101
14795
  dryRunFiles.push({
14102
- path: path15.relative(repoPath, areaInstructionPath(repoPath, area)),
14796
+ path: path18.relative(repoPath, areaInstructionPath(repoPath, area)),
14103
14797
  bytes: Buffer.byteLength(body, "utf8")
14104
14798
  });
14105
14799
  }
@@ -14120,7 +14814,7 @@ async function instructionsCommand(options) {
14120
14814
  continue;
14121
14815
  }
14122
14816
  if (shouldLog(options)) {
14123
- progress.succeed(`Wrote ${path15.relative(process.cwd(), result.filePath)}`);
14817
+ progress.succeed(`Wrote ${path18.relative(process.cwd(), result.filePath)}`);
14124
14818
  }
14125
14819
  }
14126
14820
  }
@@ -14155,7 +14849,7 @@ async function instructionsCommand(options) {
14155
14849
 
14156
14850
  // src/commands/generate.ts
14157
14851
  async function generateCommand(type, repoPathArg, options) {
14158
- const repoPath = path16.resolve(repoPathArg ?? process.cwd());
14852
+ const repoPath = path19.resolve(repoPathArg ?? process.cwd());
14159
14853
  if (type === "instructions" || type === "agents") {
14160
14854
  if (!options.quiet) {
14161
14855
  process.stderr.write(
@@ -14169,7 +14863,7 @@ async function generateCommand(type, repoPathArg, options) {
14169
14863
  `
14170
14864
  );
14171
14865
  }
14172
- const output = type === "agents" ? path16.join(repoPath, "AGENTS.md") : void 0;
14866
+ const output = type === "agents" ? path19.join(repoPath, "AGENTS.md") : void 0;
14173
14867
  await instructionsCommand({
14174
14868
  repo: repoPath,
14175
14869
  output,
@@ -14235,17 +14929,19 @@ async function generateCommand(type, repoPathArg, options) {
14235
14929
  }
14236
14930
 
14237
14931
  // src/commands/init.ts
14238
- import path18 from "path";
14932
+ import { execFile as execFile3 } from "child_process";
14933
+ import path21 from "path";
14934
+ import { promisify as promisify3 } from "util";
14239
14935
 
14240
14936
  // packages/core/src/services/configScaffold.ts
14241
- import path17 from "path";
14937
+ import path20 from "path";
14242
14938
  async function scaffoldAgentrcConfig(repoPath, areas, force = false) {
14243
- const configPath = path17.join(repoPath, "agentrc.config.json");
14939
+ const configPath = path20.join(repoPath, "agentrc.config.json");
14244
14940
  const workspaces = areas.length > 0 ? await detectWorkspaces(repoPath, areas) : [];
14245
14941
  const workspacePaths = workspaces.map((ws) => ws.path + "/");
14246
14942
  const standaloneAreas = areas.filter((a) => {
14247
14943
  if (!a.path) return true;
14248
- const rel = path17.relative(repoPath, a.path).replace(/\\/gu, "/");
14944
+ const rel = path20.relative(repoPath, a.path).replace(/\\/gu, "/");
14249
14945
  return !workspacePaths.some((prefix) => rel.startsWith(prefix));
14250
14946
  }).map((a) => ({
14251
14947
  name: a.name,
@@ -14261,9 +14957,9 @@ async function scaffoldAgentrcConfig(repoPath, areas, force = false) {
14261
14957
  }
14262
14958
 
14263
14959
  // src/commands/init.ts
14264
- import { checkbox, select } from "@inquirer/prompts";
14960
+ import { checkbox, confirm, select } from "@inquirer/prompts";
14265
14961
  async function initCommand(repoPathArg, options) {
14266
- let repoPath = path18.resolve(repoPathArg ?? process.cwd());
14962
+ let repoPath = path21.resolve(repoPathArg ?? process.cwd());
14267
14963
  const provider = options.provider ?? (options.github ? "github" : void 0);
14268
14964
  if (provider && provider !== "github" && provider !== "azure") {
14269
14965
  outputError("Invalid provider. Use github or azure.", Boolean(options.json));
@@ -14301,7 +14997,7 @@ async function initCommand(repoPathArg, options) {
14301
14997
  value: repo
14302
14998
  }))
14303
14999
  });
14304
- const cacheRoot = path18.join(process.cwd(), ".agentrc-cache");
15000
+ const cacheRoot = path21.join(process.cwd(), ".agentrc-cache");
14305
15001
  repoPath = validateCachePath(cacheRoot, selection.owner, selection.name);
14306
15002
  await ensureDir(repoPath);
14307
15003
  const hasGit = await isGitRepo(repoPath);
@@ -14354,7 +15050,7 @@ async function initCommand(repoPathArg, options) {
14354
15050
  value: repo
14355
15051
  }))
14356
15052
  });
14357
- const cacheRoot = path18.join(process.cwd(), ".agentrc-cache");
15053
+ const cacheRoot = path21.join(process.cwd(), ".agentrc-cache");
14358
15054
  repoPath = validateCachePath(
14359
15055
  cacheRoot,
14360
15056
  orgSelection.name,
@@ -14393,17 +15089,17 @@ async function initCommand(repoPathArg, options) {
14393
15089
  });
14394
15090
  const allFiles = [];
14395
15091
  if (selections.includes("instructions")) {
14396
- const outputPath = path18.join(repoPath, ".github", "copilot-instructions.md");
14397
- await ensureDir(path18.dirname(outputPath));
15092
+ const outputPath = path21.join(repoPath, ".github", "copilot-instructions.md");
15093
+ await ensureDir(path21.dirname(outputPath));
14398
15094
  try {
14399
15095
  const content = await generateCopilotInstructions({ repoPath, model: options.model });
14400
15096
  const { wrote } = await safeWriteFile(outputPath, content, Boolean(options.force));
14401
15097
  allFiles.push({
14402
- path: path18.relative(process.cwd(), outputPath),
15098
+ path: path21.relative(process.cwd(), outputPath),
14403
15099
  action: wrote ? "wrote" : "skipped"
14404
15100
  });
14405
15101
  if (shouldLog(options)) {
14406
- const rel = path18.relative(process.cwd(), outputPath);
15102
+ const rel = path21.relative(process.cwd(), outputPath);
14407
15103
  process.stderr.write((wrote ? `Wrote ${rel}` : `Skipped ${rel} (exists)`) + "\n");
14408
15104
  }
14409
15105
  } catch (error) {
@@ -14436,12 +15132,13 @@ async function initCommand(repoPathArg, options) {
14436
15132
  analysis.areas ?? [],
14437
15133
  Boolean(options.force)
14438
15134
  );
14439
- const rel = path18.relative(process.cwd(), result.configPath);
15135
+ const rel = path21.relative(process.cwd(), result.configPath);
14440
15136
  allFiles.push({ path: rel, action: result.wrote ? "wrote" : "skipped" });
14441
15137
  if (shouldLog(options)) {
14442
15138
  process.stderr.write((result.wrote ? `Wrote ${rel}` : `Skipped ${rel} (exists)`) + "\n");
14443
15139
  }
14444
15140
  }
15141
+ await offerApmInit(repoPath, options);
14445
15142
  if (options.json) {
14446
15143
  const { ok, status } = deriveFileStatus(allFiles);
14447
15144
  const result = {
@@ -14463,9 +15160,52 @@ async function initCommand(repoPathArg, options) {
14463
15160
  process.stderr.write(" agentrc eval --init Scaffold evaluation test cases\n");
14464
15161
  }
14465
15162
  }
15163
+ var execFileAsync3 = promisify3(execFile3);
15164
+ var APM_TIMEOUT_MS = 1e4;
15165
+ async function isApmInstalled() {
15166
+ try {
15167
+ await execFileAsync3("apm", ["--version"], { timeout: APM_TIMEOUT_MS });
15168
+ return true;
15169
+ } catch {
15170
+ return false;
15171
+ }
15172
+ }
15173
+ async function offerApmInit(repoPath, options) {
15174
+ if (options.json) return;
15175
+ const hasApmYml = await fileExists(path21.join(repoPath, "apm.yml"));
15176
+ if (hasApmYml) return;
15177
+ const apmAvailable = await isApmInstalled();
15178
+ if (apmAvailable) {
15179
+ const accepted = options.yes ? true : await confirm({
15180
+ message: "Set up APM to install and share agent packages across your team?",
15181
+ default: false
15182
+ });
15183
+ if (accepted) {
15184
+ try {
15185
+ await execFileAsync3("apm", ["init", "--yes"], { cwd: repoPath, timeout: APM_TIMEOUT_MS });
15186
+ if (shouldLog(options)) {
15187
+ process.stderr.write(
15188
+ "APM initialized \u2014 run `apm install <package>` to add shared agent packages.\n"
15189
+ );
15190
+ }
15191
+ } catch (error) {
15192
+ if (shouldLog(options)) {
15193
+ process.stderr.write(
15194
+ `Warning: APM init failed; continuing without APM: ${error instanceof Error ? error.message : String(error)}
15195
+ `
15196
+ );
15197
+ }
15198
+ }
15199
+ }
15200
+ } else if (shouldLog(options)) {
15201
+ process.stderr.write(
15202
+ "\nTip: use APM to install shared agent packages and distribute your instructions across repos.\n https://github.com/microsoft/apm\n"
15203
+ );
15204
+ }
15205
+ }
14466
15206
 
14467
15207
  // src/commands/pr.ts
14468
- import path19 from "path";
15208
+ import path22 from "path";
14469
15209
  var DEFAULT_PR_BRANCH = "agentrc/add-ai-config";
14470
15210
  async function prCommand(repo, options) {
14471
15211
  const provider = options.provider ?? "github";
@@ -14499,7 +15239,7 @@ async function prCommand(repo, options) {
14499
15239
  try {
14500
15240
  progress.update("Fetching repo info...");
14501
15241
  const repoInfo = await getRepo(token2, organization, project, name2);
14502
- const cacheRoot = path19.join(process.cwd(), ".agentrc-cache");
15242
+ const cacheRoot = path22.join(process.cwd(), ".agentrc-cache");
14503
15243
  const repoPath = validateCachePath(cacheRoot, organization, project, name2);
14504
15244
  await ensureDir(repoPath);
14505
15245
  if (!await isGitRepo(repoPath)) {
@@ -14513,8 +15253,8 @@ async function prCommand(repo, options) {
14513
15253
  await checkoutBranch(repoPath, branch);
14514
15254
  progress.update("Generating instructions...");
14515
15255
  const instructions = await generateCopilotInstructions({ repoPath, model: options.model });
14516
- const instructionsPath = path19.join(repoPath, ".github", "copilot-instructions.md");
14517
- await ensureDir(path19.dirname(instructionsPath));
15256
+ const instructionsPath = path22.join(repoPath, ".github", "copilot-instructions.md");
15257
+ await ensureDir(path22.dirname(instructionsPath));
14518
15258
  const { wrote, reason } = await safeWriteFile(instructionsPath, instructions, true);
14519
15259
  if (!wrote) {
14520
15260
  throw new Error(
@@ -14581,7 +15321,7 @@ async function prCommand(repo, options) {
14581
15321
  try {
14582
15322
  progress.update("Fetching repo info...");
14583
15323
  const repoInfo = await getRepo2(token, owner, name);
14584
- const cacheRoot = path19.join(process.cwd(), ".agentrc-cache");
15324
+ const cacheRoot = path22.join(process.cwd(), ".agentrc-cache");
14585
15325
  const repoPath = validateCachePath(cacheRoot, owner, name);
14586
15326
  await ensureDir(repoPath);
14587
15327
  if (!await isGitRepo(repoPath)) {
@@ -14593,8 +15333,8 @@ async function prCommand(repo, options) {
14593
15333
  await checkoutBranch(repoPath, branch);
14594
15334
  progress.update("Generating instructions...");
14595
15335
  const instructions = await generateCopilotInstructions({ repoPath, model: options.model });
14596
- const instructionsPath = path19.join(repoPath, ".github", "copilot-instructions.md");
14597
- await ensureDir(path19.dirname(instructionsPath));
15336
+ const instructionsPath = path22.join(repoPath, ".github", "copilot-instructions.md");
15337
+ await ensureDir(path22.dirname(instructionsPath));
14598
15338
  const { wrote, reason } = await safeWriteFile(instructionsPath, instructions, true);
14599
15339
  if (!wrote) {
14600
15340
  throw new Error(
@@ -14643,13 +15383,13 @@ async function prCommand(repo, options) {
14643
15383
  }
14644
15384
 
14645
15385
  // src/commands/readiness.ts
14646
- import path20 from "path";
15386
+ import path23 from "path";
14647
15387
  import chalk3 from "chalk";
14648
15388
  async function readinessCommand(repoPathArg, options) {
14649
- const repoPath = path20.resolve(repoPathArg ?? process.cwd());
14650
- const repoName = path20.basename(repoPath);
14651
- const resolvedOutputPath = options.output ? path20.resolve(options.output) : "";
14652
- const outputExt = options.output ? path20.extname(options.output).toLowerCase() : "";
15389
+ const repoPath = path23.resolve(repoPathArg ?? process.cwd());
15390
+ const repoName = path23.basename(repoPath);
15391
+ const resolvedOutputPath = options.output ? path23.resolve(options.output) : "";
15392
+ const outputExt = options.output ? path23.extname(options.output).toLowerCase() : "";
14653
15393
  let failLevelError;
14654
15394
  let report;
14655
15395
  try {
@@ -14711,7 +15451,7 @@ async function readinessCommand(repoPathArg, options) {
14711
15451
  title: `Readiness Report: ${repoName}`,
14712
15452
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
14713
15453
  });
14714
- const outputPath = options.output ? resolvedOutputPath : path20.join(repoPath, "readiness-report.html");
15454
+ const outputPath = options.output ? resolvedOutputPath : path23.join(repoPath, "readiness-report.html");
14715
15455
  const { wrote, reason } = await safeWriteFile(outputPath, html, Boolean(options.force));
14716
15456
  if (!wrote) {
14717
15457
  const why = reason === "symlink" ? "path is a symlink" : "file exists (use --force)";
@@ -14946,12 +15686,12 @@ function formatReadinessMarkdown(report, repoName) {
14946
15686
  }
14947
15687
 
14948
15688
  // src/commands/tui.tsx
14949
- import path22 from "path";
15689
+ import path25 from "path";
14950
15690
  import { render as render3 } from "ink";
14951
15691
 
14952
15692
  // src/ui/tui.tsx
14953
- import fs10 from "fs/promises";
14954
- import path21 from "path";
15693
+ import fs11 from "fs/promises";
15694
+ import path24 from "path";
14955
15695
  import { Box as Box5, Text as Text5, useApp as useApp4, useInput as useInput4, useStdout, useIsScreenReaderEnabled as useIsScreenReaderEnabled5 } from "ink";
14956
15696
  import { useEffect as useEffect5, useMemo, useState as useState5 } from "react";
14957
15697
  import { Fragment, jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
@@ -15066,7 +15806,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15066
15806
  const [isMonorepo, setIsMonorepo] = useState5(false);
15067
15807
  const [repoAreas, setRepoAreas] = useState5([]);
15068
15808
  const [areaCursor, setAreaCursor] = useState5(0);
15069
- const repoLabel = useMemo(() => path21.basename(repoPath), [repoPath]);
15809
+ const repoLabel = useMemo(() => path24.basename(repoPath), [repoPath]);
15070
15810
  const repoFull = useMemo(() => repoPath, [repoPath]);
15071
15811
  const isLoading = status === "generating" || status === "bootstrapping" || status === "evaluating" || status === "generating-areas" || status === "readiness-running";
15072
15812
  const isMenu = status === "model-pick" || status === "eval-pick" || status === "batch-pick" || status === "generate-pick" || status === "generate-app-pick" || status === "generate-area-pick";
@@ -15078,15 +15818,15 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15078
15818
  setStatus("idle");
15079
15819
  };
15080
15820
  useEffect5(() => {
15081
- const configPath = path21.join(repoPath, "agentrc.eval.json");
15082
- fs10.access(configPath).then(() => setHasEvalConfig(true)).catch(() => setHasEvalConfig(false));
15821
+ const configPath = path24.join(repoPath, "agentrc.eval.json");
15822
+ fs11.access(configPath).then(() => setHasEvalConfig(true)).catch(() => setHasEvalConfig(false));
15083
15823
  const agentrcConfigCandidates = [
15084
- path21.join(repoPath, "agentrc.config.json"),
15085
- path21.join(repoPath, ".github", "agentrc.config.json")
15824
+ path24.join(repoPath, "agentrc.config.json"),
15825
+ path24.join(repoPath, ".github", "agentrc.config.json")
15086
15826
  ];
15087
15827
  Promise.all(
15088
15828
  agentrcConfigCandidates.map(
15089
- (p) => fs10.access(p).then(() => true).catch(() => false)
15829
+ (p) => fs11.access(p).then(() => true).catch(() => false)
15090
15830
  )
15091
15831
  ).then((results) => setHasAgentrcConfig(results.some(Boolean))).catch(() => setHasAgentrcConfig(false));
15092
15832
  analyzeRepo(repoPath).then((analysis) => {
@@ -15149,8 +15889,8 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15149
15889
  };
15150
15890
  useEffect5(() => {
15151
15891
  let active = true;
15152
- const configPath = path21.join(repoPath, "agentrc.eval.json");
15153
- fs10.readFile(configPath, "utf8").then((raw) => {
15892
+ const configPath = path24.join(repoPath, "agentrc.eval.json");
15893
+ fs11.readFile(configPath, "utf8").then((raw) => {
15154
15894
  if (!active) return;
15155
15895
  const parsed = JSON.parse(raw);
15156
15896
  const setting = parsed.ui?.modelPicker;
@@ -15164,7 +15904,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15164
15904
  };
15165
15905
  }, [repoPath]);
15166
15906
  const bootstrapEvalConfig = async (count, force) => {
15167
- const configPath = path21.join(repoPath, "agentrc.eval.json");
15907
+ const configPath = path24.join(repoPath, "agentrc.eval.json");
15168
15908
  try {
15169
15909
  setStatus("bootstrapping");
15170
15910
  setMessage("Generating eval cases with Copilot SDK...");
@@ -15203,13 +15943,13 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15203
15943
  if (status === "preview") {
15204
15944
  if (input.toLowerCase() === "s") {
15205
15945
  try {
15206
- const outputPath = generateSavePath || path21.join(repoPath, ".github", "copilot-instructions.md");
15207
- await fs10.mkdir(path21.dirname(outputPath), { recursive: true });
15946
+ const outputPath = generateSavePath || path24.join(repoPath, ".github", "copilot-instructions.md");
15947
+ await fs11.mkdir(path24.dirname(outputPath), { recursive: true });
15208
15948
  const { wrote, reason } = await safeWriteFile(outputPath, generatedContent, true);
15209
15949
  if (!wrote)
15210
15950
  throw new Error(reason === "symlink" ? "Path is a symlink" : "Write failed");
15211
15951
  setStatus("done");
15212
- const relPath = path21.relative(repoPath, outputPath);
15952
+ const relPath = path24.relative(repoPath, outputPath);
15213
15953
  const msg = `Saved to ${relPath}`;
15214
15954
  setMessage(msg);
15215
15955
  addLog(msg, "success");
@@ -15243,10 +15983,10 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15243
15983
  setMessage("Enter a positive number of eval cases, then press Enter.");
15244
15984
  return;
15245
15985
  }
15246
- const configPath = path21.join(repoPath, "agentrc.eval.json");
15986
+ const configPath = path24.join(repoPath, "agentrc.eval.json");
15247
15987
  setEvalBootstrapCount(count);
15248
15988
  try {
15249
- await fs10.access(configPath);
15989
+ await fs11.access(configPath);
15250
15990
  setStatus("bootstrapEvalConfirm");
15251
15991
  setMessage("agentrc.eval.json exists. Overwrite? (Y/N)");
15252
15992
  } catch {
@@ -15302,7 +16042,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15302
16042
  setStatus("generate-app-pick");
15303
16043
  setMessage("Generate for root or per-app?");
15304
16044
  } else {
15305
- const savePath = path21.join(repoPath, ".github", "copilot-instructions.md");
16045
+ const savePath = path24.join(repoPath, ".github", "copilot-instructions.md");
15306
16046
  setGenerateSavePath(savePath);
15307
16047
  await doGenerate(repoPath, savePath, "copilot-instructions");
15308
16048
  }
@@ -15314,7 +16054,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15314
16054
  setStatus("generate-app-pick");
15315
16055
  setMessage("Generate for root or per-app?");
15316
16056
  } else {
15317
- const savePath = path21.join(repoPath, "AGENTS.md");
16057
+ const savePath = path24.join(repoPath, "AGENTS.md");
15318
16058
  setGenerateSavePath(savePath);
15319
16059
  await doGenerate(repoPath, savePath, "agents-md");
15320
16060
  }
@@ -15339,7 +16079,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15339
16079
  }
15340
16080
  if (status === "generate-app-pick") {
15341
16081
  if (input.toLowerCase() === "r") {
15342
- const savePath = generateTarget === "copilot-instructions" ? path21.join(repoPath, ".github", "copilot-instructions.md") : path21.join(repoPath, "AGENTS.md");
16082
+ const savePath = generateTarget === "copilot-instructions" ? path24.join(repoPath, ".github", "copilot-instructions.md") : path24.join(repoPath, "AGENTS.md");
15343
16083
  setGenerateSavePath(savePath);
15344
16084
  await doGenerate(repoPath, savePath, generateTarget);
15345
16085
  return;
@@ -15349,7 +16089,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15349
16089
  addLog(`Generating ${generateTarget} for ${repoApps.length} apps...`, "progress");
15350
16090
  let count = 0;
15351
16091
  for (const app2 of repoApps) {
15352
- const savePath = generateTarget === "copilot-instructions" ? path21.join(app2.path, ".github", "copilot-instructions.md") : path21.join(app2.path, "AGENTS.md");
16092
+ const savePath = generateTarget === "copilot-instructions" ? path24.join(app2.path, ".github", "copilot-instructions.md") : path24.join(app2.path, "AGENTS.md");
15353
16093
  setMessage(`Generating for ${app2.name} (${count + 1}/${repoApps.length})...`);
15354
16094
  try {
15355
16095
  const content = await generateCopilotInstructions({
@@ -15357,11 +16097,11 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15357
16097
  onProgress: (msg) => setMessage(`${app2.name}: ${msg}`)
15358
16098
  });
15359
16099
  if (content.trim()) {
15360
- await fs10.mkdir(path21.dirname(savePath), { recursive: true });
16100
+ await fs11.mkdir(path24.dirname(savePath), { recursive: true });
15361
16101
  const { wrote: saved } = await safeWriteFile(savePath, content, true);
15362
16102
  if (!saved) continue;
15363
16103
  count++;
15364
- addLog(`${app2.name}: saved ${path21.basename(savePath)}`, "success");
16104
+ addLog(`${app2.name}: saved ${path24.basename(savePath)}`, "success");
15365
16105
  }
15366
16106
  } catch (error) {
15367
16107
  const msg = error instanceof Error ? error.message : "Failed.";
@@ -15375,7 +16115,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15375
16115
  const num = Number.parseInt(input, 10);
15376
16116
  if (Number.isFinite(num) && num >= 1 && num <= repoApps.length) {
15377
16117
  const app2 = repoApps[num - 1];
15378
- const savePath = generateTarget === "copilot-instructions" ? path21.join(app2.path, ".github", "copilot-instructions.md") : path21.join(app2.path, "AGENTS.md");
16118
+ const savePath = generateTarget === "copilot-instructions" ? path24.join(app2.path, ".github", "copilot-instructions.md") : path24.join(app2.path, "AGENTS.md");
15379
16119
  setGenerateSavePath(savePath);
15380
16120
  await doGenerate(app2.path, savePath, generateTarget);
15381
16121
  return;
@@ -15403,7 +16143,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15403
16143
  const result = await writeAreaInstruction(repoPath, area, body);
15404
16144
  if (result.status === "written") {
15405
16145
  written++;
15406
- addLog(`${area.name}: saved ${path21.basename(result.filePath)}`, "success");
16146
+ addLog(`${area.name}: saved ${path24.basename(result.filePath)}`, "success");
15407
16147
  } else if (result.status === "skipped") {
15408
16148
  addLog(`${area.name}: skipped (file exists)`, "info");
15409
16149
  }
@@ -15497,15 +16237,15 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15497
16237
  }
15498
16238
  if (status === "eval-pick") {
15499
16239
  if (input.toLowerCase() === "r") {
15500
- const configPath = path21.join(repoPath, "agentrc.eval.json");
15501
- const outputPath = path21.join(
16240
+ const configPath = path24.join(repoPath, "agentrc.eval.json");
16241
+ const outputPath = path24.join(
15502
16242
  repoPath,
15503
16243
  ".agentrc",
15504
16244
  "evals",
15505
16245
  buildTimestampedName("eval-results")
15506
16246
  );
15507
16247
  try {
15508
- await fs10.access(configPath);
16248
+ await fs11.access(configPath);
15509
16249
  } catch {
15510
16250
  setStatus("error");
15511
16251
  const msg = "No agentrc.eval.json found. Press [E] then [I] to create one.";
@@ -15865,7 +16605,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15865
16605
  /* @__PURE__ */ jsx7(Text5, { color: "white", children: app2.name }),
15866
16606
  /* @__PURE__ */ jsxs4(Text5, { color: "gray", dimColor: true, children: [
15867
16607
  " ",
15868
- path21.relative(repoPath, app2.path)
16608
+ path24.relative(repoPath, app2.path)
15869
16609
  ] })
15870
16610
  ] }, app2.name)) })
15871
16611
  ] }),
@@ -15899,7 +16639,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
15899
16639
  children: [
15900
16640
  /* @__PURE__ */ jsxs4(Text5, { color: "cyan", bold: true, children: [
15901
16641
  "Preview (",
15902
- path21.relative(repoPath, generateSavePath) || generateTarget,
16642
+ path24.relative(repoPath, generateSavePath) || generateTarget,
15903
16643
  ")"
15904
16644
  ] }),
15905
16645
  /* @__PURE__ */ jsx7(Text5, { color: "gray", children: truncatedPreview })
@@ -16008,7 +16748,7 @@ function AgentRCTui({ repoPath, skipAnimation = false }) {
16008
16748
  // src/commands/tui.tsx
16009
16749
  import { jsx as jsx8 } from "react/jsx-runtime";
16010
16750
  async function tuiCommand(options) {
16011
- const repoPath = path22.resolve(options.repo ?? process.cwd());
16751
+ const repoPath = path25.resolve(options.repo ?? process.cwd());
16012
16752
  const skipAnimation = options.animation === false;
16013
16753
  try {
16014
16754
  const accessible = options.accessible ? true : void 0;