@runeditrun/rer 0.2.85 → 0.2.87

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 (162) hide show
  1. package/README.md +138 -29
  2. package/cli/README.md +61 -1
  3. package/cli/agent-bindings.mjs +25 -0
  4. package/cli/agent-door.mjs +145 -0
  5. package/cli/agent-fixtures.mjs +16 -0
  6. package/cli/agent-journey-fixtures.mjs +17 -0
  7. package/cli/agent-mail.mjs +54 -0
  8. package/cli/agent-network.mjs +64 -0
  9. package/cli/agent-reviewers.mjs +110 -0
  10. package/cli/agent-rpc.mjs +23 -0
  11. package/cli/agent-secrets.mjs +23 -0
  12. package/cli/agent-sponsors.mjs +43 -0
  13. package/cli/agent-surface.mjs +34 -0
  14. package/cli/agent-verifier.mjs +31 -0
  15. package/cli/agent-webhooks.mjs +19 -0
  16. package/cli/authoring.mjs +2 -1
  17. package/cli/business/archive-task.mjs +32 -0
  18. package/cli/business/carry.mjs +3 -1
  19. package/cli/business/catchup-task.mjs +42 -0
  20. package/cli/business/choices.mjs +97 -0
  21. package/cli/business/command.mjs +23 -5
  22. package/cli/business/connect.mjs +19 -7
  23. package/cli/business/detector.mjs +4 -1
  24. package/cli/business/device.mjs +13 -0
  25. package/cli/business/export-inputs.mjs +69 -0
  26. package/cli/business/export-task.mjs +17 -0
  27. package/cli/business/invocation.mjs +8 -1
  28. package/cli/business/keychain.mjs +8 -1
  29. package/cli/business/lease.mjs +11 -1
  30. package/cli/business/local-commands.mjs +79 -31
  31. package/cli/business/outbound.mjs +9 -4
  32. package/cli/business/parsers-config.mjs +8 -7
  33. package/cli/business/parsers-syntax.mjs +7 -3
  34. package/cli/business/permissions.mjs +2 -0
  35. package/cli/business/questions.mjs +89 -9
  36. package/cli/business/setup-command.mjs +49 -0
  37. package/cli/business/setup-company.json +15 -0
  38. package/cli/business/setup-demo.mjs +95 -0
  39. package/cli/business/state.mjs +44 -10
  40. package/cli/business/supervisor.mjs +94 -35
  41. package/cli/business/vendor-door.mjs +230 -0
  42. package/cli/business/vendors/README.md +29 -3
  43. package/cli/business/vendors/common.mjs +8 -6
  44. package/cli/business/vendors/index.mjs +22 -11
  45. package/cli/business/vendors/sorry.mjs +106 -0
  46. package/cli/contract.mjs +2 -2
  47. package/cli/demo-deploy-error.mjs +14 -0
  48. package/cli/demo-native.mjs +4 -1
  49. package/cli/deploy-config.mjs +1 -1
  50. package/cli/deploy-owner-input.mjs +3 -1
  51. package/cli/deploy-variables.mjs +89 -0
  52. package/cli/door-clauses.mjs +157 -0
  53. package/cli/export.mjs +17 -4
  54. package/cli/hosted-output.mjs +31 -8
  55. package/cli/inspect.mjs +4 -0
  56. package/cli/jsonc.mjs +8 -4
  57. package/cli/lifecycle.mjs +3 -1
  58. package/cli/main.mjs +1 -0
  59. package/cli/managed-data-schema.mjs +14 -1
  60. package/cli/managed-data.mjs +8 -4
  61. package/cli/portability-empty.mjs +6 -0
  62. package/cli/portability-migrations.mjs +26 -4
  63. package/cli/portability-worker.mjs +2 -1
  64. package/cli/portability.mjs +1 -0
  65. package/cli/production-auth.mjs +2 -2
  66. package/cli/production-mail.mjs +19 -3
  67. package/cli/server-registry.mjs +2 -0
  68. package/edition-authoring/archive-source.mjs +65 -0
  69. package/edition-authoring/base-copies.mjs +108 -21
  70. package/edition-authoring/cli.mjs +1 -1
  71. package/edition-authoring/copy-namespaces.mjs +28 -0
  72. package/edition-authoring/edition-migrations.mjs +7 -3
  73. package/edition-authoring/files.mjs +2 -1
  74. package/edition-authoring/module-closure.mjs +58 -27
  75. package/edition-authoring/module-edges.mjs +13 -2
  76. package/edition-authoring/workflow-copies.mjs +1 -1
  77. package/edition-authoring/workflow-scripts.mjs +12 -3
  78. package/foundation/runtime/contract-docs.mjs +220 -32
  79. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  80. package/foundation/runtime/contract-prose.mjs +88 -0
  81. package/global/CHANGELOG.md +151 -0
  82. package/global/README.md +138 -29
  83. package/global/door/command.mjs +3 -1
  84. package/global/main.mjs +1 -1
  85. package/modules/agent-door/CLAUSES.md +215 -0
  86. package/modules/agent-door/conformance/audit-pages.mjs +11 -0
  87. package/modules/agent-door/conformance/audit-rows.mjs +20 -0
  88. package/modules/agent-door/conformance/audit.mjs +63 -0
  89. package/modules/agent-door/conformance/authority.d.mts +2 -0
  90. package/modules/agent-door/conformance/authority.mjs +17 -0
  91. package/modules/agent-door/conformance/crypto.mjs +36 -0
  92. package/modules/agent-door/conformance/discovery.mjs +61 -0
  93. package/modules/agent-door/conformance/fixtures.mjs +41 -0
  94. package/modules/agent-door/conformance/index.mjs +41 -0
  95. package/modules/agent-door/conformance/injection.mjs +24 -0
  96. package/modules/agent-door/conformance/invocation.mjs +33 -0
  97. package/modules/agent-door/conformance/journey.mjs +117 -0
  98. package/modules/agent-door/conformance/narrowing.d.mts +2 -0
  99. package/modules/agent-door/conformance/narrowing.mjs +29 -0
  100. package/modules/agent-door/conformance/negative.mjs +48 -0
  101. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  102. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  103. package/modules/agent-door/conformance/policy-phases.mjs +83 -0
  104. package/modules/agent-door/conformance/protocol.mjs +153 -0
  105. package/modules/agent-door/conformance/replay.mjs +39 -0
  106. package/modules/agent-door/conformance/schema.mjs +71 -0
  107. package/modules/agent-door/conformance/security.mjs +34 -0
  108. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  109. package/modules/agent-door/conformance/step-hooks.mjs +4 -0
  110. package/modules/agent-door/conformance/surface.mjs +92 -0
  111. package/modules/agent-door/conformance/target.mjs +19 -0
  112. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  113. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  114. package/modules/agent-door/conformance/webhooks.mjs +31 -0
  115. package/modules/container/image-variables.mjs +8 -2
  116. package/modules/delivery-producer/mail.mjs +20 -0
  117. package/modules/demo-host/README.md +6 -0
  118. package/modules/demo-host/ownership.mjs +39 -0
  119. package/modules/demo-host/plan.mjs +2 -1
  120. package/modules/demo-host/remove.mjs +6 -1
  121. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  122. package/modules/import-kit/schema/importers.schema.json +107 -0
  123. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  124. package/modules/import-kit/src/door/README.md +2 -1
  125. package/modules/import-kit/src/door/admission.ts +5 -3
  126. package/modules/import-kit/src/door/archive.ts +5 -2
  127. package/modules/import-kit/src/door/authority.ts +1 -0
  128. package/modules/import-kit/src/door/grants.ts +1 -1
  129. package/modules/import-kit/src/door/handler.ts +14 -8
  130. package/modules/import-kit/src/door/index.ts +1 -1
  131. package/modules/import-kit/src/door/jobs.ts +40 -0
  132. package/modules/import-kit/src/door/operator.ts +3 -3
  133. package/modules/import-kit/src/door/planning.ts +10 -6
  134. package/modules/import-kit/src/door/protocol.ts +2 -2
  135. package/modules/import-kit/src/door/raw.ts +25 -0
  136. package/modules/import-kit/src/door/refusals.ts +1 -0
  137. package/modules/import-kit/src/door/types.ts +26 -6
  138. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  139. package/modules/import-kit/src/receipt/index.ts +69 -0
  140. package/modules/import-kit/src/receipt/policy.ts +24 -0
  141. package/modules/import-kit/src/receipt/types.ts +64 -0
  142. package/modules/import-kit/src/receipt/uri.ts +45 -0
  143. package/modules/import-kit/src/receipt/validation.ts +87 -0
  144. package/modules/import-kit/src/status/encoding.ts +13 -0
  145. package/modules/import-kit/src/status/evidence.ts +218 -0
  146. package/modules/import-kit/src/status/index.ts +56 -0
  147. package/modules/import-kit/src/status/schema.ts +208 -0
  148. package/modules/import-kit/src/status/types.ts +86 -0
  149. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  150. package/modules/operator-auth/index.d.mts +7 -0
  151. package/modules/operator-auth/service.mjs +2 -0
  152. package/modules/portability/README.md +37 -13
  153. package/modules/portability/bridge.mjs +22 -2
  154. package/modules/portability/catalogue.mjs +12 -2
  155. package/modules/portability/copies.mjs +8 -1
  156. package/modules/portability/derived.mjs +33 -0
  157. package/modules/portability/http-errors.mjs +1 -1
  158. package/modules/portability/import.mjs +14 -7
  159. package/package.json +4 -2
  160. package/scripts/publish-check/copy_identities.py +3 -1
  161. package/scripts/publish-check/github_refs.py +32 -13
  162. package/cli/business/opt-ins.mjs +0 -37
