@ybotok/loam 0.1.0-beta.1 → 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 (115) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +6 -1
  3. package/dist/cli.js +4 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/adopt.js +17 -3
  6. package/dist/commands/adopt.js.map +1 -1
  7. package/dist/commands/archive.js +24 -8
  8. package/dist/commands/archive.js.map +1 -1
  9. package/dist/commands/delta.js +74 -47
  10. package/dist/commands/delta.js.map +1 -1
  11. package/dist/commands/dependencies.js +7 -2
  12. package/dist/commands/dependencies.js.map +1 -1
  13. package/dist/commands/docs-repo-gate.js +104 -0
  14. package/dist/commands/docs-repo-gate.js.map +1 -0
  15. package/dist/commands/explore.js +195 -0
  16. package/dist/commands/explore.js.map +1 -0
  17. package/dist/commands/format.js +17 -0
  18. package/dist/commands/format.js.map +1 -0
  19. package/dist/commands/gherkin.js +87 -48
  20. package/dist/commands/gherkin.js.map +1 -1
  21. package/dist/commands/init.js +3 -3
  22. package/dist/commands/init.js.map +1 -1
  23. package/dist/commands/instructions.js +70 -0
  24. package/dist/commands/instructions.js.map +1 -0
  25. package/dist/commands/list.js +6 -76
  26. package/dist/commands/list.js.map +1 -1
  27. package/dist/commands/migrate-openspec.js +45 -28
  28. package/dist/commands/migrate-openspec.js.map +1 -1
  29. package/dist/commands/new.js +35 -34
  30. package/dist/commands/new.js.map +1 -1
  31. package/dist/commands/rebase.js +2 -4
  32. package/dist/commands/rebase.js.map +1 -1
  33. package/dist/commands/show.js +26 -31
  34. package/dist/commands/show.js.map +1 -1
  35. package/dist/commands/status.js +8 -24
  36. package/dist/commands/status.js.map +1 -1
  37. package/dist/commands/unarchive.js +12 -5
  38. package/dist/commands/unarchive.js.map +1 -1
  39. package/dist/commands/validate.js +115 -133
  40. package/dist/commands/validate.js.map +1 -1
  41. package/dist/commands/verify.js +33 -17
  42. package/dist/commands/verify.js.map +1 -1
  43. package/dist/commands/vouch.js +77 -59
  44. package/dist/commands/vouch.js.map +1 -1
  45. package/dist/core/agent.js +273 -31
  46. package/dist/core/agent.js.map +1 -1
  47. package/dist/core/arch.js +28 -2
  48. package/dist/core/arch.js.map +1 -1
  49. package/dist/core/brief.js +3 -3
  50. package/dist/core/brief.js.map +1 -1
  51. package/dist/core/coherence.js +37 -13
  52. package/dist/core/coherence.js.map +1 -1
  53. package/dist/core/concurrency.js +51 -0
  54. package/dist/core/concurrency.js.map +1 -0
  55. package/dist/core/config.js +10 -2
  56. package/dist/core/config.js.map +1 -1
  57. package/dist/core/delta.js +21 -2
  58. package/dist/core/delta.js.map +1 -1
  59. package/dist/core/dependencies.js +46 -42
  60. package/dist/core/dependencies.js.map +1 -1
  61. package/dist/core/docs.js +2 -1
  62. package/dist/core/docs.js.map +1 -1
  63. package/dist/core/doctor.js +41 -26
  64. package/dist/core/doctor.js.map +1 -1
  65. package/dist/core/document-bytes.js +59 -0
  66. package/dist/core/document-bytes.js.map +1 -0
  67. package/dist/core/explore.js +225 -0
  68. package/dist/core/explore.js.map +1 -0
  69. package/dist/core/fleet-context.js +16 -63
  70. package/dist/core/fleet-context.js.map +1 -1
  71. package/dist/core/frontmatter.js +1 -5
  72. package/dist/core/frontmatter.js.map +1 -1
  73. package/dist/core/gherkin.js +3 -61
  74. package/dist/core/gherkin.js.map +1 -1
  75. package/dist/core/health.js +1 -5
  76. package/dist/core/health.js.map +1 -1
  77. package/dist/core/ids.js +34 -5
  78. package/dist/core/ids.js.map +1 -1
  79. package/dist/core/json.js +8 -1
  80. package/dist/core/json.js.map +1 -1
  81. package/dist/core/likec4.js +6 -1
  82. package/dist/core/likec4.js.map +1 -1
  83. package/dist/core/maturity.js +66 -0
  84. package/dist/core/maturity.js.map +1 -0
  85. package/dist/core/openapi-merge.js +39 -6
  86. package/dist/core/openapi-merge.js.map +1 -1
  87. package/dist/core/openapi.js +17 -5
  88. package/dist/core/openapi.js.map +1 -1
  89. package/dist/core/openspec-inventory.js +64 -27
  90. package/dist/core/openspec-inventory.js.map +1 -1
  91. package/dist/core/path-safety.js +59 -0
  92. package/dist/core/path-safety.js.map +1 -1
  93. package/dist/core/provenance.js +35 -10
  94. package/dist/core/provenance.js.map +1 -1
  95. package/dist/core/records.js +33 -0
  96. package/dist/core/records.js.map +1 -0
  97. package/dist/core/repo.js +75 -1
  98. package/dist/core/repo.js.map +1 -1
  99. package/dist/core/report.js +9 -0
  100. package/dist/core/report.js.map +1 -1
  101. package/dist/core/results.js +1 -3
  102. package/dist/core/results.js.map +1 -1
  103. package/dist/core/spec.js +3 -3
  104. package/dist/core/spec.js.map +1 -1
  105. package/dist/core/staging.js +124 -17
  106. package/dist/core/staging.js.map +1 -1
  107. package/dist/core/status.js +122 -33
  108. package/dist/core/status.js.map +1 -1
  109. package/dist/core/steps.js +72 -0
  110. package/dist/core/steps.js.map +1 -0
  111. package/dist/core/verify.js +18 -4
  112. package/dist/core/verify.js.map +1 -1
  113. package/dist/core/version.js +17 -1
  114. package/dist/core/version.js.map +1 -1
  115. package/package.json +1 -1
