@ankhorage/devtools 2.4.4 → 2.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.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  # @ankhorage/devtools
5
5
 
6
- ![license: MIT](././paradox/badges/license.svg) ![npm: v2.4.4](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: configured](././paradox/badges/tests.svg) ![paradox: warnings](././paradox/badges/docs.svg)
6
+ ![license: MIT](././paradox/badges/license.svg) ![npm: v2.6.0](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: configured](././paradox/badges/tests.svg) ![paradox: warnings](././paradox/badges/docs.svg)
7
7
 
8
8
  Shared tooling, repository automation, and agent standards for Ankhorage TypeScript projects
9
9
 
@@ -0,0 +1,2 @@
1
+ /*** Public CI-impact planning and GitHub Actions output boundary. */
2
+ export { type CiImpactConfiguration, type CiImpactJobDecision, type CiImpactKind, type CiImpactMode, type CiImpactPlan, type CiImpactSelection, type CiImpactSuite, type CiImpactWorkflowOutput, createCiImpactWorkflowOutput, planCiImpact, runCiImpact, } from './features/ci-impact/ciImpact.js';
@@ -0,0 +1,2 @@
1
+ /*** Public CI-impact planning and GitHub Actions output boundary. */
2
+ export { createCiImpactWorkflowOutput, planCiImpact, runCiImpact, } from './features/ci-impact/ciImpact.js';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { runCiImpact } from '../../ci-impact.js';
2
+ runCiImpact(process.argv.slice(2));
@@ -0,0 +1,43 @@
1
+ export type CiImpactKind = 'e2e' | 'smoke';
2
+ export type CiImpactMode = 'skip' | 'full' | 'changed' | 'scoped';
3
+ export interface CiImpactSelection {
4
+ readonly mode: CiImpactMode;
5
+ readonly scripts: readonly string[];
6
+ readonly reason: string;
7
+ }
8
+ export interface CiImpactPlan {
9
+ readonly base: string;
10
+ readonly unit: CiImpactSelection;
11
+ readonly e2e: CiImpactSelection;
12
+ readonly smoke: CiImpactSelection;
13
+ }
14
+ export interface CiImpactSuite {
15
+ readonly kind: CiImpactKind;
16
+ readonly script: string;
17
+ readonly paths: readonly string[];
18
+ }
19
+ export interface CiImpactConfiguration {
20
+ readonly complete?: Partial<Record<CiImpactKind, boolean>>;
21
+ readonly suites?: readonly CiImpactSuite[];
22
+ }
23
+ export interface CiImpactJobDecision {
24
+ readonly state: 'selected' | 'skipped' | 'full';
25
+ readonly reason: string;
26
+ readonly fallback: boolean;
27
+ }
28
+ export interface CiImpactWorkflowOutput {
29
+ readonly version: 1;
30
+ readonly plan: CiImpactPlan;
31
+ readonly jobs: Readonly<Record<string, CiImpactJobDecision>>;
32
+ }
33
+ interface CiImpactExecutionContext {
34
+ readonly cwd?: string;
35
+ readonly environment?: Readonly<Record<string, string | undefined>>;
36
+ }
37
+ /*** Select safe CI checks, using explicit suite ownership and Bun's dependency graph. */
38
+ export declare function planCiImpact(files: readonly string[] | null, scripts: Readonly<Record<string, string | undefined>>, configuration: CiImpactConfiguration | undefined, base: string): CiImpactPlan;
39
+ /*** Create safe, per-script GitHub Actions decisions from the canonical aggregate plan. */
40
+ export declare function createCiImpactWorkflowOutput(plan: CiImpactPlan, configuration: CiImpactConfiguration | undefined): CiImpactWorkflowOutput;
41
+ /*** Run the published CI impact command without evaluating repository values as shell commands. */
42
+ export declare function runCiImpact(argv: readonly string[], context?: CiImpactExecutionContext): void;
43
+ export {};
@@ -0,0 +1,203 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { writeCiImpactGitHubOutputs, writeCiImpactGitHubSummary } from './ciImpactGitHub.js';
5
+ /*** Select safe CI checks, using explicit suite ownership and Bun's dependency graph. */
6
+ export function planCiImpact(files, scripts, configuration, base) {
7
+ const full = files === null || files.some(isUnsafeChange);
8
+ const docs = files?.every(isDocumentation) === true;
9
+ const baseSelection = {
10
+ mode: full ? 'full' : 'skip',
11
+ scripts: [],
12
+ reason: full ? 'Unsafe or unavailable diff' : 'Documentation only',
13
+ };
14
+ const unit = scripts.test === undefined
15
+ ? { mode: 'skip', scripts: [], reason: 'No test script' }
16
+ : full
17
+ ? { mode: 'full', scripts: ['test'], reason: 'Unsafe or unavailable diff' }
18
+ : docs
19
+ ? baseSelection
20
+ : scripts.test.trim() === 'bun test'
21
+ ? { mode: 'changed', scripts: ['test'], reason: 'Bun transitive import graph' }
22
+ : { mode: 'full', scripts: ['test'], reason: 'Unrecognized test runner' };
23
+ return {
24
+ base,
25
+ unit,
26
+ e2e: selectSuites('e2e', files, scripts, configuration, full, docs),
27
+ smoke: selectSuites('smoke', files, scripts, configuration, full, docs),
28
+ };
29
+ }
30
+ /*** Create safe, per-script GitHub Actions decisions from the canonical aggregate plan. */
31
+ export function createCiImpactWorkflowOutput(plan, configuration) {
32
+ const jobs = Object.fromEntries(['e2e', 'smoke'].flatMap((kind) => suitesForKind(configuration, kind).map((suite) => [
33
+ suite.script,
34
+ createJobDecision(plan[kind], suite.script),
35
+ ])));
36
+ return { version: 1, plan, jobs };
37
+ }
38
+ /*** Run the published CI impact command without evaluating repository values as shell commands. */
39
+ export function runCiImpact(argv, context = {}) {
40
+ const operation = parseOperation(argv);
41
+ const cwd = context.cwd ?? process.cwd();
42
+ const environment = context.environment ?? process.env;
43
+ const planPath = join(environment.RUNNER_TEMP ?? '.', 'ankh-ci-impact-plan.json');
44
+ if (operation === 'plan') {
45
+ const { configuration, plan } = createPlan(cwd, environment);
46
+ writeFileSync(planPath, JSON.stringify(plan), { encoding: 'utf8' });
47
+ const output = createCiImpactWorkflowOutput(plan, configuration);
48
+ writeCiImpactGitHubOutputs(output, environment);
49
+ console.log(JSON.stringify(output, null, 2));
50
+ writeCiImpactGitHubSummary(plan, environment);
51
+ return;
52
+ }
53
+ const plan = JSON.parse(readFileSync(planPath, 'utf8'));
54
+ runPlan(plan, operation, cwd);
55
+ }
56
+ /*** Select scoped suites only when an exhaustive and unambiguous repository declaration is valid. */
57
+ function selectSuites(kind, files, scripts, configuration, full, docs) {
58
+ const defaults = (kind === 'e2e' ? ['test:e2e'] : ['test:smoke', 'test:standalone']).filter((name) => scripts[name] !== undefined);
59
+ const suites = suitesForKind(configuration, kind);
60
+ const validSuites = suites.length > 0 &&
61
+ new Set(suites.map((suite) => suite.script)).size === suites.length &&
62
+ suites.every((suite) => typeof scripts[suite.script] === 'string' &&
63
+ suite.paths.length > 0 &&
64
+ suite.paths.every(isSafePattern));
65
+ const fallbackScripts = defaults.length > 0
66
+ ? defaults
67
+ : suites.map((suite) => suite.script).filter((script) => scripts[script] !== undefined);
68
+ if (fallbackScripts.length === 0)
69
+ return { mode: 'skip', scripts: [], reason: 'No suite scripts' };
70
+ if (docs)
71
+ return { mode: 'skip', scripts: [], reason: 'Documentation only' };
72
+ if (full)
73
+ return { mode: 'full', scripts: fallbackScripts, reason: 'Unsafe or unavailable diff' };
74
+ if (configuration?.complete?.[kind] !== true || !validSuites) {
75
+ return { mode: 'full', scripts: fallbackScripts, reason: 'No complete suite mapping' };
76
+ }
77
+ const matches = (files ?? []).map((file) => suites.filter((suite) => suite.paths.some((pattern) => matchesPath(file, pattern))));
78
+ if (matches.some((found) => found.length !== 1)) {
79
+ return { mode: 'full', scripts: fallbackScripts, reason: 'Ambiguous or unmapped changed file' };
80
+ }
81
+ return {
82
+ mode: 'scoped',
83
+ scripts: [...new Set(matches.flat().map((suite) => suite.script))],
84
+ reason: 'Explicit complete suite mapping',
85
+ };
86
+ }
87
+ /*** Read only well-formed suite declarations from untrusted package metadata. */
88
+ function suitesForKind(configuration, kind) {
89
+ return configuration?.suites?.filter((suite) => suite.kind === kind) ?? [];
90
+ }
91
+ /*** Classify a declared script from the aggregate selection without allowing an implied pass. */
92
+ function createJobDecision(selection, script) {
93
+ if (selection.mode === 'full') {
94
+ return { state: 'full', reason: selection.reason, fallback: true };
95
+ }
96
+ if (selection.mode === 'skip') {
97
+ return { state: 'skipped', reason: selection.reason, fallback: false };
98
+ }
99
+ return selection.scripts.includes(script)
100
+ ? { state: 'selected', reason: selection.reason, fallback: false }
101
+ : { state: 'skipped', reason: selection.reason, fallback: false };
102
+ }
103
+ /*** Conservatively identify changes that invalidate impact pruning. */
104
+ function isUnsafeChange(file) {
105
+ return (/^(?:\.github\/|\.agents\/|scripts\/|tools\/|test\/|tests\/|config\/)/u.test(file) ||
106
+ /(?:^|\/)[^/]*\.config\.[^/]+$/u.test(file) ||
107
+ /(?:^|\/)(?:[^/]+\.lock|[^/]+\.lockb|(?:bun|package)-lock\.json|pnpm-lock\.yaml|yarn\.lock)$/u.test(file) ||
108
+ /^(?:package\.json|bunfig\.toml|AGENTS\.md|tsconfig[^/]*|playwright\.config\.[^/]+|vitest\.config\.[^/]+|jest\.config\.[^/]+|eslint\.config\.[^/]+|\.env[^/]*)$/u.test(file));
109
+ }
110
+ /*** Classify files whose changes cannot influence runtime test execution. */
111
+ function isDocumentation(file) {
112
+ return (file.startsWith('docs/') ||
113
+ file.startsWith('.changeset/') ||
114
+ (/\.(?:md|mdx)$/u.test(file) && !isUnsafeChange(file)) ||
115
+ file === 'LICENSE');
116
+ }
117
+ /*** Keep mapping syntax deliberately restricted to exact paths and directory descendants. */
118
+ function isSafePattern(pattern) {
119
+ return (!pattern.startsWith('/') &&
120
+ !pattern.includes('..') &&
121
+ /^(?:[a-zA-Z0-9_.@-]+\/)*[a-zA-Z0-9_.@*-]+$/u.test(pattern) &&
122
+ (!pattern.includes('*') || pattern.endsWith('/**')));
123
+ }
124
+ /*** Match one declared path or its explicit recursive directory ownership. */
125
+ function matchesPath(file, pattern) {
126
+ return pattern.endsWith('/**') ? file.startsWith(pattern.slice(0, -2)) : file === pattern;
127
+ }
128
+ /*** Read Git's binary-safe status output, failing closed for removals, renames, and invalid refs. */
129
+ function readChangedFiles(base, cwd) {
130
+ if (!/^[a-f0-9]{40}$/u.test(base))
131
+ return null;
132
+ try {
133
+ execFileSync('git', ['cat-file', '-e', base + '^{commit}'], { cwd, stdio: 'ignore' });
134
+ const output = execFileSync('git', ['diff', '--name-status', '--no-renames', '-z', base, 'HEAD', '--'], { cwd, encoding: 'utf8' });
135
+ const items = output.split('\0').filter(Boolean);
136
+ if (items.length % 2 !== 0)
137
+ return null;
138
+ const changes = Array.from({ length: items.length / 2 }, (_, index) => ({
139
+ status: items[index * 2],
140
+ path: items[index * 2 + 1],
141
+ }));
142
+ return changes.every((item) => /^[AMT]$/u.test(item.status) && !item.path.includes('\n'))
143
+ ? changes.map((item) => item.path)
144
+ : null;
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ }
150
+ /*** Produce a full plan when the workflow cannot prove a trustworthy PR delta. */
151
+ function createPlan(cwd, environment) {
152
+ const manifest = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8'));
153
+ const base = environment.GITHUB_EVENT_NAME === 'pull_request' ? (environment.ANKH_CI_BASE_SHA ?? '') : '';
154
+ const files = base ? readChangedFiles(base, cwd) : null;
155
+ const configuration = parseCiImpactConfiguration(manifest.ankh?.ciImpact);
156
+ return { configuration, plan: planCiImpact(files, manifest.scripts ?? {}, configuration, base) };
157
+ }
158
+ /*** Reject malformed package metadata before it can become a scoped ownership declaration. */
159
+ function parseCiImpactConfiguration(value) {
160
+ if (typeof value !== 'object' ||
161
+ value === null ||
162
+ !Array.isArray(value.suites)) {
163
+ return undefined;
164
+ }
165
+ const { suites } = value;
166
+ if (!suites.every(isCiImpactSuite))
167
+ return undefined;
168
+ const { complete } = value;
169
+ return {
170
+ complete: typeof complete === 'object' && complete !== null ? complete : undefined,
171
+ suites,
172
+ };
173
+ }
174
+ /*** Validate untrusted JSON suite data before constructing the typed configuration. */
175
+ function isCiImpactSuite(value) {
176
+ if (typeof value !== 'object' || value === null)
177
+ return false;
178
+ const suite = value;
179
+ return ((suite.kind === 'e2e' || suite.kind === 'smoke') &&
180
+ typeof suite.script === 'string' &&
181
+ Array.isArray(suite.paths) &&
182
+ suite.paths.every((path) => typeof path === 'string'));
183
+ }
184
+ /*** Execute an already saved CI plan without shell interpolation. */
185
+ function runPlan(plan, kind, cwd) {
186
+ const selection = plan[kind];
187
+ if (selection.mode === 'skip')
188
+ return;
189
+ if (kind === 'unit' && selection.mode === 'changed') {
190
+ execFileSync('bun', ['test', '--changed=' + plan.base], { cwd, stdio: 'inherit' });
191
+ return;
192
+ }
193
+ for (const script of selection.scripts) {
194
+ execFileSync('bun', ['run', script], { cwd, stdio: 'inherit' });
195
+ }
196
+ }
197
+ /*** Restrict the public command to known operations before it reads or executes repository state. */
198
+ function parseOperation(argv) {
199
+ if (argv.length !== 1 || !['plan', 'unit', 'e2e', 'smoke'].includes(argv[0] ?? '')) {
200
+ throw new Error('Expected exactly one operation: plan, unit, e2e, or smoke.');
201
+ }
202
+ return argv[0];
203
+ }
@@ -0,0 +1,5 @@
1
+ import type { CiImpactPlan, CiImpactWorkflowOutput } from './ciImpact.js';
2
+ /*** Write JSON-safe records so external workflows can address arbitrary script identifiers. */
3
+ export declare function writeCiImpactGitHubOutputs(output: CiImpactWorkflowOutput, environment: Readonly<Record<string, string | undefined>>): void;
4
+ /*** Render the existing aggregate plan in the GitHub Actions step summary. */
5
+ export declare function writeCiImpactGitHubSummary(plan: CiImpactPlan, environment: Readonly<Record<string, string | undefined>>): void;
@@ -0,0 +1,31 @@
1
+ import { appendFileSync } from 'node:fs';
2
+ /*** Write JSON-safe records so external workflows can address arbitrary script identifiers. */
3
+ export function writeCiImpactGitHubOutputs(output, environment) {
4
+ if (environment.GITHUB_OUTPUT === undefined)
5
+ return;
6
+ const { plan } = output;
7
+ appendFileSync(environment.GITHUB_OUTPUT, [
8
+ 'impact=' + JSON.stringify(output),
9
+ 'unit=' + plan.unit.mode,
10
+ 'e2e=' + plan.e2e.mode,
11
+ 'smoke=' + plan.smoke.mode,
12
+ ].join('\n') + '\n');
13
+ }
14
+ /*** Render the existing aggregate plan in the GitHub Actions step summary. */
15
+ export function writeCiImpactGitHubSummary(plan, environment) {
16
+ if (environment.GITHUB_STEP_SUMMARY === undefined)
17
+ return;
18
+ appendFileSync(environment.GITHUB_STEP_SUMMARY, '### CI impact\n\n| Suite | Mode | Reason | Scripts |\n| --- | --- | --- | --- |\n' +
19
+ ['unit', 'e2e', 'smoke']
20
+ .map((kind) => '| ' +
21
+ kind +
22
+ ' | ' +
23
+ plan[kind].mode +
24
+ ' | ' +
25
+ plan[kind].reason +
26
+ ' | ' +
27
+ (plan[kind].scripts.join(', ') || '—') +
28
+ ' |')
29
+ .join('\n') +
30
+ '\n');
31
+ }
@@ -1,25 +1 @@
1
- type Kind = 'e2e' | 'smoke';
2
- type Mode = 'skip' | 'full' | 'changed' | 'scoped';
3
- interface Selection {
4
- readonly mode: Mode;
5
- readonly scripts: readonly string[];
6
- readonly reason: string;
7
- }
8
- interface Plan {
9
- readonly base: string;
10
- readonly unit: Selection;
11
- readonly e2e: Selection;
12
- readonly smoke: Selection;
13
- }
14
- interface Scope {
15
- readonly kind: Kind;
16
- readonly script: string;
17
- readonly paths: readonly string[];
18
- }
19
- interface Configuration {
20
- readonly complete?: Partial<Record<Kind, boolean>>;
21
- readonly suites?: readonly Scope[];
22
- }
23
- /*** Select safe CI checks, using explicit suite ownership and Bun's dependency graph. */
24
- export declare function planCiImpact(files: readonly string[] | null, scripts: Readonly<Record<string, string>>, configuration: Configuration | undefined, base: string): Plan;
25
1
  export {};
@@ -1,157 +1,2 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- /*** Select safe CI checks, using explicit suite ownership and Bun's dependency graph. */
5
- export function planCiImpact(files, scripts, configuration, base) {
6
- const full = files === null || files.some(isUnsafeChange);
7
- const docs = files !== null && files.every(isDocumentation);
8
- const baseSelection = {
9
- mode: full ? 'full' : 'skip',
10
- scripts: [],
11
- reason: full ? 'Unsafe or unavailable diff' : 'Documentation only',
12
- };
13
- const unit = scripts.test === undefined
14
- ? { mode: 'skip', scripts: [], reason: 'No test script' }
15
- : full
16
- ? { mode: 'full', scripts: ['test'], reason: 'Unsafe or unavailable diff' }
17
- : docs
18
- ? baseSelection
19
- : scripts.test.trim() === 'bun test'
20
- ? { mode: 'changed', scripts: ['test'], reason: 'Bun transitive import graph' }
21
- : { mode: 'full', scripts: ['test'], reason: 'Unrecognized test runner' };
22
- return {
23
- base,
24
- unit,
25
- e2e: selectSuites('e2e', files, scripts, configuration, full, docs),
26
- smoke: selectSuites('smoke', files, scripts, configuration, full, docs),
27
- };
28
- }
29
- /*** Select scoped suites only when an exhaustive repository declaration is valid. */
30
- function selectSuites(kind, files, scripts, configuration, full, docs) {
31
- const defaults = (kind === 'e2e' ? ['test:e2e'] : ['test:smoke', 'test:standalone']).filter((name) => scripts[name] !== undefined);
32
- const suites = configuration?.suites?.filter((suite) => suite.kind === kind) ?? [];
33
- const validSuites = suites.length > 0 &&
34
- suites.every((suite) => typeof scripts[suite.script] === 'string' &&
35
- suite.paths.length > 0 &&
36
- suite.paths.every((path) => typeof path === 'string' && isSafePattern(path)));
37
- const fallbackScripts = defaults.length > 0
38
- ? defaults
39
- : suites.map((suite) => suite.script).filter((script) => scripts[script] !== undefined);
40
- if (fallbackScripts.length === 0)
41
- return { mode: 'skip', scripts: [], reason: 'No suite scripts' };
42
- if (docs)
43
- return { mode: 'skip', scripts: [], reason: 'Documentation only' };
44
- if (full || files === null)
45
- return { mode: 'full', scripts: fallbackScripts, reason: 'Unsafe or unavailable diff' };
46
- if (configuration?.complete?.[kind] !== true || !validSuites) {
47
- return { mode: 'full', scripts: fallbackScripts, reason: 'No complete suite mapping' };
48
- }
49
- const matches = files.map((file) => suites.filter((suite) => suite.paths.some((pattern) => matchesPath(file, pattern))));
50
- if (matches.some((found) => found.length === 0)) {
51
- return { mode: 'full', scripts: fallbackScripts, reason: 'Unmapped changed file' };
52
- }
53
- const selected = [...new Set(matches.flat().map((suite) => suite.script))];
54
- return { mode: 'scoped', scripts: selected, reason: 'Explicit complete suite mapping' };
55
- }
56
- /*** Conservatively identify changes that invalidate impact pruning. */
57
- function isUnsafeChange(file) {
58
- return (/^(?:\.github\/|\.agents\/|scripts\/|test\/|tests\/|config\/)/u.test(file) ||
59
- /^(?:package\.json|bun\.lock|bunfig\.toml|AGENTS\.md|tsconfig[^/]*|playwright\.config\.[^/]+|vitest\.config\.[^/]+|jest\.config\.[^/]+|eslint\.config\.[^/]+|\.env[^/]*)$/u.test(file));
60
- }
61
- /*** Classify files whose changes cannot influence runtime test execution. */
62
- function isDocumentation(file) {
63
- return (file.startsWith('docs/') ||
64
- file.startsWith('.changeset/') ||
65
- (/\.(?:md|mdx)$/u.test(file) && !isUnsafeChange(file)) ||
66
- file === 'LICENSE');
67
- }
68
- /*** Keep mapping syntax deliberately restricted to exact paths and directory descendants. */
69
- function isSafePattern(pattern) {
70
- return (!pattern.startsWith('/') &&
71
- !pattern.includes('..') &&
72
- /^(?:[a-zA-Z0-9_.@-]+\/)*[a-zA-Z0-9_.@*-]+$/u.test(pattern) &&
73
- (!pattern.includes('*') || pattern.endsWith('/**')));
74
- }
75
- /*** Match one declared path or its explicit recursive directory ownership. */
76
- function matchesPath(file, pattern) {
77
- return pattern.endsWith('/**') ? file.startsWith(pattern.slice(0, -2)) : file === pattern;
78
- }
79
- /*** Read Git's binary-safe status output, failing closed for removals and invalid refs. */
80
- function readChangedFiles(base) {
81
- if (!/^[a-f0-9]{40}$/u.test(base))
82
- return null;
83
- try {
84
- execFileSync('git', ['cat-file', '-e', base + '^{commit}'], { stdio: 'ignore' });
85
- const output = execFileSync('git', ['diff', '--name-status', '--no-renames', '-z', base, 'HEAD', '--'], { encoding: 'utf8' });
86
- const items = output.split('\0').filter(Boolean);
87
- if (items.length % 2 !== 0)
88
- return null;
89
- const changes = Array.from({ length: items.length / 2 }, (_, index) => ({
90
- status: items[index * 2],
91
- path: items[index * 2 + 1],
92
- }));
93
- return changes.every((item) => /^[AMT]$/u.test(item.status) && !item.path.includes('\n'))
94
- ? changes.map((item) => item.path)
95
- : null;
96
- }
97
- catch {
98
- return null;
99
- }
100
- }
101
- /*** Produce a full plan when the workflow cannot prove a trustworthy PR delta. */
102
- function createPlan() {
103
- const manifest = JSON.parse(readFileSync('package.json', 'utf8'));
104
- const base = process.env.GITHUB_EVENT_NAME === 'pull_request' ? (process.env.ANKH_CI_BASE_SHA ?? '') : '';
105
- const files = base ? readChangedFiles(base) : null;
106
- return planCiImpact(files, manifest.scripts ?? {}, manifest.ankh?.ciImpact, base);
107
- }
108
- /*** Execute an already saved CI plan without shell interpolation. */
109
- function runPlan(plan, kind) {
110
- const selection = plan[kind];
111
- if (selection.mode === 'skip')
112
- return;
113
- if (kind === 'unit' && selection.mode === 'changed') {
114
- execFileSync('bun', ['test', '--changed=' + plan.base], { stdio: 'inherit' });
115
- return;
116
- }
117
- for (const script of selection.scripts) {
118
- execFileSync('bun', ['run', script], { stdio: 'inherit' });
119
- }
120
- }
121
- /*** Expose test decisions in GitHub outputs and a human-readable step summary. */
122
- function main() {
123
- const operation = process.argv[2];
124
- const planPath = join(process.env.RUNNER_TEMP ?? '.', 'ankh-ci-impact-plan.json');
125
- if (operation === 'plan') {
126
- const plan = createPlan();
127
- writeFileSync(planPath, JSON.stringify(plan));
128
- if (process.env.GITHUB_OUTPUT) {
129
- appendFileSync(process.env.GITHUB_OUTPUT, ['unit=' + plan.unit.mode, 'e2e=' + plan.e2e.mode, 'smoke=' + plan.smoke.mode].join('\n') +
130
- '\n');
131
- }
132
- console.log(JSON.stringify(plan, null, 2));
133
- if (process.env.GITHUB_STEP_SUMMARY) {
134
- appendFileSync(process.env.GITHUB_STEP_SUMMARY, '### CI impact\n\n| Suite | Mode | Reason | Scripts |\n| --- | --- | --- | --- |\n' +
135
- ['unit', 'e2e', 'smoke']
136
- .map((kind) => '| ' +
137
- kind +
138
- ' | ' +
139
- plan[kind].mode +
140
- ' | ' +
141
- plan[kind].reason +
142
- ' | ' +
143
- (plan[kind].scripts.join(', ') || '—') +
144
- ' |')
145
- .join('\n') +
146
- '\n');
147
- }
148
- return;
149
- }
150
- if (operation !== 'unit' && operation !== 'e2e' && operation !== 'smoke') {
151
- throw new Error('Expected plan, unit, e2e, or smoke');
152
- }
153
- const plan = JSON.parse(readFileSync(planPath, 'utf8'));
154
- runPlan(plan, operation);
155
- }
156
- if (import.meta.main)
157
- main();
1
+ import { runCiImpact } from '@ankhorage/devtools/ci-impact';
2
+ runCiImpact(process.argv.slice(2));
@@ -1,234 +1,3 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
1
+ import { runCiImpact } from '@ankhorage/devtools/ci-impact';
4
2
 
5
- type Kind = 'e2e' | 'smoke';
6
- type Mode = 'skip' | 'full' | 'changed' | 'scoped';
7
- interface Selection {
8
- readonly mode: Mode;
9
- readonly scripts: readonly string[];
10
- readonly reason: string;
11
- }
12
- interface Plan {
13
- readonly base: string;
14
- readonly unit: Selection;
15
- readonly e2e: Selection;
16
- readonly smoke: Selection;
17
- }
18
- interface Scope {
19
- readonly kind: Kind;
20
- readonly script: string;
21
- readonly paths: readonly string[];
22
- }
23
- interface Configuration {
24
- readonly complete?: Partial<Record<Kind, boolean>>;
25
- readonly suites?: readonly Scope[];
26
- }
27
-
28
- /*** Select safe CI checks, using explicit suite ownership and Bun's dependency graph. */
29
- export function planCiImpact(
30
- files: readonly string[] | null,
31
- scripts: Readonly<Record<string, string>>,
32
- configuration: Configuration | undefined,
33
- base: string,
34
- ): Plan {
35
- const full = files === null || files.some(isUnsafeChange);
36
- const docs = files !== null && files.every(isDocumentation);
37
- const baseSelection: Selection = {
38
- mode: full ? 'full' : 'skip',
39
- scripts: [],
40
- reason: full ? 'Unsafe or unavailable diff' : 'Documentation only',
41
- };
42
- const unit: Selection =
43
- scripts.test === undefined
44
- ? { mode: 'skip', scripts: [], reason: 'No test script' }
45
- : full
46
- ? { mode: 'full', scripts: ['test'], reason: 'Unsafe or unavailable diff' }
47
- : docs
48
- ? baseSelection
49
- : scripts.test.trim() === 'bun test'
50
- ? { mode: 'changed', scripts: ['test'], reason: 'Bun transitive import graph' }
51
- : { mode: 'full', scripts: ['test'], reason: 'Unrecognized test runner' };
52
-
53
- return {
54
- base,
55
- unit,
56
- e2e: selectSuites('e2e', files, scripts, configuration, full, docs),
57
- smoke: selectSuites('smoke', files, scripts, configuration, full, docs),
58
- };
59
- }
60
-
61
- /*** Select scoped suites only when an exhaustive repository declaration is valid. */
62
- function selectSuites(
63
- kind: Kind,
64
- files: readonly string[] | null,
65
- scripts: Readonly<Record<string, string>>,
66
- configuration: Configuration | undefined,
67
- full: boolean,
68
- docs: boolean,
69
- ): Selection {
70
- const defaults = (kind === 'e2e' ? ['test:e2e'] : ['test:smoke', 'test:standalone']).filter(
71
- (name) => scripts[name] !== undefined,
72
- );
73
- const suites = configuration?.suites?.filter((suite) => suite.kind === kind) ?? [];
74
- const validSuites =
75
- suites.length > 0 &&
76
- suites.every(
77
- (suite) =>
78
- typeof scripts[suite.script] === 'string' &&
79
- suite.paths.length > 0 &&
80
- suite.paths.every((path) => typeof path === 'string' && isSafePattern(path)),
81
- );
82
- const fallbackScripts =
83
- defaults.length > 0
84
- ? defaults
85
- : suites.map((suite) => suite.script).filter((script) => scripts[script] !== undefined);
86
-
87
- if (fallbackScripts.length === 0)
88
- return { mode: 'skip', scripts: [], reason: 'No suite scripts' };
89
- if (docs) return { mode: 'skip', scripts: [], reason: 'Documentation only' };
90
- if (full || files === null)
91
- return { mode: 'full', scripts: fallbackScripts, reason: 'Unsafe or unavailable diff' };
92
- if (configuration?.complete?.[kind] !== true || !validSuites) {
93
- return { mode: 'full', scripts: fallbackScripts, reason: 'No complete suite mapping' };
94
- }
95
- const matches = files.map((file) =>
96
- suites.filter((suite) => suite.paths.some((pattern) => matchesPath(file, pattern))),
97
- );
98
- if (matches.some((found) => found.length === 0)) {
99
- return { mode: 'full', scripts: fallbackScripts, reason: 'Unmapped changed file' };
100
- }
101
- const selected = [...new Set(matches.flat().map((suite) => suite.script))];
102
- return { mode: 'scoped', scripts: selected, reason: 'Explicit complete suite mapping' };
103
- }
104
-
105
- /*** Conservatively identify changes that invalidate impact pruning. */
106
- function isUnsafeChange(file: string): boolean {
107
- return (
108
- /^(?:\.github\/|\.agents\/|scripts\/|test\/|tests\/|config\/)/u.test(file) ||
109
- /^(?:package\.json|bun\.lock|bunfig\.toml|AGENTS\.md|tsconfig[^/]*|playwright\.config\.[^/]+|vitest\.config\.[^/]+|jest\.config\.[^/]+|eslint\.config\.[^/]+|\.env[^/]*)$/u.test(
110
- file,
111
- )
112
- );
113
- }
114
-
115
- /*** Classify files whose changes cannot influence runtime test execution. */
116
- function isDocumentation(file: string): boolean {
117
- return (
118
- file.startsWith('docs/') ||
119
- file.startsWith('.changeset/') ||
120
- (/\.(?:md|mdx)$/u.test(file) && !isUnsafeChange(file)) ||
121
- file === 'LICENSE'
122
- );
123
- }
124
-
125
- /*** Keep mapping syntax deliberately restricted to exact paths and directory descendants. */
126
- function isSafePattern(pattern: string): boolean {
127
- return (
128
- !pattern.startsWith('/') &&
129
- !pattern.includes('..') &&
130
- /^(?:[a-zA-Z0-9_.@-]+\/)*[a-zA-Z0-9_.@*-]+$/u.test(pattern) &&
131
- (!pattern.includes('*') || pattern.endsWith('/**'))
132
- );
133
- }
134
-
135
- /*** Match one declared path or its explicit recursive directory ownership. */
136
- function matchesPath(file: string, pattern: string): boolean {
137
- return pattern.endsWith('/**') ? file.startsWith(pattern.slice(0, -2)) : file === pattern;
138
- }
139
-
140
- /*** Read Git's binary-safe status output, failing closed for removals and invalid refs. */
141
- function readChangedFiles(base: string): readonly string[] | null {
142
- if (!/^[a-f0-9]{40}$/u.test(base)) return null;
143
- try {
144
- execFileSync('git', ['cat-file', '-e', base + '^{commit}'], { stdio: 'ignore' });
145
- const output = execFileSync(
146
- 'git',
147
- ['diff', '--name-status', '--no-renames', '-z', base, 'HEAD', '--'],
148
- { encoding: 'utf8' },
149
- );
150
- const items = output.split('\0').filter(Boolean);
151
- if (items.length % 2 !== 0) return null;
152
- const changes = Array.from({ length: items.length / 2 }, (_, index) => ({
153
- status: items[index * 2],
154
- path: items[index * 2 + 1],
155
- }));
156
- return changes.every((item) => /^[AMT]$/u.test(item.status) && !item.path.includes('\n'))
157
- ? changes.map((item) => item.path)
158
- : null;
159
- } catch {
160
- return null;
161
- }
162
- }
163
-
164
- /*** Produce a full plan when the workflow cannot prove a trustworthy PR delta. */
165
- function createPlan(): Plan {
166
- const manifest = JSON.parse(readFileSync('package.json', 'utf8')) as {
167
- scripts?: Record<string, string>;
168
- ankh?: { ciImpact?: Configuration };
169
- };
170
- const base =
171
- process.env.GITHUB_EVENT_NAME === 'pull_request' ? (process.env.ANKH_CI_BASE_SHA ?? '') : '';
172
- const files = base ? readChangedFiles(base) : null;
173
- return planCiImpact(files, manifest.scripts ?? {}, manifest.ankh?.ciImpact, base);
174
- }
175
-
176
- /*** Execute an already saved CI plan without shell interpolation. */
177
- function runPlan(plan: Plan, kind: 'unit' | Kind): void {
178
- const selection = plan[kind];
179
- if (selection.mode === 'skip') return;
180
- if (kind === 'unit' && selection.mode === 'changed') {
181
- execFileSync('bun', ['test', '--changed=' + plan.base], { stdio: 'inherit' });
182
- return;
183
- }
184
- for (const script of selection.scripts) {
185
- execFileSync('bun', ['run', script], { stdio: 'inherit' });
186
- }
187
- }
188
-
189
- /*** Expose test decisions in GitHub outputs and a human-readable step summary. */
190
- function main(): void {
191
- const operation = process.argv[2];
192
- const planPath = join(process.env.RUNNER_TEMP ?? '.', 'ankh-ci-impact-plan.json');
193
- if (operation === 'plan') {
194
- const plan = createPlan();
195
- writeFileSync(planPath, JSON.stringify(plan));
196
- if (process.env.GITHUB_OUTPUT) {
197
- appendFileSync(
198
- process.env.GITHUB_OUTPUT,
199
- ['unit=' + plan.unit.mode, 'e2e=' + plan.e2e.mode, 'smoke=' + plan.smoke.mode].join('\n') +
200
- '\n',
201
- );
202
- }
203
- console.log(JSON.stringify(plan, null, 2));
204
- if (process.env.GITHUB_STEP_SUMMARY) {
205
- appendFileSync(
206
- process.env.GITHUB_STEP_SUMMARY,
207
- '### CI impact\n\n| Suite | Mode | Reason | Scripts |\n| --- | --- | --- | --- |\n' +
208
- (['unit', 'e2e', 'smoke'] as const)
209
- .map(
210
- (kind) =>
211
- '| ' +
212
- kind +
213
- ' | ' +
214
- plan[kind].mode +
215
- ' | ' +
216
- plan[kind].reason +
217
- ' | ' +
218
- (plan[kind].scripts.join(', ') || '—') +
219
- ' |',
220
- )
221
- .join('\n') +
222
- '\n',
223
- );
224
- }
225
- return;
226
- }
227
- if (operation !== 'unit' && operation !== 'e2e' && operation !== 'smoke') {
228
- throw new Error('Expected plan, unit, e2e, or smoke');
229
- }
230
- const plan = JSON.parse(readFileSync(planPath, 'utf8')) as Plan;
231
- runPlan(plan, operation);
232
- }
233
-
234
- if (import.meta.main) main();
3
+ runCiImpact(process.argv.slice(2));
@@ -0,0 +1,335 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ workflow_dispatch:
7
+ inputs:
8
+ release_tag:
9
+ description: Existing v<version> tag to resume from its original commit
10
+ required: false
11
+ type: string
12
+
13
+ # The default token reads only exact-commit Check Runs. A scoped App token performs release mutation.
14
+ permissions:
15
+ actions: read
16
+ checks: read
17
+ contents: read
18
+
19
+ concurrency:
20
+ group: release-${{ github.ref }}
21
+ cancel-in-progress: false
22
+
23
+ jobs:
24
+ release:
25
+ runs-on: ubuntu-latest
26
+ outputs:
27
+ asset_name: ${{ steps.release.outputs.asset_name }}
28
+ package_version: ${{ steps.release.outputs.package_version }}
29
+ release_sha: ${{ steps.release.outputs.release_sha }}
30
+ versioned: ${{ steps.release.outputs.versioned }}
31
+ steps:
32
+ - name: Create the scoped release token
33
+ id: release-token
34
+ continue-on-error: true
35
+ uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
36
+ with:
37
+ client-id: ${{ vars.ANKHORAGE_RENOVATE_SYNC_CLIENT_ID }}
38
+ private-key: ${{ secrets.ANKHORAGE_RENOVATE_SYNC_PRIVATE_KEY }}
39
+ owner: ankhorage
40
+ repositories: ${{ github.event.repository.name }}
41
+ permission-actions: read
42
+ permission-checks: read
43
+ permission-contents: read
44
+ - name: Diagnose unavailable scoped release token
45
+ if: steps.release-token.outcome == 'failure'
46
+ run: |
47
+ echo "::error title=Release App repository access required::The Release App needs Checks: Read and Contents: Read for ${GITHUB_REPOSITORY}."
48
+ exit 1
49
+ - name: Checkout exact trusted main commit
50
+ uses: actions/checkout@v4
51
+ with:
52
+ fetch-depth: 0
53
+ token: ${{ steps.release-token.outputs.token }}
54
+ - name: Synchronize latest main
55
+ run: |
56
+ git fetch origin main --tags
57
+ git checkout -B main origin/main
58
+ - name: Select explicit artifact release intent
59
+ id: release
60
+ env:
61
+ RECOVERY_TAG: ${{ inputs.release_tag }}
62
+ run: |
63
+ set -euo pipefail
64
+ node - <<'NODE'
65
+ const { appendFileSync, readFileSync } = require('node:fs');
66
+ const { execFileSync, spawnSync } = require('node:child_process');
67
+ const fail = (message) => { throw new Error(message); };
68
+ const recoveryTag = process.env.RECOVERY_TAG;
69
+ const commitForTag = (tag) => {
70
+ const resolved = spawnSync('git', ['rev-parse', '-q', '--verify', `refs/tags/${tag}^{commit}`], { encoding: 'utf8' });
71
+ if (resolved.status !== 0 || !/^[0-9a-f]{40}$/u.test(resolved.stdout.trim())) fail(`Release tag conflict: ${tag} does not resolve to a commit.`);
72
+ return resolved.stdout.trim();
73
+ };
74
+ const sourceSha = recoveryTag === undefined || recoveryTag === '' ? undefined : commitForTag(recoveryTag);
75
+ if (sourceSha !== undefined) execFileSync('git', ['checkout', '--detach', sourceSha], { stdio: 'inherit' });
76
+ let descriptor = JSON.parse(readFileSync('.ankh/release-distribution.json', 'utf8'));
77
+ const command = (value, field) => {
78
+ if (!Array.isArray(value) || value.length === 0 || value.some((part) => typeof part !== 'string' || part.length === 0)) fail(`${field} must be a non-empty argv array.`);
79
+ return value;
80
+ };
81
+ if (!descriptor || descriptor.kind !== 'github-artifact') fail('Expected github-artifact descriptor.');
82
+ const versionArgv = command(descriptor.versionCommand, 'versionCommand');
83
+ const versionResult = spawnSync(versionArgv[0], versionArgv.slice(1), { encoding: 'utf8' });
84
+ if (versionResult.error || versionResult.status !== 0) fail(`versionCommand failed: ${versionResult.error?.message ?? versionResult.stderr}`);
85
+ const version = versionResult.stdout.trim();
86
+ if (!/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/u.test(version)) fail('The descriptor version command must print one stable semantic version.');
87
+ const tuple = (value) => value.replace(/^v/u, '').split('.').map(Number);
88
+ const compare = (left, right) => tuple(left).find((part, index) => part !== tuple(right)[index]) === undefined ? 0 : tuple(left)[tuple(left).findIndex((part, index) => part !== tuple(right)[index])] - tuple(right)[tuple(left).findIndex((part, index) => part !== tuple(right)[index])];
89
+ const tag = `v${version}`;
90
+ if (recoveryTag !== undefined && recoveryTag !== '' && recoveryTag !== tag) fail(`Recovery tag ${recoveryTag} does not match descriptor version ${version}.`);
91
+ const tagged = spawnSync('git', ['rev-parse', '-q', '--verify', `refs/tags/${tag}^{commit}`], { encoding: 'utf8' });
92
+ if (tagged.status === 0 && sourceSha !== undefined && tagged.stdout.trim() !== sourceSha) fail(`Release tag conflict: ${tag} resolved to a different commit.`);
93
+ if (sourceSha === undefined) {
94
+ const tags = execFileSync('git', ['tag', '--list', 'v*'], { encoding: 'utf8' }).split(/\r?\n/u).filter((candidate) => /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(candidate)).sort(compare);
95
+ const highest = tags.at(-1);
96
+ if (highest && compare(version, highest) < 0 && tagged.status !== 0) fail(`Artifact release version regression: ${version} is lower than existing tag ${highest}.`);
97
+ }
98
+ if (tagged.status === 0 && sourceSha === undefined) {
99
+ execFileSync('git', ['checkout', '--detach', tagged.stdout.trim()], { stdio: 'inherit' });
100
+ descriptor = JSON.parse(readFileSync('.ankh/release-distribution.json', 'utf8'));
101
+ if (!descriptor || descriptor.kind !== 'github-artifact') fail('Expected github-artifact descriptor at the tagged commit.');
102
+ const taggedVersionArgv = command(descriptor.versionCommand, 'versionCommand');
103
+ const taggedVersionResult = spawnSync(taggedVersionArgv[0], taggedVersionArgv.slice(1), { encoding: 'utf8' });
104
+ if (taggedVersionResult.error || taggedVersionResult.status !== 0 || taggedVersionResult.stdout.trim() !== version) fail(`Release tag conflict: ${tag} does not match its original descriptor version.`);
105
+ }
106
+ const releaseSha = tagged.status === 0 ? tagged.stdout.trim() : execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
107
+ if (typeof descriptor.assetName !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(descriptor.assetName)) fail('assetName must be a plain safe filename.');
108
+ appendFileSync(process.env.GITHUB_OUTPUT, `versioned=true\npackage_version=${version}\nrelease_sha=${releaseSha}\nasset_name=${descriptor.assetName}\n`);
109
+ NODE
110
+ - name: Checkout canonical release commit for recovery
111
+ if: steps.release.outputs.versioned == 'true'
112
+ uses: actions/checkout@v4
113
+ with:
114
+ fetch-depth: 0
115
+ ref: ${{ steps.release.outputs.release_sha }}
116
+ token: ${{ steps.release-token.outputs.token }}
117
+ - name: Setup Bun
118
+ if: steps.release.outputs.versioned == 'true'
119
+ uses: oven-sh/setup-bun@v2
120
+ with:
121
+ bun-version: '__ANKH_BUN_VERSION__'
122
+ - name: Install dependencies
123
+ if: steps.release.outputs.versioned == 'true'
124
+ run: bun install --frozen-lockfile
125
+ - name: Build and verify exact artifact
126
+ if: steps.release.outputs.versioned == 'true'
127
+ env:
128
+ ASSET_NAME: ${{ steps.release.outputs.asset_name }}
129
+ RELEASE_SHA: ${{ steps.release.outputs.release_sha }}
130
+ RELEASE_VERSION: ${{ steps.release.outputs.package_version }}
131
+ run: |
132
+ set -euo pipefail
133
+ node - <<'NODE'
134
+ const { createHash } = require('node:crypto');
135
+ const { copyFileSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } = require('node:fs');
136
+ const { relative, resolve, sep } = require('node:path');
137
+ const { spawnSync } = require('node:child_process');
138
+ const fail = (message) => { throw new Error(message); };
139
+ const descriptor = JSON.parse(readFileSync('.ankh/release-distribution.json', 'utf8'));
140
+ const command = (value, field) => {
141
+ if (!Array.isArray(value) || value.length === 0 || value.some((part) => typeof part !== 'string' || part.length === 0)) fail(`${field} must be a non-empty argv array.`);
142
+ return value;
143
+ };
144
+ for (const field of ['buildCommand', 'verifyCommand']) {
145
+ const argv = command(descriptor[field], field);
146
+ const result = spawnSync(argv[0], argv.slice(1), { stdio: 'inherit' });
147
+ if (result.error || result.status !== 0) fail(`${field} failed.`);
148
+ }
149
+ if (typeof descriptor.assetPath !== 'string' || descriptor.assetPath.includes('\\') || descriptor.assetPath.includes('\n') || descriptor.assetPath.includes('\r')) fail('assetPath must be a slash-separated relative path.');
150
+ const root = realpathSync('.');
151
+ const declared = resolve(root, descriptor.assetPath);
152
+ const declaredFromRoot = relative(root, declared);
153
+ if (declaredFromRoot === '' || declaredFromRoot === '..' || declaredFromRoot.startsWith(`..${sep}`)) fail('Configured artifact path escapes the repository root.');
154
+ const segments = declaredFromRoot.split(sep);
155
+ for (let index = 0; index < segments.length; index += 1) {
156
+ if (lstatSync(resolve(root, ...segments.slice(0, index + 1))).isSymbolicLink()) fail('Configured artifact path must not traverse a symbolic link.');
157
+ }
158
+ const asset = realpathSync(declared);
159
+ const pathFromRoot = relative(root, asset);
160
+ if (pathFromRoot === '' || pathFromRoot === '..' || pathFromRoot.startsWith(`..${sep}`) || !lstatSync(asset).isFile()) fail('Configured artifact must be a regular file below the repository root.');
161
+ const name = process.env.ASSET_NAME;
162
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(name)) fail('Invalid managed asset name.');
163
+ mkdirSync(process.env.RUNNER_TEMP, { recursive: true });
164
+ const output = resolve(process.env.RUNNER_TEMP, name);
165
+ copyFileSync(asset, output);
166
+ const sha256 = createHash('sha256').update(readFileSync(output)).digest('hex');
167
+ writeFileSync(`${output}.sha256`, `${sha256} ${name}\n`);
168
+ writeFileSync(`${output}.provenance.json`, `${JSON.stringify({ asset: name, commit: process.env.RELEASE_SHA, sha256, version: process.env.RELEASE_VERSION })}\n`);
169
+ NODE
170
+ - name: Require successful declared CI gates
171
+ if: steps.release.outputs.versioned == 'true'
172
+ env:
173
+ GH_TOKEN: ${{ steps.release-token.outputs.token }}
174
+ RELEASE_SHA: ${{ steps.release.outputs.release_sha }}
175
+ run: |
176
+ set -euo pipefail
177
+ gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/actions/workflows?per_page=100" > "${RUNNER_TEMP}/release-workflows.json"
178
+ for attempt in $(seq 1 18); do
179
+ gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/commits/${RELEASE_SHA}/check-runs?filter=latest&per_page=100" > "${RUNNER_TEMP}/release-checks.json"
180
+ gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/actions/runs?head_sha=${RELEASE_SHA}&event=push&branch=main&per_page=100" > "${RUNNER_TEMP}/release-workflow-runs.json"
181
+ if CHECKS_FILE="${RUNNER_TEMP}/release-checks.json" RUNS_FILE="${RUNNER_TEMP}/release-workflow-runs.json" WORKFLOWS_FILE="${RUNNER_TEMP}/release-workflows.json" node - <<'NODE'
182
+ const { readFileSync } = require('node:fs');
183
+ const descriptor = JSON.parse(readFileSync('.ankh/release-distribution.json', 'utf8'));
184
+ const checkPages = JSON.parse(readFileSync(process.env.CHECKS_FILE, 'utf8'));
185
+ if (!Array.isArray(descriptor.requiredChecks) || descriptor.requiredChecks.length === 0 || descriptor.requiredChecks.some((name) => typeof name !== 'string' || !name)) throw new Error('requiredChecks must name one or more GitHub Check Run names.');
186
+ if (typeof descriptor.requiredWorkflow !== 'string' || !/^\.github\/workflows\/[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/u.test(descriptor.requiredWorkflow)) throw new Error('requiredWorkflow must name one GitHub Actions workflow file.');
187
+ if (!Array.isArray(checkPages) || checkPages.some((page) => !page || !Array.isArray(page.check_runs))) throw new Error('Invalid GitHub Check Runs response.');
188
+ const checks = checkPages.flatMap((page) => page.check_runs);
189
+ if (!checkPages.every((page) => Number.isSafeInteger(page.total_count)) || checks.length !== checkPages[0].total_count) throw new Error('Incomplete GitHub Check Runs response; refusing to publish.');
190
+ const workflowPages = JSON.parse(readFileSync(process.env.WORKFLOWS_FILE, 'utf8'));
191
+ if (!Array.isArray(workflowPages) || workflowPages.some((page) => !page || !Array.isArray(page.workflows))) throw new Error('Invalid GitHub Actions Workflows response.');
192
+ const workflows = workflowPages.flatMap((page) => page.workflows);
193
+ if (!workflowPages.every((page) => Number.isSafeInteger(page.total_count)) || workflows.length !== workflowPages[0].total_count) throw new Error('Incomplete GitHub Actions Workflows response; refusing to publish.');
194
+ const workflow = workflows.filter((candidate) => candidate.path === descriptor.requiredWorkflow);
195
+ if (workflow.length !== 1 || !Number.isSafeInteger(workflow[0].id)) throw new Error('Trusted CI workflow provenance is missing or ambiguous.');
196
+ const required = descriptor.requiredChecks.map((name) => ({ name, runs: checks.filter((check) => check.name === name) }));
197
+ if (required.some(({ runs }) => runs.some((run) => run.head_sha !== process.env.RELEASE_SHA))) throw new Error('Required CI checks must belong to the exact release commit.');
198
+ const failed = required.filter(({ runs }) => runs.some((run) => run.status === 'completed' && run.conclusion !== 'success'));
199
+ if (failed.length > 0) throw new Error(`Required CI checks failed, cancelled, skipped, or were blocked: ${failed.map(({ name }) => name).join(', ')}.`);
200
+ if (required.some(({ runs }) => runs.length !== 1 || runs[0].status !== 'completed')) process.exit(2);
201
+ if (required.some(({ runs }) => runs[0].conclusion !== 'success')) throw new Error('Required CI checks did not successfully execute.');
202
+ const workflowId = workflow[0].id;
203
+ const runResponse = JSON.parse(readFileSync(process.env.RUNS_FILE, 'utf8'));
204
+ if (!Array.isArray(runResponse) || runResponse.some((page) => !page || !Array.isArray(page.workflow_runs))) throw new Error('Invalid GitHub Actions Workflow Runs response.');
205
+ const workflowRuns = runResponse.flatMap((page) => page.workflow_runs);
206
+ if (!runResponse.every((page) => Number.isSafeInteger(page.total_count)) || workflowRuns.length !== runResponse[0].total_count) throw new Error('Incomplete GitHub Actions Workflow Runs response; refusing to publish.');
207
+ const trusted = workflowRuns.filter((run) => run.workflow_id === workflowId && run.event === 'push' && run.head_branch === 'main' && run.head_sha === process.env.RELEASE_SHA);
208
+ const incomplete = trusted.some((run) => run.status !== 'completed');
209
+ const failedRuns = trusted.filter((run) => run.status === 'completed' && run.conclusion !== 'success');
210
+ if (failedRuns.length > 0) throw new Error('Trusted main CI workflow failed, was cancelled, skipped, or was blocked.');
211
+ if (incomplete) process.exit(2);
212
+ const requiredSuites = required.map(({ name, runs }) => {
213
+ const suiteId = runs[0].check_suite?.id;
214
+ if (!Number.isSafeInteger(suiteId)) throw new Error(`Required CI check ${name} has no Check Suite provenance.`);
215
+ return { name, suiteId };
216
+ });
217
+ const provenance = requiredSuites.map(({ name, suiteId }) => ({ name, runs: trusted.filter((run) => run.check_suite_id === suiteId) }));
218
+ if (provenance.some(({ runs }) => runs.length === 0)) process.exit(2);
219
+ if (provenance.some(({ runs }) => runs.length !== 1)) throw new Error('Required CI check provenance is ambiguous.');
220
+ if (provenance.some(({ runs }) => runs[0].status !== 'completed')) process.exit(2);
221
+ if (provenance.some(({ runs }) => runs[0].conclusion !== 'success')) throw new Error('Trusted main CI workflow did not successfully execute.');
222
+ NODE
223
+ then exit 0; else status=$?; fi
224
+ if [ "$status" -ne 2 ] || [ "$attempt" -eq 18 ]; then
225
+ echo "::error title=Required CI checks unavailable::The exact release commit did not complete all declared Check Runs successfully."
226
+ exit "$status"
227
+ fi
228
+ sleep 10
229
+ done
230
+ - name: Retain exact artifact for finalization
231
+ if: steps.release.outputs.versioned == 'true'
232
+ uses: actions/upload-artifact@v4
233
+ with:
234
+ name: release-${{ steps.release.outputs.package_version }}
235
+ if-no-files-found: error
236
+ path: |
237
+ ${{ runner.temp }}/${{ steps.release.outputs.asset_name }}
238
+ ${{ runner.temp }}/${{ steps.release.outputs.asset_name }}.sha256
239
+ ${{ runner.temp }}/${{ steps.release.outputs.asset_name }}.provenance.json
240
+ finalize:
241
+ needs: release
242
+ if: needs.release.outputs.versioned == 'true'
243
+ runs-on: ubuntu-latest
244
+ steps:
245
+ - name: Create the scoped release token
246
+ id: release-token
247
+ uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
248
+ with:
249
+ client-id: ${{ vars.ANKHORAGE_RENOVATE_SYNC_CLIENT_ID }}
250
+ private-key: ${{ secrets.ANKHORAGE_RENOVATE_SYNC_PRIVATE_KEY }}
251
+ owner: ankhorage
252
+ repositories: ${{ github.event.repository.name }}
253
+ permission-contents: write
254
+ - name: Checkout exact release commit
255
+ uses: actions/checkout@v4
256
+ with:
257
+ fetch-depth: 0
258
+ ref: ${{ needs.release.outputs.release_sha }}
259
+ token: ${{ steps.release-token.outputs.token }}
260
+ - name: Download exact artifact
261
+ uses: actions/download-artifact@v4
262
+ with:
263
+ name: release-${{ needs.release.outputs.package_version }}
264
+ path: release-artifact
265
+ - name: Finalize immutable artifact release
266
+ env:
267
+ ASSET_NAME: ${{ needs.release.outputs.asset_name }}
268
+ RELEASE_SHA: ${{ needs.release.outputs.release_sha }}
269
+ RELEASE_VERSION: ${{ needs.release.outputs.package_version }}
270
+ GH_TOKEN: ${{ steps.release-token.outputs.token }}
271
+ run: |
272
+ set -euo pipefail
273
+ tag="v${RELEASE_VERSION}"
274
+ asset="release-artifact/${ASSET_NAME}"
275
+ expected_sha="$(cut -d ' ' -f1 "${asset}.sha256")"
276
+ git fetch origin --tags
277
+ remote_sha="$(git rev-parse -q --verify "refs/tags/$tag^{commit}" 2>/dev/null || true)"
278
+ if [ -n "$remote_sha" ] && [ "$remote_sha" != "$RELEASE_SHA" ]; then
279
+ echo "::error title=Release tag mismatch::${tag} points to ${remote_sha}, expected ${RELEASE_SHA}."
280
+ exit 1
281
+ fi
282
+ if [ -z "$remote_sha" ]; then git tag "$tag" "$RELEASE_SHA"; git push origin "refs/tags/$tag"; fi
283
+ release_lookup_error="$(mktemp)"
284
+ if ! gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${tag}" >/dev/null 2>"$release_lookup_error"; then
285
+ if ! grep -q 'HTTP 404' "$release_lookup_error"; then
286
+ cat "$release_lookup_error" >&2
287
+ exit 1
288
+ fi
289
+ gh release create "$tag" --repo "$GITHUB_REPOSITORY" --draft --generate-notes --target "$RELEASE_SHA"
290
+ fi
291
+ rm -f "$release_lookup_error"
292
+ release_target="$(gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json targetCommitish --jq .targetCommitish)"
293
+ release_draft="$(gh release view "$tag" --repo "$GITHUB_REPOSITORY" --json isDraft --jq .isDraft)"
294
+ release_target_sha="$(git rev-parse -q --verify "${release_target}^{commit}" 2>/dev/null || true)"
295
+ if [ "$release_target_sha" != "$RELEASE_SHA" ]; then
296
+ echo "::error title=Release target mismatch::${tag} targets ${release_target}, expected ${RELEASE_SHA}."
297
+ exit 1
298
+ fi
299
+ release_id="$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${tag}" --jq .id)"
300
+ if ! [[ "$release_id" =~ ^[0-9]+$ ]]; then
301
+ echo "::error title=Invalid release API response::Release ${tag} did not provide a numeric release ID."
302
+ exit 1
303
+ fi
304
+ assets_json="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases/${release_id}/assets?per_page=100")"
305
+ ASSETS_JSON="$assets_json" ASSET_NAME="$ASSET_NAME" node - <<'NODE'
306
+ const pages = JSON.parse(process.env.ASSETS_JSON);
307
+ if (!Array.isArray(pages) || pages.some((page) => !Array.isArray(page))) throw new Error('Invalid release-assets API response.');
308
+ const expected = [process.env.ASSET_NAME, `${process.env.ASSET_NAME}.sha256`, `${process.env.ASSET_NAME}.provenance.json`];
309
+ const names = pages.flat().map((asset) => asset?.name);
310
+ if (names.some((name) => typeof name !== 'string')) throw new Error('Invalid release asset entry.');
311
+ for (const name of expected) if (names.filter((candidate) => candidate === name).length > 1) throw new Error(`Duplicate release asset name: ${name}.`);
312
+ NODE
313
+ for companion in "$ASSET_NAME" "${ASSET_NAME}.sha256" "${ASSET_NAME}.provenance.json"; do
314
+ if ASSETS_JSON="$assets_json" COMPANION="$companion" node -e 'const pages=JSON.parse(process.env.ASSETS_JSON); process.exit(pages.flat().some((asset) => asset.name === process.env.COMPANION) ? 0 : 1)'; then
315
+ mkdir -p remote-artifact
316
+ gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern "$companion" --dir remote-artifact
317
+ cmp "release-artifact/${companion}" "remote-artifact/${companion}"
318
+ else
319
+ gh release upload "$tag" "release-artifact/${companion}#${companion}" --repo "$GITHUB_REPOSITORY"
320
+ fi
321
+ done
322
+ rm -rf remote-artifact
323
+ mkdir remote-artifact
324
+ for companion in "$ASSET_NAME" "${ASSET_NAME}.sha256" "${ASSET_NAME}.provenance.json"; do
325
+ gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern "$companion" --dir remote-artifact
326
+ done
327
+ EXPECTED_SHA="$expected_sha" ASSET_NAME="$ASSET_NAME" RELEASE_SHA="$RELEASE_SHA" RELEASE_VERSION="$RELEASE_VERSION" node - <<'NODE'
328
+ const { createHash } = require('node:crypto'); const { readFileSync } = require('node:fs');
329
+ const asset = readFileSync(`remote-artifact/${process.env.ASSET_NAME}`); const sha = createHash('sha256').update(asset).digest('hex');
330
+ if (sha !== process.env.EXPECTED_SHA) throw new Error('Existing release asset bytes differ from the exact validated artifact.');
331
+ if (readFileSync(`remote-artifact/${process.env.ASSET_NAME}.sha256`, 'utf8') !== `${sha} ${process.env.ASSET_NAME}\n`) throw new Error('Existing release checksum companion differs from the expected portable content.');
332
+ const expected = `${JSON.stringify({ asset: process.env.ASSET_NAME, commit: process.env.RELEASE_SHA, sha256: sha, version: process.env.RELEASE_VERSION })}\n`;
333
+ if (readFileSync(`remote-artifact/${process.env.ASSET_NAME}.provenance.json`, 'utf8') !== expected) throw new Error('Existing release provenance companion differs from the expected content.');
334
+ NODE
335
+ if [ "$release_draft" = true ]; then gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --draft=false; fi
@@ -5,25 +5,13 @@ import { resolveApmReleaseCommandAsync } from '../../features/apm-release-valida
5
5
  import { resolveStructureReleaseCommandAsync } from '../../features/structure-descriptor-generation/adapters/outbound/resolveStructureReleaseCommandAsync.js';
