vouchington-tooling 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +5 -0
  2. package/dist/agent-issue-labels/ensure-labels.d.mts +17 -0
  3. package/dist/agent-issue-labels/ensure-labels.mjs +55 -0
  4. package/dist/agent-issue-labels/index.d.mts +5 -0
  5. package/dist/agent-issue-labels/index.mjs +3 -0
  6. package/dist/agent-issue-labels/label-policy.d.mts +21 -0
  7. package/dist/agent-issue-labels/label-policy.mjs +67 -0
  8. package/dist/agent-issue-labels/labels-from-paths.d.mts +9 -0
  9. package/dist/agent-issue-labels/labels-from-paths.mjs +54 -0
  10. package/dist/cli/commands/agent-issue-labels.d.mts +2 -0
  11. package/dist/cli/commands/agent-issue-labels.mjs +17 -0
  12. package/dist/cli/index.mjs +6 -0
  13. package/dist/cli/parse-agent-issue-labels.d.mts +19 -0
  14. package/dist/cli/parse-agent-issue-labels.mjs +70 -0
  15. package/dist/cli/parse-forwarded-commands.d.mts +3 -0
  16. package/dist/cli/parse-forwarded-commands.mjs +2 -0
  17. package/dist/cli/parse.d.mts +5 -1
  18. package/dist/cli/parse.mjs +3 -0
  19. package/dist/cli/usage.d.mts +1 -1
  20. package/dist/cli/usage.mjs +5 -0
  21. package/dist/index.d.mts +2 -0
  22. package/dist/index.mjs +1 -0
  23. package/dist/workflow-secrets-drift/cli.d.mts +10 -0
  24. package/dist/workflow-secrets-drift/cli.mjs +73 -0
  25. package/dist/workflow-secrets-drift/collect.d.mts +10 -0
  26. package/dist/workflow-secrets-drift/collect.mjs +70 -0
  27. package/dist/workflow-secrets-drift/drift.d.mts +22 -0
  28. package/dist/workflow-secrets-drift/drift.mjs +49 -0
  29. package/dist/workflow-secrets-drift/gh-parse.d.mts +5 -0
  30. package/dist/workflow-secrets-drift/gh-parse.mjs +41 -0
  31. package/dist/workflow-secrets-drift/gh.d.mts +4 -0
  32. package/dist/workflow-secrets-drift/gh.mjs +51 -0
  33. package/dist/workflow-secrets-drift/index.d.mts +11 -0
  34. package/dist/workflow-secrets-drift/index.mjs +6 -0
  35. package/dist/workflow-secrets-drift/inventory.d.mts +10 -0
  36. package/dist/workflow-secrets-drift/inventory.mjs +78 -0
  37. package/dist/workflow-secrets-drift/scopes.d.mts +12 -0
  38. package/dist/workflow-secrets-drift/scopes.mjs +56 -0
  39. package/dist/workflow-secrets-drift/settle.d.mts +3 -0
  40. package/dist/workflow-secrets-drift/settle.mjs +19 -0
  41. package/dist/workflow-secrets-drift/types.d.mts +33 -0
  42. package/dist/workflow-secrets-drift/types.mjs +1 -0
  43. package/package.json +11 -1
  44. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
package/README.md CHANGED
@@ -55,6 +55,8 @@ vouchington allocate-browser-safe-ports 2 --policy ./policy.json --forbidden-por
55
55
  vouchington diagnose-port-collision --ports "2200 2216"
56
56
  vouchington prepare-trivy-db
57
57
  vouchington gha-artifacts-cleanup run --run-id 123 --keep-pattern 'plan-*' --delete-pattern 'coverage-*'
58
+ vouchington agent-issue-labels labels-from-paths --labeler .github/labeler.yml src/a.ts
59
+ vouchington agent-issue-labels ensure-labels --policy-file labels.json --repo owner/name bug
58
60
  vouchington http-origin --field cdn_origin https://images.example.com
59
61
  vouchington vitest-blob-manifest <suite> [reports-directory]
60
62
  vouchington vitest-report-attempt write <directory> <suite>
@@ -83,6 +85,7 @@ vouchington harness-admission-lane 4
83
85
  vouchington harness-assert-gates HARNESS_DISPATCH_ENABLED HARNESS_SHEPHERD_ENABLED
84
86
  echo '[{"login":"octocat","type":"User"}]' | vouchington gha-collaborator-trust owner/repo --allow-bot github-actions[bot]
85
87
  vouchington nuget-central-version trusted.props candidate.props metadata.json out.props
88
+ vouchington verify-workflow-secrets --repo owner/name --inventory .github/workflows/workflow-secrets-inventory.mts
86
89
  vouchington swift-semantic-equal BASE HEAD App.swift
87
90
  vouchington post-review
88
91
  vouchington stage-review-payload optional|required <source> <destination>
@@ -306,6 +309,7 @@ import {
306
309
  writeSelectedFilesOutput,
307
310
  } from 'vouchington-tooling/gha-selected-files'
308
311
  import { createArtifactClassifier, runCleanup } from 'vouchington-tooling/gha-artifacts-cleanup'
312
+ import { ensureLabels, labelsFromPaths } from 'vouchington-tooling/agent-issue-labels'
309
313
  import { validateOptionalHttpOrigin } from 'vouchington-tooling/http-origin'
310
314
  import { boundPendingLine, splitCompleteLines } from 'vouchington-tooling/process-line-buffer'
