@ybotok/loam 0.0.0 → 0.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +138 -0
  2. package/COMPARISON.md +63 -0
  3. package/LICENSE +21 -0
  4. package/MIGRATING-from-OpenSpec.md +202 -0
  5. package/README.md +246 -9
  6. package/SCHEMA.md +425 -0
  7. package/SECURITY.md +9 -0
  8. package/dist/cli.js +142 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/commands/adopt.js +240 -0
  11. package/dist/commands/adopt.js.map +1 -0
  12. package/dist/commands/archive.js +1313 -0
  13. package/dist/commands/archive.js.map +1 -0
  14. package/dist/commands/delta.js +388 -0
  15. package/dist/commands/delta.js.map +1 -0
  16. package/dist/commands/dependencies.js +83 -0
  17. package/dist/commands/dependencies.js.map +1 -0
  18. package/dist/commands/docs-repo-gate.js +104 -0
  19. package/dist/commands/docs-repo-gate.js.map +1 -0
  20. package/dist/commands/doctor.js +85 -0
  21. package/dist/commands/doctor.js.map +1 -0
  22. package/dist/commands/explore.js +195 -0
  23. package/dist/commands/explore.js.map +1 -0
  24. package/dist/commands/format.js +17 -0
  25. package/dist/commands/format.js.map +1 -0
  26. package/dist/commands/gherkin.js +309 -0
  27. package/dist/commands/gherkin.js.map +1 -0
  28. package/dist/commands/init.js +250 -0
  29. package/dist/commands/init.js.map +1 -0
  30. package/dist/commands/instructions.js +70 -0
  31. package/dist/commands/instructions.js.map +1 -0
  32. package/dist/commands/list.js +291 -0
  33. package/dist/commands/list.js.map +1 -0
  34. package/dist/commands/migrate-openspec.js +950 -0
  35. package/dist/commands/migrate-openspec.js.map +1 -0
  36. package/dist/commands/new.js +413 -0
  37. package/dist/commands/new.js.map +1 -0
  38. package/dist/commands/rebase.js +356 -0
  39. package/dist/commands/rebase.js.map +1 -0
  40. package/dist/commands/show.js +320 -0
  41. package/dist/commands/show.js.map +1 -0
  42. package/dist/commands/status.js +254 -0
  43. package/dist/commands/status.js.map +1 -0
  44. package/dist/commands/unarchive.js +317 -0
  45. package/dist/commands/unarchive.js.map +1 -0
  46. package/dist/commands/validate.js +1591 -0
  47. package/dist/commands/validate.js.map +1 -0
  48. package/dist/commands/verify.js +775 -0
  49. package/dist/commands/verify.js.map +1 -0
  50. package/dist/commands/vouch.js +343 -0
  51. package/dist/commands/vouch.js.map +1 -0
  52. package/dist/core/agent.js +2065 -0
  53. package/dist/core/agent.js.map +1 -0
  54. package/dist/core/agents-stamp.js +68 -0
  55. package/dist/core/agents-stamp.js.map +1 -0
  56. package/dist/core/arch.js +130 -0
  57. package/dist/core/arch.js.map +1 -0
  58. package/dist/core/brief.js +733 -0
  59. package/dist/core/brief.js.map +1 -0
  60. package/dist/core/coherence.js +577 -0
  61. package/dist/core/coherence.js.map +1 -0
  62. package/dist/core/concurrency.js +51 -0
  63. package/dist/core/concurrency.js.map +1 -0
  64. package/dist/core/config.js +180 -0
  65. package/dist/core/config.js.map +1 -0
  66. package/dist/core/delta.js +476 -0
  67. package/dist/core/delta.js.map +1 -0
  68. package/dist/core/dependencies.js +356 -0
  69. package/dist/core/dependencies.js.map +1 -0
  70. package/dist/core/docs.js +144 -0
  71. package/dist/core/docs.js.map +1 -0
  72. package/dist/core/doctor.js +559 -0
  73. package/dist/core/doctor.js.map +1 -0
  74. package/dist/core/document-bytes.js +59 -0
  75. package/dist/core/document-bytes.js.map +1 -0
  76. package/dist/core/explore.js +225 -0
  77. package/dist/core/explore.js.map +1 -0
  78. package/dist/core/fleet-context.js +225 -0
  79. package/dist/core/fleet-context.js.map +1 -0
  80. package/dist/core/frontmatter.js +199 -0
  81. package/dist/core/frontmatter.js.map +1 -0
  82. package/dist/core/gherkin.js +463 -0
  83. package/dist/core/gherkin.js.map +1 -0
  84. package/dist/core/health.js +67 -0
  85. package/dist/core/health.js.map +1 -0
  86. package/dist/core/ids.js +122 -0
  87. package/dist/core/ids.js.map +1 -0
  88. package/dist/core/issue.js +9 -0
  89. package/dist/core/issue.js.map +1 -0
  90. package/dist/core/json.js +74 -0
  91. package/dist/core/json.js.map +1 -0
  92. package/dist/core/likec4.js +479 -0
  93. package/dist/core/likec4.js.map +1 -0
  94. package/dist/core/maturity.js +66 -0
  95. package/dist/core/maturity.js.map +1 -0
  96. package/dist/core/openapi-merge.js +552 -0
  97. package/dist/core/openapi-merge.js.map +1 -0
  98. package/dist/core/openapi.js +255 -0
  99. package/dist/core/openapi.js.map +1 -0
  100. package/dist/core/openspec-inventory.js +1440 -0
  101. package/dist/core/openspec-inventory.js.map +1 -0
  102. package/dist/core/path-safety.js +168 -0
  103. package/dist/core/path-safety.js.map +1 -0
  104. package/dist/core/provenance.js +720 -0
  105. package/dist/core/provenance.js.map +1 -0
  106. package/dist/core/records.js +33 -0
  107. package/dist/core/records.js.map +1 -0
  108. package/dist/core/repo.js +436 -0
  109. package/dist/core/repo.js.map +1 -0
  110. package/dist/core/report.js +47 -0
  111. package/dist/core/report.js.map +1 -0
  112. package/dist/core/results.js +199 -0
  113. package/dist/core/results.js.map +1 -0
  114. package/dist/core/spec.js +481 -0
  115. package/dist/core/spec.js.map +1 -0
  116. package/dist/core/staging.js +890 -0
  117. package/dist/core/staging.js.map +1 -0
  118. package/dist/core/status.js +1104 -0
  119. package/dist/core/status.js.map +1 -0
  120. package/dist/core/steps.js +72 -0
  121. package/dist/core/steps.js.map +1 -0
  122. package/dist/core/verify.js +807 -0
  123. package/dist/core/verify.js.map +1 -0
  124. package/dist/core/version.js +24 -0
  125. package/dist/core/version.js.map +1 -0
  126. package/package.json +63 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provenance.js","sourceRoot":"","sources":["../../src/core/provenance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,S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KAAK,CAAC;QACf,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,2FAA2F;AAC3F,SAAS,YAAY,CAAC,OAAe,EAAE,MAAc;IACnD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACvC,IAAI,CAAC;QACH,OAAO,UAAU,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,MAAM,GAAG,CAAC,CAAC,CAAC;IAC3E,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["/**\n * Provenance checks: is this artifact anchored to anything, and has anyone\n * vouched for it?\n *\n * SCHEMA.md has declared `status` / `owner` / `sources` / `last_verified` since\n * the beginning and nothing read them. They matter more now that the prose is\n * written by an agent: coherence proves the corpus agrees with itself, and only\n * `sources` says it has anything to do with the code.\n *\n * Absence and contradiction are graded differently on purpose. A missing field\n * is incompleteness — a warning, something to work through. A field that says\n * the wrong thing (a spec claiming to be another service, a status nobody\n * defined) is a bug, and gates.\n */\nimport { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readdir, readFile, realpath, stat } from \"node:fs/promises\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport {\n listField,\n parseFrontmatter,\n rawBody,\n readFrontmatter,\n stringField,\n FEATURE_STATUSES,\n SERVICE_STATUSES,\n type Frontmatter,\n} from \"./frontmatter.js\";\nimport type { Finding } from \"./report.js\";\nimport { featurePaths, servicePaths, SPEC_AXES } from \"./repo.js\";\nimport { isPathInside, resolveInside } from \"./path-safety.js\";\n\n/** Fields every artifact is expected to carry, beyond its identity and status. */\nconst EXPECTED = [\"owner\"] as const;\n\nexport interface ProvenanceOptions {\n /**\n * The repo `sources` resolve against — the service repo loam is running in.\n * Undefined when the docs being validated describe some other repository, in\n * which case the paths are not ours to resolve and are left alone.\n */\n repoDir?: string;\n}\n\nexport async function serviceProvenance(\n docsDir: string,\n service: string,\n opts: ProvenanceOptions = {},\n): Promise<Finding[]> {\n const paths = servicePaths(docsDir, service);\n const findings: Finding[] = [];\n // Both requirement-carrying specs get the same pass: arch.spec.md follows\n // spec.md's frontmatter conventions exactly, so the checks are one loop —\n // only the label tells a reader which file moved. The pair comes from\n // SPEC_AXES rather than being respelled, so a third axis is graded here the\n // day it is declared instead of the day somebody notices.\n for (const { path, file } of SPEC_AXES.map((axis) => ({ path: paths[axis.key], file: axis.file }))) {\n if (!existsSync(path)) continue;\n const raw = await readFile(path, \"utf8\");\n const fm = parseFrontmatter(raw);\n const label = `${service}: ${file}`;\n findings.push(\n ...identityFindings(fm, {\n label,\n idField: \"service\",\n idValue: service,\n statuses: [...SERVICE_STATUSES],\n }),\n );\n // With no frontmatter at all, \"it names no sources\" says nothing the missing\n // header did not already say — and a malformed one proves nothing either:\n // `sources.absent` against a header nobody can read is the same false\n // advice as the field cascade, so frontmatter.malformed stands alone.\n if (fm.present && !fm.malformed) {\n findings.push(...(await sourceFindings(fm, service, label, opts.repoDir)));\n findings.push(...contentFindings(fm, raw, service, label));\n }\n }\n return findings;\n}\n\nexport async function featureProvenance(\n featureDir: string,\n featureId: string,\n): Promise<Finding[]> {\n const path = featurePaths(featureDir).intent;\n if (!existsSync(path)) return [];\n const fm = await readFrontmatter(path);\n return identityFindings(fm, {\n label: \"intent.md\",\n idField: \"feature\",\n idValue: featureId,\n statuses: [...FEATURE_STATUSES],\n });\n}\n\ninterface IdentitySpec {\n label: string;\n idField: \"service\" | \"feature\";\n idValue: string;\n statuses: string[];\n}\n\nfunction identityFindings(fm: Frontmatter, spec: IdentitySpec): Finding[] {\n const findings: Finding[] = [];\n if (!fm.present) {\n return [\n {\n severity: \"warn\",\n code: \"frontmatter.missing\",\n subject: spec.idValue,\n message: `${spec.label} has no frontmatter — no owner, no status, no link to the code it describes`,\n },\n ];\n }\n\n // One honest error instead of the cascade: with an unreadable header the\n // field checks below would grade owner/status/service \"missing\" and send the\n // author adding fields to a block YAML refuses to parse. Nothing can be\n // concluded from a header nobody can read — including that it lacks fields.\n if (fm.malformed) {\n return [\n {\n severity: \"error\",\n code: \"frontmatter.malformed\",\n subject: spec.idValue,\n message: `${spec.label} has frontmatter that does not parse as YAML — owner, status and sources are unreadable until the header is fixed`,\n },\n ];\n }\n\n const id = stringField(fm, spec.idField);\n if (id !== undefined && id !== spec.idValue) {\n findings.push({\n severity: \"error\",\n code: \"frontmatter.field-mismatch\",\n subject: spec.idValue,\n message: `${spec.label} declares ${spec.idField}: ${id}, but it lives under ${spec.idValue}`,\n });\n }\n\n const status = stringField(fm, \"status\");\n if (status !== undefined && !spec.statuses.includes(status)) {\n findings.push({\n severity: \"error\",\n code: \"frontmatter.status-unknown\",\n subject: spec.idValue,\n message: `${spec.label} has status '${status}' — expected one of ${spec.statuses.join(\", \")}`,\n });\n }\n\n const missing = [\n ...(id === undefined ? [spec.idField] : []),\n ...(status === undefined ? [\"status\"] : []),\n ...EXPECTED.filter((f) => stringField(fm, f) === undefined),\n ];\n if (missing.length > 0) {\n findings.push({\n severity: \"warn\",\n code: \"frontmatter.field-missing\",\n subject: spec.idValue,\n message: `${spec.label} is missing ${missing.length} frontmatter field(s)`,\n details: missing,\n text: { detailPrefix: \"- \" },\n });\n }\n return findings;\n}\n\nasync function sourceFindings(\n fm: Frontmatter,\n service: string,\n label: string,\n repoDir: string | undefined,\n): Promise<Finding[]> {\n const sources = listField(fm, \"sources\");\n if (sources.length === 0) {\n return [\n {\n severity: \"warn\",\n code: \"sources.absent\",\n message: `${label} names no sources — nothing ties it to the code, so nothing can tell you when it goes out of date`,\n },\n ];\n }\n // Someone else's repository: the paths describe a tree loam is not standing in.\n if (repoDir === undefined) return [];\n\n // Before existence: a pattern entry would \"not exist\" as a literal path, and\n // grading it missing would send the author fixing the wrong thing.\n const patterns = patternSources(sources);\n if (patterns.length > 0) {\n return [\n {\n severity: \"error\",\n code: \"sources.path-missing\",\n message: `${label}: ${patterns.length} source(s) are glob patterns — ${patterns.join(\", \")}. Patterns are no longer supported: name files or directories (a directory already covers everything beneath it).`,\n details: patterns,\n text: { detailPrefix: \"- \" },\n },\n ];\n }\n\n const unsafe = unsafeSources(repoDir, sources);\n if (unsafe.length > 0) {\n return [\n {\n severity: \"error\",\n code: \"sources.path-outside\",\n message: `${label}: ${unsafe.length} source(s) escape the service repo — ${unsafe.join(\", \")}. Sources must be relative paths contained by this repository, including through symlinks.`,\n details: unsafe,\n text: { detailPrefix: \"- \" },\n },\n ];\n }\n\n const missing = missingSources(repoDir, sources);\n if (missing.length > 0) {\n return [\n {\n severity: \"error\",\n code: \"sources.path-missing\",\n message: `${label}: ${missing.length} source(s) do not exist — ${missing.join(\", \")}`,\n details: missing,\n text: { detailPrefix: \"- \" },\n },\n ];\n }\n const resolved: Finding = {\n severity: \"ok\",\n code: \"sources.resolved\",\n message: `${label}: ${sources.length} source(s) resolve`,\n };\n\n // The walk happens here rather than inside the staleness branch below, even\n // though only staleness needs the hashes: what the walk REFUSED to follow is\n // a hole in the tie to the code whether or not anybody has vouched yet, and\n // an unvouched service is exactly where a reader is about to decide the\n // sources list is honest.\n const { digest, files, index, skipped } = await sourcesDigest(repoDir, sources);\n const findings: Finding[] = [resolved, ...skippedFindings(skipped, label)];\n\n // The paths are there; the question staleness answers is whether what is AT\n // them is still what somebody read.\n const stamped = stringField(fm, \"sources_digest\");\n if (stamped === undefined) {\n return [\n ...findings,\n {\n severity: \"warn\",\n code: \"sources.unvouched\",\n message: `${label}: no sources_digest — nobody has vouched for this against the code, so nothing can tell you when it goes stale. Run \\`loam vouch --service ${service}\\`.`,\n },\n ];\n }\n\n const since = stringField(fm, \"last_verified\") ?? \"it was stamped\";\n if (digest === stamped) {\n return [\n ...findings,\n {\n severity: \"ok\",\n code: \"sources.current\",\n message: `${label}: sources unchanged since ${since} (${files.length} file(s), digest ${digest})`,\n },\n ];\n }\n\n // What MOVED, when the stamp recorded enough to say. Repeating the frontmatter's\n // own `sources` entries back at a reader — which is all this finding could do\n // before `sources_files` existed — answers a question nobody asked: they wrote\n // that list, and \"one of these five directories changed somehow\" is where the\n // search starts, not where it ends.\n const moved = movedSources(decodeSourceIndex(stringField(fm, \"sources_files\")), index);\n return [\n ...findings,\n {\n // A warning, not an error: the doc may still be right, and only a person\n // can say. What loam knows is that nobody has looked since the code moved.\n severity: \"warn\",\n code: \"sources.stale\",\n message: `${label}: sources changed since ${since}${moved.summary} — re-read them and \\`loam vouch --service ${service}\\``,\n details: moved.paths ?? sources,\n text: { detailPrefix: \"- \" },\n },\n ];\n}\n\n/**\n * The paths the digest walk would not follow. Never silent: a symlink dropped\n * on the floor is a file whose content nobody is watching, while the document\n * beside it says `verified` — the digest cannot go stale over bytes it never\n * hashed, so the one thing the stamp promises is quietly untrue for them.\n *\n * A warning, not an error, and for the same reason staleness is: the doc may be\n * perfectly right about the code behind that link. What loam can say is that it\n * is not watching it.\n */\nfunction skippedFindings(skipped: SkippedSource[], label: string): Finding[] {\n if (skipped.length === 0) return [];\n return [\n {\n severity: \"warn\",\n code: \"sources.skipped\",\n message: `${label}: ${skipped.length} path(s) under the listed sources were not hashed — the digest says nothing about what is behind them`,\n details: skipped.map((s) => `${s.path} — ${s.reason}`),\n text: { detailPrefix: \"- \" },\n },\n ];\n}\n\n/**\n * The doc-side half of the freshness check. `sources_digest` says whether the\n * CODE moved since a person looked, and only that service's repo can recompute\n * it; `content_digest` says whether the DOCUMENT did, and needs nothing but\n * the document — so this runs wherever the spec is readable, `--service` and\n * `--all` alike. Without it, editing a spec after it was vouched left\n * `status: verified` standing over words nobody read — forged freshness, in\n * the exact agent-written-prose threat model this layer exists for.\n */\nfunction contentFindings(fm: Frontmatter, raw: string, service: string, label: string): Finding[] {\n if (stringField(fm, \"status\") !== \"verified\") return [];\n const stamped = stringField(fm, \"content_digest\");\n // A verified doc with no stamp predates the field. Quiet on purpose: the fix\n // is re-vouching, and grading years of pre-feature vouches as suspect would\n // drown the fleet in warnings nobody chose.\n if (stamped === undefined) return [];\n if (contentDigest(raw) === stamped) return [];\n const since = stringField(fm, \"last_verified\") ?? \"it was vouched\";\n return [\n {\n // A warning, not an error — the sources.stale doctrine: the doc changed\n // since it was vouched, and only a person can say whether verified still\n // holds of the new words.\n severity: \"warn\",\n code: \"content.stale\",\n message: `${label} changed since ${since} — the doc moved under its vouch, and only a person can say whether 'verified' still holds. Re-read it and \\`loam vouch --service ${service}\\`.`,\n },\n ];\n}\n\n/**\n * The local calendar day, for the two commands that date a stamp. A vouch or a\n * verification record is a person saying \"today I read this\", so it is their\n * date, not UTC's — `toISOString` files an evening in the Americas under\n * tomorrow. It sits here because this module already owns the stamp vocabulary\n * the date is written into.\n */\nexport function today(now: Date): string {\n const pad = (n: number): string => String(n).padStart(2, \"0\");\n return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;\n}\n\n/* ------------------------------------------------------------------ */\n/* The content digest */\n/* ------------------------------------------------------------------ */\n\n/** How much of the sha256 is written into the document. */\nconst DIGEST_LENGTH = 16;\n\n/** How many source files the digest reads at once — see `sourcesDigest`. */\nconst DIGEST_READ_BATCH = 32;\n\nexport interface SourcesDigest extends SourcesExpansion {\n /** The stamp that goes in `sources_digest`. */\n digest: string;\n /**\n * Per file, its own short sha — the record `sources_files` carries so a later\n * `sources.stale` can name what moved instead of guessing. Same order as `files`.\n */\n index: SourceIndexEntry[];\n}\n\n/** One file's share of the stamp: what it is called, and what it said. */\nexport interface SourceIndexEntry {\n /** Repo-relative, `/`-separated. */\n path: string;\n /** sha256 of its bytes, truncated the way `sources_digest` is. */\n sha: string;\n}\n\n/** A path the walk found but would not hash, and the reason a reader needs. */\nexport interface SkippedSource {\n /** Repo-relative, `/`-separated. */\n path: string;\n /** Why it was left out — the half of the sentence after the path. */\n reason: string;\n}\n\n/** What a `sources` list covers, and what it does not. */\nexport interface SourcesExpansion {\n /** Repo-relative paths, sorted — exactly what a digest would hash. */\n files: string[];\n /** Everything the walk refused to follow. Empty in the ordinary case. */\n skipped: SkippedSource[];\n /**\n * Set only when `files` is empty: the one sentence that says the list covers\n * nothing. `loam vouch` refuses with it, `loam validate` grades it — see\n * emptySourcesMessage for why they must be the same words.\n */\n empty?: string;\n}\n\n/**\n * Digest the CONTENT of the files `sources` names. The recipe is spelled out\n * because the value is written into documents, and anything reading them has to\n * be able to reproduce it:\n *\n * 1. expand each entry to repo-relative file paths (`/` separators) — a file\n * is itself, a directory everything beneath it, minus what the repository\n * does not consider its own (see collectSources) — sorted and de-duplicated;\n * 2. per file, `sha256(bytes)`;\n * 3. feed `<path>\\0<hex>\\n` for each file, in that order, into an outer\n * sha256;\n * 4. keep the first 16 hex characters.\n *\n * Content, not mtime: git does not preserve modification times, so after a\n * fresh clone every file looks changed and the check would be false positives\n * end to end. Bytes survive the clone. Hashing the path alongside the content\n * means a rename registers, which is what a reader of the doc would want.\n *\n * 64 bits is a change detector, not a seal — it answers \"did this move?\", and\n * an adversary who wants a collision can have one.\n */\nexport async function sourcesDigest(repoDir: string, sources: string[]): Promise<SourcesDigest> {\n const { found, skipped } = await collectSources(repoDir, sources);\n const outer = createHash(\"sha256\");\n const index: SourceIndexEntry[] = [];\n // Read in fixed batches, hash in array order. `found` is already sorted and\n // every file's own sha depends on nothing but its own bytes, so the sequence\n // fed to `outer` — and therefore the digest — is unchanged by construction;\n // only the waiting overlaps. A `sources: [src/]` over a real service repo is\n // thousands of files, and one-await-per-file spent nearly all of its time\n // idle. The batch is bounded rather than a single `Promise.all` over the\n // whole list because an unbounded fan-out over a source tree runs the process\n // out of file descriptors, which would turn a stamp into an EMFILE.\n for (let start = 0; start < found.length; start += DIGEST_READ_BATCH) {\n const hashed = await Promise.all(\n found.slice(start, start + DIGEST_READ_BATCH).map(async (file) => ({\n rel: file.rel,\n content: createHash(\"sha256\").update(await readFile(file.abs)).digest(\"hex\"),\n })),\n );\n for (const { rel, content } of hashed) {\n outer.update(`${rel}\\0${content}\\n`);\n index.push({ path: rel, sha: content.slice(0, DIGEST_LENGTH) });\n }\n }\n // `empty` is deliberately not set here: it is a sentence about a named\n // document, and a digest has no name to put in it. Callers that need it say\n // emptySourcesMessage(label, sources) — the same words, from one definition.\n return { digest: outer.digest(\"hex\").slice(0, DIGEST_LENGTH), files: index.map((e) => e.path), index, skipped };\n}\n\n/**\n * What a `sources` list actually covers — the digest's file set without the\n * hashing.\n *\n * Exported because two commands must give the SAME answer to \"does this list\n * cover anything?\". `loam vouch` refuses to stamp an expansion that covers no\n * files (a digest over nothing never changes, so the stamp would read as\n * current forever), and until `loam validate` could say the same thing in the\n * same words, an author got a green validate followed by a vouch that refused —\n * two commands contradicting each other about one document, with nothing in the\n * green run hinting at it.\n */\nexport async function expandSourceFiles(\n repoDir: string,\n sources: string[],\n label: string,\n): Promise<SourcesExpansion> {\n const { found, skipped } = await collectSources(repoDir, sources);\n const files = found.map((f) => f.rel);\n return { files, skipped, ...(files.length === 0 ? { empty: emptySourcesMessage(label, sources) } : {}) };\n}\n\n/**\n * The one sentence for \"these paths exist and cover no file\". One definition,\n * because `vouch`'s refusal and `validate`'s finding are the same diagnosis\n * about the same document and must not drift into two descriptions of it — the\n * author fixes it once, in the sources list.\n */\nexport function emptySourcesMessage(label: string, sources: string[]): string {\n return `${label}: the sources listed match no files — ${sources.join(\", \")}. A digest over nothing would read as current forever.`;\n}\n\n/**\n * The stamp `loam vouch` writes into `content_digest`: sha256 of the\n * document's own BODY — every byte after the frontmatter block (below the\n * closing `---` line and its newline; `rawBody` is the one definition of that\n * cut) — first 16 hex characters, the sources recipe's length.\n *\n * Byte-exact, no normalization. Body-only is load-bearing: vouch itself\n * rewrites the frontmatter as it stamps, and a later frontmatter-only edit\n * (another vouch, a corrected owner) must not read as the document moving.\n */\nexport function contentDigest(source: string): string {\n return createHash(\"sha256\").update(rawBody(source), \"utf8\").digest(\"hex\").slice(0, DIGEST_LENGTH);\n}\n\ninterface SourceFile {\n /** Repo-relative, `/`-separated — the spelling that goes into the hash. */\n rel: string;\n abs: string;\n}\n\n/**\n * The files a `sources` list names: a file is itself, a directory is everything\n * beneath it. Nothing else — glob patterns used to be matched here, by a\n * hand-rolled dialect that silently differed from the gitignore/minimatch\n * conventions authors assume, so a pattern quietly digested a DIFFERENT file\n * set than its author intended. Pattern-looking entries are now refused loudly\n * upstream (see patternSources); this function only ever sees literal paths.\n *\n * Three exclusions, all part of the digest recipe's contract:\n *\n * - dot-entries are skipped while walking — `.git` is not what the doc was\n * written from — though a path naming one outright is still honoured;\n * - `node_modules` is skipped the same way, unconditionally: it is the one\n * build input every ecosystem agrees is not source, and it is the one that\n * makes the walk take minutes;\n * - anything the repository's own `.gitignore` covers is dropped, when the\n * repo is a git checkout and git is on the PATH (see gitIgnoredPaths).\n *\n * The third is the one worth stating a reason for. `sources_digest` answers\n * \"did the code move since a person read it\", and BUILD OUTPUT moves on every\n * CI run without anybody touching the code — a `sources: [src/]` over a repo\n * that compiles into `src/generated/` went stale on a schedule, so the warning\n * that means \"re-read this\" arrived when nothing had been written. A signal\n * that fires every night is a signal people learn to close. Git's answer is\n * used rather than a list of our own because it is the answer the repository\n * already gives every other tool, and it is the author's to change.\n *\n * The fallback is deliberate: no git, no checkout, a git that errors — hash\n * everything. Missing an exclusion costs noise; inventing one costs a file the\n * stamp silently stops watching, and this walk exists to have nothing in that\n * category.\n */\nasync function collectSources(\n repoDir: string,\n sources: string[],\n): Promise<{ found: SourceFile[]; skipped: SkippedSource[] }> {\n const found = new Map<string, string>();\n const skipped = new Map<string, string>();\n const relOf = (abs: string): string => relative(repoDir, abs).split(sep).join(\"/\");\n\n // realpath once, up front: every containment question below is asked against\n // the resolved root, so a repo reached through a symlink (a worktree under\n // /var -> /private/var on macOS, say) does not make its own files look external.\n const repoReal = await realpath(repoDir).catch(() => resolve(repoDir));\n // The realpaths of the directories currently being walked — the cycle guard.\n // A STACK rather than a set of everything ever entered, because the two rules\n // answer different questions: a directory reachable by two spellings (a\n // `current -> versions/3` link beside the real tree) is content under both\n // names and belongs in the digest twice, while a directory reachable from\n // INSIDE itself is a loop. A global visited-set conflates them, and then which\n // spelling survives depends on the order readdir happened to return — a\n // digest that differs between two machines holding identical bytes.\n const walking: string[] = [];\n\n const walk = async (dir: string): Promise<void> => {\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n // Sorted, so a tree walks the same way on every filesystem.\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n for (const entry of entries) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const child = join(dir, entry.name);\n if (entry.isDirectory()) await enterDir(child);\n else if (entry.isFile()) found.set(relOf(child), child);\n // readdir reports symlinks by lstat, so isDirectory() and isFile() are\n // BOTH false for one: before this branch existed a symlinked file, and a\n // whole subtree behind a symlinked directory, fell between the two arms\n // and left the digest without a word said. That is the failure this\n // module is here to prevent, arriving through its own walk.\n else if (entry.isSymbolicLink()) await follow(child);\n }\n };\n\n const enterDir = async (dir: string): Promise<void> => {\n const real = await realpath(dir).catch(() => null);\n if (real === null || walking.includes(real)) return;\n walking.push(real);\n try {\n await walk(dir);\n } finally {\n walking.pop();\n }\n };\n\n const follow = async (link: string): Promise<void> => {\n const real = await realpath(link).catch(() => null);\n if (real === null) {\n skipped.set(relOf(link), \"a symlink that does not resolve\");\n return;\n }\n // Outside the repo the file is not this service's to vouch for, and the\n // same rule already refuses it as a top-level `sources` entry\n // (sources.path-outside). Reported rather than dropped: an author who\n // vendored a sibling repo through a symlink needs to know the stamp stops\n // at the link.\n if (!isPathInside(repoReal, real)) {\n skipped.set(relOf(link), \"a symlink whose target is outside this repository\");\n return;\n }\n const info = await stat(link).catch(() => null);\n if (info === null) {\n skipped.set(relOf(link), \"a symlink that does not resolve\");\n return;\n }\n // A link's own spelling is what the doc's author wrote, so that is the path\n // that goes into the digest — the content comes from the target either way.\n if (info.isFile()) found.set(relOf(link), link);\n // A link that closes a loop is not reported: everything behind it is already\n // in the digest under the spelling it was reached by, so nothing has stopped\n // being watched. Only unhashed CONTENT is worth a warning.\n else if (info.isDirectory()) await enterDir(link);\n else skipped.set(relOf(link), \"a symlink to neither a file nor a directory\");\n };\n\n for (const source of sources) {\n const cleaned = source.trim();\n if (cleaned.length === 0) continue;\n const root = resolveInside(repoDir, cleaned, `source '${source}'`);\n const info = await stat(root).catch(() => null);\n if (info === null) continue;\n if (info.isFile()) found.set(relOf(root), root);\n else if (info.isDirectory()) await enterDir(root);\n }\n\n // One git invocation for the whole expansion, not one per file: the skipped\n // list rides along so an ignored symlink does not warn about a path the\n // repository already says is not its own.\n const ignored = await gitIgnoredPaths(repoDir, [...found.keys(), ...skipped.keys()]);\n for (const rel of ignored) {\n found.delete(rel);\n skipped.delete(rel);\n }\n\n return {\n // Plain codepoint order, not locale order: the digest has to be the same\n // everywhere it is computed.\n found: [...found.entries()]\n .map(([rel, abs]) => ({ rel, abs }))\n .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0)),\n skipped: [...skipped.entries()]\n .map(([path, reason]) => ({ path, reason }))\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)),\n };\n}\n\n/** How long the digest waits on git before deciding it learned nothing. */\nconst GIT_TIMEOUT_MS = 10_000;\n\n/**\n * Which of these repo-relative paths the repository ignores, asked once for the\n * whole list. `git check-ignore` is the authority on purpose — it reads\n * `.gitignore` at every level, `.git/info/exclude` and the user's global\n * excludes, and it already knows that a TRACKED file is not ignored no matter\n * what a pattern says, which is the distinction a re-implementation always gets\n * wrong.\n *\n * Every failure answers \"nothing is ignored\": exit 1 is git saying so, exit 128\n * is \"not a git repository\", a spawn error is git not being installed, and a\n * timeout is a repository too strange to wait for. None of them justify\n * dropping a file from a digest a person is going to sign.\n */\nasync function gitIgnoredPaths(repoDir: string, rels: string[]): Promise<Set<string>> {\n if (rels.length === 0) return new Set();\n return new Promise<Set<string>>((done) => {\n const child = spawn(\"git\", [\"check-ignore\", \"--stdin\", \"-z\"], {\n cwd: repoDir,\n stdio: [\"pipe\", \"pipe\", \"ignore\"],\n timeout: GIT_TIMEOUT_MS,\n });\n let out = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n out += chunk;\n });\n child.on(\"error\", () => done(new Set()));\n child.on(\"close\", (code) => {\n // 0: some paths are ignored and are on stdout. 1: none are — an empty\n // answer, not a failure. Anything else: we learned nothing.\n done(code === 0 || code === 1 ? new Set(out.split(\"\\0\").filter((s) => s.length > 0)) : new Set());\n });\n // A git that died before reading its input hands us EPIPE; the close\n // handler above is what decides the outcome either way.\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(rels.join(\"\\0\") + \"\\0\");\n });\n}\n\n/* ------------------------------------------------------------------ */\n/* The per-file index: what `sources.stale` names */\n/* ------------------------------------------------------------------ */\n\n/**\n * How many files `sources_files` will list one by one before it gives up and\n * records only how many there were.\n *\n * A readability budget, not a correctness one: the index lives in the header of\n * a document a person reads, and a `sources: [src/]` over a legacy service can\n * expand to thousands of files. Past the limit `sources.stale` falls back to\n * repeating the `sources` entries — worse advice, but a spec.md whose\n * frontmatter is longer than its requirements is worse still.\n */\nconst SOURCE_INDEX_LIMIT = 100;\n\n/**\n * The `sources_files` value `loam vouch` stamps beside `sources_digest`: one\n * `<sha> <path>` line per file (sha256sum's layout, and its column order, so\n * the path may contain spaces), or just the file count once the list would run\n * past SOURCE_INDEX_LIMIT.\n *\n * Its whole purpose is the next `sources.stale`. `sources_digest` can say THAT\n * the code moved and never which part of it; with the index a reader gets the\n * added, removed and changed paths, which is the difference between re-reading\n * one file and re-reading a directory. It is also a readable git diff in the\n * docs repo: the vouch commit shows exactly which source files the stamp now\n * stands over.\n */\nexport function encodeSourceIndex(index: SourceIndexEntry[]): string {\n if (index.length > SOURCE_INDEX_LIMIT) return String(index.length);\n return index.map((e) => `${e.sha} ${e.path}`).join(\"\\n\");\n}\n\n/** What a stamped `sources_files` says: the per-file shas, the count, or nothing. */\ninterface StampedIndex {\n /** path -> sha, or null when the stamp did not record them. */\n entries: Map<string, string> | null;\n /** How many files the stamp covered, when that is knowable. */\n count?: number;\n}\n\n/**\n * Read back what `encodeSourceIndex` wrote. Anything unrecognised reads as \"the\n * stamp said nothing\" rather than as an empty index: a header nobody can parse\n * must not turn into a `sources.stale` claiming every file was deleted.\n */\nfunction decodeSourceIndex(stamped: string | undefined): StampedIndex {\n if (stamped === undefined) return { entries: null };\n const text = stamped.trim();\n if (text.length === 0) return { entries: null };\n if (/^\\d+$/.test(text)) return { entries: null, count: Number(text) };\n\n const entries = new Map<string, string>();\n for (const line of text.split(\"\\n\")) {\n const match = /^([0-9a-f]{16})\\s+(.+)$/.exec(line.trim());\n if (match === null) return { entries: null };\n entries.set(match[2]!, match[1]!);\n }\n return { entries, count: entries.size };\n}\n\n/** The paths that moved between a stamp and now, with a phrase for the message. */\ninterface MovedSources {\n /** Annotated paths, or undefined when the stamp did not record enough to say. */\n paths?: string[];\n /** Appended to the `sources.stale` message; empty when there is nothing to add. */\n summary: string;\n}\n\n/**\n * added / removed / changed, from the stamped index against the current one.\n * The annotation travels IN the detail line rather than in three separate\n * lists: a reader scanning a stale report wants the paths in one column, and\n * \"which of the three\" is one word wide.\n */\nfunction movedSources(stamp: StampedIndex, now: SourceIndexEntry[]): MovedSources {\n if (stamp.entries === null) {\n // No index, but the count alone still beats silence: \"12 files then, 14\n // now\" tells a reader to go looking for two new files.\n return {\n summary: stamp.count === undefined ? \"\" : ` (${stamp.count} file(s) then, ${now.length} now)`,\n };\n }\n const paths: string[] = [];\n const current = new Map(now.map((e) => [e.path, e.sha]));\n for (const [path, sha] of current) {\n const before = stamp.entries.get(path);\n if (before === undefined) paths.push(`added ${path}`);\n else if (before !== sha) paths.push(`changed ${path}`);\n }\n for (const path of stamp.entries.keys()) if (!current.has(path)) paths.push(`removed ${path}`);\n paths.sort();\n // An index that agrees with the current tree while the digest does not is a\n // contradiction (a truncation collision, or a hand-edited header). Say\n // nothing rather than print an empty list under a staleness warning.\n if (paths.length === 0) return { summary: \"\" };\n return { paths, summary: ` (${paths.length} path(s) moved)` };\n}\n\n/** The characters that made an entry a pattern under the glob dialect loam no longer ships. */\nconst PATTERN_CHARS = /[*?[]/;\n\n/**\n * The `sources` entries that look like glob patterns — anything containing\n * `*`, `?` or `[`. Patterns are refused loudly everywhere sources are consumed\n * (`loam vouch` refuses the run, `loam validate` grades an error), never\n * resolved: the glob dialect loam used to ship silently differed from the\n * gitignore/minimatch conventions authors assume — bracket classes literal,\n * its own `**` handling — so a pattern quietly digested a different file set\n * than intended, corrupting the staleness signal in both directions. A\n * directory already means \"everything beneath it\", so the fix is to name one.\n *\n * The cost accepted with the rule: a real file with `[` in its name (a Next.js\n * route, say) cannot be listed on its own — its parent directory covers it.\n */\nexport function patternSources(sources: string[]): string[] {\n return sources.filter((s) => PATTERN_CHARS.test(s.trim()));\n}\n\n/** The `sources` entries that resolve to nothing in this repo. */\nexport function missingSources(repoDir: string, sources: string[]): string[] {\n return sources.filter((s) => !sourceExists(repoDir, s));\n}\n\n/** Entries that are absolute, traverse upward, or escape through a symlink. */\nexport function unsafeSources(repoDir: string, sources: string[]): string[] {\n return sources.filter((source) => {\n const cleaned = source.trim();\n if (cleaned.length === 0) return false;\n try {\n resolveInside(repoDir, cleaned, `source '${source}'`);\n return false;\n } catch {\n return true;\n }\n });\n}\n\n/** Does a `sources` entry point at something real? Literal paths only, checked exactly. */\nfunction sourceExists(repoDir: string, source: string): boolean {\n const cleaned = source.trim();\n if (cleaned.length === 0) return false;\n try {\n return existsSync(resolveInside(repoDir, cleaned, `source '${source}'`));\n } catch {\n return false;\n }\n}\n"]}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The shapes an unknown parsed document is asked about, in one place.
