@mnstry/atelier 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/CHANGELOG.md +383 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +262 -0
  5. package/SECURITY.md +93 -0
  6. package/TRADEMARKS.md +88 -0
  7. package/announcements/2026-08-06-announcements-channel.v1.json +12 -0
  8. package/announcements/keys/mnstry-announcements.public.v1.json +9 -0
  9. package/bin/atelier.mjs +2 -0
  10. package/bin/mnstry-atelier.mjs +3 -0
  11. package/contracts/analysis-adapter.v1.schema.json +248 -0
  12. package/contracts/atelier-action-intent.v1.schema.json +143 -0
  13. package/contracts/atelier-analysis-adapter.v1.schema.json +360 -0
  14. package/contracts/atelier-attestation.v1.schema.json +239 -0
  15. package/contracts/atelier-boundary-policy.v1.schema.json +339 -0
  16. package/contracts/atelier-claim.v1.schema.json +97 -0
  17. package/contracts/atelier-export.v1.schema.json +1015 -0
  18. package/contracts/atelier-extension-pack.v1.schema.json +290 -0
  19. package/contracts/atelier-kit-manifest.v1.schema.json +273 -0
  20. package/contracts/atelier-lock.v1.schema.json +364 -0
  21. package/contracts/atelier-migration.v1.schema.json +162 -0
  22. package/contracts/atelier-project-config.v1.schema.json +352 -0
  23. package/contracts/atelier-readiness-protocol.v1.schema.json +517 -0
  24. package/contracts/atelier-readiness-run.v1.schema.json +229 -0
  25. package/contracts/atelier-readiness.v1.schema.json +457 -0
  26. package/contracts/compat-baseline.json +10 -0
  27. package/contracts/git-promote-event.v1.schema.json +145 -0
  28. package/contracts/knowledge-source-sidecar.v1.schema.json +157 -0
  29. package/contracts/mnstry-atelier-semantic-profile.v1.json +254 -0
  30. package/docs/announcements.md +101 -0
  31. package/docs/atelier-runtime.md +34 -0
  32. package/docs/attestation.md +201 -0
  33. package/docs/continuity.md +55 -0
  34. package/docs/contract-stability.md +111 -0
  35. package/docs/distributions.md +220 -0
  36. package/docs/install.md +140 -0
  37. package/docs/knowledge-graph.md +140 -0
  38. package/docs/ontology.md +206 -0
  39. package/docs/release-engineering.md +151 -0
  40. package/docs/repo-boundary-guard.md +199 -0
  41. package/docs/tenant-readiness.md +64 -0
  42. package/docs/upgrade.md +124 -0
  43. package/fixtures/analysis/invalid/native-graph.v1.json +4 -0
  44. package/fixtures/analysis/invalid/promoted-claim.v1.json +17 -0
  45. package/fixtures/analysis/invalid/runtime-import.v1.json +20 -0
  46. package/fixtures/analysis/valid/output.claims.v1.json +17 -0
  47. package/fixtures/analysis-adapter/invalid/manifest-hidden-provider.v1.json +24 -0
  48. package/fixtures/analysis-adapter/invalid/output-frontmatter-mutation.v1.json +21 -0
  49. package/fixtures/analysis-adapter/invalid/output-native-graph.v1.json +14 -0
  50. package/fixtures/analysis-adapter/manifest.disabled.v1.json +22 -0
  51. package/fixtures/analysis-adapter/manifest.enabled-local.v1.json +23 -0
  52. package/fixtures/analysis-adapter/output.claims.v1.json +21 -0
  53. package/fixtures/atelier-action-intent/invalid/runtime-mutation-authority.v1.json +16 -0
  54. package/fixtures/atelier-action-intent/invalid/unknown-top-level-field.v1.json +17 -0
  55. package/fixtures/atelier-action-intent/invalid/writes-beyond-clipboard.v1.json +16 -0
  56. package/fixtures/atelier-action-intent/valid/copy-agent-prompt.v1.json +16 -0
  57. package/fixtures/atelier-action-intent/valid/copy-repo-path.v1.json +22 -0
  58. package/fixtures/atelier-analysis-adapter/invalid/hidden-model-provider.v1.json +24 -0
  59. package/fixtures/atelier-analysis-adapter/invalid/inert-with-execute-command.v1.json +24 -0
  60. package/fixtures/atelier-analysis-adapter/invalid/proposals-with-runtime-import.v1.json +30 -0
  61. package/fixtures/atelier-analysis-adapter/valid/manifest-inert.v1.json +24 -0
  62. package/fixtures/atelier-analysis-adapter/valid/proposals-claim-only.v1.json +27 -0
  63. package/fixtures/atelier-attestation/invalid/bad-digest.v1.json +23 -0
  64. package/fixtures/atelier-attestation/invalid/conformance-scope.v1.json +23 -0
  65. package/fixtures/atelier-attestation/invalid/missing-signature.v1.json +22 -0
  66. package/fixtures/atelier-attestation/invalid/unknown-root-field.v1.json +24 -0
  67. package/fixtures/atelier-attestation/keys/roundtrip-issuer.public.v1.json +9 -0
  68. package/fixtures/atelier-attestation/valid/rejected-with-reasons.v1.json +49 -0
  69. package/fixtures/atelier-attestation/valid/signed-admitted.v1.json +35 -0
  70. package/fixtures/atelier-attestation/valid/signed-roundtrip.v1.json +29 -0
  71. package/fixtures/atelier-attestation/valid/unsigned-advisory.v1.json +23 -0
  72. package/fixtures/atelier-claim/invalid/unknown-provider.v1.json +15 -0
  73. package/fixtures/atelier-claim/invalid/unknown-top-level-field.v1.json +16 -0
  74. package/fixtures/atelier-claim/invalid/wrong-schema-const.v1.json +15 -0
  75. package/fixtures/atelier-claim/valid/adapter-style-proposed-relation.v1.json +19 -0
  76. package/fixtures/atelier-claim/valid/codex-proposed-relation.v1.json +16 -0
  77. package/fixtures/atelier-claim/valid/manual-proposed-relation.v1.json +16 -0
  78. package/fixtures/atelier-claim/valid/readiness-proposed-relation.v1.json +18 -0
  79. package/fixtures/atelier-export/invalid/dirty-unforced-empty-taint.v1.json +19 -0
  80. package/fixtures/atelier-export/invalid/object-local-audience-visibility.v1.json +11 -0
  81. package/fixtures/atelier-export/invalid/open-object-class-owner.v1.json +23 -0
  82. package/fixtures/atelier-export/invalid/pricing-legacy-amount.v1.json +23 -0
  83. package/fixtures/atelier-export/invalid/public-disguised-internal-source-ref.v1.json +11 -0
  84. package/fixtures/atelier-export/invalid/public-nested-private-source-ref.v1.json +17 -0
  85. package/fixtures/atelier-export/invalid/public-resolved-private-source-ref.v1.json +13 -0
  86. package/fixtures/atelier-export/invalid/public-resolved-sensitive-source-ref.v1.json +13 -0
  87. package/fixtures/atelier-export/invalid/public-source-ref-missing-provenance.v1.json +20 -0
  88. package/fixtures/atelier-export/invalid/public-source-team-kg.json +12 -0
  89. package/fixtures/atelier-export/invalid/source-node-legacy-visibility.v1.json +21 -0
  90. package/fixtures/atelier-export/invalid/source-node-unknown-field.v1.json +18 -0
  91. package/fixtures/atelier-export/invalid/unresolved-public-source-ref.v1.json +11 -0
  92. package/fixtures/atelier-export/sample-studio-offer.v1.json +397 -0
  93. package/fixtures/atelier-extension-pack/invalid/bundled-slug-collision.v1.json +22 -0
  94. package/fixtures/atelier-extension-pack/invalid/escapes-root.v1.json +22 -0
  95. package/fixtures/atelier-extension-pack/invalid/posture-tampered.v1.json +22 -0
  96. package/fixtures/atelier-extension-pack/invalid/protocols/autonomous-authority.v1.json +118 -0
  97. package/fixtures/atelier-extension-pack/invalid/protocols/offer-map.v1.json +109 -0
  98. package/fixtures/atelier-extension-pack/invalid/redefines-runtime-term.v1.json +19 -0
  99. package/fixtures/atelier-extension-pack/invalid/wrong-namespace.v1.json +19 -0
  100. package/fixtures/atelier-extension-pack/valid/protocols/contract-gate.v1.json +109 -0
  101. package/fixtures/atelier-extension-pack/valid/sample-pack.v1.json +48 -0
  102. package/fixtures/atelier-kit-manifest/invalid/runtime-copy-without-canonical-role.v1.json +53 -0
  103. package/fixtures/atelier-kit-manifest/invalid/telemetry-send-path.v1.json +21 -0
  104. package/fixtures/atelier-kit-manifest/valid/mnstry-atelier.valid.v1.json +76 -0
  105. package/fixtures/atelier-lock/invalid/absolute-contract-path.v1.json +40 -0
  106. package/fixtures/atelier-lock/invalid/runtime-mutation-enabled.v1.json +41 -0
  107. package/fixtures/atelier-lock/invalid/unknown-top-level-field.v1.json +42 -0
  108. package/fixtures/atelier-lock/valid/extension-pack.v1.json +55 -0
  109. package/fixtures/atelier-lock/valid/minimal.v1.json +44 -0
  110. package/fixtures/atelier-migration/invalid/live-apply-mode.v1.json +21 -0
  111. package/fixtures/atelier-migration/invalid/missing-review-evidence.v1.json +20 -0
  112. package/fixtures/atelier-migration/invalid/runtime-mutation-enabled.v1.json +21 -0
  113. package/fixtures/atelier-migration/valid/minimal.v1.json +32 -0
  114. package/fixtures/atelier-project-config/invalid/absolute-repo-path.v1.json +11 -0
  115. package/fixtures/atelier-project-config/invalid/ext-not-object.v1.json +12 -0
  116. package/fixtures/atelier-project-config/invalid/external-kind-read-boundary.v1.json +12 -0
  117. package/fixtures/atelier-project-config/invalid/missing-repos-and-alignment.v1.json +7 -0
  118. package/fixtures/atelier-project-config/invalid/unknown-top-level-field.v1.json +14 -0
  119. package/fixtures/atelier-project-config/valid/alignment-scaffold.v1.json +15 -0
  120. package/fixtures/atelier-project-config/valid/ext-extension-packs.v1.json +36 -0
  121. package/fixtures/atelier-project-config/valid/repo-workspace.v1.json +23 -0
  122. package/fixtures/atelier-project-config/validator-only/ext-member-not-object.v1.json +14 -0
  123. package/fixtures/atelier-readiness/invalid/dry-run-only-false.v1.json +87 -0
  124. package/fixtures/atelier-readiness/invalid/support-bundle-send-path.v1.json +87 -0
  125. package/fixtures/atelier-readiness/invalid/unknown-top-level-field.v1.json +88 -0
  126. package/fixtures/atelier-readiness/valid/ready-workspace.v1.json +84 -0
  127. package/fixtures/boundary-policy/invalid/content-rule-exception-blanket-path.v1.json +67 -0
  128. package/fixtures/boundary-policy/invalid/invalid-actor-private-repo-mapping.v1.json +20 -0
  129. package/fixtures/boundary-policy/invalid/legacy-warning-missing-warning.v1.json +20 -0
  130. package/fixtures/boundary-policy/invalid/missing-repo-coverage.v1.json +19 -0
  131. package/fixtures/boundary-policy/invalid/unknown-key.v1.json +12 -0
  132. package/fixtures/boundary-policy/valid/content-rule-exception.v1.json +67 -0
  133. package/fixtures/boundary-policy/valid/legacy-warning.v1.json +33 -0
  134. package/fixtures/boundary-policy/valid/strict-private-shared.v1.json +40 -0
  135. package/fixtures/git-promote/invalid/provision-named-revocable.v1.json +29 -0
  136. package/fixtures/git-promote/private-to-team.v1.json +29 -0
  137. package/fixtures/knowledge-source-sidecar/invalid/legacy-visibility-field.v1.json +17 -0
  138. package/fixtures/knowledge-source-sidecar/invalid/missing-audience.v1.json +15 -0
  139. package/fixtures/knowledge-source-sidecar/invalid/unknown-relation-kind.v1.json +18 -0
  140. package/fixtures/knowledge-source-sidecar/valid/html-source.v1.json +18 -0
  141. package/fixtures/knowledge-source-sidecar/valid/pdf-evidence.v1.json +18 -0
  142. package/fixtures/projects/neutral-project/atelier.project.json +15 -0
  143. package/fixtures/projects/neutral-project/ops/config/repo-access.v1.json +12 -0
  144. package/fixtures/projects/neutral-project/project-knowledge.graph.json +69 -0
  145. package/fixtures/projects/sample-workspace/atelier.project.json +23 -0
  146. package/fixtures/projects/sample-workspace/boundary-policy.v1.json +59 -0
  147. package/fixtures/projects/sample-workspace/content/README.md +16 -0
  148. package/fixtures/projects/sample-workspace/content/source.html +5 -0
  149. package/fixtures/projects/sample-workspace/content/source.html.kg.json +15 -0
  150. package/fixtures/projects/sample-workspace/repo-access.v1.json +9 -0
  151. package/fixtures/projects/source-formats-workspace/atelier.project.json +23 -0
  152. package/fixtures/projects/source-formats-workspace/content/README.md +17 -0
  153. package/fixtures/projects/source-formats-workspace/content/data.json +7 -0
  154. package/fixtures/projects/source-formats-workspace/content/data.json.kg.json +15 -0
  155. package/fixtures/projects/source-formats-workspace/content/logo.png.kg.json +15 -0
  156. package/fixtures/projects/source-formats-workspace/content/metrics.csv +3 -0
  157. package/fixtures/projects/source-formats-workspace/content/metrics.csv.kg.json +15 -0
  158. package/fixtures/projects/source-formats-workspace/content/pipeline.yaml +4 -0
  159. package/fixtures/projects/source-formats-workspace/content/pipeline.yaml.kg.json +15 -0
  160. package/fixtures/projects/source-formats-workspace/repo-access.v1.json +9 -0
  161. package/fixtures/readiness-protocols/extension-pack/invalid/protocol-missing-path.v1.json +20 -0
  162. package/fixtures/readiness-protocols/extension-pack/valid/with-protocol.v1.json +24 -0
  163. package/fixtures/readiness-protocols/protocol/invalid/missing-check-target.v1.json +103 -0
  164. package/fixtures/readiness-protocols/protocol/invalid/runtime-mutation-enabled.v1.json +107 -0
  165. package/fixtures/readiness-protocols/protocol/valid/minimal.v1.json +100 -0
  166. package/fixtures/readiness-protocols/run/invalid/missing-evidence.v1.json +37 -0
  167. package/fixtures/readiness-protocols/run/invalid/pass-with-blocker.v1.json +22 -0
  168. package/fixtures/readiness-protocols/run/invalid/runtime-mutation-enabled.v1.json +22 -0
  169. package/fixtures/readiness-protocols/run/valid/pass.v1.json +44 -0
  170. package/fixtures/support/invalid/leaky-support.v1.json +13 -0
  171. package/fixtures/support/valid/minimal-safe.v1.json +20 -0
  172. package/package.json +98 -0
  173. package/skills/claude/atelier-open/SKILL.md +68 -0
  174. package/skills/claude/mnstry-readiness/SKILL.md +41 -0
  175. package/skills/codex/atelier-open/SKILL.md +68 -0
  176. package/skills/codex/mnstry-readiness/SKILL.md +41 -0
  177. package/src/analysis/adapter.mjs +20 -0
  178. package/src/analysis/analysis-claim-contract.mjs +335 -0
  179. package/src/attestation/jcs.mjs +64 -0
  180. package/src/attestation/sign.mjs +305 -0
  181. package/src/boundary/content-rules.mjs +262 -0
  182. package/src/boundary/policy.mjs +806 -0
  183. package/src/check-atelier-export-contract.mjs +116 -0
  184. package/src/cli/run.mjs +283 -0
  185. package/src/collaboration/proposals.mjs +262 -0
  186. package/src/commands/analysis.mjs +8 -0
  187. package/src/commands/announcements.mjs +308 -0
  188. package/src/commands/attestation.mjs +198 -0
  189. package/src/commands/boundary.mjs +25 -0
  190. package/src/commands/config.mjs +4 -0
  191. package/src/commands/context.mjs +3 -0
  192. package/src/commands/distribution.mjs +224 -0
  193. package/src/commands/egress.mjs +11 -0
  194. package/src/commands/extension-pack.mjs +209 -0
  195. package/src/commands/feedback.mjs +3 -0
  196. package/src/commands/graph.mjs +3 -0
  197. package/src/commands/init.mjs +130 -0
  198. package/src/commands/lock.mjs +3 -0
  199. package/src/commands/project.mjs +3 -0
  200. package/src/commands/promote.mjs +4 -0
  201. package/src/commands/readiness.mjs +3 -0
  202. package/src/commands/server.mjs +6 -0
  203. package/src/commands/setup.mjs +250 -0
  204. package/src/commands/support.mjs +3 -0
  205. package/src/commands/upgrade.mjs +3 -0
  206. package/src/contracts/corpus.mjs +171 -0
  207. package/src/egress/check.mjs +45 -0
  208. package/src/egress/forbidden-egress.mjs +323 -0
  209. package/src/export/atelier-export-contract.mjs +722 -0
  210. package/src/extension-packs/loader.mjs +491 -0
  211. package/src/graph/graph.mjs +370 -0
  212. package/src/graph/knowledge-graph.mjs +887 -0
  213. package/src/harness/context-client.mjs +144 -0
  214. package/src/harness/context.mjs +27 -0
  215. package/src/index.mjs +88 -0
  216. package/src/project/config.mjs +557 -0
  217. package/src/project/file-class.mjs +113 -0
  218. package/src/project/git-ignore.mjs +31 -0
  219. package/src/project/path-match.mjs +30 -0
  220. package/src/project/repo-identity.mjs +176 -0
  221. package/src/projection/alignment-projection.mjs +169 -0
  222. package/src/projection/policy.mjs +90 -0
  223. package/src/projection/project.mjs +152 -0
  224. package/src/readiness/readiness.mjs +312 -0
  225. package/src/readiness-protocols/bundled-pack.mjs +766 -0
  226. package/src/readiness-protocols/runtime.mjs +419 -0
  227. package/src/server/local-sidecar.mjs +640 -0
  228. package/src/server/security.mjs +229 -0
  229. package/src/server/server.mjs +42 -0
  230. package/src/support/feedback-report.mjs +414 -0
  231. package/src/support/support-bundle.mjs +226 -0
  232. package/src/ui/html-primitives.mjs +104 -0
  233. package/src/upgrade/upgrade.mjs +701 -0
  234. package/src/validate-atelier-export-dry-run.mjs +75 -0
  235. package/templates/atelier.project.example.json +23 -0
  236. package/templates/distribution-workspace/.claude/launch.json +12 -0
  237. package/templates/distribution-workspace/README.md +86 -0
  238. package/templates/distribution-workspace/atelier.project.json +36 -0
  239. package/templates/distribution-workspace/boundary-policy.v1.json +61 -0
  240. package/templates/distribution-workspace/gitignore +29 -0
  241. package/templates/distribution-workspace/governance/repo-boundary-ledger.md +5 -0
  242. package/templates/distribution-workspace/project/README.md +19 -0
  243. package/templates/distribution-workspace/repo-access.v1.json +9 -0
  244. package/templates/launch.json +12 -0
  245. package/templates/private-domain-workspace/.claude/launch.json +12 -0
  246. package/templates/private-domain-workspace/README.md +50 -0
  247. package/templates/private-domain-workspace/atelier.project.json +28 -0
  248. package/templates/private-domain-workspace/boundary-policy.v1.json +54 -0
  249. package/templates/private-domain-workspace/domain/README.md +19 -0
  250. package/templates/private-domain-workspace/gitignore +29 -0
  251. package/templates/private-domain-workspace/governance/repo-boundary-ledger.md +4 -0
  252. package/templates/private-domain-workspace/repo-access.v1.json +9 -0
  253. package/templates/shared-project-workspace/.claude/launch.json +12 -0
  254. package/templates/shared-project-workspace/README.md +51 -0
  255. package/templates/shared-project-workspace/atelier.project.json +28 -0
  256. package/templates/shared-project-workspace/boundary-policy.v1.json +61 -0
  257. package/templates/shared-project-workspace/gitignore +29 -0
  258. package/templates/shared-project-workspace/governance/repo-boundary-ledger.md +5 -0
  259. package/templates/shared-project-workspace/project/README.md +19 -0
  260. package/templates/shared-project-workspace/repo-access.v1.json +9 -0
