@ybotok/loam 0.1.0-beta.1 → 0.1.0-beta.3

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 (120) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +6 -1
  3. package/SCHEMA.md +22 -4
  4. package/dist/cli.js +4 -0
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/adopt.js +17 -3
  7. package/dist/commands/adopt.js.map +1 -1
  8. package/dist/commands/archive.js +24 -8
  9. package/dist/commands/archive.js.map +1 -1
  10. package/dist/commands/delta.js +74 -47
  11. package/dist/commands/delta.js.map +1 -1
  12. package/dist/commands/dependencies.js +7 -2
  13. package/dist/commands/dependencies.js.map +1 -1
  14. package/dist/commands/docs-repo-gate.js +104 -0
  15. package/dist/commands/docs-repo-gate.js.map +1 -0
  16. package/dist/commands/explore.js +195 -0
  17. package/dist/commands/explore.js.map +1 -0
  18. package/dist/commands/format.js +17 -0
  19. package/dist/commands/format.js.map +1 -0
  20. package/dist/commands/gherkin.js +87 -48
  21. package/dist/commands/gherkin.js.map +1 -1
  22. package/dist/commands/init.js +3 -3
  23. package/dist/commands/init.js.map +1 -1
  24. package/dist/commands/instructions.js +80 -0
  25. package/dist/commands/instructions.js.map +1 -0
  26. package/dist/commands/list.js +10 -76
  27. package/dist/commands/list.js.map +1 -1
  28. package/dist/commands/migrate-openspec.js +45 -28
  29. package/dist/commands/migrate-openspec.js.map +1 -1
  30. package/dist/commands/new.js +35 -34
  31. package/dist/commands/new.js.map +1 -1
  32. package/dist/commands/rebase.js +2 -4
  33. package/dist/commands/rebase.js.map +1 -1
  34. package/dist/commands/show.js +26 -31
  35. package/dist/commands/show.js.map +1 -1
  36. package/dist/commands/status.js +17 -25
  37. package/dist/commands/status.js.map +1 -1
  38. package/dist/commands/unarchive.js +12 -5
  39. package/dist/commands/unarchive.js.map +1 -1
  40. package/dist/commands/validate.js +306 -142
  41. package/dist/commands/validate.js.map +1 -1
  42. package/dist/commands/verify.js +33 -17
  43. package/dist/commands/verify.js.map +1 -1
  44. package/dist/commands/vouch.js +156 -60
  45. package/dist/commands/vouch.js.map +1 -1
  46. package/dist/core/agent.js +392 -42
  47. package/dist/core/agent.js.map +1 -1
  48. package/dist/core/agents-stamp.js +47 -10
  49. package/dist/core/agents-stamp.js.map +1 -1
  50. package/dist/core/arch.js +28 -2
  51. package/dist/core/arch.js.map +1 -1
  52. package/dist/core/asyncapi.js +253 -0
  53. package/dist/core/asyncapi.js.map +1 -0
  54. package/dist/core/brief.js +28 -6
  55. package/dist/core/brief.js.map +1 -1
  56. package/dist/core/coherence.js +37 -13
  57. package/dist/core/coherence.js.map +1 -1
  58. package/dist/core/concurrency.js +51 -0
  59. package/dist/core/concurrency.js.map +1 -0
  60. package/dist/core/config.js +10 -2
  61. package/dist/core/config.js.map +1 -1
  62. package/dist/core/delta.js +21 -2
  63. package/dist/core/delta.js.map +1 -1
  64. package/dist/core/dependencies.js +46 -42
  65. package/dist/core/dependencies.js.map +1 -1
  66. package/dist/core/docs.js +65 -3
  67. package/dist/core/docs.js.map +1 -1
  68. package/dist/core/doctor.js +79 -27
  69. package/dist/core/doctor.js.map +1 -1
  70. package/dist/core/document-bytes.js +59 -0
  71. package/dist/core/document-bytes.js.map +1 -0
  72. package/dist/core/explore.js +225 -0
  73. package/dist/core/explore.js.map +1 -0
  74. package/dist/core/fleet-context.js +29 -63
  75. package/dist/core/fleet-context.js.map +1 -1
  76. package/dist/core/frontmatter.js +1 -5
  77. package/dist/core/frontmatter.js.map +1 -1
  78. package/dist/core/gherkin.js +3 -61
  79. package/dist/core/gherkin.js.map +1 -1
  80. package/dist/core/health.js +1 -5
  81. package/dist/core/health.js.map +1 -1
  82. package/dist/core/ids.js +34 -5
  83. package/dist/core/ids.js.map +1 -1
  84. package/dist/core/json.js +8 -1
  85. package/dist/core/json.js.map +1 -1
  86. package/dist/core/likec4.js +19 -4
  87. package/dist/core/likec4.js.map +1 -1
  88. package/dist/core/maturity.js +66 -0
  89. package/dist/core/maturity.js.map +1 -0
  90. package/dist/core/openapi-merge.js +39 -6
  91. package/dist/core/openapi-merge.js.map +1 -1
  92. package/dist/core/openapi.js +17 -5
  93. package/dist/core/openapi.js.map +1 -1
  94. package/dist/core/openspec-inventory.js +64 -27
  95. package/dist/core/openspec-inventory.js.map +1 -1
  96. package/dist/core/path-safety.js +59 -0
  97. package/dist/core/path-safety.js.map +1 -1
  98. package/dist/core/provenance.js +102 -10
  99. package/dist/core/provenance.js.map +1 -1
  100. package/dist/core/records.js +33 -0
  101. package/dist/core/records.js.map +1 -0
  102. package/dist/core/repo.js +77 -1
  103. package/dist/core/repo.js.map +1 -1
  104. package/dist/core/report.js +9 -0
  105. package/dist/core/report.js.map +1 -1
  106. package/dist/core/results.js +1 -3
  107. package/dist/core/results.js.map +1 -1
  108. package/dist/core/spec.js +28 -4
  109. package/dist/core/spec.js.map +1 -1
  110. package/dist/core/staging.js +124 -17
  111. package/dist/core/staging.js.map +1 -1
  112. package/dist/core/status.js +152 -35
  113. package/dist/core/status.js.map +1 -1
  114. package/dist/core/steps.js +72 -0
  115. package/dist/core/steps.js.map +1 -0
  116. package/dist/core/verify.js +18 -4
  117. package/dist/core/verify.js.map +1 -1
  118. package/dist/core/version.js +17 -1
  119. package/dist/core/version.js.map +1 -1
  120. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"spec.js","sourceRoot":"","sources":["../../src/core/spec.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAsE/C,MAAM,CAAC,MAAM,OAAO,GAAG,oDAAoD,CAAC;AAC5E,MAAM,MAAM,GAAG,iCAAiC,CAAC;AACjD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AM,MAAM,GAAgB;gBAC1B,GAAG,QAAQ,CAAC,CAAC,CAAC;gBACd,GAAG,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,CAAC;aAC1D,CAAC;YACF,IAAI,CAAC,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;;gBAC1B,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Parser for OpenSpec-style requirement documents.\n *\n * Living specs use `## Requirements` with `### Requirement:` + `#### Scenario:`.\n * Feature deltas group requirements under `## ADDED|MODIFIED|REMOVED Requirements`.\n * Scenarios are the acceptance criteria (Given/When/Then) and the source for tests.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { decodeDocument } from \"./fleet-context.js\";\nimport { scenarioGherkin } from \"./gherkin.js\";\nimport type { Finding } from \"./report.js\";\n\nexport type DeltaKind = \"ADDED\" | \"MODIFIED\" | \"REMOVED\" | \"BASE\";\n\nexport interface Scenario {\n name: string;\n lines: string[];\n}\n\nexport interface Requirement {\n /** BASE for a living spec; ADDED/MODIFIED/REMOVED inside a feature delta. */\n kind: DeltaKind;\n /**\n * Stable identity from a `Requirement-ID:` body line. Optional so existing\n * OpenSpec-compatible documents continue to use their heading as identity.\n */\n id?: string;\n /**\n * The living requirement this delta was WRITTEN AGAINST, from a `Based-On:`\n * body line — `requirementDigest` of that requirement at authoring time.\n *\n * Delta-only, and meaningful on MODIFIED/REMOVED alone: those two address a\n * requirement that already exists, and a MODIFIED carries its full new text,\n * so archive does not merge the living wording — it REPLACES it. Two features\n * rewriting one requirement therefore lose the loser's text outright, and the\n * in-flight warning (`delta.modified-conflict`) cannot see the case that\n * actually happens: once the first archives it leaves `changes/`, the second\n * goes green again, and its stale text lands on top without a word. This is\n * the pin that closes that window — the same trick as `sources_digest`\n * (core/provenance.ts), one requirement wide.\n *\n * Absent on requirements adopted from OpenSpec, which never had the line;\n * those keep the older, weaker protection and are told so once (warn).\n */\n basedOn?: string;\n name: string;\n text: string[];\n /** OpenAPI operationIds this requirement governs, from an `Operations:` line. */\n operations: string[];\n /**\n * What this requirement's scenarios exercise, from a `Covers:` line — the\n * architecture analog of `Operations:`. Entries are C4 element ids, edges\n * (`source -> target`), or health signals (`alert:<id>` / `sli:<id>`);\n * core/arch.ts owns the grammar and the resolution. Parsed everywhere for one\n * grammar's sake, meaningful in arch.spec.md.\n */\n covers: string[];\n scenarios: Scenario[];\n /**\n * The H2 heading of its SOURCE DOCUMENT this requirement was parsed under,\n * verbatim (`## Behavior`), or absent if it preceded every heading. Records where\n * the text came from, so it stays true after a merge re-homes the requirement.\n *\n * `kind` alone cannot explain why a requirement is BASE, and the two BASE cases\n * differ completely: under `## Requirements` a delta is legally quoting the\n * living state, while under `## Behavior` the author wrote a change that archive\n * will silently not merge. `delta.requirement-not-merged` tells them apart.\n */\n section?: string;\n /**\n * 1-based line of this requirement's `### Requirement:` heading in its source\n * document. Body line `text[i]` is therefore at line `line + 1 + i` — the\n * capture is contiguous from the heading to the first scenario — which is what\n * lets `loam rebase` rewrite one `Based-On:` line by surgery instead of\n * reserializing the document and flattening the author's sections and prose.\n */\n line?: number;\n}\n\nexport const KIND_RE = /^##\\s+(ADDED|MODIFIED|REMOVED)\\s+Requirements\\s*$/i;\nconst REQ_RE = /^###\\s+Requirement:\\s*(.+?)\\s*$/;\nconst SCN_RE = /^####\\s+Scenario:\\s*(.+?)\\s*$/;\nconst REQUIREMENT_ID_LINE_RE = /^\\s*Requirement-ID:\\s*(.*?)\\s*$/i;\nconst BASED_ON_LINE_RE = /^\\s*Based-On:\\s*(.*?)\\s*$/i;\n\n/** Portable, review-friendly stable IDs. Case-sensitive by design. */\nexport const REQUIREMENT_ID_RE = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/;\n\n/**\n * How much of the sha256 a `Based-On:` line carries — the length\n * `sources_digest` already uses (core/provenance.ts), for one reason a reader\n * can hold: every digest loam writes into a document reads the same.\n */\nexport const REQUIREMENT_DIGEST_LENGTH = 16;\n\n/** The value shape of a `Based-On:` line, exactly as `requirementDigest` writes it. */\nexport const REQUIREMENT_DIGEST_RE = new RegExp(`^[0-9a-f]{${REQUIREMENT_DIGEST_LENGTH}}$`);\n\nexport type RequirementIdProblem =\n | { kind: \"invalid\"; requirement: string; value: string }\n | { kind: \"repeated\"; requirement: string; values: string[] }\n | { kind: \"duplicate\"; id: string; requirements: string[] };\n\n/** Every authored Requirement-ID value in a requirement body, including blanks. */\nexport function requirementIdDeclarations(requirement: Requirement): string[] {\n return requirement.text.flatMap((line) => {\n const match = REQUIREMENT_ID_LINE_RE.exec(line);\n return match === null ? [] : [match[1]!.trim()];\n });\n}\n\n/** Structural ID problems within one spec/delta document. */\nexport function requirementIdProblems(reqs: Requirement[]): RequirementIdProblem[] {\n const problems: RequirementIdProblem[] = [];\n const owners = new Map<string, string[]>();\n for (const requirement of reqs) {\n const declarations = requirementIdDeclarations(requirement);\n const values = declarations.length > 0\n ? declarations\n : requirement.id === undefined\n ? []\n : [requirement.id];\n if (declarations.length > 1) {\n problems.push({ kind: \"repeated\", requirement: requirement.name, values: declarations });\n }\n for (const value of values) {\n if (!REQUIREMENT_ID_RE.test(value)) {\n problems.push({ kind: \"invalid\", requirement: requirement.name, value });\n }\n }\n // A repeated declaration is already an error. Do not also pretend its\n // keep-last parse result is an unambiguous document identity.\n if (values.length !== 1 || !REQUIREMENT_ID_RE.test(values[0]!)) continue;\n const names = owners.get(values[0]!) ?? [];\n names.push(requirement.name);\n owners.set(values[0]!, names);\n }\n for (const [id, requirements] of owners) {\n if (requirements.length > 1) problems.push({ kind: \"duplicate\", id, requirements });\n }\n return problems;\n}\n\n/** Every authored `Based-On:` value in a requirement body, including blanks. */\nexport function basedOnDeclarations(requirement: Requirement): string[] {\n return requirement.text.flatMap((line) => {\n const match = BASED_ON_LINE_RE.exec(line);\n return match === null ? [] : [match[1]!.trim()];\n });\n}\n\n/**\n * The requirement without its baseline marker — what a digest is taken over,\n * and what archive merges into the living document.\n *\n * `Based-On:` is a statement ABOUT a delta (\"this was written against that\"),\n * never part of the requirement it describes, and both consequences of\n * forgetting that are bad. Left in the digest input, a requirement's digest\n * would depend on the pin pointing at it, so no baseline could ever be\n * self-consistent. Left in the merged text — `applyRequirementDelta` copies the\n * delta's body into living wholesale — the living document would grow a pin to\n * a version of itself, and the NEXT feature's baseline would be taken over a\n * document containing the previous feature's bookkeeping.\n */\nfunction withoutBaseline(requirement: Requirement): Requirement {\n const { basedOn: _dropped, ...rest } = requirement;\n return { ...rest, text: requirement.text.filter((line) => !BASED_ON_LINE_RE.test(line)) };\n}\n\n/**\n * The identity of a requirement's CONTENT: sha256 over its canonical\n * serialization, truncated like every other digest loam stamps.\n *\n * Canonical, not raw bytes, and deliberately: a living spec is rewritten by\n * `serializeRequirements` on every archive, so hashing the file's bytes would\n * make a baseline go stale over reflowed blank lines — a false alarm on the one\n * check whose whole value is that it only fires when something real moved.\n * What the hash therefore covers is exactly what survives a round trip: the\n * heading, the body (`Requirement-ID:` and `Operations:`/`Covers:` lines\n * included), and every scenario with its Given/When/Then lines. `kind` and\n * `section` are not serialized and so are not hashed — a requirement does not\n * change because the document quoting it moved it under another heading.\n */\nexport function requirementDigest(requirement: Requirement): string {\n return createHash(\"sha256\")\n .update(serializeRequirements([withoutBaseline(requirement)]), \"utf8\")\n .digest(\"hex\")\n .slice(0, REQUIREMENT_DIGEST_LENGTH);\n}\n\n/**\n * THE requirements section: the one H2 a living spec keeps its requirements\n * under, the one section `loam archive` rewrites, and the one heading a delta\n * may legally quote the living state beneath. One definition on purpose — the\n * archive cut point, archive's stray-requirement guard, and the delta-shape\n * exemption (core/delta.ts) used to spell this invariant three different ways,\n * and the cut point's substring `indexOf(\"\\n## Requirements\")` was a PREFIX\n * match that also hit `## Requirements Extra`. Full-line match on a trimmed\n * heading, with KIND_RE's case and interior-whitespace tolerance.\n */\nexport const REQUIREMENTS_SECTION_RE = /^##\\s+Requirements\\s*$/i;\n\n/** Is this H2 heading line (as sectionHeadings/`Requirement.section` spell it) the `## Requirements` heading? */\nexport function isRequirementsHeading(heading: string): boolean {\n return REQUIREMENTS_SECTION_RE.test(heading.trim());\n}\n\n/**\n * Track ``` / ~~~ fences line by line. Returns true while the line is fenced\n * content — including the fence marker itself — so heading-like lines inside a\n * code block are never mistaken for structure.\n */\nfunction fenceTracker(): (line: string) => boolean {\n let fence: string | null = null;\n return (line) => {\n const m = /^\\s*(```|~~~)/.exec(line);\n if (m) {\n if (fence === null) fence = m[1]!;\n else if (fence === m[1]!) fence = null;\n return true;\n }\n return fence !== null;\n };\n}\n\n/**\n * Strip a leading UTF-8 BOM (U+FEFF), which editors on Windows write unasked.\n *\n * It has to happen here, at the two functions that take raw markdown, rather than\n * at each `readFile` call: those are spread across half the commands, so any one of\n * them could forget, and the failure is invisible. One byte was enough to void an\n * entire delta — `KIND_RE` is anchored `^##`, delta files routinely open with\n * `## MODIFIED Requirements` on line 1, and behind a BOM that line stopped being a\n * heading, so every requirement in the file fell back to BASE and\n * `applyRequirementDelta` skips BASE. Archive merged nothing and said nothing.\n * OpenSpec's own reader strips it for exactly this reason.\n *\n * Only at position 0: elsewhere U+FEFF is a zero-width no-break space and belongs\n * to the author's text.\n */\nfunction stripBom(md: string): string {\n return md.charCodeAt(0) === 0xfeff ? md.slice(1) : md;\n}\n\n/** Every H2 heading outside a fenced block, with its 1-based line number. */\nexport function sectionHeadings(md: string): Array<{ text: string; line: number }> {\n const fenced = fenceTracker();\n const out: Array<{ text: string; line: number }> = [];\n stripBom(md).split(/\\r?\\n/).forEach((line, i) => {\n if (fenced(line)) return;\n if (/^##\\s+/.test(line) && !line.startsWith(\"###\")) out.push({ text: line.trim(), line: i + 1 });\n });\n return out;\n}\n\n/**\n * Split a living spec around its requirements RUN — the stretch of\n * `### Requirement:` blocks inside the `## Requirements` section — so a merge\n * can rewrite exactly that and nothing else. All three slices reassemble the\n * input byte-for-byte (`head + run + tail === text`):\n *\n * - `head` — everything before the first requirement in the section: the\n * intro, the heading line itself, any prose under the heading.\n * - `run` — from the first `### Requirement:` line to the section's end (the\n * next `## ` heading, or EOF). Empty when the section holds no requirements.\n * - `tail` — everything from the section's end onward.\n *\n * Returns null when the document has no `## Requirements` heading at all.\n * Only the FIRST matching heading opens the section; a caller that must not\n * lose content behind a duplicate (archive) counts matches via\n * sectionHeadings() and refuses. Heading detection matches parseRequirements:\n * fenced lines are never structure, and a leading BOM hides no heading — but\n * the slices themselves are raw bytes, BOM and CRLF included.\n */\nexport function splitRequirementsSection(\n text: string,\n): { head: string; run: string; tail: string } | null {\n const fenced = fenceTracker();\n let inSection = false;\n let sectionStart = -1;\n let runStart = -1;\n let sectionEnd = text.length;\n let offset = 0;\n while (offset < text.length) {\n const nl = text.indexOf(\"\\n\", offset);\n const lineEnd = nl === -1 ? text.length : nl + 1;\n let line = text.slice(offset, nl === -1 ? text.length : nl);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n // Position 0 only, mirroring stripBom: elsewhere U+FEFF is content.\n if (offset === 0 && line.charCodeAt(0) === 0xfeff) line = line.slice(1);\n if (!fenced(line)) {\n if (/^##\\s+/.test(line) && !line.startsWith(\"###\")) {\n if (inSection) {\n sectionEnd = offset;\n inSection = false;\n } else if (sectionStart === -1 && isRequirementsHeading(line)) {\n sectionStart = offset;\n inSection = true;\n }\n } else if (inSection && runStart === -1 && REQ_RE.test(line)) {\n runStart = offset;\n }\n }\n offset = lineEnd;\n }\n if (sectionStart === -1) return null;\n const cut = runStart === -1 ? sectionEnd : runStart;\n return { head: text.slice(0, cut), run: text.slice(cut, sectionEnd), tail: text.slice(sectionEnd) };\n}\n\n/**\n * A requirement document from disk as text — decoded, or refused by name.\n *\n * The read that belongs with the parser, because `readFile(path, \"utf8\")` and\n * `parseRequirements` together are a trap: a UTF-16 spec.md decodes to a string\n * in which no line matches `^###\\s+Requirement:`, so the parser returns [] and\n * the document grades as an empty baseline instead of an unreadable one. Every\n * question loam asks of a spec — is it covered, does the delta merge, what does\n * the C4 spine touch — is then answered about a file nobody read.\n *\n * It THROWS (`NotUtf8DocumentError`, which names the path), unlike\n * `readFrontmatter` next door, because the two failures are not the same\n * failure. Frontmatter is read by the fleet enumeration, where one bad file\n * must not cost the other 119 services, so there it is a flag. A requirement\n * document is read by ONE target, and the caller is the only one who knows what\n * to do about it: a read-only command turns it into a finding on that target\n * (validate's `guarded`, which names the file and keeps grading the rest), a\n * command that writes refuses outright rather than computing over mojibake.\n */\nexport async function readRequirementsDocument(path: string): Promise<string> {\n return decodeDocument(await readFile(path), path);\n}\n\n/** Parse all requirements (with their scenarios and delta kind) from a markdown doc. */\nexport function parseRequirements(md: string): Requirement[] {\n const out: Requirement[] = [];\n let kind: DeltaKind = \"BASE\";\n let section: string | undefined;\n let req: Requirement | null = null;\n let scn: Scenario | null = null;\n const fenced = fenceTracker();\n\n for (const [index, line] of stripBom(md).split(/\\r?\\n/).entries()) {\n if (fenced(line)) {\n // Fenced content, marker included: body of whatever is open, never structure.\n if (scn) scn.lines.push(line);\n else if (req) req.text.push(line);\n continue;\n }\n // Any H2 heading ends the current requirement/scenario capture — section prose\n // must not leak into the previous scenario's body.\n if (/^##\\s+/.test(line) && !line.startsWith(\"###\")) {\n req = null;\n scn = null;\n section = line.trim();\n const mk = KIND_RE.exec(line);\n // A non-delta H2 (## Notes, ## Requirements…) starts an unrelated section:\n // requirements under it are plain BASE, not part of a stale delta section.\n kind = mk ? (mk[1]!.toUpperCase() as DeltaKind) : \"BASE\";\n continue;\n }\n const mr = REQ_RE.exec(line);\n if (mr) {\n req = { kind, name: mr[1]!, text: [], operations: [], covers: [], scenarios: [], section, line: index + 1 };\n out.push(req);\n scn = null;\n continue;\n }\n const ms = SCN_RE.exec(line);\n if (ms && req) {\n scn = { name: ms[1]!, lines: [] };\n req.scenarios.push(scn);\n continue;\n }\n if (scn) {\n scn.lines.push(line);\n } else if (req) {\n req.text.push(line);\n const mi = REQUIREMENT_ID_LINE_RE.exec(line);\n if (mi) req.id = mi[1]!.trim();\n // Same keep-last quirk as Operations:/Covers: below — a repeated line is\n // a document problem, reported as one (`delta.baseline-invalid`), never\n // resolved differently by whoever happens to be reading.\n const mb = BASED_ON_LINE_RE.exec(line);\n if (mb) req.basedOn = mb[1]!.trim();\n const mo = /^\\s*Operations?:\\s*(.+?)\\s*$/i.exec(line);\n if (mo) req.operations = mo[1]!.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n // The Covers: mirror — same placement (requirement body, not a scenario),\n // same comma grammar, and deliberately the same quirk: a second line\n // REPLACES the first (assignment, not append), so the two lists can never\n // drift apart in how they read a repeated line.\n const mc = /^\\s*Covers?:\\s*(.+?)\\s*$/i.exec(line);\n if (mc) req.covers = mc[1]!.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n }\n }\n\n return out;\n}\n\n/** Requirements with no scenario — the OpenSpec coverage rule (every requirement needs ≥1). */\nexport function requirementsMissingScenarios(reqs: Requirement[]): Requirement[] {\n return reqs.filter((r) => r.kind !== \"REMOVED\" && r.scenarios.length === 0);\n}\n\n/** A `#### Scenario:` heading whose body holds nothing a runner would execute. */\nexport interface SteplessScenario {\n requirement: string;\n scenario: string;\n}\n\n/**\n * Scenarios that satisfy the coverage rule above and test nothing.\n *\n * `requirementsMissingScenarios` counts HEADINGS, so a `#### Scenario:` with no\n * recognizable Given/When/Then line satisfied the fleet gate's coverage claim\n * outright — and it is not a hypothetical shape: it is what `loam new`\n * scaffolds and what an agent writes when it puts the criteria in prose.\n * Downstream the same emptiness is fatal twice over: cucumber runs a stepless\n * scenario vacuously green, and `loam verify --results` can never confirm it.\n *\n * The detector is `loam gherkin`'s own — `scenarioGherkin` decides what a step\n * IS, and a second opinion here would mean the gate and the emitted suite could\n * disagree about whether a scenario has any. That import is the one place these\n * two modules are circular (gherkin.ts parses requirements); both sides export\n * only function declarations, which are hoisted, so neither evaluation order\n * can observe a half-built module.\n */\nexport function steplessScenarios(reqs: Requirement[]): SteplessScenario[] {\n const out: SteplessScenario[] = [];\n for (const r of reqs) {\n if (r.kind === \"REMOVED\") continue;\n for (const s of r.scenarios) {\n if (scenarioGherkin(s.lines).steps.length === 0) out.push({ requirement: r.name, scenario: s.name });\n }\n }\n return out;\n}\n\n/**\n * The stepless half of the coverage check, as findings — the missing-scenario\n * half stays where it is (`requirementsMissingScenarios`), because the two are\n * different states with different fixes: one requirement owes acceptance\n * criteria, the other owes STEPS in criteria somebody has already written.\n *\n * `label` is the coverage check's own label (`payment-service: requirements`),\n * so both halves of one document name it the same way.\n */\nexport function steplessFindings(label: string, subject: string, reqs: Requirement[]): Finding[] {\n const bare = steplessScenarios(reqs);\n if (bare.length === 0) return [];\n return [\n {\n severity: \"error\",\n code: \"requirements.stepless-scenario\",\n subject,\n message:\n `${label}: ${bare.length} scenario(s) have a heading and no recognizable steps — ` +\n `they satisfy the coverage rule and test nothing. Cucumber runs a stepless scenario vacuously green and ` +\n `\\`loam verify --results\\` can never confirm it. Write the body as \\`- **Given/When/Then**\\` bullets.`,\n details: bare.map((s) => `${s.requirement} — ${s.scenario}`),\n text: { detailPrefix: \"- \" },\n },\n ];\n}\n\n/** Serialize requirements back to OpenSpec markdown (`### Requirement:` + `#### Scenario:`). */\nexport function serializeRequirements(reqs: Requirement[]): string {\n // Framing (blank lines between sections) is normalized here; body content is\n // only edge-trimmed, never collapsed — blank lines inside a scenario (e.g. in\n // fenced code blocks) are verbatim content.\n const chunks: string[] = [];\n for (const r of reqs) {\n const chunk: string[] = [`### Requirement: ${r.name}`];\n const body = [...r.text];\n // Parsed documents already carry the authored line in `text`. This branch\n // also makes programmatically constructed Requirements serialize fully.\n if (r.id !== undefined && !body.some((line) => REQUIREMENT_ID_LINE_RE.test(line))) {\n body.unshift(`Requirement-ID: ${r.id}`);\n }\n // Directly under the identity it pins, which is where `loam rebase` writes\n // it too — the two lines are read together, so they are never apart.\n if (r.basedOn !== undefined && !body.some((line) => BASED_ON_LINE_RE.test(line))) {\n body.splice(body.findIndex((line) => REQUIREMENT_ID_LINE_RE.test(line)) + 1, 0, `Based-On: ${r.basedOn}`);\n }\n const text = body.join(\"\\n\").trim();\n if (text) chunk.push(\"\", text);\n for (const s of r.scenarios) {\n chunk.push(\"\", `#### Scenario: ${s.name}`);\n const body = s.lines.join(\"\\n\").trim();\n if (body) chunk.push(body);\n }\n chunks.push(chunk.join(\"\\n\"));\n }\n return chunks.join(\"\\n\\n\").trim() + \"\\n\";\n}\n\n/**\n * A delta requirement as it lands in the living document, with the bookkeeping\n * that belongs to the DELTA left behind: the `Based-On:` pin (a claim about\n * which living version this was written against — meaningless once it IS the\n * living version, and poison for the next feature's baseline, which would then\n * hash the previous feature's pin) and the line it was parsed from.\n */\nfunction asLiving(d: Requirement): Requirement {\n const { line: _dropped, ...rest } = withoutBaseline(d);\n return { ...rest, kind: \"BASE\" };\n}\n\n/** Apply a feature's ADDED/MODIFIED/REMOVED requirements onto a living requirement set. */\nexport function applyRequirementDelta(living: Requirement[], delta: Requirement[]): Requirement[] {\n const malformed = [...requirementIdProblems(living), ...requirementIdProblems(delta)];\n if (malformed.length > 0) {\n throw new Error(\"cannot merge requirements with invalid, repeated, or duplicate Requirement-ID declarations\");\n }\n let result: Requirement[] = living.map((r) => ({ ...r, kind: \"BASE\" as DeltaKind }));\n for (const d of delta) {\n // BASE is not a delta kind — a requirement outside an ADDED/MODIFIED/REMOVED\n // section (e.g. quoted under ## Notes) is documentation, not a change.\n if (d.kind === \"BASE\") continue;\n if (d.id !== undefined) {\n const idMatches = result\n .map((r, i) => (r.id === d.id ? i : -1))\n .filter((i) => i >= 0);\n const nameMatches = result\n .map((r, i) => (r.name === d.name ? i : -1))\n .filter((i) => i >= 0);\n const otherNameMatches = nameMatches.filter((i) => !idMatches.includes(i));\n if (idMatches.length > 1 || otherNameMatches.length > 0) {\n throw new Error(\n `ambiguous requirement identity for '${d.name}' (${d.id}): Requirement-ID and heading select different living requirements`,\n );\n }\n if (d.kind === \"REMOVED\") {\n const selected = new Set(idMatches);\n result = result.filter((_, i) => !selected.has(i));\n } else {\n const merged: Requirement = asLiving(d);\n if (idMatches.length === 1) result[idMatches[0]!] = merged;\n else result.push(merged);\n }\n } else if (d.kind === \"REMOVED\") {\n result = result.filter((r) => r.name !== d.name);\n } else {\n const i = result.findIndex((r) => r.name === d.name);\n // A legacy delta may still modify an ID-bearing living requirement by\n // its exact heading. Keep the identity while the repository migrates.\n const inheritedId = i >= 0 ? result[i]!.id : undefined;\n const merged: Requirement = {\n ...asLiving(d),\n ...(inheritedId === undefined ? {} : { id: inheritedId }),\n };\n if (i >= 0) result[i] = merged;\n else result.push(merged);\n }\n }\n return result;\n}\n"]}