6
6
  import { resolveAtlasAuditPolicyAsync } from '../../policy/resolveAtlasAuditPolicyAsync.js';
7
7
  import { readCurrentDoctorVersion } from './readCurrentDoctorVersion.js';
8
+ import { hasGitHubArtifactReleaseDescriptorAsync, readGitHubArtifactReleaseDescriptorAsync, } from './readGitHubArtifactReleaseDescriptorAsync.js';
8
9
  import { renderRenovateConfigAsync } from './renderRenovateConfigAsync.js';
9
10
  import { renderRenovateWorkflowAsync } from './renderRenovateWorkflowAsync.js';
10
11
  import { renderWorkflowAsync } from './renderWorkflowAsync.js';
11
12
  export const workflowManagedFiles = [
12
13
  createWorkflowDefinition('.github/workflows/ci.yml', './files/ci.yml'),
13
- {
14
- ...createWorkflowDefinition('.github/workflows/release.yml', './files/release.yml'),
15
- isApplicable: async (targetDirectory) => {
16
- try {
17
- await access(join(targetDirectory, '.changeset/config.json'));
18
- return true;
19
- }
20
- catch (error) {
21
- if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
22
- return false;
23
- throw error;
24
- }
25
- },
26
- },
14
+ createReleaseWorkflowDefinition(),
27
15
  createRenovateWorkflowDefinition(),
28
16
  {
29
17
  relativePath: '.github/scripts/ci-impact.ts',
@@ -49,6 +37,37 @@ function createWorkflowDefinition(relativePath, sourcePath) {
49
37
  }),
50
38
  };