@@ -0,0 +1,370 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { commandProject, gitRemoteUrl, loadRepoAccess, readJson, remoteHost, writeJson } from '../project/config.mjs'
4
+ import { gitIgnoreFilter } from '../project/git-ignore.mjs'
5
+
6
+ export const VALID_AUDIENCES = new Set(['private', 'team', 'operator', 'staff', 'public', 'sensitive'])
7
+ export const VALID_RELATIONS = new Set(['related', 'supports', 'supersedes', 'implements', 'depends_on', 'evidences', 'contradicts', 'belongs_to'])
8
+ const DOC_EXTS = new Set(['.md', '.html', '.pdf', '.docx'])
9
+ const SKIP_DIRS = new Set(['.git', 'node_modules', 'atelier-output', 'atelier-readers', '.mnstry', '.atelier-local'])
10
+
11
+ const slug = (value) => String(value ?? '').toLowerCase().replace(/\.[^.]+$/, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
12
+ const relPath = (root, file) => path.relative(root, file).split(path.sep).join('/')
13
+
14
+ // Sidecar-first census. Document extensions are always sources; any other
15
+ // file — json, yaml, csv, binary assets — opts in by carrying an adjacent
16
+ // .kg.json sidecar. The sidecar itself is metadata, never a source asset.
17
+ //
18
+ // Membership asks whether the sidecar is VISIBLE, not whether it happens to
19
+ // exist on this disk. A git-ignored sidecar is machine-local: obeying one
20
+ // enrolls a node that no tracked file declares — audience and all — so a
21
+ // clean checkout builds a different graph than the machine that wrote it.
22
+ function isSourceFile(name, sidecarVisible) {
23
+ if (name.endsWith('.kg.json')) return false
24
+ if (DOC_EXTS.has(path.extname(name).toLowerCase())) return true
25
+ return sidecarVisible === true
26
+ }
27
+
28
+ function sidecarIsVisible(abs, root, isIgnored) {
29
+ const sidecar = sidecarFor(abs)
30
+ return fs.existsSync(sidecar) && !isIgnored(relPath(root, sidecar))
31
+ }
32
+
33
+ function walk(dir, root, acc = [], isIgnored = gitIgnoreFilter(root)) {
34
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
35
+ if (ent.name.startsWith('.') || SKIP_DIRS.has(ent.name)) continue
36
+ const abs = path.join(dir, ent.name)
37
+ if (isIgnored(relPath(root, abs))) continue
38
+ if (ent.isDirectory()) walk(abs, root, acc, isIgnored)
39
+ if (!ent.isFile() || ent.name.endsWith('.kg.json')) continue
40
+ const ext = path.extname(ent.name).toLowerCase()
41
+ // Markdown carries its own front matter and never consults a sidecar.
42
+ const sidecarVisible = ext === '.md' ? false : sidecarIsVisible(abs, root, isIgnored)
43
+ if (isSourceFile(ent.name, sidecarVisible)) acc.push({ abs, rel: relPath(root, abs), ext, sidecarVisible })
44
+ }
45
+ return acc
46
+ }
47
+
48
+ function splitFrontmatter(raw) {
49
+ if (!raw.startsWith('---\n')) return null
50
+ const end = raw.indexOf('\n---', 4)
51
+ if (end === -1) return null
52
+ return raw.slice(4, end)
53
+ }
54
+
55
+ function parseValue(value) {
56
+ const text = String(value ?? '').trim()
57
+ if (!text) return ''
58
+ if ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) return text.slice(1, -1)
59
+ if (text === 'true') return true
60
+ if (text === 'false') return false
61
+ return text
62
+ }
63
+
64
+ function setPath(target, keys, value) {
65
+ let cursor = target
66
+ for (const key of keys.slice(0, -1)) {
67
+ cursor[key] ??= {}
68
+ cursor = cursor[key]
69
+ }
70
+ cursor[keys.at(-1)] = value
71
+ }
72
+
73
+ export function parseFrontmatterYaml(yaml) {
74
+ const out = {}
75
+ const lines = String(yaml ?? '').split('\n')
76
+ const stack = [{ indent: -1, value: out, key: null }]
77
+ for (let index = 0; index < lines.length; index += 1) {
78
+ const raw = lines[index]
79
+ if (!raw.trim() || raw.trim().startsWith('#')) continue
80
+ const indent = raw.match(/^\s*/)[0].length
81
+ const line = raw.trim()
82
+ while (stack.length > 1 && indent <= stack.at(-1).indent) stack.pop()
83
+ const parent = stack.at(-1).value
84
+ if (line.startsWith('- ')) {
85
+ if (!Array.isArray(parent)) continue
86
+ parent.push(parseValue(line.slice(2)))
87
+ continue
88
+ }
89
+ const match = line.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/)
90
+ if (!match) continue
91
+ const [, key, rest] = match
92
+ if (rest === '') {
93
+ parent[key] = nextYamlContainer(lines, index, indent)
94
+ stack.push({ indent, value: parent[key], key })
95
+ } else if (rest === '[]') {
96
+ parent[key] = []
97
+ stack.push({ indent, value: parent[key], key })
98
+ } else {
99
+ parent[key] = parseValue(rest)
100
+ }
101
+ }
102
+ return out
103
+ }
104
+
105
+ function nextYamlContainer(lines, fromIndex, indent) {
106
+ for (let index = fromIndex + 1; index < lines.length; index += 1) {
107
+ const raw = lines[index]
108
+ if (!raw.trim() || raw.trim().startsWith('#')) continue
109
+ const nextIndent = raw.match(/^\s*/)[0].length
110
+ if (nextIndent <= indent) return {}
111
+ return raw.trim().startsWith('- ') ? [] : {}
112
+ }
113
+ return {}
114
+ }
115
+
116
+ function normalizeRelations(relations) {
117
+ const out = {}
118
+ if (!relations || typeof relations !== 'object') return out
119
+ for (const [type, targets] of Object.entries(relations)) {
120
+ if (Array.isArray(targets)) out[type] = targets.map(String)
121
+ else if (typeof targets === 'string') out[type] = [targets]
122
+ else out[type] = []
123
+ }
124
+ return out
125
+ }
126
+
127
+ function sidecarFor(file) {
128
+ return `${file}.kg.json`
129
+ }
130
+
131
+ function validateSidecar(meta, repo, file, errors) {
132
+ const allowed = new Set(['assetFilename', 'title', 'summary', 'tags', 'kg'])
133
+ const kgAllowed = new Set(['id', 'title', 'type', 'domain', 'lifecycle', 'status', 'audience', 'relations'])
134
+ for (const key of Object.keys(meta || {})) {
135
+ if (!allowed.has(key)) errors.push(`${repo.name}/${file.rel}: sidecar has unknown key ${key}`)
136
+ }
137
+ for (const key of Object.keys(meta?.kg || {})) {
138
+ if (!kgAllowed.has(key)) errors.push(`${repo.name}/${file.rel}: sidecar kg has unknown key ${key}`)
139
+ }
140
+ }
141
+
142
+ function nodeFromMarkdown(repo, file, errors) {
143
+ const raw = fs.readFileSync(file.abs, 'utf8')
144
+ const fm = splitFrontmatter(raw)
145
+ if (!fm) return null
146
+ const parsed = parseFrontmatterYaml(fm)
147
+ const kg = parsed.kg ?? {}
148
+ if (!kg.id) errors.push(`${repo.name}/${file.rel}: kg.id is required`)
149
+ if (!kg.audience) errors.push(`${repo.name}/${file.rel}: kg.audience is required`)
150
+ if (kg.visibility) errors.push(`${repo.name}/${file.rel}: kg.visibility is invalid; use kg.audience`)
151
+ return {
152
+ id: kg.id || `${repo.name}:${slug(file.rel)}`,
153
+ title: parsed.title || kg.title || path.basename(file.rel, file.ext),
154
+ summary: parsed.summary || '',
155
+ repo: repo.name,
156
+ path: file.rel,
157
+ type: kg.type || 'document',
158
+ status: kg.status || 'active',
159
+ audience: kg.audience || 'private',
160
+ tags: Array.isArray(parsed.tags) ? parsed.tags : [],
161
+ relations: normalizeRelations(kg.relations),
162
+ }
163
+ }
164
+
165
+ function nodeFromSidecar(repo, file, errors) {
166
+ const sidecar = sidecarFor(file.abs)
167
+ // Visibility again, and for the same reason: a git-ignored sidecar must not
168
+ // supply identity, audience, or relations. A document-extension asset whose
169
+ // only sidecar is ignored therefore fails closed with the ordinary
170
+ // missing-sidecar error — the same verdict a clean checkout reaches.
171
+ if (!file.sidecarVisible) {
172
+ errors.push(`${repo.name}/${file.rel}: non-Markdown source requires sidecar ${path.basename(sidecar)}`)
173
+ return null
174
+ }
175
+ const meta = readJson(sidecar)
176
+ validateSidecar(meta, repo, file, errors)
177
+ const kg = meta.kg ?? {}
178
+ if (meta.assetFilename && meta.assetFilename !== path.basename(file.abs)) errors.push(`${repo.name}/${file.rel}: sidecar assetFilename must match source filename`)
179
+ if (!kg.id) errors.push(`${repo.name}/${file.rel}: sidecar kg.id is required`)
180
+ if (!kg.audience) errors.push(`${repo.name}/${file.rel}: sidecar kg.audience is required`)
181
+ if (kg.visibility) errors.push(`${repo.name}/${file.rel}: sidecar kg.visibility is invalid; use kg.audience`)
182
+ return {
183
+ id: kg.id || `${repo.name}:${slug(file.rel)}-${file.ext.slice(1)}`,
184
+ title: meta.title || kg.title || path.basename(file.rel, file.ext),
185
+ summary: meta.summary || '',
186
+ repo: repo.name,
187
+ path: file.rel,
188
+ type: kg.type || file.ext.slice(1),
189
+ status: kg.status || 'active',
190
+ audience: kg.audience || 'private',
191
+ tags: Array.isArray(meta.tags) ? meta.tags : [],
192
+ relations: normalizeRelations(kg.relations),
193
+ }
194
+ }
195
+
196
+ export function buildGraph(project) {
197
+ const repoAccess = loadRepoAccess(project)
198
+ const externalRelationPrefixes = new Set(Array.isArray(project.config.graph?.externalRelationPrefixes) ? project.config.graph.externalRelationPrefixes : [])
199
+ const externalRelationIds = new Set(Array.isArray(project.config.graph?.externalRelationIds) ? project.config.graph.externalRelationIds : [])
200
+ const errors = []
201
+ const diagnostics = []
202
+ const nodes = []
203
+ const edges = []
204
+ const external = []
205
+
206
+ for (const repo of project.repos) {
207
+ if (repo.external) {
208
+ // Identity acknowledged, nothing walked: the workspace does not own this
209
+ // content and cannot answer for its metadata.
210
+ external.push({ name: repo.name, path: repo.path ?? null, remoteHost: remoteHost(gitRemoteUrl(repo.path)) })
211
+ continue
212
+ }
213
+ if (!repo.name || !repo.path || !fs.existsSync(repo.path)) {
214
+ errors.push(`configured repo is missing or unreadable: ${repo.name ?? '(unnamed)'}`)
215
+ continue
216
+ }
217
+ // One batched ignore lookup per repo, shared by every walk below.
218
+ const isIgnored = gitIgnoreFilter(repo.path)
219
+ for (const file of walk(repo.path, repo.path, [], isIgnored)) {
220
+ // Markdown is the one inline metadata format; every other source is
221
+ // sidecar-described and its own bytes are never read.
222
+ const node = file.ext === '.md' ? nodeFromMarkdown(repo, file, errors) : nodeFromSidecar(repo, file, errors)
223
+ if (!node) continue
224
+ const boundary = repoAccess.repos?.[repo.name]?.readBoundary ?? repo.readBoundary ?? repoAccess.defaultReadBoundary ?? 'team'
225
+ node.repoAccess = { readBoundary: boundary }
226
+ if (['private', 'sensitive'].includes(node.audience) && boundary !== 'private') {
227
+ diagnostics.push({
228
+ severity: 'warning',
229
+ code: 'audience-wider-repo-boundary',
230
+ node: node.id,
231
+ message: `${node.id}: audience ${node.audience} is in a ${boundary}-readable repo`,
232
+ })
233
+ }
234
+ nodes.push(node)
235
+ }
236
+ for (const orphan of findOrphanSidecars(repo.path, isIgnored)) {
237
+ errors.push(`${repo.name}/${orphan}: sidecar has no matching source asset`)
238
+ }
239
+ }
240
+
241
+ const ids = new Set()
242
+ for (const node of nodes) {
243
+ if (ids.has(node.id)) errors.push(`duplicate kg.id: ${node.id}`)
244
+ ids.add(node.id)
245
+ if (!VALID_AUDIENCES.has(node.audience)) errors.push(`${node.id}: invalid audience ${node.audience}`)
246
+ }
247
+
248
+ for (const node of nodes) {
249
+ for (const [type, targets] of Object.entries(node.relations ?? {})) {
250
+ if (!VALID_RELATIONS.has(type)) errors.push(`${node.id}: invalid relation type ${type}`)
251
+ for (const target of targets) {
252
+ if (!ids.has(target) && !isExternalRelationTarget(target, { externalRelationPrefixes, externalRelationIds })) {
253
+ errors.push(`${node.id}: relation target not found: ${target}`)
254
+ }
255
+ edges.push({ source: node.id, target, type, declared: true })
256
+ }
257
+ }
258
+ }
259
+
260
+ return {
261
+ schema: 'mnstry.atelier-knowledge-graph@v1',
262
+ generatedAt: 'deterministic',
263
+ project: path.basename(project.workspaceRoot),
264
+ counts: { nodes: nodes.length, edges: edges.length, diagnostics: diagnostics.length },
265
+ nodes,
266
+ edges,
267
+ diagnostics,
268
+ external: external.sort((a, b) => String(a.name).localeCompare(String(b.name))),
269
+ errors,
270
+ }
271
+ }
272
+
273
+ function isExternalRelationTarget(target, { externalRelationPrefixes, externalRelationIds }) {
274
+ if (externalRelationIds.has(target)) return true
275
+ const prefix = String(target).split(':')[0]
276
+ return externalRelationPrefixes.has(prefix)
277
+ }
278
+
279
+ function findOrphanSidecars(root, isIgnored = gitIgnoreFilter(root)) {
280
+ const orphans = []
281
+ function visit(dir) {
282
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
283
+ if (ent.name.startsWith('.') || SKIP_DIRS.has(ent.name)) continue
284
+ const abs = path.join(dir, ent.name)
285
+ if (isIgnored(relPath(root, abs))) continue
286
+ if (ent.isDirectory()) visit(abs)
287
+ else if (ent.isFile() && ent.name.endsWith('.kg.json')) {
288
+ const asset = abs.slice(0, -'.kg.json'.length)
289
+ if (!fs.existsSync(asset)) orphans.push(relPath(root, abs))
290
+ }
291
+ }
292
+ }
293
+ visit(root)
294
+ return orphans
295
+ }
296
+
297
+ // Sidecars that exist on disk but are git-ignored, next to a file the census
298
+ // can see. Refused, never obeyed — and never silently: dropping them without a
299
+ // word is what let an untracked sidecar mint a public node.
300
+ function findIgnoredSidecars(root, isIgnored = gitIgnoreFilter(root)) {
301
+ const found = []
302
+ function visit(dir) {
303
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
304
+ if (ent.name.startsWith('.') || SKIP_DIRS.has(ent.name)) continue
305
+ const abs = path.join(dir, ent.name)
306
+ const rel = relPath(root, abs)
307
+ if (ent.isDirectory()) {
308
+ if (!isIgnored(rel)) visit(abs)
309
+ continue
310
+ }
311
+ if (!ent.isFile() || !ent.name.endsWith('.kg.json') || !isIgnored(rel)) continue
312
+ const assetRel = rel.slice(0, -'.kg.json'.length)
313
+ // Nothing was refused if the asset is itself machine-local or absent, and
314
+ // Markdown never reads a sidecar in the first place.
315
+ if (assetRel.toLowerCase().endsWith('.md')) continue
316
+ if (isIgnored(assetRel) || !fs.existsSync(path.join(root, assetRel))) continue
317
+ found.push({ path: assetRel, sidecar: rel })
318
+ }
319
+ }
320
+ visit(root)
321
+ return found
322
+ }
323
+
324
+ // Deliberately NOT part of buildGraph's return value: that object is written
325
+ // verbatim to the graph artifact, so a machine-local observation inside it
326
+ // would make the artifact differ between a developer's tree and a clean
327
+ // checkout — the exact churn the ignore filter exists to prevent. The operator
328
+ // hears about the refusal; the shared artifact never does.
329
+ export function ignoredSidecarWarnings(project) {
330
+ const warnings = []
331
+ for (const repo of project.repos ?? []) {
332
+ if (repo.external || !repo.name || !repo.path || !fs.existsSync(repo.path)) continue
333
+ for (const found of findIgnoredSidecars(repo.path)) {
334
+ warnings.push({
335
+ severity: 'warning',
336
+ code: 'ignored-sidecar',
337
+ repo: repo.name,
338
+ path: found.path,
339
+ sidecar: found.sidecar,
340
+ message: `${repo.name}/${found.sidecar}: sidecar is git-ignored and was refused; it cannot enroll ${found.path} or describe it`,
341
+ })
342
+ }
343
+ }
344
+ return warnings
345
+ }
346
+
347
+ export function runGraphCommand(argv = process.argv.slice(2)) {
348
+ const check = argv.includes('--check')
349
+ const project = commandProject({ argv })
350
+ const graph = buildGraph(project)
351
+ for (const warning of ignoredSidecarWarnings(project)) console.warn(`warning: ${warning.message}`)
352
+ if (graph.errors.length) {
353
+ console.error(graph.errors.join('\n'))
354
+ process.exit(1)
355
+ }
356
+ if (check) {
357
+ const current = fs.existsSync(project.graphPath) ? fs.readFileSync(project.graphPath, 'utf8') : null
358
+ const next = `${JSON.stringify(graph, null, 2)}\n`
359
+ if (current !== next) {
360
+ console.error(`knowledge graph is stale: ${project.graphPath}`)
361
+ process.exit(1)
362
+ }
363
+ } else {
364
+ writeJson(project.graphPath, graph)
365
+ }
366
+ console.log(`knowledge graph: ${graph.counts.nodes} nodes · ${graph.counts.edges} edges · ${graph.counts.diagnostics} diagnostics`)
367
+ for (const repo of graph.external ?? []) {
368
+ console.log(`external repo (not walked): ${repo.name} → ${repo.remoteHost ?? 'no origin remote'}`)
369
+ }
370
+ }