@patronage/factory-ci 1.0.0-alpha.4 → 1.0.0-alpha.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +712 -10
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  7. package/dist/execute-alchemy-entry-CZ7Knz4q.js +160 -0
  8. package/dist/index.d.ts +1205 -87
  9. package/dist/index.js +2752 -317
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +92 -18
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +223 -48
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
@@ -0,0 +1,168 @@
1
+ /**
2
+ * One read and delete surface over a state layer.
3
+ *
4
+ * Alchemy's `State/Tree` module answers "which `(stack, stage)` pairs does
5
+ * this store hold" and "remove one stage" against the `State` service
6
+ * interface, so it works over any state layer a consumer configured,
7
+ * including `@patronage/alchemy-d1-state`. This module is the typed entry to
8
+ * those two operations plus the record read, and it launches no child
9
+ * process: every answer comes from the state layer the caller passes in.
10
+ *
11
+ * The caller owns the state layer and the policy. This module owns the
12
+ * address: a `(stack, stage)` pair is one stack and one stage, and nothing
13
+ * else. `Tree` addresses a stage by the path `stack/stage`, so an empty or
14
+ * padded stage collapses that path to the stack and a delete meant for one
15
+ * stage removes every stage of the stack. `assertStageAddress` refuses those
16
+ * inputs before any path is built.
17
+ *
18
+ * Which stages a consumer may delete stays with the consumer: this module
19
+ * deletes the stage it is given.
20
+ */
21
+
22
+ import { State } from "alchemy/State";
23
+ import type { StateService } from "alchemy/State";
24
+ import { allStages, deleteState } from "alchemy/State/Tree";
25
+ import * as Effect from "effect/Effect";
26
+
27
+ import type { StageStateStore, StageTarget } from "./lifecycle.ts";
28
+
29
+ /**
30
+ * The subset of the state layer the record read goes through: the atomic
31
+ * stage view and the per-resource record. `@patronage/alchemy-d1-state`
32
+ * satisfies it structurally, the same way `runAlchemyLifecycle` takes it.
33
+ */
34
+ type StageRecordStore = Pick<StageStateStore, "get" | "snapshotStage">;
35
+
36
+ /**
37
+ * Pins part of the inventory.
38
+ *
39
+ * A pinned `stack` or `stage` is taken at face value and skips the matching
40
+ * list call, because naming a scope is not a claim that it exists. So a
41
+ * pinned `stage` returns that stage once per stack whether or not the stack
42
+ * holds it. Pass no filter to inventory what the store actually holds.
43
+ */
44
+ interface StageFilter {
45
+ readonly stack?: string;
46
+ readonly stage?: string;
47
+ }
48
+
49
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
50
+ typeof value === "object" && value !== null;
51
+
52
+ /**
53
+ * Refuse a stack or stage name that does not address exactly one scope.
54
+ *
55
+ * `Tree` splits a path on `/` and drops empty and `.` segments, so `""`,
56
+ * `"."`, a padded name and a name holding a separator all address something
57
+ * other than the one stage the caller named. A stage read from an
58
+ * environment variable carries a trailing newline often enough to matter.
59
+ */
60
+ const assertStageAddress = (field: string, value: string): void => {
61
+ if (value !== value.trim() || value === "") {
62
+ throw new Error(
63
+ `A state ${field} must be a non-empty name with no surrounding whitespace.`
64
+ );
65
+ }
66
+ if (value.includes("/") || value === "." || value === "..") {
67
+ throw new Error(
68
+ `A state ${field} must name one scope: '/', '.' and '..' are not allowed.`
69
+ );
70
+ }
71
+ };
72
+
73
+ /** Run one `Tree` effect over the caller's state layer. */
74
+ const overState = <A, E>(
75
+ state: StateService,
76
+ effect: Effect.Effect<A, E, State>
77
+ ): Promise<A> =>
78
+ Effect.runPromise(
79
+ Effect.provideService(effect, State, Effect.succeed(state))
80
+ );
81
+
82
+ /**
83
+ * Every `(stack, stage)` pair the state layer holds, or the subset a filter
84
+ * pins. Ordered by stack then stage.
85
+ *
86
+ * The pairs come from the store's own `listStacks` and `listStages`, so an
87
+ * empty result is the store reporting nothing, never a read this module
88
+ * could not make: a state layer that cannot be read fails instead.
89
+ */
90
+ export const inventoryStages = async (
91
+ state: StateService,
92
+ filter: StageFilter = {}
93
+ ): Promise<readonly StageTarget[]> => {
94
+ if (filter.stack !== undefined) {
95
+ assertStageAddress("stack", filter.stack);
96
+ }
97
+ if (filter.stage !== undefined) {
98
+ assertStageAddress("stage", filter.stage);
99
+ }
100
+ const pairs = await overState(state, allStages(filter));
101
+ return pairs.map(({ stack, stage }) => ({ stack, stage }));
102
+ };
103
+
104
+ /**
105
+ * The persisted-state document for one stage, as `parseStateSnapshot` reads
106
+ * it: `{ resources: [{ stack, stage, fqn, state }] }`, ordered by fqn.
107
+ *
108
+ * The read is the one `runAlchemyLifecycle` already makes — the atomic stage
109
+ * view, then each listed resource record — so a caller holding the document
110
+ * and a caller holding the lifecycle see the same records. A listed resource
111
+ * with no readable record fails the read; it is never left out, because a
112
+ * short document reads as a stage with less in it than it has.
113
+ *
114
+ * A stage the store does not hold reads as a document with no resource in
115
+ * it, the same reading the lifecycle takes for a first deploy. Only a stage
116
+ * the store cannot read fails. `deleteStageRows` answers an absent stage the
117
+ * other way, because it addresses a path rather than a stage view.
118
+ */
119
+ export const readStageSnapshot = async (
120
+ state: StageRecordStore,
121
+ target: StageTarget
122
+ ): Promise<string> => {
123
+ assertStageAddress("stack", target.stack);
124
+ assertStageAddress("stage", target.stage);
125
+ const scope = { stack: target.stack, stage: target.stage };
126
+ const view = await Effect.runPromise(state.snapshotStage(scope));
127
+ if (
128
+ !Array.isArray(view.resources) ||
129
+ view.resources.some((fqn) => typeof fqn !== "string" || fqn === "")
130
+ ) {
131
+ throw new Error(
132
+ `The state layer returned no resource list for ${target.stack} in ${target.stage}.`
133
+ );
134
+ }
135
+ const resources = await Promise.all(
136
+ [...view.resources].toSorted().map(async (fqn) => ({
137
+ ...scope,
138
+ fqn,
139
+ state: await Effect.runPromise(state.get({ ...scope, fqn })),
140
+ }))
141
+ );
142
+ if (resources.some((resource) => !isRecord(resource.state))) {
143
+ throw new Error(
144
+ `The state layer listed a resource it could not read for ${target.stack} in ${target.stage}.`
145
+ );
146
+ }
147
+ return JSON.stringify({ resources });
148
+ };
149
+
150
+ /**
151
+ * Remove every row the state layer holds for one stage. Other stages of the
152
+ * same stack keep every row.
153
+ *
154
+ * A stage the store does not hold is refused by the state layer rather than
155
+ * reported as removed, so a caller never reads a mistyped stage as a stage
156
+ * that was already empty.
157
+ */
158
+ export const deleteStageRows = async (
159
+ state: StateService,
160
+ target: StageTarget
161
+ ): Promise<void> => {
162
+ assertStageAddress("stack", target.stack);
163
+ assertStageAddress("stage", target.stage);
164
+ await overState(
165
+ state,
166
+ deleteState({ path: `${target.stack}/${target.stage}`, recursive: true })
167
+ );
168
+ };
@@ -0,0 +1,264 @@
1
+ /**
2
+ * The url-implies-auth invariant: a Worker the internet can reach declares how
3
+ * it is authenticated (#994).
4
+ *
5
+ * A stack reaches production one Worker at a time, and the cheapest way to
6
+ * publish an unauthenticated admin surface is to add `workersDev: true`, a
7
+ * `domain`, or a route to a Worker that never had one. The Worker still works, nothing
8
+ * fails, and the only record of the decision is a diff nobody re-read. This
9
+ * check reads the evaluated graph instead and demands that every publicly
10
+ * reachable Worker names its guard.
11
+ *
12
+ * What counts as a guard is the project's call, not this module's. Patronage
13
+ * gates on Cloudflare Access and on a secrets-store token whose binding name
14
+ * the project chooses; another project spells both differently. So the caller
15
+ * supplies the binding-name pattern and the allowlist, and this module carries
16
+ * no Patronage names.
17
+ *
18
+ * The three declarations that publish a Worker at beta.76 are `workersDev`, a
19
+ * `domain`, and a non-empty `routes` list. A route is a hostname pattern on a
20
+ * zone the account owns, so it is as public as a domain is.
21
+ *
22
+ * The invariant reads what the stack **declares**. Alchemy's own default for
23
+ * `workersDev` is on, so a Worker that declares no `workersDev`, no `domain`,
24
+ * and no `routes` still gets a `workers.dev` URL — and this check leaves it alone,
25
+ * because a rule inferred from a default would fire on every Worker in every
26
+ * stack and be waived everywhere within a week. A project that wants the
27
+ * default stated declares `workersDev: false` on the Workers that are private.
28
+ */
29
+
30
+ import type { EvaluatedGraph, EvaluatedResource } from "./evaluate-stack.ts";
31
+
32
+ /** The Alchemy resource type a Cloudflare Worker plans as, at beta.76. */
33
+ const WORKER_TYPE = "Cloudflare.Worker";
34
+
35
+ /** The Alchemy resource type a Cloudflare Access application plans as, at beta.76. */
36
+ const ACCESS_APPLICATION_TYPE = "Cloudflare.Access.Application";
37
+
38
+ /** One Worker the project has decided may stay reachable without a declared guard. */
39
+ export interface UrlImpliesAuthAllowance {
40
+ /** The Worker's logical id, as the graph reports it. */
41
+ readonly worker: string;
42
+ /** Why this Worker is public. An empty reason is not an answer. */
43
+ readonly reason: string;
44
+ }
45
+
46
+ /**
47
+ * Recognises the binding name a project's auth secret carries. A `RegExp` is
48
+ * tested against the binding name; a predicate is called with it.
49
+ */
50
+ export type AuthBindingNameMatcher = RegExp | ((name: string) => boolean);
51
+
52
+ export interface AssertUrlImpliesAuthOptions {
53
+ /** The `secrets_store_secret` binding names this project accepts as auth. */
54
+ readonly authBindingName: AuthBindingNameMatcher;
55
+ /** Workers exempted by a written decision. Every entry needs a reason. */
56
+ readonly allowlist?: readonly UrlImpliesAuthAllowance[];
57
+ }
58
+
59
+ /** Why one Worker failed the invariant. */
60
+ export type UrlImpliesAuthViolationReason =
61
+ /** The Worker is reachable and the graph shows no guard and no allowance. */
62
+ | "unauthenticated"
63
+ /** An allowlist entry names the Worker but states no reason. */
64
+ | "allowance-without-reason";
65
+
66
+ export interface UrlImpliesAuthViolation {
67
+ readonly worker: string;
68
+ readonly reason: UrlImpliesAuthViolationReason;
69
+ }
70
+
71
+ /** Every offending Worker in one throw, so a stack is fixed in one pass. */
72
+ export class UrlImpliesAuthError extends Error {
73
+ readonly violations: readonly UrlImpliesAuthViolation[];
74
+
75
+ constructor(violations: readonly UrlImpliesAuthViolation[]) {
76
+ const described = violations
77
+ .map(({ reason, worker }) =>
78
+ reason === "allowance-without-reason"
79
+ ? `${worker} (allowlisted with an empty reason)`
80
+ : `${worker} (no auth binding, no Access application, no allowance)`
81
+ )
82
+ .join(", ");
83
+ super(
84
+ `${violations.length} publicly reachable Worker declares no authentication: ${described}`
85
+ );
86
+ this.name = "UrlImpliesAuthError";
87
+ this.violations = violations;
88
+ }
89
+ }
90
+
91
+ /** `workersDev` is a boolean or a config object; both spellings can be off. */
92
+ const workersDevReachable = (workersDev: unknown): boolean => {
93
+ if (typeof workersDev === "boolean") {
94
+ return workersDev;
95
+ }
96
+ if (typeof workersDev !== "object" || workersDev === null) {
97
+ // `undefined` included: an undeclared prop is out of scope by design.
98
+ return false;
99
+ }
100
+ // A version preview URL is a public URL too, so only turning both off is
101
+ // private. Each flag defaults to on, so an absent one stays reachable.
102
+ const { enabled, previewsEnabled } = workersDev as Record<string, unknown>;
103
+ return enabled !== false || previewsEnabled !== false;
104
+ };
105
+
106
+ /** `domain` is a hostname, a config object with a `name`, or `null` to detach. */
107
+ const domainReachable = (domain: unknown): boolean => {
108
+ if (typeof domain === "string") {
109
+ return domain.trim().length > 0;
110
+ }
111
+ if (typeof domain !== "object" || domain === null) {
112
+ return false;
113
+ }
114
+ const { name } = domain as Record<string, unknown>;
115
+ return typeof name === "string" && name.trim().length > 0;
116
+ };
117
+
118
+ /** `routes` is a list of zone patterns. Any entry publishes the Worker. */
119
+ const routesReachable = (routes: unknown): boolean =>
120
+ Array.isArray(routes) && routes.length > 0;
121
+
122
+ /** The Worker's own `access` prop: a shared application, or a dedicated one. */
123
+ const enrollsInAccess = (access: unknown): boolean =>
124
+ access !== undefined && access !== null;
125
+
126
+ /** Is this Worker reachable from the internet by what the stack declares? */
127
+ const publiclyReachable = ({ props }: EvaluatedResource): boolean =>
128
+ workersDevReachable(props.workersDev) ||
129
+ domainReachable(props.domain) ||
130
+ routesReachable(props.routes);
131
+
132
+ /**
133
+ * Test a pattern without carrying state between Workers.
134
+ *
135
+ * A `RegExp` with `g` or `y` advances `lastIndex` on every match, so the same
136
+ * pattern answers "yes" for the first Worker and "no" for the second Worker
137
+ * with the same binding name. A guard that alternates is worse than one that
138
+ * always refuses, so a flagged pattern is tested through a fresh copy whose
139
+ * `lastIndex` starts at zero. The copy carries the complete flags: `y`
140
+ * anchors the match at `lastIndex`, so dropping it would let `/TOKEN/y`
141
+ * credit a binding named `X_TOKEN` that the caller's pattern rejects. The
142
+ * caller's own `RegExp` is never written to, so a frozen one still works.
143
+ * Same isolation `stage-policy` already applies to stage names.
144
+ */
145
+ const statelessTest = (pattern: RegExp, name: string): boolean =>
146
+ pattern.global || pattern.sticky
147
+ ? new RegExp(pattern.source, pattern.flags).test(name)
148
+ : pattern.test(name);
149
+
150
+ const matchesAuthBindingName = (
151
+ matcher: AuthBindingNameMatcher,
152
+ name: string
153
+ ): boolean =>
154
+ matcher instanceof RegExp ? statelessTest(matcher, name) : matcher(name);
155
+
156
+ /**
157
+ * The Workers a Cloudflare Access application gates in production.
158
+ *
159
+ * A Worker enrolled through its own `access` prop is read from the Worker
160
+ * instead — Alchemy pushes that enrollment onto the application at deploy
161
+ * time, so the application's planned props never name it. What is left is an
162
+ * application that declares its own `destinations`: `all_workers` covers the
163
+ * whole account, and a `worker` destination covers the Workers this
164
+ * application references. The graph resolves those references per prop, so
165
+ * only the ids the application's own `destinations` prop names are credited:
166
+ * a Worker some other prop happens to mention is not gated by this
167
+ * application.
168
+ *
169
+ * Within `destinations` the graph resolves a destination's `workerId` to a
170
+ * logical id but not to the destination that holds it, so an application that
171
+ * also declares a `preview_worker` destination is credited with nothing: its
172
+ * production and preview references are indistinguishable here, and crediting
173
+ * a preview-only reference would pass an open Worker.
174
+ */
175
+ const accessProtectedWorkers = (
176
+ resources: readonly EvaluatedResource[]
177
+ ): { accountWide: boolean; workers: ReadonlySet<string> } => {
178
+ const workers = new Set<string>();
179
+ let accountWide = false;
180
+
181
+ for (const resource of resources) {
182
+ if (resource.type !== ACCESS_APPLICATION_TYPE) {
183
+ continue;
184
+ }
185
+ const destinations = Array.isArray(resource.props.destinations)
186
+ ? (resource.props.destinations as readonly unknown[])
187
+ : [];
188
+ const types = new Set(
189
+ destinations.map((destination) =>
190
+ typeof destination === "object" && destination !== null
191
+ ? (destination as Record<string, unknown>).type
192
+ : undefined
193
+ )
194
+ );
195
+ if (types.has("all_workers")) {
196
+ accountWide = true;
197
+ }
198
+ if (types.has("worker") && !types.has("preview_worker")) {
199
+ for (const id of resource.upstreamByProp.destinations ?? []) {
200
+ workers.add(id);
201
+ }
202
+ }
203
+ }
204
+
205
+ return { accountWide, workers };
206
+ };
207
+
208
+ /**
209
+ * Proves every publicly reachable Worker in the graph declares an
210
+ * authentication mechanism.
211
+ *
212
+ * A Worker passes when it enrolls in Cloudflare Access (its own `access`
213
+ * prop, or an Access application that declares a destination for it), when it
214
+ * carries a `secrets_store_secret` binding whose name the caller's matcher
215
+ * accepts, or when the allowlist names it with a reason. Otherwise it is a
216
+ * violation, and every violation in the graph is reported in one
217
+ * `UrlImpliesAuthError`.
218
+ */
219
+ export const assertUrlImpliesAuth = (
220
+ graph: EvaluatedGraph,
221
+ { allowlist = [], authBindingName }: AssertUrlImpliesAuthOptions
222
+ ): void => {
223
+ const allowed = new Map(
224
+ allowlist.map(({ reason, worker }) => [worker, reason])
225
+ );
226
+ const access = accessProtectedWorkers(graph.resources);
227
+ const violations: UrlImpliesAuthViolation[] = [];
228
+
229
+ for (const resource of graph.resources) {
230
+ if (resource.type !== WORKER_TYPE || !publiclyReachable(resource)) {
231
+ continue;
232
+ }
233
+ if (allowed.has(resource.id)) {
234
+ // An allowance with no reason is a Worker nobody decided about, so it
235
+ // fails louder than the bare Worker would: the entry claims a decision
236
+ // that was never made.
237
+ if (allowed.get(resource.id)?.trim()) {
238
+ continue;
239
+ }
240
+ violations.push({
241
+ reason: "allowance-without-reason",
242
+ worker: resource.id,
243
+ });
244
+ continue;
245
+ }
246
+ const guarded =
247
+ enrollsInAccess(resource.props.access) ||
248
+ access.accountWide ||
249
+ access.workers.has(resource.id) ||
250
+ graph.bindings.some(
251
+ (binding) =>
252
+ binding.worker === resource.id &&
253
+ binding.type === "secrets_store_secret" &&
254
+ matchesAuthBindingName(authBindingName, binding.name)
255
+ );
256
+ if (!guarded) {
257
+ violations.push({ reason: "unauthenticated", worker: resource.id });
258
+ }
259
+ }
260
+
261
+ if (violations.length > 0) {
262
+ throw new UrlImpliesAuthError(violations);
263
+ }
264
+ };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The Alchemy fleet baseline (#985, #993). Every factory project that
3
+ * imports `@patronage/factory-ci/alchemy` pins `alchemy` and `effect` to
4
+ * these exact versions. The pair moves together, in the same lockstep
5
+ * release that bumps this constant.
6
+ *
7
+ * This module is a plain constant: it imports neither `alchemy` nor
8
+ * `effect`, so it ships from the root entry, not the `./alchemy` subpath.
9
+ */
10
+ export const ALCHEMY_BASELINE = {
11
+ alchemy: "2.0.0-beta.77",
12
+ effect: "4.0.0-rc.112",
13
+ } as const;
14
+
15
+ /**
16
+ * The slice of a consumer's `package.json` that carries the pins this
17
+ * baseline checks. Only `dependencies` and `devDependencies` are read —
18
+ * `peerDependencies` is deliberately a range, not a pin (ADR 0031), so it is
19
+ * never compared against the exact baseline.
20
+ */
21
+ export interface AlchemyBaselinePackageJson {
22
+ readonly dependencies?: Record<string, string>;
23
+ readonly devDependencies?: Record<string, string>;
24
+ }
25
+
26
+ export interface AssertAlchemyBaselineInput {
27
+ readonly packageJson: AlchemyBaselinePackageJson;
28
+ }
29
+
30
+ const BASELINE_PACKAGE_NAMES = Object.keys(
31
+ ALCHEMY_BASELINE
32
+ ) as (keyof typeof ALCHEMY_BASELINE)[];
33
+
34
+ /**
35
+ * Fails when the consumer's `alchemy` or `effect` pin differs from
36
+ * {@link ALCHEMY_BASELINE}, or when only one of the pair is present.
37
+ * Alchemy peers on Effect, so an unpinned auto-installed Effect can drift
38
+ * outside the baseline while a lone `alchemy` pin would otherwise pass.
39
+ * Both packages remaining absent is not drift — they are optional peers of
40
+ * the `./alchemy` subpath, so a consumer that never touches it carries
41
+ * neither.
42
+ *
43
+ * Reads only the `packageJson` object it is handed; it never walks the
44
+ * filesystem.
45
+ */
46
+ export const assertAlchemyBaseline = ({
47
+ packageJson,
48
+ }: AssertAlchemyBaselineInput): void => {
49
+ const drifted: string[] = [];
50
+ const pinOf = (name: keyof typeof ALCHEMY_BASELINE): string | undefined =>
51
+ packageJson.dependencies?.[name] ?? packageJson.devDependencies?.[name];
52
+ const pairPresent = BASELINE_PACKAGE_NAMES.some(
53
+ (name) => pinOf(name) !== undefined
54
+ );
55
+
56
+ for (const name of BASELINE_PACKAGE_NAMES) {
57
+ const pinned = pinOf(name);
58
+ const baseline = ALCHEMY_BASELINE[name];
59
+ if (pinned === undefined) {
60
+ if (pairPresent) {
61
+ drifted.push(`missing ${name} (baseline: ${name}@${baseline})`);
62
+ }
63
+ continue;
64
+ }
65
+ if (pinned !== baseline) {
66
+ drifted.push(`${name}@${pinned} (baseline: ${name}@${baseline})`);
67
+ }
68
+ }
69
+
70
+ if (drifted.length > 0) {
71
+ throw new Error(
72
+ `Alchemy fleet baseline drift: ${drifted.join(", ")}. Bump to match ALCHEMY_BASELINE in @patronage/factory-ci, or wait for the next lockstep release.`
73
+ );
74
+ }
75
+ };
@@ -151,6 +151,11 @@ export const bundleAlchemyEntry = async (
151
151
  entryPoints: [path.resolve(root, options.entry)],
152
152
  external: ALCHEMY_EXTERNALS,
153
153
  format: "esm",
154
+ // esbuild writes its own diagnostics — resolver paths and source
155
+ // excerpts — straight to the inherited stderr descriptor before the
156
+ // promise rejects. Silenced at the source: the rejection is the signal,
157
+ // and the caller decides what an operator sees.
158
+ logLevel: "silent",
154
159
  metafile: true,
155
160
  outfile,
156
161
  packages: options.packages ?? "external",
@@ -0,0 +1,110 @@
1
+ import type { WorkflowStep } from "./factory-workflow.ts";
2
+ import { impactDemandConditions } from "./impact-demand-condition.ts";
3
+ import { productionImpactTargetOutput } from "./production-impact-workflow.ts";
4
+ import { assertRunnableCli } from "./runnable-cli.ts";
5
+
6
+ export const FACTORY_CANDIDATE_IMPACT_STEP_ID = "candidate_impact";
7
+ export const FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT = "decision";
8
+ export const FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT = "basis";
9
+ export const FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT = "inert_paths";
10
+ export const FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT =
11
+ "unsubscribed_paths";
12
+
13
+ const shellQuote = (value: string): string =>
14
+ `'${value.replaceAll("'", `'"'"'`)}'`;
15
+
16
+ export interface FactoryCandidateImpactWorkflowOptions {
17
+ readonly base?: string;
18
+ readonly cli?: string;
19
+ readonly head?: string;
20
+ readonly profilePath?: string;
21
+ readonly targets: readonly string[];
22
+ }
23
+
24
+ export interface FactoryCandidateImpactWorkflow {
25
+ /** Outputs for a caller-owned decision job that subsequent jobs may consume. */
26
+ readonly decisionJobOutputs: Readonly<Record<string, string>>;
27
+ readonly decisionStep: WorkflowStep;
28
+ /**
29
+ * A fail-open cross-job condition: only an explicit usable withdrawal skips
30
+ * work. The decision job id is required.
31
+ */
32
+ readonly demandedIf: (targetName: string, decisionJob: string) => string;
33
+ /** The same fail-open condition for a step in the decision job. */
34
+ readonly demandedIfAtStep: (targetName: string) => string;
35
+ readonly targetOutputs: Readonly<Record<string, string>>;
36
+ }
37
+
38
+ /**
39
+ * Generate the factory-owned candidate routing seam for a consumer
40
+ * pull-request workflow (#741). The decision step calls
41
+ * `psf candidate:impact` with the pull request's exact base/head commits, so
42
+ * the canonical profile impact declarations and dependency graph route the
43
+ * run — never a second path matcher. Consumers retain jobs, surface names,
44
+ * runners, commands, and credentials; this artifact supplies only the
45
+ * decision step and per-target withdrawal conditions. Target output keys are
46
+ * the same stable contract the production decision seam writes.
47
+ *
48
+ * The decision checkout must have the exact head commit checked out and the
49
+ * base commit reachable (`fetchDepth: 0`, `ref` = the head SHA); anything
50
+ * else refuses withdrawal and keeps every target demanded.
51
+ */
52
+ export const factoryCandidateImpactWorkflow = (
53
+ options: FactoryCandidateImpactWorkflowOptions
54
+ ): FactoryCandidateImpactWorkflow => {
55
+ const targetOutputs = Object.fromEntries(
56
+ options.targets.map((target) => [
57
+ target,
58
+ productionImpactTargetOutput(target),
59
+ ])
60
+ );
61
+ if (new Set(Object.values(targetOutputs)).size !== options.targets.length) {
62
+ throw new Error(
63
+ "Impact target names must map to distinct GitHub output keys."
64
+ );
65
+ }
66
+
67
+ const base = options.base ?? `\${{ github.event.pull_request.base.sha }}`;
68
+ const head = options.head ?? `\${{ github.event.pull_request.head.sha }}`;
69
+ const cli = options.cli ?? "pnpm exec psf";
70
+ assertRunnableCli("cli", cli);
71
+ const profile = options.profilePath
72
+ ? ` --profile ${shellQuote(options.profilePath)}`
73
+ : "";
74
+ const decisionStep: WorkflowStep = {
75
+ continueOnError: true,
76
+ env: {
77
+ FACTORY_BASE_SHA: base,
78
+ FACTORY_HEAD_SHA: head,
79
+ },
80
+ id: FACTORY_CANDIDATE_IMPACT_STEP_ID,
81
+ name: "Classify candidate impact",
82
+ run: `${cli} candidate:impact --base "$FACTORY_BASE_SHA" --head "$FACTORY_HEAD_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${profile}`,
83
+ };
84
+
85
+ const conditions = impactDemandConditions({
86
+ decisionOutput: FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT,
87
+ label: "candidate",
88
+ stepId: FACTORY_CANDIDATE_IMPACT_STEP_ID,
89
+ targetOutputs,
90
+ });
91
+
92
+ return Object.freeze({
93
+ decisionJobOutputs: Object.freeze({
94
+ basis: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT} }}`,
95
+ decision: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT} }}`,
96
+ inert_paths: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT} }}`,
97
+ unsubscribed_paths: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT} }}`,
98
+ ...Object.fromEntries(
99
+ Object.values(targetOutputs).map((output) => [
100
+ output,
101
+ `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${output} }}`,
102
+ ])
103
+ ),
104
+ }),
105
+ decisionStep: Object.freeze(decisionStep),
106
+ demandedIf: conditions.demandedIf,
107
+ demandedIfAtStep: conditions.demandedIfAtStep,
108
+ targetOutputs: Object.freeze(targetOutputs),
109
+ });
110
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Pull-request events that can create or refresh a Factory candidate run.
3
+ *
4
+ * GitHub's draft boolean remains the lifecycle authority: these triggers make
5
+ * a run visible, while `factoryCandidateOrPushCondition` keeps substantive
6
+ * jobs idle until the pull request is a candidate.
7
+ */
8
+ export const FACTORY_CANDIDATE_PULL_REQUEST_TYPES = Object.freeze([
9
+ "opened",
10
+ "synchronize",
11
+ "reopened",
12
+ "ready_for_review",
13
+ ] as const);
14
+
15
+ /**
16
+ * Build a GitHub Actions job condition for candidate PRs and merge-target
17
+ * pushes. The caller owns triggers, jobs, runners, permissions, and topology.
18
+ */
19
+ export const factoryCandidateOrPushCondition = (
20
+ candidateCondition?: string
21
+ ): string => {
22
+ const candidate = [
23
+ "github.event_name == 'pull_request'",
24
+ "github.event.pull_request.draft != true",
25
+ ...(candidateCondition ? [candidateCondition] : []),
26
+ ].join(" && ");
27
+
28
+ return ["github.event_name == 'push'", `(${candidate})`].join(" || ");
29
+ };