51
39
  }
40
+ /*** Render the legacy npm lane unchanged unless a repository explicitly opts into artifact-only release. */
41
+ function createReleaseWorkflowDefinition() {
42
+ return {
43
+ relativePath: '.github/workflows/release.yml',
44
+ isApplicable: async (targetDirectory) => (await hasGitHubArtifactReleaseDescriptorAsync(targetDirectory)) ||
45
+ (await hasChangesetsConfigAsync(targetDirectory)),
46
+ render: async (targetDirectory) => {
47
+ const artifactRelease = await readGitHubArtifactReleaseDescriptorAsync(targetDirectory);
48
+ return await renderWorkflowAsync(new URL(artifactRelease === undefined ? './files/release.yml' : './files/release-artifact.yml', import.meta.url), {
49
+ apmReleaseCommand: await resolveApmReleaseCommandAsync(targetDirectory),
50
+ structureReleaseCommand: await resolveStructureReleaseCommandAsync(targetDirectory),
51
+ bunVersion: REPOSITORY_RULE_METADATA.runtime.bun.version,
52
+ doctorVersion: readCurrentDoctorVersion(),
53
+ nodeVersion: REPOSITORY_RULE_METADATA.runtime.node.setupVersion,
54
+ atlasAudit: await resolveAtlasAuditPolicyAsync(targetDirectory),
55
+ });
56
+ },
57
+ };
58
+ }
59
+ /*** Check the established Changesets opt-in without treating any read failure as absence. */
60
+ async function hasChangesetsConfigAsync(targetDirectory) {
61
+ try {
62
+ await access(join(targetDirectory, '.changeset/config.json'));
63
+ return true;
64
+ }
65
+ catch (error) {
66
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
67
+ return false;
68
+ throw error;
69
+ }
70
+ }
52
71
  /*** Creates the managed workflow whose immutable digest remains Renovate-owned. */
