@patronage/software-factory 1.0.0-alpha.46 → 1.0.0-alpha.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.js";
2
2
  import path from "node:path";
3
3
  import { Command, InvalidArgumentError } from "commander";
4
4
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
@@ -22,7 +22,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
22
22
  import { pathToFileURL } from "node:url";
23
23
  // package.json
24
24
  var name = "@patronage/software-factory";
25
- var version = "1.0.0-alpha.46";
25
+ var version = "1.0.0-alpha.48";
26
26
  // src/git-globals-parse.ts
27
27
  const VALUE_TAKING_GIT_OPTIONS = /* @__PURE__ */ new Set([
28
28
  "-C",
@@ -405,6 +405,8 @@ function gitEnv() {
405
405
  for (const [key, value] of Object.entries(process.env)) if (!omit.has(key)) env[key] = value;
406
406
  return env;
407
407
  }
408
+ const RUN_CAPTURE_MAX_BUFFER_BYTES = 67108864;
409
+ const RUN_CAPTURE_TIMEOUT_MS = 6e5;
408
410
  function runCapture(command, args, cwd, options = {}) {
409
411
  const baseEnv = path.basename(command) === "git" ? gitEnv() : process.env;
410
412
  const env = options.extraEnv === void 0 ? baseEnv : {
@@ -427,17 +429,25 @@ function runCapture(command, args, cwd, options = {}) {
427
429
  cwd,
428
430
  env: guardEnv
429
431
  });
432
+ const timeoutMs = options.timeoutMs ?? RUN_CAPTURE_TIMEOUT_MS;
430
433
  const result = spawnSync(command, args, {
431
434
  cwd,
432
435
  encoding: "utf-8",
433
436
  env,
437
+ maxBuffer: RUN_CAPTURE_MAX_BUFFER_BYTES,
434
438
  stdio: [
435
439
  "ignore",
436
440
  "pipe",
437
441
  "pipe"
438
- ]
442
+ ],
443
+ timeout: timeoutMs
439
444
  });
440
- if (result.error) throw result.error;
445
+ if (result.error) {
446
+ const { code } = result.error;
447
+ if (code === "ETIMEDOUT") throw new Error(`${command} ${args.join(" ")} did not finish within ${timeoutMs}ms`, { cause: result.error });
448
+ if (code === "ENOBUFS") throw new Error(`${command} ${args.join(" ")} wrote more than ${RUN_CAPTURE_MAX_BUFFER_BYTES} bytes of output`, { cause: result.error });
449
+ throw result.error;
450
+ }
441
451
  if (!(options.acceptableExitCodes ?? [0]).includes(result.status ?? -1)) throw new Error(`${command} ${args.join(" ")} failed:\n${result.stderr.trim()}`);
442
452
  return {
443
453
  stderr: result.stderr,
@@ -547,6 +557,15 @@ function showFileAtRef(cwd, ref, repositoryRelativePath) {
547
557
  return;
548
558
  }
549
559
  }
560
+ /** Every path tracked in the tree of `ref` (#1658). */
561
+ function trackedFilesAt(cwd, ref) {
562
+ return runCapture("git", [
563
+ "ls-tree",
564
+ "-r",
565
+ "--name-only",
566
+ ref
567
+ ], cwd).stdout.split("\n").filter(Boolean);
568
+ }
550
569
  function emptyTreeHash(cwd) {
551
570
  return runCapture("git", [
552
571
  "hash-object",
@@ -1584,7 +1603,9 @@ const parseLockfile = (content) => {
1584
1603
  try {
1585
1604
  const documents = parseAllDocuments(content);
1586
1605
  if (!Array.isArray(documents) || documents.some((document) => document.errors.length > 0)) return;
1587
- const values = documents.map((document) => document.toJS());
1606
+ const values = documents.map((document) => {
1607
+ return document.toJS();
1608
+ });
1588
1609
  const [first, second] = values;
1589
1610
  const project = values.length === 2 ? second : first;
1590
1611
  if (values.length === 0 || values.length > 2 || values.length === 2 && !isPackageManagerLockfile(first) || !isRecord$2(project)) return;
@@ -1973,6 +1994,7 @@ const DIFF_CLASSIFICATIONS = [
1973
1994
  ];
1974
1995
  // src/required-check-policy.ts
1975
1996
  const EVIDENCE_CHECK_TYPES = ["review", "verify"];
1997
+ const evidenceCheckTypeSchema = z.enum(EVIDENCE_CHECK_TYPES);
1976
1998
  const requiredCheckScopeSchema = z.object({ classifications: z.array(z.enum(DIFF_CLASSIFICATIONS)).min(1) }).strict();
1977
1999
  const requiredCheckInScope = ({ context, scope }) => {
1978
2000
  if (!scope) return {
@@ -1992,6 +2014,103 @@ const requiredCheckInScope = ({ context, scope }) => {
1992
2014
  reason: `out of scope — classification "${context.classification}" is not one of: ${scope.classifications.join(", ")}`
1993
2015
  };
1994
2016
  };
2017
+ // src/review-ladder-policy.ts
2018
+ const REVIEW_SEVERITIES = [
2019
+ "critical",
2020
+ "high",
2021
+ "medium",
2022
+ "low",
2023
+ "unknown"
2024
+ ];
2025
+ const REVIEW_CATEGORIES = [
2026
+ "correctness",
2027
+ "safety",
2028
+ "coordination",
2029
+ "maintainability",
2030
+ "unknown"
2031
+ ];
2032
+ const resolveReviewFindingSeverity = (priority) => {
2033
+ const normalized = priority?.trim().toLowerCase();
2034
+ if (!normalized) return "unknown";
2035
+ if ([
2036
+ "p0",
2037
+ "critical",
2038
+ "crit",
2039
+ "blocker",
2040
+ "blocking"
2041
+ ].includes(normalized)) return "critical";
2042
+ if ([
2043
+ "p1",
2044
+ "high",
2045
+ "severe",
2046
+ "major"
2047
+ ].includes(normalized)) return "high";
2048
+ if ([
2049
+ "p2",
2050
+ "medium",
2051
+ "moderate",
2052
+ "normal",
2053
+ "refinement"
2054
+ ].includes(normalized)) return "medium";
2055
+ if ([
2056
+ "p3",
2057
+ "p4",
2058
+ "low",
2059
+ "minor",
2060
+ "info",
2061
+ "informational"
2062
+ ].includes(normalized)) return "low";
2063
+ return "unknown";
2064
+ };
2065
+ const countFindingsBySeverity = (findings) => {
2066
+ const counts = {
2067
+ critical: 0,
2068
+ high: 0,
2069
+ low: 0,
2070
+ medium: 0,
2071
+ unknown: 0
2072
+ };
2073
+ for (const finding of findings) counts[resolveReviewFindingSeverity(finding.priority)] += 1;
2074
+ return counts;
2075
+ };
2076
+ const resolveReviewFindingCategory = (category) => REVIEW_CATEGORIES.find((value) => value === category?.trim().toLowerCase()) ?? "unknown";
2077
+ const resolveFindingBlocking = (finding, disposition = "open") => {
2078
+ if (disposition !== "open") return false;
2079
+ if (resolveReviewFindingCategory(finding.category) !== "maintainability") return true;
2080
+ if (finding.blockingAfterCap !== void 0) return finding.blockingAfterCap;
2081
+ const severity = resolveReviewFindingSeverity(finding.priority);
2082
+ return severity === "critical" || severity === "high" || severity === "unknown";
2083
+ };
2084
+ /**
2085
+ * The review-round limit in force: the base profile's
2086
+ * `review.roundsWithoutWaiver`, or the default when the base declares none.
2087
+ *
2088
+ * Callers pass the AUTHORITATIVE base policy (#922), never the candidate's, and
2089
+ * pass `undefined` when the base could not be read, so an unreadable authority
2090
+ * falls back to the stricter default rather than to anything the candidate
2091
+ * wrote.
2092
+ */
2093
+ const resolveReviewRoundsWithoutWaiver = (basePolicy) => basePolicy?.roundsWithoutWaiver ?? 2;
2094
+ const ORDINALS = [
2095
+ "first",
2096
+ "second",
2097
+ "third",
2098
+ "fourth",
2099
+ "fifth"
2100
+ ];
2101
+ /**
2102
+ * The limit as an ordinal ("second"), for the "a round past the ..." wording
2103
+ * the round-limit refusals share. Falls back to "round N" past the table.
2104
+ */
2105
+ const reviewRoundLimitOrdinal = (limit) => ORDINALS[limit - 1] ?? `round ${limit}`;
2106
+ /**
2107
+ * The review rounds a ladder holds (#1280). A round is every cycle recorded at
2108
+ * one reviewed patch-id, historical or live, so a pair of clean sessions at
2109
+ * one head is one round and a single-session review is one round. A cycle
2110
+ * with no recorded identity cannot share a patch, so it is a round of its own.
2111
+ */
2112
+ const reviewRoundCount = (cycles) => new Set(cycles.map((cycle, index) => cycle.identity?.patchId ?? `unidentified:${index}`)).size;
2113
+ const resolveReviewLadderPolicy = () => ({ gate: { cap: 5 } });
1995
2114
  // src/profile.ts
1996
2115
  const DEFAULT_FACTORY_REPOSITORY = "unknown/unknown";
1997
2116
  /**
@@ -2033,7 +2152,10 @@ const conditionalReviewSchema = z.object({ paths: z.array(z.string().min(1).refi
2033
2152
  * class: a guardrail must not lock the operator out). One definition, two parse
2034
2153
  * scopes.
2035
2154
  */
2036
- const reviewPolicySchema = z.object({ conditional: z.array(conditionalReviewSchema).min(1) }).strict();
2155
+ const reviewPolicySchema = z.object({
2156
+ conditional: z.array(conditionalReviewSchema).min(1),
2157
+ roundsWithoutWaiver: z.number().int().min(1).max(5).optional().describe(`Review rounds one pull request may record before the next round needs an operator \`review-round-limit\` waiver. Defaults to 2. At most the factory review cycle cap (5). Read from the profile on the pull request's base ref, never the candidate's own, so a change here takes effect once it has merged.`)
2158
+ }).strict();
2037
2159
  const hqEndpointDeclarationSchema = z.intersection(z.string().url(), z.string().regex(/^https:\/\/[^/@\s]+(?:[/?#]|$)/u, "Must use HTTPS without embedded credentials"));
2038
2160
  const hqIngestConfigSchema = z.object({
2039
2161
  enabled: z.boolean(),
@@ -2366,10 +2488,11 @@ function createVerificationRunContext(input) {
2366
2488
  const lockfileImporters = input.lockfileImporters !== void 0 && input.lockfileImporters.length > 0 && matchingFiles.length === 1 && matchingFiles[0] === "pnpm-lock.yaml" ? input.lockfileImporters : void 0;
2367
2489
  const forcesFullSuite = matchingFiles.length > 0 || input.changedFiles.length === 0;
2368
2490
  const fullSuiteReasons = input.changedFiles.length === 0 ? ["no changed files detected; forcing full suite"] : matchingFiles.map(fullSuiteReasonForFile);
2491
+ const runScope = forcesFullSuite && lockfileImporters === void 0 && input.trackedFiles !== void 0 ? "whole-tree" : "diff-scoped";
2369
2492
  return {
2370
2493
  baseRef: input.baseRef,
2371
2494
  buildEnv: () => {
2372
- const payload = input.changedFiles.join("\n");
2495
+ const payload = (runScope === "whole-tree" && input.trackedFiles ? input.trackedFiles() : input.changedFiles).join("\n");
2373
2496
  const env = {
2374
2497
  [FACTORY_BASE_REF_ENV]: forcesFullSuite ? fullSuiteBaseRef : input.baseRef,
2375
2498
  [FACTORY_CHANGED_FILES_ENV]: "",
@@ -2401,6 +2524,7 @@ function createVerificationRunContext(input) {
2401
2524
  changedFiles: input.changedFiles,
2402
2525
  forcesFullSuite,
2403
2526
  fullSuiteReasons,
2527
+ runScope,
2404
2528
  runSummaryLines: () => {
2405
2529
  const lines = [];
2406
2530
  if (input.changedFiles.length > 0) {
@@ -2412,6 +2536,7 @@ function createVerificationRunContext(input) {
2412
2536
  lines.push("Forcing full verification suite:");
2413
2537
  for (const reason of fullSuiteReasons) lines.push(`- ${reason}`);
2414
2538
  }
2539
+ if (runScope === "whole-tree") lines.push("Run scope: whole-tree (commands see every tracked path as changed)");
2415
2540
  return lines;
2416
2541
  }
2417
2542
  };
@@ -2837,6 +2962,7 @@ function createAffectedCommand(output) {
2837
2962
  }
2838
2963
  // src/admission-credential.ts
2839
2964
  const OPERATION_LABELS = {
2965
+ "add-hold-label": "adding the factory:hold label",
2840
2966
  "create-pull-request": "creating the pull request",
2841
2967
  "edit-pull-request-body": "editing the pull request body",
2842
2968
  "read-issue": "reading an issue",
@@ -3123,7 +3249,7 @@ const membershipWaveDemand = (graph, pr) => {
3123
3249
  kind: "unbound",
3124
3250
  reasons: [`PR #${pr} closes no declared boundary issue; membership derives from closing links — found 0 matching issues.`]
3125
3251
  };
3126
- let strictest = memberships[0];
3252
+ let [strictest] = memberships;
3127
3253
  for (const membership of memberships) if (RUNG_ORDER[membership.wave.review] > RUNG_ORDER[strictest.wave.review]) strictest = membership;
3128
3254
  return {
3129
3255
  demand: {
@@ -3586,12 +3712,14 @@ const DEMAND_KEYS = {
3586
3712
  /** The profile-resolved review ladder policy. */
3587
3713
  reviewLadder: "review-ladder",
3588
3714
  /**
3589
- * A review round past the second on one pull request (#1280). A round is
3590
- * every review recorded at one patch, so a pair of clean sessions at one
3591
- * head is one round. Only an operator waiver clears it: `pr:review
3592
- * --assemble` refuses to start a third round without one, and `pr:ready`
3593
- * refuses a ladder that holds more than two. The waiver rationale carries
3594
- * the operator's disposition.
3715
+ * A review round past the repository's round limit on one pull request
3716
+ * (#1280). The limit is `review.roundsWithoutWaiver` in the profile on the
3717
+ * base ref, 2 when absent; the candidate's own value is never read (#922).
3718
+ * A round is every review recorded at one patch, so a pair of clean
3719
+ * sessions at one head is one round. Only an operator waiver clears it:
3720
+ * `pr:review --assemble` refuses to start a round past the limit without
3721
+ * one, and `pr:ready` refuses a ladder that holds more rounds than the
3722
+ * limit. The waiver rationale carries the operator's disposition.
3595
3723
  */
3596
3724
  reviewRoundLimit: "review-round-limit",
3597
3725
  /** Unresolved GitHub review threads. */
@@ -3835,80 +3963,80 @@ const authorizeDemandWaiver = ({ authenticatedLogin, session }) => {
3835
3963
  };
3836
3964
  // src/sha256-hex.ts
3837
3965
  const ROUND_CONSTANTS = new Uint32Array([
3838
- 1116352408,
3839
- 1899447441,
3840
- 3049323471,
3841
- 3921009573,
3966
+ 0x428a2f98,
3967
+ 0x71374491,
3968
+ 0xb5c0fbcf,
3969
+ 0xe9b5dba5,
3842
3970
  961987163,
3843
- 1508970993,
3844
- 2453635748,
3845
- 2870763221,
3846
- 3624381080,
3971
+ 0x59f111f1,
3972
+ 0x923f82a4,
3973
+ 0xab1c5ed5,
3974
+ 0xd807aa98,
3847
3975
  310598401,
3848
3976
  607225278,
3849
- 1426881987,
3850
- 1925078388,
3851
- 2162078206,
3852
- 2614888103,
3853
- 3248222580,
3854
- 3835390401,
3855
- 4022224774,
3856
- 264347078,
3977
+ 0x550c7dc3,
3978
+ 0x72be5d74,
3979
+ 0x80deb1fe,
3980
+ 0x9bdc06a7,
3981
+ 0xc19bf174,
3982
+ 0xe49b69c1,
3983
+ 0xefbe4786,
3984
+ 0xfc19dc6,
3857
3985
  604807628,
3858
3986
  770255983,
3859
- 1249150122,
3860
- 1555081692,
3861
- 1996064986,
3862
- 2554220882,
3863
- 2821834349,
3864
- 2952996808,
3865
- 3210313671,
3866
- 3336571891,
3867
- 3584528711,
3868
- 113926993,
3987
+ 0x4a7484aa,
3988
+ 0x5cb0a9dc,
3989
+ 0x76f988da,
3990
+ 0x983e5152,
3991
+ 0xa831c66d,
3992
+ 0xb00327c8,
3993
+ 0xbf597fc7,
3994
+ 0xc6e00bf3,
3995
+ 0xd5a79147,
3996
+ 0x6ca6351,
3869
3997
  338241895,
3870
3998
  666307205,
3871
3999
  773529912,
3872
- 1294757372,
3873
- 1396182291,
3874
- 1695183700,
3875
- 1986661051,
3876
- 2177026350,
3877
- 2456956037,
3878
- 2730485921,
3879
- 2820302411,
3880
- 3259730800,
3881
- 3345764771,
3882
- 3516065817,
3883
- 3600352804,
3884
- 4094571909,
4000
+ 0x4d2c6dfc,
4001
+ 0x53380d13,
4002
+ 0x650a7354,
4003
+ 0x766a0abb,
4004
+ 0x81c2c92e,
4005
+ 0x92722c85,
4006
+ 0xa2bfe8a1,
4007
+ 0xa81a664b,
4008
+ 0xc24b8b70,
4009
+ 0xc76c51a3,
4010
+ 0xd192e819,
4011
+ 0xd6990624,
4012
+ 0xf40e3585,
3885
4013
  275423344,
3886
4014
  430227734,
3887
4015
  506948616,
3888
4016
  659060556,
3889
4017
  883997877,
3890
4018
  958139571,
3891
- 1322822218,
3892
- 1537002063,
3893
- 1747873779,
3894
- 1955562222,
3895
- 2024104815,
3896
- 2227730452,
3897
- 2361852424,
3898
- 2428436474,
3899
- 2756734187,
3900
- 3204031479,
3901
- 3329325298
4019
+ 0x4ed8aa4a,
4020
+ 0x5b9cca4f,
4021
+ 0x682e6ff3,
4022
+ 0x748f82ee,
4023
+ 0x78a5636f,
4024
+ 0x84c87814,
4025
+ 0x8cc70208,
4026
+ 0x90befffa,
4027
+ 0xa4506ceb,
4028
+ 0xbef9a3f7,
4029
+ 0xc67178f2
3902
4030
  ]);
3903
4031
  const INITIAL_STATE = new Uint32Array([
3904
- 1779033703,
3905
- 3144134277,
3906
- 1013904242,
3907
- 2773480762,
3908
- 1359893119,
3909
- 2600822924,
4032
+ 0x6a09e667,
4033
+ 0xbb67ae85,
4034
+ 0x3c6ef372,
4035
+ 0xa54ff53a,
4036
+ 0x510e527f,
4037
+ 0x9b05688c,
3910
4038
  528734635,
3911
- 1541459225
4039
+ 0x5be0cd19
3912
4040
  ]);
3913
4041
  const BLOCK_BYTES = 64;
3914
4042
  const LENGTH_FIELD_BYTES = 8;
@@ -4052,82 +4180,6 @@ const findingKey = (finding) => {
4052
4180
  return sha256Hex(`${path}\0${spanDigest}\0${actionJoined}\0${legacyDiscriminator}`);
4053
4181
  };
4054
4182
  const declarationMatchesEntry = (entry, target) => normalizeTitle(entry.title) === normalizeTitle(target.title) && (target.file === void 0 || entry.file !== void 0 && normalizeFile(entry.file) === normalizeFile(target.file));
4055
- // src/review-ladder-policy.ts
4056
- const REVIEW_SEVERITIES = [
4057
- "critical",
4058
- "high",
4059
- "medium",
4060
- "low",
4061
- "unknown"
4062
- ];
4063
- const REVIEW_CATEGORIES = [
4064
- "correctness",
4065
- "safety",
4066
- "coordination",
4067
- "maintainability",
4068
- "unknown"
4069
- ];
4070
- const resolveReviewFindingSeverity = (priority) => {
4071
- const normalized = priority?.trim().toLowerCase();
4072
- if (!normalized) return "unknown";
4073
- if ([
4074
- "p0",
4075
- "critical",
4076
- "crit",
4077
- "blocker",
4078
- "blocking"
4079
- ].includes(normalized)) return "critical";
4080
- if ([
4081
- "p1",
4082
- "high",
4083
- "severe",
4084
- "major"
4085
- ].includes(normalized)) return "high";
4086
- if ([
4087
- "p2",
4088
- "medium",
4089
- "moderate",
4090
- "normal",
4091
- "refinement"
4092
- ].includes(normalized)) return "medium";
4093
- if ([
4094
- "p3",
4095
- "p4",
4096
- "low",
4097
- "minor",
4098
- "info",
4099
- "informational"
4100
- ].includes(normalized)) return "low";
4101
- return "unknown";
4102
- };
4103
- const countFindingsBySeverity = (findings) => {
4104
- const counts = {
4105
- critical: 0,
4106
- high: 0,
4107
- low: 0,
4108
- medium: 0,
4109
- unknown: 0
4110
- };
4111
- for (const finding of findings) counts[resolveReviewFindingSeverity(finding.priority)] += 1;
4112
- return counts;
4113
- };
4114
- const resolveReviewFindingCategory = (category) => REVIEW_CATEGORIES.find((value) => value === category?.trim().toLowerCase()) ?? "unknown";
4115
- const resolveFindingBlocking = (finding, disposition = "open") => {
4116
- if (disposition !== "open") return false;
4117
- if (resolveReviewFindingCategory(finding.category) !== "maintainability") return true;
4118
- if (finding.blockingAfterCap !== void 0) return finding.blockingAfterCap;
4119
- const severity = resolveReviewFindingSeverity(finding.priority);
4120
- return severity === "critical" || severity === "high" || severity === "unknown";
4121
- };
4122
- const FACTORY_REVIEW_CYCLE_CAP = 5;
4123
- /**
4124
- * The review rounds a ladder holds (#1280). A round is every cycle recorded at
4125
- * one reviewed patch-id, historical or live, so a pair of clean sessions at
4126
- * one head is one round and a single-session review is one round. A cycle
4127
- * with no recorded identity cannot share a patch, so it is a round of its own.
4128
- */
4129
- const reviewRoundCount = (cycles) => new Set(cycles.map((cycle, index) => cycle.identity?.patchId ?? `unidentified:${index}`)).size;
4130
- const resolveReviewLadderPolicy = () => ({ gate: { cap: FACTORY_REVIEW_CYCLE_CAP } });
4131
4183
  // src/review-ladder-ledger.ts
4132
4184
  const OCCURRENCE_ADDRESS_PATTERN = /^c[1-9][0-9]*f[1-9][0-9]*$/u;
4133
4185
  const occurrenceAddress = (cycle, finding) => `c${cycle}f${finding}`;
@@ -5242,7 +5294,10 @@ const compareStrings = (left, right) => {
5242
5294
  const canonicalReviewPolicy = (review) => {
5243
5295
  if (review === void 0) return JSON.stringify(null);
5244
5296
  const groups = review.conditional.map((group) => ({ paths: [...group.paths].toSorted(compareStrings) }));
5245
- return JSON.stringify({ conditional: groups.toSorted((left, right) => compareStrings(JSON.stringify(left.paths), JSON.stringify(right.paths))) });
5297
+ return JSON.stringify({
5298
+ conditional: groups.toSorted((left, right) => compareStrings(JSON.stringify(left.paths), JSON.stringify(right.paths))),
5299
+ ...review.roundsWithoutWaiver === void 0 ? {} : { roundsWithoutWaiver: review.roundsWithoutWaiver }
5300
+ });
5246
5301
  };
5247
5302
  /** Every protected path a policy declares, across all of its groups. */
5248
5303
  const reviewPolicyPaths = (review) => (review?.conditional ?? []).flatMap((group) => group.paths);
@@ -5475,6 +5530,7 @@ const resolveReviewDemand = ({ authority, callerBaseRef, candidatePolicy, change
5475
5530
  changedFiles
5476
5531
  });
5477
5532
  return {
5533
+ basePolicy: base.policy,
5478
5534
  demand,
5479
5535
  policyResolution: authoritativePolicyResolution({
5480
5536
  base,
@@ -5485,6 +5541,14 @@ const resolveReviewDemand = ({ authority, callerBaseRef, candidatePolicy, change
5485
5541
  };
5486
5542
  };
5487
5543
  /**
5544
+ * The review-round limit a stage enforces (#1280): the one the authoritative
5545
+ * base policy declares. The candidate's own `review.roundsWithoutWaiver` is
5546
+ * never read, so a pull request cannot raise its own limit; a change to the
5547
+ * limit takes effect once it is on the base ref. An unresolved authority falls
5548
+ * back to the factory default, the stricter answer.
5549
+ */
5550
+ const authoritativeReviewRoundsWithoutWaiver = (resolved) => resolveReviewRoundsWithoutWaiver(resolved.status === "authoritative" ? resolved.basePolicy : void 0);
5551
+ /**
5488
5552
  * The authoring stages' entry point (#922 Slice B): `pr:verify` and
5489
5553
  * `pr:review`, which hold a git ref and a checkout rather than a PR number.
5490
5554
  *
@@ -6077,7 +6141,7 @@ const hqAllowedOriginsFromEnv = (env) => {
6077
6141
  const candidate = segment.trim();
6078
6142
  if (candidate === "") continue;
6079
6143
  const endpoint = validatedHqOrigin(candidate);
6080
- if (endpoint !== void 0 && candidate === endpoint.origin) origins.push(endpoint.origin);
6144
+ if (candidate === endpoint?.origin) origins.push(endpoint.origin);
6081
6145
  }
6082
6146
  return origins;
6083
6147
  };
@@ -6571,7 +6635,7 @@ const reportDiagnostic = async (dependencies, deadline, message, prefix = "HQ in
6571
6635
  }
6572
6636
  if (remainingMs(deadline) <= 0) return;
6573
6637
  if (!usesCustomDiagnostic) {
6574
- diagnostic(line);
6638
+ defaultDiagnostic(line);
6575
6639
  return;
6576
6640
  }
6577
6641
  setImmediate(async () => {
@@ -8541,14 +8605,32 @@ async function postCheckRunThroughRelay(relay, body, request, timeoutMs) {
8541
8605
  return await response.json();
8542
8606
  }
8543
8607
  // src/github-app-client.ts
8608
+ const GITHUB_DEFAULT_HEADERS = {
8609
+ Accept: "application/vnd.github+json",
8610
+ "X-GitHub-Api-Version": "2022-11-28"
8611
+ };
8612
+ /**
8613
+ * The GitHub defaults overlaid with a caller's headers, as a plain record.
8614
+ * Spreading a `Headers` instance or a tuple list into an object literal copies
8615
+ * no headers (or numeric indices), so those two forms go through `Headers`. A
8616
+ * plain record keeps its key casing. A caller's header replaces a default of
8617
+ * the same name in any casing, rather than sitting beside it.
8618
+ */
8619
+ const githubRequestHeaders = (headers) => {
8620
+ const caller = {};
8621
+ if (headers instanceof Headers || Array.isArray(headers)) Object.assign(caller, Object.fromEntries(new Headers(headers)));
8622
+ else for (const [name, value] of Object.entries(headers ?? {})) if (value !== void 0) caller[name] = value;
8623
+ const overridden = new Set(Object.keys(caller).map((name) => name.toLowerCase()));
8624
+ const defaults = Object.entries(GITHUB_DEFAULT_HEADERS).filter(([name]) => !overridden.has(name.toLowerCase()));
8625
+ return {
8626
+ ...Object.fromEntries(defaults),
8627
+ ...caller
8628
+ };
8629
+ };
8544
8630
  const readExchange = async (request, url, init, timeoutMs) => {
8545
8631
  const response = await request(url, {
8546
8632
  ...init,
8547
- headers: {
8548
- Accept: "application/vnd.github+json",
8549
- "X-GitHub-Api-Version": "2022-11-28",
8550
- ...init.headers
8551
- },
8633
+ headers: githubRequestHeaders(init.headers),
8552
8634
  signal: init.signal ?? AbortSignal.timeout(timeoutMs)
8553
8635
  });
8554
8636
  const etag = response.headers.get("etag") ?? void 0;
@@ -9024,6 +9106,7 @@ const prVerifyProofSchema = z.object({
9024
9106
  projectKey: z.string().min(1),
9025
9107
  repository: z.string().min(1),
9026
9108
  runner: runnerSchema.optional(),
9109
+ runScope: z.literal("whole-tree").optional(),
9027
9110
  schemaVersion: prVerifySchemaVersionSchema,
9028
9111
  startedAt: z.iso.datetime(),
9029
9112
  verificationCommands: z.array(z.object({
@@ -9085,6 +9168,7 @@ const prVerifyCheckPayloadFor = (proof) => {
9085
9168
  schemaVersion: PR_VERIFY_CHECK_PAYLOAD_SCHEMA_VERSION,
9086
9169
  ...typeof value.patchId === "string" ? { patchId: value.patchId } : {},
9087
9170
  ...typeof value.repository === "string" ? { repository: value.repository } : {},
9171
+ ...value.runScope === "whole-tree" ? { runScope: "whole-tree" } : {},
9088
9172
  ...carriesReleases && value.verificationCommands !== void 0 ? { verificationCommands: value.verificationCommands } : {}
9089
9173
  };
9090
9174
  try {
@@ -9101,6 +9185,12 @@ const readTransportedVerifyProof = (value, text) => {
9101
9185
  if (value === void 0 || new TextEncoder().encode(text).length > 6e4) return {};
9102
9186
  return { verificationProof: validatePrVerifyProof(value) };
9103
9187
  };
9188
+ /** The parsed payload's optional identity and scope fields, kept only when well-typed. */
9189
+ const optionalIdentityFields = (parsed) => ({
9190
+ ...typeof parsed.patchId === "string" ? { patchId: parsed.patchId } : {},
9191
+ ...typeof parsed.repository === "string" ? { repository: parsed.repository } : {},
9192
+ ...parsed.runScope === "whole-tree" ? { runScope: "whole-tree" } : {}
9193
+ });
9104
9194
  /**
9105
9195
  * Parse the binding back out of check-run `output.text` (preferred) or
9106
9196
  * `output.summary`. Absence / unparseable / wrong shape ⇒ `undefined`, so a
@@ -9124,8 +9214,7 @@ const parsePrVerifyCheckPayload = (text) => {
9124
9214
  outcome: parsed.outcome,
9125
9215
  proofSchemaVersion: typeof parsed.proofSchemaVersion === "number" ? parsed.proofSchemaVersion : 0,
9126
9216
  schemaVersion: PR_VERIFY_CHECK_PAYLOAD_SCHEMA_VERSION,
9127
- ...typeof parsed.patchId === "string" ? { patchId: parsed.patchId } : {},
9128
- ...typeof parsed.repository === "string" ? { repository: parsed.repository } : {},
9217
+ ...optionalIdentityFields(parsed),
9129
9218
  ...parsed.verificationCommands === void 0 ? {} : { verificationCommands: parsed.verificationCommands }
9130
9219
  };
9131
9220
  } catch {}
@@ -10984,6 +11073,7 @@ function defaultPrVerifyGit() {
10984
11073
  mergeBaseSha,
10985
11074
  recognizeCatchUp: recognizeCatchUpCandidate,
10986
11075
  resolveCommitSha,
11076
+ trackedFilesAt,
10987
11077
  runVerificationCommand(command, cwd, env) {
10988
11078
  return verificationOutcomeOf(runInheritedTee("bash", ["-lc", withPinnedNodeOnPath(command, path.dirname(process.execPath))], cwd, env));
10989
11079
  },
@@ -11017,7 +11107,7 @@ function baselineFullProofsForDocsOnly({ previousProof, profilePath, projectKey,
11017
11107
  seedFilter: matchesProfile
11018
11108
  });
11019
11109
  }
11020
- function buildPrVerifyProof({ authoringSession, base, baseSha, baselineFullProofs, catchUpRecognition, classification, commands, endedAt, executedCommands, files, headSha, impactStamp, mode, mergeBaseSha: proofMergeBaseSha, notRequiredCommands, outcome, patchId, policyResolution, profilePath, projectKey, repository, runner, startedAt }) {
11110
+ function buildPrVerifyProof({ authoringSession, base, baseSha, baselineFullProofs, catchUpRecognition, classification, commands, endedAt, executedCommands, files, headSha, impactStamp, mode, mergeBaseSha: proofMergeBaseSha, notRequiredCommands, outcome, patchId, policyResolution, profilePath, projectKey, repository, runner, runScope, startedAt }) {
11021
11111
  return {
11022
11112
  authoringSession,
11023
11113
  base,
@@ -11043,6 +11133,7 @@ function buildPrVerifyProof({ authoringSession, base, baseSha, baselineFullProof
11043
11133
  projectKey,
11044
11134
  repository,
11045
11135
  ...runner ? { runner } : {},
11136
+ ...runScope === "whole-tree" ? { runScope } : {},
11046
11137
  schemaVersion: 4,
11047
11138
  startedAt: startedAt.toISOString(),
11048
11139
  verificationCommands: commands
@@ -11176,7 +11267,8 @@ function runPrVerify(args, dependencies = {}) {
11176
11267
  changedFiles: files,
11177
11268
  fullSuiteBaseRef: git.emptyTreeHash(cwd),
11178
11269
  ...lockfileScope?.kind === "scoped" ? { lockfileImporters: lockfileScope.importers } : {},
11179
- rootSharedGlobs
11270
+ rootSharedGlobs,
11271
+ ...git.trackedFilesAt ? { trackedFiles: () => git.trackedFilesAt(cwd, headSha) } : {}
11180
11272
  });
11181
11273
  const resolvedMode = context.forcesFullSuite ? "full" : resolveMode({
11182
11274
  classification: classification.classification,
@@ -11230,7 +11322,7 @@ function runPrVerify(args, dependencies = {}) {
11230
11322
  sha: headSha
11231
11323
  });
11232
11324
  const accepted = binding?.payload.verificationProof;
11233
- if (binding?.conclusion === "success" && binding.payload.outcome === "passed" && accepted && accepted.outcome === "passed" && policyResolutionAllowsProofReuse(accepted.policyResolution) && accepted.authoringSession !== "unknown" && commands.every((command) => scopedOutNames.has(command.name) || accepted.executedCommands?.some((executed) => executed.name === command.name && executed.command === command.command && executed.scope === command.scope && executed.exitCode === 0)) && accepted.executedCommands?.every((executed) => executed.exitCode === 0) && accepted.headSha === headSha && accepted.patchId === patchId && accepted.repository === repository && accepted.base === base.ref && accepted.baseSha === base.sha && accepted.mergeBaseSha === proofMergeBaseSha && accepted.mode === resolvedMode && accepted.classification === classification.classification && vetoedTargets.length === 0 && isDeepStrictEqual(accepted.changedFiles.toSorted(), files.toSorted()) && isDeepStrictEqual(accepted.verificationCommands, commands) && isDeepStrictEqual(accepted.impactStamp, impactStamp) && isDeepStrictEqual(accepted.notRequiredCommands ?? [], notRequiredCommands) && isDeepStrictEqual(accepted.policyResolution, policyResolution)) {
11325
+ if (binding?.conclusion === "success" && binding.payload.outcome === "passed" && accepted?.outcome === "passed" && policyResolutionAllowsProofReuse(accepted.policyResolution) && accepted.authoringSession !== "unknown" && commands.every((command) => scopedOutNames.has(command.name) || accepted.executedCommands?.some((executed) => executed.name === command.name && executed.command === command.command && executed.scope === command.scope && executed.exitCode === 0)) && accepted.executedCommands?.every((executed) => executed.exitCode === 0) && accepted.headSha === headSha && accepted.patchId === patchId && accepted.repository === repository && accepted.base === base.ref && accepted.baseSha === base.sha && accepted.mergeBaseSha === proofMergeBaseSha && accepted.mode === resolvedMode && accepted.classification === classification.classification && vetoedTargets.length === 0 && isDeepStrictEqual(accepted.changedFiles.toSorted(), files.toSorted()) && isDeepStrictEqual(accepted.verificationCommands, commands) && isDeepStrictEqual(accepted.impactStamp, impactStamp) && isDeepStrictEqual(accepted.notRequiredCommands ?? [], notRequiredCommands) && isDeepStrictEqual(accepted.policyResolution, policyResolution)) {
11234
11326
  assertCleanWorktreeForProof({
11235
11327
  cwd,
11236
11328
  dirtyMessage: "Checkout changed while reading accepted verification.",
@@ -11280,6 +11372,7 @@ function runPrVerify(args, dependencies = {}) {
11280
11372
  projectKey: profile.repository.name,
11281
11373
  repository,
11282
11374
  runner: (dependencies.describeRunner ?? describeVerifyRunner)(dependencies.env ?? process.env),
11375
+ runScope: context.runScope,
11283
11376
  startedAt
11284
11377
  };
11285
11378
  const writePartialProof = (outcome) => {
@@ -11573,6 +11666,12 @@ const runDemandWaive = (args, dependencies = {}) => {
11573
11666
  if (args.json) console.log(JSON.stringify(waiver, null, 2));
11574
11667
  return waiver;
11575
11668
  };
11669
+ // src/arming-outcome.ts
11670
+ const ARMING_OUTCOMES = [
11671
+ "armed",
11672
+ "merged",
11673
+ "not-armed"
11674
+ ];
11576
11675
  /** One refusal sentence: single line, trimmed, bounded. */
11577
11676
  const blockedReasonDetailSchema = z.string().min(1).max(280).refine((value) => value.trim().length > 0, { message: "must not be blank" }).refine((value) => !/[\r\n]/u.test(value), { message: "must be one line, not a multi-line payload" });
11578
11677
  const blockedReasonSchema = z.object({
@@ -12364,7 +12463,6 @@ const closeoutArtifactSchema = z.object({
12364
12463
  schemaVersion: z.literal(5)
12365
12464
  }).strict();
12366
12465
  // src/schemas.ts
12367
- const evidenceCheckTypeSchema = z.enum(EVIDENCE_CHECK_TYPES);
12368
12466
  const evidenceReviewRungSchema = z.enum(EVIDENCE_REVIEW_RUNGS);
12369
12467
  const diffClassificationSchema = z.enum(DIFF_CLASSIFICATIONS);
12370
12468
  const ladderStageSchema = z.enum(LADDER_STAGES);
@@ -12627,15 +12725,11 @@ const managedReadinessLedgerSchema$1 = z.object({
12627
12725
  ])
12628
12726
  });
12629
12727
  const prReadySchemaVersionSchema = z.literal(3);
12630
- z.object({
12728
+ const prReadyProofSchema = z.object({
12631
12729
  arming: z.object({
12632
12730
  detail: z.string().min(1).optional(),
12633
12731
  headSha: z.string().regex(/^[0-9a-f]{40}$/u),
12634
- outcome: z.enum([
12635
- "armed",
12636
- "merged",
12637
- "not-armed"
12638
- ])
12732
+ outcome: z.enum(ARMING_OUTCOMES)
12639
12733
  }).optional(),
12640
12734
  authoringSession: z.string().min(1).optional(),
12641
12735
  blockedReasons: blockedReasonsSchema.optional(),
@@ -17777,9 +17871,7 @@ const FACTORY_HOLD_LABEL = "factory:hold";
17777
17871
  /**
17778
17872
  * `--hold` on pr:publish and pr:ready (#1513): put `factory:hold` on the pull
17779
17873
  * request before anything can arm it, so readiness admits it and leaves the
17780
- * merge to a person. A REST call, so it works where GraphQL is refused, and
17781
- * on the operator's own credential, like every other write that is not a
17782
- * pull request create or body edit.
17874
+ * merge to a person. A REST call, so it works where GraphQL is refused.
17783
17875
  */
17784
17876
  const ghApiArgsForHoldLabel = ({ owner, pr, repo }) => [
17785
17877
  "api",
@@ -17789,8 +17881,20 @@ const ghApiArgsForHoldLabel = ({ owner, pr, repo }) => [
17789
17881
  "-f",
17790
17882
  `labels[]=${FACTORY_HOLD_LABEL}`
17791
17883
  ];
17792
- const holdPullRequest = (input) => {
17793
- runCapture("gh", ghApiArgsForHoldLabel(input), input.cwd);
17884
+ /**
17885
+ * Off a Cursor managed runtime the label goes on with the operator's own
17886
+ * credential. A Cursor VM's own `gh` token cannot write labels, so there it
17887
+ * runs on the Factory App broker's admission token, whose `pull_requests:
17888
+ * write` covers labelling a pull request (#1653). A failed mint throws
17889
+ * `AdmissionCredentialError` before `gh` runs: the VM's credential is never
17890
+ * tried.
17891
+ */
17892
+ const holdPullRequest = async (input, dependencies = {}) => {
17893
+ const extraEnv = await (dependencies.admission ?? processAdmissionCredential).ghEnv("add-hold-label", {
17894
+ owner: input.owner,
17895
+ repo: input.repo
17896
+ });
17897
+ (dependencies.run ?? runCapture)("gh", ghApiArgsForHoldLabel(input), input.cwd, extraEnv === void 0 ? {} : { extraEnv });
17794
17898
  };
17795
17899
  // src/pr-publish-transaction-error.ts
17796
17900
  /**
@@ -18100,7 +18204,7 @@ const checkTimestampMs = (check) => {
18100
18204
  const effectiveChecks = (rollup) => {
18101
18205
  const checksByContext = /* @__PURE__ */ new Map();
18102
18206
  const unkeyed = [];
18103
- for (const [index, check] of rollup.entries()) {
18207
+ for (const check of rollup) {
18104
18208
  const context = checkContext(check);
18105
18209
  if (!context) {
18106
18210
  unkeyed.push(check);
@@ -18109,7 +18213,6 @@ const effectiveChecks = (rollup) => {
18109
18213
  const checks = checksByContext.get(context) ?? [];
18110
18214
  checks.push({
18111
18215
  check,
18112
- index,
18113
18216
  timestampMs: checkTimestampMs(check)
18114
18217
  });
18115
18218
  checksByContext.set(context, checks);
@@ -18122,20 +18225,17 @@ const effectiveChecks = (rollup) => {
18122
18225
  currentChecks.push(firstCheck.check);
18123
18226
  continue;
18124
18227
  }
18125
- if (checks.some((check) => check.timestampMs === void 0)) {
18228
+ const orderable = checks.flatMap((check) => check.timestampMs === void 0 ? [] : [{
18229
+ check: check.check,
18230
+ orderMs: check.timestampMs
18231
+ }]);
18232
+ if (orderable.length !== checks.length) {
18126
18233
  currentChecks.push(...checks.map((check) => check.check));
18127
18234
  continue;
18128
18235
  }
18129
- let latest = firstCheck;
18130
- for (const candidate of checks.slice(1)) {
18131
- if (latest.timestampMs === void 0 || candidate.timestampMs === void 0) continue;
18132
- if (candidate.timestampMs > latest.timestampMs) {
18133
- latest = candidate;
18134
- continue;
18135
- }
18136
- if (candidate.timestampMs === latest.timestampMs && candidate.index > latest.index) latest = candidate;
18137
- }
18138
- currentChecks.push(latest.check);
18236
+ const newest = selectNewestGeneration(orderable);
18237
+ if (newest.kind === "newest") currentChecks.push(newest.generation.check);
18238
+ else if (newest.kind === "ambiguous") currentChecks.push(...newest.tied.map((generation) => generation.check));
18139
18239
  }
18140
18240
  return currentChecks;
18141
18241
  };
@@ -18942,13 +19042,9 @@ const readinessRepairSchema = z.object({
18942
19042
  const managedReadinessLedgerSchema = z.object({
18943
19043
  baseSha: shaSchema$1,
18944
19044
  blockingReasons: z.array(z.string()),
18945
- classification: z.enum([
18946
- "docs/process-only",
18947
- "trivial",
18948
- "non-trivial"
18949
- ]),
19045
+ classification: z.enum(DIFF_CLASSIFICATIONS),
18950
19046
  externalChecks: z.array(z.object({
18951
- checkType: z.enum(EVIDENCE_CHECK_TYPES),
19047
+ checkType: evidenceCheckTypeSchema,
18952
19048
  name: z.string().min(1),
18953
19049
  reason: z.string().optional(),
18954
19050
  scope: requiredCheckScopeSchema.optional(),
@@ -19476,18 +19572,20 @@ const armedWithoutBoundaryBlockers = (input) => {
19476
19572
  }];
19477
19573
  };
19478
19574
  /**
19479
- * #1280: a review round past the second is a demand only the operator waives.
19480
- * `pr:review --assemble` refuses to start a third round without the waiver;
19481
- * this is the same refusal at admission, for a ladder that reached a third
19482
- * round by any other route. A round is every cycle recorded at one patch,
19483
- * historical or live.
19575
+ * #1280: a review round past the repository's limit is a demand only the
19576
+ * operator waives. `pr:review --assemble` refuses to start such a round without
19577
+ * the waiver; this is the same refusal at admission, for a ladder that reached
19578
+ * it by any other route. A round is every cycle recorded at one patch,
19579
+ * historical or live. The limit is the base profile's
19580
+ * `review.roundsWithoutWaiver`, resolved at the command boundary (#922).
19484
19581
  */
19485
19582
  const reviewRoundLimitBlockers = (input) => {
19486
19583
  const recordedRounds = reviewRoundCount(input.reviewProof?.ladder?.cycles ?? []);
19487
- if (recordedRounds <= 2) return [];
19584
+ const limit = input.reviewRoundsWithoutWaiver ?? 2;
19585
+ if (recordedRounds <= limit) return [];
19488
19586
  return [{
19489
19587
  demand: DEMAND_KEYS.reviewRoundLimit,
19490
- reason: `The review ladder holds ${recordedRounds} review rounds, and a round past the second needs an operator waiver: demand:waive --pr ${input.pr} --demand ${DEMAND_KEYS.reviewRoundLimit} with the disposition (continue, re-scope, or waive the findings) as the rationale.`
19588
+ reason: `The review ladder holds ${recordedRounds} review rounds, and a round past the ${reviewRoundLimitOrdinal(limit)} needs an operator waiver: demand:waive --pr ${input.pr} --demand ${DEMAND_KEYS.reviewRoundLimit} with the disposition (continue, re-scope, or waive the findings) as the rationale.`
19491
19589
  }];
19492
19590
  };
19493
19591
  /**
@@ -20415,6 +20513,13 @@ const CHECK_CONCLUSION_BY_READINESS_STATUS = {
20415
20513
  blocked: "failure",
20416
20514
  ready: "success"
20417
20515
  };
20516
+ /**
20517
+ * Blocked on nothing but a required check that has not settled: the one
20518
+ * refusal time alone clears. `pr:ready` withholds a follow-up for exactly this
20519
+ * state, and `pr:publish` waits on exactly this state. Both read it from the
20520
+ * recorded verdict, so publish never infers it from a missing follow-up.
20521
+ */
20522
+ const isAwaitingRequiredChecksOnly = (verdict) => verdict.status === "blocked" && verdict.ledger.github.requiredChecks === "pending" && verdict.blockingReasons.length === 1;
20418
20523
  function defaultPrReadyGit() {
20419
20524
  return {
20420
20525
  canResolveCommit,
@@ -20488,35 +20593,6 @@ async function fetchPullRequestWithMergeablePoll({ fetch, sleep = setTimeout$1 }
20488
20593
  function defaultPrReadyGithub() {
20489
20594
  return { fetchPullRequest };
20490
20595
  }
20491
- const prReadyProofSchema = z.object({
20492
- arming: z.object({
20493
- detail: z.string().min(1).optional(),
20494
- headSha: z.string().regex(/^[0-9a-f]{40}$/u),
20495
- outcome: z.enum([
20496
- "armed",
20497
- "merged",
20498
- "not-armed"
20499
- ])
20500
- }).optional(),
20501
- authoringSession: z.string().min(1).optional(),
20502
- blockedReasons: blockedReasonsSchema.optional(),
20503
- blockingReasons: z.array(z.string()),
20504
- command: z.literal("patronage-factory pr:ready"),
20505
- followUp: FollowUpActionSchema.optional(),
20506
- humanBlockingReasons: z.array(z.string()).default([]),
20507
- ledger: managedReadinessLedgerSchema,
20508
- notices: z.array(z.string().min(1)).optional(),
20509
- policyResolution: policyResolutionSchema.optional(),
20510
- profileBlobSha: z.string().regex(/^[0-9a-f]{40}$/u).optional(),
20511
- profilePath: z.string().min(1).optional(),
20512
- repairs: z.array(readinessRepairSchema).default([]),
20513
- repository: z.string().regex(/^[^/\s]+\/[^/\s]+$/u).optional(),
20514
- schemaVersion: z.literal(3),
20515
- status: z.enum(["ready", "blocked"]),
20516
- waivedDemands: z.array(waivedDemandSchema).optional()
20517
- }).superRefine((proof, context) => {
20518
- for (const issue of blockedReasonIssues({ ...proof })) context.addIssue(issue);
20519
- });
20520
20596
  function validatePrReadyProof(value) {
20521
20597
  return prReadyProofSchema.parse(value);
20522
20598
  }
@@ -21037,7 +21113,7 @@ async function runPrReady(args, dependencies = {}) {
21037
21113
  owner: repository.owner,
21038
21114
  pr: args.pr,
21039
21115
  repo: repository.name
21040
- });
21116
+ }, { admission });
21041
21117
  const pr = await withAdmissionReadRetry((extraEnv) => fetchPullRequestWithMergeablePoll({
21042
21118
  fetch: () => github.fetchPullRequest({
21043
21119
  owner: repository.owner,
@@ -21232,6 +21308,7 @@ async function runPrReady(args, dependencies = {}) {
21232
21308
  reviewDecision: pr.reviewDecision,
21233
21309
  reviewModes: authoritativeReview.reviewModes,
21234
21310
  reviewProof,
21311
+ reviewRoundsWithoutWaiver: authoritativeReviewRoundsWithoutWaiver(policy),
21235
21312
  unresolvedReviewThreads: pr.unresolvedReviewThreads,
21236
21313
  verificationProof: verification.verificationProof,
21237
21314
  waivers: candidateWaivers,
@@ -21246,7 +21323,7 @@ async function runPrReady(args, dependencies = {}) {
21246
21323
  recorded: verifyProofRead.proof?.authoringSession
21247
21324
  });
21248
21325
  const undraftRepair = evaluation.repairs.find((repair) => repair.code === "undraft-pr");
21249
- const pendingExternalChecksOnly = externalCheckState === "pending" && evaluation.blockingReasons.length === 1;
21326
+ const pendingExternalChecksOnly = isAwaitingRequiredChecksOnly(evaluation);
21250
21327
  const routeOwnedNotYetOnly = evaluation.status === "blocked" && evaluation.humanBlockingReasons.length === 0;
21251
21328
  const boundary = waveDemand?.kind === "demanded" ? waveDemand.demand : void 0;
21252
21329
  const armingConsidered = evaluation.status === "ready" && boundary?.autoMerge !== false;
@@ -22171,19 +22248,20 @@ const assertPriorPromptRecorded = ({ checkoutLadder, existing, patchId, priorLad
22171
22248
  throw new Error(`pr:review --assemble refuses: ${DEFAULT_ASSEMBLED_REVIEW_PROMPT_PATH} holds a prompt for patch ${prompted.patchId} at ${prompted.headSha}, and the review ladder has no cycle for that patch. The candidate is now patch ${patchId}. Record the review of that patch first: patronage-factory pr:review --historical --findings <findings file for patch ${prompted.patchId}>. If no reviewer read that prompt, delete ${DEFAULT_ASSEMBLED_REVIEW_PROMPT_PATH} and assemble again.`);
22172
22249
  };
22173
22250
  /**
22174
- * `--assemble` refuses to start a review round past the second until the
22175
- * operator waives `review-round-limit` for this pull request at this head
22176
- * (#1280). A round is every review recorded at one patch, so a patch that
22251
+ * `--assemble` refuses to start a review round past the repository's limit
22252
+ * (`review.roundsWithoutWaiver` on the base profile, default
22253
+ * `REVIEW_ROUNDS_WITHOUT_WAIVER`) until the operator waives
22254
+ * `review-round-limit` for this pull request at this head (#1280). A round is every review recorded at one patch, so a patch that
22177
22255
  * already has a recorded cycle is another arm of that round and needs no
22178
22256
  * waiver. The waiver is the one `demand:waive` records, folded through the
22179
22257
  * same `applyDemandWaiver` that `pr:ready` uses. Its rationale carries the
22180
22258
  * operator's disposition: continue, re-scope, or waive the findings.
22181
22259
  */
22182
- const assertReviewRoundAllowed = ({ cwd, headSha, patchId, priorLadder, pullRequest }) => {
22260
+ const assertReviewRoundAllowed = ({ cwd, headSha, patchId, priorLadder, pullRequest, roundsWithoutWaiver }) => {
22183
22261
  const cycles = priorLadder?.cycles ?? [];
22184
22262
  if (cycles.some((cycle) => cycle.identity?.patchId === patchId)) return;
22185
22263
  const recordedRounds = reviewRoundCount(cycles);
22186
- if (recordedRounds < 2) return;
22264
+ if (recordedRounds < roundsWithoutWaiver) return;
22187
22265
  const demand = DEMAND_KEYS.reviewRoundLimit;
22188
22266
  const unmet = `The review ladder already holds ${recordedRounds} review rounds for this pull request, so the next review starts round ${recordedRounds + 1}.`;
22189
22267
  const outcome = applyDemandWaiver({
@@ -22201,7 +22279,7 @@ const assertReviewRoundAllowed = ({ cwd, headSha, patchId, priorLadder, pullRequ
22201
22279
  }
22202
22280
  const waiveCommand = `patronage-factory demand:waive --pr ${pullRequest ?? "<pr>"} --demand ${demand} --rationale "<continue | re-scope | waive the findings>: <why>"`;
22203
22281
  const pushStep = pullRequest === void 0 ? "The waiver binds to a pull request, and no pull request is open for this branch. Open one and push this head" : `Push this head (${headSha})`;
22204
- throw new Error(`pr:review --assemble refuses: ${unmet} A round past the second is a demand that only the operator waives. ${pushStep}, then record the operator's disposition in the waiver: ${waiveCommand}. Then assemble again and give the reviewer the prompt that run writes. The prompt already on disk is from the earlier round and describes an older head.`);
22282
+ throw new Error(`pr:review --assemble refuses: ${unmet} A round past the ${reviewRoundLimitOrdinal(roundsWithoutWaiver)} is a demand that only the operator waives. ${pushStep}, then record the operator's disposition in the waiver: ${waiveCommand}. Then assemble again and give the reviewer the prompt that run writes. The prompt already on disk is from the earlier round and describes an older head.`);
22205
22283
  };
22206
22284
  /**
22207
22285
  * The refusals `--assemble` makes before it writes a prompt (#1245, #1280),
@@ -22209,7 +22287,7 @@ const assertReviewRoundAllowed = ({ cwd, headSha, patchId, priorLadder, pullRequ
22209
22287
  * write reuses. Assembly is not a recording: an unreadable prior proof yields
22210
22288
  * no prior ladder here and is diagnosed by doctor and by the recording run.
22211
22289
  */
22212
- const assertAssembleMayPrepareReview = ({ args, base, cwd, git, headSha, output, patchId }) => {
22290
+ const assertAssembleMayPrepareReview = ({ args, base, cwd, git, headSha, output, patchId, roundsWithoutWaiver }) => {
22213
22291
  assertEpicPullRequestOpen({
22214
22292
  args,
22215
22293
  base
@@ -22233,7 +22311,8 @@ const assertAssembleMayPrepareReview = ({ args, base, cwd, git, headSha, output,
22233
22311
  headSha,
22234
22312
  patchId,
22235
22313
  priorLadder,
22236
- pullRequest: base.source.kind === "pull-request" ? base.source.number : void 0
22314
+ pullRequest: base.source.kind === "pull-request" ? base.source.number : void 0,
22315
+ roundsWithoutWaiver
22237
22316
  });
22238
22317
  return {
22239
22318
  existing,
@@ -22770,7 +22849,8 @@ async function runPrReview(args, dependencies = {}) {
22770
22849
  git,
22771
22850
  headSha,
22772
22851
  output,
22773
- patchId
22852
+ patchId,
22853
+ roundsWithoutWaiver: authoritativeReviewRoundsWithoutWaiver(policy)
22774
22854
  });
22775
22855
  const issueReads = await assembleIssueReads({
22776
22856
  args,
@@ -23073,9 +23153,10 @@ const resolveFollowUpArgv = (followUp, factoryCliInvocation) => {
23073
23153
  ...args
23074
23154
  ];
23075
23155
  };
23156
+ const FOLLOW_UP_TIMEOUT_MS = 36e5;
23076
23157
  const defaultFollowUpRunner = (factoryCliInvocation) => (followUp, cwd) => {
23077
23158
  const [command, ...args] = resolveFollowUpArgv(followUp, factoryCliInvocation);
23078
- runCapture(command, args, cwd);
23159
+ runCapture(command, args, cwd, { timeoutMs: FOLLOW_UP_TIMEOUT_MS });
23079
23160
  };
23080
23161
  const prPublishCliInvocation = (explicit) => explicit ?? defaultFactoryCliInvocation(factoryCliEntry());
23081
23162
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
@@ -23731,15 +23812,6 @@ const requirePromotedProofHead = ({ expectedHeadSha, promotion, proof }) => {
23731
23812
  };
23732
23813
  const candidateFollowUpAfterPromotion = (promotion, proof) => promotion.status === "not-requested" ? proof.followUp : void 0;
23733
23814
  /**
23734
- * A proof with no follow-up that is not `ready` means `pr:ready` found the
23735
- * candidate blocked solely on a pending hosted check for the family excluded
23736
- * from readiness's own evaluation (`isFactoryReadyCheck`) — the only
23737
- * condition time alone can resolve. Everything else — a human action, a
23738
- * route-owned repair, a verification rerun — carries a follow-up and is
23739
- * publish's current, actionable answer; this function must not wait on it.
23740
- */
23741
- const isAwaitingHostedRunOnly = (proof) => proof.followUp === void 0 && proof.status !== "ready";
23742
- /**
23743
23815
  * The bounded transaction's await-and-re-evaluate loop (#348). Starting from
23744
23816
  * `proof`, while the candidate is blocked solely on a pending hosted check for
23745
23817
  * its head: abort honestly if that head moves (the candidate this invocation
@@ -23752,7 +23824,7 @@ async function awaitCurrentReadyVerdict({ args, dependencies, proof }) {
23752
23824
  const originalHeadSha = proof.ledger.headSha;
23753
23825
  const sleep = dependencies.sleep ?? setTimeout$1;
23754
23826
  let current = proof;
23755
- for (let attempt = 0; isAwaitingHostedRunOnly(current); attempt += 1) {
23827
+ for (let attempt = 0; isAwaitingRequiredChecksOnly(current); attempt += 1) {
23756
23828
  if (current.ledger.headSha !== originalHeadSha) throw new PrPublishTransactionAbortedError(`awaited the newest hosted check run for ${originalHeadSha}, but the head moved to ${current.ledger.headSha} while waiting. Re-run pr:publish against the current head.`);
23757
23829
  if (attempt >= 12) throw new PrPublishTransactionAbortedError(`timed out after ${12 * PUBLISH_HOSTED_RUN_POLL_MS}ms awaiting the newest hosted check run to leave pending for ${originalHeadSha}. Re-run pr:publish once hosted CI finishes.`);
23758
23830
  await sleep(PUBLISH_HOSTED_RUN_POLL_MS);
@@ -23933,7 +24005,7 @@ async function runPrPublish(args, dependencies = {}) {
23933
24005
  owner: profile.repository.owner,
23934
24006
  pr: prNumber,
23935
24007
  repo: profile.repository.name
23936
- });
24008
+ }, { admission: dependencies.admission });
23937
24009
  const promotionStartedAt = promotionInstant(dependencies);
23938
24010
  const promotion = await promoteDraftBeforeDemandEvaluation({
23939
24011
  cwd,
@@ -25997,6 +26069,7 @@ const policySchema = z.object({
25997
26069
  })).min(1),
25998
26070
  targets: z.array(z.string().regex(/^preview:[a-z][a-z0-9-]*$/u)).min(1)
25999
26071
  });
26072
+ const profileExtensionsSchema = z.object({ extensions: z.object({ hostedPreviewReceipts: z.unknown() }).optional() });
26000
26073
  const safeCapture = (capture) => (args, cwd) => {
26001
26074
  try {
26002
26075
  const text = capture(args, cwd);
@@ -26015,7 +26088,7 @@ const readPreviewReceiptPolicy = (repository, cwd, rawCapture) => {
26015
26088
  content: z.string(),
26016
26089
  encoding: z.literal("base64")
26017
26090
  }).parse(JSON.parse(capture(["api", `repos/${repository}/contents/software-factory.profile.json?ref=${ref.object.sha}`], cwd)));
26018
- const profile = JSON.parse(Buffer.from(file.content, "base64").toString("utf-8"));
26091
+ const profile = profileExtensionsSchema.parse(JSON.parse(Buffer.from(file.content, "base64").toString("utf-8")));
26019
26092
  const policy = policySchema.parse(profile.extensions?.hostedPreviewReceipts);
26020
26093
  return {
26021
26094
  ...policy,