@driftsys/markspec 0.9.0 → 0.10.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 (87) hide show
  1. package/esm/compiler/mod.d.ts +7 -0
  2. package/esm/compiler/mod.d.ts.map +1 -1
  3. package/esm/compiler/mod.js +17 -3
  4. package/esm/compiler/schema.d.ts +8 -1
  5. package/esm/compiler/schema.d.ts.map +1 -1
  6. package/esm/compiler/schema.js +8 -1
  7. package/esm/formatter/dprint.d.ts +62 -0
  8. package/esm/formatter/dprint.d.ts.map +1 -0
  9. package/esm/formatter/dprint.js +83 -0
  10. package/esm/formatter/md_equiv.d.ts +24 -0
  11. package/esm/formatter/md_equiv.d.ts.map +1 -0
  12. package/esm/formatter/md_equiv.js +81 -0
  13. package/esm/formatter/mod.d.ts +25 -0
  14. package/esm/formatter/mod.d.ts.map +1 -1
  15. package/esm/formatter/mod.js +106 -6
  16. package/esm/formatter/prose.d.ts +48 -0
  17. package/esm/formatter/prose.d.ts.map +1 -0
  18. package/esm/formatter/prose.js +85 -0
  19. package/esm/mod.d.ts +8 -4
  20. package/esm/mod.d.ts.map +1 -1
  21. package/esm/mod.js +5 -2
  22. package/esm/model/mod.d.ts +19 -1
  23. package/esm/model/mod.d.ts.map +1 -1
  24. package/esm/model/profile.d.ts +34 -0
  25. package/esm/model/profile.d.ts.map +1 -1
  26. package/esm/profile/chain.js +1 -0
  27. package/esm/profile/delivered.d.ts +27 -0
  28. package/esm/profile/delivered.d.ts.map +1 -0
  29. package/esm/profile/delivered.js +60 -0
  30. package/esm/profile/manifest.d.ts +1 -0
  31. package/esm/profile/manifest.d.ts.map +1 -1
  32. package/esm/profile/manifest.js +107 -0
  33. package/esm/profile/merge.d.ts.map +1 -1
  34. package/esm/profile/merge.js +21 -0
  35. package/esm/refs/mod.d.ts.map +1 -1
  36. package/esm/refs/mod.js +22 -0
  37. package/esm/reporter/mod.js +17 -4
  38. package/esm/validator/corpus.d.ts +25 -0
  39. package/esm/validator/corpus.d.ts.map +1 -0
  40. package/esm/validator/corpus.js +138 -0
  41. package/esm/validator/mod.d.ts +2 -0
  42. package/esm/validator/mod.d.ts.map +1 -1
  43. package/esm/validator/mod.js +1 -0
  44. package/package.json +3 -1
  45. package/script/compiler/mod.d.ts +7 -0
  46. package/script/compiler/mod.d.ts.map +1 -1
  47. package/script/compiler/mod.js +16 -2
  48. package/script/compiler/schema.d.ts +8 -1
  49. package/script/compiler/schema.d.ts.map +1 -1
  50. package/script/compiler/schema.js +8 -1
  51. package/script/formatter/dprint.d.ts +62 -0
  52. package/script/formatter/dprint.d.ts.map +1 -0
  53. package/script/formatter/dprint.js +120 -0
  54. package/script/formatter/md_equiv.d.ts +24 -0
  55. package/script/formatter/md_equiv.d.ts.map +1 -0
  56. package/script/formatter/md_equiv.js +87 -0
  57. package/script/formatter/mod.d.ts +25 -0
  58. package/script/formatter/mod.d.ts.map +1 -1
  59. package/script/formatter/mod.js +106 -5
  60. package/script/formatter/prose.d.ts +48 -0
  61. package/script/formatter/prose.d.ts.map +1 -0
  62. package/script/formatter/prose.js +88 -0
  63. package/script/mod.d.ts +8 -4
  64. package/script/mod.d.ts.map +1 -1
  65. package/script/mod.js +14 -3
  66. package/script/model/mod.d.ts +19 -1
  67. package/script/model/mod.d.ts.map +1 -1
  68. package/script/model/profile.d.ts +34 -0
  69. package/script/model/profile.d.ts.map +1 -1
  70. package/script/profile/chain.js +1 -0
  71. package/script/profile/delivered.d.ts +27 -0
  72. package/script/profile/delivered.d.ts.map +1 -0
  73. package/script/profile/delivered.js +65 -0
  74. package/script/profile/manifest.d.ts +1 -0
  75. package/script/profile/manifest.d.ts.map +1 -1
  76. package/script/profile/manifest.js +108 -1
  77. package/script/profile/merge.d.ts.map +1 -1
  78. package/script/profile/merge.js +21 -0
  79. package/script/refs/mod.d.ts.map +1 -1
  80. package/script/refs/mod.js +22 -0
  81. package/script/reporter/mod.js +17 -4
  82. package/script/validator/corpus.d.ts +25 -0
  83. package/script/validator/corpus.d.ts.map +1 -0
  84. package/script/validator/corpus.js +142 -0
  85. package/script/validator/mod.d.ts +2 -0
  86. package/script/validator/mod.d.ts.map +1 -1
  87. package/script/validator/mod.js +4 -1