@@ -85,6 +85,65 @@ export function resolvePortableFileInside(root, candidate, label = "path") {
85
85
  }
86
86
  return resolveInside(root, candidate, label);
87
87
  }
88
+ /**
89
+ * The same portable spelling rules, with containment judged LEXICALLY — for a
90
+ * path that names a file the docs repo itself mounts.
91
+ *
92
+ * Every spelling defence above is kept, and for its reason: a snapshot manifest
93
+ * is loam's own file, but a corrupted or hostile one could carry `..` segments,
94
+ * an absolute path or a `C:\` spelling, and what comes out of this join is a
95
+ * path a caller then goes and reads.
96
+ *
97
+ * What is deliberately not applied is the realpath test. Composing a docs repo
98
+ * out of symlinks — a worktree, a submodule, one service's directory shared
99
+ * between two checkouts — is a supported layout that every walk of the repo
100
+ * FOLLOWS rather than refuses (repo.ts's `entryIs` says so in full), and that
101
+ * `archive` already writes through: its living-document writes are planned from
102
+ * `servicePaths()` and never see this file. With the realpath test in force on
103
+ * the manifest's `path` field, a `services/<svc>/` mounted that way made an
104
+ * interrupted archive permanently unrepairable — the retry was told the
105
+ * snapshot could not be read when it was perfectly intact, and the half-merge it
106
+ * was the only record of could never be repaired.
107
+ *
108
+ * This is only ever safe on a READ. A symlink that leaves the repo is
109
+ * lexically indistinguishable from a service directory the operator mounted on
110
+ * purpose — `escape/owned.txt` and `services/<svc>/spec.md` are both "inside
111
+ * docsDir" until something resolves them — so the realpath test is the only
112
+ * check that can refuse the first, at the price of also refusing the second.
113
+ * A caller that goes on to WRITE through the path must pay that price and use
114
+ * `resolvePortableFileInside`; `unarchive` does, and says so where it does.
115
+ * A caller that only reads a file and compares a digest it never discloses
116
+ * gains nothing from refusing, and loses the operator's ability to repair an
117
+ * interrupted archive.
118
+ */
119
+ export function resolvePortableFileInsideLexically(root, candidate, label = "path") {
120
+ if (candidate.length === 0) {
121
+ throw new UnsafePathError(candidate, `${label} must not be empty`);
122
+ }
123
+ if (candidate.includes("\\")) {
124
+ throw new UnsafePathError(candidate, `${label} must use forward slashes`);
125
+ }
126
+ const parts = candidate.split("/");
127
+ if (parts.some((part) => part === "" || part === "." || part === "..")) {
128
+ throw new UnsafePathError(candidate, `${label} must be a canonical relative file path`);
129
+ }
130
+ // win32.isAbsolute is intentional even on POSIX, for the reason `resolveInside`
131
+ // gives: a snapshot travels with its feature directory between operating
132
+ // systems, and `C:\...` must never turn into an innocuous relative filename
133
+ // merely because the question was asked on Linux.
134
+ if (isAbsolute(candidate) || win32.isAbsolute(candidate)) {
135
+ throw new UnsafePathError(candidate, `${label} must be relative to its owning directory`);
136
+ }
137
+ const rootAbs = resolve(root);
138
+ const target = resolve(rootAbs, ...parts);
139
+ // Already implied by the segment test above, and asked anyway: this line is
140
+ // the containment claim itself, so a later loosening of the spelling rules
141
+ // cannot quietly stop making it.
142
+ if (!isPathInside(rootAbs, target)) {
143
+ throw new UnsafePathError(candidate, `${label} resolves outside its owning directory`);
144
+ }
145
+ return target;
146
+ }
88
147
  /** Find the closest lexically contained path that exists, including symlinks. */
