@runeditrun/rer 0.2.83 → 0.2.85

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 (269) hide show
  1. package/README.md +21 -24
  2. package/cli/README.md +17 -1
  3. package/cli/authoring.mjs +1 -0
  4. package/cli/bounded.mjs +1 -1
  5. package/cli/business/carry.mjs +149 -0
  6. package/cli/business/command.mjs +6 -1
  7. package/cli/business/connect.mjs +1 -1
  8. package/cli/business/local-commands.mjs +2 -0
  9. package/cli/business/opt-ins.mjs +8 -4
  10. package/cli/business/questions.mjs +4 -1
  11. package/cli/business/state.mjs +1 -1
  12. package/cli/business/supervisor.mjs +7 -1
  13. package/cli/container-transfer.mjs +2 -2
  14. package/cli/contract.mjs +7 -7
  15. package/cli/demo-host.mjs +5 -1
  16. package/cli/demo-native.mjs +2 -1
  17. package/cli/demo.mjs +6 -1
  18. package/cli/deploy-command.mjs +6 -4
  19. package/cli/deploy.mjs +9 -7
  20. package/cli/errors.mjs +1 -1
  21. package/cli/export.mjs +1 -1
  22. package/cli/human-error.mjs +20 -0
  23. package/cli/lifecycle.mjs +23 -5
  24. package/cli/main.mjs +1 -1
  25. package/cli/managed-data-schema.mjs +114 -0
  26. package/cli/managed-data-zip.mjs +116 -0
  27. package/cli/managed-data.mjs +110 -0
  28. package/cli/managed-server.mjs +25 -14
  29. package/cli/native-owner-entry.mjs +86 -0
  30. package/cli/output.mjs +3 -2
  31. package/cli/parse.mjs +3 -3
  32. package/cli/portability-empty.mjs +59 -0
  33. package/cli/portability-migrations.mjs +7 -5
  34. package/cli/portability-policy.mjs +5 -2
  35. package/cli/portability-worker.mjs +15 -6
  36. package/cli/portability.mjs +30 -8
  37. package/cli/ready-summary.mjs +9 -0
  38. package/cli/run-transfers.mjs +37 -0
  39. package/cli/runtime-front-door.mjs +4 -4
  40. package/cli/server-proxy.mjs +4 -3
  41. package/cli/server-registry.mjs +13 -8
  42. package/cli/site.mjs +6 -1
  43. package/cli/transfers.mjs +17 -4
  44. package/edition-authoring/base-copies.mjs +125 -30
  45. package/edition-authoring/copy-checkout.mjs +7 -120
  46. package/edition-authoring/edition-migrations.mjs +41 -0
  47. package/edition-authoring/files.mjs +67 -0
  48. package/edition-authoring/lock.mjs +2 -2
  49. package/edition-authoring/module-closure.mjs +232 -0
  50. package/edition-authoring/module-edges.mjs +100 -0
  51. package/edition-authoring/module-resolution.mjs +66 -0
  52. package/edition-authoring/module-syntax.mjs +57 -0
  53. package/edition-authoring/package-target.mjs +92 -0
  54. package/edition-authoring/runtime-dependencies.mjs +74 -97
  55. package/edition-authoring/vendor/babel-parser/LICENSE +22 -0
  56. package/edition-authoring/vendor/babel-parser/README.md +21 -0
  57. package/edition-authoring/vendor/babel-parser/babel-helper-string-parser/index.mjs +292 -0
  58. package/edition-authoring/vendor/babel-parser/babel-helper-validator-identifier/identifier.mjs +66 -0
  59. package/edition-authoring/vendor/babel-parser/babel-helper-validator-identifier/index.mjs +13 -0
  60. package/edition-authoring/vendor/babel-parser/babel-helper-validator-identifier/keyword.mjs +31 -0
  61. package/edition-authoring/vendor/babel-parser/babel-parser/index.mjs +99 -0
  62. package/edition-authoring/vendor/babel-parser/babel-parser/options.mjs +81 -0
  63. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/bind-operator-errors.mjs +8 -0
  64. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/module-errors.mjs +15 -0
  65. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/parse-expression-errors.mjs +10 -0
  66. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/pipeline-operator-errors.mjs +29 -0
  67. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/standard-errors.mjs +224 -0
  68. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/strict-mode-errors.mjs +17 -0
  69. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/to-node-description.mjs +31 -0
  70. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error.mjs +114 -0
  71. package/edition-authoring/vendor/babel-parser/babel-parser/parser/base.mjs +34 -0
  72. package/edition-authoring/vendor/babel-parser/babel-parser/parser/comments.mjs +199 -0
  73. package/edition-authoring/vendor/babel-parser/babel-parser/parser/expression.mjs +1794 -0
  74. package/edition-authoring/vendor/babel-parser/babel-parser/parser/index.mjs +76 -0
  75. package/edition-authoring/vendor/babel-parser/babel-parser/parser/lval.mjs +439 -0
  76. package/edition-authoring/vendor/babel-parser/babel-parser/parser/node.mjs +111 -0
  77. package/edition-authoring/vendor/babel-parser/babel-parser/parser/statement.mjs +1962 -0
  78. package/edition-authoring/vendor/babel-parser/babel-parser/parser/util.mjs +244 -0
  79. package/edition-authoring/vendor/babel-parser/babel-parser/plugin-utils.mjs +116 -0
  80. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/estree.mjs +417 -0
  81. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/flow/index.mjs +2412 -0
  82. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/flow/scope.mjs +37 -0
  83. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/jsx/index.mjs +420 -0
  84. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/jsx/xhtml.mjs +261 -0
  85. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/placeholders.mjs +205 -0
  86. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/typescript/index.mjs +2889 -0
  87. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/typescript/scope.mjs +115 -0
  88. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/v8intrinsic.mjs +26 -0
  89. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/context.mjs +22 -0
  90. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/index.mjs +1037 -0
  91. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/state.mjs +178 -0
  92. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/types.mjs +583 -0
  93. package/edition-authoring/vendor/babel-parser/babel-parser/types.mjs +1 -0
  94. package/edition-authoring/vendor/babel-parser/babel-parser/util/class-scope.mjs +82 -0
  95. package/edition-authoring/vendor/babel-parser/babel-parser/util/expression-scope.mjs +121 -0
  96. package/edition-authoring/vendor/babel-parser/babel-parser/util/identifier.mjs +23 -0
  97. package/edition-authoring/vendor/babel-parser/babel-parser/util/location.mjs +34 -0
  98. package/edition-authoring/vendor/babel-parser/babel-parser/util/production-parameter.mjs +40 -0
  99. package/edition-authoring/vendor/babel-parser/babel-parser/util/scope.mjs +173 -0
  100. package/edition-authoring/vendor/babel-parser/babel-parser/util/scopeflags.mjs +66 -0
  101. package/edition-authoring/vendor/babel-parser/babel-parser/util/whitespace.mjs +61 -0
  102. package/edition-authoring/vendor/yaml/LICENSE +13 -0
  103. package/edition-authoring/vendor/yaml/README.md +11 -0
  104. package/edition-authoring/vendor/yaml/compose/compose-collection.mjs +88 -0
  105. package/edition-authoring/vendor/yaml/compose/compose-doc.mjs +43 -0
  106. package/edition-authoring/vendor/yaml/compose/compose-node.mjs +110 -0
  107. package/edition-authoring/vendor/yaml/compose/compose-scalar.mjs +86 -0
  108. package/edition-authoring/vendor/yaml/compose/composer.mjs +218 -0
  109. package/edition-authoring/vendor/yaml/compose/resolve-block-map.mjs +115 -0
  110. package/edition-authoring/vendor/yaml/compose/resolve-block-scalar.mjs +198 -0
  111. package/edition-authoring/vendor/yaml/compose/resolve-block-seq.mjs +49 -0
  112. package/edition-authoring/vendor/yaml/compose/resolve-end.mjs +37 -0
  113. package/edition-authoring/vendor/yaml/compose/resolve-flow-collection.mjs +207 -0
  114. package/edition-authoring/vendor/yaml/compose/resolve-flow-scalar.mjs +228 -0
  115. package/edition-authoring/vendor/yaml/compose/resolve-props.mjs +148 -0
  116. package/edition-authoring/vendor/yaml/compose/util-contains-newline.mjs +34 -0
  117. package/edition-authoring/vendor/yaml/compose/util-empty-scalar-position.mjs +27 -0
  118. package/edition-authoring/vendor/yaml/compose/util-flow-indent-check.mjs +15 -0
  119. package/edition-authoring/vendor/yaml/compose/util-map-includes.mjs +13 -0
  120. package/edition-authoring/vendor/yaml/doc/Document.mjs +333 -0
  121. package/edition-authoring/vendor/yaml/doc/anchors.mjs +74 -0
  122. package/edition-authoring/vendor/yaml/doc/applyReviver.mjs +54 -0
  123. package/edition-authoring/vendor/yaml/doc/createNode.mjs +88 -0
  124. package/edition-authoring/vendor/yaml/doc/directives.mjs +176 -0
  125. package/edition-authoring/vendor/yaml/errors.mjs +57 -0
  126. package/edition-authoring/vendor/yaml/index.mjs +17 -0
  127. package/edition-authoring/vendor/yaml/log.mjs +11 -0
  128. package/edition-authoring/vendor/yaml/nodes/Alias.mjs +119 -0
  129. package/edition-authoring/vendor/yaml/nodes/Collection.mjs +147 -0
  130. package/edition-authoring/vendor/yaml/nodes/Node.mjs +38 -0
  131. package/edition-authoring/vendor/yaml/nodes/Pair.mjs +36 -0
  132. package/edition-authoring/vendor/yaml/nodes/Scalar.mjs +24 -0
  133. package/edition-authoring/vendor/yaml/nodes/YAMLMap.mjs +144 -0
  134. package/edition-authoring/vendor/yaml/nodes/YAMLSeq.mjs +113 -0
  135. package/edition-authoring/vendor/yaml/nodes/addPairToJSMap.mjs +62 -0
  136. package/edition-authoring/vendor/yaml/nodes/identity.mjs +36 -0
  137. package/edition-authoring/vendor/yaml/nodes/toJS.mjs +35 -0
  138. package/edition-authoring/vendor/yaml/parse/cst-scalar.mjs +214 -0
  139. package/edition-authoring/vendor/yaml/parse/cst-stringify.mjs +61 -0
  140. package/edition-authoring/vendor/yaml/parse/cst-visit.mjs +97 -0
  141. package/edition-authoring/vendor/yaml/parse/cst.mjs +98 -0
  142. package/edition-authoring/vendor/yaml/parse/lexer.mjs +722 -0
  143. package/edition-authoring/vendor/yaml/parse/line-counter.mjs +39 -0
  144. package/edition-authoring/vendor/yaml/parse/parser.mjs +975 -0
  145. package/edition-authoring/vendor/yaml/public-api.mjs +102 -0
  146. package/edition-authoring/vendor/yaml/schema/Schema.mjs +37 -0
  147. package/edition-authoring/vendor/yaml/schema/common/map.mjs +17 -0
  148. package/edition-authoring/vendor/yaml/schema/common/null.mjs +15 -0
  149. package/edition-authoring/vendor/yaml/schema/common/seq.mjs +17 -0
  150. package/edition-authoring/vendor/yaml/schema/common/string.mjs +14 -0
  151. package/edition-authoring/vendor/yaml/schema/core/bool.mjs +19 -0
  152. package/edition-authoring/vendor/yaml/schema/core/float.mjs +43 -0
  153. package/edition-authoring/vendor/yaml/schema/core/int.mjs +38 -0
  154. package/edition-authoring/vendor/yaml/schema/core/schema.mjs +23 -0
  155. package/edition-authoring/vendor/yaml/schema/json/schema.mjs +62 -0
  156. package/edition-authoring/vendor/yaml/schema/tags.mjs +96 -0
  157. package/edition-authoring/vendor/yaml/schema/yaml-1.1/binary.mjs +59 -0
  158. package/edition-authoring/vendor/yaml/schema/yaml-1.1/bool.mjs +26 -0
  159. package/edition-authoring/vendor/yaml/schema/yaml-1.1/float.mjs +46 -0
  160. package/edition-authoring/vendor/yaml/schema/yaml-1.1/int.mjs +71 -0
  161. package/edition-authoring/vendor/yaml/schema/yaml-1.1/merge.mjs +67 -0
  162. package/edition-authoring/vendor/yaml/schema/yaml-1.1/omap.mjs +74 -0
  163. package/edition-authoring/vendor/yaml/schema/yaml-1.1/pairs.mjs +78 -0
  164. package/edition-authoring/vendor/yaml/schema/yaml-1.1/schema.mjs +39 -0
  165. package/edition-authoring/vendor/yaml/schema/yaml-1.1/set.mjs +93 -0
  166. package/edition-authoring/vendor/yaml/schema/yaml-1.1/timestamp.mjs +101 -0
  167. package/edition-authoring/vendor/yaml/stringify/foldFlowLines.mjs +146 -0
  168. package/edition-authoring/vendor/yaml/stringify/stringify.mjs +130 -0
  169. package/edition-authoring/vendor/yaml/stringify/stringifyCollection.mjs +155 -0
  170. package/edition-authoring/vendor/yaml/stringify/stringifyComment.mjs +20 -0
  171. package/edition-authoring/vendor/yaml/stringify/stringifyDocument.mjs +85 -0
  172. package/edition-authoring/vendor/yaml/stringify/stringifyNumber.mjs +25 -0
  173. package/edition-authoring/vendor/yaml/stringify/stringifyPair.mjs +150 -0
  174. package/edition-authoring/vendor/yaml/stringify/stringifyString.mjs +338 -0
  175. package/edition-authoring/vendor/yaml/util.mjs +11 -0
  176. package/edition-authoring/vendor/yaml/visit.mjs +233 -0
  177. package/edition-authoring/workflow-copies.mjs +125 -0
  178. package/edition-authoring/workflow-scripts.mjs +112 -0
  179. package/foundation/runtime/contract-docs.mjs +754 -0
  180. package/foundation/runtime/run-data.d.mts +1 -0
  181. package/foundation/runtime/run-data.mjs +2 -0
  182. package/global/CHANGELOG.md +55 -3
  183. package/global/README.md +21 -24
  184. package/global/cli/command.mjs +8 -2
  185. package/global/cli/install.mjs +4 -5
  186. package/global/cli/path-link.mjs +3 -2
  187. package/global/cli/repo-command.mjs +3 -7
  188. package/global/launch/dev.mjs +12 -2
  189. package/global/launch/facts.mjs +2 -2
  190. package/global/launch/render.mjs +16 -9
  191. package/global/launch/state.mjs +4 -4
  192. package/global/main.mjs +12 -7
  193. package/install.sh +17 -6
  194. package/modules/container/README.md +6 -1
  195. package/modules/container/adapters/d1-limits.mjs +286 -0
  196. package/modules/container/adapters/d1-sqlite.mjs +95 -0
  197. package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
  198. package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
  199. package/modules/container/adapters/d1-workerd.mjs +5 -0
  200. package/modules/container/adapters/sqlite-worker.mjs +5 -3
  201. package/modules/container/build.mjs +1 -0
  202. package/modules/container/image-variables.mjs +8 -3
  203. package/modules/container/transfer.mjs +14 -4
  204. package/modules/container/worker-engine.mjs +3 -3
  205. package/modules/demo/declaration.mjs +1 -4
  206. package/modules/demo/vite.mjs +1 -1
  207. package/modules/demo-host/build.mjs +1 -0
  208. package/modules/demo-host/native/prepare.mjs +2 -1
  209. package/modules/demo-host/native/sql.mjs +7 -2
  210. package/modules/deploy-kit/README.md +23 -3
  211. package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
  212. package/modules/deploy-kit/d1-import.mjs +17 -5
  213. package/modules/deploy-kit/diagnostics.mjs +29 -3
  214. package/modules/deploy-kit/owner-cli.mjs +20 -7
  215. package/modules/deploy-kit/provider-transport.mjs +19 -4
  216. package/modules/deploy-kit/provider.mjs +57 -22
  217. package/modules/deploy-kit/readiness-window.mjs +1 -1
  218. package/modules/deploy-kit/site.mjs +8 -3
  219. package/modules/deploy-kit/templates.mjs +3 -3
  220. package/modules/deploy-kit/worker.mjs +4 -4
  221. package/modules/import-kit/src/d1/README.md +23 -4
  222. package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
  223. package/modules/import-kit/src/d1/budget.ts +15 -7
  224. package/modules/import-kit/src/d1/column-layout.ts +5 -0
  225. package/modules/import-kit/src/d1/creation.ts +15 -8
  226. package/modules/import-kit/src/d1/database.ts +3 -3
  227. package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
  228. package/modules/import-kit/src/d1/erasure.ts +2 -2
  229. package/modules/import-kit/src/d1/jobs.ts +10 -6
  230. package/modules/import-kit/src/d1/plans.ts +14 -8
  231. package/modules/import-kit/src/d1/retirement.ts +2 -2
  232. package/modules/import-kit/src/d1/sets.ts +1 -3
  233. package/modules/import-kit/src/d1/staged-creation.ts +3 -3
  234. package/modules/import-kit/src/door/limits.ts +1 -1
  235. package/modules/import-kit/src/door/refusals.ts +1 -1
  236. package/modules/portability/README.md +112 -4
  237. package/modules/portability/backfills.mjs +9 -8
  238. package/modules/portability/bridge.mjs +12 -5
  239. package/modules/portability/catalogue.mjs +12 -5
  240. package/modules/portability/files.mjs +4 -3
  241. package/modules/portability/http.mjs +3 -3
  242. package/modules/portability/import.mjs +18 -9
  243. package/modules/portability/index.d.mts +4 -3
  244. package/modules/portability/index.mjs +1 -1
  245. package/modules/portability/ledgers.mjs +3 -2
  246. package/modules/portability/legacy-safety.mjs +11 -2
  247. package/modules/portability/migration-history.mjs +2 -2
  248. package/modules/portability/progress.mjs +1 -0
  249. package/modules/portability/restore-empty.mjs +12 -0
  250. package/modules/release/github-verify.mjs +11 -2
  251. package/onboarding/adapter.mjs +35 -6
  252. package/onboarding/app-fetch.mjs +6 -4
  253. package/onboarding/development-runtime.mjs +19 -0
  254. package/onboarding/local/operation.mjs +45 -27
  255. package/onboarding/loopback-fetch.mjs +16 -0
  256. package/onboarding/operator-installer.mjs +4 -6
  257. package/onboarding/process-diagnostics.mjs +6 -2
  258. package/onboarding/production-runtime.mjs +4 -2
  259. package/onboarding/readiness.mjs +1 -0
  260. package/package.json +1 -1
  261. package/scripts/publish-check/README.md +6 -0
  262. package/scripts/publish-check/history_scan.py +5 -3
  263. package/scripts/publish-check/hygiene_config.py +2 -1
  264. package/scripts/publish-check/public_hygiene.py +1 -1
  265. package/scripts/publish-check/report.py +9 -3
  266. package/scripts/publish-check/third-party-notices.json +13 -0
  267. package/scripts/publish-check/third_party_notices.py +38 -0
  268. package/scripts/publish-check/tree_scan.py +6 -0
  269. package/scripts/publish-check.mjs +1 -1
