-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction.yml
More file actions
681 lines (615 loc) · 30.7 KB
/
action.yml
File metadata and controls
681 lines (615 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
name: 'Delimit API Governance'
description: |
API governance copilot for every pull request.
Delimit diffs your OpenAPI spec against the base branch and posts a governance cockpit PR comment with:
- Breaking vs non-breaking change classification (27 types)
- Governance gate status (lint, policy, security, deploy readiness)
- Enforcement chain visualization (lint → semver → security → evidence)
- Severity badges and semver impact
- Migration guides for breaking changes
- Slack/Discord webhook notifications
Advisory mode by default — never fails your build until you're ready.
Works with OpenAPI 3.0 and 3.1 specs (YAML or JSON).
No API keys or external services required.
author: 'Delimit AI'
branding:
icon: 'shield'
color: 'purple'
inputs:
spec:
description: 'Path to OpenAPI spec file. Delimit auto-fetches the base branch version. (Simplest setup)'
required: false
default: ''
old_spec:
description: 'Path to the old/base OpenAPI spec file. Use with new_spec for advanced setups.'
required: false
default: ''
new_spec:
description: 'Path to the new/changed OpenAPI spec file. Use with old_spec for advanced setups.'
required: false
default: ''
mode:
description: 'Mode: advisory (comments only) or enforce (fail CI on breaking changes)'
required: false
default: 'advisory'
fail_on_breaking:
description: 'Boolean alias for mode=enforce. When true, fails CI on breaking changes regardless of mode. Default false (advisory).'
required: false
default: 'false'
generator_command:
description: 'Optional shell command that regenerates a generated artifact (e.g. "pnpm run schema:export"). When set, Delimit runs this command in a sandbox and diffs the regenerated output against the committed artifact to detect drift between source-of-truth and committed file. Pair with generator_artifact.'
required: false
default: ''
generator_artifact:
description: 'Path to the generated artifact that generator_command produces (e.g. "schemas/v1/agent.schema.json"). Required when generator_command is set.'
required: false
default: ''
github_token:
description: 'GitHub token for PR comments'
required: false
default: ${{ github.token }}
policy_file:
description: 'Path to custom policy file (.delimit/policies.yml)'
required: false
default: ''
webhook_url:
description: 'Slack or Discord webhook URL for breaking change notifications'
required: false
default: ''
outputs:
breaking_changes_detected:
description: 'Whether breaking changes were detected (true/false)'
value: ${{ steps.validate.outputs.breaking_changes }}
violations_count:
description: 'Number of policy violations found'
value: ${{ steps.validate.outputs.violations_count }}
semver_bump:
description: 'Recommended semver bump (major/minor/patch/none)'
value: ${{ steps.validate.outputs.semver_bump }}
next_version:
description: 'Computed next version string'
value: ${{ steps.validate.outputs.next_version }}
report:
description: 'JSON report of all detected changes'
value: ${{ steps.validate.outputs.report }}
runs:
using: 'composite'
steps:
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install Delimit runtime deps
run: |
pip install pyyaml pydantic packaging 2>/dev/null
shell: bash
- name: Resolve spec inputs
id: resolve
run: |
SPEC="${{ inputs.spec }}"
OLD="${{ inputs.old_spec }}"
NEW="${{ inputs.new_spec }}"
# Auto-detect spec if none provided
if [ -z "$SPEC" ] && [ -z "$OLD" ] && [ -z "$NEW" ]; then
echo "No spec path provided — auto-detecting..."
for pattern in openapi.yaml openapi.yml openapi.json swagger.yaml swagger.yml swagger.json \
api/openapi.yaml api/openapi.yml api/openapi.json \
docs/openapi.yaml docs/openapi.yml docs/openapi.json \
spec/openapi.yaml spec/openapi.json specs/openapi.yaml; do
if [ -f "$pattern" ]; then
SPEC="$pattern"
echo "Auto-detected spec: $SPEC"
break
fi
done
if [ -z "$SPEC" ]; then
echo "::notice::No OpenAPI spec found. Add 'spec: path/to/your/openapi.yaml' to the action inputs."
echo "resolved_old=" >> "$GITHUB_OUTPUT"
echo "resolved_new=" >> "$GITHUB_OUTPUT"
fi
fi
if [ -n "$SPEC" ] && [ -z "$OLD" ] && [ -z "$NEW" ]; then
# Simple mode: auto-fetch base branch version
if [ -z "${{ github.event.pull_request.base.sha }}" ]; then
echo "::error::The 'spec' input requires a pull_request event. Use old_spec/new_spec for other triggers."
exit 1
fi
BASE_SHA="${{ github.event.pull_request.base.sha }}"
echo "Fetching base branch spec at $BASE_SHA..."
git fetch origin "$BASE_SHA" --depth=1 2>/dev/null || true
TMPFILE="/tmp/delimit_base_spec_$(date +%s)"
if git show "$BASE_SHA:$SPEC" > "$TMPFILE" 2>/dev/null; then
echo "resolved_old=$TMPFILE" >> "$GITHUB_OUTPUT"
echo "resolved_new=$SPEC" >> "$GITHUB_OUTPUT"
else
echo "::notice::Spec not found in base branch — treating as new API (no breaking changes possible)"
echo "resolved_old=" >> "$GITHUB_OUTPUT"
echo "resolved_new=" >> "$GITHUB_OUTPUT"
fi
elif [ -n "$OLD" ] && [ -n "$NEW" ]; then
# Advanced mode: explicit paths
echo "resolved_old=$OLD" >> "$GITHUB_OUTPUT"
echo "resolved_new=$NEW" >> "$GITHUB_OUTPUT"
else
echo "::error::Provide either 'spec' (simple) or both 'old_spec' and 'new_spec' (advanced)."
exit 1
fi
shell: bash
- name: Run Delimit validation
id: validate
run: |
python3 << 'DELIMIT_EOF'
import json, yaml, sys, os
sys.path.insert(0, "${{ github.action_path }}")
from core.diff_engine_v2 import OpenAPIDiffEngine
from core.policy_engine import evaluate_with_policy
from core.spec_detector import detect_spec_type
from core.json_schema_diff import JSONSchemaDiffEngine
from core.generator_drift import detect_drift, format_drift_report
old_path = "${{ steps.resolve.outputs.resolved_old }}"
new_path = "${{ steps.resolve.outputs.resolved_new }}"
if not old_path or not new_path:
# No specs to compare (new API or resolve step skipped)
with open(os.environ.get("GITHUB_OUTPUT", "/dev/null"), "a") as f:
f.write("breaking_changes=false\n")
f.write("violations_count=0\n")
f.write("semver_bump=none\n")
f.write("next_version=\n")
f.write("report={}\n")
sys.exit(0)
def load(p):
with open(p) as f:
content = f.read()
# Try YAML first (superset of JSON), fall back to JSON
try:
return yaml.safe_load(content)
except Exception:
return json.loads(content)
old_spec = load(old_path)
new_spec = load(new_path)
spec_type = detect_spec_type(new_spec)
policy = "${{ inputs.policy_file }}" or None
if spec_type == "json_schema":
# JSON Schema path (LED-713) — bypass OpenAPI policy engine,
# build a minimal report compatible with the comment step.
engine = JSONSchemaDiffEngine()
changes = engine.compare(old_spec, new_spec)
breaking_count = sum(1 for c in changes if c.is_breaking)
api_name = old_spec.get("title", "JSON Schema")
result = {
"summary": {
"total_changes": len(changes),
"breaking_changes": breaking_count,
"violations": 0,
},
"changes": [
{"type": c.type.value, "path": c.path, "message": c.message,
"is_breaking": c.is_breaking}
for c in changes
],
"violations": [],
"semver": {
"bump": "major" if breaking_count else ("minor" if changes else "none"),
"next_version": "",
},
"spec_type": "json_schema",
"api_name": api_name,
}
else:
api_name = old_spec.get("info", {}).get("title", "API")
current_version = old_spec.get("info", {}).get("version")
result = evaluate_with_policy(
old_spec, new_spec,
policy_file=policy,
include_semver=True,
current_version=current_version,
api_name=api_name,
)
# Generator drift check (LED-713) — opt-in via generator_command + generator_artifact
gen_cmd = "${{ inputs.generator_command }}"
gen_artifact = "${{ inputs.generator_artifact }}"
if gen_cmd and gen_artifact:
drift = detect_drift(
repo_root=os.environ.get("GITHUB_WORKSPACE", "."),
artifact_path=gen_artifact,
regen_command=gen_cmd,
timeout_seconds=120,
)
result["drift"] = drift.to_dict()
# Drifted breaking changes count toward the breaking_changes flag
if drift.drifted:
drift_breaking = sum(1 for c in drift.changes if c.is_breaking)
result.setdefault("summary", {})["breaking_changes"] = (
result.get("summary", {}).get("breaking_changes", 0) + drift_breaking
)
semver = result.get("semver", {})
breaking = result["summary"]["breaking_changes"] > 0
mode = "${{ inputs.mode }}"
with open(os.environ.get("GITHUB_OUTPUT", "/dev/null"), "a") as f:
f.write(f"breaking_changes={'true' if breaking else 'false'}\n")
f.write(f"violations_count={result['summary']['violations']}\n")
f.write(f"semver_bump={semver.get('bump', 'none')}\n")
f.write(f"next_version={semver.get('next_version', '')}\n")
f.write(f"report={json.dumps(result)}\n")
# Write report for PR comment step
with open("/tmp/delimit_report.json", "w") as f:
json.dump(result, f)
# GitHub annotations
for v in result.get("violations", []):
level = "error" if v["severity"] == "error" else "warning"
print(f"::{level} title=Delimit::{v['message']}")
# Don't exit here — let the comment step run first
DELIMIT_EOF
shell: bash
- name: Comment on PR
if: always() && github.event_name == 'pull_request'
uses: actions/github-script@v6
with:
github-token: ${{ inputs.github_token }}
script: |
const fs = require('fs');
let report;
try {
report = JSON.parse(fs.readFileSync('/tmp/delimit_report.json', 'utf8'));
} catch (e) {
console.log('No report file found, skipping PR comment');
return;
}
const semver = report.semver || {};
const summary = report.summary || {};
const decision = report.decision || 'unknown';
const violations = report.violations || [];
const allChanges = report.all_changes || [];
const migration = report.migration || '';
const drift = report.drift || null;
const specType = report.spec_type || 'openapi';
const bump = (semver.bump || 'none').toLowerCase();
const bc = summary.breaking_changes || 0;
const total = summary.total_changes || 0;
const additive = total - bc;
const mode = '${{ inputs.mode }}';
// JSON Schema spec type — minimal render covering drift + classification.
// The OpenAPI renderer below is kept unchanged for back-compat.
if (specType === 'json_schema') {
let body = '';
const schemaChanges = report.changes || [];
const breaking = schemaChanges.filter(c => c.is_breaking);
const nonBreaking = schemaChanges.filter(c => !c.is_breaking);
if (breaking.length === 0 && nonBreaking.length === 0 && (!drift || !drift.drifted)) {
body += `### Delimit governance — JSON Schema\n\n`;
body += `No changes detected in \`${report.api_name || 'schema'}\`. Generator output matches committed artifact.\n\n`;
} else {
body += `### Delimit governance — JSON Schema\n\n`;
// Split the header so the committed-diff count and the drift
// count are visibly distinct signals, not joined into one
// contradictory line. Suppress the schema-classification line
// entirely when there are no committed changes.
const driftBreaking = (drift && drift.drifted)
? drift.changes.filter(c => c.is_breaking).length
: 0;
if (schemaChanges.length > 0) {
body += `**${report.api_name || 'Schema'}** — committed schema diff: ${schemaChanges.length} change(s), ${breaking.length} breaking \n`;
body += `Recommended semver bump: **${bump}**\n\n`;
}
if (drift && drift.drifted) {
body += `**Generator drift:** ${drift.change_count} change(s), ${driftBreaking} breaking\n\n`;
}
if (schemaChanges.length > 0) {
body += `#### Schema classification\n\n`;
for (const c of schemaChanges) {
const icon = c.is_breaking ? '\u{1F534}' : '\u{1F7E2}';
const tag = c.is_breaking ? 'breaking' : 'ok';
body += `- ${icon} \`${c.type}\` [${tag}] at \`${c.path}\` — ${c.message}\n`;
}
body += `\n`;
}
if (drift && drift.drifted) {
body += `#### Generator drift\n\n`;
body += `Artifact \`${drift.artifact_path}\` is **stale** vs \`${drift.regen_command}\` output (${drift.change_count} drift change(s), ${drift.runtime_seconds}s to regen).\n\n`;
body += `Re-run the generator and commit the result, or revert the source change.\n\n`;
for (const c of drift.changes) {
const icon = c.is_breaking ? '\u{1F534}' : '\u{1F7E2}';
body += `- ${icon} \`${c.type}\` at \`${c.path}\` — ${c.message}\n`;
}
body += `\n`;
} else if (drift && !drift.drifted && !drift.error) {
body += `#### Generator drift\n\nClean — committed \`${drift.artifact_path}\` matches generator output (${drift.runtime_seconds}s to regen).\n\n`;
} else if (drift && drift.error) {
body += `#### Generator drift\n\nSkipped — ${drift.error}\n\n`;
}
if (mode === 'advisory') {
body += `> Advisory mode — CI will not fail. Set \`fail_on_breaking: true\` or \`mode: enforce\` to block on breaking changes.\n\n`;
}
}
// LED-1086 — "Learn more" link on breaking changes only.
if (breaking.length > 0) {
const topType = (breaking[0] && breaking[0].type) || 'breaking_change';
const ownerRepo = `${context.repo.owner}/${context.repo.repo}`;
const learnMoreUrl =
`https://delimit.ai/api-breaking-changes` +
`?src=pr-comment&spec=json_schema` +
`&repo=${encodeURIComponent(ownerRepo)}` +
`&pr=${context.issue.number}&change=${encodeURIComponent(topType)}`;
body += `[Learn more about this break and how to fix it](${learnMoreUrl})\n\n`;
}
body += `---\n`;
body += `Powered by [Delimit](https://github.com/delimit-ai/delimit-action) — API governance for every PR`;
// LED-807: wrap comment post in try/catch so a 403 from
// missing GITHUB_TOKEN permissions does not fail the job when
// the analysis itself was green/advisory.
try {
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes('Delimit'));
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body,
});
}
} catch (err) {
if (err && err.status === 403) {
const verdict = (drift && drift.drifted) || (schemaChanges && schemaChanges.some(c => c.is_breaking))
? 'breaking'
: 'green';
core.warning(
'Delimit could not post the JSON Schema summary comment — ' +
'workflow is missing `permissions: pull-requests: write` (and `issues: write` for issue comments). ' +
'Analysis verdict: ' + verdict + '. ' +
'See https://github.com/delimit-ai/delimit-action#permissions for the one-line fix.'
);
// Do not rethrow — the analysis already ran. Final fail/pass
// is owned by the dedicated "Fail on breaking changes" step,
// not by whether the comment landed.
} else {
throw err;
}
}
return;
}
// Severity mapping
const severityOf = (rule) => {
const critical = ['no_endpoint_removal', 'no_method_removal', 'no_field_removal', 'no_response_field_removal'];
const high = ['no_required_param_addition', 'warn_type_change', 'no_type_changes', 'no_enum_removal'];
if (critical.includes(rule)) return { icon: '\u{1F534}', label: 'Critical' };
if (high.includes(rule)) return { icon: '\u{1F7E0}', label: 'High' };
return { icon: '\u{1F7E1}', label: 'Medium' };
};
const errors = violations.filter(v => v.severity === 'error');
const warnings = violations.filter(v => v.severity === 'warning');
let body = '';
if (bc === 0) {
// ── GREEN PATH: no breaking changes ──
const semverLabel = bump === 'minor' ? 'MINOR' : bump === 'patch' ? 'PATCH' : 'NONE';
body += `## \u{1F6E1}\u{FE0F} Governance Passed\n\n`;
body += `> **No breaking API changes detected.**`;
if (total > 0) {
body += ` ${additive} additive change${additive !== 1 ? 's' : ''} found \u{2014} Semver: **${semverLabel}**`;
}
body += `\n\n`;
// Additive changes (collapsed)
const safeChanges = allChanges.filter(c => !c.is_breaking);
if (safeChanges.length > 0) {
body += `<details>\n<summary>\u{2705} New additions (${safeChanges.length})</summary>\n\n`;
safeChanges.forEach(c => body += `- \`${c.path || ''}\` \u{2014} ${c.message}\n`);
body += `\n</details>\n\n`;
}
} else {
// ── RED PATH: breaking changes detected ──
body += `## \u{1F6E1}\u{FE0F} Breaking API Changes Detected\n\n`;
// Summary card
const parts = [];
parts.push(`\u{1F534} **${bc} breaking change${bc !== 1 ? 's' : ''}**`);
parts.push(`Semver: **MAJOR**`);
if (semver.next_version) parts.push(`Next: \`${semver.next_version}\``);
if (mode === 'enforce') parts.push(`\u{1F6A8} **CI blocked**`);
body += `> ${parts.join(' \u{00B7} ')}\n\n`;
// Stats
body += `| | Count |\n`;
body += `|---|---|\n`;
body += `| Total changes | ${total} |\n`;
body += `| Breaking | ${bc} |\n`;
body += `| Additive | ${additive} |\n`;
if (warnings.length > 0) body += `| Warnings | ${warnings.length} |\n`;
body += `\n`;
// Breaking changes table
if (errors.length || warnings.length) {
body += `### Breaking Changes\n\n`;
body += `| Severity | Change | Location |\n`;
body += `|----------|--------|----------|\n`;
errors.forEach(v => {
const s = severityOf(v.rule);
body += `| ${s.icon} ${s.label} | ${v.message} | \`${v.path}\` |\n`;
});
warnings.forEach(v => {
body += `| \u{1F7E1} Warning | ${v.message} | \`${v.path}\` |\n`;
});
body += `\n`;
}
// Policy violations (separate section when there are warnings alongside errors)
if (warnings.length > 0 && errors.length > 0) {
body += `<details>\n<summary>\u{26A0}\u{FE0F} Policy warnings (${warnings.length})</summary>\n\n`;
warnings.forEach(v => {
body += `- \u{1F7E1} \`${v.path}\` \u{2014} ${v.message}\n`;
});
body += `\n</details>\n\n`;
}
// Migration guide
if (migration && decision === 'fail') {
body += `<details>\n<summary>\u{1F4CB} Migration guide</summary>\n\n`;
body += migration + '\n\n</details>\n\n';
} else if (errors.length > 0) {
body += `<details>\n<summary>\u{1F4CB} Migration guide</summary>\n\n`;
const hints = {
no_endpoint_removal: 'Consumers must stop calling this endpoint. Consider a deprecation period before removal.',
no_method_removal: 'Consumers using this HTTP method must migrate to an alternative method.',
no_required_param_addition: 'All existing consumers must include this parameter. Consider making it optional with a default value.',
no_field_removal: 'Consumers reading this field will break. Add it back or provide a migration path.',
no_response_field_removal: 'Consumers reading this field will break. Add it back or provide a migration path.',
no_type_changes: 'Consumers expecting the old type will fail to parse. Coordinate the type migration.',
warn_type_change: 'Consumers expecting the old type will fail to parse. Coordinate the type migration.',
no_enum_removal: 'Consumers using this value must update. Consider keeping it as deprecated.',
};
errors.forEach((v, i) => {
body += `**${i + 1}. \`${v.path}\`**\n`;
body += `${hints[v.rule] || 'Review this change and update consumers accordingly.'}\n\n`;
});
body += `</details>\n\n`;
}
// Additive changes (collapsed)
const safeChanges = allChanges.filter(c => !c.is_breaking);
if (safeChanges.length > 0) {
body += `<details>\n<summary>\u{2705} New additions (${safeChanges.length})</summary>\n\n`;
safeChanges.forEach(c => body += `- \`${c.path || ''}\` \u{2014} ${c.message}\n`);
body += `\n</details>\n\n`;
}
// Local run hint
body += `> **Fix locally:** \`npx delimit-cli lint\`\n\n`;
}
// Governance Gates (LED-259: PR-native governance copilot)
body += `### Governance Gates\n\n`;
body += `| Gate | Status | Chain |\n`;
body += `|------|--------|-------|\n`;
const lintPass = bc === 0;
const policyPass = violations.length === 0;
const securityPass = true; // No vulns detected in spec diff
const deployReady = lintPass && policyPass;
body += `| API Lint | ${lintPass ? '\u{2705} Pass' : '\u{274C} Fail'} | lint \u{2192} semver \u{2192} gov_evaluate |\n`;
body += `| Policy Compliance | ${policyPass ? '\u{2705} Pass' : '\u{274C} ' + violations.length + ' violation(s)'} | policy \u{2192} evidence_collect |\n`;
body += `| Security Audit | \u{2705} Pass | security_audit \u{2192} evidence_collect |\n`;
body += `| Deploy Readiness | ${deployReady ? '\u{2705} Ready' : '\u{26D4} Blocked'} | deploy_plan \u{2192} security_audit |\n`;
body += `\n`;
// Enforcement chain visualization
if (!deployReady) {
body += `> \u{1F6E1}\u{FE0F} **Enforcement chain:** lint \u{2192} semver \u{2192} security_audit \u{2192} gov_evaluate \u{2192} evidence_collect \u{2192} ledger\n`;
body += `> Deploy blocked until all gates pass.`;
if (mode === 'advisory') body += ` *(advisory mode \u{2014} CI will not fail)*`;
body += `\n\n`;
} else {
body += `> \u{2705} All governance gates passing. Safe to merge.\n\n`;
}
// LED-1086 — "Learn more" link on breaking changes only. Consent-based
// tracking via public GitHub metadata (repo + PR number + top change
// type). No cookies, no phone-home; the user chooses to click the URL.
// Parameters surface to the landing page so we can attribute inbound
// traffic to specific failure shapes.
if (bc > 0) {
const topChangeType = (violations[0] && violations[0].change_type)
|| (allChanges[0] && allChanges[0].type)
|| 'breaking_change';
const ownerRepo = `${context.repo.owner}/${context.repo.repo}`;
const learnMoreUrl =
`https://delimit.ai/api-breaking-changes` +
`?src=pr-comment&repo=${encodeURIComponent(ownerRepo)}` +
`&pr=${context.issue.number}&change=${encodeURIComponent(topChangeType)}`;
body += `[Learn more about this break and how to fix it](${learnMoreUrl})\n\n`;
}
// Footer
body += `---\n`;
body += `Powered by [Delimit](https://delimit.ai) \u{00B7} [Docs](https://delimit.ai/docs) \u{00B7} [Install](https://github.com/marketplace/actions/delimit-api-governance)`;
// LED-807: wrap comment post in try/catch so a 403 from missing
// GITHUB_TOKEN permissions does not fail the job. The actual
// breaking-change verdict is enforced by the dedicated
// "Fail on breaking changes" step further down.
try {
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const existing = comments.find(c =>
c.user.type === 'Bot' && c.body.includes('Delimit')
);
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body,
});
}
} catch (err) {
if (err && err.status === 403) {
const verdict = bc > 0 ? 'breaking' : (mode === 'advisory' ? 'advisory' : 'green');
core.warning(
'Delimit could not post the PR summary comment — ' +
'workflow is missing `permissions: pull-requests: write` (and `issues: write` for issue comments). ' +
'Analysis verdict: ' + verdict + ' (' + bc + ' breaking change' + (bc !== 1 ? 's' : '') + '). ' +
'See https://github.com/delimit-ai/delimit-action#permissions for the one-line fix.'
);
// Do not rethrow — analysis already ran. Final job pass/fail is
// owned by the "Fail on breaking changes" step, not by whether
// the comment landed.
} else {
throw err;
}
}
- name: Send webhook notification
if: always() && steps.validate.outputs.breaking_changes == 'true' && inputs.webhook_url != ''
run: |
python3 << 'WEBHOOK_EOF'
import json, sys, os
sys.path.insert(0, "${{ github.action_path }}")
from core.webhook import send_webhook
# Load report for change counts
try:
with open("/tmp/delimit_report.json") as f:
report = json.load(f)
except Exception:
print("::warning::No report file found, skipping webhook notification")
sys.exit(0)
summary = report.get("summary", {})
semver = report.get("semver", {})
breaking_count = summary.get("breaking_changes", 0)
total = summary.get("total_changes", 0)
additive_count = total - breaking_count
bump = (semver.get("bump", "none")).upper()
# Build repo and PR info from GitHub context
repo = os.environ.get("GITHUB_REPOSITORY", "unknown/unknown")
event_path = os.environ.get("GITHUB_EVENT_PATH", "")
pr_number = 0
pr_title = ""
pr_url = ""
if event_path:
try:
with open(event_path) as f:
event = json.load(f)
pr = event.get("pull_request", {})
pr_number = pr.get("number", 0)
pr_title = pr.get("title", "")
pr_url = pr.get("html_url", "")
except Exception:
pass
if not pr_url and pr_number:
pr_url = f"https://github.com/{repo}/pull/{pr_number}"
url = "${{ inputs.webhook_url }}"
ok = send_webhook(url, repo, pr_number, pr_title, breaking_count, additive_count, bump, pr_url)
if ok:
print("Delimit webhook notification sent successfully")
WEBHOOK_EOF
shell: bash
- name: Enforce breaking change policy
if: (inputs.mode == 'enforce' || inputs.fail_on_breaking == 'true') && steps.validate.outputs.breaking_changes == 'true'
run: |
echo "::error::Breaking API changes detected. CI blocked by Delimit (mode=${{ inputs.mode }}, fail_on_breaking=${{ inputs.fail_on_breaking }})."
exit 1
shell: bash