qfai 2.2.0 → 2.2.1

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 (117) hide show
  1. package/README.md +46 -6
  2. package/assets/defaults/workflows/bump-dependency.yml +4 -1
  3. package/assets/defaults/workflows/decide-design.yml +5 -1
  4. package/assets/defaults/workflows/rename-concept.yml +30 -0
  5. package/assets/defaults/workflows/resolve-conflicts.yml +14 -0
  6. package/assets/defaults/workflows/retire-feature.yml +26 -0
  7. package/assets/defaults/workflows/run-release.yml +12 -0
  8. package/assets/init/.claude/settings.json +11 -11
  9. package/assets/init/.codex/hooks.json +9 -9
  10. package/assets/init/.qfai/assistant/agent/backend-engineer.md +1 -1
  11. package/assets/init/.qfai/assistant/agent/frontend-engineer.md +1 -1
  12. package/assets/init/.qfai/assistant/agent/implementation-reviewer.md +5 -0
  13. package/assets/init/.qfai/assistant/agent/product-surface-reviewer.md +8 -3
  14. package/assets/init/.qfai/assistant/rule/constitution.md +5 -3
  15. package/assets/init/.qfai/assistant/rule/drift-protocol.md +18 -0
  16. package/assets/init/.qfai/assistant/rule/references/gate-failure-autorepair.md +1 -1
  17. package/assets/init/.qfai/assistant/rule/review-convergence.md +9 -3
  18. package/assets/init/.qfai/assistant/rule/shared-skill-delegation-baseline.md +11 -2
  19. package/assets/init/.qfai/assistant/rule/shared-skill-operating-baseline.md +6 -4
  20. package/assets/init/.qfai/assistant/rule/ui-definition-protocol.md +2 -1
  21. package/assets/init/.qfai/assistant/skill/qfai-discussion/SKILL.md +5 -2
  22. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-completion-matrix.md +15 -2
  23. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui-bearing-playbook.md +17 -0
  24. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/trend_scan_playbook.md +3 -1
  25. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/01_Context.md +4 -1
  26. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/04_Sources.md +5 -1
  27. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/00_index.md +4 -1
  28. package/assets/init/.qfai/assistant/skill/qfai-implement/SKILL.md +2 -2
  29. package/assets/init/.qfai/assistant/skill/qfai-implement/references/parallelization-policy.md +10 -0
  30. package/assets/init/.qfai/assistant/skill/qfai-implement/references/red-admissibility.md +35 -0
  31. package/assets/init/.qfai/assistant/skill/qfai-implement/references/test-runner-recipes.md +445 -0
  32. package/assets/init/.qfai/assistant/skill/qfai-implement/references/ui-affecting.md +2 -2
  33. package/assets/init/.qfai/assistant/skill/qfai-prototyping/SKILL.md +10 -9
  34. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/generator-prompt.md +33 -2
  35. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/handoff.md +77 -2
  36. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/iteration-loop.md +12 -3
  37. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/review-payload-schema.md +3 -1
  38. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/reviewer-prompt.md +31 -5
  39. package/assets/init/.qfai/assistant/skill/qfai-run/SKILL.md +17 -17
  40. package/assets/init/.qfai/assistant/skill/qfai-run/references/extraction.md +194 -129
  41. package/assets/init/.qfai/assistant/skill/qfai-run/references/operator-screens.md +29 -14
  42. package/assets/init/.qfai/assistant/skill/qfai-run/references/plan.md +46 -22
  43. package/assets/init/.qfai/assistant/skill/qfai-run/references/reached-step-observations.md +2 -0
  44. package/assets/init/.qfai/assistant/skill/qfai-run/references/stage-points.md +7 -4
  45. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/concrete-abstract-cycle.md +2 -1
  46. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/contract-artifact-rules.md +1 -1
  47. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-execution-playbook.md +2 -2
  48. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-phase-checklists.md +1 -1
  49. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-pre-draft-grilling.md +1 -0
  50. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-quality-gate.md +1 -1
  51. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-triage.md +83 -6
  52. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/spec-traceability-rules.md +1 -1
  53. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-contract-guide.md +23 -5
  54. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/change-request.md +1 -1
  55. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions/page-NNNN.md +6 -0
  56. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions.md +9 -0
  57. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/open-questions.md +13 -0
  58. package/assets/init/.qfai/assistant/skill/qfai-verify/references/verify-output-contract.md +15 -9
  59. package/assets/init/.qfai/assistant/skill/web-research/SKILL.md +1 -1
  60. package/assets/init/.qfai/assistant/step/common-gate-run/STEP.md +11 -8
  61. package/assets/init/.qfai/assistant/step/common-grilling-record/STEP.md +15 -2
  62. package/assets/init/.qfai/assistant/step/common-review-cycle/STEP.md +48 -11
  63. package/assets/init/.qfai/assistant/step/discussion-interview/STEP.md +11 -3
  64. package/assets/init/.qfai/assistant/step/discussion-oq/STEP.md +12 -0
  65. package/assets/init/.qfai/assistant/step/discussion-pack/STEP.md +18 -2
  66. package/assets/init/.qfai/assistant/step/discussion-uiux/STEP.md +4 -0
  67. package/assets/init/.qfai/assistant/step/implement-acceptance/STEP.md +3 -0
  68. package/assets/init/.qfai/assistant/step/implement-credentials/STEP.md +4 -0
  69. package/assets/init/.qfai/assistant/step/implement-dep-bump/STEP.md +31 -7
  70. package/assets/init/.qfai/assistant/step/implement-diagnose/STEP.md +12 -3
  71. package/assets/init/.qfai/assistant/step/implement-procedure/STEP.md +35 -6
  72. package/assets/init/.qfai/assistant/step/implement-refactor/STEP.md +25 -5
  73. package/assets/init/.qfai/assistant/step/implement-retire/STEP.md +26 -0
  74. package/assets/init/.qfai/assistant/step/implement-scaffold/STEP.md +28 -5
  75. package/assets/init/.qfai/assistant/step/implement-tdd/STEP.md +20 -5
  76. package/assets/init/.qfai/assistant/step/maintain-edit/STEP.md +70 -6
  77. package/assets/init/.qfai/assistant/step/prototyping-grill/STEP.md +39 -6
  78. package/assets/init/.qfai/assistant/step/prototyping-handoff/STEP.md +12 -3
  79. package/assets/init/.qfai/assistant/step/prototyping-loop/STEP.md +56 -6
  80. package/assets/init/.qfai/assistant/step/prototyping-preflight/STEP.md +5 -0
  81. package/assets/init/.qfai/assistant/step/sdd-contract/STEP.md +8 -0
  82. package/assets/init/.qfai/assistant/step/sdd-cycle/STEP.md +9 -4
  83. package/assets/init/.qfai/assistant/step/sdd-story/STEP.md +22 -1
  84. package/assets/init/.qfai/assistant/step/sdd-triage/STEP.md +48 -12
  85. package/assets/init/.qfai/assistant/step/triage-close/STEP.md +7 -2
  86. package/assets/init/.qfai/assistant/step/triage-handoff/STEP.md +6 -0
  87. package/assets/init/.qfai/assistant/step/triage-operate/STEP.md +76 -3
  88. package/assets/init/.qfai/assistant/step/verify-commit/STEP.md +35 -10
  89. package/assets/init/.qfai/assistant/step/verify-repo-gate/STEP.md +65 -7
  90. package/assets/init/root/.agents/rules/api-budget.md +8 -3
  91. package/assets/init/root/.agents/rules/graph-exploration.md +18 -4
  92. package/assets/init/root/.agents/rules/reminders.json +20 -28
  93. package/assets/init/root/.agents/rules/user-questions.md +21 -11
  94. package/assets/init/root/.gitattributes +2 -0
  95. package/assets/init/root/AGENTS.md +1 -1
  96. package/assets/mdschema/manifest.yml +3 -0
  97. package/assets/mdschema/story/03_contract/tech.mdschema.yml +1 -1
  98. package/assets/mdschema/story/decisions/page-NNNN.mdschema.yml +32 -0
  99. package/assets/mdschema/story/decisions.mdschema.yml +12 -0
  100. package/assets/schemas/workflow/extraction.schema.json +94 -2
  101. package/assets/schemas/workflow/plan.schema.json +34 -1
  102. package/assets/scripts/check-mdschema.mjs +434 -45
  103. package/dist/cli/index.cjs +4930 -2264
  104. package/dist/cli/index.cjs.map +1 -1
  105. package/dist/cli/index.mjs +4690 -2016
  106. package/dist/cli/index.mjs.map +1 -1
  107. package/dist/graph/cli.cjs.map +1 -1
  108. package/dist/graph/cli.mjs.map +1 -1
  109. package/dist/graph/hook.cjs.map +1 -1
  110. package/dist/graph/hook.mjs.map +1 -1
  111. package/dist/index.cjs +3338 -1830
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.d.cts +59 -3
  114. package/dist/index.d.ts +59 -3
  115. package/dist/index.mjs +3154 -1649
  116. package/dist/index.mjs.map +1 -1
  117. package/package.json +1 -1
