qfai 2.1.2 → 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 (162) hide show
  1. package/README.md +46 -6
  2. package/assets/defaults/agent-routing/qfai-implement.yml +9 -0
  3. package/assets/defaults/agent-routing/qfai-triage.yml +9 -0
  4. package/assets/defaults/workflows/answer-in-session.yml +8 -0
  5. package/assets/defaults/workflows/bump-dependency.yml +4 -1
  6. package/assets/defaults/workflows/decide-design.yml +5 -1
  7. package/assets/defaults/workflows/quarantine-flaky.yml +3 -0
  8. package/assets/defaults/workflows/rename-concept.yml +30 -0
  9. package/assets/defaults/workflows/repair-consistency.yml +1 -0
  10. package/assets/defaults/workflows/resolve-conflicts.yml +14 -0
  11. package/assets/defaults/workflows/retire-feature.yml +26 -0
  12. package/assets/defaults/workflows/run-operation.yml +11 -0
  13. package/assets/defaults/workflows/run-release.yml +12 -0
  14. package/assets/defaults/workflows/write-procedure.yml +18 -0
  15. package/assets/graph/codegraph-native.mjs +174 -0
  16. package/assets/graph/graphify-native.py +72 -0
  17. package/assets/init/.claude/settings.json +11 -29
  18. package/assets/init/.codex/hooks.json +9 -21
  19. package/assets/init/.qfai/assistant/agent/backend-engineer.md +1 -1
  20. package/assets/init/.qfai/assistant/agent/frontend-engineer.md +1 -1
  21. package/assets/init/.qfai/assistant/agent/implementation-reviewer.md +5 -0
  22. package/assets/init/.qfai/assistant/agent/product-surface-reviewer.md +8 -3
  23. package/assets/init/.qfai/assistant/rule/constitution.md +36 -18
  24. package/assets/init/.qfai/assistant/rule/drift-protocol.md +80 -1
  25. package/assets/init/.qfai/assistant/rule/references/codex-delegation.md +27 -0
  26. package/assets/init/.qfai/assistant/rule/references/gate-failure-autorepair.md +1 -1
  27. package/assets/init/.qfai/assistant/rule/references/griller-recommendations.md +21 -9
  28. package/assets/init/.qfai/assistant/rule/review-convergence.md +34 -15
  29. package/assets/init/.qfai/assistant/rule/shared-skill-delegation-baseline.md +12 -2
  30. package/assets/init/.qfai/assistant/rule/shared-skill-operating-baseline.md +14 -7
  31. package/assets/init/.qfai/assistant/rule/ui-definition-protocol.md +2 -1
  32. package/assets/init/.qfai/assistant/rule/workflow.md +2 -1
  33. package/assets/init/.qfai/assistant/skill/qfai-discussion/SKILL.md +11 -2
  34. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-completion-matrix.md +32 -10
  35. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui-bearing-playbook.md +17 -0
  36. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/trend_scan_playbook.md +3 -1
  37. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/01_Context.md +4 -1
  38. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/04_Sources.md +5 -1
  39. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/00_index.md +4 -1
  40. package/assets/init/.qfai/assistant/skill/qfai-grilling/SKILL.md +30 -20
  41. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/delegated-session.md +4 -3
  42. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/session-record.md +8 -2
  43. package/assets/init/.qfai/assistant/skill/qfai-implement/SKILL.md +9 -2
  44. package/assets/init/.qfai/assistant/skill/qfai-implement/references/parallelization-policy.md +10 -0
  45. package/assets/init/.qfai/assistant/skill/qfai-implement/references/red-admissibility.md +35 -0
  46. package/assets/init/.qfai/assistant/skill/qfai-implement/references/test-runner-recipes.md +445 -0
  47. package/assets/init/.qfai/assistant/skill/qfai-implement/references/ui-affecting.md +3 -3
  48. package/assets/init/.qfai/assistant/skill/qfai-prototyping/SKILL.md +10 -9
  49. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/generator-prompt.md +33 -2
  50. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/handoff.md +77 -2
  51. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/iteration-loop.md +12 -3
  52. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/review-payload-schema.md +3 -1
  53. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/reviewer-prompt.md +31 -5
  54. package/assets/init/.qfai/assistant/skill/qfai-run/SKILL.md +48 -46
  55. package/assets/init/.qfai/assistant/skill/qfai-run/references/codex-cloud-install.md +80 -0
  56. package/assets/init/.qfai/assistant/skill/qfai-run/references/extraction.md +202 -126
  57. package/assets/init/.qfai/assistant/skill/qfai-run/references/operator-screens.md +38 -15
  58. package/assets/init/.qfai/assistant/skill/qfai-run/references/plan.md +48 -22
  59. package/assets/init/.qfai/assistant/skill/qfai-run/references/reached-step-observations.md +134 -0
  60. package/assets/init/.qfai/assistant/skill/qfai-run/references/stage-points.md +7 -4
  61. package/assets/init/.qfai/assistant/skill/qfai-run/scripts/codex-cloud-install.mjs +117 -0
  62. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/concrete-abstract-cycle.md +2 -1
  63. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/contract-artifact-rules.md +1 -1
  64. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-md-authoring.md +20 -7
  65. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-execution-playbook.md +2 -2
  66. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-phase-checklists.md +2 -2
  67. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-pre-draft-grilling.md +5 -1
  68. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-quality-gate.md +2 -2
  69. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-triage.md +111 -7
  70. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/spec-traceability-rules.md +1 -1
  71. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-contract-guide.md +58 -8
  72. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/change-request.md +1 -1
  73. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions/page-NNNN.md +6 -0
  74. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions.md +18 -0
  75. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/open-questions.md +13 -0
  76. package/assets/init/.qfai/assistant/skill/qfai-triage/SKILL.md +10 -7
  77. package/assets/init/.qfai/assistant/skill/qfai-verify/references/verify-output-contract.md +22 -16
  78. package/assets/init/.qfai/assistant/skill/web-research/SKILL.md +1 -1
  79. package/assets/init/.qfai/assistant/step/common-design-md/STEP.md +33 -16
  80. package/assets/init/.qfai/assistant/step/common-gate-run/STEP.md +37 -8
  81. package/assets/init/.qfai/assistant/step/common-grilling-record/STEP.md +25 -4
  82. package/assets/init/.qfai/assistant/step/common-policy-check/STEP.md +1 -0
  83. package/assets/init/.qfai/assistant/step/common-review-cycle/STEP.md +68 -15
  84. package/assets/init/.qfai/assistant/step/discussion-interview/STEP.md +25 -10
  85. package/assets/init/.qfai/assistant/step/discussion-oq/STEP.md +17 -1
  86. package/assets/init/.qfai/assistant/step/discussion-pack/STEP.md +23 -3
  87. package/assets/init/.qfai/assistant/step/discussion-uiux/STEP.md +9 -1
  88. package/assets/init/.qfai/assistant/step/implement-acceptance/STEP.md +3 -0
  89. package/assets/init/.qfai/assistant/step/implement-credentials/STEP.md +4 -0
  90. package/assets/init/.qfai/assistant/step/implement-dep-bump/STEP.md +33 -3
  91. package/assets/init/.qfai/assistant/step/implement-diagnose/STEP.md +12 -3
  92. package/assets/init/.qfai/assistant/step/implement-procedure/STEP.md +98 -0
  93. package/assets/init/.qfai/assistant/step/implement-quarantine/STEP.md +21 -4
  94. package/assets/init/.qfai/assistant/step/implement-refactor/STEP.md +25 -5
  95. package/assets/init/.qfai/assistant/step/implement-regression-fix/STEP.md +3 -3
  96. package/assets/init/.qfai/assistant/step/implement-retire/STEP.md +26 -0
  97. package/assets/init/.qfai/assistant/step/implement-scaffold/STEP.md +28 -5
  98. package/assets/init/.qfai/assistant/step/implement-stress-harness/STEP.md +33 -2
  99. package/assets/init/.qfai/assistant/step/implement-tdd/STEP.md +20 -5
  100. package/assets/init/.qfai/assistant/step/maintain-edit/STEP.md +70 -6
  101. package/assets/init/.qfai/assistant/step/prototyping-grill/STEP.md +39 -6
  102. package/assets/init/.qfai/assistant/step/prototyping-handoff/STEP.md +12 -3
  103. package/assets/init/.qfai/assistant/step/prototyping-loop/STEP.md +56 -6
  104. package/assets/init/.qfai/assistant/step/prototyping-preflight/STEP.md +13 -0
  105. package/assets/init/.qfai/assistant/step/sdd-contract/STEP.md +8 -0
  106. package/assets/init/.qfai/assistant/step/sdd-cycle/STEP.md +9 -4
  107. package/assets/init/.qfai/assistant/step/sdd-story/STEP.md +22 -1
  108. package/assets/init/.qfai/assistant/step/sdd-triage/STEP.md +52 -14
  109. package/assets/init/.qfai/assistant/step/triage-answer/STEP.md +2 -2
  110. package/assets/init/.qfai/assistant/step/triage-close/STEP.md +7 -2
  111. package/assets/init/.qfai/assistant/step/triage-handoff/STEP.md +6 -0
  112. package/assets/init/.qfai/assistant/step/triage-operate/STEP.md +123 -0
  113. package/assets/init/.qfai/assistant/step/verify-commit/STEP.md +35 -10
  114. package/assets/init/.qfai/assistant/step/verify-qfai-gate/STEP.md +8 -1
  115. package/assets/init/.qfai/assistant/step/verify-repeat-run/STEP.md +40 -0
  116. package/assets/init/.qfai/assistant/step/verify-repo-gate/STEP.md +77 -7
  117. package/assets/init/root/.agents/rules/api-budget.md +8 -3
  118. package/assets/init/root/.agents/rules/document-schema.md +17 -0
  119. package/assets/init/root/.agents/rules/documentation-clarity.md +1 -1
  120. package/assets/init/root/.agents/rules/graph-exploration.md +164 -0
  121. package/assets/init/root/.agents/rules/grilling.md +100 -43
  122. package/assets/init/root/.agents/rules/reminders.json +20 -32
  123. package/assets/init/root/.agents/rules/session-feedback.md +6 -11
  124. package/assets/init/root/.agents/rules/untrusted-content.md +2 -2
  125. package/assets/init/root/.agents/rules/user-questions.md +24 -14
  126. package/assets/init/root/.gitattributes +2 -0
  127. package/assets/init/root/.github/workflows/qfai-docs.yml +2 -2
  128. package/assets/init/root/.github/workflows/qfai-tests.yml +88 -35
  129. package/assets/init/root/.github/workflows/qfai-validate.yml +2 -2
  130. package/assets/init/root/AGENTS.md +1 -0
  131. package/assets/mdschema/manifest.yml +3 -0
  132. package/assets/mdschema/story/03_contract/tech.mdschema.yml +1 -1
  133. package/assets/mdschema/story/decisions/page-NNNN.mdschema.yml +32 -0
  134. package/assets/mdschema/story/decisions.mdschema.yml +12 -0
  135. package/assets/schemas/workflow/extraction.schema.json +98 -2
  136. package/assets/schemas/workflow/plan.schema.json +34 -1
  137. package/assets/scripts/check-mdschema.mjs +497 -39
  138. package/dist/cli/index.cjs +7667 -3515
  139. package/dist/cli/index.cjs.map +1 -1
  140. package/dist/cli/index.mjs +8872 -4702
  141. package/dist/cli/index.mjs.map +1 -1
  142. package/dist/graph/cli.cjs +1568 -0
  143. package/dist/graph/cli.cjs.map +1 -0
  144. package/dist/graph/cli.d.cts +9 -0
  145. package/dist/graph/cli.d.ts +9 -0
  146. package/dist/graph/cli.mjs +1541 -0
  147. package/dist/graph/cli.mjs.map +1 -0
  148. package/dist/graph/hook.cjs +817 -0
  149. package/dist/graph/hook.cjs.map +1 -0
  150. package/dist/graph/hook.d.cts +9 -0
  151. package/dist/graph/hook.d.ts +9 -0
  152. package/dist/graph/hook.mjs +792 -0
  153. package/dist/graph/hook.mjs.map +1 -0
  154. package/dist/index.cjs +6436 -3012
  155. package/dist/index.cjs.map +1 -1
  156. package/dist/index.d.cts +185 -1
  157. package/dist/index.d.ts +185 -1
  158. package/dist/index.mjs +6620 -3197
  159. package/dist/index.mjs.map +1 -1
  160. package/dist/process-C21nTvkT.d.cts +12 -0
  161. package/dist/process-C21nTvkT.d.ts +12 -0
  162. 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,