3
+ *
4
+ * Every YAML and JSON file loam reads arrives as `unknown`, and every reader
5
+ * has to answer the same first question before it can look at a key: is this an
6
+ * object at all? Six modules each carried their own copy of the answer, two of
7
+ * them spelled with a cast — and a cast is exactly what this test exists to
8
+ * make unnecessary, since the predicate form hands the caller a narrowed type
9
+ * that tsc keeps checking. A leaf with no imports, so any layer can ask.
10
+ */
11
+ /** An object with string keys — not null, and not an array. */
12
+ export function isRecord(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ /** The same question where the answer is used rather than branched on. */
16
+ export function asRecord(value) {
17
+ return isRecord(value) ? value : null;
18
+ }
19
+ /**
20
+ * A map whose keys come from a document somebody else wrote.
21
+ *
22
+ * `Object.create(null)` rather than `{}` because a key read out of untrusted
23
+ * YAML can be `__proto__` or `constructor`, and on a normal object those either
24
+ * mutate the prototype or read back a function that was never in the file.
25
+ */
26
+ export function dictionary() {
27
+ return Object.create(null);
28
+ }
29
+ /** The value a record actually holds for `key`, never one it inherited. */
30
+ export function ownValue(record, key) {
31
+ return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
32
+ }
33
+ //# sourceMappingURL=records.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"records.js","sourceRoot":"","sources":["../../src/core/records.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,+DAA+D;AAC/D,MAAM,UAAU,QAAQ,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,QAAQ,CAAC,KAAc;IACrC,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAsB,CAAC;AAClD,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,QAAQ,CAAI,MAAyB,EAAE,GAAW;IAChE,OAAO,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACrF,CAAC","sourcesContent":["/**\n * The shapes an unknown parsed document is asked about, in one place.\n *\n * Every YAML and JSON file loam reads arrives as `unknown`, and every reader\n * has to answer the same first question before it can look at a key: is this an\n * object at all? Six modules each carried their own copy of the answer, two of\n * them spelled with a cast — and a cast is exactly what this test exists to\n * make unnecessary, since the predicate form hands the caller a narrowed type\n * that tsc keeps checking. A leaf with no imports, so any layer can ask.\n */\n\n/** An object with string keys — not null, and not an array. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The same question where the answer is used rather than branched on. */\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n return isRecord(value) ? value : null;\n}\n\n/**\n * A map whose keys come from a document somebody else wrote.\n *\n * `Object.create(null)` rather than `{}` because a key read out of untrusted\n * YAML can be `__proto__` or `constructor`, and on a normal object those either\n * mutate the prototype or read back a function that was never in the file.\n */\nexport function dictionary<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/** The value a record actually holds for `key`, never one it inherited. */\nexport function ownValue<T>(record: Record<string, T>, key: string): T | undefined {\n return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;\n}\n"]}
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Read model of the docs repo — the single place that knows its layout.
3
+ *
4
+ * Enumeration goes by the filesystem, and only by the filesystem: files are the
5
+ * source of truth, so `services/` IS the list of services and there is no
6
+ * manifest that can disagree with it. Every command that needs "which services
7
+ * exist", "which features are in flight" or "where does artifact X live" asks
8
+ * here, so the layout is spelled exactly once.
9
+ */
10
+ import { existsSync, statSync } from "node:fs";
11
+ import { readdir } from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ import { listField, readFrontmatter, stringField } from "./frontmatter.js";
14
+ import { serviceIdProblem } from "./ids.js";
15
+ /** Directory under features/ holding shipped features. Never a feature itself. */
16
+ const ARCHIVE_DIR = "archive";
17
+ /**
18
+ * Compare ids so digit runs sort numerically: FEAT-2 before FEAT-10.
19
+ * Deterministic and locale-independent — ordering is part of the output
20
+ * contract for `list`, and `--json` consumers diff it.
21
+ */
22
+ export function compareIds(a, b) {
23
+ const ta = tokenize(a);
24
+ const tb = tokenize(b);
25
+ for (let i = 0; i < Math.max(ta.length, tb.length); i += 1) {
26
+ const x = ta[i];
27
+ const y = tb[i];
28
+ if (x === undefined)
29
+ return -1;
30
+ if (y === undefined)
31
+ return 1;
32
+ if (typeof x === "number" && typeof y === "number") {
33
+ if (x !== y)
34
+ return x - y;
35
+ }
36
+ else if (String(x) !== String(y)) {
37
+ return String(x) < String(y) ? -1 : 1;
38
+ }
39
+ }
40
+ return 0;
41
+ }
42
+ function tokenize(s) {
43
+ return (s.match(/\d+|\D+/g) ?? []).map((t) => (/^\d/.test(t) ? Number(t) : t));
44
+ }
45
+ /**
46
+ * Known ids within a small edit distance of `id`, closest first, at most three.
47
+ *
48
+ * The did-you-mean hint for a name somebody typed: `loam new --touches` and
49
+ * `loam delta <svc>` answer the same mistake, and each carried its own copy of
50
+ * these twenty-four lines. It belongs here because the ids being scored are
51
+ * this module's ids — service directory names, feature ids — and because
52
+ * `compareIds` right above is the tiebreak that keeps the list deterministic
53
+ * when two candidates score equally. Not in `core/ids.ts`: `compareIds` lives
54
+ * here and repo.ts imports ids.js, so putting it there would close a cycle.
55
+ *
56
+ * `arch.ts`'s `closeIds` looks similar and is not: substring and prefix, capped
57
+ * at five, answering "which element could this be" rather than "did you
58
+ * misspell a directory". Two rules, two homes.
59
+ */
60
+ export function nearestIds(id, known) {
61
+ const budget = Math.max(1, Math.floor(id.length / 4));
62
+ return known
63
+ .map((candidate) => ({ candidate, distance: editDistance(id.toLowerCase(), candidate.toLowerCase()) }))
64
+ .filter((scored) => scored.distance <= budget)
65
+ .sort((a, b) => a.distance - b.distance || compareIds(a.candidate, b.candidate))
66
+ .slice(0, 3)
67
+ .map((scored) => scored.candidate);
68
+ }
69
+ /** Plain Levenshtein — ids are short, and the row-at-a-time form keeps it obvious. */
70
+ function editDistance(a, b) {
71
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
72
+ for (let i = 1; i <= a.length; i += 1) {
73
+ const current = [i];
74
+ for (let j = 1; j <= b.length; j += 1) {
75
+ const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
76
+ current.push(Math.min(previous[j] + 1, current[j - 1] + 1, substitution));
77
+ }
78
+ previous = current;
79
+ }
80
+ return previous[b.length];
81
+ }
82
+ /**
83
+ * Feature id from a directory name: everything up to and including the first
84
+ * number run (`FEAT-101-payment-splitting` -> `FEAT-101`). A name with no
85
+ * `<word>-<number>` head is its own id. Quirk: a dated slug keeps only its first
86
+ * segment (`release-2024-01-x` -> `release-2024`) — ids are not meant to be dates.
87
+ */
88
+ export function featureIdFromDirName(dirName) {
89
+ const m = /^(.*?-\d+)(?:-|$)/.exec(dirName);
90
+ return m ? m[1] : dirName;
91
+ }
92
+ export function servicePaths(docsDir, service) {
93
+ const dir = join(docsDir, "services", service);
94
+ return {
95
+ dir,
96
+ model: join(dir, "model.likec4"),
97
+ spec: join(dir, "spec.md"),
98
+ archSpec: join(dir, "arch.spec.md"),
99
+ openapi: join(dir, "openapi.yaml"),
100
+ runbook: join(dir, "runbook.md"),
101
+ health: join(dir, "health.yaml"),
102
+ adrsDir: join(dir, "adrs"),
103
+ };
104
+ }
105
+ /**
106
+ * The pair of requirement-carrying spec files, living and delta alike: the
107
+ * business spec and the architecture spec. Same grammar, same delta algebra,
108
+ * same merge — everything that walks "the spec files" of a service walks this
109
+ * list, so the two axes cannot drift apart in what handles them. `key` indexes
110
+ * ServicePaths/FeatureSpecPaths; `label` is how the axis names itself in prose.
111
+ */
112
+ export const SPEC_AXES = [
113
+ { key: "spec", file: "spec.md", label: "requirements" },
114
+ { key: "archSpec", file: "arch.spec.md", label: "arch requirements" },
115
+ ];
116
+ export function featurePaths(featureDir) {
117
+ return {
118
+ dir: featureDir,
119
+ intent: join(featureDir, "intent.md"),
120
+ delta: join(featureDir, "delta.likec4"),
121
+ specsDir: join(featureDir, "specs"),
122
+ adrsDir: join(featureDir, "adrs"),
123
+ };
124
+ }
125
+ export function featureSpecPaths(featureDir, service) {
126
+ const dir = join(featureDir, "specs", service);
127
+ return {
128
+ dir,
129
+ spec: join(dir, "spec.md"),
130
+ archSpec: join(dir, "arch.spec.md"),
131
+ openapi: join(dir, "openapi.yaml"),
132
+ };
133
+ }
134
+ export function landscapePath(docsDir) {
135
+ return join(docsDir, "architecture", "landscape.likec4");
136
+ }
137
+ export function featuresDir(docsDir) {
138
+ return join(docsDir, "features");
139
+ }
140
+ /**
141
+ * The agent contract's filename, and where it sits in a docs repo.
142
+ *
143
+ * Both spellings are exported because the two questions are different: `init`,
144
+ * `doctor` and `validate` want a path under a docsDir they already hold, while
145
+ * `docs.ts` builds the scaffold as `[relative path, bytes]` pairs and needs the
146
+ * bare name. Four modules spelled the literal out for themselves, and one of
147
+ * them — `init` — uses it to decide whether a directory IS a docs repo at all,
148
+ * so a rename that reached three of the four would leave `init` recognising a
149
+ * file nothing else writes any more.
150
+ *
151
+ * `openspec-inventory.ts`'s "AGENTS.md" is deliberately NOT this constant: it
152
+ * names a file in a foreign OpenSpec tree that happens to share the name.
153
+ */
154
+ export const AGENTS_FILENAME = "AGENTS.md";
155
+ export function agentsPath(docsDir) {
156
+ return join(docsDir, AGENTS_FILENAME);
157
+ }
158
+ /**
159
+ * Where shipped features live. `features/archive/` is spelled here and nowhere
160
+ * else for the same reason every other artifact path is: `archive` and
161
+ * `unarchive` move directories in and out of it, and a layout string that two
162
+ * commands re-derive is a layout two commands can disagree about. The
163
+ * `features/archive/…` strings in refusal PROSE are not this path — they are
164
+ * what a reader types into `ls`, and they stay spelled out.
165
+ */
166
+ export function archiveDir(docsDir) {
167
+ return join(featuresDir(docsDir), ARCHIVE_DIR);
168
+ }
169
+ export function docsRepoState(docsDir) {
170
+ const path = docsDir;
171
+ let isDir = false;
172
+ try {
173
+ isDir = statSync(path).isDirectory();
174
+ }
175
+ catch {
176
+ isDir = false;
177
+ }
178
+ if (!isDir)
179
+ return { kind: "missing", path };
180
+ return { kind: existsSync(join(path, "services")) ? "ok" : "no-services", path };
181
+ }
182
+ /**
183
+ * The docs repo is not there. Thrown rather than returned because every caller
184
+ * of the enumeration wants the same thing — to stop — and a `[]` return is the
185
+ * bug this closes. `message` is written for a human at a terminal: the CLI's
186
+ * top-level handler prints it verbatim, and commands that catch it report
187
+ * `repository-unavailable`.
188
+ */
189
+ export class DocsRepoUnavailableError extends Error {
190
+ state;
191
+ constructor(state, message) {
192
+ super(message);
193
+ this.state = state;
194
+ this.name = "DocsRepoUnavailableError";
195
+ }
196
+ }
197
+ /**
198
+ * Refuse to enumerate a docs repo that is not one. `allow` names the states the
199
+ * caller can honestly survive: features/ may be absent from a real docs repo
200
+ * (nothing is in flight yet), so feature enumeration only insists the docs repo
201
+ * EXISTS, while service enumeration insists it is shaped like a docs repo — a
202
+ * `services/` directory is what makes it one.
203
+ */
204
+ function requireDocsRepo(docsDir, allow) {
205
+ const state = docsRepoState(docsDir);
206
+ if (allow.includes(state.kind))
207
+ return;
208
+ if (state.kind === "missing") {
209
+ throw new DocsRepoUnavailableError(state, `The configured docs repo does not exist: ${state.path}. ` +
210
+ "Fix `docsDir` in loam.json, clone the docs repo there, " +
211
+ "or run `loam init --docs <dir> --create` to make a new one.");
212
+ }
213
+ throw new DocsRepoUnavailableError(state, `${state.path} is not a docs repo — it has no services/ directory. ` +
214
+ "Point `docsDir` in loam.json at the shared docs repo, " +
215
+ "or run `loam init --docs <dir> --create` to make one.");
216
+ }
217
+ /* ------------------------------------------------------------------ */
218
+ /* Enumeration */
219
+ /* ------------------------------------------------------------------ */
220
+ /**
221
+ * What a directory entry IS, following a symlink to find out.
222
+ *
223
+ * `readdir(withFileTypes)` does not follow symlinks: for a symlink `Dirent`
224
+ * every `isDirectory()`/`isFile()` is false, whatever it points at. That made a
225
+ * symlinked `services/<id>/` or `features/<id>/` vanish from every enumeration
226
+ * at once — `list`, `validate --all`, the fleet gate — with no diagnostic
227
+ * anywhere, which is the one outcome a shared docs repo cannot survive: the
228
+ * fleet gate reported a service that is not there as fine because it never saw
229
+ * it. Composing a docs repo out of symlinks (a worktree, a submodule, one
230
+ * service's directory shared between two checkouts) is legitimate, so they are
231
+ * FOLLOWED rather than refused. A dangling link stats as nothing and is skipped
232
+ * exactly as an absent directory is — it is not a service, and saying so would
233
+ * mean inventing an entry to hang the complaint on.
234
+ */
235
+ function entryIs(dir, e, want) {
236
+ if (!e.isSymbolicLink())
237
+ return want === "dir" ? e.isDirectory() : e.isFile();
238
+ try {
239
+ const s = statSync(join(dir, e.name));
240
+ return want === "dir" ? s.isDirectory() : s.isFile();
241
+ }
242
+ catch {
243
+ return false;
244
+ }
245
+ }
246
+ /**
247
+ * Sorted names of the real subdirectories of `dir` (dot-dirs and files skipped).
248
+ * A missing `dir` is an empty list — the swallow is deliberate but narrow: it
249
+ * only ever runs INSIDE a docs repo that `requireDocsRepo` has already
250
+ * confirmed, where an absent `features/` or `specs/` means "none yet" and
251
+ * nothing else.
252
+ */
253
+ async function subdirs(dir) {
254
+ if (!existsSync(dir))
255
+ return [];
256
+ const entries = await readdir(dir, { withFileTypes: true });
257
+ return entries
258
+ .filter((e) => !e.name.startsWith(".") && entryIs(dir, e, "dir"))
259
+ .map((e) => e.name)
260
+ .sort(compareIds);
261
+ }
262
+ /**
263
+ * Markdown files sitting directly in `dir` — the ADR count, and the only place
264
+ * that rule is spelled. Exported because `show` kept a second copy that tested
265
+ * `Dirent.isFile()` itself: always false for a symlink, whatever it points at,
266
+ * so a docs repo composed of symlinks (the layout `entryIs` above exists to
267
+ * support) had `loam list` and `loam show` reporting different ADR counts for
268
+ * the same service. One rule, one answer.
269
+ */
270
+ export async function countMarkdown(dir) {
271
+ if (!existsSync(dir))
272
+ return 0;
273
+ const entries = await readdir(dir, { withFileTypes: true });
274
+ return entries.filter((e) => e.name.endsWith(".md") && entryIs(dir, e, "file")).length;
275
+ }
276
+ /** Services a feature carries a delta for, ordered — the subdirs of its specs/. */
277
+ export async function featureSpecServices(featureDir, context) {
278
+ if (context !== undefined)
279
+ return context.featureSpecServices(featureDir);
280
+ return subdirs(featurePaths(featureDir).specsDir);
281
+ }
282
+ /** Every service in the docs repo, ordered by id. */
283
+ export async function listServices(docsDir, context) {
284
+ if (context !== undefined)
285
+ return context.listServices(docsDir);
286
+ requireDocsRepo(docsDir, ["ok"]);
287
+ const names = await subdirs(join(docsDir, "services"));
288
+ return Promise.all(names.map(async (id) => {
289
+ const p = servicePaths(docsDir, id);
290
+ const fm = await readFrontmatter(p.spec);
291
+ const idProblem = serviceIdProblem(id, "directory name");
292
+ return {
293
+ id,
294
+ dir: p.dir,
295
+ ...(idProblem === null ? {} : { idProblem }),
296
+ has: {
297
+ model: existsSync(p.model),
298
+ spec: existsSync(p.spec),
299
+ openapi: existsSync(p.openapi),
300
+ runbook: existsSync(p.runbook),
301
+ health: existsSync(p.health),
302
+ },
303
+ adrs: await countMarkdown(p.adrsDir),
304
+ status: stringField(fm, "status") ?? null,
305
+ sources: {
306
+ declared: listField(fm, "sources").length > 0,
307
+ stamped: stringField(fm, "sources_digest") !== undefined,
308
+ },
309
+ };
310
+ }));
311
+ }
312
+ /**
313
+ * The directories under `services/` that no loam command can address.
314
+ *
315
+ * A finding rather than a silent skip, and an ERROR rather than a warning,
316
+ * because the state is not survivable in either direction: `loam adopt`,
317
+ * `loam delta`, `loam rebase` and `loam new --touches` all refuse the id with
318
+ * `invalid-option`, so the documents in there can never be updated by loam
319
+ * again, while `validate --all` used to grade the directory as an ordinary
320
+ * service and demand `model.likec4`, a spec and a landscape binding for it. The
321
+ * fix is a rename, and it is a rename loam cannot do for you — the id is
322
+ * spelled in the landscape binding, in the frontmatter and in every feature
323
+ * that touched the service — so the message names all three.
324
+ *
325
+ * Emitted from the fleet target (`validate --all`), where the SET of service
326
+ * directories is the thing being checked; a per-service run is already refused
327
+ * by its own `--service` guard before it gets here.
328
+ */
329
+ export function serviceIdFindings(services) {
330
+ return services
331
+ .filter((s) => s.idProblem !== undefined)
332
+ .map((s) => ({
333
+ severity: "error",
334
+ code: "service.id-invalid",
335
+ subject: s.id,
336
+ message: `services/${s.id}/ — ${s.idProblem} ` +
337
+ `Every authoring command refuses this id (\`loam adopt\`, \`loam delta\`, \`loam new --touches\`), so nothing in that directory can be changed through loam. ` +
338
+ `Rename the directory to a legal id, then update its \`service:\` frontmatter, its \`metadata { service '${s.id}' }\` binding in architecture/landscape.likec4, and any features/<FEAT>/specs/${s.id}/ that names it.`,
339
+ }));
340
+ }
341
+ async function readFeature(dir, dirName, archived) {
342
+ const p = featurePaths(dir);
343
+ return {
344
+ id: featureIdFromDirName(dirName),
345
+ dirName,
346
+ dir,
347
+ archived,
348
+ services: await subdirs(p.specsDir),
349
+ has: { intent: existsSync(p.intent), delta: existsSync(p.delta) },
350
+ };
351
+ }
352
+ /**
353
+ * Features in the docs repo, ordered by id (active and archived interleaved when
354
+ * both are asked for). `features/archive/` is the archive, never a feature.
355
+ */
356
+ export async function listFeatures(docsDir, opts = {}, context) {
357
+ if (context !== undefined)
358
+ return context.listFeatures(docsDir, opts);
359
+ // "no-services" is tolerated here on purpose: a docs repo whose services/ is
360
+ // gone is broken, but it is `listServices` (and `loam doctor`) that says so.
361
+ // Refusing here too would turn one diagnosis into two contradictory ones.
362
+ requireDocsRepo(docsDir, ["ok", "no-services"]);
363
+ const root = featuresDir(docsDir);
364
+ const active = (await subdirs(root)).filter((n) => n !== ARCHIVE_DIR);
365
+ const out = await Promise.all(active.map((n) => readFeature(join(root, n), n, false)));
366
+ if (opts.includeArchived) {
367
+ const archiveRoot = join(root, ARCHIVE_DIR);
368
+ const archived = await subdirs(archiveRoot);
369
+ out.push(...(await Promise.all(archived.map((n) => readFeature(join(archiveRoot, n), n, true)))));
370
+ }
371
+ return out.sort((a, b) => compareIds(a.id, b.id) || compareIds(a.dirName, b.dirName));
372
+ }
373
+ /**
374
+ * Resolve a feature argument — a canonical id (`FEAT-5`) or an exact directory
375
+ * name (`FEAT-5-slug`) — to its entry. The entry's `id` is the canonical
376
+ * spelling, and it is the only name a caller may use from here on: tag filters,
377
+ * coherence, and the cross-feature self-exclusion scans all compare against
378
+ * `feature.id`, never against the raw argument.
379
+ *
380
+ * Matching is EXACT, on one of two spellings: the directory name as it is on
381
+ * disk, or the canonical id derived from it. It used to also match any dirName
382
+ * starting with `arg + "-"`, which made the argument a prefix query in
383
+ * disguise: with FEAT-401 and FEAT-402 in flight, `loam archive FEAT` archived
384
+ * whichever sorted first, and `loam delta billing` reached into
385
+ * `billing-7-rewrite`. A destructive command must never pick a target the
386
+ * caller did not name, so a prefix now resolves to nothing at all.
387
+ *
388
+ * An exact directory name still wins over the id spelling (`FEAT-5` the
389
+ * directory over `FEAT-5-slug`, whose id is also `FEAT-5`), and under "include"
390
+ * an active feature wins over an archived one. Ties among equally-exact
391
+ * candidates go to the first by name — deterministic, unlike the raw readdir
392
+ * order this replaces; `ambiguousFeatureMessage` lists them for the caller.
393
+ */
394
+ export async function resolveFeature(docsDir, arg, archived, context) {
395
+ return (await featureCandidates(docsDir, arg, archived, context))[0] ?? null;
396
+ }
397
+ /**
398
+ * Every feature the argument names exactly, best first. Split out of
399
+ * `resolveFeature` so a caller that wants to REFUSE an ambiguous argument can
400
+ * see the tie instead of inheriting the winner.
401
+ */
402
+ export async function featureCandidates(docsDir, arg, archived, context) {
403
+ const all = await listFeatures(docsDir, { includeArchived: archived !== "exclude" }, context);
404
+ return all
405
+ .filter((f) => archived === "include" || f.archived === (archived === "only"))
406
+ .filter((f) => f.dirName === arg || f.id === arg)
407
+ .sort((a, b) => Number(b.dirName === arg) - Number(a.dirName === arg) ||
408
+ Number(a.archived) - Number(b.archived) ||
409
+ compareIds(a.dirName, b.dirName));
410
+ }
411
+ /**
412
+ * The message for an argument that names more than one feature — two directories
413
+ * carrying the same id (`FEAT-6-aaa` and `FEAT-6-zzz`). `resolveFeature` still
414
+ * picks one deterministically, but a command that is about to WRITE should say
415
+ * which directories collided and make the caller spell one out.
416
+ */
417
+ export function ambiguousFeatureMessage(arg, candidates) {
418
+ return (`'${arg}' names ${candidates.length} features: ${candidates.map((c) => c.dirName).join(", ")}. ` +
419
+ "Pass the directory name you mean.");
420
+ }
421
+ /**
422
+ * The message for an exclude-mode miss. When the feature exists under
423
+ * `features/archive/`, "no feature" is a lie the caller would have to debug —
424
+ * the honest answer is "already archived", plus how to look at it. The `--json`
425
+ * code stays `unknown-target` either way: the target is unknown to the command
426
+ * that asked, and the prose carries the diagnosis.
427
+ */
428
+ export async function missingFeatureMessage(docsDir, arg, context) {
429
+ const shipped = await resolveFeature(docsDir, arg, "only", context);
430
+ if (shipped !== null) {
431
+ return (`Feature '${shipped.id}' is already archived (features/archive/${shipped.dirName}) — ` +
432
+ `\`loam show ${shipped.id}\` reads it, \`loam unarchive ${shipped.id}\` re-opens it.`);
433
+ }
434
+ return `No feature '${arg}' under ${featuresDir(docsDir)}.`;
435
+ }
436
+ //# sourceMappingURL=repo.js.map