@ariestools/toolchain 10.1.3 → 10.1.5

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.
Files changed (44) hide show
  1. package/dist/actions/agent/defaults.d.ts +33 -0
  2. package/dist/actions/agent/defaults.d.ts.map +1 -0
  3. package/dist/actions/agent/docRules.d.ts +6 -0
  4. package/dist/actions/agent/docRules.d.ts.map +1 -0
  5. package/dist/actions/agent/edit.d.ts +28 -0
  6. package/dist/actions/agent/edit.d.ts.map +1 -0
  7. package/dist/actions/agent/fixAgents.d.ts +21 -0
  8. package/dist/actions/agent/fixAgents.d.ts.map +1 -0
  9. package/dist/actions/agent/fixDocs.d.ts +20 -0
  10. package/dist/actions/agent/fixDocs.d.ts.map +1 -0
  11. package/dist/actions/agent/init.d.ts +7 -1
  12. package/dist/actions/agent/init.d.ts.map +1 -1
  13. package/dist/actions/agent/lint.d.ts +5 -1
  14. package/dist/actions/agent/lint.d.ts.map +1 -1
  15. package/dist/actions/agent/mutate.d.ts +1 -0
  16. package/dist/actions/agent/mutate.d.ts.map +1 -1
  17. package/dist/actions/agent/ruleSupport.d.ts +12 -0
  18. package/dist/actions/agent/ruleSupport.d.ts.map +1 -0
  19. package/dist/actions/agent/rules.d.ts.map +1 -1
  20. package/dist/actions/ruleAsk.d.ts +23 -0
  21. package/dist/actions/ruleAsk.d.ts.map +1 -0
  22. package/dist/actions/ruleCatalogRender.d.ts +3 -0
  23. package/dist/actions/ruleCatalogRender.d.ts.map +1 -1
  24. package/dist/actions/ruleRunner.d.ts +21 -1
  25. package/dist/actions/ruleRunner.d.ts.map +1 -1
  26. package/dist/actions/skills/defaults.d.ts +4 -3
  27. package/dist/actions/skills/defaults.d.ts.map +1 -1
  28. package/dist/actions/skills/detectProfile.d.ts +23 -0
  29. package/dist/actions/skills/detectProfile.d.ts.map +1 -1
  30. package/dist/actions/skills/lint.d.ts.map +1 -1
  31. package/dist/actions/skills/missingSkillReason.d.ts +10 -0
  32. package/dist/actions/skills/missingSkillReason.d.ts.map +1 -0
  33. package/dist/actions/skills/skillRules.d.ts +13 -1
  34. package/dist/actions/skills/skillRules.d.ts.map +1 -1
  35. package/dist/bin/package/clean.mjs.map +1 -1
  36. package/dist/bin/package/recompile.mjs.map +1 -1
  37. package/dist/bin/xy.mjs +1330 -436
  38. package/dist/bin/xy.mjs.map +1 -1
  39. package/dist/bin/xyex.mjs +1330 -436
  40. package/dist/bin/xyex.mjs.map +1 -1
  41. package/dist/xy/common/agent/index.d.ts.map +1 -1
  42. package/dist/xy/common/skills/index.d.ts.map +1 -1
  43. package/dist/xy/stability.d.ts.map +1 -1
  44. package/package.json +5 -5
package/dist/bin/xy.mjs CHANGED
@@ -22,6 +22,7 @@ import { fileURLToPath as fileURLToPath$1 } from "url";
22
22
  import { createJiti } from "jiti";
23
23
  import { performance as performance$1 } from "node:perf_hooks";
24
24
  import util, { promisify, stripVTControlCharacters } from "node:util";
25
+ import readline$1 from "node:readline/promises";
25
26
  import ts from "typescript";
26
27
  import { createHash, randomBytes } from "node:crypto";
27
28
  import { ESLint } from "eslint";
@@ -30,7 +31,6 @@ import { includeIgnoreFile } from "eslint/config";
30
31
  import { pipeline } from "node:stream/promises";
31
32
  import zlib from "node:zlib";
32
33
  import { builtinRules } from "eslint/use-at-your-own-risk";
33
- import readline$1 from "node:readline/promises";
34
34
  import { notStrictEqual, strictEqual } from "assert";
35
35
  import { format, inspect } from "util";
36
36
  //#region \0rolldown/runtime.js
@@ -1189,11 +1189,14 @@ const DOC_DIRS = [
1189
1189
  "evidence",
1190
1190
  "archive"
1191
1191
  ];
1192
- const AGENTS_TEMPLATE = `# Project
1192
+ const DEFAULT_ORIENT = "What this repository is. Link the existing docs instead of copying them.";
1193
+ /** The AGENTS.md stub; `--fix-interactive` fills the title and orient line. */
1194
+ function agentsTemplate(title = "Project", orient = DEFAULT_ORIENT) {
1195
+ return `# ${title}
1193
1196
 
1194
1197
  ## Orient
1195
1198
 
1196
- What this repository is. Link the existing docs instead of copying them.
1199
+ ${orient}
1197
1200
 
1198
1201
  ## Authority
1199
1202
 
@@ -1213,6 +1216,7 @@ Use the repository package scripts from the root.
1213
1216
 
1214
1217
  Re-run the failing command after the fix. Keep task assignments out of this file.
