@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.
- package/README.md +712 -10
- package/dist/.build-fingerprint.json +3 -0
- package/dist/alchemy/index.d.ts +1174 -0
- package/dist/alchemy/index.js +2142 -0
- package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
- package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
- package/dist/execute-alchemy-entry-CZ7Knz4q.js +160 -0
- package/dist/index.d.ts +1205 -87
- package/dist/index.js +2752 -317
- package/package.json +28 -10
- package/src/actions.ts +13 -0
- package/src/alchemy/child-diagnostics.ts +148 -0
- package/src/alchemy/credential-preflight.ts +428 -0
- package/src/alchemy/destroy-postcondition.ts +103 -0
- package/src/alchemy/evaluate-stack.ts +153 -0
- package/src/alchemy/first-deploy-authorization.ts +194 -0
- package/src/alchemy/index.ts +144 -0
- package/src/alchemy/lifecycle-failure.ts +174 -0
- package/src/alchemy/lifecycle.ts +1330 -0
- package/src/alchemy/local-emulation.ts +89 -0
- package/src/alchemy/plan-effects.ts +510 -0
- package/src/alchemy/retained-identity.ts +248 -0
- package/src/alchemy/secret-name-policy.ts +96 -0
- package/src/alchemy/stage-policy.ts +269 -0
- package/src/alchemy/state-tree.ts +168 -0
- package/src/alchemy/url-implies-auth.ts +264 -0
- package/src/alchemy-baseline.ts +75 -0
- package/src/bundle-alchemy-entry.ts +5 -0
- package/src/candidate-impact-workflow.ts +110 -0
- package/src/candidate-lifecycle.ts +29 -0
- package/src/cursor-oidc.ts +33 -0
- package/src/execute-alchemy-entry.ts +128 -8
- package/src/factory-workflow.ts +83 -40
- package/src/github-app-token.ts +92 -18
- package/src/github-transport.ts +186 -0
- package/src/impact-demand-condition.ts +67 -0
- package/src/index.ts +174 -0
- package/src/lifecycle-contract-lane.ts +113 -0
- package/src/merge-freeze-job.ts +253 -0
- package/src/pinned-action.ts +30 -0
- package/src/pr-status-hud-workflow.ts +96 -0
- package/src/preview-cleanup-topology.ts +115 -0
- package/src/preview-proof-inventory.ts +1092 -0
- package/src/preview-proof-lifecycle.ts +328 -0
- package/src/preview-receipt-workflow.ts +83 -0
- package/src/production-impact-workflow.ts +181 -0
- package/src/proof-reuse-gate.ts +223 -48
- package/src/proof-reuse-presentation.ts +131 -0
- package/src/push-identity-workflow.ts +463 -0
- package/src/runnable-cli.ts +27 -0
- package/src/verify-runner-policy.ts +290 -0
- package/src/vitest-profile-reader.test.ts +208 -0
- package/src/vitest-profile-reader.ts +225 -0
- package/src/vitest-profile.ts +631 -0
package/README.md
CHANGED
|
@@ -6,13 +6,15 @@ The CI and deploy building blocks that already repeat across Patronage **factory
|
|
|
6
6
|
pnpm add -E @patronage/factory-ci
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
It is a **pure library**. There is no `bin`: anything invocable belongs to `psf`.
|
|
9
|
+
It is a **pure library**. There is no `bin`: anything invocable belongs to `psf`. `esbuild` is its own dependency, which is what lets consumers delete their local arrangements for finding one.
|
|
10
|
+
|
|
11
|
+
`alchemy` and `effect` are **optional peer dependencies** (ADR 0031). A peer resolves from the consumer's own installation, so this package still cannot pull a second copy of either into a consumer's graph — and a second copy is the thing that breaks both silently, because Alchemy's resource registry and Effect's service tags are identity-sensitive. The package root imports neither; every Alchemy-importing helper ships from the `@patronage/factory-ci/alchemy` subpath. A consumer that never imports that subpath installs neither package and sees no warning.
|
|
10
12
|
|
|
11
13
|
## What it is for
|
|
12
14
|
|
|
13
15
|
Three repositories independently built the same scaffolding and then drifted: three wordings of the same setup block, the same `@v4` action tags pinned to different commits because they were generated months apart, two esbuild pre-bundles, two Alchemy CLI wrappers, and one disposable-stage grammar invented twice.
|
|
14
16
|
|
|
15
|
-
The admission rule is **
|
|
17
|
+
The admission rule is **experiment, prove, fan out** (ADR 0036). A mechanism starts as an experiment in one project. When the experiment proves it and the intent is fleet-wide, it moves into the factory: into this package, or into `psf` when it is invocable. Then it fans out to the other projects. A single consumer is a risk to record, not a gate. The public surface is made of deep modules, not a workflow framework.
|
|
16
18
|
|
|
17
19
|
## Exports
|
|
18
20
|
|
|
@@ -20,7 +22,10 @@ The admission rule is **upstream on repetition**: nothing enters this package un
|
|
|
20
22
|
|
|
21
23
|
```ts
|
|
22
24
|
import {
|
|
25
|
+
FACTORY_CANDIDATE_PULL_REQUEST_TYPES,
|
|
26
|
+
factoryProductionImpactWorkflow,
|
|
23
27
|
factoryWorkflow,
|
|
28
|
+
factoryCandidateOrPushCondition,
|
|
24
29
|
NODE_PNPM_ACTION_FAMILY_NODE24,
|
|
25
30
|
} from "@patronage/factory-ci";
|
|
26
31
|
```
|
|
@@ -29,9 +34,34 @@ import {
|
|
|
29
34
|
|
|
30
35
|
- `actions`: the explicit Node/pnpm action family plus every workflow-specific action pin
|
|
31
36
|
- `setupSteps`: checkout → pnpm → Node → install, customizable by named role
|
|
37
|
+
- `setupStepsByRole`: the same steps keyed by stable role (`SetupStepRole`: `"checkout"`, `"setupPnpm"`, `"setupNode"`, `"install"`) instead of array position, so a caller never locates the checkout step by display name or asserts a fixed install-step count
|
|
32
38
|
- `writeOptions`: the provenance banner and `pinDeps: false`, ready to spread into gagen's `writeOrLint`
|
|
33
39
|
|
|
34
|
-
|
|
40
|
+
A consumer that needs its own checkout step (for example, one pinned to a pull request's head SHA) followed by the shared pnpm/Node/install sequence selects by role instead of destructuring `setupSteps`:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { setupStepsForRoles } from "@patronage/factory-ci";
|
|
44
|
+
|
|
45
|
+
const afterCheckout = setupStepsForRoles(verifyWorkflow, [
|
|
46
|
+
"setupPnpm",
|
|
47
|
+
"setupNode",
|
|
48
|
+
"install",
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
const steps = [
|
|
52
|
+
{
|
|
53
|
+
name: "Checkout (head SHA)",
|
|
54
|
+
uses: verifyWorkflow.actions.checkout.uses,
|
|
55
|
+
with: { ref },
|
|
56
|
+
},
|
|
57
|
+
...afterCheckout,
|
|
58
|
+
// job-specific steps
|
|
59
|
+
];
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
This selection is stable under a renamed step or an added supported role: `setupStepsForRoles` reads named roles from `setupStepsByRole`, never array shape.
|
|
63
|
+
|
|
64
|
+
Every action is validated as `owner/repo@<full sha>`, with its release tag kept separately. A complete `actionFamily` is required; there is no default that could silently move a consumer between action majors. `NODE_PNPM_ACTION_FAMILY_NODE24` is the canonical family whose checkout, Node setup, and pnpm setup actions all declare a Node 24 JavaScript runtime. Generated workflows read Node from `.nvmrc`. This repository pins 24.20.0.
|
|
35
65
|
|
|
36
66
|
```ts
|
|
37
67
|
const generated = factoryWorkflow({
|
|
@@ -47,6 +77,7 @@ const generated = factoryWorkflow({
|
|
|
47
77
|
regenerate: "pnpm workflows:generate",
|
|
48
78
|
},
|
|
49
79
|
setup: {
|
|
80
|
+
checkout: { fetchDepth: 0, ref: "${{ github.sha }}" },
|
|
50
81
|
setupNode: { cacheDependencyPath: "pnpm-lock.yaml" },
|
|
51
82
|
},
|
|
52
83
|
});
|
|
@@ -57,7 +88,264 @@ workflow({/* caller-owned jobs and topology */}).writeOrLint({
|
|
|
57
88
|
});
|
|
58
89
|
```
|
|
59
90
|
|
|
60
|
-
|
|
91
|
+
`factoryWorkflow()` still does not set `runsOn`. This package does not depend on gagen. Job ids, permissions, topology, and deploy policy stay with the caller. Verify runner kinds are this package's business. Name each job's kind (or an override with a non-empty why), pass `.label` into gagen `job()`, and hand the same table to `assertVerifyRunnerPolicy` next to `assertWorkflowShellParses`:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import {
|
|
95
|
+
assertVerifyRunnerPolicy,
|
|
96
|
+
assertWorkflowShellParses,
|
|
97
|
+
factoryVerifyRunner,
|
|
98
|
+
type FactoryVerifyRunner,
|
|
99
|
+
} from "@patronage/factory-ci";
|
|
100
|
+
|
|
101
|
+
type VerifyJobId = "changes" | "core";
|
|
102
|
+
|
|
103
|
+
const verifyRunners: Record<VerifyJobId, FactoryVerifyRunner> = {
|
|
104
|
+
changes: factoryVerifyRunner("rounding-tax"),
|
|
105
|
+
core: factoryVerifyRunner("sustained-compute"),
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const runsOnFor = (id: VerifyJobId) => verifyRunners[id].label;
|
|
109
|
+
|
|
110
|
+
const changes = job("changes", {
|
|
111
|
+
if: factoryCandidateOrPushCondition(),
|
|
112
|
+
runsOn: runsOnFor("changes"),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const core = job("core", {
|
|
116
|
+
if: factoryCandidateOrPushCondition("needs.changes.outputs.core == 'true'"),
|
|
117
|
+
runsOn: runsOnFor("core"),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const generated = workflow({ jobs: [changes, core] });
|
|
121
|
+
|
|
122
|
+
assertWorkflowShellParses(generated.toYamlString(), {
|
|
123
|
+
source: ".github/workflows/verify.ts",
|
|
124
|
+
});
|
|
125
|
+
assertVerifyRunnerPolicy(generated.toYamlString(), {
|
|
126
|
+
source: ".github/workflows/verify.ts",
|
|
127
|
+
jobs: verifyRunners,
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`sustained-compute` and `rounding-tax` both resolve to `depot-ubuntu-24.04`. They stay distinct so a short billed-rounding job cannot be confused with a long compute job in the table. `app-token` resolves to `ubuntu-latest`. `deploy-credentials` also resolves to `ubuntu-latest` and is refused inside `assertVerifyRunnerPolicy`, because a Verify workflow has no Cloudflare production secret. HQ deploy keeps a literal `ubuntu-latest` and never calls this assert.
|
|
132
|
+
|
|
133
|
+
Candidate lifecycle support follows the same boundary. Use `FACTORY_CANDIDATE_PULL_REQUEST_TYPES` for the pull-request trigger matrix and `factoryCandidateOrPushCondition()` on each substantive job. With an optional caller-owned path condition, the helper emits the GitHub expression that runs merge-target pushes unconditionally and runs pull-request work only when GitHub's draft boolean says the pull request is a Candidate. The runner label still comes from the kind table above.
|
|
134
|
+
|
|
135
|
+
Migration: upgrade `@patronage/factory-ci`, apply the shared trigger types and job condition in the TypeScript workflow source, then regenerate and commit the emitted YAML. Draft `opened` and `synchronize` events will stop running substantive Verify work. Promotion through `ready_for_review`, later non-draft Candidate events, and merge-target pushes continue to run their applicable battery. A skipped draft run is presentation, not proof.
|
|
136
|
+
|
|
137
|
+
Production impact support follows the same ownership line. A generated deploy workflow declares only its target names and consumes the returned decision step and fail-open `demandedIf(target, decisionJob)` expressions:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
const impact = factoryProductionImpactWorkflow({
|
|
141
|
+
targets: profile.impact?.targets.map(({ name }) => name) ?? [],
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const decide = job("impact", {
|
|
145
|
+
outputs: impact.decisionJobOutputs,
|
|
146
|
+
steps: [...setupSteps, impact.decisionStep],
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
const deployWebsite = job("deploy-website", {
|
|
150
|
+
if: impact.demandedIf("website", "impact"),
|
|
151
|
+
needs: [decide],
|
|
152
|
+
// consumer-owned runner, credentials, deploy commands, and convergence
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The generated decision step runs `psf production:impact --candidate "$FACTORY_CANDIDATE_SHA"` (the `candidate` option, default `github.sha`, plus `--stage` when the consumer passes one). The command resolves each target's demand from that target's last trusted successful deployment receipt to the candidate, never from the push's `before` and `after` commits. The step is `continue-on-error`, and every generated target condition keeps work demanded unless the command succeeded, reported a usable decision, and explicitly withdrew that target. Each deploy job declares `impact.permissions` and appends `impact.receiptSteps(target)` after its deploy and health steps: a success receipt (`--publish-receipt success --target <name> --candidate "$FACTORY_CANDIDATE_SHA"`), a bind step named for the new deployment id, and a failure receipt. Only a bound success receipt becomes the next baseline. The artifact with an empty target list generates no deploy jobs because job creation remains with the consumer. This package does not own target declarations, deploy topology, credentials, commands, health policy, or convergence/no-op proof.
|
|
157
|
+
|
|
158
|
+
The decision checkout must make the baseline commit reachable. Use `factoryWorkflow({ setup: { checkout: { fetchDepth: 0, ref: "${{ github.sha }}" } } })`; a shallow checkout is safe but deliberately refuses withdrawal because the baseline commit is unreadable.
|
|
159
|
+
|
|
160
|
+
When deployment begins from a successful `workflow_run` instead of the push event itself, carry that push identity through the typed artifact seam so the decision job checks out the triggering head and passes it as the candidate:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import {
|
|
164
|
+
factoryProductionImpactWorkflow,
|
|
165
|
+
factoryPushIdentityConsumer,
|
|
166
|
+
factoryPushIdentityProducer,
|
|
167
|
+
factoryWorkflow,
|
|
168
|
+
NODE_PNPM_ACTION_FAMILY_NODE24,
|
|
169
|
+
UPLOAD_ARTIFACT,
|
|
170
|
+
} from "@patronage/factory-ci";
|
|
171
|
+
|
|
172
|
+
const workflowArtifact = factoryWorkflow({
|
|
173
|
+
actionFamily: NODE_PNPM_ACTION_FAMILY_NODE24,
|
|
174
|
+
additionalActions: {
|
|
175
|
+
downloadArtifact: {
|
|
176
|
+
tag: "v5.0.0",
|
|
177
|
+
uses: "actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0",
|
|
178
|
+
},
|
|
179
|
+
uploadArtifact: UPLOAD_ARTIFACT,
|
|
180
|
+
},
|
|
181
|
+
generated: {
|
|
182
|
+
source: ".github/workflows/verify.ts",
|
|
183
|
+
regenerate: "pnpm workflows:generate",
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// At the end of the push-triggered Verify job:
|
|
188
|
+
const producer = factoryPushIdentityProducer({
|
|
189
|
+
if: "github.ref == 'refs/heads/main'",
|
|
190
|
+
uploadArtifact: workflowArtifact.actions.uploadArtifact,
|
|
191
|
+
});
|
|
192
|
+
const verifySteps = [...consumerOwnedVerifySteps, ...producer.steps];
|
|
193
|
+
|
|
194
|
+
// In a caller-owned workflow_run decision job:
|
|
195
|
+
const identity = factoryPushIdentityConsumer({
|
|
196
|
+
checkout: workflowArtifact.actions.checkout,
|
|
197
|
+
downloadArtifact: workflowArtifact.actions.downloadArtifact,
|
|
198
|
+
});
|
|
199
|
+
const impact = factoryProductionImpactWorkflow({
|
|
200
|
+
candidate: identity.outputs.after,
|
|
201
|
+
targets: profile.impact.targets.map(({ name }) => name),
|
|
202
|
+
});
|
|
203
|
+
const decision = {
|
|
204
|
+
outputs: { ...identity.outputs, ...impact.decisionJobOutputs },
|
|
205
|
+
permissions: identity.requiredPermissions,
|
|
206
|
+
steps: [
|
|
207
|
+
...identity.steps,
|
|
208
|
+
...consumerOwnedInstallSteps,
|
|
209
|
+
{ ...impact.decisionStep, if: identity.usableIf },
|
|
210
|
+
],
|
|
211
|
+
};
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
The producer records schema version, repository, string run ID, and the exact push-event `before` / `after` values, then uploads one run-named artifact. The consumer enumerates artifacts only on the triggering run in the current repository, requires that run to have been triggered by `push` and concluded successfully, requires exactly one bounded artifact, downloads it by artifact ID, checks out the triggering head with full history, and validates envelope, repository, run, head, commit reachability, and ancestry. Missing, duplicate, malformed, oversized, abbreviated, zero, unreachable, mismatched, or contradictory identity returns `disposition=refused`, empty commit outputs, a stable `reason`, a JSON `provenance` output, and a job-summary explanation. Run classification only under `identity.usableIf`; the existing `impact.demandedIf(...)` condition then keeps every target demanded on any transport or classification refusal.
|
|
215
|
+
|
|
216
|
+
The helper selects no action family or action version. Callers pass the explicit tagged pins already validated by their `factoryWorkflow()` artifact, keeping action-family and additional-action policy in the generated workflow source.
|
|
217
|
+
|
|
218
|
+
This is identity transport and validation only. The consumer still owns the `workflow_run` trigger and branch policy, job topology and runners, deploy credentials and environments, target declarations, commands, ordering, and convergence/no-op proof. None of those belong in the identity artifact or decision job.
|
|
219
|
+
|
|
220
|
+
Candidate pull-request routing follows the same ownership line through `factoryCandidateImpactWorkflow` (#741). A generated Verify workflow declares only its target names and consumes the returned decision step and fail-open `demandedIf(target, decisionJob)` expressions, so the profile's canonical impact declarations and dependency graph route the run instead of a repository-maintained path filter:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
const impact = factoryCandidateImpactWorkflow({
|
|
224
|
+
targets: profile.impact?.targets.map(({ name }) => name) ?? [],
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
const decide = job("impact", {
|
|
228
|
+
// The lifecycle contract applies to the decision job too: a draft pull
|
|
229
|
+
// request runs no checkout, install, or classification.
|
|
230
|
+
if: factoryCandidateOrPushCondition(),
|
|
231
|
+
outputs: impact.decisionJobOutputs,
|
|
232
|
+
steps: [...setupSteps, impact.decisionStep],
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
const core = job("core", {
|
|
236
|
+
// Wrap the impact condition in `factoryCandidateOrPushCondition` as well:
|
|
237
|
+
// a skipped decision job is not `success`, so promotion out of draft
|
|
238
|
+
// re-demands every routed target. Impact routing narrows candidate work;
|
|
239
|
+
// it never widens the lifecycle.
|
|
240
|
+
if: factoryCandidateOrPushCondition(impact.demandedIf("core", "impact")),
|
|
241
|
+
needs: [decide],
|
|
242
|
+
// consumer-owned runner, surface commands, and credentials
|
|
243
|
+
});
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
`demandedIf(target, decisionJob)` builds the cross-job condition. The decision job id is required, so a routed job cannot receive a same-job condition by accident. It emits `always()` so a failed decision job still demands work, and it checks only the decision job's result. Declare the decision job as the routed job's only `needs`. A routed job with more prerequisites must add its own `needs.<job>.result == 'success'` clauses, because `always()` suppresses GitHub's implicit success gating for every dependency. `demandedIfAtStep(target)` builds the same fail-open condition for a step inside the decision job, where the decision is read from `steps.<stepId>`. The production decision seam has the same contract.
|
|
247
|
+
|
|
248
|
+
Trust boundary: candidate routing is a cost control inside the pull request's own CI, not a merge-security control. A `pull_request` run executes the PR's workflow file and install scripts, so a hostile PR can already shape any of its own job outputs — with or without this seam, exactly as with a repository path filter. Merge admission never trusts these outputs: merge-target push verification stays full and unrouted, and the factory proof chain binds to commits, not to job conditions.
|
|
249
|
+
|
|
250
|
+
The step calls `psf candidate:impact` with the pull request's exact `base` and `head` commits (`github.event.pull_request.base.sha` / `head.sha` by default) and classifies the merge-base-to-head delta. It is `continue-on-error`, and every generated target condition keeps work demanded unless the command succeeded, reported a usable decision, and explicitly withdrew that target — unreadable identity, malformed or unsupported graph data, and classifier refusal all route to full demand. The decision checkout must check out the exact head commit with full history (`fetchDepth: 0`, `ref` = the head SHA); the default merge-ref checkout refuses withdrawal because the head is not `HEAD`. Surface job names, runners, commands, and credentials stay with the consumer, and `factoryProductionImpactWorkflow` keeps its merge-push contract unchanged.
|
|
251
|
+
|
|
252
|
+
The non-credentialed lifecycle-contract lane follows the same ownership line through `factoryLifecycleContractLane` (#765). Presence is a profile declaration (`lifecycleContract` in `software-factory.profile.json`); this package never loads the profile. Pass the parsed object, or omit it, and include or skip the returned job:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
const lane = factoryLifecycleContractLane(profile.lifecycleContract);
|
|
256
|
+
|
|
257
|
+
const jobs = [
|
|
258
|
+
core,
|
|
259
|
+
...(lane
|
|
260
|
+
? [
|
|
261
|
+
job(lane.jobId, {
|
|
262
|
+
name: lane.jobName,
|
|
263
|
+
permissions: { contents: "read" },
|
|
264
|
+
steps: [...setupSteps, ...lane.steps],
|
|
265
|
+
}),
|
|
266
|
+
]
|
|
267
|
+
: []),
|
|
268
|
+
];
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
When declared, the helper returns job id `factory-contracts`, display name `Factory / Alchemy Contracts` (overridable), a `run:` step that is exactly the declared package-script command, and an `always()` evidence summary that states what the lane proves and that it does not prove live deploy, D1, smoke, convergence, or cleanup. When omitted, the helper returns `undefined` and the caller emits no such job.
|
|
272
|
+
|
|
273
|
+
**Command contract.** Consumers expose a root package script and declare its invocation in the profile. The conventional name is `test:factory`:
|
|
274
|
+
|
|
275
|
+
```json
|
|
276
|
+
{
|
|
277
|
+
"lifecycleContract": {
|
|
278
|
+
"command": "pnpm test:factory"
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Hosted CI runs that package script only. The allowed grammar is `pnpm run <script>` (and the npm/yarn/bun `run` equivalents) or a shorthand whose script name contains `:` (`pnpm test:factory`). Optional pnpm `--filter <pkg>` may precede either form. A bare manager verb (`pnpm create`, `npm init`) is not a script invocation. Shell operators, GitHub expressions, `secrets.`, Cloudflare/Alchemy credential env, extra flags, and direct Vitest are refused. The generated job and steps carry no `secrets.`, no Cloudflare or Alchemy password env, and no GitHub `environment:` that would inject deploy credentials. The lane must stay green in fork and no-secret contexts. Setup, runners, job `if:` conditions, and topology stay with the caller. The contract suites themselves stay consumer-owned.
|
|
284
|
+
|
|
285
|
+
The preview-cleanup residue audit follows the same ownership line through `factoryPreviewCleanupTopology` (#764). Callers pass the stack names and the whole-stage audit command; this package never loads a profile and never decides what counts as residue. Destroy _steps_ stay consumer-owned. The helper returns one destroy job id per stack and exactly one audit job whose `needs` lists every destroy:
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
const topology = factoryPreviewCleanupTopology({
|
|
289
|
+
stacks: ["website", "loop"],
|
|
290
|
+
audit: { command: "assert-stage-absent" },
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
const jobs = [
|
|
294
|
+
...topology.destroyJobs.map((destroy) =>
|
|
295
|
+
job(destroy.jobId, {
|
|
296
|
+
name: `Destroy ${destroy.stack}`,
|
|
297
|
+
steps: [...setupSteps, consumerDestroy(destroy.stack)],
|
|
298
|
+
})
|
|
299
|
+
),
|
|
300
|
+
job(topology.auditJob.jobId, {
|
|
301
|
+
name: topology.auditJob.jobName,
|
|
302
|
+
if: topology.auditJob.if,
|
|
303
|
+
needs: topology.auditJob.needs,
|
|
304
|
+
steps: [...setupSteps, ...topology.auditJob.steps],
|
|
305
|
+
}),
|
|
306
|
+
];
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
The audit job is `always()` so a failed destroy still runs the stage-wide check. It does not receive a stack name or path filter — per-stack audit filters are rejected because they trade away the whole-stage guarantee (paitronage#1143). `previewCleanupDestroyJobId(stack)` is the same id mapping callers can use when they assemble destroy jobs by hand.
|
|
310
|
+
|
|
311
|
+
### Merge-freeze writer job
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
import {
|
|
315
|
+
factoryMergeFreezeJob,
|
|
316
|
+
factoryVerifyRunner,
|
|
317
|
+
} from "@patronage/factory-ci";
|
|
318
|
+
|
|
319
|
+
const freeze = factoryMergeFreezeJob({
|
|
320
|
+
createGithubAppToken: workflowArtifact.actions.createGithubAppToken,
|
|
321
|
+
needs: [changes, core, docs],
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
const jobs = [
|
|
325
|
+
changes,
|
|
326
|
+
core,
|
|
327
|
+
docs,
|
|
328
|
+
job(freeze.jobId, {
|
|
329
|
+
name: freeze.jobName,
|
|
330
|
+
needs: freeze.needs,
|
|
331
|
+
if: freeze.if,
|
|
332
|
+
runsOn: factoryVerifyRunner("app-token").label,
|
|
333
|
+
permissions: freeze.permissions,
|
|
334
|
+
timeoutMinutes: 10,
|
|
335
|
+
steps: freeze.steps,
|
|
336
|
+
}),
|
|
337
|
+
];
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
A consumer's generated merge-target-push Verify workflow is the only producer of `patronage-factory/merge-freeze` generations (#356, ADR 0016; #429, #872). A red merge-target Verify completes a generation active, a green one completes it inactive, and `pr:ready` reads the generation on the candidate's own base tip. No command, scheduled job, or second workflow writes that check run; the operator override (`demand:waive --demand merge-freeze`) waives the demand for one candidate and never writes here.
|
|
341
|
+
|
|
342
|
+
`factoryMergeFreezeJob` owns everything a reader trusts: the check name (`FACTORY_MERGE_FREEZE_CHECK_NAME`), the pinned Patronage Factory App identity, the `actions/create-github-app-token` inputs, the `needs.*.result` fold (`FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION`), the merge-target condition (`FACTORY_MERGE_FREEZE_IF`, built from `FACTORY_MERGE_TARGET_REF_CONDITION`), and the job's least-privilege `permissions` (an empty block: the App installation token carries the check-run write, the job uses no `GITHUB_TOKEN` scope, and it never checks out the repository). The caller owns the runner kind (`app-token` for the Factory App token), the timeout, and the `needs` list.
|
|
343
|
+
|
|
344
|
+
That `needs` list is the whole trust input: it must name **every authoritative verification leaf**, because the fold is what decides active or inactive. An empty list is refused — a fold over no needed job always reports success, which would report a merge target nothing verified as green.
|
|
345
|
+
|
|
346
|
+
`if` is `always() && github.event_name == 'push' && (main or epic/**)`. Each clause is load-bearing. `always()` keeps the red path running when a needed job failed. `push` keeps a `pull_request` run from writing a generation at its synthetic merge SHA. The namespace is literal by decision — `main` plus repository-owned `epic/**` integration branches — so a consumer's `push` trigger branch list names the same two things.
|
|
347
|
+
|
|
348
|
+
The job needs no checkout and no install: it mints an App installation token, then makes two Checks API calls. The write is deliberately fail-closed, the opposite of the proof-reuse gate's fail-open shell. The step runs under the runner's default `bash -e {0}`, so any API refusal aborts it, the generation stays absent or `in_progress`, and every arming-time read of that tip refuses until a later push writes a green generation. `factoryMergeFreezeScript()` is that script alone, for a consumer test that executes it against a stubbed `gh` and parses the emitted payload with the factory package's `validateMergeFreezeState` — the round trip that keeps writer and reader from drifting.
|
|
61
349
|
|
|
62
350
|
### Generated shell
|
|
63
351
|
|
|
@@ -90,6 +378,8 @@ import {
|
|
|
90
378
|
assertProofReuseCoverage,
|
|
91
379
|
FACTORY_PROOF_GATE_GUARD,
|
|
92
380
|
factoryProofGateStep,
|
|
381
|
+
factoryProofReuseSummaryStep,
|
|
382
|
+
factoryProofTimingStartStep,
|
|
93
383
|
} from "@patronage/factory-ci";
|
|
94
384
|
|
|
95
385
|
import profile from "../../software-factory.profile.json" with { type: "json" };
|
|
@@ -99,17 +389,25 @@ const coreCommands = profile.verification.commands.filter(
|
|
|
99
389
|
);
|
|
100
390
|
|
|
101
391
|
const core = job("core", {
|
|
392
|
+
// `checks: read` is all the PR-only gate needs. It reads one Checks API
|
|
393
|
+
// endpoint and nothing else.
|
|
102
394
|
permissions: { checks: "read", contents: "read" },
|
|
103
395
|
steps: [
|
|
104
396
|
step(factoryProofGateStep({ commands: coreCommands, surface: "core" })),
|
|
397
|
+
step(factoryProofTimingStartStep()),
|
|
105
398
|
...guardedSteps.map((s) => ({ ...s, if: FACTORY_PROOF_GATE_GUARD })),
|
|
399
|
+
step(factoryProofReuseSummaryStep({ surface: "core" })),
|
|
106
400
|
],
|
|
107
401
|
});
|
|
108
402
|
```
|
|
109
403
|
|
|
110
404
|
The **proof-reuse gate** decides whether a hosted job may reuse the local verification the factory already published for this exact head (ADR 0022). Refusing runs hosted CI; it never fails the candidate. The App identity, check name, step id, output names, guard, and every trust predicate are fixed here rather than consumer-configurable — three repositories had grown three answers to the same question and had already drifted.
|
|
111
405
|
|
|
112
|
-
|
|
406
|
+
**The gate runs on pull requests only** (#863). A merge target's guarantee is about the whole tree, not the diff, and a candidate proof binds only the diff that candidate was scoped to. Every default-branch push therefore executes the full hosted suite, and the job needs only `checks: read`. #931 is the defect this answers: a `main` push reused an impact-scoped candidate proof, executed no command, and left a red package unnoticed for three days.
|
|
407
|
+
|
|
408
|
+
There is no mode to choose. The emitted condition is a trust predicate, so the package owns it: the merge-target opt-out and its push-event merge fallback (#611) are deleted, and no consumer option can reuse proof outside a pull request.
|
|
409
|
+
|
|
410
|
+
A proof is reusable only when the complete Checks API result (`filter=all`, every page) establishes one unambiguous newest generation by greatest `started_at`, produced by the pinned App for the exact repository and head, completed successfully with `outcome: passed`, and covering every command identity the guarded surface requires. Coverage is the union of `executedCommands` and commands released by `notRequiredCommands` only after the gate validates each release against that same proof binding's command-to-target map and identity-bound impact stamp. Missing, malformed, duplicated, affected, unknown, or differently bound release data refuses reuse and runs the hosted surface. `mode` is reported as diagnostic metadata, never authorized on: a reduced-mode proof whose executed and stamp-authorized released commands cover a surface is reusable.
|
|
113
411
|
|
|
114
412
|
The only thing a consumer chooses is **what its surface requires**, expressed as the plain profile command objects that surface selects — a repository with distinct core and docs jobs selects distinct sets and gets distinct required coverage. `proofReuseRequiredCommands()` is the single derivation both the gate and the assertion go through. Identities are baked into the emitted script, so they are held to a plain `[A-Za-z0-9_][\w.:@/-]*` allow-list and shell-quoted at the interpolation site; a selection carrying anything else is unusable and degrades to a gate that always refuses.
|
|
115
413
|
|
|
@@ -121,17 +419,21 @@ The gate is a **step, not a job**, marked `continue-on-error`, with no `set -e`.
|
|
|
121
419
|
|
|
122
420
|
`assertProofReuseCoverage({ commands, skipped, surface })` is the compile-time guard in front of the runtime `incomplete` refusal: hand it the same selection and the command strings the workflow would skip, and it fails the consumer's build when the two drift apart. Coverage is exact executable coverage. The deprecated `equivalents` input remains only for patch-release source compatibility and is ignored; prose cannot authorize a skip. Extracting the skipped strings stays with the consumer — this package never parses workflow source, because establishing trust that way is what killed an earlier attempt.
|
|
123
421
|
|
|
422
|
+
`factoryProofTimingStartStep()` and `factoryProofReuseSummaryStep()` replace consumer-local proof timing summaries without taking over workflow topology. Put the start step immediately after the gate and the summary step after the guarded work. The helpers keep the established `Start CI timing` / `Record proof-reuse timing` names and distinguish proof reuse, full fallback with the gate's reason, and pushes where the gate's step condition kept it off entirely. Reuse links the exact source check and bound head; every path emits a cheap Actions notice. Both steps are `continue-on-error`: missing timing support or an unwritable presentation destination cannot change a required job's conclusion. These helpers change no trust predicate or guard.
|
|
423
|
+
|
|
424
|
+
The raw summary script builder and the internal `ci-timing` step-id and step-name constants are not exported. Only the two step builders above are public; every production caller already consumed them through the builders, so this is a same-prerelease narrowing rather than a behavior change (#686).
|
|
425
|
+
|
|
124
426
|
### Alchemy entries
|
|
125
427
|
|
|
126
428
|
```ts
|
|
127
429
|
import { bundleAlchemyEntry, executeAlchemyEntry } from "@patronage/factory-ci";
|
|
128
430
|
```
|
|
129
431
|
|
|
130
|
-
`bundleAlchemyEntry({ entry, outfile, ... })` flattens a TypeScript Alchemy entry to a single ESM file the Alchemy CLI can run, keeping `alchemy`, `alchemy/*`, `effect`, and `effect/*` external — both packages are identity-sensitive and a second copy breaks them silently. Options: `absWorkingDir`, `alias`, `packages` (`"external"` by default), `sourcemap`, `target`, `tsconfig`. Returns the absolute outfile path.
|
|
432
|
+
`bundleAlchemyEntry({ entry, outfile, ... })` flattens a TypeScript Alchemy entry to a single ESM file the Alchemy CLI can run, keeping `alchemy`, `alchemy/*`, `effect`, and `effect/*` external — both packages are identity-sensitive and a second copy breaks them silently. The bundler runs with `logLevel: "silent"`: a failed build rejects, and writes no resolver path or source excerpt to the inherited stderr on its way out. Options: `absWorkingDir`, `alias`, `packages` (`"external"` by default), `sourcemap`, `target`, `tsconfig`. Returns the absolute outfile path.
|
|
131
433
|
|
|
132
434
|
`alias` is a specifier-to-target map handed to esbuild. Substitution runs before the `packages` and `external` decisions, so an aliased bare specifier is inlined even under `packages: "external"` — that is how a repo points a workspace-only or duplicated package at one file. Give absolute paths or package names; which aliases a repo needs is consumer policy and this package ships no defaults. `executeAlchemyEntry` passes its whole `bundle` option through, so the map is available there too. Because substitution runs first, an alias on `alchemy`, `effect`, or any of their subpaths would silently defeat the externals and bundle a second copy, so those keys are rejected outright. Targets are not string-matched — no rule over how a path is spelled can survive `..` segments or symlinks — so instead the build's metafile is checked afterwards and the bundle is rejected if it carries any input from a reserved package, however that file was reached. A consumer shim that re-exports `effect` by bare specifier stays external naturally and is allowed.
|
|
133
435
|
|
|
134
|
-
`executeAlchemyEntry({ from, bundle, args, ... })` owns the repeated choreography: resolve the consumer's Alchemy CLI from `from`, bundle the entry, run that CLI under the current Node binary with the absolute bundled entry appended, and throw on spawn errors, signals, missing statuses, or non-zero exits. It returns only after status 0.
|
|
436
|
+
`executeAlchemyEntry({ from, bundle, args, ... })` owns the repeated choreography: resolve the consumer's Alchemy CLI from `from`, bundle the entry, run that CLI under the current Node binary with the absolute bundled entry appended, and throw on spawn errors, signals, missing statuses, or non-zero exits. It returns only after status 0. Options carry exactly one entry source. Pass `bundle` to bundle now, or `bundledEntry` (absolute or cwd-relative) to reuse a path from a prior `bundleAlchemyEntry` call. Passing both, or neither, does not type-check. Captured output (`stdio: "pipe"`) honors `maxBuffer` only when the caller supplies it (Node's `spawnSync` default is 1 MiB; pass `EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER` for 64 MiB) and, when supplied, a `redact: (text: string) => string` hook applied to stdout and stderr before they are returned. Default `stdio: "inherit"` still streams the child unredacted. This package does not own a secret-name policy.
|
|
135
437
|
|
|
136
438
|
The caller still owns deploy/destroy/plan arguments, stage admission, credentials, environment shaping, destructive-plan guards, and convergence. Failure messages never repeat arguments or environment values.
|
|
137
439
|
|
|
@@ -147,6 +449,48 @@ import {
|
|
|
147
449
|
|
|
148
450
|
`local-pr-<pr>-<short sha>` construction and interpretation live behind one private grammar. `localPreviewStage({ pr, headSha, shaLength? })` accepts a positive PR, a full 40-character SHA, and a 7–40-character slice length (default 12). `parseLocalPreviewStage(stage, expected?)` returns the PR and SHA prefix, optionally proving ownership against a PR and full head SHA. `isLocalPreviewStage(stage, pr?)` is the boolean type guard. The raw regex is not public.
|
|
149
451
|
|
|
452
|
+
### Preview-proof lifecycle
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
import { previewProofLifecycle } from "@patronage/factory-ci";
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
`previewProofLifecycle` owns the commodity preview-proof state machine that two consumers had each written: admit a disposable stage, register envelope-bound proof at the candidate head, and record cleanup. `transition(state, event)` is the only mutation. `recover(state, cleanupEvent)` re-enters that same cleanup event from a failed outcome; it is not a second machine and not a CLI command. `resolve(state, query?)` is the consumer-readable registration read model: stack, stage, head SHA, proof identity, and cleanup status.
|
|
459
|
+
|
|
460
|
+
Events:
|
|
461
|
+
|
|
462
|
+
- `begin` — the pre-deploy gate. A mismatched branch name is accepted at the PR head SHA. A dirty tree or a SHA mismatch is refused, as are a draft, a closed PR, and any stage the disposable grammar does not own for this PR head. Does not create a registration.
|
|
463
|
+
- `register` — the same identity gate, plus passed smoke, passed convergence, and a passing three-way-bound evidence envelope at this head. Writes a registration with `cleanup.outcome: "pending"`. Cleanup, smoke, and convergence status live only on their nested objects, so no top-level copy can diverge from them. Machine evidence is that envelope; this module never posts a PR comment.
|
|
464
|
+
- `cleanup` — records an explicit passed or failed outcome onto an existing registration. Cleanup is never inferred from whether the stage still exists. `recover` is the failed-to-resolved re-entry of this event.
|
|
465
|
+
|
|
466
|
+
Proof runs entirely on one side of GitHub's draft/ready boundary: both `begin` and `register` refuse `isDraft: true`. Undraft first, then prove. Callers still own deploy, destroy, credentials, smoke probes, envelope emission, and stack names.
|
|
467
|
+
|
|
468
|
+
### Preview-proof inventory
|
|
469
|
+
|
|
470
|
+
```ts
|
|
471
|
+
import { previewProofInventory } from "@patronage/factory-ci";
|
|
472
|
+
|
|
473
|
+
const store = previewProofInventory.githubStore({
|
|
474
|
+
fetch,
|
|
475
|
+
token: process.env.GITHUB_TOKEN,
|
|
476
|
+
});
|
|
477
|
+
const rows = await previewProofInventory.list({ owner, repo, pr }, { store });
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
`previewProofInventory` is the hosted read and write API on that registration read model. A consumer workflow enumerates registered preview deployments for a PR (stack, stage, head SHA, proof identity, cleanup status) and records a cleanup outcome against a registration so the proof record reflects closure.
|
|
481
|
+
|
|
482
|
+
Registration is a consumer-readable read model. Cleanup outcomes are recorded by this API; they are never inferred from whether a Cloudflare or Alchemy stage still exists. Physical stage listing is a different artifact.
|
|
483
|
+
|
|
484
|
+
Persistence is an injectable GitHub transport in the same style as `mintInstallationToken`: the caller passes `fetch` and a token. This package does not read operator config or hold secrets. Records bind to the Patronage Factory GitHub App (`FACTORY_PROOF_GATE_APP_ID`) and the disposable-stage grammar. Check-runs named `patronage-factory/preview-proof` (`PREVIEW_PROOF_INVENTORY_CHECK_NAME`) carry the registration JSON. This API does not POST or PATCH issue comments.
|
|
485
|
+
|
|
486
|
+
`list({ owner, repo, pr }, { token })` works with a workflow `GITHUB_TOKEN` (read). Give that job `permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS` (also `previewProofInventory.listPermissions`): `checks: read`, `contents: read`, `pull-requests: read`. A job that omits `pull-requests: read` gets 403 on the PR commit listing for a same-repository PR and discovers nothing (#859). `persist` and `recordCleanup` write App-owned check-runs, which GitHub only allows the producing App to update. Pass an installation token the caller minted (`mintInstallationToken`); a job `GITHUB_TOKEN` cannot write those records. There is no `psf` command for this surface.
|
|
487
|
+
|
|
488
|
+
`recordCleanup` loads the PR's registrations, applies `previewProofLifecycle.transition(..., { type: "cleanup" })`, then persists. Failed then passed uses that same event; in-memory re-entry from a failed outcome is `previewProofLifecycle.recover`, which calls that transition. Unknown stack or stage, and an identity mismatch on the disposable stage or head SHA, fail closed. Check-runs from another App, including `github-actions`, are ignored.
|
|
489
|
+
|
|
490
|
+
Pass `{ store }` to substitute the GitHub adapter. `previewProofInventory.memoryStore()` is an in-memory `list`/`put` port for tests. `githubStore({ token, fetch, timeoutMs? })` is the GitHub-backed implementation. Stack names stay caller strings.
|
|
491
|
+
|
|
492
|
+
Transient transport failures — a network-level rejection such as EPIPE, a timeout, a 408/429/5xx, or a response body that dies mid-read — are retried with doubling backoff up to three transport attempts in total (the first attempt plus two retries), and then throw `PreviewProofTransportError` (attempt count, last transient status, credential-free reason); a permanent HTTP refusal throws `GitHubApiError` without retrying (#830). Either failure from `persist` or `recordCleanup` is an evidence-registration failure, not a failed deployment: retain the healthy disposable stage, record the proof BLOCKED (never PASS), and re-run registration at the same head — writes are keyed by stack and stage, so resuming needs no redeploy. Admission stays fail-closed on its own: an unregistered proof never satisfies the preview demand.
|
|
493
|
+
|
|
150
494
|
### GitHub App installation tokens
|
|
151
495
|
|
|
152
496
|
```ts
|
|
@@ -162,14 +506,366 @@ The factory publishes its check runs, and paitronage its proof comments, under t
|
|
|
162
506
|
|
|
163
507
|
`mintInstallationToken({ credentials, owner, repo }, options?)` is that mechanism and nothing more. `credentials` is `{ appId, installationId?, privateKeyPath }`: the app id GitHub issued, the installation when a consumer has recorded one, and the path to the private key. The key is a _path_, not key material, so no caller has to hold a secret in memory to make this call — and **where that path comes from stays the consumer's**. Operator config, a secret manager, an environment variable: this package neither reads a config file nor knows a key-path convention. `githubAppJwt(credentials, options?)` is the signing step alone, for a caller that needs the app JWT rather than an installation token.
|
|
164
508
|
|
|
165
|
-
Nothing is cached. The token is returned to the caller, which owns its lifetime — this module keeps no copy of the token or the key, and never writes either to any output.
|
|
509
|
+
Nothing is cached. The token is returned to the caller, which owns its lifetime — this module keeps no copy of the token or the key, and never writes either to any output. Mint requests send `Connection: close` and retry transport failures — fetch rejection, timeout, a body that dies mid-read, or 408/429/5xx — with doubling backoff for three attempts by default. Exhaustion throws `GitHubAppTokenTransportError` with the attempt count and a bounded credential-free reason. Any other 4xx is GitHub's verdict and throws `GitHubApiError` on the first response without retrying. The budget is the caller's: `transportAttempts` sets the total attempts, and a caller whose mint is best-effort and already has a fallback passes `1` so the fallback stays prompt. The backoff is fixed and does not scale with `timeoutMs`.
|
|
510
|
+
|
|
511
|
+
`options` are all injectable seams: `fetch`, `now`, `readPrivateKey`, `transportAttempts`, and a `timeoutMs` per request (five seconds by default). Tests substitute the seams; production passes at most a timeout and a budget.
|
|
512
|
+
|
|
513
|
+
Callers that must not receive the App's full installation grant pass `permissions` and `repositories` on the mint input. GitHub then issues a token covering only that subset. The Factory App broker uses `FACTORY_APP_BROKER_TOKEN_PERMISSIONS` (`checks: write`) and the one repository the Cursor OIDC claim authenticated (#949). Omitted, those fields keep the historical full-grant mint that operator PEM and Actions already use.
|
|
514
|
+
|
|
515
|
+
### Vitest suite profiling
|
|
516
|
+
|
|
517
|
+
```ts
|
|
518
|
+
import { runVitestProfile } from "@patronage/factory-ci";
|
|
519
|
+
|
|
520
|
+
const profile = await runVitestProfile({
|
|
521
|
+
cwd: packageRoot,
|
|
522
|
+
gitDirectory: repositoryRoot,
|
|
523
|
+
maxWorkers: 4,
|
|
524
|
+
outputPath: "/abs/path/profile.json",
|
|
525
|
+
samples: 3,
|
|
526
|
+
slowLimit: 20,
|
|
527
|
+
});
|
|
528
|
+
```
|
|
166
529
|
|
|
167
|
-
`options`
|
|
530
|
+
`runVitestProfile(options, dependencies?)` takes N **serial** Vitest runs at one worker count and writes a machine-readable profile after every sample: per-file and per-test timings sorted slowest first, duration statistics across samples, and the machine the samples ran on. Samples never overlap — concurrent runs would measure CPU and I/O contention instead of the worker count under test — and the profile is rewritten after each one, so a run that goes red at sample three still leaves two usable measurements on disk. A failed sample throws `VitestProfileError`, which carries the `exitCode` a caller should exit with.
|
|
531
|
+
|
|
532
|
+
The **environment capture is the reason this is shared**. The #640 runner comparison only resolved because each sample recorded its `cpuModel`: 4-CPU samples that were indistinguishable by label split into two non-overlapping populations, AMD at 15.3–16.2s and Intel at 24.6–24.9s. `captureVitestProfileEnvironment({ cwd, gitDirectory? })` records CPU model and count, available parallelism, total memory, arch, platform, OS release, Node version, the **consumer's** Vitest version (resolved from `cwd`, never this package's), and the Git head and dirtiness. Git failures and an unresolvable Vitest degrade to `null` / `"unknown"` rather than throwing: an artifact from a tarball checkout is still a measurement.
|
|
533
|
+
|
|
534
|
+
`normalizeVitestProfileSample(report, input)` folds one Vitest `--reporter=json` document into a sample; a missing report yields `reportAvailable: false` instead of nothing. `writeVitestProfile(path, profile)` is the atomic write — a partial file must never be readable as a complete measurement. Every emitted document carries `schemaVersion: VITEST_PROFILE_SCHEMA_VERSION` and `tool: VITEST_PROFILE_TOOL` so artifacts from different repositories are comparable and self-identifying.
|
|
535
|
+
|
|
536
|
+
**Everything a repository decides stays with the repository**: worker counts, sample counts, slow-list length, output-path conventions, runner labels, artifact upload, and console output. `onSampleStart` / `onSampleComplete` hand the caller each sample so it can print whatever it prints; this package logs nothing. `stdio` for the Vitest child is the caller's too — `"inherit"` by default, so a caller whose own stdout is structured passes `"ignore"`. A reporting hook is a console, not a control: if `onSampleStart` or `onSampleComplete` throws, the sample still runs and the `VitestProfileError` still wins, and the hook's error surfaces only when the sample was otherwise green. `samples` below one is refused outright — it would resolve green having measured nothing and written no artifact. `now`, `runSample`, and `writeResult` are injectable seams for tests.
|
|
537
|
+
|
|
538
|
+
### Alchemy subpath
|
|
539
|
+
|
|
540
|
+
```ts
|
|
541
|
+
import { ALCHEMY_SUBPATH, evaluateStack } from "@patronage/factory-ci/alchemy";
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
`@patronage/factory-ci/alchemy` is the one place in this package that may import `alchemy` or `effect` (ADR 0031). Its source is `src/alchemy/`, it builds as its own entry, and it is the only subpath — there is no per-module subpath.
|
|
545
|
+
|
|
546
|
+
Install `alchemy` and `effect` yourself before importing it. The published ranges are `>=2.0.0-beta.63 <3` and `>=4.0.0-beta.98 <5`, the same ones `@patronage/alchemy-d1-state` carries, and both are marked optional so an installation that never touches this surface stays quiet.
|
|
547
|
+
|
|
548
|
+
The published ranges are wide, but the workspace pins one copy: `alchemy` and `effect` are devDependencies here at the same versions `@patronage/alchemy-d1-state` and `software-factory-hq` pin. Without that pin pnpm resolves the peer range to its newest release for this importer alone, which is a second copy of both in the workspace and a lockfile that no longer installs. `evaluateStack` imports both, so `knip` sees them used.
|
|
549
|
+
|
|
550
|
+
`ALCHEMY_SUBPATH` is the specifier itself. Stage policy, retained-identity asserts, the lifecycle guards, stack evaluation, and the graph invariants ship here. The Alchemy entry helpers named above (`bundleAlchemyEntry`, `executeAlchemyEntry`) stay on the package root, where they belong: they shell out to the consumer's Alchemy CLI and import neither package.
|
|
551
|
+
|
|
552
|
+
#### Stage policy
|
|
553
|
+
|
|
554
|
+
```ts
|
|
555
|
+
import {
|
|
556
|
+
anyStage,
|
|
557
|
+
LOCAL_PREVIEW_STAGES,
|
|
558
|
+
stagePolicy,
|
|
559
|
+
} from "@patronage/factory-ci/alchemy";
|
|
560
|
+
|
|
561
|
+
const policy = stagePolicy({
|
|
562
|
+
stacks: [
|
|
563
|
+
{ claims: ["bootstrap"], stack: "bootstrap-stack", stages: ["bootstrap"] },
|
|
564
|
+
{ claims: ["telemetry"], stack: "app" },
|
|
565
|
+
{ stack: "audit", stages: ["staging", "prod"] },
|
|
566
|
+
],
|
|
567
|
+
stages: {
|
|
568
|
+
disposable: anyStage(/^pr-\d+$/u, LOCAL_PREVIEW_STAGES),
|
|
569
|
+
protected: ["bootstrap", "dev", "prod", "staging", "telemetry"],
|
|
570
|
+
},
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
policy.assertDestructiveStage(stage); // throws on a protected stage
|
|
574
|
+
policy.assertStackOwnsStage(stack, stage);
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
Two projects wrote the same three questions — is this stage protected, is it disposable, and may this stack run it — and each answered them with its own stage names compiled into the answer. `stagePolicy` takes the table and returns the decisions: `isProtectedStage`, `isDisposableStage`, `isKnownStage`, `assertKnownStage`, `assertDestructiveStage`, and `assertStackOwnsStage`. **No project or stack name appears in this package, and one stage name does — `local`, the local emulator's own name, described below.**
|
|
578
|
+
|
|
579
|
+
A `StageMatcher` is a name list, a `RegExp`, or a predicate — the predicate is how a project expresses a stage set it resolves itself, such as one config file per client. `anyStage(...)` composes matchers, and `LOCAL_PREVIEW_STAGES` is the disposable grammar this package already owns (`isLocalPreviewStage`), offered as a matcher rather than assumed, because a project's disposable set is wider than that one grammar.
|
|
580
|
+
|
|
581
|
+
Stack ownership runs in two independent directions. `stages` restricts a stack to the stages it may run. `claims` reserves stages for one stack. Declaring the same matcher as both pairs a stack and its stages in both directions; declaring `claims` alone reserves a stage without narrowing the stack that owns it. A declared `stacks` registry is exhaustive, so a mistyped stack is refused rather than passing as unconstrained; omit `stacks` to leave ownership unpoliced.
|
|
582
|
+
|
|
583
|
+
Refusals are `StagePolicyError` with a stable `code` — `UNKNOWN_STAGE`, `AMBIGUOUS_STAGE`, `PROTECTED_STAGE`, `UNKNOWN_STACK`, `STAGE_NOT_OWNED` — so a project maps them onto its own lifecycle failure envelope instead of matching on message text. A stage a table classifies as both protected and disposable is a table defect: every query on it throws `AMBIGUOUS_STAGE` rather than silently picking a side.
|
|
584
|
+
|
|
585
|
+
What stays with the project: which environment variable authorizes an attended protected operation, what counts as a trusted hosted context, whether an outstanding state-transfer proof blocks a stack, and the shape of its own failure envelope. Those name credentials, issues, and contexts, and none of them is a stage question.
|
|
586
|
+
|
|
587
|
+
#### Local emulation
|
|
588
|
+
|
|
589
|
+
```ts
|
|
590
|
+
import {
|
|
591
|
+
isLocalEmulationStage,
|
|
592
|
+
localEmulationEnvironment,
|
|
593
|
+
} from "@patronage/factory-ci/alchemy";
|
|
594
|
+
|
|
595
|
+
if (isLocalEmulationStage(stage)) {
|
|
596
|
+
child.env = { ...child.env, ...localEmulationEnvironment({ stage }) };
|
|
597
|
+
}
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
`isLocalEmulationStage(stage)` is true for the literal `local` and nothing else. Two projects and HQ each answered this question with their own rule — a refusal list, a constant, and `$(whoami)` — and all three meant that one name, so the answer is a literal, not a pattern and not a table. A disposable preview stage such as `local-pr-1-abcdef0` shares the prefix but runs against a real account, so it is false. The comparison is exact: no trim, no case folding. The question sits outside `stagePolicy` because a project's table classifies the stages of its own estate, and the emulated stage belongs to no estate.
|
|
601
|
+
|
|
602
|
+
`localEmulationEnvironment({ stage })` returns the two Cloudflare variables a local-emulation child is launched with. Alchemy refuses to start when `CLOUDFLARE_ACCOUNT_ID` is missing or malformed, even for a run that calls no Cloudflare API, so projects handed the child real credentials to satisfy a check the run never needed. The helper hands it a sentinel pair instead:
|
|
603
|
+
|
|
604
|
+
| Variable | Value |
|
|
605
|
+
| --- | --- |
|
|
606
|
+
| `CLOUDFLARE_ACCOUNT_ID` | thirty-two zeros — well-formed, and addresses no account |
|
|
607
|
+
| `CLOUDFLARE_API_TOKEN` | `factory-ci-local-emulation-no-cloudflare-token` — spelled as words, so no reader and no scanner mistakes it for a credential |
|
|
608
|
+
|
|
609
|
+
The account id is the shape Alchemy validates (`/^[0-9a-f]{32}$/i`, `validateAccountId`); a placeholder such as `""` or `dummy` fails that check before a run starts. Neither value is a secret.
|
|
610
|
+
|
|
611
|
+
Set `FACTORY_CI_LIVE_CLOUDFLARE_BINDING` to a non-empty value and the helper returns no variables, so whatever credentials the parent carries pass through to the child and the run may bind a live Cloudflare resource. That opt-in is the only way a real credential reaches a local-emulation child. The presence of a real credential is never the signal, and the helper reads no credential: it reads the opt-in and nothing else. The result is an overlay — merge it over the environment the launcher has otherwise assembled. Any stage other than `local` throws, because a non-local stage deploys to a real account.
|
|
612
|
+
|
|
613
|
+
Scrubbing an ambient token out of the child stays with the launcher. This package owns the environment shape only.
|
|
614
|
+
|
|
615
|
+
#### Retained identities
|
|
616
|
+
|
|
617
|
+
```ts
|
|
618
|
+
import {
|
|
619
|
+
assertRetainedIdentities,
|
|
620
|
+
parseStateSnapshot,
|
|
621
|
+
} from "@patronage/factory-ci/alchemy";
|
|
622
|
+
|
|
623
|
+
const scope = { stack: "loop", stage: "prod" };
|
|
624
|
+
|
|
625
|
+
assertRetainedIdentities({
|
|
626
|
+
after: parseStateSnapshot(currentState, scope),
|
|
627
|
+
before: parseStateSnapshot(recordedState, scope),
|
|
628
|
+
markers: [
|
|
629
|
+
{
|
|
630
|
+
field: "databaseId",
|
|
631
|
+
fqn: "app-db",
|
|
632
|
+
resourceType: "Cloudflare.D1Database",
|
|
633
|
+
section: "attr",
|
|
634
|
+
value: expectedDatabaseId,
|
|
635
|
+
},
|
|
636
|
+
],
|
|
637
|
+
});
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
A protected stage's value is the physical resources it already owns. An Alchemy deploy that no longer recognises one of them does not fail — it creates a second one and leaves the first orphaned with the data still in it. `assertRetainedIdentities` reads the recorded state before the operation runs and throws `RetainedIdentityError` when an identity is `missing`, `unexpected` (not the `value` the marker names), or `changed` between the two snapshots. Every violation is reported, not just the first.
|
|
641
|
+
|
|
642
|
+
`parseStateSnapshot` reads the persisted-state document — the bulk document, `{ resources: [{ stack, stage, fqn, state }] }`, not a single record. A document covering the whole estate holds one fqn once per stage; pass the second argument, `{ stack, stage }`, to narrow the document to the stage the markers are about. A scoped document that still records one fqn twice throws rather than letting a marker match whichever record sorted first. State it cannot read throws, because reading a broken state as an empty one turns a failed read into a passing assert. An evaluated stack graph is a different artifact carrying the same identities; a caller holding one projects it onto `StateSnapshot` at the call site.
|
|
643
|
+
|
|
644
|
+
Two inputs are refused outright rather than passing: an empty marker list, and a marker with neither a `value` nor a `before` snapshot to compare against. Both would resolve green having asserted nothing.
|
|
645
|
+
|
|
646
|
+
#### Stage inventory, record read, and stage delete
|
|
647
|
+
|
|
648
|
+
```ts
|
|
649
|
+
import {
|
|
650
|
+
deleteStageRows,
|
|
651
|
+
inventoryStages,
|
|
652
|
+
parseStateSnapshot,
|
|
653
|
+
readStageSnapshot,
|
|
654
|
+
} from "@patronage/factory-ci/alchemy";
|
|
655
|
+
|
|
656
|
+
const stages = await inventoryStages(state);
|
|
657
|
+
const snapshot = parseStateSnapshot(
|
|
658
|
+
await readStageSnapshot(state, { stack: "app", stage: "pr-12" }),
|
|
659
|
+
{ stack: "app", stage: "pr-12" }
|
|
660
|
+
);
|
|
661
|
+
await deleteStageRows(state, { stack: "app", stage: "pr-12" });
|
|
662
|
+
```
|
|
663
|
+
|
|
664
|
+
These three read and write the state layer the consumer passes in — the store it configured, and the only thing they address. They launch no child process, and each answer is the state layer's own. `inventoryStages` returns every `(stack, stage)` pair the store holds, ordered by stack then stage. `readStageSnapshot` returns one stage as the persisted-state document `parseStateSnapshot` reads, built from the same atomic stage view and per-resource records `runAlchemyLifecycle` uses; a listed resource with no readable record fails the read rather than being left out. `deleteStageRows` removes every row of one stage and no row of any other; a stage the store does not hold is refused, not reported as removed, while `readStageSnapshot` reads that same stage as a document with no resource in it. Which stages may be deleted stays with the consumer.
|
|
665
|
+
|
|
666
|
+
A stage is addressed by the path `stack/stage`, and a name that is empty, padded, or carries a separator addresses something wider: an empty stage collapses the path to the stack, so a delete meant for one stage would take every stage of that stack. All three refuse such a name before they build a path. `inventoryStages` also takes an optional `{ stack, stage }` filter, and a pinned value is taken at face value: it skips the matching list call, so a pinned `stage` returns that stage once per stack whether or not the stack holds it. Pass no filter to inventory what the store actually holds.
|
|
667
|
+
|
|
668
|
+
#### Lifecycle
|
|
669
|
+
|
|
670
|
+
```ts
|
|
671
|
+
import { runAlchemyLifecycle } from "@patronage/factory-ci/alchemy";
|
|
672
|
+
|
|
673
|
+
const result = await runAlchemyLifecycle({
|
|
674
|
+
request: { operation: "deploy", stack: "hq", stage: "v1" },
|
|
675
|
+
policy: {
|
|
676
|
+
stages: table,
|
|
677
|
+
holder: runId,
|
|
678
|
+
retainedIdentities: markers,
|
|
679
|
+
adopt: true,
|
|
680
|
+
nonConvergentResources: ["hq-worker"],
|
|
681
|
+
},
|
|
682
|
+
state: d1Service,
|
|
683
|
+
entry: { from: import.meta.url, bundledEntry: "alchemy.run.ts", env },
|
|
684
|
+
});
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
`runAlchemyLifecycle` is the one operation over an Alchemy plan, deploy, or destroy. It owns the order; a consumer cannot get the order wrong because it does not call the steps. Paitronage and HQ each reconstructed this sequence from the guards below and got different parts wrong (paitronage#1917), which was the evidence that admitted it here.
|
|
688
|
+
|
|
689
|
+
The consumer passes typed policy and two capabilities. `state` is the store from `@patronage/alchemy-d1-state`: `snapshotStage`, `get`, and `acquireStageOwnership`, whose lease carries `renew`, `release`, `deleteEmptyStage` and `childEnvironment`, matched structurally, so this package learns no table, account, or SQL. `entry` is what `executeAlchemyEntry` needs minus what the lifecycle decides: the arguments are the lifecycle's, stdio is always piped so the plan can be read, and a `bundle` is built once up front, with every child launched in `cwd`, then the bundle root, then this process's directory — the same chain `executeAlchemyEntry` resolves. A bundle that cannot build is `PREPARATION_FAILED` and nothing else: the bundler's own diagnostics are silenced at the source. There is no `redact` and no echo because there is no sink: each child's captured output is parsed and dropped, written nowhere, so nothing in it can reach a job log or an evidence file through this operation. Every child's environment carries the stage lease; see ownership below.
|
|
690
|
+
|
|
691
|
+
The optional `childDiagnostics: { path, redact }` is the one way any of that captured output reaches a file. Omitted — the default, and byte-identical to the behavior above — nothing is written and nothing changes. Set, every child of the operation (both dry runs, the apply, the destroy) has its stdout and its stderr appended to `path` under a header naming the operation, the child, and the stage. Each stream is passed **whole** through `redact`, not a line at a time, because a declared value can itself span lines — a PEM key, a pasted service-account JSON — and a per-line pass would find no line holding the whole value and write every one of them verbatim. The consumer chooses the path and supplies the redactor — `secretNamePolicy({ names, values })` builds the usual one — because the secret names are project policy and this package holds none. The record is a copy: `redact` never runs over what the child hands back, so the plan text parsed by `parsePlanEffects` and hashed for a first deploy is the child's own bytes. A `CHILD_FAILED` from such a run carries `childDiagnosticsPath`, the path and never the output, so an operator knows where to look.
|
|
692
|
+
|
|
693
|
+
A record that cannot be written is `CHILD_DIAGNOSTICS_UNWRITABLE`, never a misreported child failure, and **when** it is reported depends on what has already happened to the stage. The file is opened and headed before each child starts, so while no mutating child has run — an unwritable path at the first child, a redactor that throws on a dry run — the run is refused up front with the stage still untouched. Once the apply or the destroy child has started, the failure is retained and reported only after the operation has run to its end, the way `LEASE_RELEASE_FAILED` is: the mutation succeeded, and abandoning the convergence check over a missing record would invite an operator to destroy and retry a stage that is fine. So a good deploy still converges and is still checked, and the run then ends in `CHILD_DIAGNOSTICS_UNWRITABLE` with the mutation certainty it actually reached. A child that failed is reported ahead of a record that could not be written, because the child is the finding. The file is only as redacted as the declared name list makes it — a value the project did not declare, and any re-encoded form of one it did, reaches the file verbatim — so it belongs outside the repository and outside anything uploaded as an artifact.
|
|
694
|
+
|
|
695
|
+
The optional `entry.envFile` selects the dotenv file for every child, including both dry runs. Its path follows Alchemy’s normal resolution from the child working directory. Omit it to preserve Alchemy’s default `.env` behavior. A consumer that requires environment-only credentials can supply its own private empty file for the operation’s lifetime; file creation and cleanup remain consumer policy.
|
|
696
|
+
|
|
697
|
+
The sequence, per operation:
|
|
698
|
+
|
|
699
|
+
- **`plan`** takes the stage lease, reads the persisted state, runs `deploy --dry-run`, reads the state again, and refuses with `STATE_CHANGED` if any resource record or the stack output differs — all under the one lease, so no other writer can reach the stage while the child plans. That refusal wins over the child's own exit status, because a planning child that wrote is the more serious finding. On an empty protected stage with a `firstDeploy` policy the result carries `planHash`, the value an operator authorizes.
|
|
700
|
+
- **`deploy`** starts with the same leased read-only plan, then admits it under the same lease. An empty protected stage is a first deploy: the plan may only `create` or `adopted` — `adopted` is the create of a resource the provider already finds, and it plans only for a record with no prior state — and its hash must be on `firstDeploy.authorizedHashes`, or the refusal is `FIRST_DEPLOY_UNAUTHORIZED` carrying the hash. A protected stage with state refuses `replace` and `delete` (`EFFECT_NOT_PERMITTED`), and every `retainedIdentities` marker must hold against the recorded values before the apply (`RESOURCE_IDENTITY_MISMATCH`); a protected stage with no markers is `INVALID_POLICY`, because a check with nothing in it must not read as a proof. A disposable stage is constrained by neither. Then the apply child (`--yes`, with `--adopt` when the policy says so), under the same lease. Then, still under it: the persisted state again, which must record every resource the plan created (`DEPLOY_INCOMPLETE`; the result's `created` names their FQNs — a planned create resolves to an FQN that was absent before the apply, or was recorded in flight, `creating` or `deleting`, and is exactly the FQN the create row names — a row carries the FQN, so an interrupted create recovers at any depth; the record must have left the in-flight state) and, on a protected stage, the same identities as before; then a second `deploy --dry-run`, bracketed by the same two-read check as the first so a convergence child that wrote is `STATE_CHANGED`, which must be a no-op (`NOT_CONVERGED`) except an `update` on a persisted FQN named in `nonConvergentResources`: a Worker carrying a write-only secret binding re-plans as `update` on every deploy because the value can never be read back. Only `update`, only on those FQNs. A task row (`run` or `drop`) prints only while the task still has work, so any task row is `NOT_CONVERGED` too.
|
|
701
|
+
- **`destroy`** is refused on a protected stage. Then, under the stage lease, the destroy child, then the atomic stage view must be empty (`DESTROY_RESIDUE`) and the empty output row is removed in the same lease (`cleanup: "removed" | "absent"`). An unreadable store fails with `STATE_STORE_UNAVAILABLE`; it never reads as empty.
|
|
702
|
+
|
|
703
|
+
Ownership follows #1074 and #1107. Each operation runs under **one** stage lease, held from its first read to its last decision, and every child it launches — the dry runs, the apply, the destroy — runs inside that lease: the lifecycle spreads the lease's `childEnvironment()` into the child's environment, and the adapter in the child adopts it. The stage is never unowned while an operation runs, so no other writer can interleave between the admitted plan and the apply, and a second run on the stage is `STAGE_HELD`. Before anything read under the lease is decided on, the lifecycle **renews** the lease: renewal is the adapter's fenced operation, it changes no rows unless this holder's unexpired row is still there, and it fails with `lost` when the lease expired or was taken over — `OWNERSHIP_LOST`, and the decision is not made. Independently of that, every exit from a leased window passes the same fence check, whether the window returned or threw and wherever it threw from: a lease lost anywhere in the window — during the apply child, during a state read, under a child failure — is `OWNERSHIP_LOST` at the phase the run was in, ahead of whatever else was found there. The check sits outside the window's code, so no early return or new failure path inside it can skip acceptance. A fence that holds lets a genuine store or child failure through unchanged. A successful `release` is not that check: the adapter's release is idempotent by design and succeeds when the row is gone or belongs to a later holder, so it proves nothing, and the lifecycle infers nothing from it. A release that _fails_ is a different fact — the store could not be reached and this holder's row may still be there, blocking the stage until it expires — so after a successful operation it is reported as `LEASE_RELEASE_FAILED`; a failure inside the operation is reported ahead of it.
|
|
704
|
+
|
|
705
|
+
The consumer's entry point passes its environment to the adapter: `d1State({ ..., ownership: { stack, stage, holder, adoptFrom: process.env } })`. That is the whole wiring, the same for a plan, a deploy and a destroy, and the same when an operator runs the entry by hand with no parent (the adapter then acquires as usual). Nothing in the child is trusted to opt in: while the parent holds the stage, a child whose state layer takes its own lease is refused at its first state call, and one that takes none is refused at its first write, by the store's fence. The token crosses the process boundary only through that environment; it is on no result, no failure, and no type this package exports. The store fences its rows, not Cloudflare: a provider call that reached Cloudflare before a lease was lost is not undone, and the refused state write is how the loss surfaces (see the adapter's README). The lifecycle does not reimplement any of this; it consumes it.
|
|
706
|
+
|
|
707
|
+
Every failure is an `AlchemyLifecycleError` with an enumerated `code`, `phase` (`request`, `admission`, `state`, `execution`, `postcondition`), and `mutation` (`not-started`, `read-only-started`, `mutation-may-have-occurred`). The message is the fixed sentence `LIFECYCLE_FAILURE_MESSAGES[code]` and nothing else; no failure carries a `cause`. The one field that says anything about a child's output is `childDiagnosticsPath`, present on `CHILD_FAILED` and `CHILD_DIAGNOSTICS_UNWRITABLE` when the run configured `childDiagnostics`: it is the path the consumer chose, never the output, and never part of the message. Nothing a child printed, nothing the store said, and nothing a credential resolver quoted can reach an evidence sink through this error. After a deploy or destroy child was started, no failure reports `not-started`.
|
|
708
|
+
|
|
709
|
+
The plan is read once, by `parsePlanEffects`, from the lines Alchemy's `formatPlanLines` prints: one `Plan:` summary, one `[fqn] action` row per resource, one `[fqn/name] action` row per binding of that resource, and one `[fqn] run|drop [action]` row per task. Every line arrives wrapped in Effect's pretty log prefix (`[HH:MM:SS.mmm] INFO (#1): `) and, when the child inherits `FORCE_COLOR`, in colour; both are stripped first. The id in a row is the resource's fully qualified name, the identity it is persisted under, so every check that binds a row to a resource resolves it to the persisted FQN it names exactly — a planned create to that FQN recorded after the apply and not before it, a convergence row to that FQN recorded for it — and refuses when it is absent. A plan that prints one FQN twice cannot come from the renderer and is refused (`AMBIGUOUS_RESOURCE`). The summary counts `create`, `update`, `adopted`, `replace`, `delete` and `orphaned` resources, then `N binding changes` and `N tasks`; `noop` rows print but are not counted. A binding row extends its resource's FQN by `/name`, and so does a resource inside a namespace, so when a resource named `Parent` is followed by rows tagged `Parent/...` the renderer gives no evidence which are its bindings and which are namespaced resources; the summary's counts decide, the one reading that adds up is taken, a plan the counts can place in more than one way is refused (`ambiguous-rows`; the counts are global, so two such resources in one plan couple and are refused together), the search is memoised so a plan of many such resources costs rows times counts and never the product of their readings, and a `noop` row under such a resource — placed by no count and read by no decision — is read as a binding. `orphaned` (a retained resource leaving the stack) is refused wherever `delete` is; `adopted` (a resource the provider already finds, planned only for a record with no prior state) is permitted wherever `create` is. The adapter is bound to `PLAN_OUTPUT_ALCHEMY_VERSION`, which is `ALCHEMY_BASELINE.alchemy`, and the lifecycle refuses an installed Alchemy of any other version (`UNSUPPORTED_ALCHEMY_VERSION`) before any child runs, so a renderer change cannot be read as a plan with different effects. The version is read from the manifest of the package that owns the CLI the children run — `alchemy/bin/alchemy.js` is resolved from the consumer and the nearest `package.json` named `alchemy` above it is read from disk — because `alchemy/package.json` is not on the package's `exports` map and cannot be resolved as a specifier. The adapter fails on output it cannot account for — no summary, two summaries, an unknown action, a summary it cannot parse, a count that does not match the rows, rows the counts place in more than one way — and reports only the reason, never the output. An effect it could not account for is never reported as zero.
|
|
710
|
+
|
|
711
|
+
What stays with the consumer: the resource graph, the credentials and environment the child runs with, the stage table, the retained-identity markers, the first-deploy authorization list, the state store's configuration, and health checks after the deploy. The Paitronage stack keys, HQ's frozen identities, and every other product value are inputs. There is no `psf` command for the lifecycle: the capabilities are consumer code, not flags, so the consumer calls the function from its own script.
|
|
712
|
+
|
|
713
|
+
#### Lifecycle guards
|
|
714
|
+
|
|
715
|
+
```ts
|
|
716
|
+
import {
|
|
717
|
+
assertDestroyLeftNothing,
|
|
718
|
+
credentialPreflight,
|
|
719
|
+
firstDeployAuthorization,
|
|
720
|
+
secretNamePolicy,
|
|
721
|
+
} from "@patronage/factory-ci/alchemy";
|
|
722
|
+
```
|
|
723
|
+
|
|
724
|
+
Four checks that surround an Alchemy run. Paitronage and firedup each built the first one and the last one, and paitronage built all four, so the check repeats and the policy does not: the account, the permission list, the eligible stages, the authorized plans, the state store, and the secret names are all inputs.
|
|
725
|
+
|
|
726
|
+
`credentialPreflight({ accountId, environment, requiredPermissionGroups, resolveCredential, resourcesFor?, source, tokenKind? })` proves the deploy holds the credential it claims to. `source: "hosted"` requires `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` in the environment and requires the account to be the one the deploy allows; `source: "trusted-local"` requires that neither is there, because a local run resolves its credential from the project's own secret manager and an ambient token means the run is not the run it says it is. `resolveCredential` is where that resolution happens — a 1Password read, a hosted environment read, whatever the project uses. `tokenKind` selects the verification endpoint: `"account"` (the default) uses `/accounts/<accountId>/tokens/verify`; `"user"` uses `/user/tokens/verify`. Token ownership is independent of credential source and permission scope: an account-scoped user token still selects `"user"`. Unknown kinds refuse before resolving credentials; there is no endpoint fallback. Both kinds enforce the same account, receipt, permission, and resource checks. The token is then verified against Cloudflare, matched to the reviewed policy document by token id, and reduced to permission-group names, which must equal `requiredPermissionGroups` with nothing missing, extra, or repeated. `resourcesFor` names the exact resource identifiers a group may be scoped to and defaults to the account resource, which is how a zone-scoped group is declared. On the hosted path the resolved token must be the environment token, compared and never named, because that is the token the deploy will use. A `CloudflareCredentialUnavailableError` means Cloudflare could not be asked, or the project's own resolver failed; a resolver failure is reported as one fixed message with no `cause`, because a secret-manager error can quote the value it was reading. Every other failure means the credential is wrong. No error and no result carries a credential value.
|
|
727
|
+
|
|
728
|
+
`firstDeployAuthorization({ authorizedHashes, planText, sourceSha, stack, stage })` binds the one deploy no earlier state can constrain. The plan, the target, and the reviewed source hash to one value, and that value must appear on a list the project owns. `sourceSha` is required. A full lowercase 40-character SHA binds the plan to that commit; `null` binds the plan to no commit, and that is the project's explicit choice rather than a field it forgot — an omitted field and a deliberate `null` are different decisions, so only the second one is spellable. Anything else, an empty string included, is refused. It fails closed on an empty list, a list entry that is not a sha256 hash, an empty plan, plan output that is not well-formed, plan output the plan adapter cannot read, an unlisted plan, and a stack, stage, or source SHA carrying surrounding whitespace — padding would mint a second hash for one target. The refusal names the hash to review, never the plan. `firstDeployPlanHash` computes the same value on its own, for the run that produces a plan for an operator to read.
|
|
729
|
+
|
|
730
|
+
What the hash binds is the plan, not the run that printed it (#1232). `planText` is read by the same `parsePlanEffects` adapter above and reduced to a canonical form first: the `Plan:` summary line, every row under it as its tag and action — resource rows, binding rows and task rows alike, `noop` rows included, sorted and with duplicates kept — and the reading of those rows the adapter arrives at, the resource list and the binding-change count. That canonical form, the stack, the stage and the source SHA are what hash. The logger prefix Alchemy puts on every line (`[HH:MM:SS.mmm] INFO (#1): `), the run's own elapsed durations (`Plan ready (2.9s)`), ANSI colour, the apply-session and progress lines after the rows, and the order the rows were printed in are all facts about one process rather than about the plan, and none of them is bound.
|
|
731
|
+
|
|
732
|
+
Row order is not bound; the reading of the rows is, and those are not the same fact. A binding row and a resource inside the sibling's namespace print alike, so `[Parent/bound] create` and `[Parent/Zed] create` under `[Parent] create` are one row multiset that creates `Parent` and `Parent/Zed` in one order and `Parent` and `Parent/bound` in the other. Order alone carried that; the canonical form states it, so sorting the rows cannot make two plans that create different resources agree. A rename, a changed action, an added or removed row, a renamed binding whose count is unchanged, a row read as a resource in one plan and a binding in the other, or a different stack, stage or source each change the hash; so does output the adapter refuses, which throws a `PlanEffectsError` rather than hashing. Before this change the verbatim output was hashed, so two graph-identical runs disagreed and a reviewed plan could never be deployed: every first-deploy hash issued earlier is invalidated, and those hashes were unreproducible in any case.
|
|
733
|
+
|
|
734
|
+
`assertDestroyLeftNothing({ stack, stage, stateReader })` is the postcondition that a zero exit does not prove: after `destroy`, the state store lists nothing for the stage. The project supplies `stateReader`, because only the project knows which store it configured. A reader that returns anything other than a list of non-blank resource identifiers is a failure, not an empty stage — a check that cannot fail is not a check. A padded stack or stage is refused for the same reason: it addresses a stage the store does not know, which answers empty.
|
|
735
|
+
|
|
736
|
+
`secretNamePolicy({ names, values })` builds the `redact` function `executeAlchemyEntry` already takes. It is a policy, not a mechanism. The project passes the names; this package ships no secret-name list and infers none from a name pattern. The policy is fail-closed at construction: a declared name with no value, a value under eight characters, or an empty `names` list handed a populated `values` map, throws before there is any output to redact, rather than quietly covering less than the caller believes. Empty names beside empty values is the one pass-through: a project with no secrets in its Alchemy output declares none. Values are trimmed before replacement, so redaction never swallows the line break after a secret, and longer values are replaced first, so a secret containing another secret leaves no fragment.
|
|
737
|
+
|
|
738
|
+
Two things paitronage does are deliberately not here. Stage eligibility is dropped: which stages may take a first deploy is project policy, and `firstDeployAuthorization` answers only whether this exact plan was authorized. The live zone lookup on the hosted path stays with the consumer: which zones an account may deploy into is project policy, and this package makes one Cloudflare call, against the token, not against the account's inventory. Two things that were once left out now live in `runAlchemyLifecycle` above: the plan-read-only before/after state capture, which caught a real write in the shared D1 store (#1074), and the first-deploy rule that a plan may only create or adopt, which the plan adapter can now read.
|
|
739
|
+
|
|
740
|
+
#### `evaluateStack`
|
|
741
|
+
|
|
742
|
+
```ts
|
|
743
|
+
import { evaluateStack } from "@patronage/factory-ci/alchemy";
|
|
744
|
+
|
|
745
|
+
const graph = await evaluateStack({
|
|
746
|
+
name: "hq",
|
|
747
|
+
program,
|
|
748
|
+
stage: "placeholder",
|
|
749
|
+
});
|
|
750
|
+
// { resources: [{ id, type, props, upstreamByProp }], bindings: [{ worker, name, type, target? }] }
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
`evaluateStack` runs a stack program at one stage and returns the graph Alchemy would plan, with no state store and no network. It wraps Alchemy's `Plan.make`: the program registers its resources under a `Stack` service, then the plan builds under `inMemoryState()` at the requested `Stage`. Every provider answers its `read` and `list` probes with "absent", so the cold-adoption probe `Plan.make` makes for a resource with resolved props and no prior state never leaves the process. A stage the program returns from early (paitronage's `placeholder` stage) evaluates to an empty graph.
|
|
754
|
+
|
|
755
|
+
`program` is the effect the consumer hands `Alchemy.Stack`, not the `Alchemy.Stack(...)` value. The value captures the consumer's real `providers` and `state` layers, and at Alchemy 2.0.0-beta.77 `Cloudflare.providers()` resolves credentials when its layer builds (`Credentials.fromAuthProvider` inside `CloudflareApiLive`), so evaluating the value cannot stay credential-free. Export the program next to the stack:
|
|
756
|
+
|
|
757
|
+
```ts
|
|
758
|
+
export const program = Effect.gen(function* () {
|
|
759
|
+
/* ... */
|
|
760
|
+
});
|
|
761
|
+
export default Alchemy.Stack("hq", { providers, state }, program);
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
Pass `providers` when the program depends on hand-written provider layers. Every provider that layer registers keeps its identity (`stables`, `aliases`, `diff`) and loses its probes; an unregistered resource type still evaluates. Each graph resource carries the `LogicalId`, `Type`, and raw `Props` of its plan node, so a prop may hold an unresolved Alchemy output. `upstreamByProp` names, per top-level prop, the logical ids that prop's value references, which is the only way to read a cross-resource reference out of raw props: an output is a function, so the prop that holds it says nothing on its own. A prop that references nothing carries no key. The references are kept per prop and never pooled into one list, so a caller asking which resources one prop names is never answered with an id a different prop mentioned. Each binding row comes from Alchemy's Worker binding channel: `worker` is the host's logical id, `name` and `type` are the strings Alchemy emits (`d1`, `kv_namespace`, `secrets_store_secret`, and so on), and `target` is the logical id of the resource the row references, when it references one.
|
|
765
|
+
|
|
766
|
+
The caller's `providers` layer is **built** before its probes are stubbed: `evaluateStack` wraps that layer, and Alchemy's own lookup resolves each provider out of it before `read` and `list` are replaced. So any side effect a layer performs at construction — a credential read, a network call, a file write — is the caller's, and happens. This is why `Cloudflare.providers()` must not be passed: at beta.77 it resolves credentials when its layer builds (`Credentials.fromAuthProvider` inside `CloudflareApiLive`), before there is anything to stub. The no-network guarantee covers evaluation, not layer construction: pass only layers whose construction is inert.
|
|
767
|
+
|
|
768
|
+
The helper decides nothing about the graph. Invariants over it are separate exports; `assertUrlImpliesAuth` below is the first.
|
|
769
|
+
|
|
770
|
+
#### `assertUrlImpliesAuth`
|
|
771
|
+
|
|
772
|
+
```ts
|
|
773
|
+
import { assertUrlImpliesAuth } from "@patronage/factory-ci/alchemy";
|
|
774
|
+
|
|
775
|
+
assertUrlImpliesAuth(graph, {
|
|
776
|
+
allowlist: [
|
|
777
|
+
{
|
|
778
|
+
reason: "Public marketing site, no data behind it.",
|
|
779
|
+
worker: "marketing",
|
|
780
|
+
},
|
|
781
|
+
],
|
|
782
|
+
authBindingName: /_TOKEN$/u,
|
|
783
|
+
});
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
Every publicly reachable Worker in the graph must declare how it is authenticated. The cheapest way to publish an unauthenticated admin surface is to add `workersDev: true`, a `domain`, or a route to a Worker that never had one: nothing fails, and the only record of the decision is a diff nobody re-read.
|
|
787
|
+
|
|
788
|
+
A Worker is publicly reachable when the stack **declares** it so — `workersDev` on (the boolean, or a config object that does not turn both the stable URL and version previews off), a `domain`, or a non-empty `routes` list. A route is a hostname pattern on a zone the account owns, so it is as public as a domain is. Alchemy's own default for `workersDev` is on, so a Worker that declares none of the three still gets a `workers.dev` URL, and this check leaves it alone: a rule inferred from a default fires on every Worker in every stack and is waived everywhere within a week. A project that wants the default stated declares `workersDev: false` on the Workers that are private.
|
|
789
|
+
|
|
790
|
+
A reachable Worker passes on any one of four guards. It enrolls in Cloudflare Access through its own `access` prop. A `Cloudflare.Access.Application` resource declares an `all_workers` destination, or a `worker` destination whose own `upstreamByProp.destinations` names it — an application that also declares a `preview_worker` destination credits nobody, because the graph resolves a destination's worker reference to a logical id but not to the destination holding it, and a preview-only reference protects preview URLs rather than the production one. It carries a `secrets_store_secret` binding whose name `authBindingName` accepts, as a `RegExp` or a predicate. Or `allowlist` names it with a reason; an empty reason fails louder than the bare Worker, because the entry claims a decision nobody made.
|
|
791
|
+
|
|
792
|
+
What counts as a guard is the project's call: the binding-name matcher and the allowlist are both caller-supplied, and this package ships no worker names and no name pattern. Every offending Worker is named in one `UrlImpliesAuthError`, whose `violations` carry the worker and whether it was unauthenticated or allowlisted without a reason.
|
|
793
|
+
|
|
794
|
+
The factory's own security review prompt carries the same rule in prose, so a repository with no graph check still gets it read by a reviewer.
|
|
795
|
+
|
|
796
|
+
### Alchemy fleet baseline
|
|
797
|
+
|
|
798
|
+
```ts
|
|
799
|
+
import { ALCHEMY_BASELINE, assertAlchemyBaseline } from "@patronage/factory-ci";
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
`ALCHEMY_BASELINE` is the exact `alchemy` and `effect` pair the fleet moves together on: `{ alchemy: "2.0.0-beta.77", effect: "4.0.0-rc.112" }`. It is a plain constant on the root entry — it imports neither package — so any consumer can read it without installing the `./alchemy` subpath's peers.
|
|
803
|
+
|
|
804
|
+
`assertAlchemyBaseline({ packageJson })` is a consumer contract helper: it fails when the consumer's own `dependencies` or `devDependencies` pin `alchemy` or `effect` to anything other than the baseline, and it fails when only one of the pair is present. Alchemy peers on Effect, so an unpinned auto-installed Effect can drift outside the baseline while a lone `alchemy` pin would otherwise pass. Both packages remaining absent is not drift — they are optional peers of the subpath, so a consumer that never imports it, such as this package's own CLI, carries neither and passes. The pin is exact, not a range: the fleet is pre-1.0 and moves together, so a range would let one project drift silently ahead of or behind the rest. `assertAlchemyBaseline` reads only the object it is handed; it never walks the filesystem or reads a lockfile. Call it from a consumer's own contract test, passing that consumer's parsed `package.json`.
|
|
805
|
+
|
|
806
|
+
The baseline bumps only in a lockstep release: the same commit that bumps `@patronage/factory-ci`'s own `alchemy`/`effect` devDependencies and the `./alchemy` subpath's peer ranges (ADR 0031) also bumps `ALCHEMY_BASELINE`, so the constant a consumer's contract test checks against can never point at a version the subpath itself has moved past.
|
|
168
807
|
|
|
169
808
|
### Published-package contract
|
|
170
809
|
|
|
171
810
|
The tests pack the actual tarball, extract it into a throwaway external consumer, import the built package root without the workspace's `development` condition, assert the exact runtime exports, and exercise the workflow and stage interfaces. This catches source-only successes, stale or missing `dist/`, exports-map mistakes, and accidental tarball growth before the attended release check.
|
|
172
811
|
|
|
812
|
+
The same consumer proves the ADR 0031 rule from the packed bytes rather than from source: it imports `@patronage/factory-ci/alchemy` with neither `alchemy` nor `effect` installed, and it bundles the packed `dist/index.js` so esbuild's own resolution reports every bare specifier the root graph still needs. Either package appearing in that list fails the build.
|
|
813
|
+
|
|
814
|
+
A second suite packs **both** `@patronage/factory-ci` and `@patronage/alchemy-d1-state` and installs the two tarballs side by side in one consumer, over one copy of `alchemy` and one of `effect` — the pairing a real deploy runs. It packs with `pnpm`, not `npm`, because `publishConfig.exports` is applied by pnpm and ignored by npm: packing with npm would install a manifest no consumer ever sees. It then runs a whole `runAlchemyLifecycle` deploy and destroy from the tarballs, with a real child process adopting the parent's stage lease and writing through the packed adapter into local SQLite.
|
|
815
|
+
|
|
816
|
+
Three facts only that shape can establish. The subpath's deep exports run from `dist` — a manifest that lost `./alchemy` once broke every lifecycle call while a source-tree import stayed green. The **adapter** and the consumer resolve one copy of `alchemy`: an error the adapter raises is `instanceof` the `StateStoreError` class the consumer imported, which a class-name comparison would not catch, because a duplicate names its class the same. And both tarballs declare the same peer ranges, read from the installed manifests and asserted against the installed pins and `ALCHEMY_BASELINE` together.
|
|
817
|
+
|
|
818
|
+
That second claim is narrow on purpose, and the suite says so where it is made. The `instanceof` compares exactly two things — the class the adapter raised and the class the consumer imported — so it detects a second copy of `alchemy` resolved by **the adapter tarball**, and only that. Three things it does not cover, none of them asserted anywhere here: a duplicate under this package's own tarball, which leaves the whole suite green because the detector never compares a class this package raised; what a duplicate would go on to break, since Alchemy's services are keyed by string and a faithful second copy still satisfies the same `State` key; and `effect`, where a second copy under the adapter with a distinct `runPromise` also leaves the suite green, because Effect values are plain data and cross copies.
|
|
819
|
+
|
|
820
|
+
## Adopting the shared lifecycle
|
|
821
|
+
|
|
822
|
+
`runAlchemyLifecycle` owns the order a plan, a deploy or a destroy runs in. A consumer hands it typed policy and two narrow capabilities — a state store and an Alchemy entry — and cannot call the steps in another order, because it does not call the steps.
|
|
823
|
+
|
|
824
|
+
### What adoption deletes
|
|
825
|
+
|
|
826
|
+
- **The local plan parser.** Plan text is read by `parsePlanEffects` inside the operation. A consumer that still greps plan output is running a second implementation of a contract that moved.
|
|
827
|
+
- **Local sequencing.** Any plan-then-apply-then-converge routine becomes the one call.
|
|
828
|
+
- **Local destructive-plan gates and stage guards** written as ad-hoc conditionals. They become the `stages` table and `retainedIdentities`.
|
|
829
|
+
- **Push-diff production demand.** Demand comes from the last trusted successful deployment receipt, never from a push's before/after commits.
|
|
830
|
+
- **Setup steps located by array position or display name.** They become `setupStepsForRoles`.
|
|
831
|
+
- **`paths:` filters on a deploy trigger.** A path filter asks whether this push touched the project, which is the wrong question once a shared-package change can reach the default branch and fail to deploy.
|
|
832
|
+
|
|
833
|
+
### What stays with the consumer
|
|
834
|
+
|
|
835
|
+
The resource graph and its physical names; every credential the graph needs; the stage table; the retained-identity markers; the first-deploy authorization list; the state store's own configuration; product health policy; and the lease holder label, which must identify one run rather than be typed by an operator.
|
|
836
|
+
|
|
837
|
+
Convergence proves the control plane agrees with the state store. It cannot prove the product serves, so a consumer that needs that runs its own health gate after the operation and before it records a successful deployment.
|
|
838
|
+
|
|
839
|
+
### Contract and schema changes
|
|
840
|
+
|
|
841
|
+
| Change | Package | What an adopter does |
|
|
842
|
+
| --- | --- | --- |
|
|
843
|
+
| `runAlchemyLifecycle`, `AlchemyLifecycleError` with enumerated `code`/`phase`/`mutation` | `@patronage/factory-ci/alchemy` | Replace local sequencing with one call; print the enumerated fields, never free text. |
|
|
844
|
+
| `StageStateStore` | `@patronage/factory-ci/alchemy` | Structural. `@patronage/alchemy-d1-state`'s `buildService` already satisfies it. |
|
|
845
|
+
| `acquireStageOwnership`, `StageOwnership`, `snapshotStage`, `ownership.adoptFrom` | `@patronage/alchemy-d1-state` | New surface, no migration. The ownership row is a second reserved sentinel FQN in the existing `(stack, stage, fqn, data)` shape, one row per owned stage. |
|
|
846
|
+
| Deployment receipts | `psf production:impact` | Grant `deployments: write` on the deploying job and take the receipt-binding step name from the generator, never by hand. |
|
|
847
|
+
| `setupStepsForRoles`, `SETUP_STEP_ROLES` | `@patronage/factory-ci` | Select setup steps by role. |
|
|
848
|
+
|
|
849
|
+
Neither package's peer range moved: both accept `alchemy >=2.0.0-beta.63 <3` and `effect >=4.0.0-beta.98 <5`, and the qualified installed pair is the one in `ALCHEMY_BASELINE`.
|
|
850
|
+
|
|
851
|
+
### What a consumer still owes its own tests
|
|
852
|
+
|
|
853
|
+
HQ, the first production consumer, exercises one path: a `deploy` into a protected stage, with `adopt`, retained identities, an empty non-convergent list, and a lease every child adopts. Everything below is shared behaviour HQ's production path never reaches. None of it is covered by a production run, so a consumer that depends on one owes its own qualification against its own graph.
|
|
854
|
+
|
|
855
|
+
The right-hand column says what this repository proves about each, because "covered by tests" and "covered through the operation" are different claims:
|
|
856
|
+
|
|
857
|
+
| # | Path | Covered here |
|
|
858
|
+
| --- | --- | --- |
|
|
859
|
+
| 1 | `destroy`, including `DESTROY_RESIDUE` and all three cleanup outcomes | Yes, through `runAlchemyLifecycle`. All three outcomes — `removed`, `occupied` and `absent` — are asserted on the operation's result, not on a direct call to the adapter |
|
|
860
|
+
| 2 | `firstDeploy` — the plan-hash authorization for an empty protected stage | Yes, through `runAlchemyLifecycle` |
|
|
861
|
+
| 3 | `STAGE_HELD` contention between two runs on one stage | Yes, through `runAlchemyLifecycle` |
|
|
862
|
+
| 4 | A `deploy` into a disposable stage: the admission branch for an unprotected stage | Yes, through `runAlchemyLifecycle` |
|
|
863
|
+
| 5 | `nonConvergentResources` — the tolerated-`update` branch | Yes, through `runAlchemyLifecycle` |
|
|
864
|
+
| 6 | `policy.ownershipTtlMillis` | Yes — the lease window the database records, at the one acquire site every operation shares. Added by #1079. **Note the adoption behaviour it exposes**: adoption resets `expiresAt` to the database's current time plus the **adopting** process's TTL, without taking the maximum against the stored expiry, so it can shorten a parent's window as easily as lengthen it. A shortened window fails closed — the fenced renewal reports `OWNERSHIP_LOST` rather than proceeding — and exclusivity is unaffected. HQ never notices, because both sides take the ten-minute default. `alchemy-d1-state`'s README carries the full note |
|
|
865
|
+
| 7 | The `bundle` entry mode, and the `alias` map with it | Yes, through `runAlchemyLifecycle`, including the `alias` map: the operation bundles an entry that imports an aliased module, and the test reads the bundle the operation produced and asserts the aliased module's marker is in it. Losing the alias does not fail the build — `bundleAlchemyEntry` defaults an unresolved package to external, so the import survives unresolved and the bundle is still written — it fails that marker assertion. A consumer that hands the operation a `bundledEntry` never bundles |
|
|
866
|
+
| 8 | `LEASE_RELEASE_FAILED` — a store outage at exactly the release | Yes, through `runAlchemyLifecycle` |
|
|
867
|
+
| 9 | More than one stack, or a stack claiming more than one stage | **Only at the stage table.** `stagePolicy` is tested with multi-stack tables; no test drives `runAlchemyLifecycle` with one |
|
|
868
|
+
|
|
173
869
|
## No configuration surface
|
|
174
870
|
|
|
175
871
|
Functions take plain typed objects. Proof and preview configuration lives in the canonical `software-factory.profile.json` schema, never in this package (ADR 0021); consumers pass the relevant profile policy directly at generation time.
|
|
@@ -182,8 +878,14 @@ The credential env-block helper that the audit found repeated was deliberately c
|
|
|
182
878
|
|
|
183
879
|
## Releases
|
|
184
880
|
|
|
185
|
-
Attended and hand-cut, on the same terms as `@patronage/alchemy-d1-state`: bump the version, run the workspace checks, read the `npm pack --dry-run` file list, publish, tag `factory-ci@<version>`. There is no changesets setup and no automatic release trigger, by design. Consumers pin exact versions.
|
|
881
|
+
Attended and hand-cut, on the same terms as `@patronage/alchemy-d1-state`: bump the version, run the workspace checks, read the `npm pack --dry-run` file list, build and approve one pnpm tarball, publish that exact tarball with an explicit channel tag, then tag `factory-ci@<version>`. Publishing the package directory is not allowed because its `prepack` build would replace the reviewed bytes. There is no changesets setup and no automatic release trigger, by design. Consumers pin exact versions.
|
|
186
882
|
|
|
187
883
|
## License
|
|
188
884
|
|
|
189
885
|
MIT.
|
|
886
|
+
|
|
887
|
+
### Hosted preview receipts
|
|
888
|
+
|
|
889
|
+
`factoryPreviewReceiptWorkflow({ target: "preview:app" })` supplies a `beginStep`, `completionSteps`, `invalidateStep`, and job `permissions` for `psf preview:receipt`. Place `beginStep` before the selected target's first mutation, then the consumer deploy and smoke steps, then `completionSteps`. Keep the bind step name intact. Apply the target selection guard to the begin step; completion requires its nonempty intent output. Canceled runs leave the intent pending. Place `invalidateStep` before cleanup, including cleanup of a failed deployment that never registered a pass.
|
|
890
|
+
|
|
891
|
+
This artifact does not select targets, deploy, smoke, or certify current health. The consumer's reviewed default-branch profile declares publisher workflow paths, job names/IDs, required deploy/smoke step names, cleanup paths, and targets under `extensions.hostedPreviewReceipts`. The CLI reads that profile from GitHub at an immutable default-branch SHA. Candidate workflows must have the same blob as that reviewed version for a receipt to be trusted. See the software-factory command reference for the profile shape and ordered rollout. This source addition does not deploy or adopt the contract in Firedup.
|