@@ -1,16 +1,20 @@
1
1
  // All recorded code uses the same source graph and seed ownership boundary.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import {raw, safe, requirePhysical, testSource, freedEntries} from './files.mjs';
4
+ import {raw, safe, requirePhysical, testSource, freedEntries, toolFile} from './files.mjs';
5
5
  import {dependencies, resolve, external, bindings, lexicalExports} from './runtime-dependencies.mjs';
6
+ import {relocateDependencies} from './module-edges.mjs';
7
+ import {sharedNamespaces} from './copy-namespaces.mjs';
6
8
  const code = name => /\.(?:[cm]?[jt]s|[jt]sx)$/.test(name) && !testSource(name);
7
9
  const inside = (name, prefix) => prefix === '.' ? !name.startsWith('../') && !path.posix.isAbsolute(name) : name === prefix || name.startsWith(prefix + '/');
8
10
  const mapped = (source, copy) => copy.path + source.slice(copy.originPath.length);
9
11
  const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
10
12
 
11
- export function completeModuleCopies(root, plans, {tree, read, revision, base, deliveries = [], ownerSources = new Map()}) {
13
+ export function completeModuleCopies(root, plans, {tree, read, revision, base, deliveries = [], ownerSources = new Map(), relocations = new Map()}) {
12
14
  const index = new Set(raw(root, 'ls-files', '-z').toString('utf8').split('\0').filter(Boolean));
13
15
  const required = new Set();
16
+ const mappings = plans.filter(plan => !plan.retired).map(({copy}) => ({copy, ...namespace(copy)})).filter(mapping => mapping.from);
17
+ const shared = sharedNamespaces(mappings);
14
18
  const cache = new Map(), planned = new Map(), recorded = new Map(), queue = [], withheld = [];
15
19
  const disk = {has: name => {
16
20
  try { return fs.lstatSync(path.join(root, name)).isFile(); }
@@ -37,14 +41,29 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
37
41
  for (const target of Object.keys(plan.copy.adapted ?? {})) enqueue(plan, plan.copy.originPath + target.slice(plan.copy.path.length), null, true);
38
42
  }
39
43
  const directoryAdditions = new Set([...planned].filter(([target, {plan}]) => !Object.hasOwn(plan.copy.files, target) && !tree.has(plan.copy.originPath)).map(([target]) => target));
44
+ function namespace(copy) {
45
+ const file = Object.hasOwn(copy.files, copy.path) || tree.has(copy.originPath);
46
+ if (file && path.posix.basename(copy.path) !== path.posix.basename(copy.originPath)) return {};
47
+ return {directory: !file, to: file ? path.posix.dirname(copy.path) : copy.path,
48
+ from: file ? path.posix.dirname(copy.originPath) : copy.originPath};
49
+ }
40
50
  function witness(target, source) {
41
- return plans.some(({copy}) => {
42
- const file = Object.hasOwn(copy.files, copy.path) || tree.has(copy.originPath);
43
- if (file && path.posix.basename(copy.path) !== path.posix.basename(copy.originPath)) return false;
44
- const to = file ? path.posix.dirname(copy.path) : copy.path;
45
- const from = file ? path.posix.dirname(copy.originPath) : copy.originPath;
46
- return inside(target, to) && path.posix.join(from, path.posix.relative(to, target)) === source;
47
- });
51
+ if (plans.some(({copy}) => {
52
+ const {to, from} = namespace(copy);
53
+ return from && inside(target, to) && path.posix.join(from, path.posix.relative(to, target)) === source;
54
+ })) return true;
55
+ return recordedDestination(source).includes(target);
56
+ }
57
+ function recordedDestination(source) {
58
+ // Prefer the explicitly selected subtree over a broader, sparse runtime
59
+ // copy. Never choose between equally specific namespaces for the seed.
60
+ let candidates = [...mappings, ...shared].filter(({from}) => inside(source, from));
61
+ const specificity = Math.max(...candidates.map(({from}) => from.length));
62
+ candidates = candidates.filter(({from}) => from.length === specificity);
63
+ const destination = ({from, to}) => path.posix.join(to, path.posix.relative(from, source));
64
+ const members = candidates.filter(mapping => mapping.copy && Object.hasOwn(mapping.copy.files, destination(mapping)));
65
+ if (members.length) candidates = members;
66
+ return [...new Set(candidates.map(destination))];
48
67
  }
49
68
  function include(source, target) {
50
69
  required.add(target);
@@ -115,12 +134,30 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
115
134
  const source = planned.get(destination)?.source ?? (owner && owner.copy.originPath + destination.slice(owner.copy.path.length)) ?? dependency;
116
135
  return {...request, dependency: source, destination, satisfied: true};
117
136
  }
118
- return {...request, manifests, dependency, destination: dependency && path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency))};
137
+ const expected = dependency && path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency));
138
+ // Relocate only new deliveries. Existing files and acknowledged adaptations
139
+ // retain their current imports and ownership, including old missing edges.
140
+ if (specifier.startsWith('.') && dependency && !recorded.has(target) && !witness(expected, dependency)) {
141
+ const destinations = recordedDestination(dependency);
142
+ if (destinations.length > 1) return {...request, manifests, dependency, destination: expected,
143
+ reason: `ambiguous Base copy mappings for ${dependency}: ${destinations.join(', ')}`};
144
+ if (destinations.length === 1) {
145
+ const destination = destinations[0];
146
+ // Preserve extensionless TS and emitted-JS spellings by moving the
147
+ // original request path by the same displacement as its resolved file.
148
+ const requested = path.posix.join(path.posix.dirname(source), request.kind === 'require' ? specifier : decodeURIComponent(specifier));
149
+ let relocation = path.posix.relative(path.posix.dirname(target), path.posix.join(path.posix.dirname(destination), path.posix.relative(path.posix.dirname(dependency), requested)));
150
+ if (!relocation.startsWith('.')) relocation = './' + relocation;
151
+ return {...request, manifests, dependency, destination, relocation};
152
+ }
153
+ }
154
+ return {...request, manifests, dependency, destination: expected};
119
155
  }
