@mnaimfaizy/agent-kit 1.0.0-alpha.12 → 1.0.0-beta.10

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 (43) hide show
  1. package/README.md +14 -6
  2. package/bin/agent-kit.mjs +3 -1
  3. package/package.json +1 -1
  4. package/src/callers.mjs +73 -10
  5. package/src/checks/kit-owned-trees.mjs +47 -4
  6. package/src/checks/result.mjs +8 -2
  7. package/src/checks/review-response.mjs +205 -0
  8. package/src/checks/rulesets.mjs +7 -2
  9. package/src/checks/scan-recipe.mjs +56 -0
  10. package/src/checks/secrets-and-variables.mjs +65 -15
  11. package/src/cli.mjs +306 -19
  12. package/src/deep-scan/agent.mjs +410 -0
  13. package/src/deep-scan/claude-code.mjs +25 -0
  14. package/src/deep-scan/credential.mjs +215 -0
  15. package/src/deep-scan/docker-driver.mjs +696 -0
  16. package/src/deep-scan/egress.mjs +150 -0
  17. package/src/deep-scan/lifecycle.mjs +703 -0
  18. package/src/deep-scan/limits.mjs +126 -0
  19. package/src/deep-scan/model-proxy.mjs +378 -0
  20. package/src/deep-scan/preflight.mjs +78 -0
  21. package/src/deep-scan/recipe.mjs +447 -0
  22. package/src/deep-scan/relay-script.mjs +98 -0
  23. package/src/deep-scan/relay.mjs +130 -0
  24. package/src/deep-scan/runtime.mjs +181 -0
  25. package/src/deep-scan/sbx-driver.mjs +501 -0
  26. package/src/deep-scan/steps.mjs +47 -0
  27. package/src/deep-scan/tar.mjs +84 -0
  28. package/src/deep-scan/verify.mjs +272 -0
  29. package/src/deep-scan.mjs +474 -0
  30. package/src/doctor.mjs +57 -16
  31. package/src/exec.mjs +225 -23
  32. package/src/init.mjs +653 -0
  33. package/src/kit-owned-paths.mjs +5 -3
  34. package/src/kit-tag.mjs +175 -28
  35. package/src/local-tree.mjs +142 -27
  36. package/src/local-writes.mjs +278 -0
  37. package/src/prompt.mjs +42 -0
  38. package/src/safe-paths.mjs +68 -0
  39. package/src/tags.mjs +15 -5
  40. package/src/templates.mjs +137 -0
  41. package/src/upgrade.mjs +288 -0
  42. package/src/workflow-call.mjs +3 -5
  43. package/src/yaml-subset.mjs +134 -24