@@ -609,14 +610,48 @@ export function patternToRegExp(pattern) {
609
610
  return new RegExp(`^${out}$`);
610
611
  }
611
612
 
613
+ /**
614
+ * Whether a filesystem failure says the path does not exist.
615
+ *
616
+ * @param {unknown} error
617
+ * @returns {boolean}
618
+ */
619
+ function isMissing(error) {
620
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
621
+ }
622
+
623
+ /**
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.
630
+ *
631
+ * @param {unknown} error
632
+ * @returns {string}
633
+ */
634
+ function describeFailure(error) {
635
+ if (!(error instanceof Error)) return String(error);
636
+ const code = "code" in error && typeof error.code === "string" ? error.code : "";
637
+ return code === "" ? error.message : code;
638
+ }
639
+
612
640
  /**
613
641
  * Every file under `dir`, repository-root-relative and forward-slashed.
614
642
  *
643
+ * A directory that vanishes between being listed and being read is skipped, as
644
+ * the race it is. Any other failure to list one (permission, I/O, descriptor
645
+ * exhaustion) leaves its documents unchecked, so it is recorded in `unreadable`
646
+ * rather than dropped: a tree whose subtree cannot be read has not been shown to
647
+ * conform.
648
+ *
615
649
  * @param {string} dir Absolute directory to walk.
616
650
  * @param {string} root The tree the returned paths are relative to.
651
+ * @param {{ dir: string, cause: string }[]} unreadable Receives each directory that could not be listed.
617
652
  * @returns {string[]}
618
653
  */
