@driftsys/markspec 0.9.0 → 0.10.2

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 (131) hide show
  1. package/esm/collect/mod.d.ts +34 -0
  2. package/esm/collect/mod.d.ts.map +1 -0
  3. package/esm/collect/mod.js +37 -0
  4. package/esm/compiler/mod.d.ts +7 -0
  5. package/esm/compiler/mod.d.ts.map +1 -1
  6. package/esm/compiler/mod.js +17 -3
  7. package/esm/compiler/schema.d.ts +8 -1
  8. package/esm/compiler/schema.d.ts.map +1 -1
  9. package/esm/compiler/schema.js +8 -1
  10. package/esm/formatter/dprint.d.ts +62 -0
  11. package/esm/formatter/dprint.d.ts.map +1 -0
  12. package/esm/formatter/dprint.js +83 -0
  13. package/esm/formatter/md_equiv.d.ts +24 -0
  14. package/esm/formatter/md_equiv.d.ts.map +1 -0
  15. package/esm/formatter/md_equiv.js +81 -0
  16. package/esm/formatter/mod.d.ts +25 -0
  17. package/esm/formatter/mod.d.ts.map +1 -1
  18. package/esm/formatter/mod.js +135 -7
  19. package/esm/formatter/prose.d.ts +48 -0
  20. package/esm/formatter/prose.d.ts.map +1 -0
  21. package/esm/formatter/prose.js +85 -0
  22. package/esm/gates/mod.d.ts +82 -0
  23. package/esm/gates/mod.d.ts.map +1 -0
  24. package/esm/gates/mod.js +139 -0
  25. package/esm/lint/runner.d.ts +26 -3
  26. package/esm/lint/runner.d.ts.map +1 -1
  27. package/esm/lint/runner.js +39 -9
  28. package/esm/lock/edge_drift.d.ts +31 -0
  29. package/esm/lock/edge_drift.d.ts.map +1 -0
  30. package/esm/lock/edge_drift.js +29 -0
  31. package/esm/lock/mod.d.ts +2 -0
  32. package/esm/lock/mod.d.ts.map +1 -1
  33. package/esm/lock/mod.js +1 -0
  34. package/esm/mod.d.ts +16 -7
  35. package/esm/mod.d.ts.map +1 -1
  36. package/esm/mod.js +13 -4
  37. package/esm/model/mod.d.ts +27 -1
  38. package/esm/model/mod.d.ts.map +1 -1
  39. package/esm/model/mod.js +10 -0
  40. package/esm/model/profile.d.ts +42 -0
  41. package/esm/model/profile.d.ts.map +1 -1
  42. package/esm/parser/markdown.d.ts.map +1 -1
  43. package/esm/parser/markdown.js +38 -11
  44. package/esm/profile/chain.js +1 -0
  45. package/esm/profile/delivered.d.ts +48 -0
  46. package/esm/profile/delivered.d.ts.map +1 -0
  47. package/esm/profile/delivered.js +103 -0
  48. package/esm/profile/manifest.d.ts +1 -0
  49. package/esm/profile/manifest.d.ts.map +1 -1
  50. package/esm/profile/manifest.js +107 -0
  51. package/esm/profile/merge.d.ts.map +1 -1
  52. package/esm/profile/merge.js +22 -0
  53. package/esm/refs/mod.d.ts.map +1 -1
  54. package/esm/refs/mod.js +22 -0
  55. package/esm/reporter/mod.d.ts.map +1 -1
  56. package/esm/reporter/mod.js +16 -4
  57. package/esm/util/fence.d.ts +8 -0
  58. package/esm/util/fence.d.ts.map +1 -1
  59. package/esm/util/fence.js +22 -0
  60. package/esm/validator/corpus.d.ts +25 -0
  61. package/esm/validator/corpus.d.ts.map +1 -0
  62. package/esm/validator/corpus.js +140 -0
  63. package/esm/validator/mod.d.ts +2 -0
  64. package/esm/validator/mod.d.ts.map +1 -1
  65. package/esm/validator/mod.js +1 -0
  66. package/package.json +3 -1
  67. package/script/collect/mod.d.ts +34 -0
  68. package/script/collect/mod.d.ts.map +1 -0
  69. package/script/collect/mod.js +40 -0
  70. package/script/compiler/mod.d.ts +7 -0
  71. package/script/compiler/mod.d.ts.map +1 -1
  72. package/script/compiler/mod.js +16 -2
  73. package/script/compiler/schema.d.ts +8 -1
  74. package/script/compiler/schema.d.ts.map +1 -1
  75. package/script/compiler/schema.js +8 -1
  76. package/script/formatter/dprint.d.ts +62 -0
  77. package/script/formatter/dprint.d.ts.map +1 -0
  78. package/script/formatter/dprint.js +120 -0
  79. package/script/formatter/md_equiv.d.ts +24 -0
  80. package/script/formatter/md_equiv.d.ts.map +1 -0
  81. package/script/formatter/md_equiv.js +87 -0
  82. package/script/formatter/mod.d.ts +25 -0
  83. package/script/formatter/mod.d.ts.map +1 -1
  84. package/script/formatter/mod.js +135 -6
  85. package/script/formatter/prose.d.ts +48 -0
  86. package/script/formatter/prose.d.ts.map +1 -0
  87. package/script/formatter/prose.js +88 -0
  88. package/script/gates/mod.d.ts +82 -0
  89. package/script/gates/mod.d.ts.map +1 -0
  90. package/script/gates/mod.js +144 -0
  91. package/script/lint/runner.d.ts +26 -3
  92. package/script/lint/runner.d.ts.map +1 -1
  93. package/script/lint/runner.js +39 -9
  94. package/script/lock/edge_drift.d.ts +31 -0
  95. package/script/lock/edge_drift.d.ts.map +1 -0
  96. package/script/lock/edge_drift.js +32 -0
  97. package/script/lock/mod.d.ts +2 -0
  98. package/script/lock/mod.d.ts.map +1 -1
  99. package/script/lock/mod.js +3 -1
  100. package/script/mod.d.ts +16 -7
  101. package/script/mod.d.ts.map +1 -1
  102. package/script/mod.js +56 -29
  103. package/script/model/mod.d.ts +27 -1
  104. package/script/model/mod.d.ts.map +1 -1
  105. package/script/model/mod.js +11 -0
  106. package/script/model/profile.d.ts +42 -0
  107. package/script/model/profile.d.ts.map +1 -1
  108. package/script/parser/markdown.d.ts.map +1 -1
  109. package/script/parser/markdown.js +38 -11
  110. package/script/profile/chain.js +1 -0
  111. package/script/profile/delivered.d.ts +48 -0
  112. package/script/profile/delivered.d.ts.map +1 -0
  113. package/script/profile/delivered.js +109 -0
  114. package/script/profile/manifest.d.ts +1 -0
  115. package/script/profile/manifest.d.ts.map +1 -1
  116. package/script/profile/manifest.js +108 -1
  117. package/script/profile/merge.d.ts.map +1 -1
  118. package/script/profile/merge.js +22 -0
  119. package/script/refs/mod.d.ts.map +1 -1
  120. package/script/refs/mod.js +22 -0
  121. package/script/reporter/mod.d.ts.map +1 -1
  122. package/script/reporter/mod.js +16 -4
  123. package/script/util/fence.d.ts +8 -0
  124. package/script/util/fence.d.ts.map +1 -1
  125. package/script/util/fence.js +23 -0
  126. package/script/validator/corpus.d.ts +25 -0
  127. package/script/validator/corpus.d.ts.map +1 -0
  128. package/script/validator/corpus.js +144 -0
  129. package/script/validator/mod.d.ts +2 -0
  130. package/script/validator/mod.d.ts.map +1 -1
  131. package/script/validator/mod.js +4 -1
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * @module formatter/md_equiv
4
+ *
5
+ * CommonMark-semantic Markdown equivalence — the gate for the ADR-029
6
+ * dprint pass. Two fragments are equivalent when they parse to the
7
+ * same mdast structure after eliding source `position`s and collapsing
8
+ * ASCII whitespace runs inside `text` node values. Only ASCII
9
+ * whitespace is collapsed — NBSP (U+00A0) and Unicode spaces are
10
+ * content, not wrap artifacts, and must not compare equal to a plain
11
+ * space. Soft-wrap positions,
12
+ * emphasis delimiter style (`*x*` vs `_x_`), table cell padding, and
13
+ * list marker style are presentation, not content — they compare
14
+ * equal. Hard breaks are `break` nodes in mdast, so wrap-collapsing
15
+ * cannot erase or fabricate one. Code (`code`, `inlineCode`), `html`,
16
+ * and definition `url`s stay byte-exact.
17
+ *
18
+ * DELIBERATELY weaker than ADR-015's `astEquivalent` (byte-verbatim on
19
+ * inline markup). Used ONLY to accept/reject dprint output; the
20
+ * ADR-015 relation still guards §5.2 body emission (MSL-F900) and must
21
+ * not be modified.
22
+ */
23
+ var __importDefault = (this && this.__importDefault) || function (mod) {
24
+ return (mod && mod.__esModule) ? mod : { "default": mod };
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.markdownSemanticallyEquivalent = markdownSemanticallyEquivalent;
28
+ const unified_1 = require("unified");
29
+ const remark_parse_1 = __importDefault(require("remark-parse"));
30
+ const remark_gfm_1 = __importDefault(require("remark-gfm"));
31
+ const parser = (0, unified_1.unified)().use(remark_parse_1.default).use(remark_gfm_1.default);
32
+ /** True when `a` and `b` are the same Markdown, modulo presentation. */
33
+ function markdownSemanticallyEquivalent(a, b) {
34
+ if (a === b)
35
+ return true;
36
+ return deepEqual(normalize(parser.parse(a)), normalize(parser.parse(b)));
37
+ }
38
+ /**
39
+ * Recursively strip `position` keys and collapse ASCII whitespace runs
40
+ * in `text` node values (reflow can only introduce ASCII spaces and
41
+ * newlines; `\s` would also match NBSP and Unicode Zs spaces, letting
42
+ * a content change pass as a wrap change). Returns a plain JSON-ish
43
+ * structure for comparison; never mutates the input tree.
44
+ */
45
+ function normalize(node) {
46
+ if (Array.isArray(node))
47
+ return node.map(normalize);
48
+ if (node === null || typeof node !== "object")
49
+ return node;
50
+ const src = node;
51
+ const out = {};
52
+ for (const key of Object.keys(src).sort()) {
53
+ if (key === "position")
54
+ continue;
55
+ if (key === "value" && src.type === "text" &&
56
+ typeof src.value === "string") {
57
+ out.value = src.value.replace(/[ \t\r\n\f\v]+/g, " ");
58
+ continue;
59
+ }
60
+ out[key] = normalize(src[key]);
61
+ }
62
+ return out;
63
+ }
64
+ /** Structural deep-equality over the normalized trees. */
65
+ function deepEqual(a, b) {
66
+ if (a === b)
67
+ return true;
68
+ if (typeof a !== typeof b)
69
+ return false;
70
+ if (a === null || b === null)
71
+ return a === b;
72
+ if (Array.isArray(a) || Array.isArray(b)) {
73
+ if (!Array.isArray(a) || !Array.isArray(b))
74
+ return false;
75
+ if (a.length !== b.length)
76
+ return false;
77
+ return a.every((v, i) => deepEqual(v, b[i]));
78
+ }
79
+ if (typeof a === "object" && typeof b === "object") {
80
+ const ak = Object.keys(a);
81
+ const bk = Object.keys(b);
82
+ if (ak.length !== bk.length)
83
+ return false;
84
+ return ak.every((k) => deepEqual(a[k], b[k]));
85
+ }
86
+ return false;
87
+ }
@@ -6,6 +6,7 @@
6
6
  * and requirement block insertion.
7
7
  */
8
8
  import type { Attribute, Diagnostic } from "../model/mod.js";
9
+ import { type ProseFormatter } from "./dprint.js";
9
10
  /**
10
11
  * Decide whether the EARS keyword at `offset` in `line` is at sentence
11
12
  * start (return value true). Delegates to the shared implementation in
@@ -49,6 +50,23 @@ export interface FormatOptions {
49
50
  * Injectable for deterministic tests.
50
51
  */
51
52
  readonly today?: () => string;
53
+ /**
54
+ * Whole-document Markdown formatter (ADR-029). When supplied, prose
55
+ * segments outside entry blocks and each entry body are routed
56
+ * through it (dprint-markdown), gated by CommonMark-semantic
57
+ * equivalence. When absent, format() is entry-only — the exact
58
+ * pre-ADR-029 behaviour. The entry-body polish passes a per-call
59
+ * `lineWidth` reduced by the body indent (see `emitBodyViaAst`);
60
+ * one-arg formatter callbacks simply ignore it.
61
+ *
62
+ * The pass is Markdown-only: it runs only when {@linkcode file} has a
63
+ * Markdown extension (`.md`). A source-file (or absent) `file` disables
64
+ * it even when this callback is set — a source file's doc comment must
65
+ * never be reflowed as Markdown, and the semantic gate cannot catch
66
+ * that class of corruption. Callers that format Markdown held in memory
67
+ * must therefore pass a `.md`-suffixed `file`.
68
+ */
69
+ readonly formatMarkdownProse?: ProseFormatter;
52
70
  }