120
156
  const key = (target, request) => JSON.stringify([target, request.kind, request.types, request.specifier]);
121
157
  const bootstrap = source => /^(?:edition-authoring|(?:default-seed|export)\/scripts\/base-cli\/edition-authoring)\//.test(source);
122
158
  // Snapshot the original unresolved set once, before closure can add a file.
123
- // Only toolkit bootstraps and recorded removals may change that baseline.
159
+ // Preserve these edges during traversal; required planned files may still
160
+ // complete a sparse historical copy by satisfying them.
124
161
  const baseline = new Set();
125
162
  for (const {plan, source, target} of queue) {
126
163
  if (!Object.hasOwn(plan.copy.files, target) || !disk.has(target) || bootstrap(source)) continue;
@@ -176,6 +213,14 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
176
213
  const imports = bindings(bytes), oldBindings = bindings(before);
177
214
  const typeImports = bindings(bytes, true), oldTypes = bindings(before, true);
178
215
  const edges = requests(bytes, source, target).map(request => edge(source, target, request));
216
+ // lock.mjs reads the whole tool dynamically to identify it. Deliver that
217
+ // same file set, including parser notices and modules outside its imports.
218
+ if (/^(?:edition-authoring|(?:default-seed|export)\/scripts\/base-cli\/edition-authoring)\/lock\.mjs$/.test(source)) {
219
+ const from = source.slice(0, -'lock.mjs'.length), to = target.slice(0, -'lock.mjs'.length);
220
+ for (const dependency of tree.keys()) if (dependency.startsWith(from) && toolFile(dependency.slice(from.length))) {
221
+ edges.push({dependency, destination: to + dependency.slice(from.length)});
222
+ }
223
+ }
179
224
  for (const {manifests = []} of [...edges]) for (const dependency of manifests) {
180
225
  edges.push({dependency, destination: path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency))});
181
226
  }
@@ -191,7 +236,7 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
191
236
  if (!dependency) refuse(target, edge.reason ?? `no Base source for ${specifier}`, `\${EDITOR:-vi} ${quote(target)}`);
192
237
  if (!witness(destination, dependency)) {
193
238
  if (novel) { hold = {path: target, originPath: source, dependency}; break; }
194
- refuse(target, `no copy mapping witnesses ${destination} from ${dependency}`, '${EDITOR:-vi} base-copies.json');
239
+ refuse(target, edge.reason ?? `no copy mapping witnesses ${destination} from ${dependency}`, '${EDITOR:-vi} base-copies.json');
195
240
  }
196
241
  }
197
242
  if (hold) {
@@ -212,21 +257,7 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
212
257
  }
213
258
  }
214
259
  }
215
- }
216
- const expected = new Set(), unresolved = new Set();
217
- const removed = new Set(plans.flatMap(plan => plan.removed));
218
- const final = {has: name => planned.has(name) || !removed.has(name) && disk.has(name), read: view.read};
219
- for (const {plan, source, target, entry, adapted} of queue) {
220
- if (!adapted && !plan.sources.some(([name]) => name === source)) continue;
221
- for (const request of requests(adapted ? local(target) : blob(entry), source, target)) {
222
- const id = key(target, request);
223
- if (!baseline.has(id)) continue;
224
- expected.add(id);
225
- if (!resolve(final, target, request.specifier, request)) unresolved.add(id);
226
- }
227
- }
228
- if (expected.size !== unresolved.size || [...expected].some(id => !unresolved.has(id))) {
229
- refuse('baseline imports', 'a planned file would resolve an edition-owned unresolved edge', '${EDITOR:-vi} base-copies.json');
260
+ if (!adapted && edges.some(edge => edge.relocation)) relocations.set(target, Buffer.from(relocateDependencies(bytes, edges)));
230
261
  }
231
262
  return withheld;
232
263
  }
@@ -66,8 +66,9 @@ export function dependencies(source, filename = 'module.mjs') {
66
66
  }
67
67
  } while (changed);
68
68
  const add = (node, kind, types = false) => {
69
- const specifier = literal(unwrap(node));
70
- if (specifier) result.push({specifier: canonical(specifier, kind), kind, types});
69
+ node = unwrap(node);
70
+ const specifier = literal(node);
71
+ if (specifier) result.push({specifier: canonical(specifier, kind), kind, types, start: node.start, end: node.end, literal: specifier});
71
72
  };
