@moo.md/hum 0.2.0 → 0.3.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.
@@ -0,0 +1,74 @@
1
+ import type { HumConfig } from "./schema.ts";
2
+
3
+ /** The secret Claude Code's OAuth token is stored in, under the env name Claude Code reads it from. */
4
+ export const CLAUDE_TOKEN = "CLAUDE_CODE_OAUTH_TOKEN";
5
+
6
+ /** The env the wake job sets itself. */
7
+ export const WAKE_ENV = {
8
+ claudeToken: CLAUDE_TOKEN,
9
+ githubToken: "GH_TOKEN",
10
+ event: "HUM_EVENT",
11
+ /** Whether the App's client ID secret is set, because a step's `if` cannot read a secret. */
12
+ hasApp: "HUM_HAS_APP",
13
+ gitName: "HUM_GIT_NAME",
14
+ gitEmail: "HUM_GIT_EMAIL",
15
+ /** Set from env, so no shell expands the token's name before git runs the helper. */
16
+ gitCredentialHelper: "HUM_GIT_CREDENTIAL_HELPER",
17
+ /** Git's own name for the file `git config --global` writes: the job points it into the runner's temp folder. */
18
+ gitConfig: "GIT_CONFIG_GLOBAL",
19
+ } as const;
20
+
21
+ /** The env names the wake job sets itself, which `ciEnv` may not set. */
22
+ export const WAKE_OWN_ENV: ReadonlySet<string> = new Set(Object.values(WAKE_ENV));
23
+
24
+ /** The action that mints a GitHub App's token, named without its version. */
25
+ export const APP_TOKEN_ACTION = "actions/create-github-app-token";
26
+
27
+ /** GitHub's fixed life of an App's installation token. */
28
+ export const APP_TOKEN_MINUTES = 60;
29
+
30
+ /** The workflow files hum writes: the wake job, and one trigger per event that starts it. */
31
+ export const WORKFLOW_FILES = {
32
+ wake: "hum-wake.yml",
33
+ comment: "hum-comment.yml",
34
+ push: "hum-push.yml",
35
+ dispatch: "hum-dispatch.yml",
36
+ schedule: "hum-schedule.yml",
37
+ } as const;
38
+
39
+ /** The names of the workflow files hum writes. */
40
+ export const CI_WORKFLOW_FILES: ReadonlySet<string> = new Set(Object.values(WORKFLOW_FILES));
41
+
42
+ /**
43
+ * How GitHub relates a comment's author to the repo, for the people hum hears: the owner, a member of the owning
44
+ * organisation and an invited collaborator. Anyone else's comment starts no wake and is no reply.
45
+ */
46
+ export const TRUSTED_ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR"] as const;
47
+
48
+ /** What the wake job takes from the owner as written, where a workflow expression may sit: the runner, the container and env. */
49
+ export type WakeJobSetting = HumConfig["ciRunner"] | HumConfig["ciContainer"] | HumConfig["ciEnv"];
50
+
51
+ /** `secrets.NAME` or `secrets['NAME']`; the quote may follow a backslash, as it does in a setting's JSON. */
52
+ const NAMED_SECRET = /\bsecrets\s*(?:\.\s*|\[\s*\\?['"])([A-Za-z_][A-Za-z0-9_]*)/g;
53
+
54
+ /** The secrets the workflow expressions in the settings name. */
55
+ export const secretsNamed = (...settings: readonly WakeJobSetting[]): string[] => [...JSON.stringify(settings).matchAll(NAMED_SECRET)].flatMap(([, name]) => name ?? []);
56
+
57
+ /** Whether `text` reads the secrets context at all, named or whole. */
58
+ export const readsSecrets = (text: string): boolean => /\bsecrets\b/.test(text);
59
+
60
+ /** A workflow expression that reads a context the wake job lacks: it has no matrix, no earlier job, and takes no inputs. */
61
+ const FOREIGN_CONTEXT = /\$\{\{[^}]*\b(matrix|strategy|needs|steps|inputs)\s*[.[]/;
62
+
63
+ /** Whether a setting holds an expression that means nothing in the wake job, so a value copied from another job would break it. */
64
+ export const readsForeignContext = (setting: WakeJobSetting): boolean => FOREIGN_CONTEXT.test(JSON.stringify(setting));
65
+
66
+ type Runner = HumConfig["ciRunner"];
67
+
68
+ const isGroup = (runner: Runner): runner is Extract<Runner, { readonly group: string }> => runner instanceof Object && "group" in runner;
69
+
70
+ /** The labels of the runners GitHub hosts start with the system they run. */
71
+ const HOSTED_LABEL = /^(ubuntu|windows|macos)-/;
72
+
73
+ /** Whether GitHub hosts the runner: a fresh machine per job. A group, or any other label, may be a machine that outlives the job. */
74
+ export const isGitHubHosted = (runner: Runner): boolean => !isGroup(runner) && [runner].flat().every((label) => HOSTED_LABEL.test(label));
@@ -1,31 +1,42 @@
1
- import { stringify } from "yaml";
1
+ import { Document, visit } from "yaml";
2
2
  import { CLAUDE_FLOOR } from "../adapters/claude-p.ts";
3
- import type { HumConfig } from "../config/schema.ts";
3
+ import type { HumConfig, PullRequestToken } from "../config/schema.ts";
4
+ import { APP_TOKEN_ACTION, CLAUDE_TOKEN, readsSecrets, secretsNamed, TRUSTED_ASSOCIATIONS, WAKE_ENV as ENV, WORKFLOW_FILES } from "../config/wake-job.ts";
4
5
 
5
6
  /** The settings the workflows are built from. */
6
- export type WorkflowSettings = Pick<HumConfig, "runBranchPrefix" | "itemsDir" | "ciSchedule" | "commitIdentity" | "ciWakeTimeoutMinutes" | "pullRequestTokenSecret">;
7
-
8
- const WAKE_FILE = "hum-wake.yml";
7
+ export type WorkflowSettings = Pick<
8
+ HumConfig,
9
+ "runBranchPrefix" | "itemsDir" | "ciSchedule" | "commitIdentity" | "ciWakeTimeoutMinutes" | "pullRequestToken" | "ciRunner" | "ciContainer" | "ciEnv" | "ciClaudeAuth"
10
+ >;
9
11
 
10
12
  /** The type of the `repository_dispatch` event a tracker's webhook sends. */
11
13
  const DISPATCH_EVENT = "hum-wake";
12
14
 
13
- const WAKE_PATH = `./.github/workflows/${WAKE_FILE}`;
14
-
15
- const TOKEN_SECRET = "CLAUDE_CODE_OAUTH_TOKEN";
15
+ const WAKE_PATH = `./.github/workflows/${WORKFLOW_FILES.wake}`;
16
16
 
17
17
  const HOPE_MARKETPLACE = "saadshahd/moo.md";
18
18
 
19
19
  /** The Bun that builds the workflows is the one the owner's repo runs, so CI installs with the same lockfile reader. */
20
20
  const BUN_VERSION = Bun.version;
21
21
 
22
- const ACTIONS = { checkout: "actions/checkout@v4", setupBun: "oven-sh/setup-bun@v2" } as const;
22
+ /**
23
+ * Each action the workflows run, at the one commit its release is. A tag can move to code that then holds the App's
24
+ * private key and every secret of the job; a commit cannot. The release rides beside the commit as a comment.
25
+ */
26
+ const ACTIONS = {
27
+ checkout: { uses: "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", release: "v7.0.1" },
28
+ appToken: { uses: `${APP_TOKEN_ACTION}@64ab729a6294000f5aa4a4bc0b73d1f32bc45510`, release: "v3.3.0" },
29
+ } as const;
30
+
31
+ const RELEASE_OF: ReadonlyMap<string, string> = new Map(Object.values(ACTIONS).map(({ uses, release }) => [uses, release]));
23
32
 
24
33
  const PERMISSIONS = { contents: "write", issues: "write", "pull-requests": "write" } as const;
25
34
 
26
35
  /** One wake at a time: a second event waits for the first run instead of racing it. */
27
36
  const CONCURRENCY = { group: "hum-wake", "cancel-in-progress": false } as const;
28
37
 
38
+ const APP_TOKEN_STEP = "app-token";
39
+
29
40
  /** The events a trigger workflow starts on. */
30
41
  type TriggerEvents = {
31
42
  readonly issue_comment?: { readonly types: readonly string[] };
@@ -46,52 +57,158 @@ const trigger = (name: string, on: TriggerEvents, job: TriggerJob = {}) => ({
46
57
  jobs: { wake: { ...job, uses: WAKE_PATH, secrets: "inherit" } },
47
58
  });
48
59
 
60
+ const secret = (name: string): string => `\${{ secrets.${name} }}`;
61
+
62
+ /** The inputs that give an App's token the workflow's own permissions, each written out as the action names it. */
63
+ const APP_TOKEN_PERMISSIONS = {
64
+ "permission-contents": PERMISSIONS.contents,
65
+ "permission-issues": PERMISSIONS.issues,
66
+ "permission-pull-requests": PERMISSIONS["pull-requests"],
67
+ } as const;
68
+
69
+ /** Where the job keeps what would else be machine-wide: a runner GitHub does not host keeps its home folder between jobs, and empties its temp folder after each. */
70
+ const JOB_TOOLS = "$RUNNER_TEMP/hum-tools";
71
+
72
+ /** Later steps read git's global config from the job's temp folder and find the job's own tools first on PATH. */
73
+ const JOB_PATHS_STEP = {
74
+ run: `echo "${ENV.gitConfig}=$RUNNER_TEMP/hum-gitconfig" >> "$GITHUB_ENV"
75
+ echo "${JOB_TOOLS}/bin" >> "$GITHUB_PATH"
76
+ `,
77
+ } as const;
78
+
79
+ /** The YAML writer leaves out a key whose value is undefined, so a job that runs on the runner itself has no `container`. */
80
+ const NO_KEY = undefined;
81
+
82
+ const OPTIONAL_SECRET = { required: false } as const;
83
+
84
+ /** The secrets the owner's settings name. A called workflow reads only the secrets it declares, so each is declared, and none is required. */
85
+ const ownerSecrets = ({ ciRunner, ciContainer, ciEnv }: Pick<WorkflowSettings, "ciRunner" | "ciContainer" | "ciEnv">) =>
86
+ Object.fromEntries(secretsNamed(ciRunner, ciContainer, ciEnv).map((name) => [name, OPTIONAL_SECRET]));
87
+
88
+ /** `ciEnv` split by reach: a value that reads a secret goes to the step that runs hum alone, so no install step holds it. */
89
+ const envByReach = (ciEnv: WorkflowSettings["ciEnv"]) => ({
90
+ everyStep: Object.fromEntries(Object.entries(ciEnv).filter(([, value]) => !readsSecrets(value))),
91
+ humStep: Object.fromEntries(Object.entries(ciEnv).filter(([, value]) => readsSecrets(value))),
92
+ });
93
+
94
+ /** The secret and env Claude Code signs in with: the OAuth token, or none where `ciEnv` carries the credentials. */
95
+ const CLAUDE_SIGN_IN = {
96
+ "oauth-token": { secrets: { [CLAUDE_TOKEN]: { required: true } }, env: { [CLAUDE_TOKEN]: secret(CLAUDE_TOKEN) } },
97
+ env: { secrets: {}, env: {} },
98
+ } as const satisfies Record<HumConfig["ciClaudeAuth"], { readonly secrets: object; readonly env: object }>;
99
+
49
100
  /**
50
- * The job every wake runs. A run clones the repo again into a temp folder, so the git credentials and identity are
51
- * global: the checkout's own are local to its workspace. A run that needs the owner has pushed its run branch, asked
52
- * on the item and ended; the owner's answer starts a fresh run on that branch, so no session, artifact or approval
53
- * is kept between runs.
101
+ * The secrets a wake's GitHub token comes from, the env and steps that turn them into it, and the expression that
102
+ * holds it. An App's token is minted with the workflow token's permissions, so both hold the same rights.
54
103
  */
55
- const wake = ({ commitIdentity, ciWakeTimeoutMinutes, pullRequestTokenSecret }: WorkflowSettings) => ({
56
- name: "hum wake",
57
- on: { workflow_call: { secrets: { [TOKEN_SECRET]: { required: true }, [pullRequestTokenSecret]: { required: false } } } },
58
- permissions: PERMISSIONS,
59
- jobs: {
60
- wake: {
61
- "runs-on": "ubuntu-latest",
62
- "timeout-minutes": ciWakeTimeoutMinutes,
63
- env: {
64
- [TOKEN_SECRET]: `\${{ secrets.${TOKEN_SECRET} }}`,
65
- GH_TOKEN: `\${{ secrets.${pullRequestTokenSecret} || github.token }}`,
66
- HUM_EVENT: "${{ github.event_name }}",
67
- },
68
- steps: [
69
- { uses: ACTIONS.checkout, with: { "fetch-depth": 0 } },
70
- { uses: ACTIONS.setupBun, with: { "bun-version": BUN_VERSION } },
71
- { run: "bun install --frozen-lockfile" },
72
- { run: `npm install --global @anthropic-ai/claude-code@${CLAUDE_FLOOR}` },
73
- { run: `claude plugin marketplace add ${HOPE_MARKETPLACE}\nclaude plugin install hope@moo.md\n` },
74
- { run: "gh auth setup-git" },
75
- {
76
- run: 'git config --global user.name "$HUM_GIT_NAME"\ngit config --global user.email "$HUM_GIT_EMAIL"\n',
77
- env: { HUM_GIT_NAME: commitIdentity.name, HUM_GIT_EMAIL: commitIdentity.email },
78
- },
79
- { run: './node_modules/.bin/hum wake --event "$HUM_EVENT"' },
80
- ],
81
- },
104
+ const githubToken = (source: PullRequestToken) =>
105
+ source.from === "secret"
106
+ ? { secrets: { [source.secret]: OPTIONAL_SECRET }, env: {}, steps: [], token: `\${{ secrets.${source.secret} || github.token }}` }
107
+ : {
108
+ secrets: { [source.clientIdSecret]: OPTIONAL_SECRET, [source.privateKeySecret]: OPTIONAL_SECRET },
109
+ env: { [ENV.hasApp]: `\${{ secrets.${source.clientIdSecret} != '' }}` },
110
+ steps: [
111
+ {
112
+ id: APP_TOKEN_STEP,
113
+ if: `env.${ENV.hasApp} == 'true'`,
114
+ uses: ACTIONS.appToken.uses,
115
+ with: {
116
+ "client-id": secret(source.clientIdSecret),
117
+ "private-key": secret(source.privateKeySecret),
118
+ ...APP_TOKEN_PERMISSIONS,
119
+ },
120
+ },
121
+ ],
122
+ token: `\${{ steps.${APP_TOKEN_STEP}.outputs.token || github.token }}`,
123
+ };
124
+
125
+ /**
126
+ * A run clones the repo again into a temp folder, so the git identity and credentials are global: the checkout's own
127
+ * are local to its workspace. Global here is the job's own file, which `JOB_PATHS_STEP` names, so no other job on the
128
+ * machine commits as hum. The credential helper hands git the token in the env when git asks, so git needs no `gh`,
129
+ * which a job container may lack. In a job container the runner's user may own the checkout while the steps run as
130
+ * root, and git refuses a repo another user owns until it is trusted.
131
+ */
132
+ const gitSetup = ({ name, email }: HumConfig["commitIdentity"]) => ({
133
+ run: `git config --global user.name "$${ENV.gitName}"
134
+ git config --global user.email "$${ENV.gitEmail}"
135
+ git config --global credential.https://github.com.helper "$${ENV.gitCredentialHelper}"
136
+ git config --global --add safe.directory "$GITHUB_WORKSPACE"
137
+ `,
138
+ env: {
139
+ [ENV.gitName]: name,
140
+ [ENV.gitEmail]: email,
141
+ [ENV.gitCredentialHelper]: `!f() { if [ "$1" = get ]; then echo username=x-access-token; echo "password=$${ENV.githubToken}"; fi; }; f`,
82
142
  },
83
143
  });
84
144
 
145
+ /**
146
+ * The job every wake runs. A run that needs the owner has pushed its run branch, asked on the item and ended; the
147
+ * owner's answer starts a fresh run on that branch, so no session, artifact or approval is kept between runs. Bun and
148
+ * Claude Code install through npm into the job's temp folder, so the job needs only git, node and npm from its runner
149
+ * or container, and leaves nothing on a machine that outlives it. The Claude sign-in, the GitHub token and every
150
+ * `ciEnv` value that reads a secret reach the last step alone. An App's token lasts an hour, so it is minted last.
151
+ */
152
+ const wake = ({ commitIdentity, ciWakeTimeoutMinutes, pullRequestToken, ciRunner, ciContainer, ciEnv, ciClaudeAuth }: WorkflowSettings) => {
153
+ const claude = CLAUDE_SIGN_IN[ciClaudeAuth];
154
+ const github = githubToken(pullRequestToken);
155
+ const env = envByReach(ciEnv);
156
+
157
+ return {
158
+ name: "hum wake",
159
+ on: { workflow_call: { secrets: { ...ownerSecrets({ ciRunner, ciContainer, ciEnv }), ...claude.secrets, ...github.secrets } } },
160
+ permissions: PERMISSIONS,
161
+ jobs: {
162
+ wake: {
163
+ "runs-on": ciRunner,
164
+ container: ciContainer ?? NO_KEY,
165
+ "timeout-minutes": ciWakeTimeoutMinutes,
166
+ env: { ...env.everyStep, ...github.env, [ENV.event]: "${{ github.event_name }}" },
167
+ steps: [
168
+ { uses: ACTIONS.checkout.uses, with: { "fetch-depth": 0 } },
169
+ JOB_PATHS_STEP,
170
+ { run: `npm install --global --prefix "${JOB_TOOLS}" bun@${BUN_VERSION} @anthropic-ai/claude-code@${CLAUDE_FLOOR}` },
171
+ { run: "bun install --frozen-lockfile" },
172
+ { run: `claude plugin marketplace add ${HOPE_MARKETPLACE}\nclaude plugin install hope@moo.md\n` },
173
+ gitSetup(commitIdentity),
174
+ ...github.steps,
175
+ { run: `./node_modules/.bin/hum wake --event "$${ENV.event}"`, env: { ...env.humStep, ...claude.env, [ENV.githubToken]: github.token } },
176
+ ],
177
+ },
178
+ },
179
+ };
180
+ };
181
+
182
+ /** A comment wakes hum only when a person the repo trusts wrote it: on a public repo anyone may comment, and a wake holds every secret. */
183
+ const TRUSTED_COMMENT = `github.event.comment.user.type != 'Bot' && contains(fromJSON('${JSON.stringify(TRUSTED_ASSOCIATIONS)}'), github.event.comment.author_association)`;
184
+
185
+ type Workflow = ReturnType<typeof wake> | ReturnType<typeof trigger>;
186
+
187
+ /** A workflow as YAML, each pinned action followed by its release as a comment, and a value two keys share written out under both. */
188
+ const render = (workflow: Workflow): string => {
189
+ const document = new Document(workflow, { aliasDuplicateObjects: false });
190
+
191
+ visit(document, {
192
+ Scalar: (_key, node) => {
193
+ const release = RELEASE_OF.get(String(node.value));
194
+
195
+ if (release !== undefined) node.comment = ` ${release}`;
196
+ },
197
+ });
198
+
199
+ return document.toString({ lineWidth: 0 });
200
+ };
201
+
85
202
  const WORKFLOWS = {
86
- [WAKE_FILE]: wake,
87
- "hum-comment.yml": () => trigger("hum on comment", { issue_comment: { types: ["created"] } }, { if: "github.event.comment.user.type != 'Bot'" }),
88
- "hum-push.yml": ({ itemsDir, runBranchPrefix }) => trigger("hum on item push", { push: { branches: ["**", `!${runBranchPrefix}**`], paths: [`${itemsDir}/**`] } }),
89
- "hum-dispatch.yml": () => trigger("hum on dispatch", { repository_dispatch: { types: [DISPATCH_EVENT] } }),
90
- "hum-schedule.yml": ({ ciSchedule }) => trigger("hum on schedule", { schedule: [{ cron: ciSchedule }], workflow_dispatch: null }),
91
- } as const satisfies Record<string, (settings: WorkflowSettings) => object>;
203
+ [WORKFLOW_FILES.wake]: wake,
204
+ [WORKFLOW_FILES.comment]: () => trigger("hum on comment", { issue_comment: { types: ["created"] } }, { if: TRUSTED_COMMENT }),
205
+ [WORKFLOW_FILES.push]: ({ itemsDir, runBranchPrefix }) => trigger("hum on item push", { push: { branches: ["**", `!${runBranchPrefix}**`], paths: [`${itemsDir}/**`] } }),
206
+ [WORKFLOW_FILES.dispatch]: () => trigger("hum on dispatch", { repository_dispatch: { types: [DISPATCH_EVENT] } }),
207
+ [WORKFLOW_FILES.schedule]: ({ ciSchedule }) => trigger("hum on schedule", { schedule: [{ cron: ciSchedule }], workflow_dispatch: null }),
208
+ } as const satisfies Record<(typeof WORKFLOW_FILES)[keyof typeof WORKFLOW_FILES], (settings: WorkflowSettings) => object>;
92
209
 
93
210
  export type WorkflowFile = { readonly file: string; readonly text: string };
94
211
 
95
212
  /** The workflow files for an owner's repo, each named for `.github/workflows/`. */
96
213
  export const ciWorkflows = (settings: WorkflowSettings): WorkflowFile[] =>
97
- Object.entries(WORKFLOWS).map(([file, build]) => ({ file, text: stringify(build(settings), { lineWidth: 0 }) }));
214
+ Object.entries(WORKFLOWS).map(([file, build]) => ({ file, text: render(build(settings)) }));
@@ -1,11 +1,17 @@
1
1
  import type { Item } from "../adapter-api.ts";
2
2
  import { declaredKind } from "../decide/kind.ts";
3
3
  import { usualSize } from "../decide/risk.ts";
4
- import type { DefaultsConfig, HumConfig, PathRule, RunPlace, SlotRecipe } from "../config/schema.ts";
4
+ import type { DefaultsConfig, HumConfig, PathRule, PullRequestToken, RunPlace, SlotRecipe } from "../config/schema.ts";
5
+ import { APP_TOKEN_ACTION, CI_WORKFLOW_FILES, CLAUDE_TOKEN, isGitHubHosted, readsForeignContext, WAKE_OWN_ENV } from "../config/wake-job.ts";
5
6
  import type { CiJob, RepoScan } from "./scan.ts";
6
7
  import {
7
8
  CHECK_COMMAND,
8
9
  CHECK_SCRIPTS,
10
+ CLAUDE_ACTION,
11
+ CLAUDE_ACTION_SIGN_IN,
12
+ CLAUDE_API_KEY,
13
+ CLAUDE_CREDENTIAL_ENV,
14
+ CLAUDE_COMMAND,
9
15
  DATA_AND_SECRET_GLOBS,
10
16
  DEFAULT_FOLDER_RANK,
11
17
  FOLDER_RANKS,
@@ -15,6 +21,7 @@ import {
15
21
  ROOT_MARKDOWN_RANK,
16
22
  RUN_SCRIPT,
17
23
  SECRET_TEMPLATE,
24
+ SECRET_VALUE,
18
25
  } from "./tables.ts";
19
26
 
20
27
  /** The settings setup proposes from a scan; the owner changes any of them before they are written. */
@@ -28,6 +35,7 @@ export type Proposal = {
28
35
  readonly kindLabels: Readonly<Record<string, string>>;
29
36
  readonly runSlots: Pick<HumConfig["runSlots"], "services" | "recipe">;
30
37
  readonly runPlaces: readonly RunPlace[];
38
+ readonly wakeJob: Pick<HumConfig, "ciRunner" | "ciContainer" | "ciEnv" | "ciClaudeAuth" | "pullRequestToken">;
31
39
  };
32
40
 
33
41
  const isPullRequestJob = ({ triggers }: CiJob): boolean => triggers.includes("pull_request");
@@ -103,8 +111,70 @@ const recipeOf = (scan: RepoScan, checks: readonly string[]): SlotRecipe => {
103
111
  };
104
112
  };
105
113
 
114
+ const isAction = (uses: string, action: string): boolean => uses.startsWith(`${action}@`);
115
+
116
+ const runsClaude = ({ commands, actions }: CiJob): boolean => commands.some((command) => CLAUDE_COMMAND.test(command)) || actions.some(({ uses }) => isAction(uses, CLAUDE_ACTION));
117
+
118
+ const secretIn = (value: string | undefined): string | undefined => (value === undefined ? undefined : SECRET_VALUE.exec(value)?.[1]);
119
+
120
+ /** The first GitHub App a job mints a token from with both its client ID, or its older App ID, and its private key in secrets. */
121
+ const appOf = (jobs: readonly CiJob[]): PullRequestToken | undefined =>
122
+ jobs
123
+ .flatMap(({ actions }) => actions)
124
+ .flatMap(({ uses, with: inputs }): PullRequestToken[] => {
125
+ const clientIdSecret = secretIn(inputs["client-id"] ?? inputs["app-id"]);
126
+ const privateKeySecret = secretIn(inputs["private-key"]);
127
+
128
+ return isAction(uses, APP_TOKEN_ACTION) && clientIdSecret !== undefined && privateKeySecret !== undefined ? [{ from: "app", clientIdSecret, privateKeySecret }] : [];
129
+ })[0];
130
+
131
+ /** The inputs a job gives the Claude Code action, all its steps together. */
132
+ const claudeInputsOf = ({ actions }: CiJob): Readonly<Record<string, string>> =>
133
+ Object.assign({}, ...actions.filter(({ uses }) => isAction(uses, CLAUDE_ACTION)).map((action) => action.with));
134
+
135
+ /** Whether a job hands Claude Code an OAuth token: its env, commands or action inputs name the token, or the action takes one under any secret's name. */
136
+ const readsClaudeToken = (job: CiJob): boolean =>
137
+ CLAUDE_ACTION_SIGN_IN.oauthToken in claudeInputsOf(job) ||
138
+ [...Object.entries(job.env).flat(), ...job.commands, ...job.actions.flatMap((action) => Object.values(action.with))].some((text) => text.includes(CLAUDE_TOKEN));
139
+
140
+ /** The env the Claude Code job signs in and runs with: its own, without the names the wake job sets itself, and the API key its action takes as an input. */
141
+ const claudeEnvOf = (job: CiJob): Record<string, string> => {
142
+ const apiKey = claudeInputsOf(job)[CLAUDE_ACTION_SIGN_IN.apiKey];
143
+ const fromInput = apiKey === undefined ? [] : [[CLAUDE_API_KEY, apiKey] as const];
144
+
145
+ return Object.fromEntries([...Object.entries(job.env), ...fromInput].filter(([name, value]) => !WAKE_OWN_ENV.has(name) && !readsForeignContext(value)));
146
+ };
147
+
148
+ /** What a scan cannot read from the files: the repo's labels, and whether anyone may read and comment on it. */
149
+ export type RepoFacts = { readonly labels?: readonly string[]; readonly isPublic?: boolean };
150
+
151
+ /**
152
+ * The wake job's settings from the job most like it: the one that runs Claude Code gives its runner, container, env
153
+ * and sign-in; without one, the first pull request job that names a runner gives its runner and container. hum's own
154
+ * workflows are left out, so a second setup reads the owner's. The App comes from any job that mints a token. Sign-in
155
+ * through env is proposed only where the env holds a credential, so no proposal signs in with nothing. A value that
156
+ * reads a context the wake job lacks would break the wake, so it is not proposed. On a public repo a runner GitHub
157
+ * does not host is never proposed: the owner names one on their own.
158
+ */
159
+ const wakeJobOf = (ci: readonly CiJob[], shipped: DefaultsConfig, isPublic: boolean): Proposal["wakeJob"] => {
160
+ const jobs = ci.filter(({ file }) => !CI_WORKFLOW_FILES.has(file));
161
+ const claude = jobs.find(runsClaude);
162
+ const like = claude ?? jobs.find((job) => isPullRequestJob(job) && job.runner !== undefined);
163
+ const ciEnv = claude ? claudeEnvOf(claude) : shipped.ciEnv;
164
+ const holdsCredential = Object.keys(ciEnv).some((name) => CLAUDE_CREDENTIAL_ENV.has(name));
165
+ const mayRunOn = (runner: HumConfig["ciRunner"]): boolean => !readsForeignContext(runner) && (!isPublic || isGitHubHosted(runner));
166
+
167
+ return {
168
+ ciRunner: like?.runner !== undefined && mayRunOn(like.runner) ? like.runner : shipped.ciRunner,
169
+ ciContainer: like?.container !== undefined && !readsForeignContext(like.container) ? like.container : shipped.ciContainer,
170
+ ciEnv,
171
+ ciClaudeAuth: claude && readsClaudeToken(claude) ? "oauth-token" : claude && holdsCredential ? "env" : shipped.ciClaudeAuth,
172
+ pullRequestToken: appOf(jobs) ?? shipped.pullRequestToken,
173
+ };
174
+ };
175
+
106
176
  /** Everything setup proposes from a scan, before it asks. */
107
- export const proposeSetup = (scan: RepoScan, shipped: DefaultsConfig, repoLabels: readonly string[] = []): Proposal => {
177
+ export const proposeSetup = (scan: RepoScan, shipped: DefaultsConfig, { labels = [], isPublic = false }: RepoFacts = {}): Proposal => {
108
178
  const checks = checksOf(scan);
109
179
 
110
180
  return {
@@ -113,8 +183,9 @@ export const proposeSetup = (scan: RepoScan, shipped: DefaultsConfig, repoLabels
113
183
  strictPaths: strictGlobsOf(scan.tracked),
114
184
  usualSizes: scan.folders.map(({ folder, sizes }) => ({ folder, usual: usualSize(sizes, shipped.sizeRange) })),
115
185
  windows: { fixWindow: shipped.changeLabels.fixWindow, measureWindow: shipped.measureWindow },
116
- kindLabels: kindLabelsOf(scan, repoLabels, shipped.kinds),
186
+ kindLabels: kindLabelsOf(scan, labels, shipped.kinds),
117
187
  runSlots: { services: shipped.runSlots.services, recipe: recipeOf(scan, checks) },
118
188
  runPlaces: shipped.runPlaces,
189
+ wakeJob: wakeJobOf(scan.ci, shipped, isPublic),
119
190
  };
120
191
  };
package/src/setup/scan.ts CHANGED
@@ -4,7 +4,7 @@ import { parseDocument } from "yaml";
4
4
  import { z } from "zod";
5
5
  import { gitIn } from "../adapters/git.ts";
6
6
  import { readHistory } from "../adapters/history.ts";
7
- import { SHIPPED_DEFAULTS } from "../config/schema.ts";
7
+ import { type HumConfig, SHIPPED_DEFAULTS } from "../config/schema.ts";
8
8
  import { SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
9
9
  import { orMissing } from "../state/fs.ts";
10
10
  import {
@@ -22,8 +22,20 @@ import {
22
22
  WORKFLOW_FOLDER,
23
23
  } from "./tables.ts";
24
24
 
25
- /** One job of a CI workflow: when it runs and the shell commands its steps run. */
26
- export type CiJob = { readonly file: string; readonly job: string; readonly triggers: readonly string[]; readonly commands: readonly string[] };
25
+ /** One job of a CI workflow: when it runs, where, with what env, and the shell commands and actions its steps run. */
26
+ export type CiJob = {
27
+ readonly file: string;
28
+ readonly job: string;
29
+ readonly triggers: readonly string[];
30
+ readonly commands: readonly string[];
31
+ /** What the job's `runs-on` holds: a label, a label list or a runner group. */
32
+ readonly runner: HumConfig["ciRunner"] | undefined;
33
+ /** The job's container: its image, with the registry sign-in, env, ports, volumes and options where the job names them. */
34
+ readonly container: NonNullable<HumConfig["ciContainer"]> | undefined;
35
+ /** The env every step gets: the workflow's, with the job's own over it. */
36
+ readonly env: Readonly<Record<string, string>>;
37
+ readonly actions: readonly { readonly uses: string; readonly with: Readonly<Record<string, string>> }[];
38
+ };
27
39
 
28
40
  type FolderHistory = { readonly folder: string; readonly changes: number; readonly sizes: readonly number[] };
29
41
 
@@ -61,9 +73,49 @@ const PackageJson = z.looseObject({
61
73
  devDependencies: z.record(z.string(), z.string()).default({}),
62
74
  });
63
75
 
76
+ /** YAML reads `1` and `true` as a number and a boolean; a workflow passes each on as text. */
77
+ const Text = z.union([z.string(), z.number(), z.boolean()]).transform(String);
78
+
79
+ /** A map's entries that are text: one that is not, such as a key YAML reads with no value, is left out alone. No entries where the workflow writes an expression in the map's place. */
80
+ const TextMap = z
81
+ .record(z.string(), z.unknown())
82
+ .catch({})
83
+ .transform((map) => Object.fromEntries(Object.entries(map).flatMap(([key, value]) => (Text.safeParse(value).success ? [[key, String(value)]] : []))));
84
+
85
+ const RunnerLabels = z.union([z.string(), z.array(z.string()).min(1)]);
86
+
87
+ /** A key the workflow leaves out stays out, so what a scan reads has the shape `hum.json` holds. */
88
+ const withoutUnset = <T extends object>(value: T): T => JSON.parse(JSON.stringify(value));
89
+
90
+ const RunsOn = z
91
+ .union([RunnerLabels, z.looseObject({ group: z.string(), labels: RunnerLabels.optional() }).transform(({ group, labels }) => withoutUnset({ group, labels })), z.looseObject({ labels: RunnerLabels }).transform(({ labels }) => labels)])
92
+ .optional()
93
+ .catch(undefined);
94
+
95
+ const Container = z
96
+ .union([
97
+ z.string(),
98
+ z
99
+ .object({ image: z.string(), credentials: z.object({ username: Text, password: Text }).optional(), env: TextMap.optional(), ports: z.array(z.union([z.string(), z.number()])).optional(), volumes: z.array(z.string()).optional(), options: z.string().optional() })
100
+ .transform(({ image, ...beside }) => (Object.values(beside).every((value) => value === undefined) ? image : withoutUnset({ image, ...beside }))),
101
+ ])
102
+ .optional()
103
+ .catch(undefined);
104
+
64
105
  const Workflow = z.looseObject({
65
106
  on: z.union([z.string().transform((trigger) => [trigger]), z.array(z.string()), z.record(z.string(), z.unknown()).transform((triggers) => Object.keys(triggers))]).default([]),
66
- jobs: z.record(z.string(), z.looseObject({ steps: z.array(z.looseObject({ run: z.string().optional() })).default([]) })).default({}),
107
+ env: TextMap,
108
+ jobs: z
109
+ .record(
110
+ z.string(),
111
+ z.looseObject({
112
+ "runs-on": RunsOn,
113
+ container: Container,
114
+ env: TextMap,
115
+ steps: z.array(z.looseObject({ run: z.string().optional(), uses: z.string().optional(), with: TextMap })).default([]),
116
+ }),
117
+ )
118
+ .default({}),
67
119
  });
68
120
 
69
121
  const Compose = z.looseObject({ services: z.record(z.string(), z.looseObject({ image: z.string().optional() })).default({}) });
@@ -95,11 +147,15 @@ const ciJobsOf = (repo: string): CiJob[] =>
95
147
 
96
148
  const triggers = workflow.on;
97
149
 
98
- return Object.entries(workflow.jobs).map(([job, { steps }]) => ({
150
+ return Object.entries(workflow.jobs).map(([job, { steps, ...where }]) => ({
99
151
  file: basename(file),
100
152
  job,
101
153
  triggers,
102
154
  commands: steps.flatMap((step) => commandsOf(step.run ?? "")),
155
+ runner: where["runs-on"],
156
+ container: where.container,
157
+ env: { ...workflow.env, ...where.env },
158
+ actions: steps.flatMap((step) => (step.uses === undefined ? [] : [{ uses: step.uses, with: step.with }])),
103
159
  }));
104
160
  });
105
161
 
@@ -40,6 +40,24 @@ export const CHECK_COMMAND = /\b(test|tests|lint|typecheck|type-check|tsc|check|
40
40
  /** A CI command line that is not a check, whatever words it holds: installs, publishing, shell plumbing. */
41
41
  export const NOT_A_CHECK = /^(echo|export|cd|mkdir|cp|mv|rm|curl|wget|sudo|gh|git)\b|\b(install|publish|deploy|release|upload|setup)\b/;
42
42
 
43
+ /** A CI command line that installs or runs Claude Code. */
44
+ export const CLAUDE_COMMAND = /@anthropic-ai\/claude-code|(^|[\s;&|(])claude(\s|$)/;
45
+
46
+ /** The action a CI step runs Claude Code with, named without its version. */
47
+ export const CLAUDE_ACTION = "anthropics/claude-code-action";
48
+
49
+ /** The action's inputs that sign Claude Code in: an API key, and the OAuth token `claude setup-token` makes. */
50
+ export const CLAUDE_ACTION_SIGN_IN = { apiKey: "anthropic_api_key", oauthToken: "claude_code_oauth_token" } as const;
51
+
52
+ /** The env name Claude Code reads an API key from. */
53
+ export const CLAUDE_API_KEY = "ANTHROPIC_API_KEY";
54
+
55
+ /** Env that signs Claude Code in with no OAuth token: a key, a gateway's token, or a cloud provider whose own credentials the job holds. */
56
+ export const CLAUDE_CREDENTIAL_ENV: ReadonlySet<string> = new Set([CLAUDE_API_KEY, "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"]);
57
+
58
+ /** An input or env value that is one secret, which the first group names. */
59
+ export const SECRET_VALUE = /^\$\{\{\s*secrets\.(\w+)\s*\}\}$/;
60
+
43
61
  /** The files that hold a repo's tool versions. */
44
62
  export const TOOL_VERSION_FILES = [".tool-versions", ".nvmrc", ".node-version", ".bun-version", ".python-version", "mise.toml", ".mise.toml", "rust-toolchain.toml", ".go-version"] as const;
45
63