@@ -0,0 +1,474 @@
1
+ // `agent-kit deep-scan`: the host-side launcher for a Deep scan (ADR 0019).
2
+ // Its first stage finds the Consumer's Scan recipe at the trusted ref (the
3
+ // default branch's tip, never the working tree) and validates it, or refuses
4
+ // with what is wrong and a pointer to the docs. There is no fallback to a
5
+ // `full` audit. Then the pre-flight refusals (a GitHub token in the
6
+ // environment, a .env the copy-in would carry wholesale), what the agent is
7
+ // handed (the deep procedure and the Threat pack, at the same ref), and the
8
+ // model credential (from the environment or 1Password, kept only in this
9
+ // process); then the choice of a sandbox runtime from the host, or its
10
+ // refusal, with no override (ADR 0018). Then the sandbox lifecycle on that
11
+ // runtime, from image to teardown (deep-scan/lifecycle.mjs), its agent step
12
+ // the real Claude Code behind the key-injecting model proxy, every run
13
+ // bounded by the limits its flags set (deep-scan/limits.mjs). With
14
+ // `--verify <file> --ref <ref>`, the run is a Verification run instead
15
+ // (deep-scan/verify.mjs): local only, confirm-only against the finding file,
16
+ // on the ref the maintainer named, with its own limits.
17
+
18
+ import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
19
+ import { dirname, join, resolve } from "node:path";
20
+ import { firstLine } from "./exec.mjs";
21
+ import { detectDefaultBranch, parseAnswer } from "./init.mjs";
22
+ import { checkSafePath, UnsafePathError } from "./safe-paths.mjs";
23
+ import {
24
+ DEFAULT_RECIPE_PATH,
25
+ readRecipeAtRef,
26
+ RecipeError,
27
+ RECIPE_DOCS_URL,
28
+ recipeSteps,
29
+ validateRecipe,
30
+ } from "./deep-scan/recipe.mjs";
31
+ import { readHandIn } from "./deep-scan/agent.mjs";
32
+ import {
33
+ credentialKind,
34
+ credentialSource,
35
+ readCredential,
36
+ SUBSCRIPTION,
37
+ withoutCredentials,
38
+ } from "./deep-scan/credential.mjs";
39
+ import { DEFAULT_LIMITS, describeLimits, parseLimits, VERIFY_LIMITS } from "./deep-scan/limits.mjs";
40
+ import { runLifecycle } from "./deep-scan/lifecycle.mjs";
41
+ import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
42
+ import { envFilesAtRef, envFilesCarriedFromDefault, strayTokens } from "./deep-scan/preflight.mjs";
43
+ import { RUNTIMES_DOCS_URL, selectRuntime } from "./deep-scan/runtime.mjs";
44
+ import {
45
+ readFindingFile,
46
+ REF_NAME,
47
+ verificationProcedure,
48
+ VERIFY_DOCS_URL,
49
+ } from "./deep-scan/verify.mjs";
50
+ import { CLI_VERSION } from "./tags.mjs";
51
+
52
+ const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/security-audit.md#credentials`;
53
+
54
+ /**
55
+ * @param {{
56
+ * cwd: string,
57
+ * runner: import("./exec.mjs").Runner,
58
+ * recipePath?: string,
59
+ * defaultBranch?: string,
60
+ * credential?: string,
61
+ * credentialFrom?: string,
62
+ * model?: string,
63
+ * effort?: string,
64
+ * reportPath?: string,
65
+ * verifyPath?: string,
66
+ * ref?: string,
67
+ * limitFlags?: Record<string, string | undefined>,
68
+ * platform?: string,
69
+ * env?: Record<string, string | undefined>,
70
+ * fetch?: typeof globalThis.fetch,
71
+ * signals?: { on: Function, off: Function },
72
+ * reportDir?: string,
73
+ * modelApi?: string,
74
+ * timers?: { setTimeout: Function, clearTimeout: Function },
75
+ * out: (s: string) => void,
76
+ * err: (s: string) => void,
77
+ * }} opts `limitFlags` holds the limit flags' values, keyed by flag name.
78
+ * `verifyPath` (a finding file) and `ref` go together, for a
79
+ * Verification run.
80
+ * `platform`, `env`, `fetch`, `signals` and `timers` are the host's
81
+ * (`process.platform`, `process.env`, the global fetch, `process`, the
82
+ * real clock), and `reportDir` is a new private temporary folder, and
83
+ * `modelApi` is the real model API; only tests pass others, and no flag
84
+ * can change them.
85
+ * @returns {Promise<number>} exit code: 0 the sandbox ran and the report came
86
+ * out, 1 refused or a step failed, 2 usage error, 3 a limit stopped the
87
+ * run, 130 or 143 interrupted
88
+ */
89
+ export async function runDeepScan({
90
+ cwd,
91
+ runner: hostRunner,
92
+ recipePath,
93
+ defaultBranch,
94
+ credential,
95
+ credentialFrom,
96
+ model,
97
+ effort,
98
+ reportPath,
99
+ verifyPath,
100
+ ref,
101
+ limitFlags = {},
102
+ platform = process.platform,
103
+ env = process.env,
104
+ fetch = globalThis.fetch,
105
+ signals = process,
106
+ reportDir,
107
+ modelApi,
108
+ timers = globalThis,
109
+ out,
110
+ err,
111
+ }) {
112
+ const refuse = (lines, docs = RECIPE_DOCS_URL) => {
113
+ err([`REFUSED ${lines[0]}`, ...lines.slice(1), `See ${docs}`].join("\n"));
114
+ return 1;
115
+ };
116
+
117
+ // A Verification run: local only. Refused in CI before anything is read,
118
+ // naming no path, since a finding file names a concept id under response.
119
+ const verifying = verifyPath !== undefined;
120
+ if (verifying && env.GITHUB_ACTIONS === "true") {
121
+ return refuse(
122
+ [
123
+ "--verify has no CI form: a Verification run's finding file names a concept id that is private until release, and a CI log could show it.",
124
+ "Run it on your own machine, with an accepted sandbox runtime.",
125
+ ],
126
+ VERIFY_DOCS_URL,
127
+ );
128
+ }
129
+ if (ref !== undefined && !verifying) {
130
+ err("--ref names the ref a Verification run exports: pass --verify <file> with it.");
131
+ return 2;
132
+ }
133
+ if (verifying && ref === undefined) {
134
+ err(
135
+ "--verify needs --ref <ref>: the local branch, tag or commit to verify the fix on, such as your fix branch.",
136
+ );
137
+ return 2;
138
+ }
139
+ if (verifying && reportPath !== undefined) {
140
+ err(
141
+ "--report is not taken with --verify: a Verification run's report goes only to a new private folder on this machine.",
142
+ );
143
+ return 2;
144
+ }
145
+ if (verifying && !REF_NAME.test(ref)) {
146
+ err(`--ref must be a ref name or commit id, got: ${JSON.stringify(ref)}`);
147
+ return 2;
148
+ }
149
+
150
+ const path = recipePath ?? DEFAULT_RECIPE_PATH;
151
+ try {
152
+ checkSafePath(path, "--recipe");
153
+ } catch (e) {
154
+ if (!(e instanceof UnsafePathError)) throw e;
155
+ err(`${e.message}; give a path relative to the repository root.`);
156
+ return 2;
157
+ }
158
+
159
+ if (model !== undefined && !MODEL_ID.test(model)) {
160
+ err(
161
+ `--model must be a plain model id (letters, digits and . _ : @ / [ ] -), got: ${JSON.stringify(model)}`,
162
+ );
163
+ return 2;
164
+ }
165
+ if (effort !== undefined && !EFFORTS.includes(effort)) {
166
+ err(
167
+ `--effort must be one of ${EFFORTS.slice(0, -1).join(", ")} or ${EFFORTS.at(-1)}, got: ${JSON.stringify(effort)}`,
168
+ );
169
+ return 2;
170
+ }
171
+
172
+ // The CI workflow's delivery steps read the report from a path they name.
173
+ // Checked before anything runs, so a run never ends with nowhere to write.
174
+ let reportFile;
175
+ if (reportPath !== undefined) {
176
+ reportFile = resolve(cwd, reportPath);
177
+ if (existsSync(reportFile)) {
178
+ err(`--report ${reportFile} already exists; name a new file.`);
179
+ return 2;
180
+ }
181
+ const folder = dirname(reportFile);
182
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) {
183
+ err(`--report ${reportFile}: its folder ${folder} does not exist.`);
184
+ return 2;
185
+ }
186
+ }
187
+
188
+ const bounds = parseLimits(limitFlags, verifying ? VERIFY_LIMITS : DEFAULT_LIMITS);
189
+ if ("error" in bounds) {
190
+ err(bounds.error);
191
+ return 2;
192
+ }
193
+ const { limits } = bounds;
194
+
195
+ // The credential's kind: an API key, or the opted-into subscription token.
196
+ const chosen = credentialKind(credential);
197
+ if ("error" in chosen) {
198
+ err(chosen.error);
199
+ return 2;
200
+ }
201
+ const subscription = chosen.kind === SUBSCRIPTION;
202
+ const source = credentialSource(credentialFrom, chosen.kind);
203
+ if ("error" in source) {
204
+ err(source.error);
205
+ return 2;
206
+ }
207
+
208
+ // The finding file, read and checked on the host before anything runs.
209
+ let given = null;
210
+ if (verifying) {
211
+ const file = resolve(cwd, verifyPath);
212
+ const read = readFindingFile(file);
213
+ if ("refused" in read) return refuse(read.refused, VERIFY_DOCS_URL);
214
+ given = { ...read, file };
215
+ }
216
+ // No command this launcher runs inherits a model credential: the key
217
+ // lives only in this process, for the model proxy.
218
+ const runner = withoutCredentials(
219
+ hostRunner,
220
+ [env, process.env],
221
+ source.kind === "env" ? [source.name] : [],
222
+ );
223
+
224
+ if (defaultBranch !== undefined) {
225
+ const answer = parseAnswer("defaultBranch", defaultBranch);
226
+ if (answer.error) {
227
+ err(answer.error);
228
+ return 2;
229
+ }
230
+ }
231
+
232
+ const top = runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
233
+ if (top.status === null) {
234
+ return refuse([`Could not run git: ${firstLine(top.stderr)}`]);
235
+ }
236
+ if (top.status !== 0) {
237
+ return refuse([`${cwd} is not a git repository; deep-scan reads the Scan recipe from git.`]);
238
+ }
239
+ const root = top.stdout.trim();
240
+
241
+ // The trusted ref: the default branch's tip as this checkout has it.
242
+ const branch = defaultBranch ?? detectDefaultBranch(runner, root);
243
+ const tip = runner("git", [
244
+ "-C",
245
+ root,
246
+ "rev-parse",
247
+ "--verify",
248
+ "--quiet",
249
+ `refs/heads/${branch}^{commit}`,
250
+ ]);
251
+ if (tip.status !== 0) {
252
+ return refuse([
253
+ `No local branch ${branch} (the default branch) to read the Scan recipe from.`,
254
+ `deep-scan reads ${path} as committed on the default branch, never the working tree: create or fetch ${branch}, then run it again.`,
255
+ ...(defaultBranch === undefined
256
+ ? [
257
+ `If your default branch is not ${branch} (origin's HEAD is not set here), name it with --default-branch <name>.`,
258
+ ]
259
+ : []),
260
+ ]);
261
+ }
262
+ const commit = tip.stdout.trim();
263
+ const at = `${path} on ${branch} (${commit.slice(0, 12)})`;
264
+
265
+ let recipe;
266
+ try {
267
+ recipe = readRecipeAtRef({ runner, root, ref: commit, path });
268
+ } catch (e) {
269
+ if (!(e instanceof RecipeError)) throw e;
270
+ return refuse([`Cannot read the Scan recipe at ${branch}: ${firstLine(e.message)}`]);
271
+ }
272
+
273
+ const local = workingCopy(root, path);
274
+ if (!recipe.found) {
275
+ const lines = [
276
+ `No Scan recipe at ${path} on ${branch}. A Deep scan needs one, and does not fall back to a full audit.`,
277
+ ];
278
+ if (local !== null) {
279
+ lines.push(
280
+ `Your working tree has ${path}, but deep-scan reads only what is committed on ${branch}: commit it there first.`,
281
+ );
282
+ }
283
+ return refuse(lines);
284
+ }
285
+
286
+ const problems = validateRecipe(recipe.text);
287
+ const drift =
288
+ local !== null && lf(local) !== lf(recipe.text)
289
+ ? `Note: your working copy of ${path} differs from ${branch}'s; deep-scan used ${branch}'s.`
290
+ : null;
291
+ if (problems.length) {
292
+ return refuse([
293
+ `The Scan recipe ${at} is invalid:`,
294
+ ...problems.map((p) => ` - ${p}`),
295
+ ...(drift ? [drift] : []),
296
+ ]);
297
+ }
298
+ out(`Scan recipe ${at} is valid.`);
299
+ if (drift) out(drift);
300
+
301
+ // What is copied in as the repository: the default branch's tip, or the
302
+ // ref a Verification run names. The recipe, the skill and the Threat pack
303
+ // still come from the default branch.
304
+ let target = { name: branch, commit };
305
+ if (given) {
306
+ const found = runner("git", [
307
+ "-C",
308
+ root,
309
+ "rev-parse",
310
+ "--verify",
311
+ "--quiet",
312
+ `${ref}^{commit}`,
313
+ ]);
314
+ if (found.status !== 0) {
315
+ return refuse(
316
+ [
317
+ `No local ref ${ref} to verify the fix on: name a local branch, tag or commit.`,
318
+ "deep-scan exports a committed ref, never the working tree: commit the fix on a branch (or fetch the advisory's private-fork branch you reviewed into one), then run it again.",
319
+ ],
320
+ VERIFY_DOCS_URL,
321
+ );
322
+ }
323
+ target = { name: ref, commit: found.stdout.trim() };
324
+ }
325
+
326
+ // Pre-flight, before any runtime CLI runs.
327
+ const tokens = strayTokens(env);
328
+ if (tokens.length) {
329
+ return refuse(
330
+ [
331
+ `${tokens.join(" and ")} ${tokens.length > 1 ? "are" : "is"} set in deep-scan's environment, and a GitHub token must never reach the sandbox.`,
332
+ `Unset ${tokens.length > 1 ? "them" : "it"} for this run, for example:`,
333
+ " env -u GH_TOKEN -u GITHUB_TOKEN npx @mnaimfaizy/agent-kit deep-scan",
334
+ " In PowerShell: Remove-Item Env:GH_TOKEN, Env:GITHUB_TOKEN -ErrorAction SilentlyContinue, then run it again.",
335
+ ],
336
+ RUNTIMES_DOCS_URL,
337
+ );
338
+ }
339
+ // On what is copied in: a Verification run's ref, when there is one.
340
+ const envFiles = envFilesAtRef({ runner, root, ref: target.commit });
341
+ if ("error" in envFiles) {
342
+ return refuse(
343
+ [`Could not list the files on ${target.name}: ${envFiles.error}`],
344
+ RUNTIMES_DOCS_URL,
345
+ );
346
+ }
347
+ if (envFiles.files.length) {
348
+ return refuse(
349
+ [
350
+ `${target.name} (${target.commit.slice(0, 12)}) has environment files that the copy-in would carry into the sandbox, forwarded wholesale:`,
351
+ ...envFiles.files.map((f) => ` - ${f}`),
352
+ `Remove them from ${target.name} (keep a .env.example with placeholder values instead), and rotate any real secret they held.`,
353
+ ],
354
+ RUNTIMES_DOCS_URL,
355
+ );
356
+ }
357
+ // A Verification run still reads the Dockerfile's build context and the
358
+ // grounding paths from the default branch: check what they would carry.
359
+ if (target.commit !== commit) {
360
+ const onDefault = envFilesAtRef({ runner, root, ref: commit });
361
+ if ("error" in onDefault) {
362
+ return refuse(
363
+ [`Could not list the files on ${branch}: ${onDefault.error}`],
364
+ RUNTIMES_DOCS_URL,
365
+ );
366
+ }
367
+ const carried = envFilesCarriedFromDefault(onDefault.files, recipeSteps(recipe.text));
368
+ if (carried.files.length) {
369
+ return refuse(
370
+ [
371
+ `${branch} (${commit.slice(0, 12)}) has environment files that ${carried.why}, read from ${branch} even on a Verification run, would carry into the sandbox:`,
372
+ ...carried.files.map((f) => ` - ${f}`),
373
+ `Remove them from ${branch} too (keep a .env.example with placeholder values instead), and rotate any real secret they held.`,
374
+ ],
375
+ RUNTIMES_DOCS_URL,
376
+ );
377
+ }
378
+ }
379
+
380
+ // What the agent is handed, read at the trusted ref like the recipe.
381
+ const handed = readHandIn({ runner, root, ref: commit, branch });
382
+ if ("refused" in handed) return refuse(handed.refused);
383
+ const { handIn } = handed;
384
+ let verification;
385
+ if (given) {
386
+ const cut = verificationProcedure(handIn.skill["DEEP.md"]);
387
+ const variant = /^## Verification-run variant[ \t]*$/m.test(handIn.skill["report-format.md"]);
388
+ const missing = [
389
+ ...("missing" in cut ? cut.missing.map((m) => `DEEP.md on ${branch} has no ${m}`) : []),
390
+ ...(variant ? [] : [`report-format.md on ${branch} has no Verification-run variant`]),
391
+ ];
392
+ if (missing.length) {
393
+ return refuse(
394
+ [
395
+ `The security-audit skill is out of date for a Verification run: its ${missing.join(", and its ")}.`,
396
+ `Bring the skill up to date on ${branch} (npx @mnaimfaizy/agent-kit upgrade, then commit), then run deep-scan --verify again.`,
397
+ ],
398
+ VERIFY_DOCS_URL,
399
+ );
400
+ }
401
+ verification = { findings: given.findings, data: given.data, procedure: cut.procedure };
402
+ }
403
+ out(
404
+ `Threat pack: ${handIn.threatModel.path} and ${handIn.findingsLedger.path} (${handIn.from ? `from ${handIn.from}` : "the default paths"}); ${verification ? "the Verification-run procedure, from" : "the deep procedure:"} the security-audit skill's DEEP.md, on the same branch.`,
405
+ );
406
+ if (given) {
407
+ out(
408
+ `Verification run: ${given.findings.length} finding(s) from ${given.file}, on ${target.name} (${target.commit.slice(0, 12)}); confirm-only, with no full walk and no exploration.`,
409
+ );
410
+ }
411
+
412
+ // The model credential: read once, and kept only in this process.
413
+ const key = readCredential({ source, env, runner, kind: chosen.kind });
414
+ if ("refused" in key) return refuse(key.refused, CREDENTIALS_DOCS_URL);
415
+ out(
416
+ subscription
417
+ ? `Model credential: a Claude subscription token from ${key.from} (--credential subscription, at your own risk: it relies on undocumented Claude Code behaviour, and the token cap is its only spend lever); it stays in the model proxy, outside the sandbox.`
418
+ : `Model credential: an API key from ${key.from}; it stays in the model proxy, outside the sandbox.`,
419
+ );
420
+
421
+ const choice = selectRuntime({ runner, platform });
422
+ if ("refused" in choice) return refuse(choice.refused, RUNTIMES_DOCS_URL);
423
+ out(`Sandbox runtime: ${choice.runtime.name}.`);
424
+ out(describeLimits(limits));
425
+ return runLifecycle({
426
+ limits,
427
+ ...(model !== undefined ? { model } : {}),
428
+ ...(effort !== undefined ? { effort } : {}),
429
+ timers,
430
+ runner,
431
+ credential: key.credential,
432
+ credentialKind: chosen.kind,
433
+ credentialFrom: key.from,
434
+ ...(modelApi !== undefined ? { modelApi } : {}),
435
+ runtime: choice.runtime,
436
+ root,
437
+ branch,
438
+ commit,
439
+ steps: recipeSteps(recipe.text),
440
+ handIn,
441
+ recipePath: path,
442
+ recipeText: recipe.text,
443
+ fetch,
444
+ signals,
445
+ ...(reportDir !== undefined ? { reportDir } : {}),
446
+ ...(reportFile !== undefined ? { reportFile } : {}),
447
+ ...(verification ? { target, verification } : {}),
448
+ // The Actions log is world-readable: in GitHub Actions nothing the scan
449
+ // shaped is printed (the Public-log rule). No CI caller can forget it.
450
+ publicLog: env.GITHUB_ACTIONS === "true",
451
+ out,
452
+ err,
453
+ });
454
+ }
455
+
456
+ /**
457
+ * The effort levels Claude Code's --effort takes (2.1.328's --help), and the
458
+ * static workflow's effort input: nothing else reaches the command line.
459
+ */
460
+ export const EFFORTS = Object.freeze(["low", "medium", "high", "xhigh", "max"]);
461
+
462
+ /** Text with LF line ends, so a CRLF checkout of the same file compares equal. */
463
+ const lf = (text) => text.replace(/\r\n?/g, "\n");
464
+
465
+ /** The working tree's copy of `path` as text, or null if there is no regular file. */
466
+ function workingCopy(root, path) {
467
+ const file = join(root, path);
468
+ try {
469
+ if (!existsSync(file) || !lstatSync(file).isFile()) return null;
470
+ return readFileSync(file, "utf8");
471
+ } catch {
472
+ return null;
473
+ }
474
+ }
package/src/doctor.mjs CHANGED
@@ -9,6 +9,8 @@ import { checkKitOwnedTrees } from "./checks/kit-owned-trees.mjs";
9
9
  import { checkLabels } from "./checks/labels.mjs";