72
73
  for (const node of all) {
73
74
  if (node.type === 'ImportDeclaration') {
@@ -98,3 +99,13 @@ export function dependencies(source, filename = 'module.mjs') {
98
99
  versions.set(source, result);
99
100
  return result;
100
101
  }
102
+
103
+ // Only parsed dependency literals are rewritten: comments, strings and JSX
104
+ // text that happen to contain the same path remain edition source.
105
+ export function relocateDependencies(source, requests) {
106
+ const replacements = new Map(requests.filter(request => request.relocation).map(request => [request.start, request]));
107
+ for (const {start, end, literal, specifier, relocation} of [...replacements.values()].sort((a, b) => b.start - a.start)) {
108
+ source = source.slice(0, start) + JSON.stringify(relocation + literal.slice(specifier.length)) + source.slice(end);
109
+ }
110
+ return source;
111
+ }
@@ -54,7 +54,7 @@ export function adoptWorkflowTemplates(root, plans, {tree, read, revision, files
54
54
  if (match) {
55
55
  include(plans, target, source, tree.get(source), revision);
56
56
  templateAdoptions.push({path: target, originPath: source, from: match.revision});
57
- } else if (target.endsWith('.yml')) {
57
+ } else if (target.endsWith('.yml') && !file.read().equals(read.blobs([tree.get(source).object]).get(tree.get(source).object))) {
58
58
  notices.push(`${target}: preserved seed-owned workflow. The current template pins Ubuntu 24.04 and moves browser and apt caches to the runner temporary directory. To adopt, merge export/${path.posix.basename(source)} from Base ${revision} into ${target}, then run node node_modules/@runeditrun/rer/edition-authoring/cli.mjs record-base ${target} ${source} ${revision} --base <base-checkout> and repeat rer refresh-base --ref ${revision} --base <base-checkout>.`);
59
59
  }
60
60
  }
@@ -95,16 +95,25 @@ export function shellWords(script) {
95
95
 
96
96
  export function literalPaths(script) {
97
97
  const names = new Set();
98
- function scan(text, ancestors = new Set()) {
98
+ function scan(text, ancestors = new Set(), words = shellWords(text)) {
99
99
  if (ancestors.has(text)) return;
100
100
  const nested = new Set([...ancestors, text]);
101
- for (const {value, dynamic} of shellWords(text)) {
101
+ for (const {value, dynamic} of words) {
102
102
  if (dynamic) continue;
103
103
  const relative = value.replace(/^\.\//, '');
104
104
  if ((value.startsWith('./') || relative.startsWith('scripts/') || !/\s/.test(value) && (relative.includes('/') || /\.[a-z0-9]+$/i.test(relative))) && !relative.startsWith('/')) names.add(relative);
105
105
  // A complete quoted path is one word; only script-like quoted content is
106
106
  // recursively tokenized, never a path whose filename contains whitespace.
107
- else if (/\s/.test(value)) scan(value, nested);
107
+ else if (/\s/.test(value)) {
108
+ // Decoded arguments may be prose, not another shell program. A quote
109
+ // that was literal in its enclosing word must not invalidate that
110
+ // workflow. Recurse only when the whole argument is valid shell text;
111
+ // the actual run script and its substitutions are still strict.
112
+ let words;
113
+ try { words = shellWords(value); }
114
+ catch { continue; }
115
+ scan(value, nested, words);
116
+ }
108
117
  }
109
118
  }
110
119
  scan(script);
@@ -4,6 +4,7 @@ import fs from 'node:fs'
4
4
  import path from 'node:path'
5
5
  import { execFileSync } from 'node:child_process'
6
6
  import { parseContract, clauseIdSource, plainText } from './seed-contract.mjs'
7
+ import { contractProseFindings, printProseFindings } from './contract-prose.mjs'
7
8
 
8
9
  const marker = '<!-- Generated from CONTRACT.md by contract-docs. Edit CONTRACT.md, then regenerate. -->'
9
10
  const idPattern = new RegExp(`^${clauseIdSource}$`)
@@ -14,6 +15,7 @@ const json = value => JSON.stringify(value, null, 2) + '\n'
14
15
  const linesOf = text => text.replace(/\r\n?/g, '\n').split('\n')
15
16
  const cells = line => line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '').split(/(?<!\\)\|/).map(cell => cell.trim())
16
17
  const divider = line => /^\|?(\s*:?-{3,}:?\s*\|)+\s*:?-{0,}:?\s*$/.test(line.trim())
18
+ const tableCell = text => text.replace(/(?<!\\)\|/g, '\\|')
17
19
  const idsIn = text => [...text.matchAll(new RegExp(`(?<![A-Za-z0-9.-])(${clauseIdSource})(?![A-Za-z0-9.-])`, 'g'))].map(match => match[1])
18
20
  const block = text => text.replace(/^\s*\n|\n\s*$/g, '').trim()
19
21
  function outline(text) {
@@ -130,30 +132,50 @@ function generatedFiles(text) {
130
132
  }
131
133
  }
132
134
  acceptance.push('## Field proof register', register)
133
- const tables = homepageClaims(text), rows = tables.flatMap(table => table.rows.map(row => ({ ...row, header: table.header })))
135
+ const rows = claimRows(text), provenance = validateClaimSource(text, rows)
134
136
  const claims = [marker, `# ${seed} homepage claims`]
135
137
  if (!rows.length) claims.push('No homepage claims are mapped yet.')
136
138
  else {
137
- claims.push('A claim is done when every clause behind it is done, missing when every one is missing, and partial otherwise.')
139
+ claims.push('A product claim is done when every clause behind it is done, missing when every one is missing, and partial otherwise. Explicit source-bound non-product facts are unassessed; their historical status is history, not current proof.')
138
140
  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
+ const hasNonProduct = provenance?.claims.some(row => row.nonProduct)
142
+ const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasNonProduct ? ['Basis'] : []), ...(provenance ? ['Historical status'] : []), 'Status']
143
+ const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], counts = { done: 0, partial: 0, missing: 0, unassessed: 0 }
141
144
  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')))] ?? ''
145
+ const value = label => claimValue(row, label)
146
+ const source = provenance?.claims[index]
147
+ if (source?.nonProduct) {
148
+ counts.unassessed++
149
+ table.push(`| ${[value('#'), ...(hasSection ? [value('Section')] : []), value('Claim'), '', `Non-product: ${source.nonProduct}`, source.status || 'Not recorded', 'unassessed'].map(tableCell).join(' | ')} |`)
150
+ continue
151
+ }
143
152
  const ids = idsIn(value('Clauses?')), linked = ids.map(id => clauses.find(clause => clause.id === id))
144
153
  if (!ids.length || linked.some(clause => !clause)) throw Error(`CONTRACT.md:${row.line}: Homepage claim needs existing clause ids.`)
145
154
  const state = linked.every(clause => clause.status === 'done') ? 'done' : linked.every(clause => clause.status === 'missing') ? 'missing' : 'partial'
146
155
  counts[state]++
147
- table.push(`| ${[value('#') || String(index + 1), ...(hasSection ? [value('Section')] : []), value('Claim'), linked.map(clause => `\`${clause.id}\` ${clause.status}`).join('; '), state].join(' | ')} |`)
156
+ table.push(`| ${[value('#') || String(index + 1), ...(hasSection ? [value('Section')] : []), value('Claim'), linked.map(clause => `\`${clause.id}\` ${clause.status}`).join('; '), ...(hasNonProduct ? ['Product'] : []), ...(provenance ? [source?.status || 'Not recorded'] : []), state].map(tableCell).join(' | ')} |`)
148
157
  }
149
- claims.push(table.join('\n'), `Claims: ${rows.length}; ${counts.done} done, ${counts.partial} partial, ${counts.missing} missing.`)
158
+ claims.push(table.join('\n'), `Claims: ${rows.length}; ${counts.done} done, ${counts.partial} partial, ${counts.missing} missing.${hasNonProduct ? ` Non-product: ${counts.unassessed} unassessed.` : ''}`)
159
+ if (provenance) claims.push(`Historical claim source: \`${provenance.old}\`. Exact source files, lines, text and historical statuses are retained in CONTRACT.md's contract-claim-source record.`)
150
160
  }
151
161
  return { 'CONTRACT.md': rewritten, 'ACCEPTANCE.md': acceptance.join('\n\n') + '\n', 'docs/CLAIMS.md': claims.join('\n\n') + '\n' }
152
162
  }