53
71
  /** Result of a format operation. */
54
72
  export interface FormatResult {
@@ -107,6 +125,13 @@ export declare function sortAttributes(attributes: Attribute[]): Attribute[];
107
125
  * 0 for entries inside source-file doc comments).
108
126
  */
109
127
  export declare function renderAttributeBlock(attributes: Attribute[], indent: number): string;
128
+ /**
129
+ * Find the 0-based line index where a list item's content ends.
130
+ * Exported for the ADR-029 prose pass (entry-extent computation).
131
+ * Scans forward from the entry start, stopping at: a sibling list item
132
+ * (`- ` at the entry's marker column), a line with less indent, or EOF.
133
+ */
134
+ export declare function findItemEnd(lines: readonly string[], startIdx: number, indent: number): number;
110
135
  /**
111
136
  * Find the 0-based line range [start, end) of the attribute block
112
137
  * for an entry starting at the given line.
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/formatter/mod.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,KAAK,EACV,SAAS,EACT,UAAU,EAGX,MAAM,iBAAiB,CAAC;AA0BzB;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,C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,EAAE,SAAS,EAAE,GAAG,SAAS,EAAE,CAmB/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAGnD;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAC5B,UAAU,EAAE,SAAS,EAAE,GACtB,SAAS,EAAE,CA2Bb;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,SAAS,EAAE,EACvB,MAAM,EAAE,MAAM,GACb,MAAM,CAKR;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,MAAM,CAcR;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,GACb;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CA2B5C"}
@@ -14,10 +14,13 @@ exports.expandCsvValues = expandCsvValues;
14
14
  exports.canonicalizeKey = canonicalizeKey;
15
15
  exports.sortAttributes = sortAttributes;
16
16
  exports.renderAttributeBlock = renderAttributeBlock;
17
+ exports.findItemEnd = findItemEnd;
17
18
  exports.findAttributeBlockRange = findAttributeBlockRange;
19
+ const path_1 = require("@std/path");
18
20
  const ulid_1 = require("@std/ulid");
19
21
  const yaml_1 = require("@std/yaml");
20
22
  const mod_js_1 = require("../model/mod.js");
23
+ const mod_js_2 = require("../discovery/mod.js");
21
24
  const attributes_js_1 = require("../parser/attributes.js");
22
25
  const frontmatter_js_1 = require("../parser/frontmatter.js");
23
26
  const markdown_js_1 = require("../parser/markdown.js");
@@ -29,6 +32,9 @@ const build_js_1 = require("../ast/build.js");
29
32
  const render_js_1 = require("../ast/render.js");
30
33
  const normalize_js_1 = require("../ast/normalize.js");
31
34
  const equivalence_js_1 = require("../ast/equivalence.js");
35
+ const prose_js_1 = require("./prose.js");
36
+ const dprint_js_1 = require("./dprint.js");
37
+ const md_equiv_js_1 = require("./md_equiv.js");
32
38
  /**
33
39
  * Decide whether the EARS keyword at `offset` in `line` is at sentence
34
40
  * start (return value true). Delegates to the shared implementation in
@@ -185,6 +191,14 @@ const CANONICAL_ORDER = [
185
191
  * string, preserving the leading/trailing blank-line delimiters
186
192
  * that separate the body from the title and attr block.
187
193
  *
194
+ * When `proseFormat` (ADR-029) is supplied, the AST-canonical body is
195
+ * further polished by the whole-document Markdown formatter (dprint),
196
+ * gated by CommonMark-semantic equivalence — NOT the strict ADR-015
197
+ * relation above, which is byte-verbatim on inline markup and would
198
+ * reject every legitimate re-wrap. A rejected polish keeps the
199
+ * AST-canonical body and raises an info diagnostic (MSL-F012) naming
200
+ * the entry.
201
+ *
188
202
  * Returns `true` when any entry body was rewritten (so `format()` can
189
203
  * keep `changed` accurate for `--check` mode); `false` when every body
190
204
  * was already §5.2-canonical.
@@ -193,7 +207,7 @@ const CANONICAL_ORDER = [
193
207
  * `normalizeBodyAst` is FORMATTER-ONLY — the validate/parse path must
194
208
  * never call it.
195
209
  */