1215
1218
  `;
1219
+ }
1216
1220
  const CLAUDE_ADAPTER = "@AGENTS.md\n";
1217
1221
  function writeIfMissing(cwd, relativePath, contents, result) {
1218
1222
  const fullPath = path.join(cwd, relativePath);
@@ -1228,12 +1232,12 @@ function writeIfMissing(cwd, relativePath, contents, result) {
1228
1232
  * Create the agent-doc skeleton. Existing AGENTS.md, adapters, and docs are
1229
1233
  * left in place. A second run changes nothing.
1230
1234
  */
1231
- function agentInit(cwd) {
1235
+ function agentInit(cwd, options = {}) {
1232
1236
  const result = {
1233
1237
  created: [],
1234
1238
  kept: []
1235
1239
  };
1236
- writeIfMissing(cwd, "AGENTS.md", AGENTS_TEMPLATE, result);
1240
+ writeIfMissing(cwd, "AGENTS.md", agentsTemplate(options.title, options.orient), result);
1237
1241
  writeIfMissing(cwd, "CLAUDE.md", CLAUDE_ADAPTER, result);
1238
1242
  for (const dir of DOC_DIRS) writeIfMissing(cwd, `docs/${dir}/.gitkeep`, "", result);
1239
1243
  const context = loadAgentLintContext(cwd);
@@ -4912,11 +4916,11 @@ function readJsonFile$1(path) {
4912
4916
  return;
4913
4917
  }
4914
4918
  }
4915
- function readRootPackageJson$1(cwd = process.cwd()) {
4919
+ function readRootPackageJson$2(cwd = process.cwd()) {
4916
4920
  return readJsonFile$1(path.resolve(cwd, "package.json"));
4917
4921
  }
4918
4922
  function readWorkspacePatternsFromPackageJson$1(cwd = process.cwd()) {
4919
- const pkg = readRootPackageJson$1(cwd);
4923
+ const pkg = readRootPackageJson$2(cwd);
4920
4924
  if (!pkg?.workspaces) return [];
4921
4925
  if (Array.isArray(pkg.workspaces)) return [...pkg.workspaces];
4922
4926
  return pkg.workspaces.packages ? [...pkg.workspaces.packages] : [];
@@ -4991,7 +4995,7 @@ function listDeclaredWorkspaces(cwd = process.cwd()) {
4991
4995
  return workspaces.toSorted((a, b) => a.location.localeCompare(b.location));
4992
4996
  }
4993
4997
  function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
4994
- const packageManager = readRootPackageJson$1(cwd)?.packageManager;
4998
+ const packageManager = readRootPackageJson$2(cwd)?.packageManager;
4995
4999
  return packageManager == null || packageManager.length === 0 ? void 0 : packageManager.split("@", 1)[0];
4996
5000
  }
4997
5001
  //#endregion
@@ -7149,7 +7153,7 @@ var require_semver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7149
7153
  //#region src/lib/toolchainVersion.ts
7150
7154
  createRequire(import.meta.url);
7151
7155
  function bundledToolchainVersion() {
7152
- return "10.1.3";
7156
+ return "10.1.5";
7153
7157
  }
7154
7158
  function bundledToolchainRange() {
7155
7159
  return `^${bundledToolchainVersion()}`;
@@ -24195,6 +24199,78 @@ async function runUpdo(pm, options = {}) {
24195
24199
  console.log(chalk.gray("Installing updated dependencies..."));
24196
24200
  return runSteps("Updo", [pm.install(), pm.dedupe()], true);
24197
24201
  }
24202
+ /**
24203
+ * Turn raw input into an answer: Enter takes the default (or skips when there
24204
+ * is none), `-` skips, and a choice may be given by text or 1-based number.
24205
+ */
24206
+ function resolveRuleAnswer(question, raw) {
24207
+ const input = raw.trim();
24208
+ if (input === "-") return {};
24209
+ const candidate = input.length === 0 ? question.default : input;
24210
+ if (candidate === void 0 || candidate.length === 0) return {};
24211
+ let value = candidate;
24212
+ if (question.choices !== void 0) {
24213
+ const index = /^\d+$/.test(candidate) ? Number(candidate) - 1 : -1;
24214
+ const match = question.choices[index] ?? question.choices.find((choice) => choice.toLowerCase() === candidate.toLowerCase());
24215
+ if (match === void 0) return { error: `Choose one of: ${question.choices.join(", ")}` };
24216
+ value = match;
24217
+ }
24218
+ const error = question.validate?.(value);
24219
+ return error === void 0 ? { value } : { error };
24220
+ }
24221
+ /** The question and its choices, printed above the input line. */
24222
+ function questionLines(question) {
24223
+ const lines = [chalk.cyan(`? ${question.message}`)];
24224
+ if (question.choices !== void 0) lines.push(chalk.gray(` ${question.choices.map((choice, index) => `${String(index + 1)}) ${choice}`).join(" ")}`));
24225
+ return lines;
24226
+ }
24227
+ /** Readline handles a one-line prompt; the question goes above it. */
24228
+ function inputPrompt(question) {
24229
+ return ` ${question.default === void 0 ? "" : chalk.gray(`[${question.default}] `)}› `;
24230
+ }
24231
+ /**
24232
+ * Ask on the terminal. Closing input (Ctrl-D) skips every remaining question.
24233
+ */
24234
+ function createTerminalRuleAsk(commandName) {
24235
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error(`${commandName} --fix-interactive needs a TTY. Use --fix for the fixes that need no answers.`);
24236
+ const rl = readline$1.createInterface({
24237
+ input: process.stdin,
24238
+ output: process.stdout
24239
+ });
24240
+ let isClosed = false;
24241
+ let isAsking = false;
24242
+ let hasIntroduced = false;
24243
+ rl.on("close", () => {
24244
+ isClosed = true;
24245
+ if (isAsking) process.stdout.write("\n");
24246
+ });
24247
+ const ask = async (question) => {
24248
+ if (isClosed) return;
24249
+ if (!hasIntroduced) {
24250
+ hasIntroduced = true;
24251
+ console.log(chalk.gray(` Enter accepts the [default], - skips a question, Ctrl-D skips the rest.`));
24252
+ }
24253
+ for (const line of questionLines(question)) console.log(line);
24254
+ while (!isClosed) {
24255
+ let raw;
24256
+ isAsking = true;
24257
+ try {
24258
+ raw = await rl.question(inputPrompt(question));
24259
+ } catch {
24260
+ return;
24261
+ } finally {
24262
+ isAsking = false;
24263
+ }
24264
+ const answer = resolveRuleAnswer(question, raw);
24265
+ if (answer.error === void 0) return answer.value;
24266
+ console.log(chalk.yellow(` ${answer.error}`));
24267
+ }
24268
+ };
24269
+ return {
24270
+ ask,
24271
+ close: () => rl.close()
24272
+ };
24273
+ }
24198
24274
  //#endregion
24199
24275
  //#region src/actions/result.ts
24200
24276
  function actionResult({ errorCount, exitCode = errorCount, warningCount }) {
@@ -24360,7 +24436,7 @@ function recordRuleOutcome(report, rule, diagnostics, fixedCount, reporter) {
24360
24436
  if (fixedCount > 0) reporter?.fixed?.(rule, fixedCount);
24361
24437
  if (fixedCount === 0 && diagnostics.length === 0) reporter?.passed?.(rule);
24362
24438
  }
24363
- async function runRuleChecks({ commandName, configKey = commandName, config, context, fix = false, levelOverrides, reporter, rules, strict = isStrictMode() }) {
24439
+ async function runRuleChecks({ ask, commandName, configKey = commandName, config, context, fix = false, levelOverrides, reporter, rules, strict = isStrictMode() }) {
24364
24440
  validateConfiguredRuleIds(commandName, configKey, rules, config);
24365
24441
  const report = {
24366
24442
  diagnostics: [],
@@ -24375,7 +24451,8 @@ async function runRuleChecks({ commandName, configKey = commandName, config, con
24375
24451
  if (level === "off") continue;
24376
24452
  const isExplicit = resolved.isExplicit || override !== void 0;
24377
24453
  const outcome = await rule.check(context, {
24378
- fix,
24454
+ ...ask !== void 0 && rule.interactive === true && { ask },
24455
+ fix: fix || ask !== void 0,
24379
24456
  isExplicit,
24380
24457
  level
24381
24458
  });
@@ -24384,33 +24461,26 @@ async function runRuleChecks({ commandName, configKey = commandName, config, con
24384
24461
  return buildRunResult(report, strict);
24385
24462
  }
24386
24463
  //#endregion
24387
- //#region src/actions/agent/rules.ts
24388
- const SIZE_BUDGET = 200;
24389
- const STALE_DAYS = 180;
24390
- const RUNBOOK_STALE_DAYS = 90;
24391
- const REQUIRED_SECTIONS = [
24392
- {
24393
- label: "orient",
24394
- pattern: /orient|what this|overview|about this/i
24395
- },
24396
- {
24397
- label: "authority",
24398
- pattern: /authorit/i
24399
- },
24400
- {
24401
- label: "repository map",
24402
- pattern: /repository map|repo map|\blayout\b|\bpackages\b/i
24403
- },
24404
- {
24405
- label: "commands",
24406
- pattern: /command/i
24407
- },
24408
- {
24409
- label: "failures",
24410
- pattern: /fail|troubleshoot|what not to do|pitfall/i
24411
- }
24464
+ //#region src/actions/agent/defaults.ts
24465
+ /** Plausible answers for `--fix-interactive` questions, derived from the checkout. */
24466
+ const DOCUMENT_KINDS = [
24467
+ "paper",
24468
+ "spec",
24469
+ "decision",
24470
+ "plan",
24471
+ "runbook",
24472
+ "evidence",
24473
+ "handoff",
24474
+ "research"
24412
24475
  ];
24413
- const FRONT_MATTER_KINDS = [
24476
+ const DOCUMENT_STATES = [
24477
+ "draft",
24478
+ "active",
24479
+ "normative",
24480
+ "superseded",
24481
+ "retired"
24482
+ ];
24483
+ const FOLDER_KINDS = [
24414
24484
  {
24415
24485
  kind: "decision",
24416
24486
  pattern: /^docs\/decisions\//
@@ -24436,12 +24506,621 @@ const FRONT_MATTER_KINDS = [
24436
24506
  pattern: /^specs\//
24437
24507
  }
24438
24508
  ];
24509
+ const NAME_KINDS = [
24510
+ {
24511
+ kind: "plan",
24512
+ pattern: /roadmap|plan|follow-?up|todo/i
24513
+ },
24514
+ {
24515
+ kind: "decision",
24516
+ pattern: /decision|^adr/i
24517
+ },
24518
+ {
24519
+ kind: "evidence",
24520
+ pattern: /evidence|qualification|receipt/i
24521
+ },
24522
+ {
24523
+ kind: "handoff",
24524
+ pattern: /handoff/i
24525
+ },
24526
+ {
24527
+ kind: "research",
24528
+ pattern: /review|audit|research|survey/i
24529
+ },
24530
+ {
24531
+ kind: "runbook",
24532
+ pattern: /runbook|deploy|migrat|setup|install|release/i
24533
+ }
24534
+ ];
24535
+ /** The kind a document's folder implies, as `--fix` writes it. */
24536
+ function folderKind(relativePath) {
24537
+ return FOLDER_KINDS.find((entry) => entry.pattern.test(relativePath))?.kind;
24538
+ }
24539
+ /** The folder's kind, else a guess from the file name, else `spec`. */
24540
+ function guessKind(relativePath) {
24541
+ const name = path.posix.basename(relativePath, ".md");
24542
+ return folderKind(relativePath) ?? NAME_KINDS.find((entry) => entry.pattern.test(name))?.kind ?? "spec";
24543
+ }
24544
+ function defaultState(kind) {
24545
+ if (kind === "paper" || kind === "decision") return "normative";
24546
+ return kind === "evidence" || kind === "research" ? void 0 : "active";
24547
+ }
24548
+ function todayIso() {
24549
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
24550
+ }
24551
+ function lastCommitDate(cwd, relativePath) {
24552
+ const result = spawnSync$1("git", [
24553
+ "log",
24554
+ "-1",
24555
+ "--format=%as",
24556
+ "--",
24557
+ relativePath
24558
+ ], {
24559
+ cwd,
24560
+ encoding: "utf8"
24561
+ });
24562
+ const date = result.status === 0 ? result.stdout.trim() : "";
24563
+ return /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : void 0;
24564
+ }
24565
+ function readText(cwd, relativePath) {
24566
+ try {
24567
+ return fs.readFileSync(path.join(cwd, relativePath), "utf8");
24568
+ } catch {
24569
+ return;
24570
+ }
24571
+ }
24572
+ function readRootPackageJson$1(cwd) {
24573
+ const text = readText(cwd, "package.json");
24574
+ if (text === void 0) return void 0;
24575
+ try {
24576
+ const parsed = JSON.parse(text);
24577
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
24578
+ } catch {
24579
+ return;
24580
+ }
24581
+ }
24582
+ /** Heading text without code spans, links, or emphasis markers. */
24583
+ function plainHeading(heading) {
24584
+ return heading.replaceAll(/!?\[([^\]]*)]\([^)]*\)/g, "$1").replaceAll(/[`*_]/g, "").trim();
24585
+ }
24586
+ /**
24587
+ * The root README H1, else the root package.json name. The README comes
24588
+ * first because a monorepo root package.json usually names the private
24589
+ * workspace (`@scope/config`), not the product.
24590
+ */
24591
+ function productName(cwd) {
24592
+ const readme = readText(cwd, "README.md");
24593
+ const heading = readme === void 0 ? void 0 : firstHeading(readme);
24594
+ const title = heading === void 0 ? "" : plainHeading(heading);
24595
+ if (title.length > 0 && !/^(?:readme|agents)(?:\.md)?$/i.test(title)) return title;
24596
+ const name = readRootPackageJson$1(cwd)?.name;
24597
+ return typeof name === "string" && name.length > 0 ? name : void 0;
24598
+ }
24599
+ function agentsTitle(cwd) {
24600
+ const product = productName(cwd);
24601
+ return product === void 0 ? void 0 : `${product} agent guidance`;
24602
+ }
24603
+ /** The root package.json description, else the README's first prose line. */
24604
+ function repoDescription(cwd) {
24605
+ const description = readRootPackageJson$1(cwd)?.description;
24606
+ if (typeof description === "string" && description.trim().length > 0) return description.trim();
24607
+ return (readText(cwd, "README.md") ?? "").split("\n").map((line) => line.trim()).find((line) => line.length > 0 && !/^(?:#|!?\[|<|>|```|\||-{3})/.test(line));
24608
+ }
24609
+ function workspaceGlobs(cwd) {
24610
+ const text = readText(cwd, "pnpm-workspace.yaml");
24611
+ if (text === void 0) return [];
24612
+ return (/^packages:\s*\n((?:[ \t]+-.*\n?)+)/m.exec(text)?.[1] ?? "").split("\n").map((line) => line.trim().replace(/^-\s*/, "").replaceAll(/^['"]|['"]$/g, "")).filter((glob) => glob.length > 0 && !glob.startsWith("!"));
24613
+ }
24614
+ function repositoryMapLine(cwd) {
24615
+ const globs = workspaceGlobs(cwd);
24616
+ if (globs.length > 0) return `Workspace packages live in ${globs.map((glob) => `\`${glob}\``).join(", ")}.`;
24617
+ return fs.existsSync(path.join(cwd, "src")) ? "Source lives in `src/`." : void 0;
24618
+ }
24619
+ function gateCommand(cwd) {
24620
+ const devDependencies = readRootPackageJson$1(cwd)?.devDependencies ?? {};
24621
+ return fs.existsSync(path.join(cwd, "xy.config.ts")) || "@ariestools/toolchain" in devDependencies || "@xylabs/toolchain" in devDependencies ? "pnpm xy check && pnpm xy build && pnpm xy test" : void 0;
24622
+ }
24623
+ function authorityDefault(cwd) {
24624
+ return [
24625
+ "docs/README.md",
24626
+ "papers/README.md",
24627
+ "README.md"
24628
+ ].find((candidate) => fs.existsSync(path.join(cwd, candidate)));
24629
+ }
24630
+ /** The only repository file with the same name, for a link whose target moved. */
24631
+ function sameNamePath(cwd, target) {
24632
+ const name = path.posix.basename(target);
24633
+ if (name.length === 0) return void 0;
24634
+ const matches = walkRepoFiles(cwd, (relativePath) => path.posix.basename(relativePath) === name);
24635
+ return matches.length === 1 ? matches[0] : void 0;
24636
+ }
24637
+ /** The only other live document that names this one, as a successor guess. */
24638
+ function successorGuess(context, document) {
24639
+ const name = path.posix.basename(document.relativePath);
24640
+ const naming = context.documents.filter((other) => other !== document && other.relativePath !== "docs/README.md" && !other.relativePath.startsWith("docs/archive/") && other.text.includes(name));
24641
+ return naming.length === 1 ? naming[0]?.relativePath : void 0;
24642
+ }
24643
+ /** A version or date stated in a paper's visible header, under its H1. */
24644
+ function headerValue(document, field) {
24645
+ const header = document.body.split("\n").slice(0, 20).join("\n");
24646
+ const match = (field === "date" ? /\b\d{4}-\d{2}-\d{2}\b/ : /\bv?(\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?)\b/).exec(header);
24647
+ return field === "date" ? match?.[0] : match?.[1];
24648
+ }
24649
+ //#endregion
24650
+ //#region src/actions/agent/edit.ts
24651
+ const FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
24652
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
24653
+ /** A double-quoted YAML scalar. */
24654
+ function yamlString(value) {
24655
+ return JSON.stringify(value);
24656
+ }
24657
+ /**
24658
+ * Set front-matter fields, replacing an existing line for the key or adding
24659
+ * one. `kind` goes first; other new keys go last. Values are YAML scalars.
24660
+ */
24661
+ function setFrontMatterFields(text, fields) {
24662
+ const match = FRONT_MATTER.exec(text);
24663
+ if (match?.[1] === void 0) return `---\n${fields.map(([key, value]) => `${key}: ${value}`).join("\n")}\n---\n\n${text}`;
24664
+ const lines = match[1].split(/\r?\n/);
24665
+ for (const [key, value] of fields) {
24666
+ const line = `${key}: ${value}`;
24667
+ const pattern = new RegExp(String.raw`^${key}\s*:`);
24668
+ const index = lines.findIndex((existing) => pattern.test(existing.trim()));
24669
+ if (index !== -1) lines[index] = line;
24670
+ else if (key === "kind") lines.unshift(line);
24671
+ else lines.push(line);
24672
+ }
24673
+ return `---\n${lines.join("\n")}\n---\n${text.slice(match[0].length)}`;
24674
+ }
24675
+ /** Front-matter scalars become index cells and are read one line at a time. */
24676
+ function validateScalar(answer) {
24677
+ if (answer.includes("|")) return "Leave out \"|\"; the value becomes a table cell";
24678
+ return answer.includes("\"") ? "Leave out double quotes" : void 0;
24679
+ }
24680
+ function validateIsoDate(answer) {
24681
+ return ISO_DATE.test(answer) && !Number.isNaN(Date.parse(answer)) ? void 0 : "Use YYYY-MM-DD";
24682
+ }
24683
+ function validateRepoPath(cwd, from) {
24684
+ return (answer) => {
24685
+ const resolved = path.resolve(cwd, path.dirname(from), answer);
24686
+ const root = path.resolve(cwd);
24687
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) return "Give a path inside the repository";
24688
+ return fs.existsSync(resolved) ? void 0 : `${answer} does not exist`;
24689
+ };
24690
+ }
24691
+ function lstatIfPresent$3(fullPath) {
24692
+ try {
24693
+ return fs.lstatSync(fullPath);
24694
+ } catch {
24695
+ return;
24696
+ }
24697
+ }
24698
+ /**
24699
+ * Write a regular file in the checkout. Refuses symlinks, so a fix never
24700
+ * writes through a link to somewhere else.
24701
+ */
24702
+ function writeRegularFile(cwd, relativePath, text) {
24703
+ const fullPath = path.join(cwd, relativePath);
24704
+ const stat = lstatIfPresent$3(fullPath);
24705
+ if (stat !== void 0 && !stat.isFile()) return false;
24706
+ fs.writeFileSync(fullPath, text);
24707
+ return true;
24708
+ }
24709
+ /** Write a document and keep the in-memory copy in step for later rules. */
24710
+ function rewriteDocument(context, document, text) {
24711
+ if (!writeRegularFile(context.cwd, document.relativePath, text)) return false;
24712
+ Object.assign(document, {
24713
+ text,
24714
+ ...parseFrontMatter(text)
24715
+ });
24716
+ return true;
24717
+ }
24718
+ function setDocumentFields(context, document, fields) {
24719
+ return rewriteDocument(context, document, setFrontMatterFields(document.text, fields));
24720
+ }
24721
+ /** Replace the first Markdown heading line with `# title`. */
24722
+ function replaceFirstHeading(text, title) {
24723
+ return text.replace(/^#{1,6}[ \t]+.+$/m, () => `# ${title}`);
24724
+ }
24725
+ /** Append a block, separated from the existing text by one blank line. */
24726
+ function appendBlock(text, block) {
24727
+ return `${text.trimEnd()}\n\n${block.trimEnd()}\n`;
24728
+ }
24729
+ //#endregion
24730
+ //#region src/actions/agent/fixAgents.ts
24731
+ const IMPORT_LINE = "@AGENTS.md";
24732
+ const IMPORT_PATTERN = /^@(\.\/)?AGENTS\.md$/;
24733
+ const COPILOT_LINK = "Follow the repository instructions in [AGENTS.md](../AGENTS.md).";
24734
+ function isCopilot(relativePath) {
24735
+ return relativePath.endsWith("copilot-instructions.md");
24736
+ }
24737
+ function validateTitle(answer) {
24738
+ return /^agents\.md$/i.test(answer) ? "Name the product, not the file" : void 0;
24739
+ }
24740
+ /** Remove the first `@AGENTS.md` line outside fences and comments, then lead with it. */
24741
+ function withLeadingImport(text) {
24742
+ const lines = text.split("\n");
24743
+ let fence;
24744
+ let isInComment = false;
24745
+ const index = lines.findIndex((line) => {
24746
+ const trimmed = line.trim();
24747
+ const marker = /^ {0,3}([`~]{3,})/.exec(line)?.[1];
24748
+ if (marker !== void 0 && (fence === void 0 || marker.startsWith(fence))) {
24749
+ fence = fence === void 0 ? marker : void 0;
24750
+ return false;
24751
+ }
24752
+ if (fence !== void 0) return false;
24753
+ if (isInComment) {
24754
+ isInComment = !trimmed.includes("-->");
24755
+ return false;
24756
+ }
24757
+ if (trimmed.startsWith("<!--") && !trimmed.includes("-->")) {
24758
+ isInComment = true;
24759
+ return false;
24760
+ }
24761
+ return IMPORT_PATTERN.test(trimmed);
24762
+ });
24763
+ if (index !== -1) lines.splice(index, 1);
24764
+ return `${IMPORT_LINE}\n\n${lines.join("\n").trimStart()}`;
24765
+ }
24766
+ function readFile(cwd, relativePath) {
24767
+ return fs.readFileSync(path.join(cwd, relativePath), "utf8");
24768
+ }
24769
+ /**
24770
+ * Adapter fixes that need no answer: each only moves the import or drops a
24771
+ * byte-for-byte copy of AGENTS.md. A Copilot copy stays, since Copilot has
24772
+ * no import and would lose the instructions.
24773
+ */
24774
+ function fixAdapter(cwd, relativePath, problem) {
24775
+ switch (problem) {
24776
+ case "copilot-link": return writeRegularFile(cwd, relativePath, `${COPILOT_LINK}\n\n${readFile(cwd, relativePath).trimStart()}`);
24777
+ case "duplicate": return !isCopilot(relativePath) && writeRegularFile(cwd, relativePath, `${IMPORT_LINE}\n`);
24778
+ case "pointer": return writeRegularFile(cwd, relativePath, withLeadingImport(readFile(cwd, relativePath)));
24779
+ default: return false;
24780
+ }
24781
+ }
24782
+ /** Adapter fixes that discard or keep text, so the user decides. */
24783
+ async function askAdapter(cwd, relativePath, problem, ask) {
24784
+ if (problem === "divergent") {
24785
+ const choice = await ask({
24786
+ choices: ["prepend", "replace"],
24787
+ default: "prepend",
24788
+ message: `${relativePath} does not import AGENTS.md. prepend keeps its text below an @AGENTS.md line; replace leaves only the import, so move anything AGENTS.md lacks first`
24789
+ });
24790
+ if (choice === void 0) return false;
24791
+ return writeRegularFile(cwd, relativePath, choice === "replace" ? `${IMPORT_LINE}\n` : `${IMPORT_LINE}\n\n${readFile(cwd, relativePath).trimStart()}`);
24792
+ }
24793
+ if (problem === "restates") {
24794
+ if (await ask({
24795
+ choices: ["yes", "no"],
24796
+ default: "no",
24797
+ message: `${relativePath} restates AGENTS.md. Replace it with ${isCopilot(relativePath) ? "a link to" : "an import of"} AGENTS.md, dropping its own text?`
24798
+ }) !== "yes") return false;
24799
+ return writeRegularFile(cwd, relativePath, `${isCopilot(relativePath) ? COPILOT_LINK : IMPORT_LINE}\n`);
24800
+ }
24801
+ return false;
24802
+ }
24803
+ /** Create AGENTS.md, and what `xy agent init` creates with it, from two answers. */
24804
+ async function askAgentsFile(context, ask) {
24805
+ if (lstatIfPresent$3(path.join(context.cwd, "AGENTS.md")) !== void 0) return false;
24806
+ const title = await ask({
24807
+ default: agentsTitle(context.cwd),
24808
+ message: "AGENTS.md is missing. Title for a new AGENTS.md, naming the product",
24809
+ validate: validateTitle
24810
+ });
24811
+ if (title === void 0) return false;
24812
+ const orient = await ask({
24813
+ default: repoDescription(context.cwd),
24814
+ message: "What is this repository, in one sentence?"
24815
+ });
24816
+ agentInit(context.cwd, {
24817
+ orient,
24818
+ title
24819
+ });
24820
+ Object.assign(context, loadAgentLintContext(context.cwd));
24821
+ return context.agents !== void 0;
24822
+ }
24823
+ async function askAgentsTitle(context, agents, ask) {
24824
+ const title = await ask({
24825
+ default: agentsTitle(context.cwd),
24826
+ message: "AGENTS.md is titled after the file. New title, naming the product",
24827
+ validate: validateTitle
24828
+ });
24829
+ return title !== void 0 && rewriteDocument(context, agents, replaceFirstHeading(agents.text, title));
24830
+ }
24831
+ const SECTION_FIXES = {
24832
+ "authority": {
24833
+ heading: "## Authority: which document wins",
24834
+ question: (cwd) => ({
24835
+ default: authorityDefault(cwd),
24836
+ message: "AGENTS.md has no authority section. Which document wins when sources disagree? (repository path)",
24837
+ validate: validateRepoPath(cwd, "AGENTS.md")
24838
+ }),
24839
+ render: (answer) => `| When the task touches | Authority |\n| --- | --- |\n| Anything this file does not cover | [${answer}](${answer}) |`
24840
+ },
24841
+ "commands": {
24842
+ heading: "## Commands",
24843
+ question: (cwd) => ({
24844
+ default: gateCommand(cwd),
24845
+ message: "AGENTS.md has no commands section. Which command runs the full local gate?"
24846
+ }),
24847
+ render: (answer) => `\`\`\`bash\n${answer}\n\`\`\``
24848
+ },
24849
+ "failures": {
24850
+ heading: "## Failures: what not to do",
24851
+ question: () => ({ message: "AGENTS.md has no failures section. One thing an agent must not do here, from a real past mistake" }),
24852
+ render: (answer) => `- ${answer}`
24853
+ },
24854
+ "orient": {
24855
+ heading: "## Orient before acting",
24856
+ question: (cwd) => ({
24857
+ default: repoDescription(cwd),
24858
+ message: "AGENTS.md has no orient section. What is this repository, in one sentence?"
24859
+ }),
24860
+ render: (answer) => answer
24861
+ },
24862
+ "repository map": {
24863
+ heading: "## Repository map",
24864
+ question: (cwd) => ({
24865
+ default: repositoryMapLine(cwd),
24866
+ message: "AGENTS.md has no repository map. Where does the code live, in one line?"
24867
+ }),
24868
+ render: (answer) => answer
24869
+ }
24870
+ };
24871
+ /** Append each missing section the user writes a line for; returns the labels still missing. */
24872
+ async function askRequiredSections(context, agents, missing, ask) {
24873
+ const remaining = [];
24874
+ for (const label of missing) {
24875
+ const fix = SECTION_FIXES[label];
24876
+ const answer = fix === void 0 ? void 0 : await ask(fix.question(context.cwd));
24877
+ if (!(fix !== void 0 && answer !== void 0 && rewriteDocument(context, agents, appendBlock(agents.text, `${fix.heading}\n\n${fix.render(answer)}`)))) remaining.push(label);
24878
+ }
24879
+ return remaining;
24880
+ }
24881
+ async function askLinkReplacement(context, agents, target, ask) {
24882
+ const suffix = /[#?].*$/.exec(target)?.[0] ?? "";
24883
+ const bare = target.slice(0, target.length - suffix.length);
24884
+ const answer = await ask({
24885
+ default: sameNamePath(context.cwd, bare),
24886
+ message: `AGENTS.md links to missing path ${target}. Path to link instead`,
24887
+ validate: validateRepoPath(context.cwd, "AGENTS.md")
24888
+ });
24889
+ return answer !== void 0 && rewriteDocument(context, agents, agents.text.replaceAll(`](${target})`, () => `](${answer}${suffix})`));
24890
+ }
24891
+ function tableCells(line) {
24892
+ return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
24893
+ }
24894
+ /** The first table under the authority heading: its header cells and the line after its last row. */
24895
+ function authorityTable(lines) {
24896
+ const headingAt = lines.findIndex((line) => /^##\s+.*authorit/i.test(line));
24897
+ if (headingAt === -1) return void 0;
24898
+ let start = -1;
24899
+ for (let index = headingAt + 1; index < lines.length && !/^#{1,2}\s/.test(lines[index] ?? ""); index++) if ((lines[index] ?? "").trimStart().startsWith("|")) {
24900
+ start = index;
24901
+ break;
24902
+ }
24903
+ if (start === -1) return void 0;
24904
+ let end = start;
24905
+ while ((lines[end + 1] ?? "").trimStart().startsWith("|")) end++;
24906
+ return {
24907
+ header: tableCells(lines[start] ?? ""),
24908
+ insertAt: end + 1
24909
+ };
24910
+ }
24911
+ function rowCells(header, document, answer) {
24912
+ const linkAt = Math.max(header.findIndex((cell) => /authority|document|^path$/i.test(cell)), 0);
24913
+ const link = `[${document.relativePath}](${document.relativePath})`;
24914
+ let isAnswerPlaced = answer === void 0;
24915
+ return header.map((cell, index) => {
24916
+ if (index === linkAt) return link;
24917
+ if (/^kind$/i.test(cell)) return document.frontMatter.kind ?? "";
24918
+ if (/status|state/i.test(cell)) return document.frontMatter.status ?? document.frontMatter.state ?? "";
24919
+ if (isAnswerPlaced) return "";
24920
+ isAnswerPlaced = true;
24921
+ return answer ?? "";
24922
+ });
24923
+ }
24924
+ /** Link an orphaned document from a new row in the AGENTS.md authority table. */
24925
+ async function askOrphanRow(context, document, ask) {
24926
+ const agents = context.agents;
24927
+ if (agents === void 0 || document.relativePath.startsWith("docs/archive/")) return false;
24928
+ const lines = agents.text.split("\n");
24929
+ const table = authorityTable(lines);
24930
+ if (table === void 0) return false;
24931
+ const linkAt = Math.max(table.header.findIndex((cell) => /authority|document|^path$/i.test(cell)), 0);
24932
+ const hasFreeColumn = table.header.some((cell, index) => index !== linkAt && !/^kind$|status|state/i.test(cell));
24933
+ const prefix = `${document.relativePath} is not linked from AGENTS.md or another document.`;
24934
+ const heading = firstHeading(document.body);
24935
+ const answer = hasFreeColumn ? await ask({
24936
+ default: heading === void 0 ? void 0 : plainHeading(heading),
24937
+ message: `${prefix} When should an agent read it? (adds a row to the AGENTS.md authority table)`,
24938
+ validate: validateScalar
24939
+ }) : await ask({
24940
+ choices: ["yes", "no"],
24941
+ default: "yes",
24942
+ message: `${prefix} Add it to the AGENTS.md authority table?`
24943
+ });
24944
+ if (answer === void 0 || !hasFreeColumn && answer !== "yes") return false;
24945
+ lines.splice(table.insertAt, 0, `| ${rowCells(table.header, document, hasFreeColumn ? answer : void 0).join(" | ")} |`);
24946
+ return rewriteDocument(context, agents, lines.join("\n"));
24947
+ }
24948
+ //#endregion
24949
+ //#region src/actions/agent/mutate.ts
24950
+ function agentIndex(cwd) {
24951
+ writeDocsIndex(cwd, loadAgentLintContext(cwd).documents);
24952
+ return "docs/README.md";
24953
+ }
24954
+ function archiveDestination(relativeSource) {
24955
+ const underDocs = relativeSource.startsWith("docs/") ? relativeSource.slice(5) : path.posix.basename(relativeSource);
24956
+ return path.posix.join("docs/archive", underDocs);
24957
+ }
24958
+ function withArchivedState(text) {
24959
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
24960
+ if (match?.[1] === void 0) return `---\nstate: retired\n---\n\n${text}`;
24961
+ let replaced = false;
24962
+ const lines = match[1].split("\n").map((line) => {
24963
+ const field = /^state\s*:\s*(.*)$/.exec(line.trim());
24964
+ if (field === null) return line;
24965
+ replaced = true;
24966
+ return field[1]?.trim().replaceAll(/^['"]|['"]$/g, "") === "superseded" ? line : "state: retired";
24967
+ });
24968
+ if (!replaced) lines.push("state: retired");
24969
+ const body = text.slice(match[0].length);
24970
+ return `---\n${lines.join("\n")}\n---\n${body.startsWith("\n") ? "" : "\n"}${body}`;
24971
+ }
24972
+ function agentArchive(cwd, source) {
24973
+ const relativeSource = source.split(path.sep).join("/");
24974
+ const fullSource = path.resolve(cwd, relativeSource);
24975
+ const root = path.resolve(cwd);
24976
+ if (fullSource !== root && !fullSource.startsWith(`${root}${path.sep}`)) throw new Error(`Refusing to archive a path outside the repository: ${source}`);
24977
+ if (!fs.existsSync(fullSource) || !fs.statSync(fullSource).isFile()) throw new Error(`Nothing to archive at ${relativeSource}`);
24978
+ const text = fs.readFileSync(fullSource, "utf8");
24979
+ const parsed = parseFrontMatter(text);
24980
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
24981
+ const successor = parsed.frontMatter.supersededBy;
24982
+ const banner = `> ${parsed.frontMatter.state === "superseded" ? `Superseded${successor === void 0 ? "" : ` by ${successor}`}` : "Retired"} on ${date}. Original path: ${relativeSource}. This document is historical and is not a current instruction.`;
24983
+ const withState = withArchivedState(text);
24984
+ const front = /^(---\r?\n[\s\S]*?\r?\n---\r?\n)/.exec(withState);
24985
+ const archived = front?.[1] === void 0 || withState.includes(banner) ? withState : `${front[1]}\n${banner}\n\n${withState.slice(front[1].length)}`;
24986
+ const destination = archiveDestination(relativeSource);
24987
+ const fullDestination = path.join(cwd, destination);
24988
+ if (path.resolve(fullDestination) === fullSource) throw new Error(`Archive destination is the source file: ${destination}`);
24989
+ if (fs.existsSync(fullDestination)) throw new Error(`Archive destination already exists: ${destination}`);
24990
+ fs.mkdirSync(path.dirname(fullDestination), { recursive: true });
24991
+ fs.writeFileSync(fullDestination, archived.endsWith("\n") ? archived : `${archived}\n`);
24992
+ fs.rmSync(fullSource);
24993
+ writeDocsIndex(cwd, loadAgentLintContext(cwd).documents);
24994
+ return destination;
24995
+ }
24996
+ //#endregion
24997
+ //#region src/actions/agent/fixDocs.ts
24998
+ /**
24999
+ * Ask for the front matter of a document that has none, or for the `kind`
25000
+ * of one whose front matter lacks it. Skipping `kind` leaves the file alone.
25001
+ */
25002
+ async function askFrontMatter(context, document, ask) {
25003
+ const hasMatter = Object.keys(document.frontMatter).length > 0;
25004
+ const kind = await ask({
25005
+ choices: DOCUMENT_KINDS,
25006
+ default: guessKind(document.relativePath),
25007
+ message: `${document.relativePath} has no front matter${hasMatter ? " kind" : ""}. Kind`
25008
+ });
25009
+ if (kind === void 0) return false;
25010
+ const fields = [["kind", kind]];
25011
+ if (!hasMatter) {
25012
+ const state = await ask({
25013
+ choices: DOCUMENT_STATES,
25014
+ default: defaultState(kind),
25015
+ message: `${document.relativePath} state`
25016
+ });
25017
+ if (state !== void 0) fields.push(["state", state]);
25018
+ const date = await ask({
25019
+ default: lastCommitDate(context.cwd, document.relativePath) ?? todayIso(),
25020
+ message: `${document.relativePath} date (created, or last substantive revision)`,
25021
+ validate: validateIsoDate
25022
+ });
25023
+ if (date !== void 0) fields.push(["date", yamlString(date)]);
25024
+ const status = await ask({
25025
+ message: `${document.relativePath} status, one line of prose for the docs index (Enter to skip)`,
25026
+ validate: validateScalar
25027
+ });
25028
+ if (status !== void 0) fields.push(["status", yamlString(status)]);
25029
+ }
25030
+ return setDocumentFields(context, document, fields);
25031
+ }
25032
+ function successorExists(cwd, from) {
25033
+ return (answer) => {
25034
+ const root = path.resolve(cwd);
25035
+ const inside = [path.resolve(cwd, answer), path.resolve(cwd, path.dirname(from), answer)].filter((candidate) => candidate.startsWith(`${root}${path.sep}`));
25036
+ if (inside.length === 0) return "Give a path inside the repository";
25037
+ return inside.some((candidate) => fs.existsSync(candidate)) ? void 0 : `${answer} does not exist`;
25038
+ };
25039
+ }
25040
+ async function askSuccessor(context, document, ask) {
25041
+ const successor = await ask({
25042
+ default: successorGuess(context, document),
25043
+ message: `${document.relativePath} is superseded. Path of the document that replaces it, from the repository root`,
25044
+ validate: successorExists(context.cwd, document.relativePath)
25045
+ });
25046
+ return successor !== void 0 && setDocumentFields(context, document, [["supersededBy", successor]]);
25047
+ }
25048
+ /**
25049
+ * Move a superseded or retired document under docs/archive/. Not offered
25050
+ * while AGENTS.md still cites it, since archiving would break that link.
25051
+ */
25052
+ async function askArchive(context, document, ask) {
25053
+ if (context.agents?.text.includes(document.relativePath) === true || lstatIfPresent$3(path.join(context.cwd, document.relativePath))?.isFile() !== true) return false;
25054
+ const destination = archiveDestination(document.relativePath);
25055
+ if (await ask({
25056
+ choices: ["yes", "no"],
25057
+ default: "yes",
25058
+ message: `${document.relativePath} is ${document.frontMatter.state ?? ""} but not under docs/archive/. Move it to ${destination}? Links to it are not rewritten`
25059
+ }) !== "yes") return false;
25060
+ try {
25061
+ agentArchive(context.cwd, document.relativePath);
25062
+ } catch {
25063
+ return false;
25064
+ }
25065
+ const archived = readAgentDocument(context.cwd, destination);
25066
+ if (archived !== void 0) Object.assign(document, archived);
25067
+ const index = context.documents.find((other) => other.relativePath === "docs/README.md");
25068
+ const freshIndex = readAgentDocument(context.cwd, "docs/README.md");
25069
+ if (index !== void 0 && freshIndex !== void 0) Object.assign(index, freshIndex);
25070
+ return archived !== void 0;
25071
+ }
25072
+ async function askAmends(context, document, commits, ask) {
25073
+ const change = await ask({
25074
+ message: `${document.relativePath} has ${String(commits)} content commits. Describe the correction to record in amends (Enter to skip)`,
25075
+ validate: validateScalar
25076
+ });
25077
+ return change !== void 0 && setDocumentFields(context, document, [["amends", `[{ date: ${yamlString(todayIso())}, change: ${yamlString(change)} }]`]]);
25078
+ }
25079
+ async function askReviewed(context, document, stamp, ask) {
25080
+ return await ask({
25081
+ choices: ["yes", "no"],
25082
+ default: "no",
25083
+ message: `${document.relativePath} was last reviewed ${stamp}. Have you re-verified it? yes sets reviewed to today`
25084
+ }) === "yes" && setDocumentFields(context, document, [["reviewed", yamlString(todayIso())]]);
25085
+ }
25086
+ async function askDecisionState(context, document, ask) {
25087
+ const state = await ask({
25088
+ choices: DOCUMENT_STATES,
25089
+ default: "normative",
25090
+ message: `${document.relativePath} has no state. State`
25091
+ });
25092
+ return state !== void 0 && setDocumentFields(context, document, [["state", state]]);
25093
+ }
25094
+ /** Ask for each missing paper header field; returns the fields still missing. */
25095
+ async function askPaperFields(context, document, missing, ask) {
25096
+ const fields = [];
25097
+ const remaining = [];
25098
+ for (const field of missing) {
25099
+ const fallback = field === "date" ? headerValue(document, "date") ?? lastCommitDate(context.cwd, document.relativePath) : void 0;
25100
+ const answer = await ask({
25101
+ default: field === "version" ? headerValue(document, "version") : fallback,
25102
+ message: `${document.relativePath} header has no ${field}. ${field === "status" ? "Status, one line of prose" : `Paper ${field}`}`,
25103
+ validate: field === "date" ? validateIsoDate : validateScalar
25104
+ });
25105
+ if (answer === void 0) remaining.push(field);
25106
+ else fields.push([field, yamlString(answer)]);
25107
+ }
25108
+ return fields.length > 0 && !setDocumentFields(context, document, fields) ? [...missing] : remaining;
25109
+ }
25110
+ //#endregion
25111
+ //#region src/actions/agent/ruleSupport.ts
24439
25112
  function finding(message) {
24440
25113
  return { diagnostics: [{ message }] };
24441
25114
  }
24442
25115
  function findings(messages) {
24443
25116
  return messages.length === 0 ? {} : { diagnostics: messages.map((message) => ({ message })) };
24444
25117
  }
25118
+ function withFixed(outcome, fixedCount) {
25119
+ return fixedCount > 0 ? {
25120
+ ...outcome,
25121
+ fixedCount
25122
+ } : outcome;
25123
+ }
24445
25124
  function documentAt(context, relativePath) {
24446
25125
  return context.documents.find((document) => document.relativePath === relativePath);
24447
25126
  }
@@ -24458,6 +25137,266 @@ function docLinkExists(cwd, from, target) {
24458
25137
  const bare = target.split("#", 1)[0]?.split("?", 1)[0] ?? "";
24459
25138
  return bare.length === 0 || fs.existsSync(path.resolve(cwd, bare)) || linkExists(cwd, from, target);
24460
25139
  }
25140
+ function readLinkedDocument(context, target) {
25141
+ return documentAt(context, path.posix.normalize(target.replace(/^\.\//, "")));
25142
+ }
25143
+ //#endregion
25144
+ //#region src/actions/agent/docRules.ts
25145
+ const STALE_DAYS = 180;
25146
+ const RUNBOOK_STALE_DAYS = 90;
25147
+ function daysSince(isoDate, now) {
25148
+ const parsed = Date.parse(isoDate);
25149
+ return Number.isNaN(parsed) ? void 0 : (now - parsed) / 864e5;
25150
+ }
25151
+ function contentCommitCount(cwd, relativePath) {
25152
+ const result = spawnSync$1("git", [
25153
+ "rev-list",
25154
+ "--count",
25155
+ "HEAD",
25156
+ "--",
25157
+ relativePath
25158
+ ], {
25159
+ cwd,
25160
+ encoding: "utf8"
25161
+ });
25162
+ if (result.status !== 0) return void 0;
25163
+ const count = Number(result.stdout.trim());
25164
+ return Number.isFinite(count) ? count : void 0;
25165
+ }
25166
+ function decisionScheme(base) {
25167
+ if (/^\d{8}-/.test(base)) return { scheme: "dated" };
25168
+ const prefixed = /^[A-Za-z]\w*-D(\d+)/.exec(base)?.[1];
25169
+ if (prefixed !== void 0) return {
25170
+ id: Number(prefixed),
25171
+ scheme: "prefixed"
25172
+ };
25173
+ const adr = /^ADR-(\d+)/i.exec(base)?.[1];
25174
+ if (adr !== void 0) return {
25175
+ id: Number(adr),
25176
+ scheme: "adr"
25177
+ };
25178
+ const numbered = /^(\d+)-/.exec(base)?.[1];
25179
+ return numbered === void 0 ? { scheme: "other" } : {
25180
+ id: Number(numbered),
25181
+ scheme: "numbered"
25182
+ };
25183
+ }
25184
+ function decisionIdMessages(schemes, ids) {
25185
+ const messages = [];
25186
+ if (schemes.size > 1) messages.push(`docs/decisions uses more than one naming scheme: ${[...schemes].toSorted().join(", ")}`);
25187
+ const unique = new Set(ids);
25188
+ if (unique.size !== ids.length) messages.push("docs/decisions ids are not unique");
25189
+ if (ids.length > 1) {
25190
+ const sorted = [...unique].toSorted((left, right) => left - right);
25191
+ if ((sorted.at(-1) ?? 0) - (sorted[0] ?? 0) + 1 !== sorted.length) messages.push("docs/decisions ids are not contiguous");
25192
+ }
25193
+ return messages;
25194
+ }
25195
+ function isLinked(context, relativePath) {
25196
+ const name = path.posix.basename(relativePath);
25197
+ return context.documents.some((other) => other.relativePath !== relativePath && other.relativePath !== "docs/README.md" && (other.text.includes(relativePath) || other.text.includes(name))) || (context.agents?.text.includes(relativePath) ?? false) || (context.agents?.text.includes(name) ?? false);
25198
+ }
25199
+ function missingPaperFields(document) {
25200
+ const matter = Object.entries(document.frontMatter).map(([key, value]) => `${key}: ${value}`).join("\n");
25201
+ const header = `${document.text}\n${matter}`;
25202
+ return [
25203
+ "version",
25204
+ "status",
25205
+ "date"
25206
+ ].filter((field) => {
25207
+ return !new RegExp(String.raw`\b${field}\b`, "i").test(header);
25208
+ });
25209
+ }
25210
+ const DOC_LINT_RULES = [
25211
+ {
25212
+ check: async (context, rule) => {
25213
+ let fixedCount = 0;
25214
+ const messages = [];
25215
+ for (const document of context.documents) {
25216
+ if (!/^(?:docs|papers|specs)\//.test(document.relativePath) || document.relativePath.endsWith("/README.md")) continue;
25217
+ const hasMatter = Object.keys(document.frontMatter).length > 0;
25218
+ if (hasMatter && document.frontMatter.kind !== void 0) continue;
25219
+ const kind = folderKind(document.relativePath);
25220
+ if (rule.ask === void 0 ? kind !== void 0 && rule.fix && setDocumentFields(context, document, [["kind", kind]]) : await askFrontMatter(context, document, rule.ask)) fixedCount += 1;
25221
+ else messages.push(`${document.relativePath} is missing front matter${hasMatter ? " kind" : ""}`);
25222
+ }
25223
+ return withFixed(findings(messages), fixedCount);
25224
+ },
25225
+ defaultLevel: "warn",
25226
+ description: "Markdown under docs/, papers/, and specs/ has front matter",
25227
+ fixable: true,
25228
+ id: "docs.front-matter",
25229
+ interactive: true
25230
+ },
25231
+ {
25232
+ check: async (context, rule) => {
25233
+ let fixedCount = 0;
25234
+ const messages = [];
25235
+ for (const document of context.documents) {
25236
+ const state = document.frontMatter.state;
25237
+ if (state !== "superseded" && state !== "retired") continue;
25238
+ const successor = document.frontMatter.supersededBy;
25239
+ if (state === "superseded" && (successor === void 0 || !docLinkExists(context.cwd, document.relativePath, successor))) {
25240
+ if (rule.ask !== void 0 && await askSuccessor(context, document, rule.ask)) fixedCount += 1;
25241
+ else messages.push(`${document.relativePath} is superseded without a resolvable supersededBy`);
25242
+ }
25243
+ if (document.relativePath.startsWith("docs/archive/")) continue;
25244
+ const original = document.relativePath;
25245
+ if (rule.ask !== void 0 && await askArchive(context, document, rule.ask)) fixedCount += 1;
25246
+ else messages.push(`${original} has state ${state} but is not under docs/archive/`);
25247
+ }
25248
+ return withFixed(findings(messages), fixedCount);
25249
+ },
25250
+ defaultLevel: "warn",
25251
+ description: "Superseded and retired documents live under docs/archive/ and name a successor",
25252
+ id: "docs.superseded-archived",
25253
+ interactive: true
25254
+ },
25255
+ {
25256
+ check: async (context, rule) => {
25257
+ let fixedCount = 0;
25258
+ const messages = [];
25259
+ for (const document of context.documents) {
25260
+ if (!document.relativePath.startsWith("docs/evidence/") || document.frontMatter.amends !== void 0) continue;
25261
+ const commits = contentCommitCount(context.cwd, document.relativePath);
25262
+ if (commits === void 0 || commits <= 1) continue;
25263
+ if (rule.ask !== void 0 && await askAmends(context, document, commits, rule.ask)) fixedCount += 1;
25264
+ else messages.push(`${document.relativePath} has ${String(commits)} content commits; evidence should stay immutable or set amends`);
25265
+ }
25266
+ return withFixed(findings(messages), fixedCount);
25267
+ },
25268
+ defaultLevel: "warn",
25269
+ description: "docs/evidence files keep a single content commit unless they declare amends",
25270
+ id: "docs.evidence-immutable",
25271
+ interactive: true
25272
+ },
25273
+ {
25274
+ check: async (context, rule) => {
25275
+ const now = Date.now();
25276
+ let fixedCount = 0;
25277
+ const messages = [];
25278
+ for (const document of context.documents) {
25279
+ if (/^docs\/(?:evidence|decisions|archive)\//.test(document.relativePath)) continue;
25280
+ const state = document.frontMatter.state;
25281
+ if (state === "superseded" || state === "retired") continue;
25282
+ const stamp = document.frontMatter.reviewed ?? document.frontMatter.date;
25283
+ const age = stamp === void 0 ? void 0 : daysSince(stamp, now);
25284
+ if (stamp === void 0 || age === void 0) continue;
25285
+ const limit = document.relativePath.includes("/runbooks/") ? RUNBOOK_STALE_DAYS : STALE_DAYS;
25286
+ if (age <= limit) continue;
25287
+ if (rule.ask !== void 0 && await askReviewed(context, document, stamp, rule.ask)) fixedCount += 1;
25288
+ else messages.push(`${document.relativePath} was last reviewed ${stamp}, older than ${String(limit)} days`);
25289
+ }
25290
+ return withFixed(findings(messages), fixedCount);
25291
+ },
25292
+ defaultLevel: "warn",
25293
+ description: "reviewed or date front matter is within 180 days (runbooks 90)",
25294
+ id: "docs.stale",
25295
+ interactive: true
25296
+ },
25297
+ {
25298
+ check: async (context, rule) => {
25299
+ let fixedCount = 0;
25300
+ const messages = [];
25301
+ for (const document of context.documents) {
25302
+ if (!document.relativePath.startsWith("docs/") || document.relativePath === "docs/README.md" || isLinked(context, document.relativePath)) continue;
25303
+ if (rule.ask !== void 0 && await askOrphanRow(context, document, rule.ask)) fixedCount += 1;
25304
+ else messages.push(`${document.relativePath} is not linked from AGENTS.md or another document`);
25305
+ }
25306
+ return withFixed(findings(messages), fixedCount);
25307
+ },
25308
+ defaultLevel: "warn",
25309
+ description: "docs/ files are linked from AGENTS.md or another document",
25310
+ id: "docs.orphan",
25311
+ interactive: true
25312
+ },
25313
+ {
25314
+ check: async (context, rule) => {
25315
+ const decisions = context.documents.filter((document) => document.relativePath.startsWith("docs/decisions/") && !document.relativePath.endsWith("/README.md"));
25316
+ if (decisions.length === 0) return {};
25317
+ const schemes = /* @__PURE__ */ new Set();
25318
+ const ids = [];
25319
+ let fixedCount = 0;
25320
+ const messages = [];
25321
+ for (const document of decisions) {
25322
+ const { id, scheme } = decisionScheme(path.posix.basename(document.relativePath));
25323
+ schemes.add(scheme);
25324
+ if (id !== void 0) ids.push(id);
25325
+ if (document.frontMatter.state !== void 0) continue;
25326
+ if (rule.ask !== void 0 && await askDecisionState(context, document, rule.ask)) fixedCount += 1;
25327
+ else messages.push(`${document.relativePath} has no state`);
25328
+ }
25329
+ return withFixed(findings([...messages, ...decisionIdMessages(schemes, ids)]), fixedCount);
25330
+ },
25331
+ defaultLevel: "warn",
25332
+ description: "Decision records share one id scheme, with unique contiguous ids and a state",
25333
+ id: "decisions.naming",
25334
+ interactive: true
25335
+ },
25336
+ {
25337
+ check: async (context, rule) => {
25338
+ let fixedCount = 0;
25339
+ const messages = [];
25340
+ for (const document of context.documents) {
25341
+ if (!document.relativePath.startsWith("papers/") || document.relativePath.endsWith("/README.md")) continue;
25342
+ const missing = missingPaperFields(document);
25343
+ if (missing.length === 0) continue;
25344
+ const remaining = rule.ask === void 0 ? missing : await askPaperFields(context, document, missing, rule.ask);
25345
+ fixedCount += missing.length - remaining.length;
25346
+ if (remaining.length > 0) messages.push(`${document.relativePath} header is missing ${remaining.join(", ")}`);
25347
+ }
25348
+ return withFixed(findings(messages), fixedCount);
25349
+ },
25350
+ defaultLevel: "warn",
25351
+ description: "Papers carry version, status, and date consistently with the header",
25352
+ id: "papers.header",
25353
+ interactive: true
25354
+ }
25355
+ ];
25356
+ /** Runs last, so the index reflects front matter every earlier fix wrote. */
25357
+ const DOCS_INDEX_RULE = {
25358
+ check: (context, rule) => {
25359
+ const expected = renderDocsIndex(context.documents);
25360
+ if (documentAt(context, "docs/README.md")?.text === expected) return {};
25361
+ if (context.documents.every((document) => !document.relativePath.startsWith("docs/"))) return {};
25362
+ if (rule.fix) {
25363
+ writeDocsIndex(context.cwd, context.documents);
25364
+ return { fixedCount: 1 };
25365
+ }
25366
+ return finding("docs/README.md does not match the index generated from front matter");
25367
+ },
25368
+ defaultLevel: "warn",
25369
+ description: "docs/README.md matches the index generated from front matter",
25370
+ fixable: true,
25371
+ id: "docs.index-current"
25372
+ };
25373
+ //#endregion
25374
+ //#region src/actions/agent/rules.ts
25375
+ const SIZE_BUDGET = 200;
25376
+ const REQUIRED_SECTIONS = [
25377
+ {
25378
+ label: "orient",
25379
+ pattern: /orient|what this|overview|about this/i
25380
+ },
25381
+ {
25382
+ label: "authority",
25383
+ pattern: /authorit/i
25384
+ },
25385
+ {
25386
+ label: "repository map",
25387
+ pattern: /repository map|repo map|\blayout\b|\bpackages\b/i
25388
+ },
25389
+ {
25390
+ label: "commands",
25391
+ pattern: /command/i
25392
+ },
25393
+ {
25394
+ label: "failures",
25395
+ pattern: /fail|troubleshoot|what not to do|pitfall/i
25396
+ }
25397
+ ];
25398
+ /** Each adapter fix may expose the next problem, such as a moved import that still restates. */
25399
+ const ADAPTER_FIX_PASSES = 3;
24461
25400
  function cellPath(cell) {
24462
25401
  return (/\[[^\]]*]\(([^)]+)\)/.exec(cell)?.[1] ?? cell).replaceAll(/[`[\]()]/g, " ").trim().split(/\s+/).find((part) => part.includes("/") || part.endsWith(".md"));
24463
25402
  }
@@ -24482,31 +25421,9 @@ function authorityRows(section) {
24482
25421
  }
24483
25422
  return found;
24484
25423
  }
24485
- function daysSince(isoDate, now) {
24486
- const parsed = Date.parse(isoDate);
24487
- return Number.isNaN(parsed) ? void 0 : (now - parsed) / 864e5;
24488
- }
24489
25424
  function mismatchedAuthorityKind(kind, actual) {
24490
25425
  return kind !== void 0 && kind.length > 0 && actual !== void 0 && actual !== kind;
24491
25426
  }
24492
- function contentCommitCount(cwd, relativePath) {
24493
- const result = spawnSync$1("git", [
24494
- "rev-list",
24495
- "--count",
24496
- "HEAD",
24497
- "--",
24498
- relativePath
24499
- ], {
24500
- cwd,
24501
- encoding: "utf8"
24502
- });
24503
- if (result.status !== 0) return void 0;
24504
- const count = Number(result.stdout.trim());
24505
- return Number.isFinite(count) ? count : void 0;
24506
- }
24507
- function inferredFrontMatterKind(relativePath) {
24508
- return FRONT_MATTER_KINDS.find((entry) => entry.pattern.test(relativePath))?.kind;
24509
- }
24510
25427
  function resolvesToAgentsMd(cwd, from, target) {
24511
25428
  const bare = target.split("#", 1)[0]?.split("?", 1)[0] ?? "";
24512
25429
  return bare.length > 0 && !/^(?:https?:|mailto:)/.test(bare) && path.resolve(cwd, path.dirname(from), bare) === path.resolve(cwd, "AGENTS.md");
@@ -24528,310 +25445,192 @@ function restatesAgents(adapterText, agentsText) {
24528
25445
  function adapterFinding(cwd, relativePath, agentsText) {
24529
25446
  const fullPath = path.join(cwd, relativePath);
24530
25447
  if (!fs.existsSync(fullPath)) return void 0;
24531
- if (fs.lstatSync(fullPath).isSymbolicLink()) return path.basename(fs.readlinkSync(fullPath)) === "AGENTS.md" ? void 0 : `${relativePath} symlink does not point at AGENTS.md (inverted-symlink)`;
25448
+ if (fs.lstatSync(fullPath).isSymbolicLink()) return path.basename(fs.readlinkSync(fullPath)) === "AGENTS.md" ? void 0 : {
25449
+ message: `${relativePath} symlink does not point at AGENTS.md (inverted-symlink)`,
25450
+ problem: "symlink"
25451
+ };
24532
25452
  const text = fs.readFileSync(fullPath, "utf8");
24533
- if (agentsText !== void 0 && text === agentsText) return `${relativePath} duplicates AGENTS.md (duplicate)`;
25453
+ if (agentsText !== void 0 && text === agentsText) return {
25454
+ message: `${relativePath} duplicates AGENTS.md (duplicate)`,
25455
+ problem: "duplicate"
25456
+ };
24534
25457
  if (relativePath.endsWith("copilot-instructions.md")) {
24535
- if (!(hasCopilotAgentsReference(text) || markdownLinkTargets(text).some((target) => resolvesToAgentsMd(cwd, relativePath, target)))) return `${relativePath} does not link to AGENTS.md; use a Markdown link to ../AGENTS.md or a symlink`;
25458
+ if (!(hasCopilotAgentsReference(text) || markdownLinkTargets(text).some((target) => resolvesToAgentsMd(cwd, relativePath, target)))) return {
25459
+ message: `${relativePath} does not link to AGENTS.md; use a Markdown link to ../AGENTS.md or a symlink`,
25460
+ problem: "copilot-link"
25461
+ };
24536
25462
  } else {
24537
25463
  const placement = claudeAgentsImportPlacement(text);
24538
- if (placement === "later") return `${relativePath} mentions @AGENTS.md but the import is not the first line (pointer-not-import)`;
24539
- if (placement === "absent") return `${relativePath} is a divergent adapter; start with an @AGENTS.md import or use a symlink`;
25464
+ if (placement === "later") return {
25465
+ message: `${relativePath} mentions @AGENTS.md but the import is not the first line (pointer-not-import)`,
25466
+ problem: "pointer"
25467
+ };
25468
+ if (placement === "absent") return {
25469
+ message: `${relativePath} is a divergent adapter; start with an @AGENTS.md import or use a symlink`,
25470
+ problem: "divergent"
25471
+ };
25472
+ }
25473
+ return agentsText !== void 0 && restatesAgents(text, agentsText) ? {
25474
+ message: `${relativePath} duplicates AGENTS.md (duplicate)`,
25475
+ problem: "restates"
25476
+ } : void 0;
25477
+ }
25478
+ async function checkAdapter(context, relativePath, rule) {
25479
+ let fixedCount = 0;
25480
+ for (let pass = 0; pass < ADAPTER_FIX_PASSES; pass++) {
25481
+ const found = adapterFinding(context.cwd, relativePath, context.agents?.text);
25482
+ if (found === void 0) break;
25483
+ if (!(rule.fix && fixAdapter(context.cwd, relativePath, found.problem) || rule.ask !== void 0 && await askAdapter(context.cwd, relativePath, found.problem, rule.ask))) return {
25484
+ fixedCount,
25485
+ message: found.message
25486
+ };
25487
+ fixedCount += 1;
24540
25488
  }
24541
- return agentsText !== void 0 && restatesAgents(text, agentsText) ? `${relativePath} duplicates AGENTS.md (duplicate)` : void 0;
25489
+ return {
25490
+ fixedCount,
25491
+ message: void 0
25492
+ };
24542
25493
  }
24543
25494
  const AGENT_LINT_RULES = [
24544
- {
24545
- check: (context) => context.agents === void 0 ? finding("AGENTS.md is missing at the repository root") : {},
24546
- defaultLevel: "error",
24547
- description: "AGENTS.md exists at the repository root",
24548
- id: "agents.file-present"
24549
- },
24550
- {
24551
- check: (context) => {
24552
- const agentsStat = fs.existsSync(path.join(context.cwd, "AGENTS.md")) ? fs.lstatSync(path.join(context.cwd, "AGENTS.md")) : void 0;
24553
- const messages = [];
24554
- for (const relativePath of ADAPTER_PATHS) {
24555
- if (agentsStat?.isSymbolicLink() === true) {
24556
- if (path.basename(fs.readlinkSync(path.join(context.cwd, "AGENTS.md"))) === path.basename(relativePath)) messages.push(`AGENTS.md is a symlink to ${relativePath} (inverted-symlink)`);
24557
- }
24558
- const message = adapterFinding(context.cwd, relativePath, context.agents?.text);
24559
- if (message !== void 0) messages.push(message);
24560
- }
24561
- return findings(messages);
24562
- },
24563
- defaultLevel: "warn",
24564
- description: "Tool adapters lead with an AGENTS.md import or link, then tool-specific notes",
24565
- id: "agents.adapter-thin"
24566
- },
24567
- {
24568
- check: (context) => {
24569
- const heading = context.agents === void 0 ? void 0 : firstHeading(context.agents.text);
24570
- if (heading === void 0) return {};
24571
- return /^agents\.md$/i.test(heading) ? finding("AGENTS.md H1 names the file instead of the product") : {};
24572
- },
24573
- defaultLevel: "warn",
24574
- description: "The AGENTS.md H1 names the product, not the filename",
24575
- id: "agents.h1-not-filename"
24576
- },
24577
- {
24578
- check: (context) => {
24579
- if (context.agents === void 0) return {};
24580
- const present = headings(context.agents.text);
24581
- const missing = REQUIRED_SECTIONS.filter((section) => present.every((heading) => !section.pattern.test(heading)));
24582
- return missing.length === 0 ? {} : finding(`AGENTS.md is missing sections: ${missing.map((section) => section.label).join(", ")}`);
24583
- },
24584
- defaultLevel: "warn",
24585
- description: "AGENTS.md has orient, authority, repository map, commands, and failures sections",
24586
- id: "agents.required-sections"
24587
- },
24588
- {
24589
- check: (context) => {
24590
- if (context.agents === void 0) return {};
24591
- const lines = context.agents.text.split("\n").length;
24592
- return lines > SIZE_BUDGET ? finding(`AGENTS.md is ${String(lines)} lines; budget is ${String(SIZE_BUDGET)}`) : {};
24593
- },
24594
- defaultLevel: "warn",
24595
- description: "AGENTS.md stays within the line budget (default 200)",
24596
- id: "agents.size-budget"
24597
- },
24598
- {
24599
- check: (context) => {
24600
- if (context.agents === void 0) return {};
24601
- return findings(markdownLinks(context.agents.text).filter((target) => !linkExists(context.cwd, "AGENTS.md", target)).map((target) => `AGENTS.md links to missing path ${target}`));
24602
- },
24603
- defaultLevel: "error",
24604
- description: "Repository paths and relative links in AGENTS.md exist",
24605
- id: "agents.links-resolve"
24606
- },
24607
- {
24608
- check: (context) => {
24609
- const messages = [];
24610
- for (const document of context.documents) if (/\/(?:Users|home)\//.test(document.text)) messages.push(`${document.relativePath} contains an absolute home-directory path`);
24611
- return findings(messages);
24612
- },
24613
- defaultLevel: "warn",
24614
- description: "Committed instruction files do not contain /Users or /home paths",
24615
- id: "agents.no-absolute-paths"
24616
- },
24617
- {
24618
- check: (context) => {
24619
- if (context.agents === void 0) return {};
24620
- return /\b(?:claimed by|assigned to|in-flight|in flight)\b|\b(?:feature|fix|hotfix)\/[a-z0-9-]+/i.test(context.agents.text) ? finding("AGENTS.md contains live task, branch, or claim state") : {};
24621
- },
24622
- defaultLevel: "warn",
24623
- description: "AGENTS.md does not carry task assignments, branch names, or claim state",
24624
- id: "agents.no-live-state"
24625
- },
24626
- {
24627
- check: (context) => {
24628
- if (context.agents === void 0) return {};
24629
- const rootLines = new Set(context.agents.text.split("\n").map((line) => line.trim()).filter((line) => line.length > 40));
24630
- const messages = [];
24631
- for (const document of context.nestedAgents) if (document.text.split("\n").filter((line) => rootLines.has(line.trim())).length >= 8) messages.push(`${document.relativePath} restates the root AGENTS.md instead of a package delta`);
24632
- return findings(messages);
24633
- },
24634
- defaultLevel: "warn",
24635
- description: "Package AGENTS.md files add a delta and do not restate the root",
24636
- id: "agents.nested-delta-only"
24637
- },
24638
- {
24639
- check: (context) => {
24640
- if (context.agents === void 0) return {};
24641
- const section = context.agents.text.split(/^##\s+/m).find((part) => /authorit/i.test(part.split("\n", 1)[0] ?? ""));
24642
- if (section === void 0) return {};
24643
- const messages = [];
24644
- for (const row of authorityRows(section)) {
24645
- if (!linkExists(context.cwd, "AGENTS.md", row.target)) {
24646
- messages.push(`Authority row ${row.target} does not exist`);
24647
- continue;
24648
- }
24649
- const actual = readLinkedDocument(context, row.target)?.frontMatter.kind?.toLowerCase();
24650
- if (mismatchedAuthorityKind(row.kind, actual)) messages.push(`Authority row ${row.target} claims kind ${row.kind ?? ""} but front matter says ${actual ?? ""}`);
24651
- }
24652
- return findings(messages);
25495
+ ...[
25496
+ {
25497
+ check: async (context, rule) => {
25498
+ if (context.agents !== void 0) return {};
25499
+ return rule.ask !== void 0 && await askAgentsFile(context, rule.ask) ? { fixedCount: 1 } : finding("AGENTS.md is missing at the repository root");
25500
+ },
25501
+ defaultLevel: "error",
25502
+ description: "AGENTS.md exists at the repository root",
25503
+ id: "agents.file-present",
25504
+ interactive: true
24653
25505
  },
24654
- defaultLevel: "warn",
24655
- description: "Authority-table rows point at files whose front-matter kind matches",
24656
- id: "agents.authority-rows-resolve"
24657
- },
24658
- {
24659
- check: (context, rule) => {
24660
- let fixedCount = 0;
24661
- const messages = [];
24662
- for (const document of context.documents) {
24663
- if (!/^(?:docs|papers|specs)\//.test(document.relativePath) || document.relativePath.endsWith("/README.md")) continue;
24664
- const hasMatter = Object.keys(document.frontMatter).length > 0;
24665
- if (hasMatter && document.frontMatter.kind !== void 0) continue;
24666
- const kind = inferredFrontMatterKind(document.relativePath);
24667
- if (kind !== void 0 && !hasMatter && rule.fix) {
24668
- const next = `---\nkind: ${kind}\n---\n\n${document.text}`;
24669
- fs.writeFileSync(path.join(context.cwd, document.relativePath), next);
24670
- document.text = next;
24671
- document.frontMatter = { kind };
24672
- document.body = document.text;
24673
- fixedCount += 1;
24674
- continue;
25506
+ {
25507
+ check: async (context, rule) => {
25508
+ const agentsStat = fs.existsSync(path.join(context.cwd, "AGENTS.md")) ? fs.lstatSync(path.join(context.cwd, "AGENTS.md")) : void 0;
25509
+ let fixedCount = 0;
25510
+ const messages = [];
25511
+ for (const relativePath of ADAPTER_PATHS) {
25512
+ if (agentsStat?.isSymbolicLink() === true) {
25513
+ if (path.basename(fs.readlinkSync(path.join(context.cwd, "AGENTS.md"))) === path.basename(relativePath)) messages.push(`AGENTS.md is a symlink to ${relativePath} (inverted-symlink)`);
25514
+ }
25515
+ const outcome = await checkAdapter(context, relativePath, rule);
25516
+ fixedCount += outcome.fixedCount;
25517
+ if (outcome.message !== void 0) messages.push(outcome.message);
24675
25518
  }
24676
- messages.push(`${document.relativePath} is missing front matter${hasMatter ? " kind" : ""}`);
24677
- }
24678
- return fixedCount > 0 ? {
24679
- ...findings(messages),
24680
- fixedCount
24681
- } : findings(messages);
25519
+ return withFixed(findings(messages), fixedCount);
25520
+ },
25521
+ defaultLevel: "warn",
25522
+ description: "Tool adapters lead with an AGENTS.md import or link, then tool-specific notes",
25523
+ fixable: true,
25524
+ id: "agents.adapter-thin",
25525
+ interactive: true
24682
25526
  },
24683
- defaultLevel: "warn",
24684
- description: "Markdown under docs/, papers/, and specs/ has front matter",
24685
- fixable: true,
24686
- id: "docs.front-matter"
24687
- },
24688
- {
24689
- check: (context, rule) => {
24690
- const expected = renderDocsIndex(context.documents);
24691
- if (documentAt(context, "docs/README.md")?.text === expected) return {};
24692
- if (context.documents.every((document) => !document.relativePath.startsWith("docs/"))) return {};
24693
- if (rule.fix) {
24694
- writeDocsIndex(context.cwd, context.documents);
24695
- return { fixedCount: 1 };
24696
- }
24697
- return finding("docs/README.md does not match the index generated from front matter");
25527
+ {
25528
+ check: async (context, rule) => {
25529
+ const agents = context.agents;
25530
+ const heading = agents === void 0 ? void 0 : firstHeading(agents.text);
25531
+ if (agents === void 0 || heading === void 0 || !/^agents\.md$/i.test(heading)) return {};
25532
+ return rule.ask !== void 0 && await askAgentsTitle(context, agents, rule.ask) ? { fixedCount: 1 } : finding("AGENTS.md H1 names the file instead of the product");
25533
+ },
25534
+ defaultLevel: "warn",
25535
+ description: "The AGENTS.md H1 names the product, not the filename",
25536
+ id: "agents.h1-not-filename",
25537
+ interactive: true
24698
25538
  },
24699
- defaultLevel: "warn",
24700
- description: "docs/README.md matches the index generated from front matter",
24701
- fixable: true,
24702
- id: "docs.index-current"
24703
- },
24704
- {
24705
- check: (context) => {
24706
- const messages = [];
24707
- for (const document of context.documents) {
24708
- const state = document.frontMatter.state;
24709
- if (state !== "superseded" && state !== "retired") continue;
24710
- if (!document.relativePath.startsWith("docs/archive/")) messages.push(`${document.relativePath} has state ${state} but is not under docs/archive/`);
24711
- if (state !== "superseded") continue;
24712
- const successor = document.frontMatter.supersededBy;
24713
- if (successor === void 0 || !docLinkExists(context.cwd, document.relativePath, successor)) messages.push(`${document.relativePath} is superseded without a resolvable supersededBy`);
24714
- }
24715
- return findings(messages);
25539
+ {
25540
+ check: async (context, rule) => {
25541
+ const agents = context.agents;
25542
+ if (agents === void 0) return {};
25543
+ const present = headings(agents.text);
25544
+ const missing = REQUIRED_SECTIONS.filter((section) => present.every((heading) => !section.pattern.test(heading))).map((section) => section.label);
25545
+ if (missing.length === 0) return {};
25546
+ const remaining = rule.ask === void 0 ? missing : await askRequiredSections(context, agents, missing, rule.ask);
25547
+ return withFixed(remaining.length === 0 ? {} : finding(`AGENTS.md is missing sections: ${remaining.join(", ")}`), missing.length - remaining.length);
25548
+ },
25549
+ defaultLevel: "warn",
25550
+ description: "AGENTS.md has orient, authority, repository map, commands, and failures sections",
25551
+ id: "agents.required-sections",
25552
+ interactive: true
24716
25553
  },
24717
- defaultLevel: "warn",
24718
- description: "Superseded and retired documents live under docs/archive/ and name a successor",
24719
- id: "docs.superseded-archived"
24720
- },
24721
- {
24722
- check: (context) => {
24723
- const messages = [];
24724
- for (const document of context.documents) {
24725
- if (!document.relativePath.startsWith("docs/evidence/") || document.frontMatter.amends !== void 0) continue;
24726
- const commits = contentCommitCount(context.cwd, document.relativePath);
24727
- if (commits !== void 0 && commits > 1) messages.push(`${document.relativePath} has ${String(commits)} content commits; evidence should stay immutable or set amends`);
24728
- }
24729
- return findings(messages);
25554
+ {
25555
+ check: (context) => {
25556
+ if (context.agents === void 0) return {};
25557
+ const lines = context.agents.text.split("\n").length;
25558
+ return lines > SIZE_BUDGET ? finding(`AGENTS.md is ${String(lines)} lines; budget is ${String(SIZE_BUDGET)}`) : {};
25559
+ },
25560
+ defaultLevel: "warn",
25561
+ description: "AGENTS.md stays within the line budget (default 200)",
25562
+ id: "agents.size-budget"
24730
25563
  },
24731
- defaultLevel: "warn",
24732
- description: "docs/evidence files keep a single content commit unless they declare amends",
24733
- id: "docs.evidence-immutable"
24734
- },
24735
- {
24736
- check: (context) => {
24737
- const now = Date.now();
24738
- const messages = [];
24739
- for (const document of context.documents) {
24740
- if (document.relativePath.startsWith("docs/evidence/") || document.relativePath.startsWith("docs/decisions/") || document.relativePath.startsWith("docs/archive/")) continue;
24741
- const state = document.frontMatter.state;
24742
- if (state === "superseded" || state === "retired") continue;
24743
- const stamp = document.frontMatter.reviewed ?? document.frontMatter.date;
24744
- if (stamp === void 0) continue;
24745
- const age = daysSince(stamp, now);
24746
- if (age === void 0) continue;
24747
- const limit = document.relativePath.includes("/runbooks/") ? RUNBOOK_STALE_DAYS : STALE_DAYS;
24748
- if (age > limit) messages.push(`${document.relativePath} was last reviewed ${stamp}, older than ${String(limit)} days`);
24749
- }
24750
- return findings(messages);
25564
+ {
25565
+ check: async (context, rule) => {
25566
+ const agents = context.agents;
25567
+ if (agents === void 0) return {};
25568
+ const missing = markdownLinks(agents.text).filter((target) => !linkExists(context.cwd, "AGENTS.md", target));
25569
+ const fixed = /* @__PURE__ */ new Set();
25570
+ const targets = [...new Set(missing)];
25571
+ for (const target of targets) if (rule.ask !== void 0 && await askLinkReplacement(context, agents, target, rule.ask)) fixed.add(target);
25572
+ return withFixed(findings(missing.filter((target) => !fixed.has(target)).map((target) => `AGENTS.md links to missing path ${target}`)), fixed.size);
25573
+ },
25574
+ defaultLevel: "error",
25575
+ description: "Repository paths and relative links in AGENTS.md exist",
25576
+ id: "agents.links-resolve",
25577
+ interactive: true
24751
25578
  },
24752
- defaultLevel: "warn",
24753
- description: "reviewed or date front matter is within 180 days (runbooks 90)",
24754
- id: "docs.stale"
24755
- },
24756
- {
24757
- check: (context) => {
24758
- const messages = [];
24759
- for (const document of context.documents) {
24760
- if (!document.relativePath.startsWith("docs/") || document.relativePath === "docs/README.md") continue;
24761
- const name = path.posix.basename(document.relativePath);
24762
- if (!(context.documents.some((other) => other.relativePath !== document.relativePath && other.relativePath !== "docs/README.md" && (other.text.includes(document.relativePath) || other.text.includes(name))) || (context.agents?.text.includes(document.relativePath) ?? false) || (context.agents?.text.includes(name) ?? false))) messages.push(`${document.relativePath} is not linked from AGENTS.md or another document`);
24763
- }
24764
- return findings(messages);
25579
+ {
25580
+ check: (context) => {
25581
+ const messages = [];
25582
+ for (const document of context.documents) if (/\/(?:Users|home)\//.test(document.text)) messages.push(`${document.relativePath} contains an absolute home-directory path`);
25583
+ return findings(messages);
25584
+ },
25585
+ defaultLevel: "warn",
25586
+ description: "Committed instruction files do not contain /Users or /home paths",
25587
+ id: "agents.no-absolute-paths"
24765
25588
  },
24766
- defaultLevel: "warn",
24767
- description: "docs/ files are linked from AGENTS.md or another document",
24768
- id: "docs.orphan"
24769
- },
24770
- {
24771
- check: (context) => {
24772
- const decisions = context.documents.filter((document) => document.relativePath.startsWith("docs/decisions/") && !document.relativePath.endsWith("/README.md"));
24773
- if (decisions.length === 0) return {};
24774
- const schemes = /* @__PURE__ */ new Set();
24775
- const ids = [];
24776
- const messages = [];
24777
- for (const document of decisions) {
24778
- const base = path.posix.basename(document.relativePath);
24779
- const dated = /^(\d{8})-/.exec(base);
24780
- const prefixed = /^[A-Za-z][\w]*-D(\d+)/.exec(base);
24781
- const adr = /^ADR-(\d+)/i.exec(base);
24782
- const numbered = /^(\d+)-/.exec(base);
24783
- if (dated !== null) schemes.add("dated");
24784
- else if (prefixed?.[1] !== void 0) {
24785
- schemes.add("prefixed");
24786
- ids.push(Number(prefixed[1]));
24787
- } else if (adr?.[1] !== void 0) {
24788
- schemes.add("adr");
24789
- ids.push(Number(adr[1]));
24790
- } else if (numbered?.[1] === void 0) schemes.add("other");
24791
- else {
24792
- schemes.add("numbered");
24793
- ids.push(Number(numbered[1]));
24794
- }
24795
- if (document.frontMatter.state === void 0) messages.push(`${document.relativePath} has no state`);
24796
- }
24797
- if (schemes.size > 1) messages.push(`docs/decisions uses more than one naming scheme: ${[...schemes].toSorted().join(", ")}`);
24798
- const unique = new Set(ids);
24799
- if (unique.size !== ids.length) messages.push("docs/decisions ids are not unique");
24800
- if (ids.length > 1) {
24801
- const sorted = [...unique].toSorted((left, right) => left - right);
24802
- if ((sorted.at(-1) ?? 0) - (sorted[0] ?? 0) + 1 !== sorted.length) messages.push("docs/decisions ids are not contiguous");
24803
- }
24804
- return findings(messages);
25589
+ {
25590
+ check: (context) => {
25591
+ if (context.agents === void 0) return {};
25592
+ return /\b(?:claimed by|assigned to|in-flight|in flight)\b|\b(?:feature|fix|hotfix)\/[a-z0-9-]+/i.test(context.agents.text) ? finding("AGENTS.md contains live task, branch, or claim state") : {};
25593
+ },
25594
+ defaultLevel: "warn",
25595
+ description: "AGENTS.md does not carry task assignments, branch names, or claim state",
25596
+ id: "agents.no-live-state"
24805
25597
  },
24806
- defaultLevel: "warn",
24807
- description: "Decision records share one id scheme, with unique contiguous ids and a state",
24808
- id: "decisions.naming"
24809
- },
24810
- {
24811
- check: (context) => {
24812
- const messages = [];
24813
- for (const document of context.documents) {
24814
- if (!document.relativePath.startsWith("papers/") || document.relativePath.endsWith("/README.md")) continue;
24815
- const matter = Object.entries(document.frontMatter).map(([key, value]) => `${key}: ${value}`).join("\n");
24816
- const header = `${document.text}\n${matter}`;
24817
- const missing = [];
24818
- for (const field of [
24819
- "version",
24820
- "status",
24821
- "date"
24822
- ]) if (!new RegExp(String.raw`\b${field}\b`, "i").test(header)) missing.push(field);
24823
- if (missing.length > 0) messages.push(`${document.relativePath} header is missing ${missing.join(", ")}`);
24824
- }
24825
- return findings(messages);
25598
+ {
25599
+ check: (context) => {
25600
+ if (context.agents === void 0) return {};
25601
+ const rootLines = new Set(context.agents.text.split("\n").map((line) => line.trim()).filter((line) => line.length > 40));
25602
+ const messages = [];
25603
+ for (const document of context.nestedAgents) if (document.text.split("\n").filter((line) => rootLines.has(line.trim())).length >= 8) messages.push(`${document.relativePath} restates the root AGENTS.md instead of a package delta`);
25604
+ return findings(messages);
25605
+ },
25606
+ defaultLevel: "warn",
25607
+ description: "Package AGENTS.md files add a delta and do not restate the root",
25608
+ id: "agents.nested-delta-only"
24826
25609
  },
24827
- defaultLevel: "warn",
24828
- description: "Papers carry version, status, and date consistently with the header",
24829
- id: "papers.header"
24830
- }
25610
+ {
25611
+ check: (context) => {
25612
+ if (context.agents === void 0) return {};
25613
+ const section = context.agents.text.split(/^##\s+/m).find((part) => /authorit/i.test(part.split("\n", 1)[0] ?? ""));
25614
+ if (section === void 0) return {};
25615
+ const messages = [];
25616
+ for (const row of authorityRows(section)) {
25617
+ if (!linkExists(context.cwd, "AGENTS.md", row.target)) {
25618
+ messages.push(`Authority row ${row.target} does not exist`);
25619
+ continue;
25620
+ }
25621
+ const actual = readLinkedDocument(context, row.target)?.frontMatter.kind?.toLowerCase();
25622
+ if (mismatchedAuthorityKind(row.kind, actual)) messages.push(`Authority row ${row.target} claims kind ${row.kind ?? ""} but front matter says ${actual ?? ""}`);
25623
+ }
25624
+ return findings(messages);
25625
+ },
25626
+ defaultLevel: "warn",
25627
+ description: "Authority-table rows point at files whose front-matter kind matches",
25628
+ id: "agents.authority-rows-resolve"
25629
+ }
25630
+ ],
25631
+ ...DOC_LINT_RULES,
25632
+ DOCS_INDEX_RULE
24831
25633
  ];
24832
- function readLinkedDocument(context, target) {
24833
- return documentAt(context, path.posix.normalize(target.replace(/^\.\//, "")));
24834
- }
24835
25634
  //#endregion
24836
25635
  //#region src/actions/agent/lint.ts
24837
25636
  /**
@@ -24850,16 +25649,24 @@ async function isAgentLintEnabled(cwd) {
24850
25649
  }
24851
25650
  async function agentLint(options = {}) {
24852
25651
  const cwd = options.cwd ?? INIT_CWD();
24853
- return runRuleChecks({
24854
- commandName: "agent lint",
24855
- config: await loadWorkspaceCommandConfig(cwd, "agentLint"),
24856
- configKey: "agentLint",
24857
- context: loadAgentLintContext(cwd),
24858
- fix: options.fix === true,
24859
- reporter: defaultRuleReporter(),
24860
- rules: AGENT_LINT_RULES,
24861
- strict: options.strict === true || isStrictMode()
24862
- });
25652
+ const config = await loadWorkspaceCommandConfig(cwd, "agentLint");
25653
+ const session = options.fixInteractive === true && options.ask === void 0 ? createTerminalRuleAsk("xy agent lint") : void 0;
25654
+ const ask = options.ask ?? session?.ask;
25655
+ try {
25656
+ return await runRuleChecks({
25657
+ ...options.fixInteractive === true && ask !== void 0 && { ask },
25658
+ commandName: "agent lint",
25659
+ config,
25660
+ configKey: "agentLint",
25661
+ context: loadAgentLintContext(cwd),
25662
+ fix: options.fix === true || options.fixInteractive === true,
25663
+ reporter: defaultRuleReporter(),
25664
+ rules: AGENT_LINT_RULES,
25665
+ strict: options.strict === true || isStrictMode()
25666
+ });
25667
+ } finally {
25668
+ session?.close();
25669
+ }
24863
25670
  }
24864
25671
  const AUDIT_RULES = /* @__PURE__ */ new Set([
24865
25672
  "agents.no-live-state",
@@ -24881,54 +25688,6 @@ async function agentAudit(options = {}) {
24881
25688
  });
24882
25689
  }
24883
25690
  //#endregion
24884
- //#region src/actions/agent/mutate.ts
24885
- function agentIndex(cwd) {
24886
- writeDocsIndex(cwd, loadAgentLintContext(cwd).documents);
24887
- return "docs/README.md";
24888
- }
24889
- function archiveDestination(relativeSource) {
24890
- const underDocs = relativeSource.startsWith("docs/") ? relativeSource.slice(5) : path.posix.basename(relativeSource);
24891
- return path.posix.join("docs/archive", underDocs);
24892
- }
24893
- function withArchivedState(text) {
24894
- const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
24895
- if (match?.[1] === void 0) return `---\nstate: retired\n---\n\n${text}`;
24896
- let replaced = false;
24897
- const lines = match[1].split("\n").map((line) => {
24898
- const field = /^state\s*:\s*(.*)$/.exec(line.trim());
24899
- if (field === null) return line;
24900
- replaced = true;
24901
- return field[1]?.trim().replaceAll(/^['"]|['"]$/g, "") === "superseded" ? line : "state: retired";
24902
- });
24903
- if (!replaced) lines.push("state: retired");
24904
- const body = text.slice(match[0].length);
24905
- return `---\n${lines.join("\n")}\n---\n${body.startsWith("\n") ? "" : "\n"}${body}`;
24906
- }
24907
- function agentArchive(cwd, source) {
24908
- const relativeSource = source.split(path.sep).join("/");
24909
- const fullSource = path.resolve(cwd, relativeSource);
24910
- const root = path.resolve(cwd);
24911
- if (fullSource !== root && !fullSource.startsWith(`${root}${path.sep}`)) throw new Error(`Refusing to archive a path outside the repository: ${source}`);
24912
- if (!fs.existsSync(fullSource) || !fs.statSync(fullSource).isFile()) throw new Error(`Nothing to archive at ${relativeSource}`);
24913
- const text = fs.readFileSync(fullSource, "utf8");
24914
- const parsed = parseFrontMatter(text);
24915
- const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
24916
- const successor = parsed.frontMatter.supersededBy;
24917
- const banner = `> ${parsed.frontMatter.state === "superseded" ? `Superseded${successor === void 0 ? "" : ` by ${successor}`}` : "Retired"} on ${date}. Original path: ${relativeSource}. This document is historical and is not a current instruction.`;
24918
- const withState = withArchivedState(text);
24919
- const front = /^(---\r?\n[\s\S]*?\r?\n---\r?\n)/.exec(withState);
24920
- const archived = front?.[1] === void 0 || withState.includes(banner) ? withState : `${front[1]}\n${banner}\n\n${withState.slice(front[1].length)}`;
24921
- const destination = archiveDestination(relativeSource);
24922
- const fullDestination = path.join(cwd, destination);
24923
- if (path.resolve(fullDestination) === fullSource) throw new Error(`Archive destination is the source file: ${destination}`);
24924
- if (fs.existsSync(fullDestination)) throw new Error(`Archive destination already exists: ${destination}`);
24925
- fs.mkdirSync(path.dirname(fullDestination), { recursive: true });
24926
- fs.writeFileSync(fullDestination, archived.endsWith("\n") ? archived : `${archived}\n`);
24927
- fs.rmSync(fullSource);
24928
- writeDocsIndex(cwd, loadAgentLintContext(cwd).documents);
24929
- return destination;
24930
- }
24931
- //#endregion
24932
25691
  //#region src/actions/analyze.ts
24933
25692
  /**
24934
25693
  Dynamic import that static bundlers cannot rewrite into chunks.
@@ -49245,7 +50004,7 @@ function parseMajorVersion(version = "") {
49245
50004
  return Number.isNaN(major) ? void 0 : major;
49246
50005
  }
49247
50006
  function configuredPnpmMajorVersion() {
49248
- const packageManager = readRootPackageJson$1()?.packageManager;
50007
+ const packageManager = readRootPackageJson$2()?.packageManager;
49249
50008
  return parseMajorVersion(/^pnpm@(\d+)/.exec(packageManager ?? "")?.[1]);
49250
50009
  }
49251
50010
  function installedPnpmMajorVersion() {
@@ -50033,7 +50792,8 @@ const argvAfterCommand = (command) => {
50033
50792
  //#endregion
50034
50793
  //#region src/actions/skills/defaults.ts
50035
50794
  /**
50036
- Source of truth for xy-development, xy-toolchain, xy-agent, and ariestools-sdk.
50795
+ Source of truth for xy-development, xy-toolchain, xy-agent, ariestools-sdk,
50796
+ ariestools-sdk-react, and ariestools-actor.
50037
50797
  */
50038
50798
  const ARIESTOOLS_SKILLS_SOURCE = "ariestools/ariestools-skills";
50039
50799
  /**
@@ -50041,7 +50801,9 @@ Source of truth for xyo-knowledge and xl1-* skills.
50041
50801
  */
50042
50802
  const XYO_SKILLS_SOURCE = "XYOracleNetwork/xyo-skills";
50043
50803
  const ARIESTOOLS_SKILLS = [
50804
+ "ariestools-actor",
50044
50805
  "ariestools-sdk",
50806
+ "ariestools-sdk-react",
50045
50807
  "xy-agent",
50046
50808
  "xy-development",
50047
50809
  "xy-toolchain"
@@ -50120,6 +50882,8 @@ const SKILL_ORDER = [
50120
50882
  "xy-toolchain",
50121
50883
  "xy-agent",
50122
50884
  "ariestools-sdk",
50885
+ "ariestools-sdk-react",
50886
+ "ariestools-actor",
50123
50887
  "xyo-knowledge",
50124
50888
  "xl1-knowledge",
50125
50889
  "xl1-patterns",
@@ -50210,23 +50974,39 @@ function applySkillPresence(skills, presence) {
50210
50974
  return sortSkills([...next]);
50211
50975
  }
50212
50976
  /**
50977
+ * Aries Tools package-family skills for a profile. `ariestools-sdk-react` and
50978
+ * `ariestools-actor` are Layer-3 siblings of `ariestools-sdk` in
50979
+ * ariestools-skills and build on it, so each also requires `ariestools-sdk`.
50980
+ * Their consumers often reach `@ariestools/sdk` only transitively (sdk-react
50981
+ * imports it without declaring it), so the sdk-js signal alone would miss them.
50982
+ */
50983
+ const ariestoolsFamilySkills = (profile) => {
50984
+ const skills = /* @__PURE__ */ new Set();
50985
+ if (profile.isUsingAriestoolsSdk) skills.add("ariestools-sdk");
50986
+ if (profile.isUsingAriestoolsSdkReact === true) {
50987
+ skills.add("ariestools-sdk");
50988
+ skills.add("ariestools-sdk-react");
50989
+ }
50990
+ if (profile.isUsingAriestoolsActor === true) {
50991
+ skills.add("ariestools-sdk");
50992
+ skills.add("ariestools-actor");
50993
+ }
50994
+ return [...skills];
50995
+ };
50996
+ /**
50213
50997
  * Required skills for a detected repo profile.
50214
50998
  * Adds `ariestools-sdk` when the repo depends on or produces packages from ariestools/sdk-js,
50999
+ * adds `ariestools-sdk-react` (and `ariestools-sdk`) for `@ariestools/sdk-react*` packages,
51000
+ * adds `ariestools-actor` (and `ariestools-sdk`) for actor-kit, cli-kit and browser-kit packages,
50215
51001
  * adds `xl1-dapp-kit` when the repo depends on or produces `@xyo-network/dapp-kit` packages,
50216
51002
  * plus any validated `additionalSkills` override from xy config.
50217
51003
  */
50218
51004
  const requiredSkillsForProfile = (profile) => {
50219
51005
  const base = requiredSkillsForTier(profile.tier);
50220
- const withSdk = (() => {
50221
- if (!profile.isUsingAriestoolsSdk) return base;
50222
- if (base.length === 0) return sortSkills([
50223
- "xy-development",
50224
- "xy-toolchain",
50225
- "ariestools-sdk"
50226
- ]);
50227
- return withSkill(base, "ariestools-sdk");
50228
- })();
50229
- const withDappKit = profile.isUsingDappKit ? withSkill(withSdk, "xl1-dapp-kit") : withSdk;
51006
+ const family = ariestoolsFamilySkills(profile);
51007
+ const familyBase = base.length === 0 ? XY_SKILLS : base;
51008
+ const withFamily = family.length === 0 ? base : sortSkills([.../* @__PURE__ */ new Set([...familyBase, ...family])]);
51009
+ const withDappKit = profile.isUsingDappKit ? withSkill(withFamily, "xl1-dapp-kit") : withFamily;
50230
51010
  const additional = profile.additionalSkills ?? [];
50231
51011
  return applySkillPresence(additional.length === 0 ? withDappKit : sortSkills([.../* @__PURE__ */ new Set([...withDappKit, ...additional])]), profile.skillPresence);
50232
51012
  };
@@ -56309,6 +57089,7 @@ function runtimeRuleCatalog(command, configKey, definitions, config) {
56309
57089
  description: rule.description,
56310
57090
  fixable: rule.fixable === true,
56311
57091
  id: rule.id,
57092
+ ...rule.interactive === true && { interactive: true },
56312
57093
  level: parseRuleLevelSetting(ruleConfigPath(configKey, rule.id), resolveSetting(rule), rule.defaultLevel)
56313
57094
  }));
56314
57095
  }
@@ -56370,10 +57151,14 @@ function ruleTableConfig(widths, hasWeight) {
56370
57151
  ].includes(index)
56371
57152
  };
56372
57153
  }
57154
+ function fixLabel(rule) {
57155
+ if (rule.interactive === true) return rule.fixable ? "yes, ask" : "ask";
57156
+ return rule.fixable ? "yes" : "no";
57157
+ }
56373
57158
  function formatRuleTable(rules) {
56374
57159
  const rows = rules.map((rule) => ({
56375
57160
  description: rule.description ?? "",
56376
- fix: rule.fixable ? "yes" : "no",
57161
+ fix: fixLabel(rule),
56377
57162
  id: rule.id,
56378
57163
  level: rule.defaultLevel === rule.level ? rule.defaultLevel : `${rule.defaultLevel} (${rule.level})`,
56379
57164
  resolvedLevel: rule.level,
@@ -56497,6 +57282,7 @@ const ARIESTOOLS_SCOPE = "@ariestools/";
56497
57282
  const XYO_NETWORK_SCOPE = "@xyo-network/";
56498
57283
  const XL1_PACKAGE_PREFIX = "@xyo-network/xl1";
56499
57284
  const DAPP_KIT_PACKAGE = "@xyo-network/dapp-kit";
57285
+ const SDK_REACT_PACKAGE = "@ariestools/sdk-react";
56500
57286
  const LEGACY_TOOLCHAIN_PACKAGES = /* @__PURE__ */ new Set([
56501
57287
  "@xylabs/ts-scripts-yarn3",
56502
57288
  "@xylabs/ts-scripts-pnpm",
@@ -56522,6 +57308,28 @@ const ARIESTOOLS_SDK_JS_PACKAGES = /* @__PURE__ */ new Set([
56522
57308
  "@ariestools/testing",
56523
57309
  "@ariestools/threads"
56524
57310
  ]);
57311
+ /**
57312
+ * Published packages from the ariestools/actor-kit, ariestools/cli-kit and
57313
+ * ariestools/browser-kit monorepos. Presence (import or produce) requires the
57314
+ * `ariestools-actor` skill. Each monorepo's private `*-kit-build` root is excluded.
57315
+ */
57316
+ const ARIESTOOLS_ACTOR_PACKAGES = /* @__PURE__ */ new Set([
57317
+ "@ariestools/actor",
57318
+ "@ariestools/actor-engine",
57319
+ "@ariestools/actor-model",
57320
+ "@ariestools/actor-system",
57321
+ "@ariestools/browser-kit",
57322
+ "@ariestools/browser-kit-page",
57323
+ "@ariestools/browser-kit-plugin",
57324
+ "@ariestools/browser-kit-service-worker",
57325
+ "@ariestools/browser-kit-worker",
57326
+ "@ariestools/cli-kit",
57327
+ "@ariestools/cli-kit-daemon",
57328
+ "@ariestools/cli-kit-node",
57329
+ "@ariestools/cli-kit-yargs",
57330
+ "@ariestools/provider",
57331
+ "@ariestools/provider-model"
57332
+ ]);
56525
57333
  const XY_ECOSYSTEM_SCOPES = [
56526
57334
  XYLABS_SCOPE,
56527
57335
  ARIESTOOLS_SCOPE,
@@ -56550,6 +57358,17 @@ const isAriestoolsSdkJsPackage = (name) => {
56550
57358
  return ARIESTOOLS_SDK_JS_PACKAGES.has(name);
56551
57359
  };
56552
57360
  /**
57361
+ * `@ariestools/sdk-react` and its focused `@ariestools/sdk-react-*` packages
57362
+ * from the ariestools/sdk-react monorepo.
57363
+ * Presence (import or produce) requires the `ariestools-sdk-react` skill.
57364
+ */
57365
+ const isAriestoolsSdkReactPackage = (name) => {
57366
+ return name === SDK_REACT_PACKAGE || name.startsWith(`${SDK_REACT_PACKAGE}-`);
57367
+ };
57368
+ const isAriestoolsActorPackage = (name) => {
57369
+ return ARIESTOOLS_ACTOR_PACKAGES.has(name);
57370
+ };
57371
+ /**
56553
57372
  * Published and private packages from the dapp-kit monorepo
56554
57373
  * (`@xyo-network/dapp-kit` and `@xyo-network/dapp-kit-*`).
56555
57374
  * Presence (import or produce) requires the `xl1-dapp-kit` skill.
@@ -56566,6 +57385,9 @@ const hasXyConfig = (cwd, workspaces) => {
56566
57385
  return existsSync(configPath);
56567
57386
  });
56568
57387
  };
57388
+ const packageFamilySignals = (packages, isFamilyPackage, label) => {
57389
+ return packages.filter((name) => isFamilyPackage(name)).toSorted((a, b) => a.localeCompare(b)).map((name) => `${label} ${name}`);
57390
+ };
56569
57391
  const resolveTier = (produces, imports, isUsingToolchain) => {
56570
57392
  const allPackages = [...produces, ...imports];
56571
57393
  if (allPackages.some(isXl1Package)) return "xl1";
@@ -56633,21 +57455,25 @@ const detectRepoProfile = (cwd) => {
56633
57455
  const imported = collectImports(declaredDeps);
56634
57456
  const toolchain = detectToolchainUsage(cwd, workspaces, declaredDeps);
56635
57457
  const allPackages = [...produced.produces, ...imported.imports];
56636
- const isUsingAriestoolsSdk = allPackages.some(isAriestoolsSdkJsPackage);
56637
- const sdkSignals = isUsingAriestoolsSdk ? allPackages.filter(isAriestoolsSdkJsPackage).toSorted((a, b) => a.localeCompare(b)).map((name) => `sdk-js ${name}`) : [];
56638
- const isUsingDappKit = allPackages.some(isDappKitPackage);
56639
- const dappKitSignals = isUsingDappKit ? allPackages.filter(isDappKitPackage).toSorted((a, b) => a.localeCompare(b)).map((name) => `dapp-kit ${name}`) : [];
57458
+ const sdkSignals = packageFamilySignals(allPackages, isAriestoolsSdkJsPackage, "sdk-js");
57459
+ const sdkReactSignals = packageFamilySignals(allPackages, isAriestoolsSdkReactPackage, "sdk-react");
57460
+ const actorSignals = packageFamilySignals(allPackages, isAriestoolsActorPackage, "actor");
57461
+ const dappKitSignals = packageFamilySignals(allPackages, isDappKitPackage, "dapp-kit");
56640
57462
  const signals = [
56641
57463
  ...produced.signals,
56642
57464
  ...imported.signals,
56643
57465
  ...toolchain.signals,
56644
57466
  ...sdkSignals,
57467
+ ...sdkReactSignals,
57468
+ ...actorSignals,
56645
57469
  ...dappKitSignals
56646
57470
  ].toSorted((a, b) => a.localeCompare(b));
56647
57471
  return {
56648
57472
  imports: imported.imports.toSorted((a, b) => a.localeCompare(b)),
56649
- isUsingAriestoolsSdk,
56650
- isUsingDappKit,
57473
+ isUsingAriestoolsActor: actorSignals.length > 0,
57474
+ isUsingAriestoolsSdk: sdkSignals.length > 0,
57475
+ isUsingAriestoolsSdkReact: sdkReactSignals.length > 0,
57476
+ isUsingDappKit: dappKitSignals.length > 0,
56651
57477
  produces: produced.produces.toSorted((a, b) => a.localeCompare(b)),
56652
57478
  signals,
56653
57479
  tier: resolveTier(produced.produces, imported.imports, toolchain.isUsingToolchain),
@@ -56912,6 +57738,54 @@ const findUnmigratedSkills = (cwd, installed, latestVersions) => {
56912
57738
  return mergeUnmigratedSkills(fromLock, fromFiles);
56913
57739
  };
56914
57740
  //#endregion
57741
+ //#region src/actions/skills/missingSkillReason.ts
57742
+ /**
57743
+ * Why a package-family signal requires a skill. The first match wins, so a
57744
+ * direct sdk-js signal outranks the skills that build on `ariestools-sdk`.
57745
+ */
57746
+ const PACKAGE_FAMILY_REASONS = [
57747
+ {
57748
+ flag: "isUsingAriestoolsSdk",
57749
+ reason: "repo uses packages from ariestools/sdk-js",
57750
+ skill: "ariestools-sdk"
57751
+ },
57752
+ {
57753
+ flag: "isUsingAriestoolsSdkReact",
57754
+ reason: "repo uses @ariestools/sdk-react packages",
57755
+ skill: "ariestools-sdk-react"
57756
+ },
57757
+ {
57758
+ flag: "isUsingAriestoolsActor",
57759
+ reason: "repo uses actor-kit, cli-kit or browser-kit packages",
57760
+ skill: "ariestools-actor"
57761
+ },
57762
+ {
57763
+ flag: "isUsingAriestoolsSdkReact",
57764
+ reason: "ariestools-sdk-react builds on it",
57765
+ skill: "ariestools-sdk"
57766
+ },
57767
+ {
57768
+ flag: "isUsingAriestoolsActor",
57769
+ reason: "ariestools-actor builds on it",
57770
+ skill: "ariestools-sdk"
57771
+ },
57772
+ {
57773
+ flag: "isUsingDappKit",
57774
+ reason: "repo uses dapp-kit packages",
57775
+ skill: "xl1-dapp-kit"
57776
+ }
57777
+ ];
57778
+ /**
57779
+ * Explains why `xy skills lint` requires a missing skill, for its
57780
+ * `skills.required-installed` diagnostic.
57781
+ */
57782
+ const missingSkillReason = (profile, skillName) => {
57783
+ const familyReason = PACKAGE_FAMILY_REASONS.find((entry) => entry.skill === skillName && profile[entry.flag]);
57784
+ if (familyReason !== void 0) return familyReason.reason;
57785
+ if (skillName === "xy-toolchain" && profile.isUsingToolchain) return "repo uses @ariestools/toolchain";
57786
+ return profile.additionalSkills?.includes(skillName) === true ? "listed in commands.skillsLint.additionalSkills" : "required for repo profile";
57787
+ };
57788
+ //#endregion
56915
57789
  //#region src/actions/skills/packageSkills.ts
56916
57790
  const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
56917
57791
  const MAX_SKILL_NAME_LENGTH = 64;
@@ -57169,12 +58043,6 @@ const installSkillOnce = (installSkill) => {
57169
58043
  return code;
57170
58044
  };
57171
58045
  };
57172
- const missingSkillReason = (profile, skillName) => {
57173
- if (skillName === "ariestools-sdk" && profile.isUsingAriestoolsSdk) return "repo uses packages from ariestools/sdk-js";
57174
- if (skillName === "xl1-dapp-kit" && profile.isUsingDappKit) return "repo uses dapp-kit packages";
57175
- if (skillName === "xy-toolchain" && profile.isUsingToolchain) return "repo uses @ariestools/toolchain";
57176
- return profile.additionalSkills?.includes(skillName) === true ? "listed in commands.skillsLint.additionalSkills" : "required for repo profile";
57177
- };
57178
58046
  const checkRequiredSkills = (required, installed, latestVersions, unmigratedNames = /* @__PURE__ */ new Set()) => {
57179
58047
  const current = [];
57180
58048
  const missing = [];
@@ -60471,7 +61339,11 @@ const xyBuildExperimentalCommands = (args, channel) => {
60471
61339
  const lintCommand$6 = {
60472
61340
  builder: (yargs) => yargs.option("fix", {
60473
61341
  default: false,
60474
- describe: "Regenerate docs/README.md and insert missing front matter",
61342
+ describe: "Apply the fixes that need no answers, such as front matter, the docs index, and adapter imports",
61343
+ type: "boolean"
61344
+ }).option("fix-interactive", {
61345
+ default: false,
61346
+ describe: "Experimental: apply --fix, then ask questions (with suggested answers) to fix titles, sections, links, and front matter",
60475
61347
  type: "boolean"
60476
61348
  }).option("rules", {
60477
61349
  default: false,
@@ -60489,11 +61361,15 @@ const lintCommand$6 = {
60489
61361
  await withEnvelope("agent lint rules", async () => ruleCatalogResult(await getAgentLintRuleCatalog(), RULE_COMMANDS.agentLint.title));
60490
61362
  return;
60491
61363
  }
60492
- await withEnvelope("agent lint", () => agentLint({
60493
- cwd: INIT_CWD(),
60494
- fix: argv.fix === true,
60495
- strict: argv.strict === true
60496
- }));
61364
+ await withEnvelope("agent lint", () => {
61365
+ if (argv.fixInteractive === true && isJsonMode()) throw new Error("xy agent lint --fix-interactive asks questions on the terminal and cannot run with --json");
61366
+ return agentLint({
61367
+ cwd: INIT_CWD(),
61368
+ fix: argv.fix === true,
61369
+ fixInteractive: argv.fixInteractive === true,
61370
+ strict: argv.strict === true
61371
+ });
61372
+ });
60497
61373
  }
60498
61374
  };
60499
61375
  const initCommand$4 = {
@@ -61317,6 +62193,12 @@ Pick is catalog-only. A TTY is required when --skill is omitted.
61317
62193
  It writes commands.skillsLint.skills.<name>.presence: 'required'
61318
62194
  and keeps other presence entries.
61319
62195
 
62196
+ Catalog:
62197
+ - ariestools/ariestools-skills xy-development, xy-toolchain, xy-agent,
62198
+ ariestools-sdk, ariestools-sdk-react,
62199
+ ariestools-actor
62200
+ - XYOracleNetwork/xyo-skills xyo-knowledge, xl1-*
62201
+
61320
62202
  Options:
61321
62203
  --skill <name> Skill to require. Repeat for more than one.
61322
62204
  -h, --help Show this help
@@ -61326,7 +62208,9 @@ const printDefaultsHelp = () => {
61326
62208
  console.log(`xy skills defaults
61327
62209
 
61328
62210
  Install the default skill stacks:
61329
- - ariestools/ariestools-skills (xy-development, xy-toolchain, xy-agent, ariestools-sdk)
62211
+ - ariestools/ariestools-skills (xy-development, xy-toolchain, xy-agent,
62212
+ ariestools-sdk, ariestools-sdk-react,
62213
+ ariestools-actor)
61330
62214
  - XYOracleNetwork/xyo-skills (xyo-knowledge, xl1-*)
61331
62215
 
61332
62216
  Usage:
@@ -61364,12 +62248,15 @@ Usage:
61364
62248
  Checks:
61365
62249
  - Detect repo tier (xy, xyo, xl1) from package.json and toolchain signals
61366
62250
  - Require ariestools-sdk when packages from ariestools/sdk-js are used
62251
+ - Require ariestools-sdk-react when @ariestools/sdk-react packages are used
62252
+ - Require ariestools-actor when actor-kit, cli-kit or browser-kit packages
62253
+ are used (both also require ariestools-sdk, which they build on)
61367
62254
  - Require xl1-dapp-kit when the repo produces or depends on @xyo-network/dapp-kit packages
61368
62255
  - Require skills listed in package.json xy.skills on workspace packages and direct dependencies
61369
62256
  - Required skills installed in .claude/skills and/or .agents/skills
61370
62257
  - xy-development and xy-toolchain are locked to ariestools-skills, not xyo-skills
61371
62258
  - Installed skill versions vs upstream main
61372
- (ariestools/ariestools-skills for xy/ariestools-sdk skills;
62259
+ (ariestools/ariestools-skills for xy-* and ariestools-* skills;
61373
62260
  XYOracleNetwork/xyo-skills for xyo/xl1 skills)
61374
62261
  - Project/global duplicate installs
61375
62262
 
@@ -61381,6 +62268,8 @@ Config (xy.config.ts):
61381
62268
  required | allowed | off. required forces a skill on,
61382
62269
  off forces it off, allowed keeps an install from
61383
62270
  counting as unnecessary
62271
+ Both keys take catalog names: xy-development, xy-toolchain, xy-agent,
62272
+ ariestools-sdk, ariestools-sdk-react, ariestools-actor, xyo-knowledge, xl1-*.
61384
62273
 
61385
62274
  Options:
61386
62275
  --fix Install missing and update outdated required and package-declared skills; migrate relocated ones (project scope)
@@ -62889,6 +63778,11 @@ const EXPERIMENTAL_CONFIG_SURFACES = [
62889
63778
  id: "lint.mode.shared-typecheck",
62890
63779
  path: "xy lint --mode shared-typecheck"
62891
63780
  },
63781
+ {
63782
+ description: "Agent-lint fixes that ask questions, with suggested answers, on the terminal. Questions and the rules that ask them may change on a minor.",
63783
+ id: "agent-lint.fix-interactive",
63784
+ path: "xy agent lint --fix-interactive"
63785
+ },
62892
63786
  {
62893
63787
  description: "npm, Yarn, and Bun. pnpm is the supported package manager.",
62894
63788
  id: "package-manager.non-pnpm",