153
163
  function generate(check = false) {
154
164
  const text = read('CONTRACT.md')
155
165
  if (text === undefined) throw Error('CONTRACT.md does not exist.')
166
+ const coverage = read(covMapPath)
167
+ if (coverage !== undefined) {
168
+ let original
169
+ try { original = snapshot(JSON.parse(coverage).old?.commit) }
170
+ catch (error) { throw Error(`${covMapPath}: original SHA is unavailable: ${error.message}`) }
171
+ validateOriginalClaims(original)
172
+ }
156
173
  const files = generatedFiles(text), changed = Object.entries(files).filter(([name, contents]) => read(name) !== contents)
174
+ const provenance = readClaimSource(text)
175
+ if (provenance) for (const { name, original } of [{ name: 'docs/contract/ID-MAP.json', original: map => map.old }, { name: 'docs/contract/COVERAGE.json', original: map => map.old?.commit }]) {
176
+ const source = read(name)
177
+ if (source === undefined || original(JSON.parse(source)) !== provenance.old) throw Error(`${name}: original SHA must equal contract-claim-source old ${provenance.old}.`)
178
+ }
157
179
  if (check && changed.length) throw Error(changed.map(([name]) => `${name}: generated content differs; run contract-docs write.`).join('\n'))
158
180
  if (!check) for (const [name, contents] of changed) put(name, contents)
159
181
  console.log(check ? 'Contract documents are current.' : `Wrote ${changed.length} contract documents.`)
@@ -238,10 +260,13 @@ function oldClauseBody(text, clause) {
238
260
  const lines = linesOf(text), start = clause.line - 1, first = lines[start]
239
261
  const bold = /^(-\s+)?\*\*[^*]+\*\*\s*/.exec(first)
240
262
  const body = [bold ? first.slice(bold[0].length) : '']
263
+ let fence
241
264
  for (let index = start + 1; index < lines.length; index++) {
242
265
  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
266
+ const insideFence = Boolean(fence), state = covFence(line, fence)
267
+ fence = state.current
268
+ if (!insideFence && !state.marker && (/^#{1,6}\s/.test(line) || new RegExp(`^(?:-\\s+)?\\*\\*${clauseIdSource}\\s+[—–-]\\s+`).test(line))) break
269
+ if (bold?.[1] && line.trim() && !/^[ \t>]/.test(line) && !insideFence && !state.marker) break
245
270
  body.push(bold?.[1] ? line.replace(/^ {1,2}/, '') : line)
246
271
  }
247
272
  return block(body.join('\n'))
@@ -259,8 +284,20 @@ function acceptanceEntries(text, ids) {
259
284
  }
260
285
  return result
261
286
  }
262
- function requirementAndAcceptance(body, oldAcceptance) {
263
- const history = [], status = /\*{1,2}Status:\*{1,2}\s*(?:done|partial|missing)\b/i.exec(body)
287
+ function requirementAndAcceptance(body, oldAcceptance, clause) {
288
+ // Blockquote syntax is presentation, not part of a retained obligation.
289
+ body = withoutQuoteMarkers(body)
290
+ oldAcceptance = oldAcceptance === undefined ? undefined : withoutQuoteMarkers(oldAcceptance)
291
+ const history = []
292
+ // A leading status records the judgment, not the end of the requirement.
293
+ // Keep its complete line in history, then read the prose below it normally.
294
+ const leadingStatus = /^(?:\*{1,2})?Status:(?:\*{1,2})?\s*(done|partial|missing)\b[^\n]*(?:\n|$)/i.exec(body)
295
+ if (leadingStatus) {
296
+ if (leadingStatus[1].toLowerCase() !== clause.status) throw Error(`${clause.id}: the leading Status line disagrees with its Status table.`)
297
+ history.push(block(leadingStatus[0]))
298
+ body = block(body.slice(leadingStatus[0].length))
299
+ }
300
+ const status = /\*{1,2}Status:\*{1,2}\s*(?:done|partial|missing)\b/i.exec(body)
264
301
  if (status) { history.push(body.slice(status.index)); body = body.slice(0, status.index).trim() }
265
302
  const markerPattern = /(?:\*{1,2}Acceptance(?: evidence)?[:.]\*{1,2}|\*\*Acceptance\*\*[:.]?)/i
266
303
  const acceptanceMarker = markerPattern.exec(body)
@@ -280,21 +317,142 @@ function requirementAndAcceptance(body, oldAcceptance) {
280
317
  }
281
318
  return { text: result.join('\n\n'), history }
282
319
  }
283
- function contractClaims(old) {
320
+ // Only spellings observed in the launch seeds' immutable homepage tables.
321
+ const claimHeaders = new Set(['claim', 'claims', 'claim on the page', 'what the page claims', 'claim text'])
322
+ function claimHeader(cell) {
323
+ const value = plainText(cell).toLowerCase()
324
+ if (claimHeaders.has(value)) return 'Claim'
325
+ if (['clause', 'clauses', 'clause(s)', 'clause id(s)'].includes(value)) return 'Clauses'
326
+ if (value === 'claim #') return '#'
327
+ return plainText(cell)
328
+ }
329
+ const claimValue = (row, label) => row.cells[row.header.findIndex(cell => new RegExp(`^${label}$`, 'i').test(claimHeader(cell)))] ?? ''
330
+ const claimRows = text => homepageClaims(text).flatMap(table => table.rows.map(row => ({ ...row, header: table.header })))
331
+ function originalClaims(old) {
284
332
  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
333
  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 })))
334
+ const rows = winner?.tables.flatMap(table => table.rows.map(row => ({ ...row, header: table.header }))) ?? []
335
+ return { file: winner?.name, rows }
336
+ }
337
+ function nonProductBasis(source, basis, ids, label) {
338
+ // These are explicit classifications, never a fallback for an unresolved ID.
339
+ const allowed = {
340
+ 'license/public-repository ownership': /^["“]?(?:100% free, open source alternative to [^"”\n]+|100% free and open source\. MIT licensed\.|MIT licen[cs](?:e|ed)\.?)["”]?$/i,
341
+ 'launcher identity': /^(?:Terminal:\s*)?`npx -y @runeditrun\/rer dev [^`]+` starts [\w -]+\.?$/,
342
+ 'hosted-demo action': /^["“]Try the demo["”] opens the hosted demo\.?$/i,
343
+ 'boundary': /^Limits:\s*["“]No [^"”\n]+["”]\.?$/i,
344
+ }
345
+ const references = plainText(source.clauses).trim()
346
+ const allowedReferences = basis === 'boundary'
347
+ ? /^none needed: a boundary, true of the code\.?$/i.test(references)
348
+ : ['', '—', 'OWN'].includes(references)
349
+ if (!Object.hasOwn(allowed, basis) || !allowed[basis].test(source.claim) ||
350
+ !allowedReferences || idsIn(source.clauses).some(id => ids.has(id)))
351
+ throw Error(`${label}: non-product basis must explicitly describe a license/public-repository ownership, launcher identity, hosted-demo action or boundary with its required original references and no original product clause link; product promises need real clauses.`)
352
+ }
353
+ function sourceClaim(file, row, index) {
354
+ return { file, line: row.line, number: claimValue(row, '#') || String(index + 1), claim: claimValue(row, 'Claim'), status: claimValue(row, 'Status'), clauses: claimValue(row, 'Clauses?'), text: row.raw }
355
+ }
356
+ function readClaimSource(text) {
357
+ const records = [...text.matchAll(/<!-- contract-claim-source\s*\n([\s\S]*?)\n-->/g)]
358
+ if (records.length > 1) throw Error('CONTRACT.md: duplicate contract-claim-source record.')
359
+ if (!records.length) return undefined
360
+ let record
361
+ try { record = JSON.parse(records[0][1]) } catch { throw Error('CONTRACT.md: invalid contract-claim-source JSON.') }
362
+ if (record?.schema !== 1 || !/^[0-9a-f]{40}$/.test(record.old) || !Array.isArray(record.claims)) throw Error('CONTRACT.md: contract-claim-source needs schema 1, a full old SHA and claims.')
363
+ return record
364
+ }
365
+ function validateClaimSource(text, rows = claimRows(text), old) {
366
+ const record = readClaimSource(text)
367
+ if (!record) {
368
+ if (rows.some(row => claimValue(row, 'Basis') && claimValue(row, 'Basis') !== 'Product')) throw Error('CONTRACT.md: non-product claims require a contract-claim-source record.')
369
+ return undefined
370
+ }
371
+ if (old && record.old !== old.commit) throw Error('CONTRACT.md: contract-claim-source old SHA differs from the coverage original.')
372
+ let original
373
+ try { original = old ?? snapshot(record.old) } catch (error) { throw Error(`CONTRACT.md: contract-claim-source old ${record.old}: ${error.message}`) }
374
+ const selected = originalClaims(original), ids = new Set(parseContract(original.files['CONTRACT.md']).clauses.map(clause => clause.id))
375
+ validateOriginalClaims(original, rows)
376
+ if (record.claims.length !== selected.rows.length) throw Error('CONTRACT.md: contract-claim-source must retain every original claim once.')
377
+ for (const [index, source] of record.claims.entries()) {
378
+ const expected = sourceClaim(selected.file, selected.rows[index], index), label = `CONTRACT.md: contract-claim-source claim ${index + 1}`
379
+ if (!source || Object.entries(expected).some(([key, value]) => source[key] !== value)) throw Error(`${label}: source SHA/file/line/number/text/historical status must match the immutable original.`)
380
+ const row = rows[index]
381
+ if (claimValue(row, '#') !== source.number || claimValue(row, 'Claim') !== source.claim) throw Error(`${label}: current claim number/text must match the original.`)
382
+ const basis = claimValue(row, 'Basis')
383
+ if (source.nonProduct !== undefined) {
384
+ nonProductBasis(source, source.nonProduct, ids, label)
385
+ if (basis !== `Non-product: ${source.nonProduct}` || claimValue(row, 'Clauses?')) throw Error(`${label}: explicit non-product basis and empty Clauses cell required.`)
386
+ } else if (basis && basis !== 'Product') throw Error(`${label}: product claim cannot acquire a non-product exemption.`)
387
+ }
388
+ return record
389
+ }
390
+ function validateOriginalClaims(old, rows = claimRows(read('CONTRACT.md'))) {
391
+ const selected = originalClaims(old), remaining = [...rows], problems = []
392
+ // An empty history imposes no retention constraint; current claims stay unique.
393
+ if (!selected.rows.length) {
394
+ const claims = rows.map(row => claimValue(row, 'Claim'))
395
+ if (new Set(claims).size === claims.length) return
396
+ }
397
+ for (const [index, row] of selected.rows.entries()) {
398
+ const source = sourceClaim(selected.file, row, index)
399
+ const found = remaining.findIndex(current => claimValue(current, '#') === source.number && claimValue(current, 'Claim') === source.claim)
400
+ if (found < 0) problems.push(`${source.file}:${source.line}: missing original Homepage claim ${source.number}: ${source.claim}; current claim number/text must match the original.`)
401
+ else remaining.splice(found, 1)
402
+ }
403
+ if (remaining.length) problems.push('CONTRACT.md: unexpected or duplicate Homepage claims.')
404
+ if (problems.length) throw Error('CONTRACT.md: must retain every original claim once.\n' + problems.join('\n'))
405
+ }
406
+ function contractClaims(old, ids, claimMapPath) {
407
+ const { file, rows } = originalClaims(old), value = claimValue
408
+ const mapped = new Map()
409
+ if (claimMapPath !== undefined) {
410
+ const source = read(claimMapPath)
411
+ if (source === undefined) throw Error(`${claimMapPath}: claim map does not exist.`)
412
+ let map
413
+ try { map = JSON.parse(source) } catch (error) { throw Error(`${claimMapPath}: invalid claim map JSON: ${error.message}`) }
414
+ if (map?.schema !== 1 || map.old !== old.commit || !Array.isArray(map.claims))
415
+ throw Error(`${claimMapPath}: claim map needs schema 1, old ${old.commit}, and a claims list.`)
416
+ for (const entry of map.claims) {
417
+ if (!entry || entry.file !== file || !Number.isInteger(entry.line) || entry.line < 1)
418
+ throw Error(`${claimMapPath}: each claim mapping needs file ${file ?? 'CONTRACT.md'} and its original positive line number.`)
419
+ const row = rows.find(row => row.line === entry.line)
420
+ const label = `${claimMapPath}: ${entry.file}:${entry.line}`
421
+ if (!row) throw Error(`${label}: not a selected original homepage claim row.`)
422
+ if (mapped.has(entry.line)) throw Error(`${label}: duplicate claim mapping; supply one clauses list per row.`)
423
+ if (entry.claim !== value(row, 'Claim')) throw Error(`${label}: claim must exactly match ${JSON.stringify(value(row, 'Claim'))}.`)
424
+ if (entry.nonProduct !== undefined) {
425
+ if (entry.clauses !== undefined) throw Error(`${label}: non-product mapping cannot also supply clauses.`)
426
+ nonProductBasis(sourceClaim(file, row, rows.indexOf(row)), entry.nonProduct, ids, label)
427
+ mapped.set(entry.line, { nonProduct: entry.nonProduct })
428
+ continue
429
+ }
430
+ if (!Array.isArray(entry.clauses) || !entry.clauses.length || new Set(entry.clauses).size !== entry.clauses.length)
431
+ throw Error(`${label}: clauses must be a non-empty list of distinct existing product clause ids.`)
432
+ for (const id of entry.clauses) if (typeof id !== 'string' || !idPattern.test(id) || !ids.has(id))
433
+ throw Error(`${label}: unknown product clause ${JSON.stringify(id)}; use an id defined in the original contract.`)
434
+ mapped.set(entry.line, { clauses: entry.clauses })
435
+ }
436
+ }
437
+ if (!rows.length) return 'No homepage claims are mapped yet.'
288
438
  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(' | ')} |`]
439
+ const hasNonProduct = [...mapped.values()].some(entry => entry.nonProduct)
440
+ const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasNonProduct ? ['Basis'] : [])]
441
+ const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], problems = []
291
442
  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(' | ')} |`)
443
+ const mapping = mapped.get(row.line), nonProduct = mapping?.nonProduct
444
+ const references = nonProduct ? '' : mapping?.clauses.join(', ') ?? value(row, 'Clauses?')
445
+ const linked = idsIn(references)
446
+ if (!nonProduct && (!linked.length || linked.some(id => !ids.has(id))))
447
+ problems.push(`${file}:${row.line}: Homepage claim ${JSON.stringify(value(row, 'Claim'))} needs existing product clause ids (found ${JSON.stringify(references)}). Supply --claim-map <file> with schema 1, old ${old.commit}, and claims entries {file, line, claim, clauses}; map only to the actual obligations, never invent a link.`)
448
+ table.push(`| ${[value(row, '#') || String(index + 1), ...(hasSection ? [value(row, 'Section')] : []), value(row, 'Claim'), references, ...(hasNonProduct ? [nonProduct ? `Non-product: ${nonProduct}` : 'Product'] : [])].map(tableCell).join(' | ')} |`)
294
449
  }
450
+ if (problems.length) throw Error(problems.join('\n'))
451
+ if (hasNonProduct) table.unshift('Explicit non-product facts have current derived status unassessed. The source record retains historical statuses as history, not current proof.', '')
452
+ table.push('', '<!-- contract-claim-source', json({ schema: 1, old: old.commit, claims: rows.map((row, index) => ({ ...sourceClaim(file, row, index), ...(mapped.get(row.line)?.nonProduct ? { nonProduct: mapped.get(row.line).nonProduct } : {}) })) }).replaceAll('|', '\\u007c').trimEnd(), '-->')
295
453
  return table.join('\n')
296
454
  }
297
- function convert(old, acceptanceOld) {
455
+ function convert(old, acceptanceOld, claimMapPath) {
298
456
  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
457
  const acceptanceSource = acceptanceOld?.files['ACCEPTANCE.md'] ?? old.files['ACCEPTANCE.md']
300
458
  const acceptances = acceptanceEntries(acceptanceSource, ids)
@@ -316,7 +474,7 @@ function convert(old, acceptanceOld) {
316
474
  output.push('## Shared duties (Base)', '| Base duty | Duty | Delta clauses | Base journey |\n| --- | --- | --- | --- |')
317
475
  const clauseContent = new Map(), extraHistory = []
318
476
  for (const clause of parsed.clauses) {
319
- const converted = requirementAndAcceptance(oldClauseBody(text, clause), acceptances.get(clause.id))
477
+ const converted = requirementAndAcceptance(oldClauseBody(text, clause), acceptances.get(clause.id), clause)
320
478
  clauseContent.set(clause.id, converted.text)
321
479
  extraHistory.push(...converted.history)
322
480
  }
@@ -341,7 +499,7 @@ function convert(old, acceptanceOld) {
341
499
  }
342
500
  }
343
501
  }
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))
502
+ 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, ids, claimMapPath))
345
503
  const retired = outline(text).filter(entry => entry.level === 2 && /^Retired\b/i.test(entry.title))
346
504
  if (retired.length) {
347
505
  const contents = retired.map(entry => block(lines.slice(entry.start + 1, entry.end).join('\n'))).join('\n\n')
@@ -377,7 +535,7 @@ const covHeading = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
377
535
  const covDefinition = new RegExp(`^(?:#{1,6}\\s+|(?:[-*+]\\s+)?\\*\\*)(${clauseIdSource})\\s+[—–-]\\s+`);
378
536
  const covSplit = text => text.replace(/\r\n?/g, '\n').split('\n');
379
537
  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, '') : '';