619
- function walk(dir, root) {
654
+ function walk(dir, root, unreadable) {
620
655
  const out = [];
621
656
  const pending = [dir];
622
657
  while (pending.length > 0) {
@@ -624,7 +659,13 @@ function walk(dir, root) {
624
659
  let entries;
625
660
  try {
626
661
  entries = readdirSync(current, { withFileTypes: true });
627
- } catch {
662
+ } catch (error) {
663
+ if (!isMissing(error)) {
664
+ unreadable.push({
665
+ dir: path.relative(root, current).split(path.sep).join("/") || ".",
666
+ cause: describeFailure(error),
667
+ });
668
+ }
628
669
  continue;
629
670
  }
630
671
  // Another repository checked out inside this one — a clone, a submodule, or a
@@ -736,14 +777,74 @@ function changedFiles(base, root) {
736
777
  * @returns {{ ok: boolean, output: string, spawnFailed: boolean }}
737
778
  */
738
779
  function runMdschema(mdschema, schemaPath, files, root) {
739
- const result = spawnSync(
740
- mdschema.command,
741
- [...mdschema.args, "check", "--schema", schemaPath, ...files],
742
- {
743
- cwd: root,
744
- encoding: "utf-8",
745
- },
746
- );
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) {
747
848
  if (result.error !== undefined || result.status === null) {
748
849
  return {
749
850
  ok: false,
@@ -888,19 +989,64 @@ export function configuredPaths(root) {
888
989
  * Each configured tree is walked once. A contract directory nested in the spec
889
990
  * tree is deduplicated before any document is routed to a schema.
890
991
  *
992
+ * A directory that could not be listed comes back as a violation of its own, so
993
+ * a subtree that vanished from the universe fails the run instead of passing it.
994
+ *
891
995
  * @param {string} root
892
996
  * @param {{ specsDir: string, contractsDir: string }} paths
893
- * @returns {string[]}
997
+ * @returns {{ files: string[], unreadable: { file: string, line: number, column: number, rule: string, message: string }[] }}
894
998
  */
895
999
  function documentUniverse(root, paths) {
896
- return [
1000
+ /** @type {{ dir: string, cause: string }[]} */
1001
+ const failed = [];
1002
+ /** @type {{ dir: string, problem: string }[]} */
1003
+ const roots = [];
1004
+ const files = [
897
1005
  ...new Set(
898
1006
  [paths.specsDir, paths.contractsDir].flatMap((dir) => {
899
1007
  const absolute = path.resolve(root, dir);
900
- return existsSync(absolute) && statSync(absolute).isDirectory() ? walk(absolute, root) : [];
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);
901
1030
  }),
902
1031
  ),
903
1032
  ];
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 }) => ({
1042
+ file: dir,
1043
+ line: 1,
1044
+ column: 1,
1045
+ rule: "inventory",
1046
+ message: `this directory could not be listed (${cause}); the documents beneath it were not checked`,
1047
+ })),
1048
+ ];
1049
+ return { files, unreadable };
904
1050
  }
905
1051
 
906
1052
  /**
@@ -911,7 +1057,7 @@ function documentUniverse(root, paths) {
911
1057
  let showPatterns = false;
912
1058
 
913
1059
  /** A forbidden-text finding: the pattern that matched and the section it matched in. */
914
- const FORBIDDEN_TEXT_MESSAGE = /^Forbidden text '.*' found in section '([^']*)'$/u;
1060
+ const FORBIDDEN_TEXT_MESSAGE = /^Forbidden text '(.*)' found in section '([^']*)'$/u;
915
1061
 
916
1062
  /**
917
1063
  * The heading entries of a schema with the description each declares.
@@ -997,36 +1143,54 @@ function sectionDescription(entries, name) {
997
1143
  * no description keeps the pattern, because it is all there is to say. The
998
1144
  * closing tally follows the findings that remain.
999
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
+ *
1000
1150
  * @param {string} output
1001
1151
  * @param {string} schemaText
1152
+ * @param {(file: string) => string | null} [readDocument] the text of a document
1153
+ * mdschema names, or `null`
1002
1154
  * @returns {string}
1003
1155
  */
1004
- export function explainForbiddenText(output, schemaText) {
1156
+ export function explainForbiddenText(output, schemaText, readDocument = readTextOrNull) {
1005
1157
  const entries = sectionDescriptions(schemaText);
1006
1158
  const lines = [];
1007
- let seen = new Set();
1159
+ /** @type {Map<string, { index: number, at: number | null }>} */
1160
+ let seen = new Map();
1008
1161
  let merged = 0;
1162
+ let document = null;
1009
1163
  for (const line of output.split(/\r?\n/)) {
1010
- 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
+ }
1011
1168
  const found = VIOLATION_LINE.exec(line);
1012
1169
  const forbidden =
1013
1170
  found !== null && found[3] === "forbidden-text"
1014
1171
  ? FORBIDDEN_TEXT_MESSAGE.exec(found[4])
1015
1172
  : null;
1016
- const description = forbidden === null ? null : sectionDescription(entries, forbidden[1]);
1173
+ const description = forbidden === null ? null : sectionDescription(entries, forbidden[2]);
1017
1174
  if (found === null || forbidden === null || description === null) {
1018
1175
  lines.push(line);
1019
1176
  continue;
1020
1177
  }
1021
- const key = `${found[1]}:${found[2]}:${forbidden[1]}`;
1022
- 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) {
1023
1185
  merged++;
1186
+ if (at !== null && (earlier.at === null || at < earlier.at)) {
1187
+ earlier.at = at;
1188
+ lines[earlier.index] = finding(at);
1189
+ }
1024
1190
  continue;
1025
1191
  }
1026
- seen.add(key);
1027
- lines.push(
1028
- ` ✗ ${found[1]}:${found[2]} [forbidden-text] Section '${forbidden[1]}' does not hold what the schema requires: ${description}`,
1029
- );
1192
+ seen.set(key, { index: lines.length, at });
1193
+ lines.push(finding(at));
1030
1194
  }
1031
1195
  return lines
1032
1196
  .map((line) =>
@@ -1040,6 +1204,79 @@ export function explainForbiddenText(output, schemaText) {
1040
1204
  .join("\n");
1041
1205
  }
1042
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
+
1043
1280
  /** One violation line of `mdschema check` output: ` ✗ 3:4 [rule] message`. */
1044
1281
  const VIOLATION_LINE = /^\s+✗\s+(\d+):(\d+)\s+\[([^\]]+)\]\s+(.*\S)\s*$/u;
1045
1282
 
@@ -1098,9 +1335,9 @@ export function parseViolations(output, files, root) {
1098
1335
  /**
1099
1336
  * Checks one manifest entry's documents and appends what fails to `violations`.
1100
1337
  *
1101
- * @returns {string | null} why the check could not run, or `null`
1338
+ * @returns {Promise<string | null>} why the check could not run, or `null`
1102
1339
  */
1103
- function checkEntryDocuments(context, entry, violations) {
1340
+ async function checkEntryDocuments(context, entry, violations) {
1104
1341
  const { root, paths, universe, mdschema } = context;
1105
1342
  const schemaPath = path.join(SCHEMA_ROOT, entry.schema);
1106
1343
  if (!existsSync(schemaPath)) {
@@ -1125,7 +1362,7 @@ function checkEntryDocuments(context, entry, violations) {
1125
1362
  gradable.push(file);
1126
1363
  }
1127
1364
  if (gradable.length === 0) return null;
1128
- const result = runMdschema(mdschema, schemaPath, gradable, root);
1365
+ const result = await runMdschemaAsync(mdschema, schemaPath, gradable, root);
1129
1366
  if (result.spawnFailed) {
1130
1367
  return `mdschema did not run: ${result.output}`;
1131
1368
  }
@@ -1144,6 +1381,162 @@ function checkEntryDocuments(context, entry, violations) {
1144
1381
  return null;
1145
1382
  }
1146
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
+
1147
1540
  /**
1148
1541
  * Checks every document the manifest routes, for a caller rather than a log.
1149
1542
  *
@@ -1152,21 +1545,46 @@ function checkEntryDocuments(context, entry, violations) {
1152
1545
  * as `main`, over the whole tree: a validation run has no merge base to ratchet
1153
1546
  * against.
1154
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
+ *
1155
1551
  * @param {string} root
1156
1552
  * @param {{ specsDir: string, contractsDir: string }} [paths] tree-relative roots
1157
- * @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 }>}
1158
1554
  */
1159
- export function checkDocuments(root, paths = configuredPaths(root)) {
1555
+ export async function checkDocuments(root, paths = configuredPaths(root)) {
1160
1556
  const mdschema = findMdschemaCommand(root);
1161
1557
  if (mdschema === null) {
1162
1558
  return { ok: false, reason: `no ${MDSCHEMA_PACKAGE} installation was found` };
1163
1559
  }
1164
- const context = { root, paths, mdschema, universe: documentUniverse(root, paths), checked: 0 };
1560
+ const register = decisionRegisterViolations(root, paths);
1561
+ if (register.unsafe) return { ok: true, checked: 0, violations: register.violations };
1562
+ const { files, unreadable } = documentUniverse(root, paths);
1563
+ const context = { root, paths, mdschema, universe: files, checked: 0 };
1165
1564
  const entries = readManifest();
1166
- const violations = coverageViolations(entries, context.universe.toSorted(), paths);
1167
- for (const entry of entries) {
1168
- 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) {
1169
1586
  if (failure !== null) return { ok: false, reason: failure };
1587
+ violations.push(...found);
1170
1588
  }
1171
1589
  return { ok: true, checked: context.checked, violations };
1172
1590
  }
@@ -1286,8 +1704,6 @@ export function main() {
1286
1704
  return 2;
1287
1705
  }
1288
1706
 
1289
- const universe = documentUniverse(root, paths);
1290
-
1291
1707
  /** @type {string[] | null} */
1292
1708
  let restrictTo = null;
1293
1709
  if (scope === "files") {
@@ -1321,6 +1737,31 @@ export function main() {
1321
1737
  let inheritedFiles = 0;
1322
1738
  const perEntry = [];
1323
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
+
1324
1765
  /** @type {Map<string, string>} */
1325
1766
  const contents = new Map();
1326
1767
  const contentOf = (file) => {
@@ -1335,6 +1776,19 @@ export function main() {
1335
1776
  // this run's failure under every scope that includes it, whatever the merge
1336
1777
  // base held: there is no earlier grade to compare against.
1337
1778
  const inScope = universe.filter((file) => restrictSet === null || restrictSet.has(file)).sort();
1779
+
1780
+ // A directory that could not be listed hides every document beneath it, and a
1781
+ // changed file there is hidden with the rest, so this fails the run whatever
1782
+ // the scope: the documents it holds were not shown to conform.
1783
+ if (unreadable.length > 0) {
1784
+ violations++;
1785
+ console.error("\n── inventory (document directories) ──");
1786
+ for (const found of unreadable) {
1787
+ console.error([found.file, ` ✗ 1:1 [${found.rule}] ${found.message}`].join("\n"));
1788
+ }
1789
+ perEntry.push({ id: "inventory", files: unreadable.length, ok: false, inherited: 0 });
1790
+ }
1791
+
1338
1792
  const uncovered = coverageViolations(entries, inScope, paths);
1339
1793
  checked += uncovered.length;
1340
1794
  if (uncovered.length > 0) {
@@ -1497,10 +1951,14 @@ export function main() {
1497
1951
  // pre-existing failures back reports what it actually established — that this
1498
1952
  // branch introduced none — because the other wording would put the migration's
1499
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.
1500
1956
  const verdict =
1501
- inheritedFiles > 0
1502
- ? `${checked} file(s) checked, no new violations`
1503
- : `${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`;
1504
1962
  console.log(`check-mdschema: ${verdict} (${where})${held}.`);
1505
1963
  return 0;
1506
1964
  }