196
- function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
210
+ function emitBodyViaAst(lines, file, diagnostics, cachedEntries, proseFormat) {
197
211
  // When the caller supplies pre-parsed entries whose line numbers are still
198
212
  // valid in `lines` (i.e., no line-count-changing operations occurred before
199
213
  // this call), skip the re-parse entirely — the common hot path for files
@@ -256,6 +270,52 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
256
270
  });
257
271
  continue;
258
272
  }
273
+ // ADR-029: polish the canonical body with the whole-document
274
+ // Markdown formatter. Gated by CommonMark-semantic equivalence —
275
+ // NOT the strict ADR-015 relation, which is byte-verbatim on
276
+ // inline markup and would reject every legitimate re-wrap. On
277
+ // rejection keep the AST-canonical body and say so (info).
278
+ let finalBody = emittedBody;
279
+ if (proseFormat !== undefined) {
280
+ // The body is formatted DEDENTED and re-indented afterwards, so the
281
+ // width budget must shrink by the indent — otherwise a wrap point
282
+ // landing near 80 columns dedented exceeds 80 re-indented, and an
283
+ // external whole-file dprint view (which sees the indent) re-wraps
284
+ // it: a formatter ping-pong. Floor of 20 keeps a pathological indent
285
+ // from degenerating into one-word-per-line output.
286
+ let polished;
287
+ try {
288
+ polished = proseFormat(emittedBody, {
289
+ lineWidth: Math.max(20, dprint_js_1.MARKSPEC_MARKDOWN_GLOBAL_CONFIG.lineWidth - indent),
290
+ }).replace(/\n$/, "");
291
+ }
292
+ catch {
293
+ // The dprint WASM formatter can throw on a pathological body.
294
+ // Treat a throw exactly like a rejected rewrite: keep the
295
+ // canonical body and report the fallback (never crash the run).
296
+ diagnostics.push({
297
+ code: "MSL-F012",
298
+ severity: "info",
299
+ message: `${entry.displayId}: Markdown pass errored — kept ` +
300
+ `the canonical body`,
301
+ location: entry.location,
302
+ });
303
+ }
304
+ if (polished !== undefined && polished !== emittedBody) {
305
+ if ((0, md_equiv_js_1.markdownSemanticallyEquivalent)(emittedBody, polished)) {
306
+ finalBody = polished;
307
+ }
308
+ else {
309
+ diagnostics.push({
310
+ code: "MSL-F012",
311
+ severity: "info",
312
+ message: `${entry.displayId}: Markdown pass produced a ` +
313
+ `non-equivalent body — kept the canonical body`,
314
+ location: entry.location,
315
+ });
316
+ }
317
+ }
318
+ }
259
319
  // The emitted body is the §5.2-canonical body and re-builds