@@ -106,9 +106,10 @@
106
106
  * on stdout, names them, and counts them in its closing line, which is why the
107
107
  * exit code alone is not the whole answer there.
108
108
  */
109
- import { spawnSync } from "node:child_process";
109
+ import { spawn, spawnSync } from "node:child_process";
110
110
  import {
111
111
  existsSync,
112
+ lstatSync,
112
113
  mkdtempSync,
113
114
  readFileSync,
114
115
  readdirSync,
@@ -620,8 +621,12 @@ function isMissing(error) {
620
621
  }
621
622
 
622
623
  /**
623
- * A filesystem failure as one line that keeps its code, so EACCES, EIO and
624
- * EMFILE can be told apart.
624
+ * A filesystem failure as its error code, so EACCES, EIO and EMFILE can be told
625
+ * apart.
626
+ *
627
+ * Node's message for a coded failure carries the syscall and the absolute path,
628
+ * which a CI log or a report should not hold; every finding already names the
629
+ * repository-relative path. A failure without a code keeps its message.
625
630
  *
626
631
  * @param {unknown} error
627
632
  * @returns {string}
@@ -629,9 +634,7 @@ function isMissing(error) {
629
634
  function describeFailure(error) {
630
635
  if (!(error instanceof Error)) return String(error);
631
636
  const code = "code" in error && typeof error.code === "string" ? error.code : "";
632
- return code === "" || error.message.startsWith(code)
633
- ? error.message
634
- : `${code}: ${error.message}`;
637
+ return code === "" ? error.message : code;
635
638
  }
636
639
 
637
640
  /**
@@ -774,14 +777,74 @@ function changedFiles(base, root) {
774
777
  * @returns {{ ok: boolean, output: string, spawnFailed: boolean }}
775
778
  */
776
779
  function runMdschema(mdschema, schemaPath, files, root) {
777
- const result = spawnSync(
778
- mdschema.command,
779
- [...mdschema.args, "check", "--schema", schemaPath, ...files],
780
- {
781
- cwd: root,
782
- encoding: "utf-8",
783
- },
784
- );
780
+ const result = spawnSync(mdschema.command, mdschemaArgs(mdschema, schemaPath, files), {
781
+ cwd: root,
782
+ encoding: "utf-8",
783
+ // `checkDocuments` reads output of any length, so the lane reads far more
784
+ // than the 1 MiB default rather than calling a long report a failed run.
785
+ maxBuffer: MDSCHEMA_MAX_OUTPUT,
786
+ });
787
+ return mdschemaResult(result, schemaPath);
788
+ }
789
+
790
+ /**
791
+ * {@link runMdschema} without blocking, so `checkDocuments` can run the
792
+ * manifest's entries at the same time. Each entry is its own mdschema process,
793
+ * and starting those one after another was most of the check's time.
794
+ *
795
+ * @param {{ command: string, args: string[] }} mdschema
796
+ * @param {string} schemaPath
797
+ * @param {string[]} files
798
+ * @param {string} root
799
+ * @returns {Promise<{ ok: boolean, output: string, spawnFailed: boolean }>}
800
+ */
801
+ function runMdschemaAsync(mdschema, schemaPath, files, root) {
802
+ return new Promise((resolve) => {
803
+ let stdout = "";
804
+ let stderr = "";
805
+ let settled = false;
806
+ // A failed start emits `error`, and Node does not promise a `close` after it.
807
+ const settle = (/** @type {{ error?: Error, status: number | null }} */ end) => {
808
+ if (settled) return;
809
+ settled = true;
810
+ resolve(mdschemaResult({ ...end, stdout, stderr }, schemaPath));
811
+ };
812
+ // `spawn` throws for some start failures (an argument list too long), and
813
+ // leaves the output streams null for others (no descriptors left). Both are
814
+ // a run that did not happen, as `spawnSync` reports them.
815
+ let child;
816
+ try {
817
+ child = spawn(mdschema.command, mdschemaArgs(mdschema, schemaPath, files), { cwd: root });
818
+ } catch (error) {
819
+ settle({ error: error instanceof Error ? error : new Error(String(error)), status: null });
820
+ return;
821
+ }
822
+ child.on("error", (error) => settle({ error, status: null }));
823
+ child.stdout?.setEncoding("utf-8").on("data", (chunk) => (stdout += chunk));
824
+ child.stderr?.setEncoding("utf-8").on("data", (chunk) => (stderr += chunk));
825
+ child.on("close", (status) => settle({ status }));
826
+ });
827
+ }
828
+
829
+ /** How much output the synchronous runner reads from one mdschema run. */
830
+ const MDSCHEMA_MAX_OUTPUT = 256 * 1024 * 1024;
831
+
832
+ /** How many manifest entries `checkDocuments` runs at the same time. */
833
+ const CONCURRENT_ENTRIES = 8;
834
+
835
+ /** The arguments of one `mdschema check` run. */
836
+ function mdschemaArgs(mdschema, schemaPath, files) {
837
+ return [...mdschema.args, "check", "--schema", schemaPath, ...files];
838
+ }
839
+
840
+ /**
841
+ * What one finished mdschema process means.
842
+ *
843
+ * @param {{ error?: Error, status: number | null, stdout?: string, stderr?: string }} result
844
+ * @param {string} schemaPath
845
+ * @returns {{ ok: boolean, output: string, spawnFailed: boolean }}
846
+ */
847
+ function mdschemaResult(result, schemaPath) {
785
848
  if (result.error !== undefined || result.status === null) {
786
849
  return {
787
850
  ok: false,
@@ -936,25 +999,53 @@ export function configuredPaths(root) {
936
999
  function documentUniverse(root, paths) {
937
1000
  /** @type {{ dir: string, cause: string }[]} */
938
1001
  const failed = [];
1002
+ /** @type {{ dir: string, problem: string }[]} */
1003
+ const roots = [];
939
1004
  const files = [
940
1005
  ...new Set(
941
1006
  [paths.specsDir, paths.contractsDir].flatMap((dir) => {
942
1007
  const absolute = path.resolve(root, dir);
943
- return existsSync(absolute) && statSync(absolute).isDirectory()
944
- ? walk(absolute, root, failed)
945
- : [];
1008
+ const relative = path.relative(root, absolute).split(path.sep).join("/") || ".";
1009
+ // An absent configured root holds no documents. One that is a file, or
1010
+ // that cannot be inspected, is a tree whose documents were not checked.
1011
+ // The spec root rarely reaches here: the decision-register check inspects
1012
+ // it first and stops the run on the same two conditions.
1013
+ let stats;
1014
+ try {
1015
+ stats = statSync(absolute);
1016
+ } catch (error) {
1017
+ if (!isMissing(error)) {
1018
+ roots.push({
1019
+ dir: relative,
1020
+ problem: `could not be inspected (${describeFailure(error)})`,
1021
+ });
1022
+ }
1023
+ return [];
1024
+ }
1025
+ if (!stats.isDirectory()) {
1026
+ roots.push({ dir: relative, problem: "is not a directory" });
1027
+ return [];
1028
+ }
1029
+ return walk(absolute, root, failed);
946
1030
  }),
947
1031
  ),
948
1032
  ];
949
- const unreadable = [...new Map(failed.map((found) => [found.dir, found])).values()].map(
950
- ({ dir, cause }) => ({
1033
+ const unreadable = [
1034
+ ...roots.map(({ dir, problem }) => ({
1035
+ file: dir,
1036
+ line: 1,
1037
+ column: 1,
1038
+ rule: "inventory",
1039
+ message: `this configured document root ${problem}; the documents beneath it were not checked`,
1040
+ })),
1041
+ ...[...new Map(failed.map((found) => [found.dir, found])).values()].map(({ dir, cause }) => ({
951
1042
  file: dir,
952
1043
  line: 1,
953
1044
  column: 1,
954
1045
  rule: "inventory",
955
1046
  message: `this directory could not be listed (${cause}); the documents beneath it were not checked`,
956
- }),
957
- );
1047
+ })),
1048
+ ];
958
1049
  return { files, unreadable };
959
1050
  }
960
1051
 
@@ -966,7 +1057,7 @@ function documentUniverse(root, paths) {
966
1057
  let showPatterns = false;
967
1058
 
968
1059
  /** A forbidden-text finding: the pattern that matched and the section it matched in. */
969
- const FORBIDDEN_TEXT_MESSAGE = /^Forbidden text '.*' found in section '([^']*)'$/u;
1060
+ const FORBIDDEN_TEXT_MESSAGE = /^Forbidden text '(.*)' found in section '([^']*)'$/u;
970
1061
 
971
1062
  /**
972
1063
  * The heading entries of a schema with the description each declares.
@@ -1052,36 +1143,54 @@ function sectionDescription(entries, name) {
1052
1143
  * no description keeps the pattern, because it is all there is to say. The
1053
1144
  * closing tally follows the findings that remain.
1054
1145
  *
1146
+ * mdschema places a forbidden-text finding on the section's heading. Where the
1147
+ * document can be read and the pattern translated, the finding moves to the
1148
+ * line the pattern matches, so the reader sees which item is wrong.
1149
+ *
1055
1150
  * @param {string} output
1056
1151
  * @param {string} schemaText
1152
+ * @param {(file: string) => string | null} [readDocument] the text of a document
1153
+ * mdschema names, or `null`
1057
1154
  * @returns {string}
1058
1155
  */
1059
- export function explainForbiddenText(output, schemaText) {
1156
+ export function explainForbiddenText(output, schemaText, readDocument = readTextOrNull) {
1060
1157
  const entries = sectionDescriptions(schemaText);
1061
1158
  const lines = [];
1062
- let seen = new Set();
1159
+ /** @type {Map<string, { index: number, at: number | null }>} */
1160
+ let seen = new Map();
1063
1161
  let merged = 0;
1162
+ let document = null;
1064
1163
  for (const line of output.split(/\r?\n/)) {
1065
- if (/^\S/.test(line)) seen = new Set();
1164
+ if (/^\S/.test(line)) {
1165
+ seen = new Map();
1166
+ if (!TALLY_LINE.test(line)) document = readDocument(line.trim());
1167
+ }
1066
1168
  const found = VIOLATION_LINE.exec(line);
1067
1169
  const forbidden =
1068
1170
  found !== null && found[3] === "forbidden-text"
1069
1171
  ? FORBIDDEN_TEXT_MESSAGE.exec(found[4])
1070
1172
  : null;
1071
- const description = forbidden === null ? null : sectionDescription(entries, forbidden[1]);
1173
+ const description = forbidden === null ? null : sectionDescription(entries, forbidden[2]);
1072
1174
  if (found === null || forbidden === null || description === null) {
1073
1175
  lines.push(line);
1074
1176
  continue;
1075
1177
  }
1076
- const key = `${found[1]}:${found[2]}:${forbidden[1]}`;
1077
- if (seen.has(key)) {
1178
+ const at = document === null ? null : offendingLine(document, Number(found[1]), forbidden[1]);
1179
+ const finding = (/** @type {number | null} */ line) =>
1180
+ ` ✗ ${line === null ? `${found[1]}:${found[2]}` : `${line}:1`} [forbidden-text] Section '${forbidden[2]}' does not hold what the schema requires: ${description}`;
1181
+ // Patterns that fail in one section are one finding, at the earliest line any of them matched.
1182
+ const key = `${found[1]}:${found[2]}:${forbidden[2]}`;
1183
+ const earlier = seen.get(key);
1184
+ if (earlier !== undefined) {
1078
1185
  merged++;
1186
+ if (at !== null && (earlier.at === null || at < earlier.at)) {
1187
+ earlier.at = at;
1188
+ lines[earlier.index] = finding(at);
1189
+ }
1079
1190
  continue;
1080
1191
  }
1081
- seen.add(key);
1082
- lines.push(
1083
- ` ✗ ${found[1]}:${found[2]} [forbidden-text] Section '${forbidden[1]}' does not hold what the schema requires: ${description}`,
1084
- );
1192
+ seen.set(key, { index: lines.length, at });
1193
+ lines.push(finding(at));
1085
1194
  }
1086
1195
  return lines
1087
1196
  .map((line) =>
@@ -1095,6 +1204,79 @@ export function explainForbiddenText(output, schemaText) {
1095
1204
  .join("\n");
1096
1205
  }
1097
1206
 
1207
+ /** The text of `file`, or `null` when it cannot be read. */
1208
+ function readTextOrNull(file) {
1209
+ try {
1210
+ return readFileSync(file, "utf-8");
1211
+ } catch {
1212
+ return null;
1213
+ }
1214
+ }
1215
+
1216
+ /**
1217
+ * A schema's Go (RE2) pattern as a JavaScript RegExp, or `null` where it uses
1218
+ * syntax this does not translate. It translates a leading `(?flags)` group of
1219
+ * `i`, `m` and `s`, and the `\A` and `\z` anchors. An anchor written after an
1220
+ * escaped backslash or inside a class, or a pattern JavaScript then refuses,
1221
+ * gives `null`.
1222
+ *
1223
+ * @param {string} pattern
1224
+ * @returns {RegExp | null}
1225
+ */
1226
+ function goPatternToRegExp(pattern) {
1227
+ const lead = /^\(\?([a-z]+)\)/u.exec(pattern);
1228
+ const flags = lead === null ? "" : lead[1];
1229
+ if (/[^ims]/u.test(flags) || /\\\\[Az]|\[[^\]]*\\[Az]/u.test(pattern)) return null;
1230
+ const body = (lead === null ? pattern : pattern.slice(lead[0].length))
1231
+ .replaceAll("\\A", "(?<![\\s\\S])")
1232
+ .replaceAll("\\z", "(?![\\s\\S])");
1233
+ try {
1234
+ return new RegExp(body, flags);
1235
+ } catch {
1236
+ return null;
1237
+ }
1238
+ }
1239
+
1240
+ /**
1241
+ * The line where `pattern` first matches in the body of the section whose
1242
+ * heading is on line `headingLine` of `document`, or `null`.
1243
+ *
1244
+ * The body runs from the line after the heading to the next heading of the same
1245
+ * or a higher level. The line is that of the match's first non-blank character.
1246
+ * `null` means the heading, the pattern or a match was not found, and the caller
1247
+ * keeps mdschema's own position. So does a body holding whitespace outside
1248
+ * ASCII, a vertical tab or a carriage return: RE2's `\s` leaves those out and
1249
+ * JavaScript's takes them in, so the two could match different lines.
1250
+ *
1251
+ * @param {string} document
1252
+ * @param {number} headingLine 1-based
1253
+ * @param {string} pattern a schema's forbidden-text pattern
1254
+ * @returns {number | null}
1255
+ */
1256
+ export function offendingLine(document, headingLine, pattern) {
1257
+ const lines = document.split(/\r?\n/u);
1258
+ const heading = /^(#{1,6})\s/u.exec(lines[headingLine - 1] ?? "");
1259
+ const re = goPatternToRegExp(pattern);
1260
+ if (heading === null || re === null) return null;
1261
+ let end = headingLine;
1262
+ while (end < lines.length) {
1263
+ const next = /^(#{1,6})\s/u.exec(lines[end] ?? "");
1264
+ if (next !== null && next[1].length <= heading[1].length) break;
1265
+ end++;
1266
+ }
1267
+ const body = lines.slice(headingLine, end).join("\n");
1268
+ if (NON_RE2_WHITESPACE.test(body)) return null;
1269
+ const match = re.exec(body);
1270
+ if (match === null) return null;
1271
+ const visible = match[0].search(/\S/u);
1272
+ const offset = match.index + (visible === -1 ? 0 : visible);
1273
+ return headingLine + 1 + (body.slice(0, offset).match(/\n/gu)?.length ?? 0);
1274
+ }
1275
+
1276
+ /** Whitespace JavaScript's `\s` matches and RE2's does not, including the line breaks only JavaScript knows. */
1277
+ const NON_RE2_WHITESPACE =
1278
+ /[\v\r\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/u;
1279
+
1098
1280
  /** One violation line of `mdschema check` output: ` ✗ 3:4 [rule] message`. */
1099
1281
  const VIOLATION_LINE = /^\s+✗\s+(\d+):(\d+)\s+\[([^\]]+)\]\s+(.*\S)\s*$/u;
1100
1282
 
@@ -1153,9 +1335,9 @@ export function parseViolations(output, files, root) {
1153
1335
  /**
1154
1336
  * Checks one manifest entry's documents and appends what fails to `violations`.
1155
1337
  *
1156
- * @returns {string | null} why the check could not run, or `null`
1338
+ * @returns {Promise<string | null>} why the check could not run, or `null`
1157
1339
  */
1158
- function checkEntryDocuments(context, entry, violations) {
1340
+ async function checkEntryDocuments(context, entry, violations) {
1159
1341
  const { root, paths, universe, mdschema } = context;
1160
1342
  const schemaPath = path.join(SCHEMA_ROOT, entry.schema);
1161
1343
  if (!existsSync(schemaPath)) {
@@ -1180,7 +1362,7 @@ function checkEntryDocuments(context, entry, violations) {
1180
1362
  gradable.push(file);
1181
1363
  }
1182
1364
  if (gradable.length === 0) return null;
1183
- const result = runMdschema(mdschema, schemaPath, gradable, root);
1365
+ const result = await runMdschemaAsync(mdschema, schemaPath, gradable, root);
1184
1366
  if (result.spawnFailed) {
1185
1367
  return `mdschema did not run: ${result.output}`;
1186
1368
  }
@@ -1199,6 +1381,162 @@ function checkEntryDocuments(context, entry, violations) {
1199
1381
  return null;
1200
1382
  }
1201
1383
 
1384
+ /**
1385
+ * Checks the physical decision register without truncating any document.
1386
+ * Pages are direct, explicitly listed members of the configured register.
1387
+ *
1388
+ * @param {string} root
1389
+ * @param {{ specsDir: string, contractsDir: string }} paths
1390
+ * @returns {{violations: {file: string, line: number, column: number, rule: string, message: string}[], unsafe: boolean}}
1391
+ */
1392
+ function decisionRegisterViolations(root, paths) {
1393
+ const result = { violations: [], unsafe: false };
1394
+ const found = result.violations;
1395
+ const specs = path.resolve(root, paths.specsDir);
1396
+ const rootFile = path.join(specs, "decisions.md");
1397
+ const pagesDir = path.join(specs, "decisions");
1398
+ const fileName = (file) => path.relative(root, file).split(path.sep).join("/");
1399
+ const report = (file, message) =>
1400
+ found.push({ file: fileName(file), line: 1, column: 1, rule: "decision-register", message });
1401
+
1402
+ const inspect = (file, directory) => {
1403
+ let stats;
1404
+ try {
1405
+ stats = lstatSync(file);
1406
+ } catch (error) {
1407
+ if (isMissing(error)) return null;
1408
+ report(
1409
+ file,
1410
+ `Cannot inspect this decision-register path (${describeFailure(error)}); resolve its access before checking.`,
1411
+ );
1412
+ result.unsafe = true;
1413
+ return false;
1414
+ }
1415
+ if (stats.isSymbolicLink() || (directory ? !stats.isDirectory() : !stats.isFile())) {
1416
+ report(
1417
+ file,
1418
+ directory
1419
+ ? "Decision-register directories must be regular directories, not links."
1420
+ : "Decision-register documents must be regular files, not links.",
1421
+ );
1422
+ result.unsafe = true;
1423
+ return false;
1424
+ }
1425
+ if (!directory && stats.nlink !== 1) {
1426
+ report(file, "Decision-register documents must not share a hard-linked file.");
1427
+ result.unsafe = true;
1428
+ return false;
1429
+ }
1430
+ return true;
1431
+ };
1432
+
1433
+ // Preserve configured roots outside the workspace. For roots inside it,
1434
+ // inspect every intermediate component as well as the configured directory.
1435
+ const relative = path.relative(path.resolve(root), specs);
1436
+ if (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(".." + path.sep)) {
1437
+ let component = path.resolve(root);
1438
+ for (const name of relative.split(path.sep).filter(Boolean)) {
1439
+ component = path.join(component, name);
1440
+ if (inspect(component, true) !== true) return result;
1441
+ }
1442
+ }
1443
+ if (inspect(specs, true) !== true) return result;
1444
+ const rootState = inspect(rootFile, false);
1445
+ if (rootState === false) return result;
1446
+ const pageState = inspect(pagesDir, true);
1447
+ if (pageState === false) return result;
1448
+ if (rootState === null && pageState === null) return result;
1449
+
1450
+ const read = (file) => {
1451
+ try {
1452
+ const text = readFileSync(file, "utf-8");
1453
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g)?.length ?? 0;
1454
+ if (lines > 500) {
1455
+ report(
1456
+ file,
1457
+ "Decision-register documents must have at most 500 physical lines; found " + lines + ".",
1458
+ );
1459
+ }
1460
+ return text;
1461
+ } catch (error) {
1462
+ result.unsafe = true;
1463
+ report(
1464
+ file,
1465
+ `Cannot read this decision-register document (${describeFailure(error)}); resolve its access before checking.`,
1466
+ );
1467
+ return null;
1468
+ }
1469
+ };
1470
+ const listed = new Set();
1471
+ if (rootState === null) {
1472
+ report(rootFile, "Decision pages require their decisions.md root and explicit page list.");
1473
+ } else {
1474
+ const text = read(rootFile);
1475
+ if (text === null) return result;
1476
+ const lines = text.split(/\r?\n/);
1477
+ const indexes = lines.flatMap((line, index) => (line === "## Decision pages" ? [index] : []));
1478
+ const tables = lines.flatMap((line, index) => (line === "## Decisions" ? [index] : []));
1479
+ if (
1480
+ indexes.length > 1 ||
1481
+ (indexes.length === 1 && (tables.length !== 1 || indexes[0] >= tables[0]))
1482
+ ) {
1483
+ report(
1484
+ rootFile,
1485
+ "Use at most one Decision pages section, before the unique Decisions section.",
1486
+ );
1487
+ } else if (indexes.length === 1) {
1488
+ for (const line of lines.slice(indexes[0] + 1, tables[0])) {
1489
+ if (line.trim() === "") continue;
1490
+ const match = /^- decisions\/(page-[0-9]{4}\.md)$/.exec(line);
1491
+ if (match === null) {
1492
+ report(
1493
+ rootFile,
1494
+ "Decision pages must contain only direct '- decisions/page-NNNN.md' entries.",
1495
+ );
1496
+ } else if (listed.has(match[1])) {
1497
+ report(rootFile, "Decision page " + match[1] + " is listed more than once.");
1498
+ } else {
1499
+ listed.add(match[1]);
1500
+ }
1501
+ }
1502
+ if (listed.size === 0)
1503
+ report(rootFile, "A Decision pages section must list at least one page.");
1504
+ }
1505
+ }
1506
+
1507
+ if (pageState === true) {
1508
+ let names;
1509
+ try {
1510
+ names = readdirSync(pagesDir);
1511
+ } catch (error) {
1512
+ result.unsafe = true;
1513
+ report(
1514
+ pagesDir,
1515
+ `Cannot list decision pages (${describeFailure(error)}); resolve directory access before checking.`,
1516
+ );
1517
+ return result;
1518
+ }
1519
+ for (const name of names) {
1520
+ if (!listed.has(name)) {
1521
+ report(
1522
+ path.join(pagesDir, name),
1523
+ "Every decision-page directory entry must be a direct page listed by decisions.md.",
1524
+ );
1525
+ }
1526
+ if (inspect(path.join(pagesDir, name), false) === false) return result;
1527
+ }
1528
+ }
1529
+ for (const name of listed) {
1530
+ const file = path.join(pagesDir, name);
1531
+ const state = inspect(file, false);
1532
+ if (state === null)
1533
+ report(file, "A listed decision page is missing; restore it before checking.");
1534
+ if (state === false) return result;
1535
+ if (state === true && read(file) === null) return result;
1536
+ }
1537
+ return result;
1538
+ }
1539
+
1202
1540
  /**
1203
1541
  * Checks every document the manifest routes, for a caller rather than a log.
1204
1542
  *
@@ -1207,22 +1545,46 @@ function checkEntryDocuments(context, entry, violations) {
1207
1545
  * as `main`, over the whole tree: a validation run has no merge base to ratchet
1208
1546
  * against.
1209
1547
  *
1548
+ * Up to eight entries run at the same time, and their findings are reported in
1549
+ * manifest order, so the answer does not depend on which process finished first.
1550
+ *
1210
1551
  * @param {string} root
1211
1552
  * @param {{ specsDir: string, contractsDir: string }} [paths] tree-relative roots
1212
- * @returns {{ ok: true, checked: number, violations: {file: string, line: number, column: number, rule: string, message: string}[] } | { ok: false, reason: string }}
1553
+ * @returns {Promise<{ ok: true, checked: number, violations: {file: string, line: number, column: number, rule: string, message: string}[] } | { ok: false, reason: string }>}
1213
1554
  */
1214
- export function checkDocuments(root, paths = configuredPaths(root)) {
1555
+ export async function checkDocuments(root, paths = configuredPaths(root)) {
1215
1556
  const mdschema = findMdschemaCommand(root);
1216
1557
  if (mdschema === null) {
1217
1558
  return { ok: false, reason: `no ${MDSCHEMA_PACKAGE} installation was found` };
1218
1559
  }
1560
+ const register = decisionRegisterViolations(root, paths);
1561
+ if (register.unsafe) return { ok: true, checked: 0, violations: register.violations };
1219
1562
  const { files, unreadable } = documentUniverse(root, paths);
1220
1563
  const context = { root, paths, mdschema, universe: files, checked: 0 };
1221
1564
  const entries = readManifest();
1222
- const violations = [...unreadable, ...coverageViolations(entries, files.toSorted(), paths)];
1223
- for (const entry of entries) {
1224
- const failure = checkEntryDocuments(context, entry, violations);
1565
+ const violations = [
1566
+ ...unreadable,
1567
+ ...coverageViolations(entries, files.toSorted(), paths),
1568
+ ...register.violations,
1569
+ ];
1570
+ // A few entries at a time, each one process; each result keeps its entry's slot.
1571
+ /** @type {{ failure: string | null, found: object[] }[]} */
1572
+ const perEntry = [];
1573
+ let next = 0;
1574
+ const worker = async () => {
1575
+ while (next < entries.length) {
1576
+ const index = next++;
1577
+ const found = [];
1578
+ perEntry[index] = {
1579
+ failure: await checkEntryDocuments(context, entries[index], found),
1580
+ found,
1581
+ };
1582
+ }
1583
+ };
1584
+ await Promise.all(Array.from({ length: Math.min(CONCURRENT_ENTRIES, entries.length) }, worker));
1585
+ for (const { failure, found } of perEntry) {
1225
1586
  if (failure !== null) return { ok: false, reason: failure };
1587
+ violations.push(...found);
1226
1588
  }
1227
1589
  return { ok: true, checked: context.checked, violations };
1228
1590
  }
@@ -1342,8 +1704,6 @@ export function main() {
1342
1704
  return 2;
1343
1705
  }
1344
1706
 
1345
- const { files: universe, unreadable } = documentUniverse(root, paths);
1346
-
1347
1707
  /** @type {string[] | null} */
1348
1708
  let restrictTo = null;
1349
1709
  if (scope === "files") {
@@ -1377,6 +1737,31 @@ export function main() {
1377
1737
  let inheritedFiles = 0;
1378
1738
  const perEntry = [];
1379
1739
 
1740
+ const registerRoot = path.join(paths.specsDir, "decisions.md").split(path.sep).join("/");
1741
+ const registerPages = path.join(paths.specsDir, "decisions").split(path.sep).join("/") + "/";
1742
+ const registerInScope =
1743
+ restrictSet === null ||
1744
+ [...restrictSet].some((file) => file === registerRoot || file.startsWith(registerPages));
1745
+ // Path safety applies before any traversal, even when only another document is selected.
1746
+ const registerCheck = decisionRegisterViolations(root, paths);
1747
+ const register = registerInScope || registerCheck.unsafe ? registerCheck.violations : [];
1748
+ if (register.length > 0) {
1749
+ violations++;
1750
+ console.error("\n── decision register ──");
1751
+ for (const found of register) {
1752
+ console.error([found.file, " ✗ 1:1 [" + found.rule + "] " + found.message].join("\n"));
1753
+ }
1754
+ }
1755
+ perEntry.push({
1756
+ id: "decision-register",
1757
+ files: new Set(register.map((found) => found.file)).size,
1758
+ ok: register.length === 0,
1759
+ inherited: 0,
1760
+ });
1761
+
1762
+ if (registerCheck.unsafe) return 1;
1763
+ const { files: universe, unreadable } = documentUniverse(root, paths);
1764
+
1380
1765
  /** @type {Map<string, string>} */
1381
1766
  const contents = new Map();
1382
1767
  const contentOf = (file) => {
@@ -1566,10 +1951,14 @@ export function main() {
1566
1951
  // pre-existing failures back reports what it actually established — that this
1567
1952
  // branch introduced none — because the other wording would put the migration's
1568
1953
  // backlog on record as clean.
1954
+ // Nor where nothing was checked: "0 file(s) conform" read as a pass for files no
1955
+ // schema covers, so a gate citing it recorded evidence that checked nothing.
1569
1956
  const verdict =
1570
- inheritedFiles > 0
1571
- ? `${checked} file(s) checked, no new violations`
1572
- : `${checked} file(s) conform`;
1957
+ checked === 0
1958
+ ? "no spec or contract document is in scope, so nothing was checked"
1959
+ : inheritedFiles > 0
1960
+ ? `${checked} file(s) checked, no new violations`
1961
+ : `${checked} file(s) conform`;
1573
1962
  console.log(`check-mdschema: ${verdict} (${where})${held}.`);
1574
1963
  return 0;
1575
1964
  }