89
148
  function nearestExisting(target, root) {
90
149
  let current = target;
@@ -1 +1 @@
1
- {"version":3,"file":"path-safety.js","sourceRoot":"","sources":["../../src/core/path-safety.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAE7B,SAAS;IADpB,YACW,SAAiB,EAC1B,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;yBAHN,SAAS;QAIlB,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AAED,8DAA8D;AAC9D,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,MAAc;IACvD,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACrD,OAAO,GAAG,KAAK,EAAE,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,GAAG,KAAK,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,CAAC,CAAC;AACzF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,SAAiB,EAAE,KAAK,GAAG,MAAM;IAC3E,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,eAAe,CAAC,SAAS,EAAE,GAAG,KAAK,oBAAoB,CAAC,CAAC;IACrE,CAAC;IACD,4EAA4E;IAC5E,6EAA6E;IAC7E,yEAAyE;IACzE,IAAI,UAAU,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,E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;YACjD,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,SAAS;gBAAE,MAAM,GAAG,CAAC;QACzD,CAAC;QACD,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAClC,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;QAChC,IAAI,MAAM,KAAK,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC;YAAE,OAAO,IAAI,CAAC;QACnE,OAAO,GAAG,MAAM,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Resolve caller-controlled paths without letting them leave an owned tree.\n *\n * A lexical `relative()` check is not enough: an existing component may be a\n * symlink whose target lives elsewhere. Conversely, checking only the final\n * path misses destinations that do not exist yet but whose nearest existing\n * parent is a symlink. This helper checks both views before a caller reads,\n * writes, walks, or removes anything.\n */\nimport { lstatSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, relative, resolve, sep, win32 } from \"node:path\";\n\nexport class UnsafePathError extends Error {\n constructor(\n readonly candidate: string,\n message: string,\n ) {\n super(message);\n this.name = \"UnsafePathError\";\n }\n}\n\n/** True when `target` is `root` or one of its descendants. */\nexport function isPathInside(root: string, target: string): boolean {\n const rel = relative(resolve(root), resolve(target));\n return rel === \"\" || (!isAbsolute(rel) && rel !== \"..\" && !rel.startsWith(`..${sep}`));\n}\n\n/**\n * Resolve a relative path beneath `root`, rejecting absolute paths, explicit\n * parent traversal, and symlink escape. The final path may be absent: its\n * nearest existing ancestor is checked in that case.\n */\nexport function resolveInside(root: string, candidate: string, label = \"path\"): string {\n if (candidate.length === 0) {\n throw new UnsafePathError(candidate, `${label} must not be empty`);\n }\n // win32.isAbsolute is intentional even on POSIX. Persisted/configured paths\n // may be moved between operating systems, and `C:\\\\...` must never turn into\n // an innocuous relative filename merely because validation ran on Linux.\n if (isAbsolute(candidate) || win32.isAbsolute(candidate)) {\n throw new UnsafePathError(candidate, `${label} must be relative to its owning directory`);\n }\n if (candidate.split(/[\\\\/]/).includes(\"..\")) {\n throw new UnsafePathError(candidate, `${label} must not contain '..' path segments`);\n }\n\n const rootAbs = resolve(root);\n const target = resolve(rootAbs, candidate);\n if (!isPathInside(rootAbs, target)) {\n throw new UnsafePathError(candidate, `${label} resolves outside its owning directory`);\n }\n\n let rootReal: string;\n let existing: string;\n try {\n rootReal = realpathSync(rootAbs);\n existing = nearestExisting(target, rootAbs);\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n throw new UnsafePathError(candidate, `${label} cannot be resolved safely: ${detail}`);\n }\n\n let existingReal: string;\n try {\n existingReal = realpathSync(existing);\n } catch (err) {\n // A broken symlink is an existing path according to lstat, but realpath\n // cannot prove where a later write through it would land. Refuse it.\n const detail = err instanceof Error ? err.message : String(err);\n throw new UnsafePathError(candidate, `${label} crosses an unreadable or broken symlink: ${detail}`);\n }\n if (!isPathInside(rootReal, existingReal)) {\n throw new UnsafePathError(candidate, `${label} crosses a symlink outside its owning directory`);\n }\n return target;\n}\n\n/**\n * Snapshot manifests are portable data, so their path spelling is stricter\n * than an interactive path: forward slashes, no redundant components, and a\n * file (not directory) name at the end.\n */\nexport function resolvePortableFileInside(root: string, candidate: string, label = \"path\"): string {\n if (candidate.includes(\"\\\\\")) {\n throw new UnsafePathError(candidate, `${label} must use forward slashes`);\n }\n const parts = candidate.split(\"/\");\n if (parts.some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n throw new UnsafePathError(candidate, `${label} must be a canonical relative file path`);\n }\n return resolveInside(root, candidate, label);\n}\n\n/** Find the closest lexically contained path that exists, including symlinks. */\nfunction nearestExisting(target: string, root: string): string {\n let current = target;\n for (;;) {\n try {\n lstatSync(current);\n return current;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\" && code !== \"ENOTDIR\") throw err;\n }\n if (current === root) return root;\n const parent = dirname(current);\n if (parent === current || !isPathInside(root, parent)) return root;\n current = parent;\n }\n}\n"]}
1
+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C;YACjD,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,SAAS;gBAAE,MAAM,GAAG,CAAC;QACzD,CAAC;QACD,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAClC,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;QAChC,IAAI,MAAM,KAAK,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC;YAAE,OAAO,IAAI,CAAC;QACnE,OAAO,GAAG,MAAM,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Resolve caller-controlled paths without letting them leave an owned tree.\n *\n * A lexical `relative()` check is not enough: an existing component may be a\n * symlink whose target lives elsewhere. Conversely, checking only the final\n * path misses destinations that do not exist yet but whose nearest existing\n * parent is a symlink. This helper checks both views before a caller reads,\n * writes, walks, or removes anything.\n */\nimport { lstatSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, relative, resolve, sep, win32 } from \"node:path\";\n\nexport class UnsafePathError extends Error {\n constructor(\n readonly candidate: string,\n message: string,\n ) {\n super(message);\n this.name = \"UnsafePathError\";\n }\n}\n\n/** True when `target` is `root` or one of its descendants. */\nexport function isPathInside(root: string, target: string): boolean {\n const rel = relative(resolve(root), resolve(target));\n return rel === \"\" || (!isAbsolute(rel) && rel !== \"..\" && !rel.startsWith(`..${sep}`));\n}\n\n/**\n * Resolve a relative path beneath `root`, rejecting absolute paths, explicit\n * parent traversal, and symlink escape. The final path may be absent: its\n * nearest existing ancestor is checked in that case.\n */\nexport function resolveInside(root: string, candidate: string, label = \"path\"): string {\n if (candidate.length === 0) {\n throw new UnsafePathError(candidate, `${label} must not be empty`);\n }\n // win32.isAbsolute is intentional even on POSIX. Persisted/configured paths\n // may be moved between operating systems, and `C:\\\\...` must never turn into\n // an innocuous relative filename merely because validation ran on Linux.\n if (isAbsolute(candidate) || win32.isAbsolute(candidate)) {\n throw new UnsafePathError(candidate, `${label} must be relative to its owning directory`);\n }\n if (candidate.split(/[\\\\/]/).includes(\"..\")) {\n throw new UnsafePathError(candidate, `${label} must not contain '..' path segments`);\n }\n\n const rootAbs = resolve(root);\n const target = resolve(rootAbs, candidate);\n if (!isPathInside(rootAbs, target)) {\n throw new UnsafePathError(candidate, `${label} resolves outside its owning directory`);\n }\n\n let rootReal: string;\n let existing: string;\n try {\n rootReal = realpathSync(rootAbs);\n existing = nearestExisting(target, rootAbs);\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n throw new UnsafePathError(candidate, `${label} cannot be resolved safely: ${detail}`);\n }\n\n let existingReal: string;\n try {\n existingReal = realpathSync(existing);\n } catch (err) {\n // A broken symlink is an existing path according to lstat, but realpath\n // cannot prove where a later write through it would land. Refuse it.\n const detail = err instanceof Error ? err.message : String(err);\n throw new UnsafePathError(candidate, `${label} crosses an unreadable or broken symlink: ${detail}`);\n }\n if (!isPathInside(rootReal, existingReal)) {\n throw new UnsafePathError(candidate, `${label} crosses a symlink outside its owning directory`);\n }\n return target;\n}\n\n/**\n * Snapshot manifests are portable data, so their path spelling is stricter\n * than an interactive path: forward slashes, no redundant components, and a\n * file (not directory) name at the end.\n */\nexport function resolvePortableFileInside(root: string, candidate: string, label = \"path\"): string {\n if (candidate.includes(\"\\\\\")) {\n throw new UnsafePathError(candidate, `${label} must use forward slashes`);\n }\n const parts = candidate.split(\"/\");\n if (parts.some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n throw new UnsafePathError(candidate, `${label} must be a canonical relative file path`);\n }\n return resolveInside(root, candidate, label);\n}\n\n/**\n * The same portable spelling rules, with containment judged LEXICALLY — for a\n * path that names a file the docs repo itself mounts.\n *\n * Every spelling defence above is kept, and for its reason: a snapshot manifest\n * is loam's own file, but a corrupted or hostile one could carry `..` segments,\n * an absolute path or a `C:\\` spelling, and what comes out of this join is a\n * path a caller then goes and reads.\n *\n * What is deliberately not applied is the realpath test. Composing a docs repo\n * out of symlinks — a worktree, a submodule, one service's directory shared\n * between two checkouts — is a supported layout that every walk of the repo\n * FOLLOWS rather than refuses (repo.ts's `entryIs` says so in full), and that\n * `archive` already writes through: its living-document writes are planned from\n * `servicePaths()` and never see this file. With the realpath test in force on\n * the manifest's `path` field, a `services/<svc>/` mounted that way made an\n * interrupted archive permanently unrepairable — the retry was told the\n * snapshot could not be read when it was perfectly intact, and the half-merge it\n * was the only record of could never be repaired.\n *\n * This is only ever safe on a READ. A symlink that leaves the repo is\n * lexically indistinguishable from a service directory the operator mounted on\n * purpose — `escape/owned.txt` and `services/<svc>/spec.md` are both \"inside\n * docsDir\" until something resolves them — so the realpath test is the only\n * check that can refuse the first, at the price of also refusing the second.\n * A caller that goes on to WRITE through the path must pay that price and use\n * `resolvePortableFileInside`; `unarchive` does, and says so where it does.\n * A caller that only reads a file and compares a digest it never discloses\n * gains nothing from refusing, and loses the operator's ability to repair an\n * interrupted archive.\n */\nexport function resolvePortableFileInsideLexically(root: string, candidate: string, label = \"path\"): string {\n if (candidate.length === 0) {\n throw new UnsafePathError(candidate, `${label} must not be empty`);\n }\n if (candidate.includes(\"\\\\\")) {\n throw new UnsafePathError(candidate, `${label} must use forward slashes`);\n }\n const parts = candidate.split(\"/\");\n if (parts.some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n throw new UnsafePathError(candidate, `${label} must be a canonical relative file path`);\n }\n // win32.isAbsolute is intentional even on POSIX, for the reason `resolveInside`\n // gives: a snapshot travels with its feature directory between operating\n // systems, and `C:\\...` must never turn into an innocuous relative filename\n // merely because the question was asked on Linux.\n if (isAbsolute(candidate) || win32.isAbsolute(candidate)) {\n throw new UnsafePathError(candidate, `${label} must be relative to its owning directory`);\n }\n const rootAbs = resolve(root);\n const target = resolve(rootAbs, ...parts);\n // Already implied by the segment test above, and asked anyway: this line is\n // the containment claim itself, so a later loosening of the spelling rules\n // cannot quietly stop making it.\n if (!isPathInside(rootAbs, target)) {\n throw new UnsafePathError(candidate, `${label} resolves outside its owning directory`);\n }\n return target;\n}\n\n/** Find the closest lexically contained path that exists, including symlinks. */\nfunction nearestExisting(target: string, root: string): string {\n let current = target;\n for (;;) {\n try {\n lstatSync(current);\n return current;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\" && code !== \"ENOTDIR\") throw err;\n }\n if (current === root) return root;\n const parent = dirname(current);\n if (parent === current || !isPathInside(root, parent)) return root;\n current = parent;\n }\n}\n"]}
@@ -18,7 +18,7 @@ import { existsSync } from "node:fs";
18
18
  import { readdir, readFile, realpath, stat } from "node:fs/promises";