260
320
  // AST-equivalent to the canonical AST. Splice it back into the
261
321
  // document — the AST is the load-bearing emission path.
@@ -274,7 +334,7 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
274
334
  while (ei >= si && rawSegment[ei].trim() === "") {
275
335
  trailBlanks.unshift(rawSegment[ei--]);
276
336
  }
277
- const emittedLines = emittedBody.split("\n").map((l) => l ? `${indentStr}${l}` : l);
337
+ const emittedLines = finalBody.split("\n").map((l) => l ? `${indentStr}${l}` : l);
278
338
  const newSegment = [...leadBlanks, ...emittedLines, ...trailBlanks];
279
339
  // `changed` accuracy: only flag a body rewrite when the spliced
280
340
  // segment actually differs from the original lines (a §5.2-canonical
@@ -340,7 +400,16 @@ function format(markdown, options) {
340
400
  const body = rawBody;
341
401
  const { entries } = (0, markdown_js_1.parseMarkdown)(body, { file });
342
402
  const diagnostics = [...fm.diagnostics];
343
- if (entries.length === 0 && !fm.hadFrontMatter) {
403
+ // ADR-029: the whole-document Markdown pass is Markdown-only. Gate on the
404
+ // file extension HERE so the invariant has one home — a caller that wires
405
+ // formatMarkdownProse without its own guard (e.g. a future write tool, or
406
+ // formatSource forwarding options with a source-file label) cannot silently
407
+ // reflow a source file's doc comment as Markdown. The CommonMark-semantic
408
+ // gate cannot catch that class, so it must be prevented, not detected. The
409
+ // CLI/LSP call-site guards remain as defense-in-depth.
410
+ const isMarkdownFile = mod_js_2.MARKDOWN_EXTENSIONS.has((0, path_1.extname)(file).toLowerCase());
411
+ const proseFormat = isMarkdownFile ? options?.formatMarkdownProse : undefined;
412
+ if (entries.length === 0 && !fm.hadFrontMatter && proseFormat === undefined) {
344
413
  // No entries and no front matter — nothing to format. Returning the
345
414
  // original `markdown` preserves the source's exact byte sequence,
346
415
  // including its line-ending convention.
@@ -354,11 +423,39 @@ function format(markdown, options) {
354
423
  for (const entry of sorted) {
355
424
  const indent = (entry.location.column - 1) + 2;
356
425
  let attrs = [...entry.rawAttributes];
426
+ const titleLineIdx = entry.location.line - 1;
427
+ // #686: a title that soft-wraps onto extra physical lines is a single
428
+ // Markdown paragraph, but the line-based passes here and in
429
+ // `emitBodyViaAst` (which takes `titleLineIdx + 1` as the body start)
430
+ // assume the title occupies one physical line. Collapse the wrapped
431
+ // title onto a single line so Id stamping and body splicing land on the
432
+ // right lines and the continuation is not clobbered or dropped. The
433
+ // parser already folded the title text on the model side; this repairs
434
+ // the raw buffer to match. The scan runs from the title line to the
435
+ // first blank line (the title/body separator), bounded above by the
436
+ // attribute block so a malformed entry with no blank line before its
437
+ // trailer cannot swallow it.
438
+ if (titleLineIdx >= 0 && titleLineIdx < lines.length) {
439
+ const attrRange = findAttributeBlockRange(lines, entry.location.line, indent);
440
+ const limit = attrRange ? attrRange.start : lines.length;
441
+ let titleEnd = titleLineIdx;
442
+ while (titleEnd + 1 < limit && lines[titleEnd + 1].trim() !== "") {
443
+ titleEnd++;
444
+ }
445
+ if (titleEnd > titleLineIdx) {
446
+ const collapsed = lines[titleLineIdx].replace(/\s+$/, "") + " " +
447
+ lines
448
+ .slice(titleLineIdx + 1, titleEnd + 1)
449
+ .map((l) => l.trim())
450
+ .join(" ");
451
+ lines.splice(titleLineIdx, titleEnd - titleLineIdx + 1, collapsed);
452
+ changed = true;
453
+ }
454
+ }
357
455
  // Title-line bullet canonicalisation per spec §3.2: rewrite `*`
358
456
  // or `+` to `-`. The list-item position from the parser is the
359
457
  // line carrying the bullet marker; we only touch the marker
360
458
  // character itself, leaving the rest of the title alone.
361
- const titleLineIdx = entry.location.line - 1;
362
459
  if (titleLineIdx >= 0 && titleLineIdx < lines.length) {
363
460
  const titleLine = lines[titleLineIdx];
364
461
  const markerCol = entry.location.column - 1;
@@ -461,9 +558,40 @@ function format(markdown, options) {
461
558
  // emitBodyViaAst skips its re-parse (the hot path for already-formatted
462
559
  // files). When `changed` is true, any splicing or collapse may have
463
560
  // shifted positions, so pass undefined to trigger the normal re-parse.
464
- if (emitBodyViaAst(collapsedLines, file, diagnostics, changed ? undefined : entries))
561
+ if (emitBodyViaAst(collapsedLines, file, diagnostics, changed ? undefined : entries, proseFormat))
465
562
  changed = true;
466
- const formattedBody = collapsedLines.join("\n");
563
+ // ADR-029 whole-document Markdown pass: prose segments outside entry
564
+ // blocks through dprint, gated per segment. Entry bodies were already
565
+ // polished inside emitBodyViaAst. Re-parse for fresh extents when any
566
+ // earlier pass changed line positions.
567
+ let proseLines = collapsedLines;
568
+ if (proseFormat !== undefined) {
569
+ const proseEntries = changed
570
+ ? (0, markdown_js_1.parseMarkdown)(collapsedLines.join("\n"), { file }).entries
571
+ : entries;
572
+ const extents = proseEntries.map((e) => {
573
+ const start = e.location.line - 1;
574
+ const entryIndent = (e.location.column - 1) + 2;
575
+ return { start, end: findItemEnd(collapsedLines, start, entryIndent) };
576
+ });
577
+ const prose = (0, prose_js_1.formatProseSegments)(collapsedLines, extents, proseFormat);
578
+ if (prose.changed)
579
+ changed = true;
580
+ for (const fallback of prose.fallbacks) {
581
+ const cause = fallback.reason === "error"
582
+ ? "errored"
583
+ : "produced non-equivalent output";
584
+ diagnostics.push({
585
+ code: "MSL-F012",
586
+ severity: "info",
587
+ message: `Markdown pass ${cause} for this prose segment — kept ` +
588
+ `the original text`,
589
+ location: { file, line: fallback.line + 1, column: 1 },
590
+ });
591
+ }
592
+ proseLines = prose.lines;
593
+ }
594
+ const formattedBody = proseLines.join("\n");
467
595
  if (fm.hadFrontMatter) {
468
596
  const canonicalFm = renderFrontMatter(fm.attributes);
469
597
  const outputLf = canonicalFm + formattedBody;
@@ -626,6 +754,7 @@ function renderAttributeBlock(attributes, indent) {
626
754
  }
627
755
  /**
628
756
  * Find the 0-based line index where a list item's content ends.
757
+ * Exported for the ADR-029 prose pass (entry-extent computation).
629
758
  * Scans forward from the entry start, stopping at: a sibling list item
630
759
  * (`- ` at the entry's marker column), a line with less indent, or EOF.
631
760
  */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @module formatter/prose
3
+ *
4
+ * ADR-029 whole-document Markdown pass: splits a document's lines into
5
+ * prose / entry-block segments and routes each prose segment through
6
+ * the injected {@linkcode ProseFormatter} (dprint-markdown). Every
7
+ * rewritten segment must pass {@linkcode markdownSemanticallyEquivalent}
8
+ * against its original — a rejected segment is kept byte-identical and
9
+ * reported via `fallbacks` (with its reason) so `format()` can emit an
10
+ * advisory diagnostic ("never make a file worse").
11
+ *
12
+ * Entry blocks (title line → item end, trailers included) are never
13
+ * given to dprint here; entry BODIES are polished separately inside
14
+ * `emitBodyViaAst` (core/formatter/mod.ts) where the parser's
15
+ * dedent/re-indent machinery and the body-AST gate already live.
16
+ */
17
+ import type { ProseFormatter } from "./dprint.js";
18
+ /** 0-based `[start, end)` line span of one entry block. */
19
+ export interface EntryExtent {
20
+ readonly start: number;
21
+ readonly end: number;
22
+ }
23
+ /**
24
+ * Why a prose segment kept its original text instead of the formatted
25
+ * output: the dprint formatter threw (`"error"`), or its output failed the
26
+ * CommonMark-semantic gate (`"non-equivalent"`). Threaded so `format()`
27
+ * can emit an accurate MSL-F012 cause per segment rather than collapsing
28
+ * both into one message.
29
+ */
30
+ export interface ProseFallback {
31
+ readonly line: number;
32
+ readonly reason: "error" | "non-equivalent";
33
+ }
34
+ /** Result of {@linkcode formatProseSegments}. */
35
+ export interface ProsePassResult {
36
+ readonly lines: string[];
37
+ readonly changed: boolean;
38
+ /** One entry per prose segment that fell back to its original text,
39
+ * with the 0-based first line and the reason. */
40
+ readonly fallbacks: readonly ProseFallback[];
41
+ }
42
+ /**
43
+ * Format every prose gap between entry extents. Boundary blank lines
44
+ * stay outside the formatted chunk so entry-block separation is never
45
+ * disturbed.
46
+ */
47
+ export declare function formatProseSegments(lines: readonly string[], entryExtents: readonly EntryExtent[], proseFormat: ProseFormatter): ProsePassResult;
48
+ //# sourceMappingURL=prose.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prose.d.ts","sourceRoot":"","sources":["../../src/formatter/prose.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAGlD,2DAA2D;AAC3D,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,gBAAgB,CAAC;CAC7C;AAED,iDAAiD;AACjD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B;qDACiD;IACjD,QAAQ,CAAC,SAAS,EAAE,SAAS,aAAa,EAAE,CAAC;CAC9C;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,YAAY,EAAE,SAAS,WAAW,EAAE,EACpC,WAAW,EAAE,cAAc,GAC1B,eAAe,CA4DjB"}
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ /**
3
+ * @module formatter/prose
4
+ *
5
+ * ADR-029 whole-document Markdown pass: splits a document's lines into
6
+ * prose / entry-block segments and routes each prose segment through
7
+ * the injected {@linkcode ProseFormatter} (dprint-markdown). Every
8
+ * rewritten segment must pass {@linkcode markdownSemanticallyEquivalent}
9
+ * against its original — a rejected segment is kept byte-identical and
10
+ * reported via `fallbacks` (with its reason) so `format()` can emit an
11
+ * advisory diagnostic ("never make a file worse").
12
+ *
13
+ * Entry blocks (title line → item end, trailers included) are never
14
+ * given to dprint here; entry BODIES are polished separately inside
15
+ * `emitBodyViaAst` (core/formatter/mod.ts) where the parser's
16
+ * dedent/re-indent machinery and the body-AST gate already live.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.formatProseSegments = formatProseSegments;
20
+ const md_equiv_js_1 = require("./md_equiv.js");
21
+ /**
22
+ * Format every prose gap between entry extents. Boundary blank lines
23
+ * stay outside the formatted chunk so entry-block separation is never
24
+ * disturbed.
25
+ */
26
+ function formatProseSegments(lines, entryExtents, proseFormat) {
27
+ const extents = [...entryExtents].sort((a, b) => a.start - b.start);
28
+ const out = [];
29
+ const fallbacks = [];
30
+ let changed = false;
31
+ let cursor = 0;
32
+ const flushProse = (gapStart, gapEnd) => {
33
+ const segment = lines.slice(gapStart, gapEnd);
34
+ // Keep boundary blank lines verbatim, format only the core.
35
+ let from = 0;
36
+ while (from < segment.length && segment[from].trim() === "")
37
+ from++;
38
+ let to = segment.length;
39
+ while (to > from && segment[to - 1].trim() === "")
40
+ to--;
41
+ if (from >= to) {
42
+ out.push(...segment);
43
+ return;
44
+ }
45
+ const chunk = segment.slice(from, to).join("\n");
46
+ let formatted;
47
+ try {
48
+ formatted = proseFormat(chunk).replace(/\n$/, "");
49
+ }
50
+ catch {
51
+ // The dprint WASM formatter can throw on a pathological fragment.
52
+ // Treat a throw exactly like a rejected rewrite: keep the original
53
+ // segment and report the fallback (never crash the whole run).
54
+ fallbacks.push({ line: gapStart + from, reason: "error" });
55
+ out.push(...segment);
56
+ return;
57
+ }
58
+ if (formatted === chunk) {
59
+ out.push(...segment);
60
+ return;
61
+ }
62
+ if (!(0, md_equiv_js_1.markdownSemanticallyEquivalent)(chunk, formatted)) {
63
+ fallbacks.push({ line: gapStart + from, reason: "non-equivalent" });
64
+ out.push(...segment);
65
+ return;
66
+ }
67
+ changed = true;
68
+ out.push(...segment.slice(0, from));
69
+ out.push(...formatted.split("\n"));
70
+ out.push(...segment.slice(to));
71
+ };
72
+ for (const extent of extents) {
73
+ // Defensive clamp: extents from a healthy parse are disjoint and
74
+ // well-formed, but this module is the last guard between entry
75
+ // blocks and the prose formatter — never re-emit lines already
76
+ // written (overlap/duplicate extents) and treat end < start as
77
+ // zero-width instead of walking the cursor backwards.
78
+ const start = Math.max(extent.start, cursor);
79
+ const end = Math.max(extent.end, start);
80
+ if (start > cursor)
81
+ flushProse(cursor, start);
82
+ out.push(...lines.slice(start, end));
83
+ cursor = end;
84
+ }
85
+ if (cursor < lines.length)
86
+ flushProse(cursor, lines.length);
87
+ return { lines: out, changed, fallbacks };
88
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @module core/gates
3
+ *
4
+ * Composite-`check` gate stages (ADR-027). Each function is a pure,
5
+ * independently-testable transformation from already-gathered inputs to a
6
+ * `Diagnostic[]`; the CLI `check` command orchestrates them (gather inputs →
7
+ * call stages → merge diagnostics → render) and owns the scope policy that
8
+ * decides whether they run at all (project-wide only).
9
+ *
10
+ * Extracted from `cli/commands/check.ts` (#659) so the diagnostic-producing
11
+ * logic lives in `core` — composable, unit-testable in isolation, and reusable
12
+ * by future surfaces — rather than inline in the command body. The command
13
+ * keeps the I/O it must do (loading the Markdown prose formatter, reading
14
+ * `markspec.lock`) and feeds the results in.
15
+ *
16
+ * `gates` is a top-level composition layer: it depends on `formatter`,
17
+ * `parser`, `refs`, `lock`, and `lint`, and nothing in those depends back on
18
+ * it — no cycle.
19
+ */
20
+ import type { Diagnostic, EffectiveProfile, Entry } from "../model/mod.js";
21
+ import type { ProseFormatter } from "../formatter/dprint.js";
22
+ import { type LockEdge, type ParseLockfileResult } from "../lock/mod.js";
23
+ /**
24
+ * Format-drift gate — the `MSL-F010` (formatter drift) and `MSL-F011`
25
+ * (reference-canonicalization drift) findings.
26
+ *
27
+ * Runs the SAME `format() → parse → canonicalizeRefs` sequence `markspec fmt`
28
+ * performs, from the same exclude-aware corpus, so bare `check` and
29
+ * `fmt --check` never disagree on what "formatted" means. `MSL-F010` is pure
30
+ * formatter drift; `MSL-F011` is reference-canonicalization drift (a ULID or
31
+ * stale display ID `fmt` would rewrite) — kept distinct so the author knows
32
+ * which fmt concern fired. Markdown only — `markspec fmt` never rewrites source
33
+ * files, so the caller passes only Markdown file contents.
34
+ *
35
+ * @param mdContents Markdown file path → current on-disk content.
36
+ * @param entries The full parsed entry set (project + corpus). Only
37
+ * project-owned entries (`!e.origin`) build the reference index
38
+ * `canonicalizeRefs` heals against — `markspec fmt` is corpus-blind (ADR-030).
39
+ * @param ledger The lockfile's `[[edge]]` ULID ledger (`lockfile.edges`, or
40
+ * `[]` when there is no lockfile), threaded into `canonicalizeRefs`.
41
+ * @param formatMarkdownProse The loaded ADR-029 whole-document Markdown
42
+ * formatter, or `undefined` to degrade to entry-only formatting.
43
+ */
44
+ export declare function fmtDriftGate(mdContents: ReadonlyMap<string, string>, entries: readonly Entry[], ledger: readonly LockEdge[], formatMarkdownProse: ProseFormatter | undefined): Promise<Diagnostic[]>;
45
+ /**
46
+ * Lockfile-drift gate — the `MSL-L212` offline traceability-edge drift finding.
47
+ *
48
+ * A malformed lockfile surfaces the parser's own diagnostics unchanged. An
49
+ * intact lockfile is compared against the current graph's canonical edge hash.
50
+ * Offline by design — upstream resolution (network) stays in
51
+ * `markspec lock --check`.
52
+ *
53
+ * Corpus-blind by design: the lockfile is not corpus-aware yet (ADR-030 defers
54
+ * lockfile integration), so `markspec lock` never counts corpus edges. Counting
55
+ * them here would raise an `MSL-L212` drift error that `markspec lock` can never
56
+ * fix — a consumer gate must not fail on upstream content the consumer cannot
57
+ * re-lock. The gate therefore filters to project-owned entries (`!e.origin`),
58
+ * mirroring `markspec lock`.
59
+ *
60
+ * @param lockParse The parsed `markspec.lock` (already read from disk).
61
+ * @param lockPath Absolute path to `markspec.lock`, used as the diagnostic
62
+ * location so JSON consumers that group by `location.file` keep the finding.
63
+ * @param entries The full parsed entry set; corpus entries are filtered out.
64
+ */
65
+ export declare function lockfileDriftGate(lockParse: ParseLockfileResult, lockPath: string, entries: readonly Entry[]): Promise<Diagnostic[]>;
66
+ /**
67
+ * Prose-lint gate — the advisory `MSL-Q` prose-analysis findings, projected to
68
+ * plain {@linkcode Diagnostic}s.
69
+ *
70
+ * Pass the FULL entry set (project + corpus) and the active profile.
71
+ * {@linkcode runLint} excludes corpus entries from its output but keeps them in
72
+ * the glossary / `$Identifier` indexes, so a corpus-defined term still silences
73
+ * Q500 in project prose (ADR-030 §D4). The profile threads into `isProseScope`
74
+ * so profile-typed entries are scoped (#675).
75
+ *
76
+ * `runLint`'s {@linkcode LintDiagnostic} carries `slug`/`group`/`score` fields
77
+ * that must not leak into `check`'s stable JSON schema — the result is projected
78
+ * to plain {@linkcode Diagnostic}. `runLint`'s `readFile` option (for glossary
79
+ * file indexing) is not needed here: `check` passes no `glossaryFilePaths`.
80
+ */
81
+ export declare function proseLintGate(entries: readonly Entry[], profile: EffectiveProfile | undefined): Promise<Diagnostic[]>;
82
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/gates/mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAE3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,mBAAmB,EACzB,MAAM,gBAAgB,CAAC;AAGxB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,YAAY,CAChC,UAAU,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EACvC,OAAO,EAAE,SAAS,KAAK,EAAE,EACzB,MAAM,EAAE,SAAS,QAAQ,EAAE,EAC3B,mBAAmB,EAAE,cAAc,GAAG,SAAS,GAC9C,OAAO,CAAC,UAAU,EAAE,CAAC,CAuCvB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,mBAAmB,EAC9B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,SAAS,KAAK,EAAE,GACxB,OAAO,CAAC,UAAU,EAAE,CAAC,CAiBvB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,SAAS,KAAK,EAAE,EACzB,OAAO,EAAE,gBAAgB,GAAG,SAAS,GACpC,OAAO,CAAC,UAAU,EAAE,CAAC,CAQvB"}