53
72
  function createRenovateWorkflowDefinition() {
54
73
  const sourceUrl = new URL('./files/renovate.yml', import.meta.url);
@@ -0,0 +1,13 @@
1
+ export interface GitHubArtifactReleaseDescriptor {
2
+ readonly assetName: string;
3
+ readonly assetPath: string;
4
+ readonly buildCommand: readonly string[];
5
+ readonly requiredChecks: readonly string[];
6
+ readonly requiredWorkflow: string;
7
+ readonly verifyCommand: readonly string[];
8
+ readonly versionCommand: readonly string[];
9
+ }
10
+ /*** Read the opted-in artifact release contract before rendering its static workflow. */
11
+ export declare function readGitHubArtifactReleaseDescriptorAsync(targetDirectory: string): Promise<GitHubArtifactReleaseDescriptor | undefined>;
12
+ /*** Determine whether the explicitly named artifact contract exists without interpreting its contents. */
13
+ export declare function hasGitHubArtifactReleaseDescriptorAsync(targetDirectory: string): Promise<boolean>;
@@ -0,0 +1,110 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join, relative, resolve } from 'node:path';
3
+ const DESCRIPTOR_PATH = '.ankh/release-distribution.json';
4
+ /*** Read the opted-in artifact release contract before rendering its static workflow. */
5
+ export async function readGitHubArtifactReleaseDescriptorAsync(targetDirectory) {
6
+ const descriptorPath = join(targetDirectory, DESCRIPTOR_PATH);
7
+ let source;
8
+ try {
9
+ source = await readFile(descriptorPath, 'utf8');
10
+ }
11
+ catch (error) {
12
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
13
+ return undefined;
14
+ throw error;
15
+ }
16
+ let value;
17
+ try {
18
+ value = JSON.parse(source);
19
+ }
20
+ catch {
21
+ throw new Error(`${DESCRIPTOR_PATH} must contain valid JSON.`);
22
+ }
23
+ if (!isRecord(value) || value.kind !== 'github-artifact') {
24
+ throw new Error(`${DESCRIPTOR_PATH} must declare kind "github-artifact".`);
25
+ }
26
+ const versionCommand = readCommand(value.versionCommand, 'versionCommand');
27
+ const buildCommand = readCommand(value.buildCommand, 'buildCommand');
28
+ const requiredChecks = readRequiredChecks(value.requiredChecks);
29
+ const requiredWorkflow = readRequiredWorkflow(value.requiredWorkflow);
30
+ const verifyCommand = readCommand(value.verifyCommand, 'verifyCommand');
31
+ const assetPath = readRelativePath(value.assetPath, 'assetPath', targetDirectory);
32
+ const assetName = readAssetName(value.assetName);
33
+ return {
34
+ assetName,
35
+ assetPath,
36
+ buildCommand,
37
+ requiredChecks,
38
+ requiredWorkflow,
39
+ verifyCommand,
40
+ versionCommand,
41
+ };
42
+ }
43
+ /*** Determine whether the explicitly named artifact contract exists without interpreting its contents. */
44
+ export async function hasGitHubArtifactReleaseDescriptorAsync(targetDirectory) {
45
+ try {
46
+ await readFile(join(targetDirectory, DESCRIPTOR_PATH), 'utf8');
47
+ return true;
48
+ }
49
+ catch (error) {
50
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
51
+ return false;
52
+ throw error;
53
+ }
54
+ }
55
+ /*** Require a command argv so workflow execution never evaluates descriptor data as a shell program. */
56
+ function readCommand(value, field) {
57
+ if (!isNonEmptyStringArray(value)) {
58
+ throw new Error(`${DESCRIPTOR_PATH} ${field} must be a non-empty array of command arguments.`);
59
+ }
60
+ return value;
61
+ }
62
+ /*** Keep artifact paths repository-relative and make traversal impossible before workflow rendering. */
63
+ function readRelativePath(value, field, targetDirectory) {
64
+ if (typeof value !== 'string' ||
65
+ value.length === 0 ||
66
+ value.includes('\\') ||
67
+ value.includes('\n') ||
68
+ value.includes('\r')) {
69
+ throw new Error(`${DESCRIPTOR_PATH} ${field} must be a non-empty slash-separated relative path.`);
70
+ }
71
+ const resolved = resolve(targetDirectory, value);
72
+ const pathFromRoot = relative(targetDirectory, resolved);
73
+ if (pathFromRoot === '' || pathFromRoot.startsWith('../') || pathFromRoot === '..') {
74
+ throw new Error(`${DESCRIPTOR_PATH} ${field} must remain below the repository root.`);
75
+ }
76
+ return pathFromRoot;
77
+ }
78
+ /*** Restrict the release label to one plain filename, never a path interpreted by GitHub CLI. */
79
+ function readAssetName(value) {
80
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(value)) {
81
+ throw new Error(`${DESCRIPTOR_PATH} assetName must be a plain safe filename.`);
82
+ }
83
+ return value;
84
+ }
85
+ /*** Require named successful CI gates so an unexecuted or blocked check can never publish an artifact. */
86
+ function readRequiredChecks(value) {
87
+ if (!isNonEmptyStringArray(value) ||
88
+ value.some((check) => check.length > 200 || !/^[A-Za-z0-9 ._:/()-]+$/u.test(check))) {
89
+ throw new Error(`${DESCRIPTOR_PATH} requiredChecks must name one or more required CI checks.`);
90
+ }
91
+ return value;
92
+ }
93
+ /*** Require one checked-in workflow file so check names cannot be satisfied by another workflow. */
94
+ function readRequiredWorkflow(value) {
95
+ if (typeof value !== 'string' ||
96
+ !/^\.github\/workflows\/[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/u.test(value)) {
97
+ throw new Error(`${DESCRIPTOR_PATH} requiredWorkflow must name one GitHub Actions workflow file.`);
98
+ }
99
+ return value;
100
+ }
101
+ /*** Narrow unknown JSON values before reading descriptor fields. */
102
+ function isRecord(value) {
103
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
104
+ }
105
+ /*** Narrow a checked-in command or check-name list to safe non-empty string values. */
106
+ function isNonEmptyStringArray(value) {
107
+ return (Array.isArray(value) &&
108
+ value.length > 0 &&
109
+ value.every((part) => typeof part === 'string' && part.length > 0));
110
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/devtools",
3
- "version": "2.4.4",
3
+ "version": "2.6.0",
4
4
  "description": "Shared tooling, repository automation, and agent standards for Ankhorage TypeScript projects",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/devtools#readme",
@@ -427,6 +427,7 @@
427
427
  ],
428
428
  "bin": {
429
429
  "ankhorage-changeset": "./dist/cli/bin/changeset.js",
430
+ "ankhorage-ci-impact": "./dist/cli/bin/ci-impact.js",
430
431
  "ankhorage-eslint": "./dist/cli/bin/eslint.js",
431
432
  "ankhorage-knip": "./dist/cli/bin/knip.js",
432
433
  "ankhorage-prettier": "./dist/cli/bin/prettier.js",
@@ -463,6 +464,10 @@
463
464
  "./capabilities": {
464
465
  "types": "./dist/capabilities/index.d.ts",
465
466
  "import": "./dist/capabilities/index.js"
467
+ },
468
+ "./ci-impact": {
469
+ "types": "./dist/ci-impact.d.ts",
470
+ "import": "./dist/ci-impact.js"
466
471
  }
467
472
  },
468
473
  "files": [