Skip to content

Commit f721bb1

Browse files
authored
feat(snapshot): section snapshot contract, engine, round-trip harness, and the first sections (#140)
1 parent 959e226 commit f721bb1

66 files changed

Lines changed: 2262 additions & 45 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎COVERAGE.md‎

Lines changed: 18 additions & 18 deletions
Large diffs are not rendered by default.

‎knip.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"src/schema.ts",
66
".github/scripts/*.ts",
77
"**/*.test.ts",
8+
"test/sections/snapshot-rows/*.ts",
89
"src/upstream-gaps/gap.ts"
910
],
1011
"project": ["src/**/*.ts", "test/**/*.ts", ".github/scripts/**/*.ts"]

‎src/engine/secrets.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
*
77
* a target repository's own settings.yml -> target
88
* the single-repo file, a central file, the defaults document -> operator
9+
*
10+
* The snapshot direction lives here too: snapshotSecretReference mints the reference a snapshot
11+
* writes for a live secret whose value GitHub never reveals.
912
*/
1013

1114
import type { SectionKey, SettingsFile } from "../schema.js";
1215
import type { SectionModule } from "../sections/contract/module.js";
13-
import type { SettingsSource, SourcedSecretValue } from "./secret-refs.js";
16+
import { type SettingsSource, type SourcedSecretValue, validateSecretRef } from "./secret-refs.js";
1417

1518
export interface SectionSecretValue extends SourcedSecretValue {
1619
section: SectionKey;
@@ -33,3 +36,36 @@ export function collectSecretValues(
3336
}
3437
return out;
3538
}
39+
40+
/** An environment variable a snapshot asks the operator to export, and its whole-value reference. */
41+
export interface MintedSecretReference {
42+
readonly variable: string;
43+
readonly reference: string;
44+
}
45+
46+
/**
47+
* The one mint behind every reference a snapshot writes: the variable's `$NAME` form, proved by
48+
* the same grammar and reserved-prefix rule the settings file enforces, so a snapshot can never
49+
* emit a reference an apply would refuse. `label` names the secret for the BUG prose.
50+
*/
51+
export function mintSecretReference(variable: string, label: string): MintedSecretReference {
52+
const reference = `$${variable}`;
53+
const checked = validateSecretRef(reference, "operator", label);
54+
if (!checked.ok) {
55+
throw new Error(
56+
`BUG: the snapshot minted a reference the settings file refuses: ${checked.error}`,
57+
);
58+
}
59+
return { variable, reference };
60+
}
61+
62+
/**
63+
* `SECRET_` leads so a store named like a runner namespace (`ACTIONS_*`) still mints a legal
64+
* reference; the store follows so two stores holding one secret name never share a variable.
65+
*/
66+
export function snapshotSecretReference(store: string, secretName: string): MintedSecretReference {
67+
return mintSecretReference(
68+
`SECRET_${store.toUpperCase()}_${secretName}`,
69+
`the ${store} secret ${secretName}`,
70+
);
71+
}

