rungate 0.4.1 → 0.6.0

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 (87) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/agents-md-sections.ts +144 -0
  11. package/lib/branch-diff.ts +139 -0
  12. package/lib/bun-version.ts +268 -0
  13. package/lib/ci-checkout.ts +1 -1
  14. package/lib/cli-commands.ts +7 -1
  15. package/lib/compliance.ts +13 -11
  16. package/lib/config-loader.ts +12 -0
  17. package/lib/conformity.ts +1147 -116
  18. package/lib/context-docs.ts +143 -28
  19. package/lib/create-brief.ts +2 -1
  20. package/lib/create-sc.ts +90 -4
  21. package/lib/doc-scan-targets.ts +9 -0
  22. package/lib/evidence-command-transport.ts +160 -0
  23. package/lib/evidence-prevalidator.ts +22 -0
  24. package/lib/fallow-availability.ts +129 -0
  25. package/lib/gate-refusal-currency.ts +112 -0
  26. package/lib/gate-timeouts.ts +82 -0
  27. package/lib/generators/agent-briefs.ts +4 -1
  28. package/lib/generators/agents-md.ts +71 -23
  29. package/lib/generators/code-map.ts +2 -1
  30. package/lib/generators/types.ts +8 -0
  31. package/lib/git-dates.ts +55 -0
  32. package/lib/github.ts +195 -0
  33. package/lib/js-top-level-code.ts +27 -2
  34. package/lib/junit-checks.ts +484 -0
  35. package/lib/local-calendar-day.ts +78 -0
  36. package/lib/package-closure.ts +278 -2
  37. package/lib/project-state-shape.ts +59 -0
  38. package/lib/promote-outputs.ts +6 -2
  39. package/lib/release-preflight.ts +196 -0
  40. package/lib/report-provenance.ts +156 -0
  41. package/lib/sc-claim-forms.ts +75 -0
  42. package/lib/sc-id-cross-tree.ts +311 -0
  43. package/lib/scaffold/ai-review-step.ts +180 -0
  44. package/lib/scaffold/defaults.ts +40 -0
  45. package/lib/scaffold/managed-workflow.ts +125 -27
  46. package/lib/scaffold/owned-files.ts +48 -2
  47. package/lib/scaffold/profiles.ts +94 -0
  48. package/lib/scaffold/rehearsal.ts +232 -73
  49. package/lib/scaffold/steps.ts +777 -152
  50. package/lib/scaffold/write-steps.ts +56 -13
  51. package/lib/scanner.ts +38 -12
  52. package/lib/source-anchor.ts +144 -0
  53. package/lib/spec-listing.ts +148 -0
  54. package/lib/spec-requirements.ts +209 -0
  55. package/lib/success-doc.ts +779 -0
  56. package/lib/suite-run-reading.ts +364 -0
  57. package/lib/test-census.ts +199 -0
  58. package/lib/test-command.ts +133 -0
  59. package/lib/test-suite-lock.ts +166 -10
  60. package/lib/tool-probe.ts +120 -0
  61. package/lib/tracked-vs-ignored.ts +234 -0
  62. package/lib/trajectory.ts +377 -0
  63. package/lib/validators/spec-validators.ts +35 -6
  64. package/lib/workflow-security.ts +101 -0
  65. package/lib/workflow-test-harness.ts +349 -0
  66. package/package.json +6 -1
  67. package/scripts/audit-specs.ts +247 -12
  68. package/scripts/audit-transcript.ts +2 -1
  69. package/scripts/convert-spec.ts +2 -1
  70. package/scripts/create-sc.ts +17 -7
  71. package/scripts/create-spec.ts +2 -1
  72. package/scripts/create-success.ts +163 -0
  73. package/scripts/extract-constraints.ts +90 -19
  74. package/scripts/generate-code-map.ts +53 -12
  75. package/scripts/scaffold-project.ts +31 -4
  76. package/scripts/split-spec.ts +2 -1
  77. package/scripts/sync-sc-status.ts +57 -5
  78. package/scripts/sync-spec-tests.ts +2 -1
  79. package/specs/SPEC-TEMPLATE.md +200 -0
  80. package/templates/SUCCESS-TEMPLATE.md +72 -0
  81. package/templates/agent-briefs/_shared.md +9 -0
  82. package/templates/agent-briefs/aditi.md +46 -0
  83. package/templates/agent-briefs/discovery.md +37 -0
  84. package/templates/agent-briefs/marcus.md +39 -0
  85. package/templates/agent-briefs/quinn.md +67 -0
  86. package/templates/agent-briefs/rook.md +40 -0
  87. package/templates/agent-briefs/serena.md +39 -0