538
+ const covNormalize = text => typeof text === 'string' ? withoutQuoteMarkers(text).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, '').replace(/[`*_]/g, '').replace(/\s+/gu, '') : '';
381
539
  const covKey = entry => JSON.stringify([entry.file, entry.line, entry.cell ?? '']);
382
540
  const covLabel = entry => `${entry.file}:${entry.line}${entry.cell ? ` (${entry.cell})` : ''}`;
383
541
 
@@ -416,6 +574,15 @@ function covFence(line, current) {
416
574
  if (marker[0] === current[0] && marker.length >= current.length) return { current: undefined, marker: true };
417
575
  return { current, marker: false };
418
576
  }
577
+ function withoutQuoteMarkers(text) {
578
+ let fence;
579
+ return linesOf(text).map(line => {
580
+ const state = covFence(line, fence);
581
+ const value = state.marker || fence ? line : line.replace(/^[ \t]*(?:>[ \t]?)+/, '');
582
+ fence = state.current;
583
+ return value;
584
+ }).join('\n');
585
+ }
419
586
 
420
587
  // A claims heading owns its descendants until a sibling or ancestor ends it.
421
588
  // A more specific claims heading, such as Opt-out claims, owns its own tables.
@@ -438,12 +605,17 @@ function homepageClaims(text) {
438
605
  if (!owner || !/\bhomepage\s+claims\b/i.test(owner.text) || /\bopt[ -]?out\b/i.test(owner.text)) continue;
439
606
  if (!value.includes('|') || !covDivider(lines[i + 1]?.text ?? '')) continue;
440
607
  const header = covCells(value);
441
- if (!header.some(cell => /^claims?$/i.test(plainText(cell)))) continue;
608
+ if (!header.some(cell => claimHeader(cell) === 'Claim')) {
609
+ // Handwritten claims files also contain clause-status appendices under
610
+ // their document title. Those are not homepage claim tables.
611
+ if (/^Clause$/i.test(plainText(header[0])) && header.some(cell => /^Status$/i.test(plainText(cell)))) continue;
612
+ throw Error(`Homepage claims:${i + 1}: unrecognized claim heading: ${value}`);
613
+ }
442
614
  const rows = [];
443
615
  let next = i + 2;
444
616
  while (next < lines.length && lines[next].text.trim() && lines[next].text.includes('|') && !covHeading.test(lines[next].text)) {
445
617
  const row = lines[next];
446
- if (covDivider(row.text) || covCells(row.text).length !== header.length) break;
618
+ if (covDivider(row.text) || covCells(row.text).length !== header.length) throw Error(`Homepage claims:${next + 1}: malformed row: ${row.raw}`);
447
619
  rows.push({ line: next + 1, cells: covCells(row.text), raw: row.raw });
448
620
  next++;
449
621
  }
@@ -478,7 +650,7 @@ function covScope(old) {
478
650
  if (level > 1 || introStarted) introEnded = true;
479
651
  continue;
480
652
  }
481
- if (!text.trim()) { if (introStarted) introEnded = true; continue; }
653
+ if (!(insideFence ? text : withoutQuoteMarkers(text)).trim()) { if (introStarted) introEnded = true; continue; }
482
654
  if (covDivider(text)) continue;
483
655
  if (definition) clause = definition[1];
484
656
  const section = [...headings].reverse().find(entry => entry.level === 2)?.text ?? '';
@@ -552,7 +724,8 @@ function covPlacement(entry, current, contractEntries) {
552
724
  if (entry.file === 'ACCEPTANCE.md') {
553
725
  const repeated = covRepeated(entry, contractEntries);
554
726
  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.' };
727
+ if (covGeneratedStatement(entry.text)) return { to: 'generated', note: 'The contract generator writes this status or count.' };
728
+ if (entry.clause) return { to: 'clause', ids: current.from.get(entry.clause) ?? [entry.clause] };
556
729
  return { to: 'docs', path: 'docs/verify.md' };
557
730
  }
558
731
  if (entry.file !== 'CONTRACT.md') return { to: 'changelog' };
@@ -585,7 +758,7 @@ function coverageInit(old) {
585
758
  function covDestination(destination, fragment, source, context, problems, label) {
586
759
  const fail = message => problems.push(`${label}: ${message}`);
587
760
  if (!destination || typeof destination !== 'object' || Array.isArray(destination)) { fail('A destination must be an object.'); return; }
588
- const { current, old, expected, groups } = context;
761
+ const { current, expected, groups } = context;
589
762
  const note = () => { if (typeof destination.note !== 'string' || !destination.note.trim()) fail(`${destination.to} needs a note.`); };
590
763
  const ids = known => {
591
764
  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; }
@@ -637,6 +810,8 @@ function covDestination(destination, fragment, source, context, problems, label)
637
810
  }
638
811
  }
639
812
  function coverageCheck(old) {
813
+ validateOriginalClaims(old);
814
+ validateClaimSource(read('CONTRACT.md'), undefined, old);
640
815
  const map = covReadMap(), problems = [], entries = covScope(old), expected = new Map(entries.map(entry => [covKey(entry), entry])), groups = new Map();
641
816
  if (map.schema !== 1) problems.push('Coverage schema must be 1.');
642
817
  if (map.old?.commit !== old.commit) problems.push(`Coverage old.commit must equal ${old.commit}; found ${JSON.stringify(map.old?.commit)}.`);
@@ -735,20 +910,33 @@ function coverageRebase(from, onto) {
735
910
  return { ...map, old: { commit: onto.commit, files: covFiles(onto) }, fragments };
736
911
  }
737
912
 
913
+ function checkProse() {
914
+ const text = read('CONTRACT.md');
915
+ if (text === undefined) throw Error('CONTRACT.md does not exist.');
916
+ const coverage = read(covMapPath) === undefined ? undefined : covReadMap();
917
+ const sources = coverage ? covScope(snapshot(coverage.old?.commit)) : [];
918
+ const findings = contractProseFindings({ text, clauses: parseContract(withoutSummary(text)).clauses, coverage, sources, generatedStatement: covGeneratedStatement });
919
+ if (printProseFindings(findings)) process.exitCode = 1;
920
+ }
921
+
922
+ const usage = 'Usage: contract-docs.mjs write|check|check-prose|id-map --old <ref>|coverage init|check --old <ref>|coverage rebase --from <ref> --onto <ref>|convert --old <ref> [--old-acceptance <ref>] [--claim-map <file>]';
738
923
  function main(args) {
739
924
  const [command, ...rest] = args
740
- const option = name => {
925
+ const option = (name, description = 'Git reference') => {
741
926
  const index = rest.indexOf(name)
742
- if (index < 0 || !rest[index + 1] || rest[index + 1].startsWith('--')) throw Error(`Provide ${name} and its Git reference.`)
927
+ if (index < 0 || !rest[index + 1] || rest[index + 1].startsWith('--')) throw Error(`Provide ${name} and its ${description}.`)
928
+ if (rest.lastIndexOf(name) !== index) throw Error(`Provide ${name} only once.`)
743
929
  return rest[index + 1]
744
930
  }
745
931
  if (command === 'write' && !rest.length) generate()
746
- else if (command === 'check' && !rest.length) generate(true)
932
+ else if (command === 'check' && !rest.length) { checkProse(); generate(true) }
933
+ else if (command === 'check-prose' && !rest.length) checkProse()
934
+ else if (command === '--help' && !rest.length) console.log(usage)
747
935
  else if (command === 'id-map') idMap(snapshot(option('--old')))
748
936
  else if (command === 'coverage' && rest[0] === 'init') coverageInit(snapshot(option('--old')))
749
937
  else if (command === 'coverage' && rest[0] === 'check') coverageCheck(snapshot(option('--old')))
750
938
  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>]')
939
+ else if (command === 'convert') convert(snapshot(option('--old')), rest.includes('--old-acceptance') ? snapshot(option('--old-acceptance')) : undefined, rest.includes('--claim-map') ? option('--claim-map', 'JSON file path') : undefined)
940
+ else throw Error(usage)
753
941
  }
754
942
  try { main(process.argv.slice(2)) } catch (error) { console.error(error.message); process.exitCode = 1 }