@@ -43,6 +43,13 @@ export interface CompileOptions {
43
43
  * list is deduplicated and sorted for deterministic output.
44
44
  */
45
45
  readonly withContributors?: boolean;
46
+ /**
47
+ * Profile-delivered corpus entries (ADR-030), pre-loaded and
48
+ * origin-stamped by `loadDeliveredCorpus`. Injected AHEAD of project
49
+ * entries so first-entry-wins graph slots resolve to the corpus
50
+ * deterministically. Optional — absent means no corpus.
51
+ */
52
+ readonly corpusEntries?: readonly Entry[];
46
53
  }
47
54
  /** Compiled project output with resolved traceability graph. */
48
55
  export interface CompileResult {
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/compiler/mod.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACV,UAAU,EACV,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,KAAK,EAEL,IAAI,EAEL,MAAM,iBAAiB,CAAC;AAQzB,OAAO,EAAE,KAAK,YAAY,EAAgB,MAAM,gBAAgB,CAAC;AAOjE,uCAAuC;AACvC,MAAM,WAAW,cAAc;IAC7B,4FAA4F;IAC5F,QAAQ,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACrD,qGAAqG;IACrG,QAAQ,CAAC,OAAO,CAAC,EAAE,gBAAgB,CAAC;IACpC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAClB,IAAI,EAAE,MAAM,KACT,OAAO,CAAC;QAAE,KAAK,EAAE,IAAI,GAAG,IAAI,CAAA;KAAE,GAAG,SAAS,CAAC,CAAC;IACjD;;;;;;;;;OASG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,CACjB,IAAI,EAAE,MAAM,KACT,OAAO,CACV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D,8BAA8B;IAC9B,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;IAChC,kDAAkD;IAClD,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;IAC1D,iEAAiE;IACjE,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;IAC1D,4GAA4G;IAC5G,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAClD,+CAA+C;IAC/C,QAAQ,CAAC,WAAW,EAAE,SAAS,UAAU,EAAE,CAAC;IAC5C;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC;CACrC;AA4BD;;;;;;;GAOG;AACH,wBAAsB,OAAO,CAC3B,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,aAAa,CAAC,CAgMxB;AA+ED,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,YAAY,EACV,uBAAuB,EACvB,eAAe,EACf,sBAAsB,GACvB,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,YAAY,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC"}
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { makeDisplayId } from "../model/mod.js";
8
8
  import { parseFile } from "../parser/mod.js";
9
- import { classifyEntriesStage, suppressDeclaredAttrR010, validate, } from "../validator/mod.js";
9
+ import { attributeCorpusDiagnostics, classifyEntriesStage, detectCorpusCollisions, suppressDeclaredAttrR010, validate, } from "../validator/mod.js";
10
10
  import { validateTypl } from "../typl/mod.js";
11
11
  import { buildEffectiveDisciplineRegistry } from "../profile/discipline_registry.js";
12
12
  import { ATTR_TO_LINK_KIND } from "./constants.js";
@@ -110,7 +110,7 @@ class Semaphore {
110
110
  */
111
111
  export async function compile(paths, options) {
112
112
  const read = options.readFile;
113
- const allEntries = [];
113
+ const allEntries = [...(options.corpusEntries ?? [])];
114
114
  const parseDiagnostics = [];
115
115
  const documents = new Map();
116
116
  // Phase 1: Read and parse all files with bounded concurrency (16 slots).
@@ -238,11 +238,25 @@ export async function compile(paths, options) {
238
238
  // diagnostics are already included in validationDiagnostics, so we discard
239
239
  // them to avoid duplicates in the output.
240
240
  const { registry: typeRegistry } = validateTypl([...entries.values()]);
241
- const diagnostics = [
241
+ let diagnostics = [
242
242
  ...parseDiagnostics,
243
243
  ...validationDiagnostics,
244
244
  ...linkTargetDiags,
245
245
  ];
246
+ // Phase 5: Corpus-aware diagnostic post-pass (ADR-030). A project entry
247
+ // that reuses a display ID or Id already delivered by a corpus is
248
+ // MSL-R014, not the generic MSL-R005/R006/I007/I008 duplicate codes —
249
+ // and findings located inside a corpus file are downgraded to
250
+ // attributed warnings so consumer builds don't go red over upstream
251
+ // bugs they cannot fix. No-op (and zero allocation beyond the spread
252
+ // above) when no corpus was injected.
253
+ if (options.corpusEntries && options.corpusEntries.length > 0) {
254
+ const collisions = detectCorpusCollisions(allEntries);
255
+ diagnostics = [
256
+ ...attributeCorpusDiagnostics(diagnostics, allEntries, collisions.collidedTokens),
257
+ ...collisions.diagnostics,
258
+ ];
259
+ }
246
260
  return {
247
261
  entries,
248
262
  links,
@@ -6,7 +6,7 @@
6
6
  * interchange.
7
7
  */
8
8
  import type { CompileResult } from "./mod.js";
9
- import type { Diagnostic, Entry, Link } from "../model/mod.js";
9
+ import type { Diagnostic, Entry, EntryOrigin, Link } from "../model/mod.js";
10
10
  import type { RegistryBinding, RegistryTypedef } from "../typl/mod.js";
11
11
  /**
12
12
  * JSON-serializable form of {@linkcode Entry}.
@@ -14,9 +14,16 @@ import type { RegistryBinding, RegistryTypedef } from "../typl/mod.js";
14
14
  * Identical to `Entry` except `typedAttributes` is a plain
15
15
  * `Record<string, readonly string[]>` instead of a `ReadonlyMap` — Maps are
16
16
  * not JSON-serializable. All other fields are passed through unchanged.
17
+ *
18
+ * `origin` (ADR-030) is restated explicitly here — rather than relying on
19
+ * the `Omit<Entry, ...>` passthrough — so the field-presence contract is
20
+ * documented at the serialization boundary: present verbatim on entries
21
+ * injected from a profile-delivered corpus, absent (not `null`) on
22
+ * project-authored entries.
17
23
  */
18
24
  export type SerializedEntry = Omit<Entry, "typedAttributes"> & {
19
25
  readonly typedAttributes?: Record<string, readonly string[]>;
26
+ readonly origin?: EntryOrigin;
20
27
  };
21
28
  /**
22
29
  * Serialized form of the {@linkcode TypeRegistry}.
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/compiler/schema.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,EAAE,iBAAiB,CAAC,GAAG;IAC7D,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;CAC9D,CAAC;AAEF;;;;;GAKG;AACH,MAAM,WAAW,sBAAsB;IACrC,8CAA8C;IAC9C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,CAAC,CAAC;IAC9D,sCAAsC;IACtC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,CAAC,CAAC;CAC/D;AAED;;;;;GAKG;AACH,MAAM,WAAW,uBAAuB;IACtC,mCAAmC;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM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CAA8C;IAC9C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,CAAC,CAAC;IAC9D,sCAAsC;IACtC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,CAAC,CAAC;CAC/D;AAED;;;;;GAKG;AACH,MAAM,WAAW,uBAAuB;IACtC,mCAAmC;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAClD,8BAA8B;IAC9B,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;IAChC,mDAAmD;IACnD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;IAClD,kEAAkE;IAClE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;IAClD,+CAA+C;IAC/C,QAAQ,CAAC,WAAW,EAAE,SAAS,UAAU,EAAE,CAAC;IAC5C,sCAAsC;IACtC,QAAQ,CAAC,YAAY,EAAE,sBAAsB,CAAC;CAC/C;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,aAAa,GACpB,uBAAuB,CAazB;AAgBD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,KAAK,GAAG,eAAe,CA4B5D"}
@@ -57,9 +57,16 @@ export function serializeEntry(entry) {
57
57
  const { sync: _sync, ...rest } = properties;
58
58
  properties = Object.keys(rest).length > 0 ? rest : undefined;
59
59
  }
60
+ // Pull `origin` (ADR-030) out of the spread so the key is entirely
61
+ // absent — not `origin: undefined` — on entries that did not come
62
+ // from a delivered corpus, matching the serialized-field-presence
63
+ // contract. Object rest destructuring drops the named key regardless
64
+ // of its value, unlike `...entry` alone.
65
+ const { origin, ...rest } = entry;
60
66
  return {
61
- ...entry,
67
+ ...rest,
62
68
  typedAttributes,
63
69
  properties,
70
+ ...(origin ? { origin } : {}),
64
71
  };
65
72
  }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @module formatter/dprint
3
+ *
4
+ * Loader for the embedded dprint-markdown WASM plugin (ADR-029).
5
+ * `markspec fmt` formats whole Markdown documents with one canonical,
6
+ * zero-config style; this module owns that style and the (cached)
7
+ * WASM instantiation. Dynamic imports keep the plugin off every code
8
+ * path except formatting (`fmt`, the `check` MSL-F010 drift gate, LSP
9
+ * documentFormatting).
10
+ *
11
+ * Node-compatible: `node:fs/promises` + WebAssembly only, no `Deno.*`.
12
+ *
13
+ * Packaging note: `@dprint/formatter` and `@dprint/markdown` are dynamically
14
+ * imported bare npm specifiers, and their `plugin.wasm` ships inside the npm
15
+ * package — no vendored copy in this repo. `deno compile` only embeds the
16
+ * resolved npm tree (and thus the wasm) when the compile entry point itself
17
+ * lives inside this workspace member (`packages/markspec/`); an entry point
18
+ * outside that tree can't resolve the import map at runtime. The project's
19
+ * one real compile target (`packages/markspec/main.ts`) already satisfies
20
+ * this, so it's a non-issue in production — it only bites a from-scratch
21
+ * smoke test placed elsewhere.
22
+ */
23
+ /** Per-call options for a {@linkcode ProseFormatter}. */
24
+ export interface ProseFormatOptions {
25
+ /** Override the effective line width for this fragment. Used by the
26
+ * entry-body polish: bodies are formatted dedented and re-indented
27
+ * afterwards, so the budget must shrink by the indent width to stay
28
+ * in agreement with a whole-file dprint view of the same content. */
29
+ readonly lineWidth?: number;
30
+ }
31
+ /** Formats a Markdown fragment to the canonical MarkSpec style. */
32
+ export type ProseFormatter = (markdown: string, options?: ProseFormatOptions) => string;
33
+ /**
34
+ * The fixed MarkSpec Markdown style (ADR-029). Zero configuration by
35
+ * design — one canonical form across every project. `newLineKind` is
36
+ * "lf" because `format()` operates on a pure-LF buffer and re-applies
37
+ * the file's detected line ending on output.
38
+ */
39
+ export declare const MARKSPEC_MARKDOWN_GLOBAL_CONFIG: Readonly<{
40
+ lineWidth: number;
41
+ newLineKind: "lf";
42
+ }>;
43
+ /** Plugin-level style knobs. See ADR-029 for the rationale per value.
44
+ *
45
+ * Frozen: this is the single canonical MarkSpec style, exported through the
46
+ * public barrel. Freezing stops a consumer from mutating the shared object
47
+ * after the formatter has already baked these values in at `instantiate()`
48
+ * (which would drift the entry-body width budget from the whole-document
49
+ * formatter — see `emitBodyViaAst`). */
50
+ export declare const MARKSPEC_MARKDOWN_PLUGIN_CONFIG: Readonly<Record<string, unknown>>;
51
+ /**
52
+ * Load the dprint-markdown WASM plugin (once — subsequent calls return
53
+ * the cached instance) and return a synchronous prose formatter.
54
+ *
55
+ * A failed instantiation is NOT cached: the rejected promise is cleared
56
+ * before it propagates, so the next call retries from scratch instead of
57
+ * replaying the same failure forever. This matters for the long-lived LSP
58
+ * session, where a transient WASM-load failure must not permanently
59
+ * disable formatting for the rest of the process.
60
+ */
61
+ export declare function loadMarkdownFormatter(): Promise<ProseFormatter>;
62
+ //# sourceMappingURL=dprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dprint.d.ts","sourceRoot":"","sources":["../../src/formatter/dprint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,yDAAyD;AACzD,MAAM,WAAW,kBAAkB;IACjC;;;yEAGqE;IACrE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG,CAC3B,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,KACzB,MAAM,CAAC;AAEZ;;;;;GAKG;AACH,eAAO,MAAM,+BAA+B,EAAE,QAAQ,CAAC;IACrD,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,IAAI,CAAC;CACnB,CAGC,CAAC;AAEH;;;;;;wCAMwC;AACxC,eAAO,MAAM,+BAA+B,EAAE,QAAQ,CACpD,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMvB,CAAC;AAIH;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,IAAI,OAAO,CAAC,cAAc,CAAC,CAM/D"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @module formatter/dprint
3
+ *
4
+ * Loader for the embedded dprint-markdown WASM plugin (ADR-029).
5
+ * `markspec fmt` formats whole Markdown documents with one canonical,
6
+ * zero-config style; this module owns that style and the (cached)
7
+ * WASM instantiation. Dynamic imports keep the plugin off every code
8
+ * path except formatting (`fmt`, the `check` MSL-F010 drift gate, LSP
9
+ * documentFormatting).
10
+ *
11
+ * Node-compatible: `node:fs/promises` + WebAssembly only, no `Deno.*`.
12
+ *
13
+ * Packaging note: `@dprint/formatter` and `@dprint/markdown` are dynamically
14
+ * imported bare npm specifiers, and their `plugin.wasm` ships inside the npm
15
+ * package — no vendored copy in this repo. `deno compile` only embeds the
16
+ * resolved npm tree (and thus the wasm) when the compile entry point itself
17
+ * lives inside this workspace member (`packages/markspec/`); an entry point
18
+ * outside that tree can't resolve the import map at runtime. The project's
19
+ * one real compile target (`packages/markspec/main.ts`) already satisfies
20
+ * this, so it's a non-issue in production — it only bites a from-scratch
21
+ * smoke test placed elsewhere.
22
+ */
23
+ /**
24
+ * The fixed MarkSpec Markdown style (ADR-029). Zero configuration by
25
+ * design — one canonical form across every project. `newLineKind` is
26
+ * "lf" because `format()` operates on a pure-LF buffer and re-applies
27
+ * the file's detected line ending on output.
28
+ */
29
+ export const MARKSPEC_MARKDOWN_GLOBAL_CONFIG = Object.freeze({
30
+ lineWidth: 80,
31
+ newLineKind: "lf",
32
+ });
33
+ /** Plugin-level style knobs. See ADR-029 for the rationale per value.
34
+ *
35
+ * Frozen: this is the single canonical MarkSpec style, exported through the
36
+ * public barrel. Freezing stops a consumer from mutating the shared object
37
+ * after the formatter has already baked these values in at `instantiate()`
38
+ * (which would drift the entry-body width budget from the whole-document
39
+ * formatter — see `emitBodyViaAst`). */
40
+ export const MARKSPEC_MARKDOWN_PLUGIN_CONFIG = Object.freeze({
41
+ textWrap: "always",
42
+ emphasisKind: "underscores",
43
+ strongKind: "asterisks",
44
+ unorderedListKind: "dashes",
45
+ });
46
+ let cached;
47
+ /**
48
+ * Load the dprint-markdown WASM plugin (once — subsequent calls return
49
+ * the cached instance) and return a synchronous prose formatter.
50
+ *
51
+ * A failed instantiation is NOT cached: the rejected promise is cleared
52
+ * before it propagates, so the next call retries from scratch instead of
53
+ * replaying the same failure forever. This matters for the long-lived LSP
54
+ * session, where a transient WASM-load failure must not permanently
55
+ * disable formatting for the rest of the process.
56
+ */
57
+ export function loadMarkdownFormatter() {
58
+ cached ??= instantiate().catch((err) => {
59
+ cached = undefined;
60
+ throw err;
61
+ });
62
+ return cached;
63
+ }
64
+ async function instantiate() {
65
+ const { createFromBuffer } = await import("@dprint/formatter");
66
+ const { getPath } = await import("@dprint/markdown");
67
+ const { readFile } = await import("node:fs/promises");
68
+ const wasm = await readFile(getPath());
69
+ // `readFile` returns a Node `Buffer`, whose `buffer` property is typed
70
+ // `ArrayBufferLike` (may be a `SharedArrayBuffer`) — not assignable to
71
+ // `BufferSource`'s `ArrayBuffer`-backed view. Copy into a plain
72
+ // `Uint8Array` so the type is unambiguous; this runs once per process
73
+ // (the result is cached by `loadMarkdownFormatter`).
74
+ const formatter = createFromBuffer(Uint8Array.from(wasm));
75
+ formatter.setConfig(MARKSPEC_MARKDOWN_GLOBAL_CONFIG, MARKSPEC_MARKDOWN_PLUGIN_CONFIG);
76
+ return (markdown, options) => formatter.formatText({
77
+ filePath: "fragment.md",
78
+ fileText: markdown,
79
+ overrideConfig: options?.lineWidth !== undefined
80
+ ? { lineWidth: options.lineWidth }
81
+ : undefined,
82
+ });
83
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @module formatter/md_equiv
3
+ *
4
+ * CommonMark-semantic Markdown equivalence — the gate for the ADR-029
5
+ * dprint pass. Two fragments are equivalent when they parse to the
6
+ * same mdast structure after eliding source `position`s and collapsing
7
+ * ASCII whitespace runs inside `text` node values. Only ASCII
8
+ * whitespace is collapsed — NBSP (U+00A0) and Unicode spaces are
9
+ * content, not wrap artifacts, and must not compare equal to a plain
10
+ * space. Soft-wrap positions,
11
+ * emphasis delimiter style (`*x*` vs `_x_`), table cell padding, and
12
+ * list marker style are presentation, not content — they compare
13
+ * equal. Hard breaks are `break` nodes in mdast, so wrap-collapsing
14
+ * cannot erase or fabricate one. Code (`code`, `inlineCode`), `html`,
15
+ * and definition `url`s stay byte-exact.
16
+ *
17
+ * DELIBERATELY weaker than ADR-015's `astEquivalent` (byte-verbatim on
18
+ * inline markup). Used ONLY to accept/reject dprint output; the
19
+ * ADR-015 relation still guards §5.2 body emission (MSL-F900) and must
20
+ * not be modified.
21
+ */
22
+ /** True when `a` and `b` are the same Markdown, modulo presentation. */
23
+ export declare function markdownSemanticallyEquivalent(a: string, b: string): boolean;
24
+ //# sourceMappingURL=md_equiv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"md_equiv.d.ts","sourceRoot":"","sources":["../../src/formatter/md_equiv.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAQH,wEAAwE;AACxE,wBAAgB,8BAA8B,CAC5C,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,GACR,OAAO,CAMT"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @module formatter/md_equiv
3
+ *
4
+ * CommonMark-semantic Markdown equivalence — the gate for the ADR-029
5
+ * dprint pass. Two fragments are equivalent when they parse to the
6
+ * same mdast structure after eliding source `position`s and collapsing
7
+ * ASCII whitespace runs inside `text` node values. Only ASCII
8
+ * whitespace is collapsed — NBSP (U+00A0) and Unicode spaces are
9
+ * content, not wrap artifacts, and must not compare equal to a plain
10
+ * space. Soft-wrap positions,
11
+ * emphasis delimiter style (`*x*` vs `_x_`), table cell padding, and
12
+ * list marker style are presentation, not content — they compare
13
+ * equal. Hard breaks are `break` nodes in mdast, so wrap-collapsing
14
+ * cannot erase or fabricate one. Code (`code`, `inlineCode`), `html`,
15
+ * and definition `url`s stay byte-exact.
16
+ *
17
+ * DELIBERATELY weaker than ADR-015's `astEquivalent` (byte-verbatim on
18
+ * inline markup). Used ONLY to accept/reject dprint output; the
19
+ * ADR-015 relation still guards §5.2 body emission (MSL-F900) and must
20
+ * not be modified.
21
+ */
22
+ import { unified } from "unified";
23
+ import remarkParse from "remark-parse";
24
+ import remarkGfm from "remark-gfm";
25
+ const parser = unified().use(remarkParse).use(remarkGfm);
26
+ /** True when `a` and `b` are the same Markdown, modulo presentation. */
27
+ export function markdownSemanticallyEquivalent(a, b) {
28
+ if (a === b)
29
+ return true;
30
+ return deepEqual(normalize(parser.parse(a)), normalize(parser.parse(b)));
31
+ }
32
+ /**
33
+ * Recursively strip `position` keys and collapse ASCII whitespace runs
34
+ * in `text` node values (reflow can only introduce ASCII spaces and
35
+ * newlines; `\s` would also match NBSP and Unicode Zs spaces, letting
36
+ * a content change pass as a wrap change). Returns a plain JSON-ish
37
+ * structure for comparison; never mutates the input tree.
38
+ */
39
+ function normalize(node) {
40
+ if (Array.isArray(node))
41
+ return node.map(normalize);
42
+ if (node === null || typeof node !== "object")
43
+ return node;
44
+ const src = node;
45
+ const out = {};
46
+ for (const key of Object.keys(src).sort()) {
47
+ if (key === "position")
48
+ continue;
49
+ if (key === "value" && src.type === "text" &&
50
+ typeof src.value === "string") {
51
+ out.value = src.value.replace(/[ \t\r\n\f\v]+/g, " ");
52
+ continue;
53
+ }
54
+ out[key] = normalize(src[key]);
55
+ }
56
+ return out;
57
+ }
58
+ /** Structural deep-equality over the normalized trees. */
59
+ function deepEqual(a, b) {
60
+ if (a === b)
61
+ return true;
62
+ if (typeof a !== typeof b)
63
+ return false;
64
+ if (a === null || b === null)
65
+ return a === b;
66
+ if (Array.isArray(a) || Array.isArray(b)) {
67
+ if (!Array.isArray(a) || !Array.isArray(b))
68
+ return false;
69
+ if (a.length !== b.length)
70
+ return false;
71
+ return a.every((v, i) => deepEqual(v, b[i]));
72
+ }
73
+ if (typeof a === "object" && typeof b === "object") {
74
+ const ak = Object.keys(a);
75
+ const bk = Object.keys(b);
76
+ if (ak.length !== bk.length)
77
+ return false;
78
+ return ak.every((k) => deepEqual(a[k], b[k]));
79
+ }
80
+ return false;
81
+ }
@@ -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,CAEvE;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAc/D;AA0OD,sCAAsC;AACtC,MAAM,WAAW,aAAa;IAC5B,yCAAyC;IACzC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,6CAA6C;IAC7C,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,MAAM,CAAC;IACrC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;CAC/B;AAED,oCAAoC;AACpC,MAAM,WAAW,YAAY;IAC3B,mCAAmC;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,QAAQ,CAAC,WAAW,EAAE,SAAS,UAAU,EAAE,CAAC;IAC5C,qCAAqC;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AA2BD;;;;;;;GAOG;AACH,wBAAgB,MAAM,CACpB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,aAAa,GACtB,YAAY,CAqLd;AA4DD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,SAAS,EAAE,CAmB/D;AA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,CAAC,EAAE,cAAc,CAAC;CAC/C;AAED,oCAAoC;AACpC,MAAM,WAAW,YAAY;IAC3B,mCAAmC;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,QAAQ,CAAC,WAAW,EAAE,SAAS,UAAU,EAAE,CAAC;IAC5C,qCAAqC;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AA2BD;;;;;;;GAOG;AACH,wBAAgB,MAAM,CACpB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,aAAa,GACtB,YAAY,CA8Nd;AA4DD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,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"}
@@ -5,9 +5,11 @@
5
5
  * ULID stamping, indentation normalization, trailing backslash enforcement,
6
6
  * and requirement block insertion.
7
7
  */
8
+ import { extname } from "@std/path";
8
9
  import { ulid as defaultUlid } from "@std/ulid";
9
10
  import { stringify as stringifyYaml } from "@std/yaml";
10
11
  import { attributeSpec, CSV_SPLITTABLE_TYPES, IDENTITY_KEY, } from "../model/mod.js";
12
+ import { MARKDOWN_EXTENSIONS } from "../discovery/mod.js";
11
13
  import { ATTR_LINE_RE } from "../parser/attributes.js";
12
14
  import { extractFrontMatter } from "../parser/frontmatter.js";
13
15
  import { parseMarkdown } from "../parser/markdown.js";
@@ -19,6 +21,9 @@ import { buildBodyAst } from "../ast/build.js";
19
21
  import { render as renderBodyAst } from "../ast/render.js";
20
22
  import { normalizeBodyAst } from "../ast/normalize.js";
21
23
  import { astEquivalent } from "../ast/equivalence.js";
24
+ import { formatProseSegments } from "./prose.js";
25
+ import { MARKSPEC_MARKDOWN_GLOBAL_CONFIG, } from "./dprint.js";
26
+ import { markdownSemanticallyEquivalent } from "./md_equiv.js";
22
27
  /**
23
28
  * Decide whether the EARS keyword at `offset` in `line` is at sentence
24
29
  * start (return value true). Delegates to the shared implementation in
@@ -175,6 +180,14 @@ const CANONICAL_ORDER = [
175
180
  * string, preserving the leading/trailing blank-line delimiters
176
181
  * that separate the body from the title and attr block.
177
182
  *
183
+ * When `proseFormat` (ADR-029) is supplied, the AST-canonical body is
184
+ * further polished by the whole-document Markdown formatter (dprint),
185
+ * gated by CommonMark-semantic equivalence — NOT the strict ADR-015
186
+ * relation above, which is byte-verbatim on inline markup and would
187
+ * reject every legitimate re-wrap. A rejected polish keeps the
188
+ * AST-canonical body and raises an info diagnostic (MSL-F012) naming
189
+ * the entry.
190
+ *
178
191
  * Returns `true` when any entry body was rewritten (so `format()` can
179
192
  * keep `changed` accurate for `--check` mode); `false` when every body
180
193
  * was already §5.2-canonical.
@@ -183,7 +196,7 @@ const CANONICAL_ORDER = [
183
196
  * `normalizeBodyAst` is FORMATTER-ONLY — the validate/parse path must
184
197
  * never call it.
185
198
  */
186
- function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
199
+ function emitBodyViaAst(lines, file, diagnostics, cachedEntries, proseFormat) {
187
200
  // When the caller supplies pre-parsed entries whose line numbers are still
188
201
  // valid in `lines` (i.e., no line-count-changing operations occurred before
189
202
  // this call), skip the re-parse entirely — the common hot path for files
@@ -246,6 +259,52 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
246
259
  });
247
260
  continue;
248
261
  }
262
+ // ADR-029: polish the canonical body with the whole-document
263
+ // Markdown formatter. Gated by CommonMark-semantic equivalence —
264
+ // NOT the strict ADR-015 relation, which is byte-verbatim on
265
+ // inline markup and would reject every legitimate re-wrap. On
266
+ // rejection keep the AST-canonical body and say so (info).
267
+ let finalBody = emittedBody;
268
+ if (proseFormat !== undefined) {
269
+ // The body is formatted DEDENTED and re-indented afterwards, so the
270
+ // width budget must shrink by the indent — otherwise a wrap point
271
+ // landing near 80 columns dedented exceeds 80 re-indented, and an
272
+ // external whole-file dprint view (which sees the indent) re-wraps
273
+ // it: a formatter ping-pong. Floor of 20 keeps a pathological indent
274
+ // from degenerating into one-word-per-line output.
275
+ let polished;
276
+ try {
277
+ polished = proseFormat(emittedBody, {
278
+ lineWidth: Math.max(20, MARKSPEC_MARKDOWN_GLOBAL_CONFIG.lineWidth - indent),
279
+ }).replace(/\n$/, "");
280
+ }
281
+ catch {
282
+ // The dprint WASM formatter can throw on a pathological body.
283
+ // Treat a throw exactly like a rejected rewrite: keep the
284
+ // canonical body and report the fallback (never crash the run).
285
+ diagnostics.push({
286
+ code: "MSL-F012",
287
+ severity: "info",
288
+ message: `${entry.displayId}: Markdown pass errored — kept ` +
289
+ `the canonical body`,
290
+ location: entry.location,
291
+ });
292
+ }
293
+ if (polished !== undefined && polished !== emittedBody) {
294
+ if (markdownSemanticallyEquivalent(emittedBody, polished)) {
295
+ finalBody = polished;
296
+ }
297
+ else {
298
+ diagnostics.push({
299
+ code: "MSL-F012",
300
+ severity: "info",
301
+ message: `${entry.displayId}: Markdown pass produced a ` +
302
+ `non-equivalent body — kept the canonical body`,
303
+ location: entry.location,
304
+ });
305
+ }
306
+ }
307
+ }
249
308
  // The emitted body is the §5.2-canonical body and re-builds
250
309
  // AST-equivalent to the canonical AST. Splice it back into the
251
310
  // document — the AST is the load-bearing emission path.
@@ -264,7 +323,7 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
264
323
  while (ei >= si && rawSegment[ei].trim() === "") {
265
324
  trailBlanks.unshift(rawSegment[ei--]);
266
325
  }
267
- const emittedLines = emittedBody.split("\n").map((l) => l ? `${indentStr}${l}` : l);
326
+ const emittedLines = finalBody.split("\n").map((l) => l ? `${indentStr}${l}` : l);
268
327
  const newSegment = [...leadBlanks, ...emittedLines, ...trailBlanks];
269
328
  // `changed` accuracy: only flag a body rewrite when the spliced
270
329
  // segment actually differs from the original lines (a §5.2-canonical
@@ -330,7 +389,16 @@ export function format(markdown, options) {
330
389
  const body = rawBody;
331
390
  const { entries } = parseMarkdown(body, { file });
332
391
  const diagnostics = [...fm.diagnostics];
333
- if (entries.length === 0 && !fm.hadFrontMatter) {
392
+ // ADR-029: the whole-document Markdown pass is Markdown-only. Gate on the
393
+ // file extension HERE so the invariant has one home — a caller that wires
394
+ // formatMarkdownProse without its own guard (e.g. a future write tool, or
395
+ // formatSource forwarding options with a source-file label) cannot silently
396
+ // reflow a source file's doc comment as Markdown. The CommonMark-semantic
397
+ // gate cannot catch that class, so it must be prevented, not detected. The
398
+ // CLI/LSP call-site guards remain as defense-in-depth.
399
+ const isMarkdownFile = MARKDOWN_EXTENSIONS.has(extname(file).toLowerCase());
400
+ const proseFormat = isMarkdownFile ? options?.formatMarkdownProse : undefined;
401
+ if (entries.length === 0 && !fm.hadFrontMatter && proseFormat === undefined) {
334
402
  // No entries and no front matter — nothing to format. Returning the
335
403
  // original `markdown` preserves the source's exact byte sequence,
336
404
  // including its line-ending convention.
@@ -451,9 +519,40 @@ export function format(markdown, options) {
451
519
  // emitBodyViaAst skips its re-parse (the hot path for already-formatted
452
520
  // files). When `changed` is true, any splicing or collapse may have
453
521
  // shifted positions, so pass undefined to trigger the normal re-parse.
454
- if (emitBodyViaAst(collapsedLines, file, diagnostics, changed ? undefined : entries))
522
+ if (emitBodyViaAst(collapsedLines, file, diagnostics, changed ? undefined : entries, proseFormat))
455
523
  changed = true;
456
- const formattedBody = collapsedLines.join("\n");
524
+ // ADR-029 whole-document Markdown pass: prose segments outside entry
525
+ // blocks through dprint, gated per segment. Entry bodies were already
526
+ // polished inside emitBodyViaAst. Re-parse for fresh extents when any
527
+ // earlier pass changed line positions.
528
+ let proseLines = collapsedLines;
529
+ if (proseFormat !== undefined) {
530
+ const proseEntries = changed
531
+ ? parseMarkdown(collapsedLines.join("\n"), { file }).entries
532
+ : entries;
533
+ const extents = proseEntries.map((e) => {
534
+ const start = e.location.line - 1;
535
+ const entryIndent = (e.location.column - 1) + 2;
536
+ return { start, end: findItemEnd(collapsedLines, start, entryIndent) };
537
+ });
538
+ const prose = formatProseSegments(collapsedLines, extents, proseFormat);
539
+ if (prose.changed)
540
+ changed = true;
541
+ for (const fallback of prose.fallbacks) {
542
+ const cause = fallback.reason === "error"
543
+ ? "errored"
544
+ : "produced non-equivalent output";
545
+ diagnostics.push({
546
+ code: "MSL-F012",
547
+ severity: "info",
548
+ message: `Markdown pass ${cause} for this prose segment — kept ` +
549
+ `the original text`,
550
+ location: { file, line: fallback.line + 1, column: 1 },
551
+ });
552
+ }
553
+ proseLines = prose.lines;
554
+ }
555
+ const formattedBody = proseLines.join("\n");
457
556
  if (fm.hadFrontMatter) {
458
557
  const canonicalFm = renderFrontMatter(fm.attributes);
459
558
  const outputLf = canonicalFm + formattedBody;
@@ -616,10 +715,11 @@ export function renderAttributeBlock(attributes, indent) {
616
715
  }
617
716
  /**
618
717
  * Find the 0-based line index where a list item's content ends.
718
+ * Exported for the ADR-029 prose pass (entry-extent computation).
619
719
  * Scans forward from the entry start, stopping at: a sibling list item
620
720
  * (`- ` at the entry's marker column), a line with less indent, or EOF.
621
721
  */
622
- function findItemEnd(lines, startIdx, indent) {
722
+ export function findItemEnd(lines, startIdx, indent) {
623
723
  const indentStr = " ".repeat(indent);
624
724
  // The marker column is indent - 2 (e.g., indent 2 → marker at column 0).
625
725
  const markerPrefix = " ".repeat(Math.max(0, indent - 2)) + "- ";