@@ -0,0 +1,65 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Prove Evidence",
4
+ "description": "Output artifact from /prove skill",
5
+ "type": "object",
6
+ "required": ["contractVersion", "issueNumber", "verdict", "commitSHA", "capturedAt", "criteriaResults"],
7
+ "properties": {
8
+ "contractVersion": { "type": "string" },
9
+ "issueNumber": { "type": "integer" },
10
+ "verdict": { "type": "string", "enum": ["PROVEN", "UNPROVEN", "INCONCLUSIVE"] },
11
+ "commitSHA": { "type": "string" },
12
+ "capturedAt": { "type": "string", "format": "date-time" },
13
+ "beforeEvidence": {
14
+ "type": "object",
15
+ "properties": {
16
+ "type": { "type": "string", "enum": ["text", "screenshot", "api", "none"] },
17
+ "path": { "type": ["string", "null"] },
18
+ "capturedAt": { "type": ["string", "null"] },
19
+ "description": { "type": "string" }
20
+ }
21
+ },
22
+ "afterEvidence": {
23
+ "type": "object",
24
+ "properties": {
25
+ "type": { "type": "string", "enum": ["text", "screenshot", "api"] },
26
+ "path": { "type": "string" },
27
+ "capturedAt": { "type": "string", "format": "date-time" },
28
+ "environment": { "type": "string", "enum": ["local", "prod"] },
29
+ "description": { "type": "string" }
30
+ }
31
+ },
32
+ "comparisonSummary": { "type": "string" },
33
+ "quinnVerdict": { "type": "string", "enum": ["PASS", "FAIL", "SKIP"] },
34
+ "reproduced": { "type": "boolean" },
35
+ "criteriaResults": {
36
+ "type": "array",
37
+ "minItems": 1,
38
+ "items": {
39
+ "type": "object",
40
+ "required": ["scId", "verdict", "evidence"],
41
+ "properties": {
42
+ "scId": { "type": "string" },
43
+ "verdict": { "type": "string", "enum": ["PASS", "FAIL", "SKIP"] },
44
+ "evidence": { "type": "string" },
45
+ "evidencePath": { "type": ["string", "null"] },
46
+ "exitCode": { "type": ["integer", "null"] }
47
+ }
48
+ }
49
+ },
50
+ "gaps": {
51
+ "type": "array",
52
+ "items": {
53
+ "type": "object",
54
+ "required": ["ac", "status"],
55
+ "properties": {
56
+ "ac": { "type": "string" },
57
+ "status": { "type": "string" },
58
+ "detail": { "type": "string" },
59
+ "priority": { "type": ["string", "null"] },
60
+ "followUpIssue": { "type": ["string", "null"] }
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "description": "Data-driven spec-alignment checks — Decision #3",
3
+ "forbiddenTargets": {
4
+ "patterns": ["SKILL\\.md"],
5
+ "scope": ["statement", "evidenceMethod.command"],
6
+ "message": "enforcement goes in scripts/hooks/gates, not SKILL.md (decision #4)"
7
+ },
8
+ "forbiddenLanguage": {
9
+ "patterns": ["DA should", "remember to", "must manually", "don.t forget", "should remember", "needs to remember"],
10
+ "scope": ["statement"],
11
+ "message": "use mechanical enforcement instead (decision #8)"
12
+ },
13
+ "implementationPatterns": {
14
+ "data-driven-enforcement": {
15
+ "decision": "#3",
16
+ "description": "Enforcement via JSON data, not inline code",
17
+ "antiPatterns": ["hardcoded.*(rule|check|gate)", "inline.*(validation|enforcement)"],
18
+ "scope": ["statement"],
19
+ "message": "enforcement should be data-driven — add patterns to JSON, not inline code (decision #3)"
20
+ },
21
+ "deep-modules-thin-consumers": {
22
+ "decision": "#7",
23
+ "description": "Shared logic in scripts/lib/, consumers call one function",
24
+ "antiPatterns": ["duplicate.*(logic|function|helper)", "copy.*(shared|lib|util)"],
25
+ "scope": ["statement"],
26
+ "message": "shared logic goes in scripts/lib/ — consumers import and call (decision #7)"
27
+ },
28
+ "warn-before-fail": {
29
+ "decision": "#9",
30
+ "description": "New checks start as WARN, promote to FAIL after precision data",
31
+ "antiPatterns": ["new.*(check|gate).*expect.*fail", "add.*expect.*throw.*new"],
32
+ "scope": ["statement", "evidenceMethod.command"],
33
+ "message": "new checks ship as WARN — promote to FAIL only with >80% precision over 10+ cycles (decision #9)"
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,15 @@
1
+ # Universal rules — loaded by scaffold into every generated AGENTS.md
2
+ # Consumer projects can override or extend via a `rules` array in .claude/rungate.json
3
+ #
4
+ # These were previously hardcoded in lib/generators/agents-md.ts.
5
+ # Now loaded from config so they can be customized per-deployment.
6
+
7
+ rules:
8
+ - "Verify before asserting — try it first, report what actually happened"
9
+ - "Never fake results or hide failures — if it fails, report it honestly"
10
+ - "Fix all test failures before reporting done — a green suite is the minimum bar"
11
+ - "Run full test suite and show real output — no summaries, no skipped files"
12
+ - "Read docs before writing code — routing table shows where"
13
+ - "Fix the source, not the output — fix generator, not generated files"
14
+ - "Commit all changes before reporting done — uncommitted work is lost work"
15
+ - "Read PROJECT-STATE.md first on session start — it's the session bridge"
@@ -0,0 +1,279 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "workflow-state",
4
+ "description": "Ship harness v2 — single state file per issue. All gates read/write this file. See gateContract for expected field values per gate check.",
5
+ "type": "object",
6
+ "required": ["schemaVersion", "issue", "repo", "slug", "phase"],
7
+ "properties": {
8
+ "schemaVersion": { "const": 2 },
9
+ "issue": { "type": "integer", "description": "GitHub issue number" },
10
+ "repo": { "type": "string", "description": "owner/repo" },
11
+ "issueRepo": { "type": "string", "description": "owner/repo for GitHub issues (if different from code repo)" },
12
+ "projectRoot": { "type": "string", "description": "Absolute path to the project root directory" },
13
+ "slug": { "type": "string", "description": "YYYYMMDD-HHMMSS_kebab-description" },
14
+ "phase": {
15
+ "enum": ["GOAL", "DISCOVERY", "SCOPE", "BUILD", "VERIFY", "SHIP", "DONE", "CIRCUIT_BREAK"],
16
+ "description": "Current phase in the single loop"
17
+ },
18
+
19
+ "issueGoal": {
20
+ "type": "string",
21
+ "description": "Verbatim Goal section from GitHub issue — never paraphrased by DA"
22
+ },
23
+
24
+ "sourceSpecs": {
25
+ "type": "array",
26
+ "items": {
27
+ "type": "object",
28
+ "required": ["path", "citedInDiscovery"],
29
+ "properties": {
30
+ "path": { "type": "string", "description": "File path or URL to the spec" },
31
+ "citedInDiscovery": { "type": "boolean", "description": "Was this spec actually read with file:line citations?" },
32
+ "specElements": {
33
+ "type": "array",
34
+ "items": { "type": "string" },
35
+ "description": "Key structural elements from the spec (e.g. '6 horizontal layers', '11 consumers')"
36
+ }
37
+ }
38
+ }
39
+ },
40
+
41
+ "sizing": {
42
+ "type": "object",
43
+ "properties": {
44
+ "predicted": { "enum": ["XS", "S", "M", "L"] },
45
+ "ceremonyTier": { "enum": ["LIGHT", "STANDARD", "THOROUGH"] },
46
+ "actualFiles": { "type": "integer" },
47
+ "actualMinutes": { "type": "integer" }
48
+ }
49
+ },
50
+
51
+ "acs": {
52
+ "type": "array",
53
+ "items": {
54
+ "type": "object",
55
+ "required": ["id", "type", "statement"],
56
+ "properties": {
57
+ "id": { "type": "string", "pattern": "^AC-[0-9]+$" },
58
+ "type": { "enum": ["CODE", "OUTCOME"] },
59
+ "statement": { "type": "string" },
60
+ "specElement": { "type": "string", "description": "Which spec element this AC traces to" },
61
+ "threshold": {
62
+ "type": "object",
63
+ "properties": {
64
+ "op": { "enum": ["==", ">=", "<=", ">", "<", "!=", "contains", "exists"] },
65
+ "value": {},
66
+ "unit": { "type": "string" }
67
+ }
68
+ },
69
+ "evidenceMethod": {
70
+ "type": "object",
71
+ "properties": {
72
+ "type": { "enum": ["GREP_CHECK", "FILE_EXISTS", "CURL_CHECK", "BUN_TEST", "SCREENSHOT", "PLAYWRIGHT", "COMMAND", "MANUAL"] },
73
+ "command": { "type": "string" }
74
+ }
75
+ },
76
+ "evidence": {
77
+ "type": ["object", "null"],
78
+ "properties": {
79
+ "type": { "enum": ["file-citation", "grep-output", "api-response", "screenshot", "test-output", "command-output", "manual-attestation"] },
80
+ "content": { "type": "string" },
81
+ "value": { "type": ["number", "null"], "description": "Structured numeric value for threshold comparison — avoids grep extraction ambiguity" },
82
+ "url": { "type": ["string", "null"] }
83
+ }
84
+ },
85
+ "contextFiles": {
86
+ "type": "array",
87
+ "items": {
88
+ "type": "object",
89
+ "properties": {
90
+ "path": { "type": "string", "description": "File path relative to project root" },
91
+ "lines": { "type": "string", "description": "Line range, e.g. '162-285'" },
92
+ "reason": { "type": "string", "description": "Why this file is relevant to the AC" }
93
+ },
94
+ "required": ["path"]
95
+ },
96
+ "description": "Source files relevant to this AC — used by brief-assembler to give Marcus context"
97
+ },
98
+ "verdict": { "enum": ["PENDING", "PASS", "FAIL"] }
99
+ }
100
+ }
101
+ },
102
+
103
+ "agents": {
104
+ "type": "object",
105
+ "default": {},
106
+ "properties": {
107
+ "marcus": {
108
+ "type": "object",
109
+ "properties": {
110
+ "spawned": { "type": "boolean" },
111
+ "verdict": { "enum": ["PASS", "FAIL", null] },
112
+ "branch": { "type": "string" },
113
+ "iterations": { "type": "integer" }
114
+ }
115
+ },
116
+ "quinn": {
117
+ "type": "object",
118
+ "properties": {
119
+ "spawned": { "type": "boolean" },
120
+ "verdict": { "enum": ["PASS", "FAIL", null] },
121
+ "comparedToSpec": { "type": "boolean" },
122
+ "screenshots": { "type": "array", "items": { "type": "string" } }
123
+ }
124
+ },
125
+ "rook": {
126
+ "type": "object",
127
+ "properties": {
128
+ "spawned": { "type": "boolean" },
129
+ "verdict": { "enum": ["PASS", "FAIL", null] },
130
+ "findings": { "type": ["string", "null"], "description": "Rook security scan findings summary" }
131
+ }
132
+ }
133
+ }
134
+ },
135
+
136
+ "environments": {
137
+ "type": "object",
138
+ "default": {},
139
+ "properties": {
140
+ "local": {
141
+ "type": "object",
142
+ "properties": {
143
+ "api": { "enum": ["PASS", "FAIL", "SKIP", null] },
144
+ "apiSkipReason": { "type": "string", "description": "Justification for skipping local API validation" },
145
+ "ui": { "enum": ["PASS", "FAIL", "SKIP", null] },
146
+ "uiSkipReason": { "type": "string", "description": "Justification for skipping local UI validation" },
147
+ "tests": { "enum": ["PASS", "FAIL", "SKIP", null] }
148
+ }
149
+ },
150
+ "prod": {
151
+ "type": "object",
152
+ "properties": {
153
+ "rebuild": { "enum": ["PASS", "FAIL", "SKIP", null] },
154
+ "rebuildSkipReason": { "type": "string", "description": "Justification for skipping prod rebuild" },
155
+ "smoke": { "enum": ["PASS", "FAIL", "SKIP", null] },
156
+ "smokeSkipReason": { "type": "string", "description": "Justification for skipping prod smoke test" },
157
+ "quinn": { "enum": ["PASS", "FAIL", "SKIP", null] },
158
+ "quinnSkipReason": { "type": "string", "description": "Justification for skipping prod Quinn validation" },
159
+ "quinnSpot": { "enum": ["PASS", "FAIL", "SKIP", null] },
160
+ "quinnSpotSkipReason": { "type": "string", "description": "Justification for skipping prod Quinn spot check" }
161
+ }
162
+ }
163
+ }
164
+ },
165
+
166
+ "gates": {
167
+ "type": "object",
168
+ "properties": {
169
+ "scope": {
170
+ "type": "object",
171
+ "properties": {
172
+ "result": { "enum": ["PASS", "FAIL", null] },
173
+ "attempt": { "type": "integer" },
174
+ "failures": { "type": "array", "items": { "type": "object" } },
175
+ "ts": { "type": "string" }
176
+ }
177
+ },
178
+ "verify": {
179
+ "type": "object",
180
+ "properties": {
181
+ "result": { "enum": ["PASS", "FAIL", null] },
182
+ "attempt": { "type": "integer" },
183
+ "failures": { "type": "array", "items": { "type": "object" } },
184
+ "ts": { "type": "string" }
185
+ }
186
+ },
187
+ "ship": {
188
+ "type": "object",
189
+ "properties": {
190
+ "result": { "enum": ["PASS", "FAIL", null] },
191
+ "attempt": { "type": "integer" },
192
+ "failures": { "type": "array", "items": { "type": "object" } },
193
+ "ts": { "type": "string" }
194
+ }
195
+ }
196
+ }
197
+ },
198
+ "iterationCount": { "type": "integer", "default": 0 },
199
+ "startTs": { "type": "string", "format": "date-time" },
200
+ "updatedTs": { "type": "string", "format": "date-time" },
201
+
202
+ "phaseTimings": {
203
+ "type": "object",
204
+ "description": "Per-phase timing entries for bottleneck analysis. Each phase maps to an array of entries — convergence loop re-entries create new entries rather than overwriting.",
205
+ "additionalProperties": {
206
+ "type": "array",
207
+ "items": {
208
+ "type": "object",
209
+ "properties": {
210
+ "enteredTs": { "type": "string", "format": "date-time" },
211
+ "exitedTs": { "type": "string", "format": "date-time" },
212
+ "iteration": { "type": "integer", "description": "Iteration number (1-based, for convergence loop re-entries)" },
213
+ "source": { "type": "string", "enum": ["gate-runner", "DA"], "description": "What wrote this timing entry" }
214
+ },
215
+ "required": ["enteredTs", "source"]
216
+ }
217
+ }
218
+ },
219
+
220
+ "gateContract": {
221
+ "type": "object",
222
+ "description": "Documents expected field paths and valid values for each gate check. DA reference — prevents setting fields to prose instead of enum values.",
223
+ "properties": {
224
+ "environments": {
225
+ "type": "object",
226
+ "description": "Expected values for environment validation fields",
227
+ "properties": {
228
+ "local.api": { "type": "string", "enum": ["PASS", "SKIP"], "description": "Set to PASS after API validation, SKIP with apiSkipReason" },
229
+ "local.ui": { "type": "string", "enum": ["PASS", "SKIP"], "description": "Set to PASS after UI validation, SKIP requires uiSkipReason field" },
230
+ "local.uiSkipReason": { "type": "string", "description": "Required when local.ui is SKIP" },
231
+ "local.tests": { "type": "string", "enum": ["PASS", "SKIP", "FAIL"], "description": "Set by Marcus after running tests. tests-pass reads this first." },
232
+ "prod.rebuild": { "type": "string", "enum": ["PASS", "SKIP"], "description": "SKIP requires rebuildSkipReason" },
233
+ "prod.smoke": { "type": "string", "enum": ["PASS", "SKIP"], "description": "SKIP requires smokeSkipReason" },
234
+ "prod.quinn": { "type": "string", "enum": ["PASS", "SKIP"], "description": "SKIP requires quinnSkipReason" }
235
+ }
236
+ },
237
+ "verdicts": {
238
+ "type": "object",
239
+ "description": "Valid verdict values for ACs and agents",
240
+ "properties": {
241
+ "ac.verdict": { "type": "string", "enum": ["PASS", "FAIL"], "description": "Each AC verdict must be exactly PASS or FAIL" },
242
+ "agent.verdict": { "type": "string", "enum": ["PASS", "FAIL", "SKIP"], "description": "Agent verdicts — SKIP requires skipReason" }
243
+ }
244
+ },
245
+ "evidence": {
246
+ "type": "object",
247
+ "description": "Valid evidence types",
248
+ "properties": {
249
+ "type": { "type": "string", "enum": ["file-citation", "grep-output", "api-response", "screenshot", "test-output", "command-output", "manual-attestation"] }
250
+ }
251
+ },
252
+ "baselines": {
253
+ "type": "object",
254
+ "description": "Baseline fields for repos with pre-existing issues",
255
+ "properties": {
256
+ "testBaseline": { "type": "integer", "description": "Pre-existing test failure count. tests-pass compares against this." },
257
+ "tscBaseline": { "type": "integer", "description": "Pre-existing TypeScript error count. tsc-pass compares against this." }
258
+ }
259
+ }
260
+ }
261
+ },
262
+
263
+ "changelog": {
264
+ "type": "array",
265
+ "description": "Append-only event log — never delete entries",
266
+ "items": {
267
+ "type": "object",
268
+ "required": ["ts", "event"],
269
+ "properties": {
270
+ "ts": { "type": "string", "format": "date-time" },
271
+ "event": { "type": "string" },
272
+ "detail": { "type": "string" },
273
+ "phase": { "type": "string" },
274
+ "actor": { "enum": ["da", "marcus", "quinn", "rook", "gate-runner"] }
275
+ }
276
+ }
277
+ }
278
+ }
279
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The one section of AGENTS.md the harness does not own (#568).
3
+ *
4
+ * `specs/bootstrap-data-flow/problem-statement.md` makes exactly one promise
5
+ * about user content surviving a scaffold run:
6
+ *
7
+ * > Everything is regenerable. All harness-managed files can be rebuilt
8
+ * > from scratch by re-running scaffold. **The only user-owned content
9
+ * > that survives regeneration is Hard Constraints in AGENTS.md**
10
+ * > (preserved between markers).
11
+ *
12
+ * Nothing implemented it. `lib/scaffold/write-steps.ts` built the file from
13
+ * a template and called `writeFileSync`, so the section and both extraction
14
+ * markers went with it. Measured on a consumer: 37 constraint lines removed
15
+ * by one run, reported as `REGENERATED: AGENTS.md`, exit 0.
16
+ *
17
+ * The cost is not the file. Those lines are the project's non-inferable
18
+ * rules — which port is destructive, which endpoint is permanently off,
19
+ * what the deploy sequence is — and an agent cannot recover them by reading
20
+ * the code, which is the entire reason the section exists. Four weeks after
21
+ * that run, an agent on that project removed a flag another issue had
22
+ * deliberately set, because nothing in the repo said why.
23
+ *
24
+ * ## Why a heading and not a marker pair
25
+ *
26
+ * The spec says "preserved between markers", and the extractor
27
+ * (`scripts/extract-constraints.ts`) does write between
28
+ * `<!-- BEGIN AUTO-EXTRACTED -->` and `<!-- END AUTO-EXTRACTED -->`. But on
29
+ * the consumer that lost them, most of the section was OUTSIDE the markers:
30
+ * eight extracted lines between them and twenty-nine hand-written ones
31
+ * after. Preserving only the marked block would have rescued the lines a
32
+ * machine can regenerate and dropped the ones only a human holds — the
33
+ * section's most valuable content, defined by the mechanism that was easiest
34
+ * to anchor on.
35
+ *
36
+ * So the unit is the **section**: the heading, and everything up to the next
37
+ * one. The markers are ordinary lines inside it and are preserved by being
38
+ * inside it, which is also what makes a project that has never run the
39
+ * extractor work the same way.
40
+ *
41
+ * ## The post-condition is the check, not the merge
42
+ *
43
+ * `preserveSections` could be wrong in a dozen ways — an anchor that is not
44
+ * there, a heading at EOF, a generated template that one day grows its own
45
+ * Hard Constraints section. Rather than reason about each, it compares
46
+ * the lines it found against the lines it produced and reports what is
47
+ * missing. A merge that silently drops something is the defect; a merge that
48
+ * names what it dropped is a refusal the caller can act on.
49
+ */
50
+
51
+ /** The heading that opens the preserved section. Case-sensitive, at the start of a line. */
52
+ const HARD_CONSTRAINTS = /^##[ \t]+Hard Constraints\b[^\n]*$/m;
53
+
54
+ /** Any other `##` heading — where the preserved section ends. */
55
+ const NEXT_H2 = /^##[ \t]+/m;
56
+
57
+ /**
58
+ * Where the preserved section is re-inserted, in order of preference.
59
+ *
60
+ * `## Rules` first, because constraints are rules and a reader scanning for
61
+ * one should not have to pass the Commands table to find the other. The
62
+ * fallbacks exist because a profile can omit sections, and an anchor that is
63
+ * not in the generated output is not an error — appending is.
64
+ */
65
+ const ANCHORS = [/^##[ \t]+Rules$/m, /^##[ \t]+Commands$/m, /^##[ \t]+Workflow$/m];
66
+
67
+ export interface SectionReading {
68
+ /** The section verbatim — heading line through the last line before the next `##`. */
69
+ text: string;
70
+ /** Its non-blank lines, heading included. The unit the loss check counts. */
71
+ lines: string[];
72
+ }
73
+
74
+ export interface PreserveResult {
75
+ /** The bytes to write. Equal to `generated` when there was nothing to preserve. */
76
+ content: string;
77
+ /** The section carried over, or null when the existing file had none. */
78
+ preserved: SectionReading | null;
79
+ /**
80
+ * Lines that were in the existing section and are not in `content`.
81
+ *
82
+ * Always empty on the paths this module controls. It is non-empty only
83
+ * when the merge itself failed, which is the case a caller must refuse on
84
+ * rather than write.
85
+ */
86
+ lost: string[];
87
+ }
88
+
89
+ /**
90
+ * Read the Hard Constraints section out of an AGENTS.md, or null.
91
+ *
92
+ * Returns null for "no such heading" AND for a heading with nothing under
93
+ * it — the second is a section somebody emptied, and carrying an empty
94
+ * heading forward would make a run that preserved nothing look identical to
95
+ * a run that preserved something.
96
+ */
97
+ export function readHardConstraints(content: string | null): SectionReading | null {
98
+ if (content === null) return null;
99
+ const open = HARD_CONSTRAINTS.exec(content);
100
+ if (open === null) return null;
101
+
102
+ const start = open.index;
103
+ const rest = content.slice(start + open[0].length);
104
+ const next = NEXT_H2.exec(rest);
105
+ const text = (next === null ? content.slice(start) : content.slice(start, start + open[0].length + next.index)).replace(/\s+$/, "");
106
+
107
+ const lines = text.split("\n").map(l => l.trim()).filter(l => l !== "");
108
+ // The heading alone is not a section. One line means nothing survived the
109
+ // last edit, and there is no content to promise anybody.
110
+ if (lines.length < 2) return null;
111
+ return { text, lines };
112
+ }
113
+
114
+ /**
115
+ * Graft the existing file's Hard Constraints section into freshly generated
116
+ * content, and report anything the graft dropped.
117
+ *
118
+ * Idempotent by construction: the section is re-inserted at the same anchor
119
+ * every run, so the second run over its own output is byte-identical, which
120
+ * is what SC-364 asks of every generator here.
121
+ */
122
+ export function preserveSections(existing: string | null, generated: string): PreserveResult {
123
+ const preserved = readHardConstraints(existing);
124
+ if (preserved === null) return { content: generated, preserved: null, lost: [] };
125
+
126
+ // A generated template that already carries the section is not a case
127
+ // today, and writing it off as impossible is how the next person finds a
128
+ // duplicate heading in a consumer's AGENTS.md. Its own section wins, and
129
+ // the post-condition below reports whatever that costs.
130
+ let content: string;
131
+ const own = readHardConstraints(generated);
132
+ if (own !== null) {
133
+ content = generated;
134
+ } else {
135
+ const anchor = ANCHORS.map(a => a.exec(generated)).find(m => m !== null) ?? null;
136
+ content =
137
+ anchor === null
138
+ ? `${generated.replace(/\s+$/, "")}\n\n${preserved.text}\n`
139
+ : `${generated.slice(0, anchor.index)}${preserved.text}\n\n${generated.slice(anchor.index)}`;
140
+ }
141
+
142
+ const have = new Set(content.split("\n").map(l => l.trim()));
143
+ return { content, preserved, lost: preserved.lines.filter(l => !have.has(l)) };
144
+ }