19
19
  import { join, relative, resolve, sep } from "node:path";
20
20
  import { listField, parseFrontmatter, rawBody, readFrontmatter, stringField, FEATURE_STATUSES, SERVICE_STATUSES, } from "./frontmatter.js";
21
- import { featurePaths, servicePaths } from "./repo.js";
21
+ import { featurePaths, servicePaths, SPEC_AXES } from "./repo.js";
22
22
  import { isPathInside, resolveInside } from "./path-safety.js";
23
23
  /** Fields every artifact is expected to carry, beyond its identity and status. */
24
24
  const EXPECTED = ["owner"];
@@ -27,11 +27,10 @@ export async function serviceProvenance(docsDir, service, opts = {}) {
27
27
  const findings = [];
28
28
  // Both requirement-carrying specs get the same pass: arch.spec.md follows
29
29
  // spec.md's frontmatter conventions exactly, so the checks are one loop —
30
- // only the label tells a reader which file moved.
31
- for (const { path, file } of [
32
- { path: paths.spec, file: "spec.md" },
33
- { path: paths.archSpec, file: "arch.spec.md" },
34
- ]) {
30
+ // only the label tells a reader which file moved. The pair comes from
31
+ // SPEC_AXES rather than being respelled, so a third axis is graded here the
32
+ // day it is declared instead of the day somebody notices.
33
+ for (const { path, file } of SPEC_AXES.map((axis) => ({ path: paths[axis.key], file: axis.file }))) {
35
34
  if (!existsSync(path))
36
35
  continue;
37
36
  const raw = await readFile(path, "utf8");
@@ -289,11 +288,24 @@ function contentFindings(fm, raw, service, label) {
289
288
  },
290
289
  ];
291
290
  }
291
+ /**
292
+ * The local calendar day, for the two commands that date a stamp. A vouch or a
293
+ * verification record is a person saying "today I read this", so it is their
294
+ * date, not UTC's — `toISOString` files an evening in the Americas under
295
+ * tomorrow. It sits here because this module already owns the stamp vocabulary
296
+ * the date is written into.
297
+ */
298
+ export function today(now) {
299
+ const pad = (n) => String(n).padStart(2, "0");
300
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
301
+ }
292
302
  /* ------------------------------------------------------------------ */
293
303
  /* The content digest */
294
304
  /* ------------------------------------------------------------------ */
295
305
  /** How much of the sha256 is written into the document. */
296
306
  const DIGEST_LENGTH = 16;
307
+ /** How many source files the digest reads at once — see `sourcesDigest`. */
308
+ const DIGEST_READ_BATCH = 32;
297
309
  /**
298
310
  * Digest the CONTENT of the files `sources` names. The recipe is spelled out
299
311
  * because the value is written into documents, and anything reading them has to
@@ -319,10 +331,23 @@ export async function sourcesDigest(repoDir, sources) {
319
331
  const { found, skipped } = await collectSources(repoDir, sources);
320
332
  const outer = createHash("sha256");
321
333
  const index = [];
322
- for (const file of found) {
323
- const content = createHash("sha256").update(await readFile(file.abs)).digest("hex");
324
- outer.update(`${file.rel}\0${content}\n`);
325
- index.push({ path: file.rel, sha: content.slice(0, DIGEST_LENGTH) });
334
+ // Read in fixed batches, hash in array order. `found` is already sorted and
335
+ // every file's own sha depends on nothing but its own bytes, so the sequence
336
+ // fed to `outer` — and therefore the digest — is unchanged by construction;
337
+ // only the waiting overlaps. A `sources: [src/]` over a real service repo is
338
+ // thousands of files, and one-await-per-file spent nearly all of its time
339
+ // idle. The batch is bounded rather than a single `Promise.all` over the
340
+ // whole list because an unbounded fan-out over a source tree runs the process
341
+ // out of file descriptors, which would turn a stamp into an EMFILE.
342
+ for (let start = 0; start < found.length; start += DIGEST_READ_BATCH) {
343
+ const hashed = await Promise.all(found.slice(start, start + DIGEST_READ_BATCH).map(async (file) => ({
344
+ rel: file.rel,
345
+ content: createHash("sha256").update(await readFile(file.abs)).digest("hex"),
346
+ })));
347
+ for (const { rel, content } of hashed) {
348
+ outer.update(`${rel}\0${content}\n`);
349
+ index.push({ path: rel, sha: content.slice(0, DIGEST_LENGTH) });
350
+ }
326
351
  }
327
352
  // `empty` is deliberately not set here: it is a sentence about a named
328
353
  // document, and a digest has no name to put in it. Callers that need it say
@@ -1 +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,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,OAAO,EACP,eAAe,EACf,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GAEjB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAE/D,kFAAkF;AAClF,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAU,CAAC;AAWpC,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAAe,EACf,OAAe,EACf,IAAI,GAAsB,EAAE;IAE5B,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC7C,MAAM,QAAQ,GAAc,EAAE,CAAC;IAC/B,0EAA0E;IAC1E,0EAA0E;IAC1E,kDAAkD;IAClD,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;QAC3B,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,E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,CAAC,CAAC,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AAC7D,CAAC;AAED,kEAAkE;AAClE,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,OAAiB;IAC/D,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;AAC1D,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,OAAiB;IAC9D,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE;QAC/B,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACvC,IAAI,CAAC;YACH,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,MAAM,GAAG,CAAC,CAAC;YACtD,OAAO,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 } 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.\n for (const { path, file } of [\n { path: paths.spec, file: \"spec.md\" },\n { path: paths.archSpec, file: \"arch.spec.md\" },\n ]) {\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 content digest */\n/* ------------------------------------------------------------------ */\n\n/** How much of the sha256 is written into the document. */\nconst DIGEST_LENGTH = 16;\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 for (const file of found) {\n const content = createHash(\"sha256\").update(await readFile(file.abs)).digest(\"hex\");\n outer.update(`${file.rel}\\0${content}\\n`);\n index.push({ path: file.rel, sha: content.slice(0, DIGEST_LENGTH) });\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"]}
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,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,E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AAC;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"]}
package/dist/core/repo.js CHANGED
@@ -42,6 +42,43 @@ export function compareIds(a, b) {
42
42
  function tokenize(s) {
43
43
  return (s.match(/\d+|\D+/g) ?? []).map((t) => (/^\d/.test(t) ? Number(t) : t));
44
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
+ }
45
82
  /**
46
83
  * Feature id from a directory name: everything up to and including the first
47
84
  * number run (`FEAT-101-payment-splitting` -> `FEAT-101`). A name with no
@@ -100,6 +137,35 @@ export function landscapePath(docsDir) {
100
137
  export function featuresDir(docsDir) {
101
138
  return join(docsDir, "features");
102
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
+ }
103
169
  export function docsRepoState(docsDir) {
104
170
  const path = docsDir;
105
171
  let isDir = false;
@@ -193,7 +259,15 @@ async function subdirs(dir) {
193
259
  .map((e) => e.name)
194
260
  .sort(compareIds);
195
261
  }
196
- async function countMarkdown(dir) {
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) {
197
271
  if (!existsSync(dir))
198
272
  return 0;
199
273
  const entries = await readdir(dir, { withFileTypes: true });