311
315
  import {
@@ -365,6 +369,7 @@ import { runGitleaksDirectoryScan } from 'vouchington-tooling/gitleaks-directory
365
369
  import { runAstGrepExamples } from 'vouchington-tooling/ast-grep-examples'
366
370
  import { astGrepPackPaths } from 'vouchington-tooling/ast-grep-pack'
367
371
  import { validateNugetUpdate } from 'vouchington-tooling/nuget-central-version'
372
+ import { runVerifyWorkflowSecretsCli } from 'vouchington-tooling/workflow-secrets-drift'
368
373
  import { normalizeSwiftSource } from 'vouchington-tooling/swift-semantic-equal'
369
374
  import { parseUniqueSwiftBinaryTargetChecksum } from 'vouchington-tooling/swift-source-offset'
370
375
  import { validateResolvedPinDelta } from 'vouchington-tooling/swift-resolved-pin-delta'
@@ -0,0 +1,17 @@
1
+ import { type RunTextCommand } from '../gh-cli/exec.mts';
2
+ import { type LabelPolicy } from './label-policy.mts';
3
+ export type EnsureLabelsOptions = {
4
+ labels: readonly string[];
5
+ /** `owner/name`; defaults to the repository `gh` resolves from the working directory. */
6
+ repo?: string;
7
+ policy?: LabelPolicy;
8
+ /** Rewrite metadata of labels that already exist (otherwise they are left untouched). */
9
+ update?: boolean;
10
+ run?: RunTextCommand;
11
+ };
12
+ /**
13
+ * Creates missing repository labels through `gh` (or force-updates all with `update`). Every label
14
+ * is validated against the policy before `gh` is called. A create that fails because the label
15
+ * appeared concurrently is accepted. Returns the labels in the requested order.
16
+ */
17
+ export declare function ensureLabels(options: EnsureLabelsOptions): Promise<string[]>;
@@ -0,0 +1,55 @@
1
+ import { runGh } from "../gh-cli/exec.mjs";
2
+ import { DEFAULT_LABEL_POLICY, labelMetadata } from "./label-policy.mjs";
3
+ /**
4
+ * Creates missing repository labels through `gh` (or force-updates all with `update`). Every label
5
+ * is validated against the policy before `gh` is called. A create that fails because the label
6
+ * appeared concurrently is accepted. Returns the labels in the requested order.
7
+ */
8
+ export async function ensureLabels(options) {
9
+ const { labels, repo, update = false, run = runGh, policy = DEFAULT_LABEL_POLICY } = options;
10
+ if (labels.length === 0)
11
+ throw new Error('at least one label is required');
12
+ const metadata = labels.map((label) => labelMetadata(label, policy));
13
+ const base = repo ? `repos/${repo}/labels` : 'repos/{owner}/{repo}/labels';
14
+ const listed = await run([
15
+ 'api',
16
+ '--paginate',
17
+ '--slurp',
18
+ '-X',
19
+ 'GET',
20
+ base,
21
+ '-F',
22
+ 'per_page=100',
23
+ ]);
24
+ const existing = new Set(JSON.parse(listed).flat().map(({ name }) => name));
25
+ for (const [index, label] of labels.entries()) {
26
+ if (!update && existing.has(label))
27
+ continue;
28
+ const { color, description } = metadata[index];
29
+ try {
30
+ await run([
31
+ 'label',
32
+ 'create',
33
+ label,
34
+ '--color',
35
+ color,
36
+ '--description',
37
+ description,
38
+ ...(update ? ['--force'] : []),
39
+ ...(repo ? ['--repo', repo] : []),
40
+ ]);
41
+ }
42
+ catch (error) {
43
+ if (update)
44
+ throw error;
45
+ try {
46
+ await run(['api', `${base}/${encodeURIComponent(label)}`, '--silent']);
47
+ }
48
+ catch {
49
+ throw error;
50
+ }
51
+ }
52
+ existing.add(label);
53
+ }
54
+ return [...labels];
55
+ }
@@ -0,0 +1,5 @@
1
+ export { DEFAULT_LABELER_PATH, labelsFromPaths } from './labels-from-paths.mts';
2
+ export { ensureLabels } from './ensure-labels.mts';
3
+ export type { EnsureLabelsOptions } from './ensure-labels.mts';
4
+ export { DEFAULT_LABEL_POLICY, labelMetadata, parseLabelPolicy, readLabelPolicyFile, } from './label-policy.mts';
5
+ export type { LabelMetadata, LabelPolicy } from './label-policy.mts';
@@ -0,0 +1,3 @@
1
+ export { DEFAULT_LABELER_PATH, labelsFromPaths } from "./labels-from-paths.mjs";
2
+ export { ensureLabels } from "./ensure-labels.mjs";
3
+ export { DEFAULT_LABEL_POLICY, labelMetadata, parseLabelPolicy, readLabelPolicyFile, } from "./label-policy.mjs";
@@ -0,0 +1,21 @@
1
+ export type LabelMetadata = {
2
+ color: string;
3
+ description: string;
4
+ };
5
+ /**
6
+ * How label names map to GitHub label metadata. `labels` holds explicit entries; any other name
7
+ * gets `defaultColor` and `defaultDescription` (`{name}` is replaced by the label name). A name
8
+ * starting with one of `strictPrefixes` must have an explicit entry, or it is rejected.
9
+ */
10
+ export type LabelPolicy = {
11
+ labels: Readonly<Record<string, LabelMetadata>>;
12
+ defaultColor: string;
13
+ defaultDescription: string;
14
+ strictPrefixes: readonly string[];
15
+ };
16
+ export declare const DEFAULT_LABEL_POLICY: LabelPolicy;
17
+ /** Validates a parsed JSON label policy; omitted fields fall back to `DEFAULT_LABEL_POLICY`. */
18
+ export declare function parseLabelPolicy(input: unknown): LabelPolicy;
19
+ export declare function readLabelPolicyFile(path: string): LabelPolicy;
20
+ /** Resolves a label's color and description, throwing for an unlisted strict-prefix label. */
21
+ export declare function labelMetadata(name: string, policy?: LabelPolicy): LabelMetadata;
@@ -0,0 +1,67 @@
1
+ import { readFileSync } from 'node:fs';
2
+ export const DEFAULT_LABEL_POLICY = {
3
+ labels: {},
4
+ defaultColor: 'EDEDED',
5
+ defaultDescription: 'Repository issue classification: {name}.',
6
+ strictPrefixes: [],
7
+ };
8
+ function isRecord(value) {
9
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
10
+ }
11
+ function text(value, field) {
12
+ if (typeof value !== 'string' || value === '') {
13
+ throw new Error(`${field} must be a non-empty string`);
14
+ }
15
+ return value;
16
+ }
17
+ function parseEntries(input) {
18
+ if (input === undefined)
19
+ return {};
20
+ if (!isRecord(input))
21
+ throw new Error('labels must be an object');
22
+ const labels = {};
23
+ for (const [name, entry] of Object.entries(input)) {
24
+ if (!isRecord(entry))
25
+ throw new Error(`labels.${name} must be an object`);
26
+ labels[name] = {
27
+ color: text(entry.color, `labels.${name}.color`),
28
+ description: text(entry.description, `labels.${name}.description`),
29
+ };
30
+ }
31
+ return labels;
32
+ }
33
+ /** Validates a parsed JSON label policy; omitted fields fall back to `DEFAULT_LABEL_POLICY`. */
34
+ export function parseLabelPolicy(input) {
35
+ if (!isRecord(input))
36
+ throw new Error('label policy must be a JSON object');
37
+ const prefixes = input.strictPrefixes ?? [];
38
+ if (!Array.isArray(prefixes) || prefixes.some((prefix) => typeof prefix !== 'string')) {
39
+ throw new Error('strictPrefixes must be an array of strings');
40
+ }
41
+ return {
42
+ labels: parseEntries(input.labels),
43
+ defaultColor: input.defaultColor === undefined
44
+ ? DEFAULT_LABEL_POLICY.defaultColor
45
+ : text(input.defaultColor, 'defaultColor'),
46
+ defaultDescription: input.defaultDescription === undefined
47
+ ? DEFAULT_LABEL_POLICY.defaultDescription
48
+ : text(input.defaultDescription, 'defaultDescription'),
49
+ strictPrefixes: prefixes,
50
+ };
51
+ }
52
+ export function readLabelPolicyFile(path) {
53
+ return parseLabelPolicy(JSON.parse(readFileSync(path, 'utf8')));
54
+ }
55
+ /** Resolves a label's color and description, throwing for an unlisted strict-prefix label. */
56
+ export function labelMetadata(name, policy = DEFAULT_LABEL_POLICY) {
57
+ const explicit = Object.hasOwn(policy.labels, name) ? policy.labels[name] : undefined;
58
+ if (explicit)
59
+ return explicit;
60
+ const prefix = policy.strictPrefixes.find((candidate) => name.startsWith(candidate));
61
+ if (prefix !== undefined)
62
+ throw new Error(`unsupported ${prefix} label: ${name}`);
63
+ return {
64
+ color: policy.defaultColor,
65
+ description: policy.defaultDescription.replaceAll('{name}', name),
66
+ };
67
+ }
@@ -0,0 +1,9 @@
1
+ /** The conventional labeler config location, relative to the repository root. */
2
+ export declare const DEFAULT_LABELER_PATH = ".github/labeler.yml";
3
+ /**
4
+ * Maps changed paths to the labels an `actions/labeler` v5 config (`changed-files` with plain or
5
+ * `any-glob-to-any-file` entries) would apply, matching dotfiles like the real labeler. A missing
6
+ * config yields no labels; an unparseable or non-mapping config throws with its path.
7
+ * Labels are returned once each, in config order.
8
+ */
9
+ export declare function labelsFromPaths(paths: string[], labelerPath: string): Promise<string[]>;
@@ -0,0 +1,54 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { parse as load } from 'yaml';
3
+ import picomatch from 'picomatch';
4
+ /** The conventional labeler config location, relative to the repository root. */
5
+ export const DEFAULT_LABELER_PATH = '.github/labeler.yml';
6
+ async function readLabeler(labelerPath) {
7
+ let raw;
8
+ try {
9
+ raw = await readFile(labelerPath, 'utf8');
10
+ }
11
+ catch (error) {
12
+ if (error.code === 'ENOENT')
13
+ return {};
14
+ throw error;
15
+ }
16
+ let parsed;
17
+ try {
18
+ parsed = load(raw);
19
+ }
20
+ catch (error) {
21
+ throw new Error(`invalid labeler config ${labelerPath}: ${error.message}`);
22
+ }
23
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
24
+ throw new Error(`invalid labeler config ${labelerPath}: top level must be a mapping`);
25
+ }
26
+ return parsed;
27
+ }
28
+ function entryGlobs(entry) {
29
+ if (typeof entry === 'string')
30
+ return [entry];
31
+ const globs = entry['any-glob-to-any-file'];
32
+ return Array.isArray(globs) ? globs : [globs];
33
+ }
34
+ /**
35
+ * Maps changed paths to the labels an `actions/labeler` v5 config (`changed-files` with plain or
36
+ * `any-glob-to-any-file` entries) would apply, matching dotfiles like the real labeler. A missing
37
+ * config yields no labels; an unparseable or non-mapping config throws with its path.
38
+ * Labels are returned once each, in config order.
39
+ */
40
+ export async function labelsFromPaths(paths, labelerPath) {
41
+ const labeler = await readLabeler(labelerPath);
42
+ const matched = [];
43
+ for (const [label, rules] of Object.entries(labeler)) {
44
+ if (!Array.isArray(rules))
45
+ continue;
46
+ const hit = rules.some((rule) => (rule['changed-files'] ?? []).some((entry) => {
47
+ const isMatch = picomatch(entryGlobs(entry), { dot: true });
48
+ return paths.some((path) => isMatch(path));
49
+ }));
50
+ if (hit)
51
+ matched.push(label);
52
+ }
53
+ return matched;
54
+ }
@@ -0,0 +1,2 @@
1
+ import type { ParsedAgentIssueLabels } from '../parse-agent-issue-labels.mts';
2
+ export declare function runAgentIssueLabels(parsed: ParsedAgentIssueLabels, cwd?: string): Promise<number>;
@@ -0,0 +1,17 @@
1
+ import { resolve } from 'node:path';
2
+ import { DEFAULT_LABELER_PATH, ensureLabels, labelsFromPaths, readLabelPolicyFile, } from "../../agent-issue-labels/index.mjs";
3
+ export async function runAgentIssueLabels(parsed, cwd = process.cwd()) {
4
+ const labels = parsed.subcommand === 'labels-from-paths'
5
+ ? await labelsFromPaths(parsed.paths, resolve(cwd, parsed.labeler ?? DEFAULT_LABELER_PATH))
6
+ : await ensureLabels({
7
+ labels: parsed.labels,
8
+ update: parsed.update,
9
+ ...(parsed.repo === undefined ? {} : { repo: parsed.repo }),
10
+ ...(parsed.policyFile === undefined
11
+ ? {}
12
+ : { policy: readLabelPolicyFile(resolve(cwd, parsed.policyFile)) }),
13
+ });
14
+ for (const label of labels)
15
+ process.stdout.write(`${label}\n`);
16
+ return 0;
17
+ }
@@ -5,6 +5,7 @@ import { pathToFileURL } from 'node:url';
5
5
  import { runPostReviewCli } from "../gha-post-review/cli.mjs";