1
+ {"version":3,"file":"spec.js","sourceRoot":"","sources":["../../src/core/spec.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAoF7C,MAAM,CAAC,MAAM,OAAO,GAAG,oDAAoD,CAAC;AAC5E,MAAM,MAAM,GAAG,iCAAiC,CAAC;AACjD,MAAM,MAAM,GAAG,+BAA+B,CAAC;AAC/C,MAAM,sBAAsB,GAAG,kCAAkC,CAAC;AAClE,MAAM,gBAAgB,GAAG,4BAA4B,CAAC;AAEtD,sEAAsE;AACtE,MAAM,CAAC,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;AAEnE;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAE5C,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,MAAM,CAAC,aAAa,yBAAyB,IAAI,CA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,IAAI,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC;YACrD,sEAAsE;YACtE,sEAAsE;YACtE,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;YACvD,MAAM,MAAM,GAAgB;gBAC1B,GAAG,QAAQ,CAAC,CAAC,CAAC;gBACd,GAAG,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,CAAC;aAC1D,CAAC;YACF,IAAI,CAAC,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;;gBAC1B,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Parser for OpenSpec-style requirement documents.\n *\n * Living specs use `## Requirements` with `### Requirement:` + `#### Scenario:`.\n * Feature deltas group requirements under `## ADDED|MODIFIED|REMOVED Requirements`.\n * Scenarios are the acceptance criteria (Given/When/Then) and the source for tests.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { decodeDocument } from \"./document-bytes.js\";\nimport { scenarioGherkin } from \"./steps.js\";\nimport type { Finding } from \"./report.js\";\n\nexport type DeltaKind = \"ADDED\" | \"MODIFIED\" | \"REMOVED\" | \"BASE\";\n\nexport interface Scenario {\n name: string;\n lines: string[];\n}\n\nexport interface Requirement {\n /** BASE for a living spec; ADDED/MODIFIED/REMOVED inside a feature delta. */\n kind: DeltaKind;\n /**\n * Stable identity from a `Requirement-ID:` body line. Optional so existing\n * OpenSpec-compatible documents continue to use their heading as identity.\n */\n id?: string;\n /**\n * The living requirement this delta was WRITTEN AGAINST, from a `Based-On:`\n * body line — `requirementDigest` of that requirement at authoring time.\n *\n * Delta-only, and meaningful on MODIFIED/REMOVED alone: those two address a\n * requirement that already exists, and a MODIFIED carries its full new text,\n * so archive does not merge the living wording — it REPLACES it. Two features\n * rewriting one requirement therefore lose the loser's text outright, and the\n * in-flight warning (`delta.modified-conflict`) cannot see the case that\n * actually happens: once the first archives it leaves `changes/`, the second\n * goes green again, and its stale text lands on top without a word. This is\n * the pin that closes that window — the same trick as `sources_digest`\n * (core/provenance.ts), one requirement wide.\n *\n * Absent on requirements adopted from OpenSpec, which never had the line;\n * those keep the older, weaker protection and are told so once (warn).\n */\n basedOn?: string;\n name: string;\n text: string[];\n /** OpenAPI operationIds this requirement governs, from an `Operations:` line. */\n operations: string[];\n /**\n * What this requirement's scenarios exercise, from a `Covers:` line — the\n * architecture analog of `Operations:`. Entries are C4 element ids, edges\n * (`source -> target`), or health signals (`alert:<id>` / `sli:<id>`);\n * core/arch.ts owns the grammar and the resolution. Parsed everywhere for one\n * grammar's sake, meaningful in arch.spec.md.\n */\n covers: string[];\n /**\n * AsyncAPI message names this requirement governs on the PRODUCING side, from\n * a `Publishes:` line — the event-axis analog of `Operations:`.\n *\n * Two lines rather than one, because the async spine is directional in a way\n * the HTTP one is not: `Publishes:` resolves against this service's OWN\n * contract, while `Consumes:` names a message another service declares, and\n * only a fleet-wide view can say whether anybody does. Grading them alike\n * would either excuse a typo in a producer or point a consumer's error at the\n * wrong repository.\n */\n publishes: string[];\n /** AsyncAPI message names this requirement consumes, from a `Consumes:` line. See `publishes`. */\n consumes: string[];\n scenarios: Scenario[];\n /**\n * The H2 heading of its SOURCE DOCUMENT this requirement was parsed under,\n * verbatim (`## Behavior`), or absent if it preceded every heading. Records where\n * the text came from, so it stays true after a merge re-homes the requirement.\n *\n * `kind` alone cannot explain why a requirement is BASE, and the two BASE cases\n * differ completely: under `## Requirements` a delta is legally quoting the\n * living state, while under `## Behavior` the author wrote a change that archive\n * will silently not merge. `delta.requirement-not-merged` tells them apart.\n */\n section?: string;\n /**\n * 1-based line of this requirement's `### Requirement:` heading in its source\n * document. Body line `text[i]` is therefore at line `line + 1 + i` — the\n * capture is contiguous from the heading to the first scenario — which is what\n * lets `loam rebase` rewrite one `Based-On:` line by surgery instead of\n * reserializing the document and flattening the author's sections and prose.\n */\n line?: number;\n}\n\nexport const KIND_RE = /^##\\s+(ADDED|MODIFIED|REMOVED)\\s+Requirements\\s*$/i;\nconst REQ_RE = /^###\\s+Requirement:\\s*(.+?)\\s*$/;\nconst SCN_RE = /^####\\s+Scenario:\\s*(.+?)\\s*$/;\nconst REQUIREMENT_ID_LINE_RE = /^\\s*Requirement-ID:\\s*(.*?)\\s*$/i;\nconst BASED_ON_LINE_RE = /^\\s*Based-On:\\s*(.*?)\\s*$/i;\n\n/** Portable, review-friendly stable IDs. Case-sensitive by design. */\nexport const REQUIREMENT_ID_RE = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/;\n\n/**\n * How much of the sha256 a `Based-On:` line carries — the length\n * `sources_digest` already uses (core/provenance.ts), for one reason a reader\n * can hold: every digest loam writes into a document reads the same.\n */\nexport const REQUIREMENT_DIGEST_LENGTH = 16;\n\n/** The value shape of a `Based-On:` line, exactly as `requirementDigest` writes it. */\nexport const REQUIREMENT_DIGEST_RE = new RegExp(`^[0-9a-f]{${REQUIREMENT_DIGEST_LENGTH}}$`);\n\nexport type RequirementIdProblem =\n | { kind: \"invalid\"; requirement: string; value: string }\n | { kind: \"repeated\"; requirement: string; values: string[] }\n | { kind: \"duplicate\"; id: string; requirements: string[] };\n\n/** Every authored Requirement-ID value in a requirement body, including blanks. */\nexport function requirementIdDeclarations(requirement: Requirement): string[] {\n return requirement.text.flatMap((line) => {\n const match = REQUIREMENT_ID_LINE_RE.exec(line);\n return match === null ? [] : [match[1]!.trim()];\n });\n}\n\n/** Structural ID problems within one spec/delta document. */\nexport function requirementIdProblems(reqs: Requirement[]): RequirementIdProblem[] {\n const problems: RequirementIdProblem[] = [];\n const owners = new Map<string, string[]>();\n for (const requirement of reqs) {\n const declarations = requirementIdDeclarations(requirement);\n const values = declarations.length > 0\n ? declarations\n : requirement.id === undefined\n ? []\n : [requirement.id];\n if (declarations.length > 1) {\n problems.push({ kind: \"repeated\", requirement: requirement.name, values: declarations });\n }\n for (const value of values) {\n if (!REQUIREMENT_ID_RE.test(value)) {\n problems.push({ kind: \"invalid\", requirement: requirement.name, value });\n }\n }\n // A repeated declaration is already an error. Do not also pretend its\n // keep-last parse result is an unambiguous document identity.\n if (values.length !== 1 || !REQUIREMENT_ID_RE.test(values[0]!)) continue;\n const names = owners.get(values[0]!) ?? [];\n names.push(requirement.name);\n owners.set(values[0]!, names);\n }\n for (const [id, requirements] of owners) {\n if (requirements.length > 1) problems.push({ kind: \"duplicate\", id, requirements });\n }\n return problems;\n}\n\n/** Every authored `Based-On:` value in a requirement body, including blanks. */\nexport function basedOnDeclarations(requirement: Requirement): string[] {\n return requirement.text.flatMap((line) => {\n const match = BASED_ON_LINE_RE.exec(line);\n return match === null ? [] : [match[1]!.trim()];\n });\n}\n\n/**\n * The requirement without its baseline marker — what a digest is taken over,\n * and what archive merges into the living document.\n *\n * `Based-On:` is a statement ABOUT a delta (\"this was written against that\"),\n * never part of the requirement it describes, and both consequences of\n * forgetting that are bad. Left in the digest input, a requirement's digest\n * would depend on the pin pointing at it, so no baseline could ever be\n * self-consistent. Left in the merged text — `applyRequirementDelta` copies the\n * delta's body into living wholesale — the living document would grow a pin to\n * a version of itself, and the NEXT feature's baseline would be taken over a\n * document containing the previous feature's bookkeeping.\n */\nfunction withoutBaseline(requirement: Requirement): Requirement {\n const { basedOn: _dropped, ...rest } = requirement;\n return { ...rest, text: requirement.text.filter((line) => !BASED_ON_LINE_RE.test(line)) };\n}\n\n/**\n * The identity of a requirement's CONTENT: sha256 over its canonical\n * serialization, truncated like every other digest loam stamps.\n *\n * Canonical, not raw bytes, and deliberately: a living spec is rewritten by\n * `serializeRequirements` on every archive, so hashing the file's bytes would\n * make a baseline go stale over reflowed blank lines — a false alarm on the one\n * check whose whole value is that it only fires when something real moved.\n * What the hash therefore covers is exactly what survives a round trip: the\n * heading, the body (`Requirement-ID:` and `Operations:`/`Covers:` lines\n * included), and every scenario with its Given/When/Then lines. `kind` and\n * `section` are not serialized and so are not hashed — a requirement does not\n * change because the document quoting it moved it under another heading.\n */\nexport function requirementDigest(requirement: Requirement): string {\n return createHash(\"sha256\")\n .update(serializeRequirements([withoutBaseline(requirement)]), \"utf8\")\n .digest(\"hex\")\n .slice(0, REQUIREMENT_DIGEST_LENGTH);\n}\n\n/**\n * THE requirements section: the one H2 a living spec keeps its requirements\n * under, the one section `loam archive` rewrites, and the one heading a delta\n * may legally quote the living state beneath. One definition on purpose — the\n * archive cut point, archive's stray-requirement guard, and the delta-shape\n * exemption (core/delta.ts) used to spell this invariant three different ways,\n * and the cut point's substring `indexOf(\"\\n## Requirements\")` was a PREFIX\n * match that also hit `## Requirements Extra`. Full-line match on a trimmed\n * heading, with KIND_RE's case and interior-whitespace tolerance.\n */\nconst REQUIREMENTS_SECTION_RE = /^##\\s+Requirements\\s*$/i;\n\n/** Is this H2 heading line (as sectionHeadings/`Requirement.section` spell it) the `## Requirements` heading? */\nexport function isRequirementsHeading(heading: string): boolean {\n return REQUIREMENTS_SECTION_RE.test(heading.trim());\n}\n\n/**\n * Track ``` / ~~~ fences line by line. Returns true while the line is fenced\n * content — including the fence marker itself — so heading-like lines inside a\n * code block are never mistaken for structure.\n */\nfunction fenceTracker(): (line: string) => boolean {\n let fence: string | null = null;\n return (line) => {\n const m = /^\\s*(```|~~~)/.exec(line);\n if (m) {\n if (fence === null) fence = m[1]!;\n else if (fence === m[1]!) fence = null;\n return true;\n }\n return fence !== null;\n };\n}\n\n/**\n * Strip a leading UTF-8 BOM (U+FEFF), which editors on Windows write unasked.\n *\n * It has to happen here, at the two functions that take raw markdown, rather than\n * at each `readFile` call: those are spread across half the commands, so any one of\n * them could forget, and the failure is invisible. One byte was enough to void an\n * entire delta — `KIND_RE` is anchored `^##`, delta files routinely open with\n * `## MODIFIED Requirements` on line 1, and behind a BOM that line stopped being a\n * heading, so every requirement in the file fell back to BASE and\n * `applyRequirementDelta` skips BASE. Archive merged nothing and said nothing.\n * OpenSpec's own reader strips it for exactly this reason.\n *\n * Only at position 0: elsewhere U+FEFF is a zero-width no-break space and belongs\n * to the author's text.\n */\nfunction stripBom(md: string): string {\n return md.charCodeAt(0) === 0xfeff ? md.slice(1) : md;\n}\n\n/** Every H2 heading outside a fenced block, with its 1-based line number. */\nexport function sectionHeadings(md: string): Array<{ text: string; line: number }> {\n const fenced = fenceTracker();\n const out: Array<{ text: string; line: number }> = [];\n stripBom(md).split(/\\r?\\n/).forEach((line, i) => {\n if (fenced(line)) return;\n if (/^##\\s+/.test(line) && !line.startsWith(\"###\")) out.push({ text: line.trim(), line: i + 1 });\n });\n return out;\n}\n\n/**\n * Split a living spec around its requirements RUN — the stretch of\n * `### Requirement:` blocks inside the `## Requirements` section — so a merge\n * can rewrite exactly that and nothing else. All three slices reassemble the\n * input byte-for-byte (`head + run + tail === text`):\n *\n * - `head` — everything before the first requirement in the section: the\n * intro, the heading line itself, any prose under the heading.\n * - `run` — from the first `### Requirement:` line to the section's end (the\n * next `## ` heading, or EOF). Empty when the section holds no requirements.\n * - `tail` — everything from the section's end onward.\n *\n * Returns null when the document has no `## Requirements` heading at all.\n * Only the FIRST matching heading opens the section; a caller that must not\n * lose content behind a duplicate (archive) counts matches via\n * sectionHeadings() and refuses. Heading detection matches parseRequirements:\n * fenced lines are never structure, and a leading BOM hides no heading — but\n * the slices themselves are raw bytes, BOM and CRLF included.\n */\nexport function splitRequirementsSection(\n text: string,\n): { head: string; run: string; tail: string } | null {\n const fenced = fenceTracker();\n let inSection = false;\n let sectionStart = -1;\n let runStart = -1;\n let sectionEnd = text.length;\n let offset = 0;\n while (offset < text.length) {\n const nl = text.indexOf(\"\\n\", offset);\n const lineEnd = nl === -1 ? text.length : nl + 1;\n let line = text.slice(offset, nl === -1 ? text.length : nl);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n // Position 0 only, mirroring stripBom: elsewhere U+FEFF is content.\n if (offset === 0 && line.charCodeAt(0) === 0xfeff) line = line.slice(1);\n if (!fenced(line)) {\n if (/^##\\s+/.test(line) && !line.startsWith(\"###\")) {\n if (inSection) {\n sectionEnd = offset;\n inSection = false;\n } else if (sectionStart === -1 && isRequirementsHeading(line)) {\n sectionStart = offset;\n inSection = true;\n }\n } else if (inSection && runStart === -1 && REQ_RE.test(line)) {\n runStart = offset;\n }\n }\n offset = lineEnd;\n }\n if (sectionStart === -1) return null;\n const cut = runStart === -1 ? sectionEnd : runStart;\n return { head: text.slice(0, cut), run: text.slice(cut, sectionEnd), tail: text.slice(sectionEnd) };\n}\n\n/**\n * A requirement document from disk as text — decoded, or refused by name.\n *\n * The read that belongs with the parser, because `readFile(path, \"utf8\")` and\n * `parseRequirements` together are a trap: a UTF-16 spec.md decodes to a string\n * in which no line matches `^###\\s+Requirement:`, so the parser returns [] and\n * the document grades as an empty baseline instead of an unreadable one. Every\n * question loam asks of a spec — is it covered, does the delta merge, what does\n * the C4 spine touch — is then answered about a file nobody read.\n *\n * It THROWS (`NotUtf8DocumentError`, which names the path), unlike\n * `readFrontmatter` next door, because the two failures are not the same\n * failure. Frontmatter is read by the fleet enumeration, where one bad file\n * must not cost the other 119 services, so there it is a flag. A requirement\n * document is read by ONE target, and the caller is the only one who knows what\n * to do about it: a read-only command turns it into a finding on that target\n * (validate's `guarded`, which names the file and keeps grading the rest), a\n * command that writes refuses outright rather than computing over mojibake.\n */\nexport async function readRequirementsDocument(path: string): Promise<string> {\n return decodeDocument(await readFile(path), path);\n}\n\n/** Parse all requirements (with their scenarios and delta kind) from a markdown doc. */\nexport function parseRequirements(md: string): Requirement[] {\n const out: Requirement[] = [];\n let kind: DeltaKind = \"BASE\";\n let section: string | undefined;\n let req: Requirement | null = null;\n let scn: Scenario | null = null;\n const fenced = fenceTracker();\n\n for (const [index, line] of stripBom(md).split(/\\r?\\n/).entries()) {\n if (fenced(line)) {\n // Fenced content, marker included: body of whatever is open, never structure.\n if (scn) scn.lines.push(line);\n else if (req) req.text.push(line);\n continue;\n }\n // Any H2 heading ends the current requirement/scenario capture — section prose\n // must not leak into the previous scenario's body.\n if (/^##\\s+/.test(line) && !line.startsWith(\"###\")) {\n req = null;\n scn = null;\n section = line.trim();\n const mk = KIND_RE.exec(line);\n // A non-delta H2 (## Notes, ## Requirements…) starts an unrelated section:\n // requirements under it are plain BASE, not part of a stale delta section.\n kind = mk ? (mk[1]!.toUpperCase() as DeltaKind) : \"BASE\";\n continue;\n }\n const mr = REQ_RE.exec(line);\n if (mr) {\n req = {\n kind,\n name: mr[1]!,\n text: [],\n operations: [],\n covers: [],\n publishes: [],\n consumes: [],\n scenarios: [],\n section,\n line: index + 1,\n };\n out.push(req);\n scn = null;\n continue;\n }\n const ms = SCN_RE.exec(line);\n if (ms && req) {\n scn = { name: ms[1]!, lines: [] };\n req.scenarios.push(scn);\n continue;\n }\n if (scn) {\n scn.lines.push(line);\n } else if (req) {\n req.text.push(line);\n const mi = REQUIREMENT_ID_LINE_RE.exec(line);\n if (mi) req.id = mi[1]!.trim();\n // Same keep-last quirk as Operations:/Covers: below — a repeated line is\n // a document problem, reported as one (`delta.baseline-invalid`), never\n // resolved differently by whoever happens to be reading.\n const mb = BASED_ON_LINE_RE.exec(line);\n if (mb) req.basedOn = mb[1]!.trim();\n const mo = /^\\s*Operations?:\\s*(.+?)\\s*$/i.exec(line);\n if (mo) req.operations = mo[1]!.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n // The Covers: mirror — same placement (requirement body, not a scenario),\n // same comma grammar, and deliberately the same quirk: a second line\n // REPLACES the first (assignment, not append), so the two lists can never\n // drift apart in how they read a repeated line.\n const mc = /^\\s*Covers?:\\s*(.+?)\\s*$/i.exec(line);\n if (mc) req.covers = mc[1]!.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n // The event axis, same grammar and the same keep-last quirk again. Note\n // what is NOT happening here: the line stays in `req.text` like every\n // other body line (the push above is unconditional), so it round-trips\n // through `serializeRequirements` and rides inside `requirementDigest`\n // exactly as `Operations:` does. That is what makes this parse purely\n // additive — no living document's digest moves, and no `Based-On:` pin\n // goes stale because loam learned to read one more line.\n const mp = /^\\s*Publishes?:\\s*(.+?)\\s*$/i.exec(line);\n if (mp) req.publishes = mp[1]!.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n const mcon = /^\\s*Consumes?:\\s*(.+?)\\s*$/i.exec(line);\n if (mcon) req.consumes = mcon[1]!.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0);\n }\n }\n\n return out;\n}\n\n/** Requirements with no scenario — the OpenSpec coverage rule (every requirement needs ≥1). */\nexport function requirementsMissingScenarios(reqs: Requirement[]): Requirement[] {\n return reqs.filter((r) => r.kind !== \"REMOVED\" && r.scenarios.length === 0);\n}\n\n/** A `#### Scenario:` heading whose body holds nothing a runner would execute. */\nexport interface SteplessScenario {\n requirement: string;\n scenario: string;\n}\n\n/**\n * Scenarios that satisfy the coverage rule above and test nothing.\n *\n * `requirementsMissingScenarios` counts HEADINGS, so a `#### Scenario:` with no\n * recognizable Given/When/Then line satisfied the fleet gate's coverage claim\n * outright — and it is not a hypothetical shape: it is what `loam new`\n * scaffolds and what an agent writes when it puts the criteria in prose.\n * Downstream the same emptiness is fatal twice over: cucumber runs a stepless\n * scenario vacuously green, and `loam verify --results` can never confirm it.\n *\n * The detector is `loam gherkin`'s own — `scenarioGherkin` decides what a step\n * IS, and a second opinion here would mean the gate and the emitted suite could\n * disagree about whether a scenario has any. That import is the one place these\n * two modules are circular (gherkin.ts parses requirements); both sides export\n * only function declarations, which are hoisted, so neither evaluation order\n * can observe a half-built module.\n */\nexport function steplessScenarios(reqs: Requirement[]): SteplessScenario[] {\n const out: SteplessScenario[] = [];\n for (const r of reqs) {\n if (r.kind === \"REMOVED\") continue;\n for (const s of r.scenarios) {\n if (scenarioGherkin(s.lines).steps.length === 0) out.push({ requirement: r.name, scenario: s.name });\n }\n }\n return out;\n}\n\n/**\n * The stepless half of the coverage check, as findings — the missing-scenario\n * half stays where it is (`requirementsMissingScenarios`), because the two are\n * different states with different fixes: one requirement owes acceptance\n * criteria, the other owes STEPS in criteria somebody has already written.\n *\n * `label` is the coverage check's own label (`payment-service: requirements`),\n * so both halves of one document name it the same way.\n */\nexport function steplessFindings(label: string, subject: string, reqs: Requirement[]): Finding[] {\n const bare = steplessScenarios(reqs);\n if (bare.length === 0) return [];\n return [\n {\n severity: \"error\",\n code: \"requirements.stepless-scenario\",\n subject,\n message:\n `${label}: ${bare.length} scenario(s) have a heading and no recognizable steps — ` +\n `they satisfy the coverage rule and test nothing. Cucumber runs a stepless scenario vacuously green and ` +\n `\\`loam verify --results\\` can never confirm it. Write the body as \\`- **Given/When/Then**\\` bullets.`,\n details: bare.map((s) => `${s.requirement} — ${s.scenario}`),\n text: { detailPrefix: \"- \" },\n },\n ];\n}\n\n/** Serialize requirements back to OpenSpec markdown (`### Requirement:` + `#### Scenario:`). */\nexport function serializeRequirements(reqs: Requirement[]): string {\n // Framing (blank lines between sections) is normalized here; body content is\n // only edge-trimmed, never collapsed — blank lines inside a scenario (e.g. in\n // fenced code blocks) are verbatim content.\n const chunks: string[] = [];\n for (const r of reqs) {\n const chunk: string[] = [`### Requirement: ${r.name}`];\n const body = [...r.text];\n // Parsed documents already carry the authored line in `text`. This branch\n // also makes programmatically constructed Requirements serialize fully.\n if (r.id !== undefined && !body.some((line) => REQUIREMENT_ID_LINE_RE.test(line))) {\n body.unshift(`Requirement-ID: ${r.id}`);\n }\n // Directly under the identity it pins, which is where `loam rebase` writes\n // it too — the two lines are read together, so they are never apart.\n if (r.basedOn !== undefined && !body.some((line) => BASED_ON_LINE_RE.test(line))) {\n body.splice(body.findIndex((line) => REQUIREMENT_ID_LINE_RE.test(line)) + 1, 0, `Based-On: ${r.basedOn}`);\n }\n const text = body.join(\"\\n\").trim();\n if (text) chunk.push(\"\", text);\n for (const s of r.scenarios) {\n chunk.push(\"\", `#### Scenario: ${s.name}`);\n const body = s.lines.join(\"\\n\").trim();\n if (body) chunk.push(body);\n }\n chunks.push(chunk.join(\"\\n\"));\n }\n return chunks.join(\"\\n\\n\").trim() + \"\\n\";\n}\n\n/**\n * A delta requirement as it lands in the living document, with the bookkeeping\n * that belongs to the DELTA left behind: the `Based-On:` pin (a claim about\n * which living version this was written against — meaningless once it IS the\n * living version, and poison for the next feature's baseline, which would then\n * hash the previous feature's pin) and the line it was parsed from.\n */\nfunction asLiving(d: Requirement): Requirement {\n const { line: _dropped, ...rest } = withoutBaseline(d);\n return { ...rest, kind: \"BASE\" };\n}\n\n/** Apply a feature's ADDED/MODIFIED/REMOVED requirements onto a living requirement set. */\nexport function applyRequirementDelta(living: Requirement[], delta: Requirement[]): Requirement[] {\n const malformed = [...requirementIdProblems(living), ...requirementIdProblems(delta)];\n if (malformed.length > 0) {\n throw new Error(\"cannot merge requirements with invalid, repeated, or duplicate Requirement-ID declarations\");\n }\n let result: Requirement[] = living.map((r) => ({ ...r, kind: \"BASE\" as DeltaKind }));\n for (const d of delta) {\n // BASE is not a delta kind — a requirement outside an ADDED/MODIFIED/REMOVED\n // section (e.g. quoted under ## Notes) is documentation, not a change.\n if (d.kind === \"BASE\") continue;\n if (d.id !== undefined) {\n const idMatches = result\n .map((r, i) => (r.id === d.id ? i : -1))\n .filter((i) => i >= 0);\n const nameMatches = result\n .map((r, i) => (r.name === d.name ? i : -1))\n .filter((i) => i >= 0);\n const otherNameMatches = nameMatches.filter((i) => !idMatches.includes(i));\n if (idMatches.length > 1 || otherNameMatches.length > 0) {\n throw new Error(\n `ambiguous requirement identity for '${d.name}' (${d.id}): Requirement-ID and heading select different living requirements`,\n );\n }\n if (d.kind === \"REMOVED\") {\n const selected = new Set(idMatches);\n result = result.filter((_, i) => !selected.has(i));\n } else {\n const merged: Requirement = asLiving(d);\n if (idMatches.length === 1) result[idMatches[0]!] = merged;\n else result.push(merged);\n }\n } else if (d.kind === \"REMOVED\") {\n result = result.filter((r) => r.name !== d.name);\n } else {\n const i = result.findIndex((r) => r.name === d.name);\n // A legacy delta may still modify an ID-bearing living requirement by\n // its exact heading. Keep the identity while the repository migrates.\n const inheritedId = i >= 0 ? result[i]!.id : undefined;\n const merged: Requirement = {\n ...asLiving(d),\n ...(inheritedId === undefined ? {} : { id: inheritedId }),\n };\n if (i >= 0) result[i] = merged;\n else result.push(merged);\n }\n }\n return result;\n}\n"]}
@@ -13,6 +13,14 @@ import { link, mkdir, open, readdir, readFile, rename, rm, rmdir, unlink, writeF
13
13
  import { hostname } from "node:os";
14
14
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
15
  import { repoPath } from "./json.js";
16
+ import { resolvePortableFileInsideLexically, UnsafePathError } from "./path-safety.js";
17
+ // Every `isRecord` below guards a record loam itself wrote and is reading back
18
+ // — the lock, the snapshot manifest — whose fields are asked for on the very
19
+ // next line, inside a REFUSAL path. `JSON.parse` answers with any JSON value,
20
+ // not with an object, and that is where a thrown `TypeError` costs the most: it
21
+ // does not make the command fail safely, it replaces a designed refusal with
22
+ // `internal`.
23
+ import { isRecord } from "./records.js";
16
24
  /** The one place a planned write becomes bytes. */
17
25
  function toBytes(content) {
18
26
  return typeof content === "string" ? Buffer.from(content, "utf8") : content;
@@ -38,29 +46,57 @@ export function planWrite(path, content) {
38
46
  /* Bytes in, text only where a parser needs it */
39
47
  /* ------------------------------------------------------------------ */
40
48
  /**
41
- * A file loam must PARSE, whose bytes are not UTF-8.
49
+ * A file loam must PARSE that does not decode as the UTF-8 text loam owns.
42
50
  *
43
51
  * Commands map this to `merge-failed`: nothing was written, the file is named,
44
52
  * and re-saving it as UTF-8 makes the command work. The read-only migration
45
53
  * ingest already refuses non-UTF-8 input outright (openspec-inventory.ts) —
46
54
  * the destructive path has strictly more to lose, so it refuses the same way
47
55
  * rather than substituting U+FFFD and rewriting the file over the author.
56
+ *
57
+ * `reason` says what the bytes actually ARE, because the two ways a document
58
+ * fails this test destroy different things: one substitutes bytes, the other
59
+ * erases the whole document's meaning. A reader told the wrong one goes looking
60
+ * in the wrong place. The advice that follows is the same either way, so it is
61
+ * spelled once, here.
48
62
  */
49
63
  export class NotUtf8Error extends Error {
50
64
  path;
51
65
  name = "NotUtf8Error";
52
- constructor(path) {
53
- super(`${path} is not valid UTF-8 — loam parses this file as text and writes it back, which would replace every ` +
54
- `undecodable byte with U+FFFD, in the living document AND in the undo snapshot. Nothing was written. ` +
55
- `Re-save it as UTF-8, then re-run.`);
66
+ constructor(path, reason) {
67
+ super(`${path} ${reason} Nothing was written. Re-save it as UTF-8, then re-run.`);
56
68
  this.path = path;
57
69
  }
58
70
  }
59
- /** Decode bytes a parser is about to be handed, or refuse naming the file. */
60
- export function decodeUtf8(bytes, path) {
61
- if (!isUtf8(bytes))
62
- throw new NotUtf8Error(path);
63
- return bytes.toString("utf8");
71
+ /**
72
+ * Decode bytes a parser is about to be handed, or refuse naming the file.
73
+ *
74
+ * Two tests, the same two the read path makes (document-bytes.ts's
75
+ * `decodeDocument`), because this side has strictly more to lose by missing
76
+ * either. `isUtf8` catches the byte sequences that cannot be UTF-8 at all —
77
+ * which is what a byte-order mark makes UTF-16 into. Without a BOM, UTF-16LE of
78
+ * ASCII is a sequence of perfectly VALID UTF-8 bytes: every other byte is NUL,
79
+ * so `isUtf8` says yes, the file decodes with a U+0000 between every character,
80
+ * and every parser loam owns reads its requirements, frontmatter and headings
81
+ * as absent rather than as unreadable. On the read path that is a document
82
+ * graded green while nothing in it was checked; here it is worse, because
83
+ * `archive` merges against that empty baseline and writes the result back — the
84
+ * author's requirements are not mis-read, they are gone, and the undo snapshot
85
+ * records the same emptiness as the pre-image.
86
+ */
87
+ function decodeUtf8(bytes, path) {
88
+ if (!isUtf8(bytes)) {
89
+ throw new NotUtf8Error(path, `is not valid UTF-8 — loam parses this file as text and writes it back, which would replace every ` +
90
+ `undecodable byte with U+FFFD, in the living document AND in the undo snapshot.`);
91
+ }
92
+ const text = bytes.toString("utf8");
93
+ if (text.includes("\u0000")) {
94
+ throw new NotUtf8Error(path, `holds NUL characters, which no document loam owns does — almost always UTF-16 saved without a byte-order ` +
95
+ `mark. Its bytes are valid UTF-8, so it decodes without complaint into text whose requirements, ` +
96
+ `frontmatter and headings all parse as ABSENT: the merge would compute over an empty baseline and write ` +
97
+ `that back, taking every requirement in the file with it.`);
98
+ }
99
+ return text;
64
100
  }
65
101
  /** Read a file loam is going to parse. The only supported way to turn a docs file into a string. */
66
102
  export async function readUtf8(path) {
@@ -71,6 +107,13 @@ function sameBytes(a, b) {
71
107
  return a === null || b === null ? a === b : a.equals(b);
72
108
  }
73
109
  /* ------------------------------------------------------------------ */
110
+ /* Reading loam's own records back off the disk */
111
+ /* ------------------------------------------------------------------ */
112
+ /** The one spelling of a sha256 loam wrote, for reading one back out of a record. */
113
+ function isDigest(value) {
114
+ return typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
115
+ }
116
+ /* ------------------------------------------------------------------ */
74
117
  /* The docs-repo advisory lock */
75
118
  /* ------------------------------------------------------------------ */
76
119
  /** The lock file, in the docs repo root — one writer at a time across the whole fleet. */
@@ -156,6 +199,13 @@ async function breakStaleLock(path) {
156
199
  // cannot understand is the one case where guessing is worst.
157
200
  return false;
158
201
  }
202
+ // A lock file holding `null` (or a bare string, or an array) is JSON this
203
+ // parses and nothing else understands. Treat it as held, exactly as an
204
+ // unparseable one is: the dereference below used to run outside the try and
205
+ // threw out of `acquireDocsLock`, replacing the `docs-busy` refusal — the
206
+ // designed answer — with an `internal` envelope.
207
+ if (!isRecord(holder))
208
+ return false;
159
209
  if (holder.host !== hostname() || typeof holder.pid !== "number")
160
210
  return false;
161
211
  try {
@@ -469,16 +519,40 @@ async function assertSnapshotReplaceable(dir, docsDir) {
469
519
  catch {
470
520
  throw new SnapshotClobberError(dir, `${SNAPSHOT_MANIFEST} cannot be read, so nothing can say whether it is stale`);
471
521
  }
472
- const parsed = manifest;
473
- if (parsed.version !== SNAPSHOT_VERSION || !Array.isArray(parsed.files)) {
522
+ // The cast that used to stand here asserted the shape rather than checking
523
+ // it: well-formed JSON that is not an object answered `undefined` to every
524
+ // field below and slipped through as "a different loam", and a bare `null`
525
+ // threw a TypeError out of the refusal itself. Both left this directory —
526
+ // which may hold the only copies of what the living docs said — one step from
527
+ // being replaced, without the staleness question ever having been asked.
528
+ if (!isRecord(manifest)) {
529
+ throw new SnapshotClobberError(dir, `${SNAPSHOT_MANIFEST} cannot be read, so nothing can say whether it is stale`);
530
+ }
531
+ if (manifest.version !== SNAPSHOT_VERSION || !Array.isArray(manifest.files)) {
474
532
  throw new SnapshotClobberError(dir, `it was written by a different loam and cannot be checked against the living docs`);
475
533
  }
534
+ // `Array.isArray` narrows to `any[]`; naming the element type here is what
535
+ // keeps that `any` from spreading past the one row being read.
536
+ const rows = manifest.files;
476
537
  const landed = [];
477
- for (const entry of parsed.files) {
478
- if (typeof entry?.path !== "string") {
538
+ for (const row of rows) {
539
+ const entry = readSnapshotClaim(row);
540
+ if (entry === null) {
479
541
  throw new SnapshotClobberError(dir, `${SNAPSHOT_MANIFEST} is malformed, so nothing can say whether it is stale`);
480
542
  }
481
- const target = join(docsDir, ...entry.path.split("/"));
543
+ let target;
544
+ try {
545
+ // These paths are data, and they are the ones this function goes and
546
+ // reads. They name living documents, so containment is lexical: a docs
547
+ // repo may legitimately mount a service directory through a symlink, and
548
+ // `unarchive` resolves the same field the same way before it writes back.
549
+ target = resolvePortableFileInsideLexically(docsDir, entry.path, `snapshot path '${entry.path}'`);
550
+ }
551
+ catch (err) {
552
+ if (!(err instanceof UnsafePathError))
553
+ throw err;
554
+ throw new SnapshotClobberError(dir, `${message(err)}, so nothing can say whether it is stale`);
555
+ }
482
556
  const now = existsSync(target) ? sha256(await readFile(target)) : null;
483
557
  // `existed: false` means archive created the file, so "nothing landed"
484
558
  // means it is still absent.
@@ -489,6 +563,34 @@ async function assertSnapshotReplaceable(dir, docsDir) {
489
563
  if (landed.length > 0)
490
564
  throw new SnapshotClobberError(dir, `${landed.length} file(s) already carry that merge: ${landed.join(", ")}`);
491
565
  }
566
+ /**
567
+ * One manifest row read back as the record `writeSnapshot` wrote, or null when
568
+ * the file does not actually say.
569
+ *
570
+ * Only the three fields the staleness question consumes are checked, and every
571
+ * one of them is checked, because an unchecked field does not read as missing
572
+ * here — it reads as an ANSWER. An `existed` that is not a boolean is falsy, and
573
+ * a `false` claim is graded by asking whether the file is ABSENT: a manifest
574
+ * recording a pre-image for a file that has since been deleted therefore graded
575
+ * as stale bookkeeping and was cleared, taking the only copy of that pre-image
576
+ * with it. A `before` of the wrong type equals no digest at all, so the opposite
577
+ * row accuses an untouched file of carrying a merge. Both are confident answers
578
+ * to a question the manifest could not answer.
579
+ *
580
+ * `unarchive` asks a stricter version of the same question of the same file
581
+ * (`after`, `archivedAt`, the feature name, no duplicates) because it is about
582
+ * to write THROUGH it; that check stays where it is, with its own refusals.
583
+ */
584
+ function readSnapshotClaim(value) {
585
+ if (!isRecord(value))
586
+ return null;
587
+ const { path, existed, before } = value;
588
+ if (typeof path !== "string" || typeof existed !== "boolean")
589
+ return null;
590
+ if (existed)
591
+ return isDigest(before) ? { path, existed, before } : null;
592
+ return before === null ? { path, existed, before } : null;
593
+ }
492
594
  /* ------------------------------------------------------------------ */
493
595
  /* The commit intent record */
494
596
  /* ------------------------------------------------------------------ */
@@ -511,7 +613,7 @@ async function assertSnapshotReplaceable(dir, docsDir) {
511
613
  * commit window it does not exist.
512
614
  */
513
615
  export const COMMIT_INTENT = ".loam-commit";
514
- export const COMMIT_INTENT_VERSION = 1;
616
+ const COMMIT_INTENT_VERSION = 1;
515
617
  /** An interrupted commit this loam must not silently write over. */
516
618
  export class InterruptedCommitError extends Error {
517
619
  name = "InterruptedCommitError";
@@ -603,7 +705,7 @@ export async function readCommitIntent(docsDir) {
603
705
  return i;
604
706
  }
605
707
  function isDigestOrNull(value) {
606
- return value === null || (typeof value === "string" && /^[0-9a-f]{64}$/.test(value));
708
+ return value === null || isDigest(value);
607
709
  }
608
710
  /**
609
711
  * Refuse or repair before this run reads anything. Returns null when there is
@@ -748,6 +850,11 @@ async function lockIsStale(path) {
748
850
  catch {
749
851
  return false;
750
852
  }
853
+ // Same shape guard as `breakStaleLock`, for the same reason: this one is read
854
+ // by `doctor`, which must be able to describe a broken repo without becoming
855
+ // the next thing that breaks.
856
+ if (!isRecord(holder))
857
+ return false;
751
858
  if (holder.host !== hostname() || typeof holder.pid !== "number")
752
859
  return false;
753
860
  try {