10
10
  import { checkPins } from "./checks/pins.mjs";
11
11
  import { result, sanitizeLine } from "./checks/result.mjs";
12
+ import { checkReviewResponseMode } from "./checks/review-response.mjs";
13
+ import { checkScanRecipe } from "./checks/scan-recipe.mjs";
12
14
  import {
13
15
  checkCreationRule,
14
16
  checkPersonalTagPush,
@@ -24,9 +26,7 @@ import {
24
26
  } from "./checks/secrets-and-variables.mjs";
25
27
  import { firstLine } from "./exec.mjs";
26
28
  import { createGitHub } from "./github.mjs";
27
- import { DEFAULT_SERVER, openKitTag, PreManifestTagError } from "./kit-tag.mjs";
28
-
29
- const SERVER = /^https:\/\/[A-Za-z0-9.-]+(?::\d+)?$/;
29
+ import { openKitTag, PreManifestTagError, serverFromEnv } from "./kit-tag.mjs";
30
30
 
31
31
  /**
32
32
  * The GitHub server the pins resolve on: the repository's host in a local
@@ -35,8 +35,7 @@ const SERVER = /^https:\/\/[A-Za-z0-9.-]+(?::\d+)?$/;
35
35
  */
36
36
  function serverFor(info, env) {
37
37
  if (info?.host) return `https://${info.host}`;
38
- const fromEnv = String(env.GITHUB_SERVER_URL ?? "").replace(/\/$/, "");
39
- return SERVER.test(fromEnv) ? fromEnv : DEFAULT_SERVER;
38
+ return serverFromEnv(env);
40
39
  }
41
40
 
42
41
  /** The checks that need a `gh` login with admin on the repository. */
@@ -49,6 +48,7 @@ export const LOCAL_ONLY_CHECKS = [
49
48
  ["ruleset-creation", "Release branches have a creation rule"],
50
49
  ["ruleset-tags", "Release tags have a v* tag ruleset"],
51
50
  ["release-tag-push", "Release tags can be pushed under the tag ruleset"],
51
+ ["review-response-mode", "Review response mode is set up"],
52
52
  ];
53
53
 
54
54
  const skipAll = (ids, reason) => ids.map(([id, title]) => result(id, title, "skip", reason));
@@ -183,6 +183,8 @@ export function runDoctor({
183
183
  }
184
184
  }
185
185
 
186
+ results.push(guarded("scan-recipe", () => checkScanRecipe({ root }), "Scan recipe"));
187
+
186
188
  if (mode === "ci") {
187
189
  results.push(
188
190
  ...skipAll(
@@ -214,19 +216,13 @@ function repoInfo(github, repoArg) {
214
216
  const TITLES = Object.fromEntries(LOCAL_ONLY_CHECKS);
215
217
 
216
218
  /** Run one check; an exception becomes a FAIL for that check, never a silent pass. */
217
- export function guarded(id, run) {
219
+ export function guarded(id, run, title = TITLES[id] ?? id) {
218
220
  try {
219
221
  return run();
220
222
  } catch (err) {
221
- return result(
222
- id,
223
- TITLES[id] ?? id,
224
- "fail",
225
- `Check crashed: ${firstLine(err?.message ?? err)}`,
226
- {
227
- details: ["This is a bug in doctor; the other checks still ran."],
228
- },
229
- );
223
+ return result(id, title, "fail", `Check crashed: ${firstLine(err?.message ?? err)}`, {
224
+ details: ["This is a bug in doctor; the other checks still ran."],
225
+ });
230
226
  }
231
227
  }
232
228
 
@@ -306,6 +302,11 @@ function localChecks({ runner, cwd, info, files, callers, snapshot }) {
306
302
  out.push(...skipAll(LOCAL_ONLY_CHECKS.slice(4, 7), rulesetError));
307
303
  }
308
304
  out.push(guarded("release-tag-push", () => checkPersonalTagPush({ ownerType, files })));
305
+ out.push(
306
+ guarded("review-response-mode", () =>
307
+ checkReviewResponseMode({ github, repo, ownerType, callers }),
308
+ ),
309
+ );
309
310
  return raw;
310
311
  }
311
312
 
@@ -358,7 +359,7 @@ function formatLines(report, { version } = {}) {
358
359
  return lines;
359
360
  }
360
361
 
361
- function formatResult(r) {
362
+ export function formatResult(r) {
362
363
  const out = [
363
364
  `${LABEL[r.status]} ${r.title}: ${r.summary}${r.strict ? " (warning; failed by --strict)" : ""}`,
364
365
  ];
@@ -366,3 +367,43 @@ function formatResult(r) {
366
367
  for (const f of r.fix) out.push(` $ ${f}`);
367
368
  return out;
368
369
  }
370
+
371
+ /** doctor --ci's pin and Kit-owned path checks, against an already-fetched tag. */
372
+ export function fileAndPinChecks({ runner, root, snap }) {
373
+ let pins;
374
+ try {
375
+ pins = checkPins(readWorkflows(root).files);
376
+ } catch (err) {
377
+ return [result("pins", "uses: pins agree", "fail", firstLine(err?.message ?? err))];
378
+ }
379
+ const results = [pins.result];
380
+ if (pins.tag !== snap.tag) {
381
+ results.push(
382
+ result(
383
+ "kit-owned-trees",
384
+ "Kit-owned paths match the pinned tag",
385
+ "fail",
386
+ `The pins do not all name ${snap.tag}.`,
387
+ ),
388
+ );
389
+ return results;
390
+ }
391
+ try {
392
+ results.push(checkKitOwnedTrees({ runner, cwd: root, snapshot: snap }));
393
+ } catch (err) {
394
+ results.push(
395
+ result("kit-owned-trees", "Kit-owned paths match the pinned tag", "fail", err.message),
396
+ );
397
+ }
398
+ return results;
399
+ }
400
+
401
+ /**
402
+ * Print fileAndPinChecks results under a heading, for init and upgrade.
403
+ * Returns true when one failed.
404
+ */
405
+ export function printFileAndPinChecks(out, results) {
406
+ out("Checks (as doctor --ci):");
407
+ for (const r of results) for (const line of formatResult(r)) out(line);
408
+ return results.some((r) => r.status === "fail");
409
+ }