6
6
  import { runStageReviewPayloadCli } from "../gha-review-payload/cli.mjs";
7
7
  import { runSwiftSemanticEqualCli } from "../swift-semantic-equal/cli.mjs";
8
+ import { runAgentIssueLabels } from "./commands/agent-issue-labels.mjs";
8
9
  import { runGhaArtifactsCleanup } from "./commands/gha-artifacts-cleanup.mjs";
9
10
  import { runGhaRuntimeAudit } from "./commands/gha-runtime-audit.mjs";
10
11
  import { runHttpOrigin } from "./commands/http-origin.mjs";
@@ -12,6 +13,7 @@ import { runPnpmInstallCli } from "./commands/pnpm-install.mjs";
12
13
  import { runRunnerPortPolicy } from "./commands/runner-port-policy.mjs";
13
14
  import { runScript } from "./commands/spawn-script.mjs";
14
15
  import { runNugetCentralVersionCommand } from "./commands/nuget-central-version.mjs";
16
+ import { runVerifyWorkflowSecretsCli } from "../workflow-secrets-drift/cli.mjs";
15
17
  import { runVitestBlobManifestCommand } from "./commands/vitest-blob-manifest.mjs";
16
18
  import { runVitestReportAttemptCommand } from "./commands/vitest-report-attempt.mjs";
17
19
  import { runPrepareVitestReportsCommand } from "./commands/prepare-vitest-reports.mjs";