@@ -0,0 +1,754 @@
1
+ #!/usr/bin/env node
2
+ // Kept beside seed-contract so a recorded copy runs without an installation.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { execFileSync } from 'node:child_process'
6
+ import { parseContract, clauseIdSource, plainText } from './seed-contract.mjs'
7
+
8
+ const marker = '<!-- Generated from CONTRACT.md by contract-docs. Edit CONTRACT.md, then regenerate. -->'
9
+ const idPattern = new RegExp(`^${clauseIdSource}$`)
10
+ const read = name => fs.existsSync(name) ? fs.readFileSync(name, 'utf8') : undefined
11
+ const put = (name, text) => { fs.mkdirSync(path.dirname(name), { recursive: true }); fs.writeFileSync(name, text) }
12
+ const git = args => execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 })
13
+ const json = value => JSON.stringify(value, null, 2) + '\n'
14
+ const linesOf = text => text.replace(/\r\n?/g, '\n').split('\n')
15
+ const cells = line => line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '').split(/(?<!\\)\|/).map(cell => cell.trim())
16
+ const divider = line => /^\|?(\s*:?-{3,}:?\s*\|)+\s*:?-{0,}:?\s*$/.test(line.trim())
17
+ const idsIn = text => [...text.matchAll(new RegExp(`(?<![A-Za-z0-9.-])(${clauseIdSource})(?![A-Za-z0-9.-])`, 'g'))].map(match => match[1])
18
+ const block = text => text.replace(/^\s*\n|\n\s*$/g, '').trim()
19
+ function outline(text) {
20
+ const lines = linesOf(text), entries = []
21
+ let fence
22
+ lines.forEach((line, index) => {
23
+ const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1]
24
+ if (mark) { if (!fence) fence = mark[0]; else if (fence === mark[0]) fence = undefined; return }
25
+ if (fence) return
26
+ const match = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line)
27
+ if (match) entries.push({ level: match[1].length, title: plainText(match[2]), start: index })
28
+ })
29
+ return entries.map(entry => ({ ...entry, end: entries.find(next => next.start > entry.start && next.level <= entry.level)?.start ?? lines.length }))
30
+ }
31
+ function section(text, name) {
32
+ const entry = outline(text).find(item => item.level === 2 && (item.title === name || (name === 'Product target' && /^Product target\b/.test(item.title))))
33
+ return entry ? block(linesOf(text).slice(entry.start + 1, entry.end).join('\n')) : ''
34
+ }
35
+ function snapshot(reference) {
36
+ if (!reference || reference.startsWith('-')) throw Error('Name an old Git reference or a tracked contract file.')
37
+ let commit, contract
38
+ if (fs.existsSync(reference) && fs.statSync(reference).isFile()) {
39
+ const relative = path.relative(process.cwd(), path.resolve(reference)).split(path.sep).join('/')
40
+ if (relative.startsWith('../') || path.isAbsolute(relative)) throw Error('An old contract file must be tracked in this checkout; otherwise use its Git reference.')
41
+ commit = git(['log', '-1', '--format=%H', '--', relative]).trim()
42
+ if (!commit) throw Error(`No commit records ${reference}; use a Git reference.`)
43
+ contract = read(reference)
44
+ if (git(['show', `${commit}:${relative}`]) !== contract) throw Error(`${reference} has uncommitted bytes; use a recorded old contract.`)
45
+ } else commit = git(['rev-parse', '--verify', '--end-of-options', `${reference}^{commit}`]).trim()
46
+ if (!/^[0-9a-f]{40}$/.test(commit)) throw Error(`Cannot resolve ${reference} to a full commit.`)
47
+ const names = new Set(git(['ls-tree', '-r', '--name-only', commit]).trim().split('\n'))
48
+ const files = {}
49
+ for (const name of ['CONTRACT.md', 'ACCEPTANCE.md', 'docs/CLAIMS.md', 'CLAIMS.md'])
50
+ if (names.has(name)) files[name] = git(['show', `${commit}:${name}`])
51
+ if (contract !== undefined) files['CONTRACT.md'] = contract
52
+ if (!files['CONTRACT.md']) throw Error(`${reference} has no CONTRACT.md.`)
53
+ return { commit, files }
54
+ }
55
+ function summaryRange(text) {
56
+ const lines = linesOf(text), start = lines.findIndex(line => cells(line).join('|') === 'Clauses|Done|Partial|Missing|Total')
57
+ if (start < 0) return undefined
58
+ let end = start + 2
59
+ while (lines[end]?.trimStart().startsWith('|')) end++
60
+ return { start, end }
61
+ }
62
+ function withoutSummary(text) {
63
+ const range = summaryRange(text)
64
+ if (!range) return text
65
+ const lines = linesOf(text)
66
+ lines.splice(range.start, range.end - range.start)
67
+ return lines.join('\n')
68
+ }
69
+ const tally = clauses => ({ done: clauses.filter(c => c.status === 'done').length, partial: clauses.filter(c => c.status === 'partial').length, missing: clauses.filter(c => c.status === 'missing').length, total: clauses.length })
70
+ const countRow = (label, clauses) => `| ${label} | ${Object.values(tally(clauses)).join(' | ')} |`
71
+ function withSummary(text, contract) {
72
+ const range = summaryRange(text)
73
+ const rows = [countRow('Published', contract.clauses.filter(c => c.kind === 'published')), countRow('Target and push further', contract.clauses.filter(c => c.kind !== 'published')), countRow('All', contract.clauses)]
74
+ if (!range) throw Error('CONTRACT.md needs the Status summary table; run convert for a legacy contract.')
75
+ // Only the summary's rows are replaced; all other bytes, including CRLF, stay.
76
+ const raw = text.split(/(?<=\n)/), newline = raw[range.start]?.endsWith('\r\n') ? '\r\n' : '\n'
77
+ raw.splice(range.start + 2, range.end - range.start - 2, ...rows.map(row => row + newline))
78
+ return raw.join('')
79
+ }
80
+ function metaLine(text) {
81
+ const meta = {}
82
+ for (const match of text.matchAll(/\*(Tier|From|Cites|Rules|Register):\*\s*([^·\n]+)/g)) meta[match[1]] = match[2].trim()
83
+ return meta
84
+ }
85
+ function entries(text, parsed) {
86
+ const lines = linesOf(text), headings = outline(text)
87
+ const published = section(text, 'Published clauses').split(/^### /m)[0]
88
+ return [...parsed.clauses].sort((a, b) => a.line - b.line).map(clause => {
89
+ if (!lines[clause.line - 1].startsWith('#### ')) throw Error(`CONTRACT.md:${clause.line}: ${clause.id} needs a level-four clause heading; run convert.`)
90
+ const end = headings.find(item => item.start >= clause.line)?.start ?? lines.length
91
+ let body = block(lines.slice(clause.line, end).join('\n'))
92
+ const metaText = clause.kind === 'published' ? published.split('\n').find(line => line.startsWith(`- \`${clause.id}\`:`)) : body.split('\n')[0]
93
+ const meta = metaLine(metaText ?? '')
94
+ if (!['Core', 'Agent surface', 'Later'].includes(meta.Tier)) throw Error(`CONTRACT.md:${clause.line}: ${clause.id} needs a Tier in its ${clause.kind === 'published' ? 'Published clauses list' : 'meta line'}.`)
95
+ if (clause.kind !== 'published') body = block(body.slice(body.indexOf('\n') + 1))
96
+ if (!body.startsWith('**Requirement.**')) throw Error(`CONTRACT.md:${clause.line}: ${clause.id} body must start **Requirement.**.`)
97
+ const row = cells(lines[clause.row - 1])
98
+ return { ...clause, meta, body, evidenceCell: row[4], gapCell: row[5] }
99
+ })
100
+ }
101
+ function seedName(text) {
102
+ return /^#\s+(.+?)\s*$/m.exec(text)?.[1].replace(/\s+target product contract$/i, '').replace(/\s+contract$/i, '') ?? 'Seed'
103
+ }
104
+ function generatedFiles(text) {
105
+ const initial = parseContract(withoutSummary(text)), rewritten = withSummary(text, initial)
106
+ const parsed = parseContract(rewritten), clauses = entries(rewritten, parsed), seed = seedName(text)
107
+ const target = section(text, 'Product target')
108
+ const journey = target.split('\n').find(line => /^The primary journey:/.test(line))
109
+ if (!journey) throw Error('CONTRACT.md: Product target needs "The primary journey:".')
110
+ const register = section(text, 'Field proof register')
111
+ if (!register) throw Error('CONTRACT.md needs a Field proof register section.')
112
+ const registerRows = register.split('\n').filter(line => /^R-\d+$/.test(plainText(cells(line)[0] ?? ''))).map(line => cells(line))
113
+ const registerCount = state => registerRows.filter(row => row[3] === state).length
114
+ const judged = section(text, 'Status').split('\n').find(line => line.startsWith('Judged from'))
115
+ const acceptance = [marker, `# Accept a ${seed} installation`, journey, '## Progress', [
116
+ '| Tier | Done | Partial | Missing | Total |', '| --- | ---: | ---: | ---: | ---: |',
117
+ ...['Core', 'Agent surface', 'Later'].map(tier => countRow(tier, clauses.filter(clause => clause.meta.Tier === tier))), countRow('Full target', clauses),
118
+ ].join('\n'), `${judged} Field proof register: ${registerRows.length} rows; ${registerCount('passed')} passed, ${registerCount('failed')} failed, ${registerCount('not run')} not run.`]
119
+ for (const tier of ['Core', 'Agent surface', 'Later']) {
120
+ acceptance.push(`## ${tier}`)
121
+ const selected = clauses.filter(clause => clause.meta.Tier === tier)
122
+ if (!selected.length) acceptance.push('None.')
123
+ let area
124
+ for (const clause of selected) {
125
+ if (clause.area !== area) { area = clause.area; acceptance.push(`### ${area}`) }
126
+ acceptance.push(`#### ${clause.id} — ${clause.title}`)
127
+ const info = [tier, clause.kind, `**${clause.status}**`]
128
+ for (const field of ['From', 'Cites', 'Rules', 'Register']) if (clause.meta[field]) info.push(`${field} ${clause.meta[field].split(/\s*,\s*/).join(', ')}`)
129
+ acceptance.push(info.join(' · '), clause.body, `**Evidence.** ${clause.evidenceCell || 'None.'}\n**Gap.** ${clause.gapCell || 'None.'}`)
130
+ }
131
+ }
132
+ acceptance.push('## Field proof register', register)
133
+ const tables = homepageClaims(text), rows = tables.flatMap(table => table.rows.map(row => ({ ...row, header: table.header })))
134
+ const claims = [marker, `# ${seed} homepage claims`]
135
+ if (!rows.length) claims.push('No homepage claims are mapped yet.')
136
+ else {
137
+ claims.push('A claim is done when every clause behind it is done, missing when every one is missing, and partial otherwise.')
138
+ const hasSection = rows.some(row => row.header.some(cell => /^Section$/i.test(plainText(cell))))
139
+ const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', 'Status']
140
+ const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], counts = { done: 0, partial: 0, missing: 0 }
141
+ for (const [index, row] of rows.entries()) {
142
+ const value = label => row.cells[row.header.findIndex(cell => new RegExp(`^${label}$`, 'i').test(plainText(cell).replace('(s)', 's')))] ?? ''
143
+ const ids = idsIn(value('Clauses?')), linked = ids.map(id => clauses.find(clause => clause.id === id))
144
+ if (!ids.length || linked.some(clause => !clause)) throw Error(`CONTRACT.md:${row.line}: Homepage claim needs existing clause ids.`)
145
+ const state = linked.every(clause => clause.status === 'done') ? 'done' : linked.every(clause => clause.status === 'missing') ? 'missing' : 'partial'
146
+ counts[state]++
147
+ table.push(`| ${[value('#') || String(index + 1), ...(hasSection ? [value('Section')] : []), value('Claim'), linked.map(clause => `\`${clause.id}\` ${clause.status}`).join('; '), state].join(' | ')} |`)
148
+ }
149
+ claims.push(table.join('\n'), `Claims: ${rows.length}; ${counts.done} done, ${counts.partial} partial, ${counts.missing} missing.`)
150
+ }
151
+ return { 'CONTRACT.md': rewritten, 'ACCEPTANCE.md': acceptance.join('\n\n') + '\n', 'docs/CLAIMS.md': claims.join('\n\n') + '\n' }
152
+ }
153
+ function generate(check = false) {
154
+ const text = read('CONTRACT.md')
155
+ if (text === undefined) throw Error('CONTRACT.md does not exist.')
156
+ const files = generatedFiles(text), changed = Object.entries(files).filter(([name, contents]) => read(name) !== contents)
157
+ if (check && changed.length) throw Error(changed.map(([name]) => `${name}: generated content differs; run contract-docs write.`).join('\n'))
158
+ if (!check) for (const [name, contents] of changed) put(name, contents)
159
+ console.log(check ? 'Contract documents are current.' : `Wrote ${changed.length} contract documents.`)
160
+ }
161
+
162
+ // Lineage is derived from From and Retired clauses; old text never supplies a new answer.
163
+ function retiredRows(text) {
164
+ return section(text, 'Retired clauses').split('\n').filter(line => line.trimStart().startsWith('|') && !divider(line)).map(line => cells(line)).filter(row => idPattern.test(plainText(row[0] ?? ''))).map(([id, now, reason]) => ({ id: plainText(id), now, reason }))
165
+ }
166
+ function idParts(id) {
167
+ const match = /^(.*?)(\d+)$/.exec(id)
168
+ return match && { prefix: match[1], width: match[2].length, number: Number(match[2]) }
169
+ }
170
+ function buildIdMap(old, text = read('CONTRACT.md')) {
171
+ const previous = parseContract(old.files['CONTRACT.md']), current = parseContract(withoutSummary(text)), clauses = entries(text, current)
172
+ const oldIds = new Set(previous.clauses.map(clause => clause.id)), kept = new Set(clauses.map(clause => clause.id)), retired = retiredRows(text), problems = [], sources = new Map()
173
+ const oldRetired = new Set(retiredRows(old.files['CONTRACT.md']).map(row => row.id))
174
+ const oldLines = linesOf(old.files['CONTRACT.md']), used = new Set(oldIds)
175
+ for (const clause of previous.clauses) for (const id of idsIn(oldLines[clause.line - 1])) used.add(id)
176
+ for (const entry of outline(old.files['CONTRACT.md']).filter(entry => /^(Retired|Superseded)\b/i.test(entry.title)))
177
+ for (const id of idsIn(oldLines.slice(entry.start, entry.end).join('\n'))) { used.add(id); oldRetired.add(id) }
178
+ for (const id of oldIds) oldRetired.delete(id)
179
+ for (const row of retired) {
180
+ if (!row.reason?.trim()) problems.push(`${row.id}: Retired reason is empty.`)
181
+ if (retired.filter(other => other.id === row.id).length > 1) problems.push(`${row.id}: duplicate Retired row.`)
182
+ if (kept.has(row.id)) problems.push(`${row.id}: retired id is reused as a clause.`)
183
+ const merges = [...row.now.matchAll(/merged into\s+([^;]+)/g)]
184
+ if (merges.length > 1 || merges.some(match => idsIn(match[1]).length !== 1 || plainText(match[1]).trim() !== idsIn(match[1])[0])) problems.push(`${row.id}: merged into must name exactly one clause.`)
185
+ for (const match of merges) for (const target of idsIn(match[1])) {
186
+ if (!kept.has(target)) problems.push(`${row.id}: merged destination ${target} does not exist.`)
187
+ }
188
+ for (const id of idsIn(row.id)) used.add(id)
189
+ }
190
+ const highest = new Map(), widths = new Map()
191
+ for (const id of used) {
192
+ const parts = idParts(id)
193
+ if (!parts) continue
194
+ highest.set(parts.prefix, Math.max(highest.get(parts.prefix) ?? 0, parts.number))
195
+ if (!widths.has(parts.prefix)) widths.set(parts.prefix, parts.width)
196
+ }
197
+ for (const clause of clauses) {
198
+ const from = clause.meta.From === undefined ? (oldIds.has(clause.id) ? [clause.id] : []) : clause.meta.From === 'new' ? [] : clause.meta.From.split(/\s*,\s*/)
199
+ if (clause.meta.From === undefined && !oldIds.has(clause.id)) problems.push(`${clause.id}: a new clause needs From new or its old source ids.`)
200
+ if (new Set(from).size !== from.length) problems.push(`${clause.id}: From repeats a source id.`)
201
+ for (const source of from) {
202
+ if (!idPattern.test(source) || !oldIds.has(source)) problems.push(`${clause.id}: From names ${source}, which the old Status table lacks.`)
203
+ if (!sources.has(source)) sources.set(source, [])
204
+ sources.get(source).push(clause.id)
205
+ }
206
+ if (oldIds.has(clause.id) && !from.includes(clause.id)) problems.push(`${clause.id}: a kept id's From omits itself.`)
207
+ if (oldRetired.has(clause.id)) problems.push(`${clause.id}: an old retired id is reused.`)
208
+ if (oldIds.has(clause.id)) continue
209
+ const parts = idParts(clause.id), width = widths.get(parts.prefix) ?? 3, next = (highest.get(parts.prefix) ?? 0) + 1
210
+ if (parts.width !== width || parts.number !== next) problems.push(`${clause.id}: new id is not the next free number; expected ${parts.prefix}${String(next).padStart(width, '0')}.`)
211
+ highest.set(parts.prefix, Math.max(highest.get(parts.prefix) ?? 0, parts.number)); widths.set(parts.prefix, width)
212
+ }
213
+ const ids = {}
214
+ for (const id of oldIds) {
215
+ const targets = sources.get(id) ?? [], retirement = retired.find(row => row.id === id)
216
+ if (targets.length >= 2) {
217
+ if (targets[0] !== id || retirement) problems.push(`${id}: text goes to multiple clauses; keep the old id as the first part of a split, never retire it.`)
218
+ ids[id] = { how: 'split', to: targets }
219
+ } else if (kept.has(id)) ids[id] = { how: 'kept', to: [id] }
220
+ else if (!retirement) problems.push(`${id}: old id is missing from both clauses and Retired clauses.`)
221
+ else {
222
+ const merged = /^merged into\s+(.+?)(?:;|$)/.exec(retirement.now), receiving = merged ? idsIn(merged[1]) : []
223
+ if (targets.length && (!merged || receiving[0] !== targets[0])) problems.push(`${id}: From destination and Retired destination disagree.`)
224
+ ids[id] = merged ? { how: 'merged', to: receiving } : { how: 'retired', to: [], now: retirement.now }
225
+ }
226
+ }
227
+ if (problems.length) throw Error(problems.join('\n'))
228
+ return { schema: 1, old: old.commit, ids }
229
+ }
230
+ function idMap(old) {
231
+ const map = buildIdMap(old)
232
+ put('docs/contract/ID-MAP.json', json(map))
233
+ console.log(`Mapped ${Object.keys(map.ids).length} old clause ids.`)
234
+ }
235
+
236
+ // Conversion preserves old source text while giving a rewrite a mechanical shape.
237
+ function oldClauseBody(text, clause) {
238
+ const lines = linesOf(text), start = clause.line - 1, first = lines[start]
239
+ const bold = /^(-\s+)?\*\*[^*]+\*\*\s*/.exec(first)
240
+ const body = [bold ? first.slice(bold[0].length) : '']
241
+ for (let index = start + 1; index < lines.length; index++) {
242
+ const line = lines[index]
243
+ if (/^#{1,6}\s/.test(line) || new RegExp(`^(?:-\\s+)?\\*\\*${clauseIdSource}\\s+[—–-]\\s+`).test(line)) break
244
+ if (bold?.[1] && line.trim() && !/^[ \t]/.test(line)) break
245
+ body.push(bold?.[1] ? line.replace(/^ {1,2}/, '') : line)
246
+ }
247
+ return block(body.join('\n'))
248
+ }
249
+ function acceptanceEntries(text, ids) {
250
+ const result = new Map(), lines = linesOf(text ?? '')
251
+ const definition = new RegExp(`^(?:#{1,6}\\s+|(?:-\\s+)?\\*\\*)(${clauseIdSource})\\s+[—–-]\\s+`)
252
+ for (let index = 0; index < lines.length; index++) {
253
+ const match = definition.exec(lines[index])
254
+ if (!match || !ids.has(match[1])) continue
255
+ const first = lines[index], boldEnd = first.indexOf('**', match[0].length)
256
+ let body = first.startsWith('#') ? [] : [boldEnd >= 0 ? first.slice(boldEnd + 2).trim() : '']
257
+ for (let next = index + 1; next < lines.length && !definition.test(lines[next]) && !/^#{1,6}\s/.test(lines[next]); next++) body.push(lines[next])
258
+ if (!result.has(match[1])) result.set(match[1], block(body.join('\n')))
259
+ }
260
+ return result
261
+ }
262
+ function requirementAndAcceptance(body, oldAcceptance) {
263
+ const history = [], status = /\*{1,2}Status:\*{1,2}\s*(?:done|partial|missing)\b/i.exec(body)
264
+ if (status) { history.push(body.slice(status.index)); body = body.slice(0, status.index).trim() }
265
+ const markerPattern = /(?:\*{1,2}Acceptance(?: evidence)?[:.]\*{1,2}|\*\*Acceptance\*\*[:.]?)/i
266
+ const acceptanceMarker = markerPattern.exec(body)
267
+ let requirement = acceptanceMarker ? block(body.slice(0, acceptanceMarker.index)) : body
268
+ let acceptance = acceptanceMarker ? block(body.slice(acceptanceMarker.index + acceptanceMarker[0].length)) : oldAcceptance
269
+ requirement = requirement.replace(/^\*\*Requirement[.:]\*\*\s*/, '').trim()
270
+ if (!requirement) throw Error('An old clause has no requirement prose to convert.')
271
+ const result = [`**Requirement.** ${requirement}`]
272
+ if (acceptance) {
273
+ acceptance = acceptance.replace(markerPattern, '').trim()
274
+ const numbered = /^1[.)]\s/m.test(acceptance)
275
+ if (numbered) result.push(`**Acceptance.**\n${acceptance}`)
276
+ else {
277
+ const sentences = acceptance.replace(/\n+/g, ' ').split(/(?<=[.!?])\s+(?=[A-Z0-9`*])/).filter(Boolean)
278
+ result.push('**Acceptance.**\n' + sentences.slice(0, 8).map((sentence, index) => `${index + 1}. ${index === 7 ? sentences.slice(7).join(' ') : sentence}`).join('\n'))
279
+ }
280
+ }
281
+ return { text: result.join('\n\n'), history }
282
+ }
283
+ function contractClaims(old) {
284
+ const candidates = Object.entries(old.files).filter(([name, text]) => name === 'CONTRACT.md' || /(?:^|\/)CLAIMS\.md$/.test(name) && !text.startsWith('<!-- Generated from CONTRACT.md by contract-docs.')).map(([name, text]) => ({ name, tables: homepageClaims(text) }))
285
+ const winner = candidates.sort((a, b) => b.tables.reduce((n, table) => n + table.rows.length, 0) - a.tables.reduce((n, table) => n + table.rows.length, 0))[0]
286
+ if (!winner?.tables.some(table => table.rows.length)) return 'No homepage claims are mapped yet.'
287
+ const rows = winner.tables.flatMap(table => table.rows.map(row => ({ ...row, header: table.header })))
288
+ const hasSection = rows.some(row => row.header.some(label => /^section$/i.test(plainText(label))))
289
+ const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses']
290
+ const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`]
291
+ for (const [index, row] of rows.entries()) {
292
+ const value = label => row.cells[row.header.findIndex(cell => new RegExp(`^${label}$`, 'i').test(plainText(cell).replace('(s)', 's')))] ?? ''
293
+ table.push(`| ${[value('#') || String(index + 1), ...(hasSection ? [value('Section')] : []), value('Claim'), value('Clauses?')].join(' | ')} |`)
294
+ }
295
+ return table.join('\n')
296
+ }
297
+ function convert(old, acceptanceOld) {
298
+ const text = old.files['CONTRACT.md'], parsed = parseContract(text), lines = linesOf(text), seed = seedName(text), ids = new Set(parsed.clauses.map(clause => clause.id))
299
+ const acceptanceSource = acceptanceOld?.files['ACCEPTANCE.md'] ?? old.files['ACCEPTANCE.md']
300
+ const acceptances = acceptanceEntries(acceptanceSource, ids)
301
+ const intro = block(lines.slice(1, lines.findIndex(line => /^##\s/.test(line))).join('\n')).split(/\n\s*\n/)[0]
302
+ let target = section(text, 'Product target')
303
+ if (!/^The primary journey:/m.test(target)) {
304
+ const journey = /^The primary journey(?: is)?:\s*(.+)$/m.exec(text)?.[1]
305
+ target += `\n\nThe primary journey: ${journey ?? 'Exercise the capabilities and acceptance journeys below.'}`
306
+ }
307
+ const output = [`# ${seed} target product contract`, intro, '## Product target', target, '## How to read this contract', [
308
+ '- This follows the RER contract standard.',
309
+ '- Core, Agent surface and Later are reported separately.',
310
+ '- Done means every acceptance point has recorded proof.',
311
+ '- Field proof is kept in its register.',
312
+ '- ACCEPTANCE.md and the homepage claims document are generated from this file.',
313
+ ].join('\n')]
314
+ const doors = section(text, 'Door rules')
315
+ if (doors) output.push('## Door rules', doors)
316
+ output.push('## Shared duties (Base)', '| Base duty | Duty | Delta clauses | Base journey |\n| --- | --- | --- | --- |')
317
+ const clauseContent = new Map(), extraHistory = []
318
+ for (const clause of parsed.clauses) {
319
+ const converted = requirementAndAcceptance(oldClauseBody(text, clause), acceptances.get(clause.id))
320
+ clauseContent.set(clause.id, converted.text)
321
+ extraHistory.push(...converted.history)
322
+ }
323
+ const areaNames = new Set()
324
+ for (const [kind, title] of [['published', 'Published clauses'], ['target', 'Target clauses'], ['push-further', 'Push further']]) {
325
+ const selected = [...parsed.clauses].filter(clause => clause.kind === kind).sort((a, b) => a.line - b.line)
326
+ if (!selected.length && kind === 'push-further') continue
327
+ output.push(`## ${title}`)
328
+ if (kind === 'published' && selected.length) output.push(selected.map(clause => `- \`${clause.id}\`: *Tier:* Core`).join('\n'))
329
+ const areas = [...new Set(selected.map(clause => clause.area))]
330
+ if (kind === 'target') { const agent = areas.indexOf('Agent surface'); if (agent >= 0) areas.splice(agent, 1); areas.push('Agent surface') }
331
+ for (const area of areas) {
332
+ let name = area
333
+ if (areaNames.has(name)) name = `${area} (${title.toLowerCase()})`
334
+ areaNames.add(name)
335
+ output.push(`### ${name}`)
336
+ if (area === 'Agent surface') output.push('Inherits BASE-AGENT-001 to BASE-AGENT-013. The company\'s policy decides every call.', '| Tool | Core clauses | Classes this call can carry |\n| --- | --- | --- |')
337
+ for (const clause of selected.filter(clause => clause.area === area)) {
338
+ output.push(`#### ${clause.id} — ${clause.title}`)
339
+ if (kind !== 'published') output.push('*Tier:* Core')
340
+ output.push(clauseContent.get(clause.id))
341
+ }
342
+ }
343
+ }
344
+ output.push('## Field proof register', 'No field proof is recorded yet.', '## Boundaries', section(text, 'Boundaries') || section(text, 'Honest boundaries') || section(text, 'Honest boundaries and delivery responsibilities') || 'No additional boundaries are recorded.', '## Homepage claims', contractClaims(old))
345
+ const retired = outline(text).filter(entry => entry.level === 2 && /^Retired\b/i.test(entry.title))
346
+ if (retired.length) {
347
+ const contents = retired.map(entry => block(lines.slice(entry.start + 1, entry.end).join('\n'))).join('\n\n')
348
+ output.push('## Retired clauses', contents)
349
+ }
350
+ const statusText = section(text, 'Status'), statusLines = linesOf(statusText), table = statusLines.findIndex(line => cells(line).join('|') === 'Clause|Title|Kind|Status|Evidence|Gap')
351
+ const judged = statusLines.find(line => line.startsWith('Judged from'))
352
+ const rows = []
353
+ for (let index = table + 2; index < statusLines.length && statusLines[index].trimStart().startsWith('|'); index++) {
354
+ rows.push(statusLines[index].replace(/^(\s*\|\s*)`?([^`| ]+)`?(\s*\|)/, '$1`$2`$3'))
355
+ }
356
+ output.push('## Status', judged, '| Clauses | Done | Partial | Missing | Total |\n| --- | ---: | ---: | ---: | ---: |\n' + [countRow('Published', parsed.clauses.filter(c => c.kind === 'published')), countRow('Target and push further', parsed.clauses.filter(c => c.kind !== 'published')), countRow('All', parsed.clauses)].join('\n'), [statusLines[table], statusLines[table + 1], ...rows].join('\n'))
357
+ const contract = output.join('\n\n') + '\n'
358
+ // Validate all generated output and lineage before changing the source files.
359
+ const generated = generatedFiles(contract), mapping = buildIdMap(old, contract)
360
+ const history = [read('CHANGELOG.md')?.trim() || '# Changelog', `## Contract source before ${old.commit}`, text.trim(), ...extraHistory]
361
+ for (const [name, contents] of Object.entries(old.files)) if (/(?:^|\/)CLAIMS\.md$/.test(name) && !contents.startsWith('<!-- Generated from CONTRACT.md by contract-docs.')) history.push(`### ${name}`, contents.trim())
362
+ put('CHANGELOG.md', history.join('\n\n') + '\n')
363
+ if (acceptanceSource && !acceptanceSource.startsWith('<!-- Generated from CONTRACT.md by contract-docs.')) put('docs/verify.md', acceptanceSource.trim() + '\n')
364
+ for (const [name, contents] of Object.entries(generated)) put(name, contents)
365
+ fs.rmSync('CLAIMS.md', { force: true })
366
+ coverageInit(old)
367
+ put('docs/contract/ID-MAP.json', json(mapping))
368
+ generate()
369
+ console.log(`Converted ${parsed.clauses.length} clauses; ${parsed.counts.done} done, ${parsed.counts.partial} partial, ${parsed.counts.missing} missing.`)
370
+ }
371
+ // Coverage tracks the original lines independently of the rewritten layout.
372
+ const covSections = new Set(['Product target', 'How to read this contract', 'How to read', 'Door rules', 'Boundaries', 'Homepage claims', 'Status']);
373
+ const covNames = ['CONTRACT.md', 'ACCEPTANCE.md', 'docs/CLAIMS.md', 'CLAIMS.md'];
374
+ const covMapPath = 'docs/contract/COVERAGE.json';
375
+ const covId = new RegExp(`^${clauseIdSource}$`);
376
+ const covHeading = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
377
+ const covDefinition = new RegExp(`^(?:#{1,6}\\s+|(?:[-*+]\\s+)?\\*\\*)(${clauseIdSource})\\s+[—–-]\\s+`);
378
+ const covSplit = text => text.replace(/\r\n?/g, '\n').split('\n');
379
+ const covGenerated = text => /^\uFEFF?<!-- Generated from CONTRACT\.md by contract-docs\./.test(covSplit(text)[0]);
380
+ const covNormalize = text => typeof text === 'string' ? text.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, '').replace(/[`*_]/g, '').replace(/\s+/gu, '') : '';
381
+ const covKey = entry => JSON.stringify([entry.file, entry.line, entry.cell ?? '']);
382
+ const covLabel = entry => `${entry.file}:${entry.line}${entry.cell ? ` (${entry.cell})` : ''}`;
383
+
384
+ function covCells(text) {
385
+ const body = text.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '');
386
+ return body.split(/(?<!\\)\|/).map(cell => cell.trim().replace(/\\\|/g, '|'));
387
+ }
388
+ function covDivider(text) {
389
+ return text.includes('|') && covCells(text).every(cell => /^:?-{3,}:?$/.test(cell));
390
+ }
391
+ function covVisibleLines(text) {
392
+ let comment = false;
393
+ return covSplit(text).map(raw => {
394
+ let visible = '', at = 0;
395
+ while (at < raw.length) {
396
+ if (comment) {
397
+ const end = raw.indexOf('-->', at);
398
+ if (end < 0) break;
399
+ at = end + 3;
400
+ comment = false;
401
+ } else {
402
+ const start = raw.indexOf('<!--', at);
403
+ if (start < 0) { visible += raw.slice(at); break; }
404
+ visible += raw.slice(at, start);
405
+ at = start + 4;
406
+ comment = true;
407
+ }
408
+ }
409
+ return { raw, text: visible };
410
+ });
411
+ }
412
+ function covFence(line, current) {
413
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
414
+ if (!marker) return { current, marker: false };
415
+ if (!current) return { current: marker, marker: true };
416
+ if (marker[0] === current[0] && marker.length >= current.length) return { current: undefined, marker: true };
417
+ return { current, marker: false };
418
+ }
419
+
420
+ // A claims heading owns its descendants until a sibling or ancestor ends it.
421
+ // A more specific claims heading, such as Opt-out claims, owns its own tables.
422
+ function homepageClaims(text) {
423
+ const lines = covVisibleLines(text), result = [], headings = [];
424
+ let fence;
425
+ for (let i = 0; i < lines.length; i++) {
426
+ const value = lines[i].text;
427
+ const state = covFence(value, fence);
428
+ fence = state.current;
429
+ if (state.marker || fence) continue;
430
+ const heading = covHeading.exec(value);
431
+ if (heading) {
432
+ const level = heading[1].length;
433
+ while (headings.length && headings.at(-1).level >= level) headings.pop();
434
+ headings.push({ level, text: plainText(heading[2]) });
435
+ continue;
436
+ }
437
+ const owner = [...headings].reverse().find(entry => /\bclaims?\b/i.test(entry.text));
438
+ if (!owner || !/\bhomepage\s+claims\b/i.test(owner.text) || /\bopt[ -]?out\b/i.test(owner.text)) continue;
439
+ if (!value.includes('|') || !covDivider(lines[i + 1]?.text ?? '')) continue;
440
+ const header = covCells(value);
441
+ if (!header.some(cell => /^claims?$/i.test(plainText(cell)))) continue;
442
+ const rows = [];
443
+ let next = i + 2;
444
+ while (next < lines.length && lines[next].text.trim() && lines[next].text.includes('|') && !covHeading.test(lines[next].text)) {
445
+ const row = lines[next];
446
+ if (covDivider(row.text) || covCells(row.text).length !== header.length) break;
447
+ rows.push({ line: next + 1, cells: covCells(row.text), raw: row.raw });
448
+ next++;
449
+ }
450
+ result.push({ header, rows, heading: owner.text });
451
+ i = next - 1;
452
+ }
453
+ return result;
454
+ }
455
+
456
+ function covFiles(old) {
457
+ return covNames.filter(file => typeof old.files[file] === 'string' && (file === 'CONTRACT.md' || !covGenerated(old.files[file])));
458
+ }
459
+ function covScope(old) {
460
+ const entries = [];
461
+ for (const file of covFiles(old)) {
462
+ const source = old.files[file], lines = covVisibleLines(source);
463
+ const claims = new Set(homepageClaims(source).flatMap(table => table.rows.map(row => row.line)));
464
+ const headings = [];
465
+ let fence, clause, introStarted = false, introEnded = false;
466
+ for (let index = 0; index < lines.length; index++) {
467
+ const { text, raw } = lines[index], line = index + 1;
468
+ const state = covFence(text, fence), insideFence = Boolean(fence);
469
+ fence = state.current;
470
+ if (state.marker) continue;
471
+ const heading = insideFence ? null : covHeading.exec(text);
472
+ const definition = insideFence ? null : covDefinition.exec(text);
473
+ if (heading) {
474
+ const level = heading[1].length;
475
+ while (headings.length && headings.at(-1).level >= level) headings.pop();
476
+ headings.push({ level, text: plainText(heading[2]) });
477
+ clause = definition?.[1];
478
+ if (level > 1 || introStarted) introEnded = true;
479
+ continue;
480
+ }
481
+ if (!text.trim()) { if (introStarted) introEnded = true; continue; }
482
+ if (covDivider(text)) continue;
483
+ if (definition) clause = definition[1];
484
+ const section = [...headings].reverse().find(entry => entry.level === 2)?.text ?? '';
485
+ const inStatus = headings.some(entry => /^Status\b/i.test(entry.text));
486
+ const cells = !insideFence && text.includes('|') ? covCells(text) : [];
487
+ // Every Status table line is out of scope except a clause row's non-empty Gap cell.
488
+ if (file === 'CONTRACT.md' && inStatus && !insideFence && text.trimStart().startsWith('|')) {
489
+ if (cells.length === 6 && covId.test(plainText(cells[0])) && plainText(cells[5]).trim()) entries.push({ file, line, cell: 'gap', text: cells[5], raw, clause: plainText(cells[0]), section, homepage: false });
490
+ continue;
491
+ }
492
+ const intro = !introEnded && !headings.some(entry => entry.level > 1) && !definition;
493
+ if (intro) introStarted = true;
494
+ entries.push({ file, line, text, raw, clause, section, intro, homepage: claims.has(line) });
495
+ }
496
+ }
497
+ return entries;
498
+ }
499
+
500
+ function covCurrent(text) {
501
+ const parsed = parseContract(text);
502
+ const lines = covVisibleLines(text), sections = new Set(), from = new Map(), ids = new Set(parsed.clauses.map(clause => clause.id));
503
+ const register = new Set(), base = new Set(), rules = new Set();
504
+ let section = '', clause;
505
+ const addSource = (oldId, id) => {
506
+ if (!from.has(oldId)) from.set(oldId, []);
507
+ if (!from.get(oldId).includes(id)) from.get(oldId).push(id);
508
+ };
509
+ for (const id of ids) addSource(id, id);
510
+ for (const { text: value } of lines) {
511
+ const heading = covHeading.exec(value), definition = covDefinition.exec(value);
512
+ if (heading) {
513
+ clause = definition?.[1];
514
+ if (heading[1].length === 2) { section = plainText(heading[2]); sections.add(section); }
515
+ }
516
+ if (definition) clause = definition[1];
517
+ const metadata = /^\s*-\s+`([^`]+)`:\s*\*Tier:\*/.exec(value);
518
+ const owner = metadata?.[1] ?? clause;
519
+ const sources = /\*From:\*\s*([^·\n]+)/.exec(value)?.[1];
520
+ if (owner && ids.has(owner) && sources) for (const oldId of sources.match(new RegExp(clauseIdSource, 'g')) ?? []) addSource(oldId, owner);
521
+ const firstCell = value.includes('|') ? plainText(covCells(value)[0]) : '';
522
+ if (/^Field proof register$/i.test(section) && /^R-\d+$/.test(firstCell)) register.add(firstCell);
523
+ if (/^Shared duties\b/i.test(section) && /^BASE-[A-Z0-9-]+$/.test(firstCell)) base.add(firstCell);
524
+ if (/^Door rules$/i.test(section)) {
525
+ const rule = /^\s*[-*+]\s+(?:\*\*|`)?(D-\d+)[.:`\s]/.exec(value)?.[1];
526
+ if (rule) rules.add(rule);
527
+ }
528
+ }
529
+ const rulings = new Set();
530
+ for (const { text: value } of covVisibleLines(read('RULINGS.md') ?? '')) {
531
+ const id = /^#{1,6}\s+(RL-\d+)\b/.exec(value)?.[1];
532
+ if (id) rulings.add(id);
533
+ }
534
+ const intro = covScope({ files: { 'CONTRACT.md': text } }).some(entry => entry.intro);
535
+ return { ids, gaps: new Set(parsed.clauses.filter(clause => clause.gap).map(clause => clause.id)), from, sections, register, base, rules, rulings, intro };
536
+ }
537
+ function covRepeated(entry, contractEntries) {
538
+ const text = covNormalize(entry.text);
539
+ return contractEntries.find(other => text && covNormalize(other.text) === text);
540
+ }
541
+ function covGeneratedStatement(text) {
542
+ const value = plainText(text).trim();
543
+ return /^(?:Judged from the code and tests at commit\b|(?:Claims|Clauses|Full target|Core|Agent surface|Later):\s*\d|\d+ clauses?:\s*\d+ done\b|(?:Evidence|Gap|Status)[.:]\s*|(?:Core|Agent surface|Later)\s*·)/i.test(value)
544
+ || (value.includes('|') && covCells(value).some(cell => /^(?:done|partial|missing)$/i.test(cell)) && covCells(value).every(cell => /^(?:\d+|Tier|Clauses|Done|Partial|Missing|Total|Core|Agent surface|Later|Full target|All|Published|Target(?: and push further)?)$/i.test(cell)))
545
+ || (value.includes('|') && covCells(value).slice(1).every(cell => /^\d+$/.test(cell)) && /^(?:Core|Agent surface|Later|Full target|All|Published|Target(?: and push further)?)$/i.test(covCells(value)[0]));
546
+ }
547
+ function covPlacement(entry, current, contractEntries) {
548
+ if (entry.homepage) {
549
+ const repeated = entry.file === 'CONTRACT.md' ? undefined : covRepeated(entry, contractEntries);
550
+ return repeated ? { to: 'copy', of: repeated.line } : { to: 'section', section: 'Homepage claims' };
551
+ }
552
+ if (entry.file === 'ACCEPTANCE.md') {
553
+ const repeated = covRepeated(entry, contractEntries);
554
+ if (repeated) return { to: 'copy', of: repeated.line };
555
+ if (entry.clause || covGeneratedStatement(entry.text)) return { to: 'generated', note: 'The contract generator writes this status or count.' };
556
+ return { to: 'docs', path: 'docs/verify.md' };
557
+ }
558
+ if (entry.file !== 'CONTRACT.md') return { to: 'changelog' };
559
+ if (entry.cell === 'gap') return { to: 'gap', ids: current.from.get(entry.clause) ?? [entry.clause] };
560
+ if (entry.clause) return { to: 'clause', ids: current.from.get(entry.clause) ?? [entry.clause] };
561
+ if (entry.intro) return { to: 'section', section: 'intro' };
562
+ if (/^Product target\b/i.test(entry.section)) return { to: 'section', section: 'Product target' };
563
+ if (current.sections.has(entry.section) && covSections.has(entry.section)) return { to: 'section', section: entry.section };
564
+ return { to: 'changelog' };
565
+ }
566
+ function covWrite(map) {
567
+ put(covMapPath, `${JSON.stringify(map, null, 2)}\n`);
568
+ return map;
569
+ }
570
+ function covReadMap() {
571
+ const source = read(covMapPath);
572
+ if (source === undefined) throw new Error('Missing `docs/contract/COVERAGE.json`. Run coverage init first.');
573
+ let map;
574
+ try { map = JSON.parse(source); } catch (error) { throw new Error(`Invalid coverage JSON: ${error.message}`); }
575
+ if (!map || typeof map !== 'object' || Array.isArray(map)) throw new Error('The coverage map must be an object.');
576
+ return map;
577
+ }
578
+ function coverageInit(old) {
579
+ const current = covCurrent(read('CONTRACT.md'));
580
+ const entries = covScope(old), contractEntries = entries.filter(entry => entry.file === 'CONTRACT.md');
581
+ const fragments = entries.map(entry => ({ file: entry.file, line: entry.line, ...(entry.cell ? { cell: entry.cell } : {}), text: entry.text, ...covPlacement(entry, current, contractEntries) }));
582
+ return covWrite({ schema: 1, seed: seedName(read('CONTRACT.md')).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''), old: { commit: old.commit, files: covFiles(old) }, fragments });
583
+ }
584
+
585
+ function covDestination(destination, fragment, source, context, problems, label) {
586
+ const fail = message => problems.push(`${label}: ${message}`);
587
+ if (!destination || typeof destination !== 'object' || Array.isArray(destination)) { fail('A destination must be an object.'); return; }
588
+ const { current, old, expected, groups } = context;
589
+ const note = () => { if (typeof destination.note !== 'string' || !destination.note.trim()) fail(`${destination.to} needs a note.`); };
590
+ const ids = known => {
591
+ if (!Array.isArray(destination.ids) || !destination.ids.length || destination.ids.some(id => typeof id !== 'string')) { fail(`${destination.to} needs a non-empty ids list.`); return; }
592
+ if (new Set(destination.ids).size !== destination.ids.length) fail(`${destination.to} repeats a destination id.`);
593
+ for (const id of destination.ids) if (!known.has(id)) fail(`Unknown ${destination.to} destination ${id}.`);
594
+ };
595
+ if (source?.homepage && !(destination.to === 'section' && destination.section === 'Homepage claims') && !['copy', 'deleted'].includes(destination.to)) fail('A homepage claim must go to Homepage claims or name the old row it repeats.');
596
+ switch (destination.to) {
597
+ case 'clause': ids(current.ids); break;
598
+ case 'gap': ids(current.gaps); break;
599
+ case 'register': ids(current.register); break;
600
+ case 'base': ids(current.base); break;
601
+ case 'door-rule': ids(current.rules); break;
602
+ case 'rulings': ids(current.rulings); break;
603
+ case 'section':
604
+ if (destination.section === 'intro' ? !current.intro : !current.sections.has(destination.section) || !covSections.has(destination.section)) fail(`Unknown section destination ${JSON.stringify(destination.section)}.`);
605
+ break;
606
+ case 'docs': {
607
+ const name = destination.path;
608
+ let exists = false;
609
+ if (typeof name === 'string' && name.startsWith('docs/') && !name.includes('\\') && !name.split('/').includes('..')) {
610
+ try { exists = fs.statSync(name).isFile(); } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error; }
611
+ }
612
+ if (!exists) fail('A docs destination must name an existing file beneath `docs`.');
613
+ break;
614
+ }
615
+ case 'changelog':
616
+ if (read('CHANGELOG.md') === undefined) fail('The changelog destination needs `CHANGELOG.md`.');
617
+ break;
618
+ case 'sibling':
619
+ if (typeof destination.seed !== 'string' || !destination.seed.trim()) fail('A sibling destination needs a seed.');
620
+ note();
621
+ break;
622
+ case 'copy': {
623
+ if (!Number.isInteger(destination.of) || destination.of < 1) { fail('A copy needs the old CONTRACT line number in of.'); break; }
624
+ const target = [...expected.values()].find(entry => entry.file === 'CONTRACT.md' && entry.line === destination.of);
625
+ if (!target || !covNormalize(fragment.text) || !covNormalize(target.text).includes(covNormalize(fragment.text))) fail(`Copy reference CONTRACT.md:${destination.of} does not contain this text.`);
626
+ else if (!groups.has(covKey(target))) fail(`Copy reference CONTRACT.md:${destination.of} is unplaced.`);
627
+ if (fragment.file === 'CONTRACT.md' && fragment.line === destination.of) fail('A copy cannot refer to its own source line.');
628
+ if (source?.homepage && target && !target.homepage) fail('A homepage copy must refer to an old homepage row.');
629
+ break;
630
+ }
631
+ case 'generated': note(); break;
632
+ case 'deleted':
633
+ note();
634
+ if (source?.homepage && (typeof destination.note !== 'string' || !/\b(?:duplicat\w*|repeat\w*)\b/i.test(destination.note) || !/\b(?:row|line)\s+\d+\b/i.test(destination.note))) fail('A deleted homepage claim must name the old row it repeats.');
635
+ break;
636
+ default: fail(`Unknown destination ${JSON.stringify(destination.to)}.`);
637
+ }
638
+ }
639
+ function coverageCheck(old) {
640
+ const map = covReadMap(), problems = [], entries = covScope(old), expected = new Map(entries.map(entry => [covKey(entry), entry])), groups = new Map();
641
+ if (map.schema !== 1) problems.push('Coverage schema must be 1.');
642
+ if (map.old?.commit !== old.commit) problems.push(`Coverage old.commit must equal ${old.commit}; found ${JSON.stringify(map.old?.commit)}.`);
643
+ const files = covFiles(old);
644
+ if (!Array.isArray(map.old?.files) || new Set(map.old.files).size !== files.length || map.old.files.length !== files.length || files.some(file => !map.old.files.includes(file))) problems.push('Coverage old.files must name every original hand-written source once.');
645
+ if (!Array.isArray(map.fragments)) problems.push('Coverage fragments must be a list.');
646
+ const fragments = Array.isArray(map.fragments) ? map.fragments : [];
647
+ fragments.forEach((fragment, index) => {
648
+ const label = `Fragment ${index + 1}`;
649
+ if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)) { problems.push(`${label}: A fragment must be an object.`); return; }
650
+ const key = covKey(fragment);
651
+ if (!expected.has(key) || !Number.isInteger(fragment.line)) problems.push(`${label}: ${covLabel(fragment)} is outside the original scoped text.`);
652
+ if (typeof fragment.text !== 'string' || !covNormalize(fragment.text)) problems.push(`${label}: A fragment needs non-empty text.`);
653
+ if (!groups.has(key)) groups.set(key, []);
654
+ groups.get(key).push(fragment);
655
+ });
656
+ for (const [key, source] of expected) {
657
+ const own = groups.get(key);
658
+ if (!own) { problems.push(`${covLabel(source)}: Unplaced original text: ${source.text}`); continue; }
659
+ if (own.some(fragment => typeof fragment.text !== 'string') || covNormalize(own.map(fragment => fragment.text).join(' ')) !== covNormalize(source.text)) problems.push(`${covLabel(source)}: Fragments must rebuild the whole original text once, in order: ${source.text}`);
660
+ }
661
+ const current = covCurrent(read('CONTRACT.md')), context = { current, old, expected, groups };
662
+ fragments.forEach((fragment, index) => {
663
+ if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)) return;
664
+ const label = `${covLabel(fragment)} fragment ${index + 1}`, source = expected.get(covKey(fragment));
665
+ covDestination(fragment, fragment, source, context, problems, label);
666
+ if (fragment.also !== undefined && !Array.isArray(fragment.also)) problems.push(`${label}: also must be a list of destinations.`);
667
+ for (const [offset, destination] of (Array.isArray(fragment.also) ? fragment.also : []).entries()) covDestination(destination, fragment, source, context, problems, `${label} also ${offset + 1}`);
668
+ });
669
+ const oldClaims = Math.max(0, ...files.map(file => homepageClaims(old.files[file]).reduce((sum, table) => sum + table.rows.length, 0)));
670
+ const newClaims = homepageClaims(read('CONTRACT.md')).reduce((sum, table) => sum + table.rows.length, 0);
671
+ if (oldClaims && oldClaims !== newClaims) problems.push(`Homepage claims have ${newClaims} rows; the largest original table has ${oldClaims}.`);
672
+ if (problems.length) throw new Error(`${covMapPath}:\n${problems.join('\n')}`);
673
+ console.log(`Coverage checked: ${entries.length} original lines placed.`);
674
+ }
675
+
676
+ // Git's explicit Myers diff gives stable unchanged-line moves without a quadratic matrix.
677
+ function covLineMoves(from, onto, file) {
678
+ const before = covSplit(from.files[file] ?? ''), after = covSplit(onto.files[file] ?? ''), moves = new Map();
679
+ const diff = git(['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--no-color', '--diff-algorithm=myers', '--unified=0', from.commit, onto.commit, '--', file]);
680
+ let oldLine = 1, newLine = 1;
681
+ const unchanged = end => {
682
+ while (oldLine < end && oldLine <= before.length && newLine <= after.length) {
683
+ if (before[oldLine - 1] !== after[newLine - 1]) throw new Error(`Git diff did not preserve ${file}:${oldLine}.`);
684
+ moves.set(oldLine++, newLine++);
685
+ }
686
+ };
687
+ for (const match of diff.matchAll(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm)) {
688
+ const oldCount = match[2] === undefined ? 1 : Number(match[2]), newCount = match[4] === undefined ? 1 : Number(match[4]);
689
+ const oldStart = Number(match[1]) + (oldCount === 0 ? 1 : 0), newStart = Number(match[3]) + (newCount === 0 ? 1 : 0);
690
+ unchanged(oldStart);
691
+ oldLine = oldStart + oldCount;
692
+ newLine = newStart + newCount;
693
+ }
694
+ unchanged(before.length + 1);
695
+ return moves;
696
+ }
697
+ function coverageRebase(from, onto) {
698
+ const map = covReadMap();
699
+ if (map.old?.commit !== from.commit) throw new Error(`Coverage old.commit must equal the rebase source ${from.commit}.`);
700
+ if (!Array.isArray(map.fragments)) throw new Error('Coverage fragments must be a list.');
701
+ const before = new Map(covScope(from).map(entry => [covKey(entry), entry])), entries = covScope(onto), after = new Map(entries.map(entry => [covKey(entry), entry]));
702
+ const moves = new Map(covFiles(onto).map(file => [file, covLineMoves(from, onto, file)]));
703
+ const fragments = [];
704
+ for (const fragment of map.fragments) {
705
+ if (!fragment || typeof fragment !== 'object' || !before.has(covKey(fragment))) continue;
706
+ const line = moves.get(fragment.file)?.get(fragment.line);
707
+ if (line === undefined) continue;
708
+ const updated = { ...fragment, line };
709
+ if (after.has(covKey(updated))) {
710
+ const remapCopy = destination => {
711
+ if (destination.to !== 'copy') return destination;
712
+ const of = moves.get('CONTRACT.md')?.get(destination.of);
713
+ return of === undefined ? undefined : { ...destination, of };
714
+ };
715
+ const placed = remapCopy(updated);
716
+ if (!placed) continue;
717
+ if (Array.isArray(placed.also)) {
718
+ const also = placed.also.map(remapCopy);
719
+ if (also.some(destination => destination === undefined)) continue;
720
+ placed.also = also;
721
+ }
722
+ fragments.push(placed);
723
+ }
724
+ }
725
+ const rebuilt = new Map();
726
+ for (const fragment of fragments) {
727
+ const key = covKey(fragment);
728
+ if (!rebuilt.has(key)) rebuilt.set(key, []);
729
+ rebuilt.get(key).push(fragment.text);
730
+ }
731
+ covWrite({ ...map, old: { commit: onto.commit, files: covFiles(onto) }, fragments });
732
+ const unmapped = entries.filter(entry => !rebuilt.has(covKey(entry)) || covNormalize(rebuilt.get(covKey(entry)).join(' ')) !== covNormalize(entry.text));
733
+ for (const entry of unmapped) console.log(`Newly unmapped ${covLabel(entry)}: ${entry.text}`);
734
+ if (!unmapped.length) console.log('Coverage rebased: no newly unmapped original lines.');
735
+ return { ...map, old: { commit: onto.commit, files: covFiles(onto) }, fragments };
736
+ }
737
+
738
+ function main(args) {
739
+ const [command, ...rest] = args
740
+ const option = name => {
741
+ const index = rest.indexOf(name)
742
+ if (index < 0 || !rest[index + 1] || rest[index + 1].startsWith('--')) throw Error(`Provide ${name} and its Git reference.`)
743
+ return rest[index + 1]
744
+ }
745
+ if (command === 'write' && !rest.length) generate()
746
+ else if (command === 'check' && !rest.length) generate(true)
747
+ else if (command === 'id-map') idMap(snapshot(option('--old')))
748
+ else if (command === 'coverage' && rest[0] === 'init') coverageInit(snapshot(option('--old')))
749
+ else if (command === 'coverage' && rest[0] === 'check') coverageCheck(snapshot(option('--old')))
750
+ else if (command === 'coverage' && rest[0] === 'rebase') coverageRebase(snapshot(option('--from')), snapshot(option('--onto')))
751
+ else if (command === 'convert') convert(snapshot(option('--old')), rest.includes('--old-acceptance') ? snapshot(option('--old-acceptance')) : undefined)
752
+ else throw Error('Usage: contract-docs.mjs write|check|id-map --old <ref>|coverage init|check --old <ref>|coverage rebase --from <ref> --onto <ref>|convert --old <ref> [--old-acceptance <ref>]')
753
+ }
754
+ try { main(process.argv.slice(2)) } catch (error) { console.error(error.message); process.exitCode = 1 }