‎src/engine/snapshot.ts‎

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
/**
2+
* The read-only twin of runForRepo in ./orchestrate.ts, honoring the sections allowlist by the
3+
* same rule.
4+
*/
5+
6+
import { stringify as stringifyYaml } from "yaml";
7+
import type { RepoRef } from "../discovery/targets.js";
8+
import type { GithubClient } from "../github/api.js";
9+
import type { Io } from "../io.js";
10+
import { describeProblem } from "../problem.js";
11+
import type { SectionKey } from "../schema.js";
12+
import {
13+
type EndpointDecl,
14+
endpointPath,
15+
matchesTemplate,
16+
} from "../sections/contract/endpoints.js";
17+
import { PermissionDenied } from "../sections/contract/errors.js";
18+
import {
19+
concealedAbsenceNote,
20+
gatedAbsentRead,
21+
type SectionSnapshot,
22+
snapshotUnsupportedNote,
23+
} from "../sections/contract/module.js";
24+
import { planContext } from "../sections/contract/plan.js";
25+
import { SECTIONS } from "../sections/registry.js";
26+
import { type ValidatedSettings, validateSettingsDoc } from "./orchestrate.js";
27+
import type { SectionSelection } from "./section-selection.js";
28+
29+
export interface SnapshotOptions {
30+
/** The target repository, parsed at the caller's validated boundary. */
31+
repo: RepoRef;
32+
/**
33+
* The allowlist. Its required set goes unread: required-sections governs what must apply, and
34+
* a snapshot never writes, so a denial classifies on onMissingPermission alone.
35+
*/
36+
sections: SectionSelection;
37+
onMissingPermission: "fail" | "warn";
38+
}
39+
40+
/**
41+
* One section's end state: read back ("snapshot", its notes in detail), denied under the warn
42+
* policy ("skipped"), without a snapshot handler ("unsupported", the reason in detail), or failed.
43+
*/
44+
interface SectionSnapshotOutcome {
45+
key: SectionKey;
46+
status: "snapshot" | "skipped" | "unsupported" | "failed";
47+
detail: string[];
48+
}
49+
50+
/**
51+
* The document exists only when the run did not fail: a denial under the fail policy and a
52+
* section producing a value its own schema rejects both withhold it, so a failed result cannot be
53+
* rendered by mistake. "partial" says a section was skipped or failed without failing the run.
54+
*/
55+
export type SnapshotResult =
56+
| {
57+
repo: string;
58+
result: "snapshot" | "partial";
59+
settings: ValidatedSettings;
60+
outcomes: SectionSnapshotOutcome[];
61+
}
62+
| { repo: string; result: "failed"; settings?: never; outcomes: SectionSnapshotOutcome[] };
63+
64+
/** A snapshot result that carries a document. */
65+
export type RenderableSnapshot = Extract<SnapshotResult, { settings: ValidatedSettings }>;
66+
67+
/** What a section without live state says for itself in the outcome and the file header. */
68+
const NOTHING_TO_DECLARE = "nothing exists on the repository, so the section is omitted";
69+
70+
/** A line under its section's key, prefixed once: a section's own notes already lead with the key. */
71+
function underKey(key: SectionKey, line: string): string {
72+
const own = line.startsWith(key) && /^[:.[]/.test(line.slice(key.length));
73+
return own ? line : `${key}: ${line}`;
74+
}
75+
76+
/**
77+
* The client as one section's snapshot sees it, reporting whether a GET on `read`'s route
78+
* answered 404 (the observation the concealed-absence note is keyed on). Null passes through.
79+
*/
80+
function watchingNotFound(
81+
api: GithubClient,
82+
read: EndpointDecl | null,
83+
seen: { notFound: boolean },
84+
): GithubClient {
85+
if (read === null) {
86+
return api;
87+
}
88+
const template = endpointPath(read.route);
89+
return {
90+
tryRequest: async (method, path, payload, options) => {
91+
const result = await api.tryRequest(method, path, payload, options);
92+
if (
93+
"error" in result &&
94+
result.error.status === 404 &&
95+
method === "GET" &&
96+
matchesTemplate(template, path)
97+
) {
98+
seen.notFound = true;
99+
}
100+
return result;
101+
},
102+
tryGraphql: (op, variables, slug) => api.tryGraphql(op, variables, slug),
103+
};
104+
}
105+
106+
/** Read one repository's supported sections back into a validated settings document. */
107+
export async function snapshotRepository(
108+
api: GithubClient,
109+
opts: SnapshotOptions,
110+
io: Io,
111+
): Promise<SnapshotResult> {
112+
const outcomes: SectionSnapshotOutcome[] = [];
113+
const document: Record<string, unknown> = {};
114+
let partial = false;
115+
let failed = false;
116+
117+
for (const section of SECTIONS) {
118+
if (opts.sections.only.size > 0 && !opts.sections.only.has(section.key)) {
119+
continue;
120+
}
121+
if (section.snapshot === undefined) {
122+
outcomes.push({
123+
key: section.key,
124+
status: "unsupported",
125+
detail: [snapshotUnsupportedNote(section)],
126+
});
127+
continue;
128+
}
129+
const absentRead = gatedAbsentRead(section);
130+
const seen = { notFound: false };
131+
let snapshot: SectionSnapshot;
132+
try {
133+
snapshot = await section.snapshot(
134+
planContext(section, watchingNotFound(api, absentRead, seen), opts.repo),
135+
);
136+
} catch (error) {
137+
if (error instanceof PermissionDenied) {
138+
const status = opts.onMissingPermission === "warn" ? "skipped" : "failed";
139+
if (status === "skipped") {
140+
io.annotate("warning", `${section.key}: skipped - ${error.detail}`);
141+
partial = true;
142+
} else {
143+
io.annotate("error", `${section.key}: not snapshotted - ${error.detail}`);
144+
failed = true;
145+
}
146+
outcomes.push({ key: section.key, status, detail: [error.detail] });
147+
continue;
148+
}
149+
const message = error instanceof Error ? error.message : String(error);
150+
const prefixed = message.startsWith(`${section.key}:`)
151+
? message
152+
: `${section.key}: ${message}`;
153+
io.annotate("error", prefixed);
154+
outcomes.push({ key: section.key, status: "failed", detail: [prefixed] });
155+
partial = true;
156+
continue;
157+
}
158+
for (const note of snapshot.notes) {
159+
io.annotate("notice", underKey(section.key, note));
160+
}
161+
if (snapshot.value === undefined) {
162+
// Chosen at the engine level so every absent-posture section behaves alike: the 404 keeps
163+
// its "nothing exists" reading, and the note names the denial it could also be. Keyed on an
164+
// observed 404, so an empty 200 listing earns no note.
165+
const concealed =
166+
absentRead !== null && seen.notFound ? concealedAbsenceNote(section, absentRead) : null;
167+
if (concealed !== null) {
168+
io.annotate("notice", concealed);
169+
}
170+
outcomes.push({
171+
key: section.key,
172+
status: "snapshot",
173+
detail: [...snapshot.notes, ...(concealed === null ? [] : [concealed]), NOTHING_TO_DECLARE],
174+
});
175+
continue;
176+
}
177+
// Validated per section so the rejection names its producer: a value the section's own
178+
// schema refuses is a bug in that section, never a document to hand out.
179+
const verdict = validateSettingsDoc(
180+
{ [section.key]: snapshot.value },
181+
`the ${section.key} snapshot of ${opts.repo.slug}`,
182+
new Set(),
183+
io,
184+
);
185+
if (verdict.isErr()) {
186+
const detail = `BUG: ${section.key} produced a snapshot its own schema rejects - ${describeProblem(verdict.error)}`;
187+
io.annotate("error", detail);
188+
outcomes.push({ key: section.key, status: "failed", detail: [...snapshot.notes, detail] });
189+
failed = true;
190+
continue;
191+
}
192+
document[section.key] = verdict.value[section.key];
193+
outcomes.push({ key: section.key, status: "snapshot", detail: [...snapshot.notes] });
194+
}
195+
196+
if (failed) {
197+
return { repo: opts.repo.slug, result: "failed", outcomes };
198+
}
199+
// The brand's one mint, over the already-parsed fragments: every section validated alone
200+
// above, so the whole cannot fail.
201+
const verdict = validateSettingsDoc(document, `the snapshot of ${opts.repo.slug}`, new Set(), io);
202+
if (verdict.isErr()) {
203+
throw new Error(
204+
`BUG: the assembled snapshot of ${opts.repo.slug} failed validation after every section validated on its own: ${describeProblem(verdict.error)}`,
205+
);
206+
}
207+
return {
208+
repo: opts.repo.slug,
209+
result: partial ? "partial" : "snapshot",
210+
settings: verdict.value,
211+
outcomes,
212+
};
213+
}
214+
215+
/**
216+
* The snapshot as a settings file: the language-server schema pin, a comment header naming the
217+
* repository, the moment (supplied by the caller, so the text is deterministic), and every
218+
* outcome line, then the document as the merge flow writes one. A message spanning several
219+
* physical lines (an API error body) is commented line by line, so no line escapes the header.
220+
*/
221+
export function renderSnapshotYaml(
222+
result: RenderableSnapshot,
223+
opts: { schemaUrl: string; timestamp: string },
224+
): string {
225+
const header = [
226+
`# yaml-language-server: $schema=${opts.schemaUrl}`,
227+
`# Snapshot of ${result.repo} taken ${opts.timestamp}`,
228+
...result.outcomes.flatMap((outcome) =>
229+
outcome.detail.flatMap((message) =>
230+
message.split(/\r?\n/).map((line) => `# ${underKey(outcome.key, line)}`),
231+
),
232+
),
233+
];
234+
return `${header.join("\n")}\n${stringifyYaml(result.settings)}`;
235+
}

‎src/sections/actions_secrets/actions_secrets.docs.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ coverage:
1717
cannot-verify note for the values; a changed value on GitHub's side is undetectable.
1818
Undeclared secrets are kept by default (their values are unrecoverable); the wrapped
1919
`_undeclared: delete` form opts into deletion.
20+
Snapshot lists the secret names as per-store `$SECRET_<STORE>_<NAME>` references (so one
21+
name in two stores never shares a variable) with one note per value to export, since values
22+
are not readable.
2023
schema:
2124
SettingsFile.actions_secrets: >-
2225
Repository Actions secrets, written by name with values sealed client-side; each value is a

‎src/sections/actions_variables/actions_variables.docs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ coverage:
1515
per_page at 30 (not the usual 100), which the page loop honors so a large inventory is never
1616
truncated. Secrets are write-only material and deliberately NOT this section: they live in the
1717
`actions_secrets` section above.
18+
Snapshot reads the variables back as name and value entries under the delete default.
1819
schema:
1920
SettingsFile.actions_variables: >-
2021
GitHub Actions repository variables, upserted by name; undeclared ones are DELETED by default

‎src/sections/agents_secrets/agents_secrets.docs.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ coverage:
99
`actions_secrets`, over the Copilot agents secret store. (GET .../agents/organization-secrets
1010
is a read-only view of org-inherited secrets, not a reconciliation target.) Undeclared secrets
1111
kept by default; `_undeclared: delete` opts into deletion.
12+
Snapshot lists the secret names as per-store `$SECRET_<STORE>_<NAME>` references with one
13+
note per value to export, since values are not readable.
1214
schema:
1315
SettingsFile.agents_secrets: >-
1416
Repository Copilot agents secrets (the secret store Copilot coding agents read), written by name

‎src/sections/agents_variables/agents_variables.docs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ coverage:
1313
environment into this store, so a repository can hold agents variables nobody created here -
1414
run `mode: check` first (it lists them as deletion drift) before the first apply, or declare
1515
`_undeclared: keep`.
16+
Snapshot reads the variables back as name and value entries under the delete default.
1617
schema:
1718
SettingsFile.agents_variables: >-
1819
Copilot agents repository variables (the plain-text configuration Copilot coding agents read),

‎src/sections/autolinks/autolinks.docs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ coverage:
77
GET/POST/DELETE /repos/{owner}/{repo}/autolinks; immutable upstream so changed entries are
88
delete+recreate; undeclared autolinks DELETED by default, kept as notes under the wrapped
99
`_undeclared: keep` form.
10+
Snapshot reads the live autolinks back as entries under the delete default.
1011
schema:
1112
SettingsFile.autolinks: >-
1213
Autolink references; undeclared ones are DELETED by default (the wrapped form can set

‎src/sections/code_quality_setup/code_quality_setup.docs.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ coverage:
1616
set. ASSUMPTION: the GET is graded as a plain read under the Administration permission,
1717
mirroring code scanning - the fine-grained grading of these endpoints is not verified against
1818
production. The sibling /code-quality/findings endpoints are read-only and stay out of scope.
19+
Snapshot reads the GET body back on the declared keys; a null the slice does not take (a
20+
not-configured setup's runner_type) is omitted.
1921
schema:
2022
SettingsFile.code_quality_setup: Code quality analysis setup.
2123
CodeQualitySetupConfig: PATCH /repos/{r}/code-quality/setup, sent verbatim.

0 commit comments

Comments
 (0)