@@ -119,6 +121,8 @@ export function runCli(argv = process.argv) {
119
121
  return runPrepareVitestReportsCommand(parsed.args);
120
122
  case 'nuget-central-version':
121
123
  return runNugetCentralVersionCommand(parsed.args);
124
+ case 'verify-workflow-secrets':
125
+ return runVerifyWorkflowSecretsCli(parsed.args);
122
126
  case 'swift-semantic-equal':
123
127
  return runSwiftSemanticEqualCli(parsed.args);
124
128
  case 'post-review':
@@ -129,6 +133,8 @@ export function runCli(argv = process.argv) {
129
133
  return runHttpOrigin(parsed.field, parsed.value);
130
134
  case 'gha-artifacts-cleanup':
131
135
  return runGhaArtifactsCleanup(parsed);
136
+ case 'agent-issue-labels':
137
+ return runAgentIssueLabels(parsed);
132
138
  case 'story-coverage':
133
139
  return runStoryCoverageLazy(parsed);
134
140
  case 'retrospective-transcript':
@@ -0,0 +1,19 @@
1
+ export type ParsedAgentIssueLabels = {
2
+ kind: 'agent-issue-labels';
3
+ subcommand: 'labels-from-paths';
4
+ labeler?: string;
5
+ paths: string[];
6
+ } | {
7
+ kind: 'agent-issue-labels';
8
+ subcommand: 'ensure-labels';
9
+ repo?: string;
10
+ policyFile?: string;
11
+ update: boolean;
12
+ labels: string[];
13
+ };
14
+ type Failure = {
15
+ kind: 'error';
16
+ message: string;
17
+ };
18
+ export declare function parseAgentIssueLabels(args: readonly string[]): ParsedAgentIssueLabels | Failure;
19
+ export {};
@@ -0,0 +1,70 @@
1
+ const PREFIX = 'agent-issue-labels';
2
+ /** Reads the value after `flag`, rejecting a missing value or another flag. */
3
+ function takeValue(args, index, flag) {
4
+ const value = args[index + 1];
5
+ if (value === undefined || value.startsWith('--')) {
6
+ return { kind: 'error', message: `${PREFIX}: ${flag} requires a value` };
7
+ }
8
+ return value;
9
+ }
10
+ export function parseAgentIssueLabels(args) {
11
+ const [subcommand, ...rest] = args;
12
+ if (subcommand !== 'labels-from-paths' && subcommand !== 'ensure-labels') {
13
+ return {
14
+ kind: 'error',
15
+ message: subcommand === undefined
16
+ ? `${PREFIX} requires labels-from-paths or ensure-labels`
17
+ : `unknown ${PREFIX} subcommand: ${subcommand}`,
18
+ };
19
+ }
20
+ const positional = [];
21
+ const values = new Map();
22
+ let update = false;
23
+ const allowed = subcommand === 'ensure-labels' ? ['--repo', '--policy-file'] : ['--labeler'];
24
+ for (let index = 0; index < rest.length; index += 1) {
25
+ const arg = rest[index];
26
+ if (arg === '--update' && subcommand === 'ensure-labels') {
27
+ if (update)
28
+ return { kind: 'error', message: `${PREFIX}: --update may be specified only once` };
29
+ update = true;
30
+ }
31
+ else if (allowed.includes(arg)) {
32
+ if (values.has(arg)) {
33
+ return { kind: 'error', message: `${PREFIX}: ${arg} may be specified only once` };
34
+ }
35
+ const value = takeValue(rest, index, arg);
36
+ if (typeof value !== 'string')
37
+ return value;
38
+ values.set(arg, value);
39
+ index += 1;
40
+ }
41
+ else if (arg.startsWith('--')) {
42
+ return { kind: 'error', message: `unknown ${PREFIX} option: ${arg}` };
43
+ }
44
+ else {
45
+ positional.push(arg);
46
+ }
47
+ }
48
+ if (subcommand === 'labels-from-paths') {
49
+ const labeler = values.get('--labeler');
50
+ return {
51
+ kind: 'agent-issue-labels',
52
+ subcommand,
53
+ paths: positional,
54
+ ...(labeler === undefined ? {} : { labeler }),
55
+ };
56
+ }
57
+ if (positional.length === 0) {
58
+ return { kind: 'error', message: `${PREFIX} ensure-labels requires at least one label` };
59
+ }
60
+ const repo = values.get('--repo');
61
+ const policyFile = values.get('--policy-file');
62
+ return {
63
+ kind: 'agent-issue-labels',
64
+ subcommand,
65
+ update,
66
+ labels: positional,
67
+ ...(repo === undefined ? {} : { repo }),
68
+ ...(policyFile === undefined ? {} : { policyFile }),
69
+ };
70
+ }
@@ -19,6 +19,9 @@ type ForwardedCommand = {
19
19
  } | {
20
20
  kind: 'nuget-central-version';
21
21
  args: string[];
22
+ } | {
23
+ kind: 'verify-workflow-secrets';
24
+ args: string[];
22
25
  } | {
23
26
  kind: 'swift-semantic-equal';
24
27
  args: string[];
@@ -13,6 +13,8 @@ export function parseForwardedCommand(command, args) {
13
13
  return { kind: 'prepare-vitest-reports', args };
14
14
  if (command === 'nuget-central-version')
15
15
  return { kind: 'nuget-central-version', args };
16
+ if (command === 'verify-workflow-secrets')
17
+ return { kind: 'verify-workflow-secrets', args };
16
18
  if (command === 'swift-semantic-equal')
17
19
  return { kind: 'swift-semantic-equal', args };
18
20
  if (command === 'post-review')
@@ -1,4 +1,5 @@
1
1
  import { type ParsedGhaArtifactsCleanup } from './parse-gha-artifacts-cleanup.mts';
2
+ import { type ParsedAgentIssueLabels } from './parse-agent-issue-labels.mts';
2
3
  import { type ParsedStoryCoverage } from './parse-story-coverage.mts';
3
4
  import { type ParsedGhaRuntimeAudit } from './parse-gha-runtime-audit.mts';
4
5
  export type ParsedCli = {
@@ -40,6 +41,9 @@ export type ParsedCli = {
40
41
  } | {
41
42
  kind: 'nuget-central-version';
42
43
  args: string[];
44
+ } | {
45
+ kind: 'verify-workflow-secrets';
46
+ args: string[];
43
47
  } | {
44
48
  kind: 'swift-semantic-equal';
45
49
  args: string[];
@@ -97,7 +101,7 @@ export type ParsedCli = {
97
101
  root?: string;
98
102
  workflowDirectories?: string[];
99
103
  actionDirectories?: string[];
100
- } | ParsedGhaRuntimeAudit | ParsedGhaArtifactsCleanup | ParsedStoryCoverage;
104
+ } | ParsedGhaRuntimeAudit | ParsedGhaArtifactsCleanup | ParsedAgentIssueLabels | ParsedStoryCoverage;
101
105
  export type ScriptCommand = 'gha-output' | 'gha-needs-results' | 'download-with-diagnostics' | 'download-optional-run-artifacts' | 'host-pressure-diagnostics' | 'allocate-browser-safe-ports' | 'diagnose-port-collision' | 'prepare-trivy-db' | 'check-cache-size' | 'make-shard-matrix' | 'load-runner-env' | 'clean-workspace' | 'install-github-release' | 'run-with-timeout' | 'lint-links' | 'materialize-pr-context' | 'wait-for-apt-locks' | 'install-playwright-chromium-arm64' | 'ghcr-package-retention' | 'harness-admission-lane' | 'harness-assert-gates' | 'gha-collaborator-trust';
102
106
  export declare function parseCli(argv: readonly string[]): ParsedCli;
103
107
  export declare function parseCommandHelp(command: string | undefined, rest: readonly string[]): {
@@ -1,4 +1,5 @@
1
1
  import { parseGhaArtifactsCleanup, } from "./parse-gha-artifacts-cleanup.mjs";
2
+ import { parseAgentIssueLabels } from "./parse-agent-issue-labels.mjs";
2
3
  import { parseStoryCoverage } from "./parse-story-coverage.mjs";
3
4
  import { parseGhaRuntimeAudit } from "./parse-gha-runtime-audit.mjs";
4
5
  import { parseForwardedCommand } from "./parse-forwarded-commands.mjs";
@@ -64,6 +65,8 @@ export function parseCli(argv) {
64
65
  return parseGhaWorkspacePolicy(rest);
65
66
  if (command === 'gha-artifacts-cleanup')
66
67
  return parseGhaArtifactsCleanup(rest);
68
+ if (command === 'agent-issue-labels')
69
+ return parseAgentIssueLabels(rest);
67
70
  if (command === 'story-coverage')
68
71
  return parseStoryCoverage(rest);
69
72
  if (command !== undefined && SCRIPT_COMMANDS.has(command)) {
@@ -1,4 +1,4 @@
1
- export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n worktree Reclaim finished git worktrees (dry run unless --yes)\n story-coverage Check component exports are imported by stories\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nworktree reclaim [--yes] [--json]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
1
+ export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n worktree Reclaim finished git worktrees (dry run unless --yes)\n story-coverage Check component exports are imported by stories\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nworktree reclaim [--yes] [--json]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
2
2
  export declare function printUsage(stream?: NodeJS.WritableStream): void;
3
3
  export declare function commandNames(usage?: string): string[];
4
4
  export declare function commandUsage(command: string, usage?: string): string;
@@ -20,6 +20,7 @@ Commands:
20
20
  diagnose-port-collision Capture bounded localhost port diagnostics
21
21
  prepare-trivy-db Download the Trivy vulnerability database
22
22
  gha-artifacts-cleanup Delete classified GitHub Actions artifacts
23
+ agent-issue-labels Map changed paths to labels; create missing repository labels
23
24
  http-origin Validate an optional HTTP(S) origin
24
25
  vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file
25
26
  vitest-report-attempt Write or read a Vitest report-attempt marker
@@ -40,6 +41,7 @@ Commands:
40
41
  harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled
41
42
  gha-collaborator-trust Classify authors as write-access collaborators or not
42
43
  nuget-central-version Validate a Directory.Packages.props PackageVersion delta
44
+ verify-workflow-secrets Check a secret inventory against live repository and environment secrets
43
45
  swift-semantic-equal Compare Swift sources ignoring comments and whitespace
44
46
  post-review Post one COMMENT review from a staged payload file
45
47
  stage-review-payload Validate a review payload file into a staging directory
@@ -96,6 +98,8 @@ diagnose-port-collision [--ports "2200 2216"] [--output-dir PATH]
96
98
  prepare-trivy-db
97
99
  gha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]
98
100
  gha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]
101
+ agent-issue-labels labels-from-paths [--labeler <path>] <path>...
102
+ agent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...
99
103
  http-origin [--field NAME] [value]
100
104
  vitest-blob-manifest <suite> [reports-directory]
101
105
  vitest-report-attempt <write DIRECTORY SUITE|read ROOT>
@@ -116,6 +120,7 @@ harness-admission-lane <lanes>
116
120
  harness-assert-gates <gate>...
117
121
  gha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json
118
122
  nuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>
123
+ verify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]
119
124
  swift-semantic-equal <base> <head> <file.swift>
120
125
  post-review
121
126
  stage-review-payload optional|required <source> <destination>
package/dist/index.d.mts CHANGED
@@ -43,6 +43,8 @@ export type { FakeGitOptions, NamedCheck, SharedContext } from './shared-context
43
43
  export { decodeSelectedFiles, encodeSelectedFiles, formatMultilineOutput, SELECTED_FILES_ENV_MAX_BYTES, selectedFilesExceedEnvBudget, writeSelectedFilesOutput, } from './gha-selected-files/index.mts';
44
44
  export { createArtifactClassifier, parseArtifactPatternsJson, planRunDeletions, runCleanup, sweepCleanup, } from './gha-artifacts-cleanup/index.mts';
45
45
  export type { ArtifactClassification, ArtifactClassifier, ArtifactPatterns, CleanupRequest, DeletionSummary, } from './gha-artifacts-cleanup/index.mts';
46
+ export { DEFAULT_LABEL_POLICY, DEFAULT_LABELER_PATH, ensureLabels, labelMetadata, labelsFromPaths, parseLabelPolicy, readLabelPolicyFile, } from './agent-issue-labels/index.mts';
47
+ export type { EnsureLabelsOptions, LabelMetadata, LabelPolicy, } from './agent-issue-labels/index.mts';
46
48
  export { validateOptionalHttpOrigin } from './http-origin/index.mts';
47
49
  export { boundPendingLine, DEFAULT_MAX_PENDING_LINE_LENGTH, DEFAULT_TRUNCATED_LINE_MARKER, splitCompleteLines, } from './process-line-buffer/index.mts';
48
50
  export { isProcessGroupAlive, ProcessGroupDrainTimeoutError, runBrowserSession, waitForProcessGroupExit, } from './browser-session-runner/index.mts';
package/dist/index.mjs CHANGED
@@ -22,6 +22,7 @@ export { flattenReleaseAgeSelectors, packageNameFromPnpmLockKey, pnpmLockPackage
22
22
  export { buildContextFromTrackedFiles, buildSharedContext, clearFakeGitEnv, gitEnv, installFakeGit, runNamedChecks, setFakeGitTrackedFiles, } from "./shared-context/index.mjs";
23
23
  export { decodeSelectedFiles, encodeSelectedFiles, formatMultilineOutput, SELECTED_FILES_ENV_MAX_BYTES, selectedFilesExceedEnvBudget, writeSelectedFilesOutput, } from "./gha-selected-files/index.mjs";
24
24
  export { createArtifactClassifier, parseArtifactPatternsJson, planRunDeletions, runCleanup, sweepCleanup, } from "./gha-artifacts-cleanup/index.mjs";
25
+ export { DEFAULT_LABEL_POLICY, DEFAULT_LABELER_PATH, ensureLabels, labelMetadata, labelsFromPaths, parseLabelPolicy, readLabelPolicyFile, } from "./agent-issue-labels/index.mjs";
25
26
  export { validateOptionalHttpOrigin } from "./http-origin/index.mjs";
26
27
  export { boundPendingLine, DEFAULT_MAX_PENDING_LINE_LENGTH, DEFAULT_TRUNCATED_LINE_MARKER, splitCompleteLines, } from "./process-line-buffer/index.mjs";
27
28
  export { isProcessGroupAlive, ProcessGroupDrainTimeoutError, runBrowserSession, waitForProcessGroupExit, } from "./browser-session-runner/index.mjs";
@@ -0,0 +1,10 @@
1
+ import type { WorkflowSecretInventory, WorkflowSecretsDependencies } from './types.mts';
2
+ export declare const USAGE: string;
3
+ export interface VerifyWorkflowSecretsOptions {
4
+ dependencies?: WorkflowSecretsDependencies;
5
+ output?: Pick<Console, 'error' | 'log'>;
6
+ /** Skips loading `--inventory` when supplied. */
7
+ inventory?: WorkflowSecretInventory;
8
+ cwd?: string;
9
+ }
10
+ export declare function runVerifyWorkflowSecretsCli(argv: readonly string[], options?: VerifyWorkflowSecretsOptions): Promise<number>;
@@ -0,0 +1,73 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { collectLiveSecretNames } from "./collect.mjs";
3
+ import { diffAgainstInventory, formatDrift, missingConfirmedSecrets, unconfirmedNewlyProvisioned, } from "./drift.mjs";
4
+ import { createGhDependencies } from "./gh.mjs";
5
+ import { DEFAULT_INVENTORY_EXPORT, DEFAULT_INVENTORY_PATH, loadInventory, normalizeInventory, } from "./inventory.mjs";
6
+ import { requiredEnvironmentNames, requiredSecretScopeViolations } from "./scopes.mjs";
7
+ import { errorMessage } from "./settle.mjs";
8
+ export const USAGE = 'Usage: vouchington verify-workflow-secrets [--repo <owner/repo>] [--confirm <name1,name2,...>] ' +
9
+ '[--inventory <module>] [--export <name>] [--branch <name>]';
10
+ const splitNames = (raw) => (raw ?? '')
11
+ .split(',')
12
+ .map((name) => name.trim().toUpperCase())
13
+ .filter((name) => name.length > 0);
14
+ export async function runVerifyWorkflowSecretsCli(argv, options = {}) {
15
+ const { output = console, dependencies = createGhDependencies() } = options;
16
+ let values;
17
+ try {
18
+ ;
19
+ ({ values } = parseArgs({
20
+ args: [...argv],
21
+ options: {
22
+ repo: { type: 'string' },
23
+ confirm: { type: 'string' },
24
+ inventory: { type: 'string', default: DEFAULT_INVENTORY_PATH },
25
+ export: { type: 'string', default: DEFAULT_INVENTORY_EXPORT },
26
+ branch: { type: 'string', default: 'main' },
27
+ },
28
+ strict: true,
29
+ }));
30
+ }
31
+ catch (err) {
32
+ output.error(`${USAGE}\n${errorMessage(err)}`);
33
+ return 2;
34
+ }
35
+ const confirmNames = splitNames(values.confirm);
36
+ const emptyOption = ['repo', 'inventory', 'export', 'branch'].find((key) => values[key] !== undefined && values[key].trim() === '');
37
+ if (emptyOption !== undefined || (values.confirm !== undefined && confirmNames.length === 0)) {
38
+ output.error(`${USAGE}\n--${emptyOption ?? 'confirm'} requires a non-empty value`);
39
+ return 2;
40
+ }
41
+ try {
42
+ const inventory = normalizeInventory(options.inventory ??
43
+ (await loadInventory(values.inventory, values.export, options.cwd ?? process.cwd())));
44
+ const repo = values.repo ?? (await dependencies.resolveRepo());
45
+ const live = await collectLiveSecretNames(repo, dependencies, requiredEnvironmentNames(inventory));
46
+ const drift = diffAgainstInventory(inventory, live.names, live.warnings);
47
+ output.log(formatDrift(drift));
48
+ const scopeViolations = requiredSecretScopeViolations(inventory, {
49
+ ...live,
50
+ deploymentBranch: values.branch,
51
+ });
52
+ if (scopeViolations.length > 0) {
53
+ output.log(`Secret scope violations:\n${scopeViolations.map((value) => ` - ${value}`).join('\n')}`);
54
+ }
55
+ const missingConfirmed = missingConfirmedSecrets(confirmNames, live.names);
56
+ if (confirmNames.length > 0) {
57
+ output.log(missingConfirmed.length > 0
58
+ ? `--confirm expected these secret(s) to be live, but gh does not see them: ${missingConfirmed.join(', ')}`
59
+ : `Confirmed all ${confirmNames.length} --confirm secret(s) are live.`);
60
+ }
61
+ const failed = unconfirmedNewlyProvisioned(drift, confirmNames).length > 0 ||
62
+ drift.notActuallyProvisioned.length > 0 ||
63
+ drift.accidentallyProvisioned.length > 0 ||
64
+ drift.warnings.length > 0 ||
65
+ scopeViolations.length > 0 ||
66
+ missingConfirmed.length > 0;
67
+ return failed ? 1 : 0;
68
+ }
69
+ catch (err) {
70
+ output.error(`verify-workflow-secrets failed: ${errorMessage(err)}`);
71
+ return 1;
72
+ }
73
+ }
@@ -0,0 +1,10 @@
1
+ import type { EnvironmentDeploymentBranchPolicy, WorkflowSecretsDependencies } from './types.mts';
2
+ export interface LiveSecretNames {
3
+ names: Set<string>;
4
+ repositoryNames: Set<string>;
5
+ organizationNames: Set<string>;
6
+ environmentNames: Map<string, Set<string>>;
7
+ environmentDeploymentBranchPolicies: Map<string, EnvironmentDeploymentBranchPolicy>;
8
+ warnings: string[];
9
+ }
10
+ export declare function collectLiveSecretNames(repo: string, dependencies: WorkflowSecretsDependencies, requiredPolicyEnvironments: ReadonlySet<string>): Promise<LiveSecretNames>;
@@ -0,0 +1,70 @@
1
+ import { errorMessage, settleLimited } from "./settle.mjs";
2
+ const QUERY_CONCURRENCY = 5;
3
+ /** GitHub stores secret names upper-case and compares them case-insensitively. */
4
+ const upperCased = (names) => new Set(names.map((name) => name.toUpperCase()));
5
+ async function collectOrganizationNames(repo, dependencies, warnings) {
6
+ try {
7
+ const ownerType = await dependencies.listRepositoryOwnerType(repo);
8
+ if (ownerType !== 'Organization' && ownerType !== 'User') {
9
+ throw new Error(`unexpected repository owner type: ${ownerType}`);
10
+ }
11
+ if (ownerType === 'User')
12
+ return new Set();
13
+ return upperCased(await dependencies.listRepositoryOrganizationSecretNames(repo));
14
+ }
15
+ catch (err) {
16
+ warnings.push(`Could not list organization secrets for ${repo}: ${errorMessage(err)}`);
17
+ return new Set();
18
+ }
19
+ }
20
+ async function collectEnvironmentNames(repo, dependencies, warnings) {
21
+ let environments = [];
22
+ try {
23
+ environments = await dependencies.listEnvironmentNames(repo);
24
+ }
25
+ catch (err) {
26
+ warnings.push(`Could not list deployment environments for ${repo}: ${errorMessage(err)}`);
27
+ }
28
+ const results = await settleLimited(environments, QUERY_CONCURRENCY, (environment) => dependencies.listEnvironmentSecretNames(repo, environment));
29
+ const byEnvironment = new Map();
30
+ results.forEach((result, index) => {
31
+ if (result.status === 'fulfilled') {
32
+ byEnvironment.set(environments[index].toLowerCase(), upperCased(result.value));
33
+ return;
34
+ }
35
+ warnings.push(`Could not list secrets for environment "${environments[index]}": ${errorMessage(result.reason)}`);
36
+ });
37
+ return byEnvironment;
38
+ }
39
+ async function collectBranchPolicies(repo, environments, dependencies, warnings) {
40
+ const names = [...environments];
41
+ const results = await settleLimited(names, QUERY_CONCURRENCY, (environment) => dependencies.getEnvironmentDeploymentBranchPolicy(repo, environment));
42
+ const policies = new Map();
43
+ results.forEach((result, index) => {
44
+ if (result.status === 'fulfilled') {
45
+ policies.set(names[index], result.value);
46
+ return;
47
+ }
48
+ warnings.push(`Could not list deployment branch policy for environment "${names[index]}": ${errorMessage(result.reason)}`);
49
+ });
50
+ return policies;
51
+ }
52
+ export async function collectLiveSecretNames(repo, dependencies, requiredPolicyEnvironments) {
53
+ const warnings = [];
54
+ const repositoryNames = upperCased(await dependencies.listRepoSecretNames(repo));
55
+ const organizationNames = await collectOrganizationNames(repo, dependencies, warnings);
56
+ const environmentNames = await collectEnvironmentNames(repo, dependencies, warnings);
57
+ const environmentDeploymentBranchPolicies = await collectBranchPolicies(repo, requiredPolicyEnvironments, dependencies, warnings);
58
+ const names = new Set([...repositoryNames, ...organizationNames]);
59
+ for (const scoped of environmentNames.values())
60
+ for (const name of scoped)
61
+ names.add(name);
62
+ return {
63
+ names,
64
+ repositoryNames,
65
+ organizationNames,
66
+ environmentNames,
67
+ environmentDeploymentBranchPolicies,
68
+ warnings,
69
+ };
70
+ }
@@ -0,0 +1,22 @@
1
+ import type { WorkflowSecretInventory } from './types.mts';
2
+ export interface SecretDrift {
3
+ /** `provisioned: false` in the inventory, but live: flip the flag to true. */
4
+ readonly newlyProvisioned: string[];
5
+ /** `provisioned: true` in the inventory, but not live: investigate. */
6
+ readonly notActuallyProvisioned: string[];
7
+ /** `neverProvision: true` in the inventory, but live anyway: delete the live secret. */
8
+ readonly accidentallyProvisioned: string[];
9
+ /** Live secret with no inventory entry: informational, not a drift failure. */
10
+ readonly unreferenced: string[];
11
+ /** Reads the secret store could not complete (permissions, deleted mid-run, etc). */
12
+ readonly warnings: string[];
13
+ }
14
+ export declare function diffAgainstInventory(inventory: WorkflowSecretInventory, liveNames: ReadonlySet<string>, warnings: readonly string[]): SecretDrift;
15
+ /** `confirmNames` entries that are not live: the operator's post-provisioning checklist fell short. */
16
+ export declare function missingConfirmedSecrets(confirmNames: readonly string[], liveNames: ReadonlySet<string>): string[];
17
+ /**
18
+ * `drift.newlyProvisioned` names not covered by `--confirm`. A confirmed name is expected to still
19
+ * be `provisioned: false` until a follow-up edit, so only other newly-provisioned names are drift.
20
+ */
21
+ export declare function unconfirmedNewlyProvisioned(drift: SecretDrift, confirmNames: readonly string[]): string[];
22
+ export declare function formatDrift(drift: SecretDrift): string;
@@ -0,0 +1,49 @@
1
+ export function diffAgainstInventory(inventory, liveNames, warnings) {
2
+ const newlyProvisioned = [];
3
+ const notActuallyProvisioned = [];
4
+ const accidentallyProvisioned = [];
5
+ for (const [name, entry] of Object.entries(inventory)) {
6
+ if (entry.neverProvision) {
7
+ if (liveNames.has(name))
8
+ accidentallyProvisioned.push(name);
9
+ }
10
+ else if (!entry.provisioned && liveNames.has(name))
11
+ newlyProvisioned.push(name);
12
+ else if (entry.provisioned && !liveNames.has(name))
13
+ notActuallyProvisioned.push(name);
14
+ }
15
+ return {
16
+ newlyProvisioned: newlyProvisioned.toSorted(),
17
+ notActuallyProvisioned: notActuallyProvisioned.toSorted(),
18
+ accidentallyProvisioned: accidentallyProvisioned.toSorted(),
19
+ unreferenced: [...liveNames].filter((name) => !Object.hasOwn(inventory, name)).toSorted(),
20
+ warnings: [...warnings],
21
+ };
22
+ }
23
+ /** `confirmNames` entries that are not live: the operator's post-provisioning checklist fell short. */
24
+ export function missingConfirmedSecrets(confirmNames, liveNames) {
25
+ return confirmNames.filter((name) => !liveNames.has(name));
26
+ }
27
+ /**
28
+ * `drift.newlyProvisioned` names not covered by `--confirm`. A confirmed name is expected to still
29
+ * be `provisioned: false` until a follow-up edit, so only other newly-provisioned names are drift.
30
+ */
31
+ export function unconfirmedNewlyProvisioned(drift, confirmNames) {
32
+ const confirmed = new Set(confirmNames);
33
+ return drift.newlyProvisioned.filter((name) => !confirmed.has(name));
34
+ }
35
+ function section(title, names) {
36
+ return names.length === 0 ? [] : [title, ...names.map((name) => ` - ${name}`)];
37
+ }
38
+ export function formatDrift(drift) {
39
+ const lines = [
40
+ ...section('Now provisioned but still marked `provisioned: false` (flip it in the inventory):', drift.newlyProvisioned),
41
+ ...section('Marked `provisioned: true` but not visible to this gh session (deleted, renamed, or a token-scope gap; verify before editing):', drift.notActuallyProvisioned),
42
+ ...section('Marked `neverProvision: true` but provisioned live anyway (delete the live secret, do not flip `provisioned`):', drift.accidentallyProvisioned),
43
+ ...section('Provisioned but not in the inventory (fine if consumed outside workflows, e.g. Dependabot/Codespaces):', drift.unreferenced),
44
+ ...drift.warnings.map((warning) => `Warning: ${warning}`),
45
+ ];
46
+ if (lines.length === 0)
47
+ lines.push('The inventory matches the live secret store. No drift.');
48
+ return `${lines.join('\n')}\n`;
49
+ }
@@ -0,0 +1,5 @@
1
+ import type { DeploymentBranchRule, EnvironmentDeploymentBranchPolicy } from './types.mts';
2
+ export declare function outputNames(stdout: string): string[];
3
+ export declare function parseSecretNames(stdout: string): string[];
4
+ export declare function parseDeploymentBranchPolicy(stdout: string): Omit<EnvironmentDeploymentBranchPolicy, 'deploymentBranchRules'>;
5
+ export declare function parseDeploymentBranchRules(stdout: string): DeploymentBranchRule[];
@@ -0,0 +1,41 @@
1
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2
+ export function outputNames(stdout) {
3
+ return stdout
4
+ .split('\n')
5
+ .map((line) => line.trim())
6
+ .filter((line) => line.length > 0);
7
+ }
8
+ export function parseSecretNames(stdout) {
9
+ return JSON.parse(stdout).map((entry) => entry.name);
10
+ }
11
+ export function parseDeploymentBranchPolicy(stdout) {
12
+ const parsed = JSON.parse(stdout);
13
+ if (!isRecord(parsed) ||
14
+ typeof parsed.protected_branches !== 'boolean' ||
15
+ typeof parsed.custom_branch_policies !== 'boolean') {
16
+ throw new Error('unexpected deployment branch policy metadata');
17
+ }
18
+ return {
19
+ protectedBranchesEnabled: parsed.protected_branches,
20
+ customBranchPoliciesEnabled: parsed.custom_branch_policies,
21
+ };
22
+ }
23
+ export function parseDeploymentBranchRules(stdout) {
24
+ const parsed = JSON.parse(stdout);
25
+ const invalid = new Error('unexpected deployment branch policy');
26
+ if (!isRecord(parsed))
27
+ throw invalid;
28
+ const { total_count, branch_policies } = parsed;
29
+ if (!Number.isSafeInteger(total_count) ||
30
+ !Array.isArray(branch_policies) ||
31
+ branch_policies.length > 2 ||
32
+ branch_policies.length !== total_count) {
33
+ throw invalid;
34
+ }
35
+ return branch_policies.map((rule) => {
36
+ if (!isRecord(rule) || typeof rule.name !== 'string' || typeof rule.type !== 'string') {
37
+ throw invalid;
38
+ }
39
+ return { name: rule.name, type: rule.type };
40
+ });
41
+ }
@@ -0,0 +1,4 @@
1
+ import { type RunTextCommand } from '../gh-cli/exec.mts';
2
+ import type { WorkflowSecretsDependencies } from './types.mts';
3
+ /** Builds the live reads on top of an injectable `gh` runner (argv in, stdout out). */
4
+ export declare function createGhDependencies(run?: RunTextCommand): WorkflowSecretsDependencies;
@@ -0,0 +1,51 @@
1
+ import { runGh } from "../gh-cli/exec.mjs";
2
+ import { outputNames, parseDeploymentBranchPolicy, parseDeploymentBranchRules, parseSecretNames, } from "./gh-parse.mjs";
3
+ /** Builds the live reads on top of an injectable `gh` runner (argv in, stdout out). */
4
+ export function createGhDependencies(run = runGh) {
5
+ return {
6
+ resolveRepo: async () => (await run(['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'])).trim(),
7
+ listRepoSecretNames: async (repo) => parseSecretNames(await run(['secret', 'list', '-R', repo, '--json', 'name'])),
8
+ listRepositoryOwnerType: async (repo) => (await run(['api', `repos/${repo}`, '--jq', '.owner.type'])).trim(),
9
+ listRepositoryOrganizationSecretNames: async (repo) => outputNames(await run([
10
+ 'api',
11
+ `repos/${repo}/actions/organization-secrets`,
12
+ '--paginate',
13
+ '--jq',
14
+ '.secrets[].name',
15
+ ])),
16
+ listEnvironmentNames: async (repo) => outputNames(await run([
17
+ 'api',
18
+ `repos/${repo}/environments`,
19
+ '--paginate',
20
+ '--jq',
21
+ '.environments[].name',
22
+ ])),
23
+ listEnvironmentSecretNames: async (repo, environment) => outputNames(await run([
24
+ 'api',
25
+ `repos/${repo}/environments/${encodeURIComponent(environment)}/secrets`,
26
+ '--paginate',
27
+ '--jq',
28
+ '.secrets[].name',
29
+ ])),
30
+ getEnvironmentDeploymentBranchPolicy: async (repo, environment) => {
31
+ const endpoint = `repos/${repo}/environments/${encodeURIComponent(environment)}`;
32
+ const policy = parseDeploymentBranchPolicy(await run(['api', endpoint, '--jq', '.deployment_branch_policy']));
33
+ if (!policy.customBranchPoliciesEnabled || policy.protectedBranchesEnabled) {
34
+ return { ...policy, deploymentBranchRules: [] };
35
+ }
36
+ const rules = await run([
37
+ 'api',
38
+ '-X',
39
+ 'GET',
40
+ `${endpoint}/deployment-branch-policies`,
41
+ '-F',
42
+ 'per_page=2',
43
+ '-F',
44
+ 'page=1',
45
+ '--jq',
46
+ '{total_count, branch_policies: [.branch_policies[] | {name, type}]}',
47
+ ]);
48
+ return { ...policy, deploymentBranchRules: parseDeploymentBranchRules(rules) };
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,11 @@
1
+ export { runVerifyWorkflowSecretsCli, USAGE } from './cli.mts';
2
+ export type { VerifyWorkflowSecretsOptions } from './cli.mts';
3
+ export { collectLiveSecretNames } from './collect.mts';
4
+ export type { LiveSecretNames } from './collect.mts';
5
+ export { diffAgainstInventory, formatDrift, missingConfirmedSecrets, unconfirmedNewlyProvisioned, } from './drift.mts';
6
+ export type { SecretDrift } from './drift.mts';
7
+ export { createGhDependencies } from './gh.mts';
8
+ export { DEFAULT_INVENTORY_EXPORT, DEFAULT_INVENTORY_PATH, loadInventory, normalizeInventory, } from './inventory.mts';
9
+ export { requiredEnvironmentNames, requiredSecretScopeViolations } from './scopes.mts';
10
+ export type { ScopeInput } from './scopes.mts';
11
+ export type { DeploymentBranchRule, EnvironmentDeploymentBranchPolicy, WorkflowSecretInventory, WorkflowSecretInventoryEntry, WorkflowSecretsDependencies, } from './types.mts';
@@ -0,0 +1,6 @@
1
+ export { runVerifyWorkflowSecretsCli, USAGE } from "./cli.mjs";
2
+ export { collectLiveSecretNames } from "./collect.mjs";
3
+ export { diffAgainstInventory, formatDrift, missingConfirmedSecrets, unconfirmedNewlyProvisioned, } from "./drift.mjs";
4
+ export { createGhDependencies } from "./gh.mjs";
5
+ export { DEFAULT_INVENTORY_EXPORT, DEFAULT_INVENTORY_PATH, loadInventory, normalizeInventory, } from "./inventory.mjs";
6
+ export { requiredEnvironmentNames, requiredSecretScopeViolations } from "./scopes.mjs";
@@ -0,0 +1,10 @@
1
+ import type { WorkflowSecretInventory } from './types.mts';
2
+ export declare const DEFAULT_INVENTORY_PATH = ".github/workflows/workflow-secrets-inventory.mts";
3
+ export declare const DEFAULT_INVENTORY_EXPORT = "SECRET_INVENTORY";
4
+ /**
5
+ * GitHub stores secret names upper-case and treats environment names case-insensitively, so
6
+ * names are compared as upper-case secrets and lower-case environments.
7
+ */
8
+ export declare function normalizeInventory(inventory: WorkflowSecretInventory): WorkflowSecretInventory;
9
+ /** Loads the named export of an inventory module (resolved against `cwd`) and checks its shape. */
10
+ export declare function loadInventory(modulePath: string, exportName: string, cwd?: string): Promise<WorkflowSecretInventory>;
@@ -0,0 +1,78 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { resolve } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ export const DEFAULT_INVENTORY_PATH = '.github/workflows/workflow-secrets-inventory.mts';
12
+ export const DEFAULT_INVENTORY_EXPORT = 'SECRET_INVENTORY';
13
+ const OPTIONAL_FIELDS = [
14
+ ['neverProvision', 'boolean'],
15
+ ['requiredEnvironment', 'string'],
16
+ ['requiredBranchPolicy', 'string'],
17
+ ];
18
+ function entryProblem(entry) {
19
+ if (typeof entry !== 'object' || entry === null)
20
+ return 'must be an object';
21
+ return recordProblem(entry);
22
+ }
23
+ function recordProblem(record) {
24
+ if (typeof record.provisioned !== 'boolean')
25
+ return 'must have a boolean provisioned';
26
+ for (const [field, type] of OPTIONAL_FIELDS) {
27
+ if (record[field] !== undefined && typeof record[field] !== type) {
28
+ return `${field} must be a ${type}`;
29
+ }
30
+ }
31
+ if (record.neverProvision && record.provisioned) {
32
+ return 'neverProvision cannot be combined with provisioned: true';
33
+ }
34
+ if (record.neverProvision && (record.requiredEnvironment ?? record.requiredBranchPolicy)) {
35
+ return 'neverProvision cannot be combined with a required scope';
36
+ }
37
+ if (record.requiredEnvironment !== undefined && record.requiredBranchPolicy !== undefined) {
38
+ return 'requiredEnvironment and requiredBranchPolicy are mutually exclusive';
39
+ }
40
+ return undefined;
41
+ }
42
+ /**
43
+ * GitHub stores secret names upper-case and treats environment names case-insensitively, so
44
+ * names are compared as upper-case secrets and lower-case environments.
45
+ */
46
+ export function normalizeInventory(inventory) {
47
+ const normalized = {};
48
+ for (const [name, entry] of Object.entries(inventory)) {
49
+ const { requiredEnvironment, requiredBranchPolicy } = entry;
50
+ if (Object.hasOwn(normalized, name.toUpperCase())) {
51
+ throw new Error(`inventory names collide after normalization: ${name}`);
52
+ }
53
+ normalized[name.toUpperCase()] = {
54
+ ...entry,
55
+ ...(requiredEnvironment === undefined
56
+ ? {}
57
+ : { requiredEnvironment: requiredEnvironment.toLowerCase() }),
58
+ ...(requiredBranchPolicy === undefined
59
+ ? {}
60
+ : { requiredBranchPolicy: requiredBranchPolicy.toLowerCase() }),
61
+ };
62
+ }
63
+ return normalized;
64
+ }
65
+ /** Loads the named export of an inventory module (resolved against `cwd`) and checks its shape. */
66
+ export async function loadInventory(modulePath, exportName, cwd = process.cwd()) {
67
+ const loaded = (await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(cwd, modulePath)).href)));
68
+ const inventory = loaded[exportName];
69
+ if (typeof inventory !== 'object' || inventory === null || Array.isArray(inventory)) {
70
+ throw new Error(`${modulePath} must export an object named ${exportName}`);
71
+ }
72
+ for (const [name, entry] of Object.entries(inventory)) {
73
+ const problem = entryProblem(entry);
74
+ if (problem !== undefined)
75
+ throw new Error(`${modulePath}: ${exportName}.${name} ${problem}`);
76
+ }
77
+ return inventory;
78
+ }
@@ -0,0 +1,12 @@
1
+ import type { EnvironmentDeploymentBranchPolicy, WorkflowSecretInventory } from './types.mts';
2
+ export declare function requiredEnvironmentNames(inventory: WorkflowSecretInventory): Set<string>;
3
+ export interface ScopeInput {
4
+ repositoryNames: ReadonlySet<string>;
5
+ environmentNames: ReadonlyMap<string, ReadonlySet<string>>;
6
+ organizationNames: ReadonlySet<string>;
7
+ environmentDeploymentBranchPolicies: ReadonlyMap<string, EnvironmentDeploymentBranchPolicy>;
8
+ /** The only branch a required environment may deploy from. */
9
+ deploymentBranch: string;
10
+ }
11
+ /** Names whose checked-in scope contract disagrees with the live secret metadata. */
12
+ export declare function requiredSecretScopeViolations(inventory: WorkflowSecretInventory, input: ScopeInput): string[];
@@ -0,0 +1,56 @@
1
+ export function requiredEnvironmentNames(inventory) {
2
+ const names = new Set();
3
+ for (const entry of Object.values(inventory)) {
4
+ if (entry.requiredEnvironment !== undefined)
5
+ names.add(entry.requiredEnvironment);
6
+ if (entry.requiredBranchPolicy !== undefined)
7
+ names.add(entry.requiredBranchPolicy);
8
+ }
9
+ return names;
10
+ }
11
+ function permitsOnlyBranch(policy, branch) {
12
+ const [rule] = policy?.deploymentBranchRules ?? [];
13
+ return (policy?.protectedBranchesEnabled === false &&
14
+ policy.customBranchPoliciesEnabled &&
15
+ policy.deploymentBranchRules.length === 1 &&
16
+ rule?.name === branch &&
17
+ rule.type === 'branch');
18
+ }
19
+ /** Names whose checked-in scope contract disagrees with the live secret metadata. */
20
+ export function requiredSecretScopeViolations(inventory, input) {
21
+ const { repositoryNames, environmentNames, organizationNames } = input;
22
+ const violations = [];
23
+ const rejectOtherScopes = (name, keepEnvironment) => {
24
+ for (const [environment, names] of environmentNames) {
25
+ if (environment !== keepEnvironment && names.has(name)) {
26
+ violations.push(`${name} must not exist in environment ${environment}`);
27
+ }
28
+ }
29
+ if (organizationNames.has(name)) {
30
+ violations.push(`${name} must not exist as an organization secret`);
31
+ }
32
+ };
33
+ for (const [name, entry] of Object.entries(inventory)) {
34
+ if (entry.requiredEnvironment) {
35
+ if (entry.provisioned && !environmentNames.get(entry.requiredEnvironment)?.has(name)) {
36
+ violations.push(`${name} is missing from environment ${entry.requiredEnvironment}`);
37
+ }
38
+ if (repositoryNames.has(name))
39
+ violations.push(`${name} must not exist as a repository secret`);
40
+ rejectOtherScopes(name, entry.requiredEnvironment);
41
+ }
42
+ else if (entry.requiredBranchPolicy) {
43
+ if (entry.provisioned && !repositoryNames.has(name)) {
44
+ violations.push(`${name} is missing from repository secrets`);
45
+ }
46
+ rejectOtherScopes(name, undefined);
47
+ }
48
+ }
49
+ for (const environment of requiredEnvironmentNames(inventory)) {
50
+ const policy = input.environmentDeploymentBranchPolicies.get(environment);
51
+ if (!permitsOnlyBranch(policy, input.deploymentBranch)) {
52
+ violations.push(`environment ${environment} must permit deployments from only ${input.deploymentBranch}`);
53
+ }
54
+ }
55
+ return violations;
56
+ }
@@ -0,0 +1,3 @@
1
+ export declare const errorMessage: (error: unknown) => string;
2
+ /** `Promise.allSettled` over `items` with at most `limit` mappers in flight; results keep input order. */
3
+ export declare function settleLimited<T, R>(items: readonly T[], limit: number, mapper: (item: T) => Promise<R>): Promise<PromiseSettledResult<R>[]>;
@@ -0,0 +1,19 @@
1
+ export const errorMessage = (error) => error instanceof Error ? error.message : String(error);
2
+ /** `Promise.allSettled` over `items` with at most `limit` mappers in flight; results keep input order. */
3
+ export async function settleLimited(items, limit, mapper) {
4
+ const results = Array.from({ length: items.length });
5
+ let next = 0;
6
+ const worker = async () => {
7
+ while (next < items.length) {
8
+ const index = next++;
9
+ try {
10
+ results[index] = { status: 'fulfilled', value: await mapper(items[index]) };
11
+ }
12
+ catch (reason) {
13
+ results[index] = { status: 'rejected', reason };
14
+ }
15
+ }
16
+ };
17
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
18
+ return results;
19
+ }
@@ -0,0 +1,33 @@
1
+ import type { SecretInventoryEntry } from '../workflow-policy/secret-readiness.mts';
2
+ /**
3
+ * One inventory entry. Extends the readiness inventory entry with the optional drift and scope
4
+ * contracts. Only secret names and presence are ever read; values never leave the secret store.
5
+ */
6
+ export interface WorkflowSecretInventoryEntry extends SecretInventoryEntry {
7
+ /** Secret must live only in this environment, never as a repository, other-environment or organization secret. */
8
+ readonly requiredEnvironment?: string;
9
+ /** Environment kept only for its deployment-branch gate while the secret itself is repository scoped. */
10
+ readonly requiredBranchPolicy?: string;
11
+ /** Contract-only placeholder name that must never become a real secret. */
12
+ readonly neverProvision?: boolean;
13
+ }
14
+ export type WorkflowSecretInventory = Readonly<Record<string, WorkflowSecretInventoryEntry>>;
15
+ export interface DeploymentBranchRule {
16
+ name: string;
17
+ type: string;
18
+ }
19
+ export interface EnvironmentDeploymentBranchPolicy {
20
+ protectedBranchesEnabled: boolean;
21
+ customBranchPoliciesEnabled: boolean;
22
+ deploymentBranchRules: DeploymentBranchRule[];
23
+ }
24
+ /** Live secret-store reads. Every method returns names or metadata, never secret values. */
25
+ export interface WorkflowSecretsDependencies {
26
+ resolveRepo: () => Promise<string>;
27
+ listRepoSecretNames: (repo: string) => Promise<string[]>;
28
+ listRepositoryOwnerType: (repo: string) => Promise<string>;
29
+ listRepositoryOrganizationSecretNames: (repo: string) => Promise<string[]>;
30
+ listEnvironmentNames: (repo: string) => Promise<string[]>;
31
+ listEnvironmentSecretNames: (repo: string, environment: string) => Promise<string[]>;
32
+ getEnvironmentDeploymentBranchPolicy: (repo: string, environment: string) => Promise<EnvironmentDeploymentBranchPolicy>;
33
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.57.0",
3
+ "version": "0.58.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -171,6 +171,11 @@
171
171
  "import": "./dist/gha-artifacts-cleanup/index.mjs",
172
172
  "default": "./dist/gha-artifacts-cleanup/index.mjs"
173
173
  },
174
+ "./agent-issue-labels": {
175
+ "types": "./dist/agent-issue-labels/index.d.mts",
176
+ "import": "./dist/agent-issue-labels/index.mjs",
177
+ "default": "./dist/agent-issue-labels/index.mjs"
178
+ },
174
179
  "./http-origin": {
175
180
  "types": "./dist/http-origin/index.d.mts",
176
181
  "import": "./dist/http-origin/index.mjs",
@@ -301,6 +306,11 @@
301
306
  "import": "./dist/dependency-license-policy/index.mjs",
302
307
  "default": "./dist/dependency-license-policy/index.mjs"
303
308
  },
309
+ "./workflow-secrets-drift": {
310
+ "types": "./dist/workflow-secrets-drift/index.d.mts",
311
+ "import": "./dist/workflow-secrets-drift/index.mjs",
312
+ "default": "./dist/workflow-secrets-drift/index.mjs"
313
+ },
304
314
  "./nuget-central-version": {
305
315
  "types": "./dist/nuget-central-version/index.d.mts",
306
316
  "import": "./dist/nuget-central-version/index.mjs",