@attalabs/vinaya 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -2
  2. package/aeg-root/roles/developer/reference.md +3 -3
  3. package/aeg-root/templates/pr-report-template.md +7 -2
  4. package/dist/checks/bin/check-body-bare-digits.js +229 -86
  5. package/dist/checks/bin/check-branch-topology.js +101 -89
  6. package/dist/checks/bin/check-brief-shape.js +222 -79
  7. package/dist/checks/bin/check-changeset-coverage.js +739 -232
  8. package/dist/checks/bin/check-ci-shard-coverage.js +82 -0
  9. package/dist/checks/bin/check-closes-n.js +101 -89
  10. package/dist/checks/bin/check-coherence.js +233 -129
  11. package/dist/checks/bin/check-dead-branch-push.js +97 -44
  12. package/dist/checks/bin/check-dispatch-readiness.js +238 -134
  13. package/dist/checks/bin/check-doc-coverage-push.js +722 -215
  14. package/dist/checks/bin/check-doc-coverage.js +726 -219
  15. package/dist/checks/bin/check-doctrine-no-procedures.js +222 -79
  16. package/dist/checks/bin/check-doctrine-portability.js +724 -217
  17. package/dist/checks/bin/check-evidence-fresh.js +720 -206
  18. package/dist/checks/bin/check-exec-bits.js +720 -213
  19. package/dist/checks/bin/check-first-push-dispatch.js +231 -129
  20. package/dist/checks/bin/check-issue-assignment.js +103 -91
  21. package/dist/checks/bin/check-issue-milestone-attach.js +94 -41
  22. package/dist/checks/bin/check-issue-objectives-numbering.js +94 -41
  23. package/dist/checks/bin/check-issue-parts-coverage.js +94 -41
  24. package/dist/checks/bin/check-issue-surface-globs.js +251 -127
  25. package/dist/checks/bin/check-issue-title-grammar.js +94 -41
  26. package/dist/checks/bin/check-issue-tranche-label.js +94 -41
  27. package/dist/checks/bin/check-main-branch-refusal.js +94 -41
  28. package/dist/checks/bin/check-no-disk-state.js +94 -41
  29. package/dist/checks/bin/check-pr-premise-reassert.js +222 -77
  30. package/dist/checks/bin/check-pr-report-density.js +94 -41
  31. package/dist/checks/bin/check-principal-test-plan-wait.js +94 -39
  32. package/dist/checks/bin/check-quoted-command.js +710 -201
  33. package/dist/checks/bin/check-reader-resolvable-prose.js +722 -213
  34. package/dist/checks/bin/check-registry-gates.js +104 -41
  35. package/dist/checks/bin/check-retired-vocabulary.js +708 -199
  36. package/dist/checks/bin/check-review-gate.js +224 -79
  37. package/dist/checks/bin/check-single-plan-pr.js +94 -41
  38. package/dist/checks/bin/check-surface-scope.js +101 -89
  39. package/dist/checks/bin/check-test-plan.js +94 -39
  40. package/dist/checks/bin/check-token-collection-wired.js +100 -42
  41. package/dist/checks/bin/check-token-report.js +96 -43
  42. package/dist/checks/bin/check-workspace-escape.js +722 -213
  43. package/dist/index.js +3725 -3148
  44. package/dist/lib/pre-push-cache-test-run.js +4175 -0
  45. package/dist/lib/pre-push-select-tests.js +709 -101
  46. package/package.json +3 -2
@@ -1,10 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
2
 
5
3
  // src/checks/bin/check-doc-coverage.ts
6
- import { execFileSync as execFileSync7 } from "node:child_process";
7
- import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
4
+ import { execFileSync as execFileSync6 } from "node:child_process";
5
+ import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
8
6
  // ../../packages/aeg-core/src/gate-audience.ts
9
7
  var GATE_AUDIENCE = {
10
8
  "check-branch-topology": { shippedAs: "branch-topology", ring: 0 },
@@ -1038,7 +1036,7 @@ function withDefaults(oldDefaults, newDefaults) {
1038
1036
  var endpoint = withDefaults(null, DEFAULTS);
1039
1037
 
1040
1038
  // ../../node_modules/fast-content-type-parse/index.js
1041
- var NullObject = function NullObject2() {};
1039
+ var NullObject = function NullObject() {};
1042
1040
  NullObject.prototype = Object.create(null);
1043
1041
  var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu;
1044
1042
  var quotedPairRE = /\\([\v\u0020-\u00ff])/gu;
@@ -1132,8 +1130,8 @@ function isPlainObject2(value) {
1132
1130
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
1133
1131
  }
1134
1132
  async function fetchWrapper(requestOptions) {
1135
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
1136
- if (!fetch) {
1133
+ const fetch2 = requestOptions.request?.fetch || globalThis.fetch;
1134
+ if (!fetch2) {
1137
1135
  throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");
1138
1136
  }
1139
1137
  const log = requestOptions.request?.log || console;
@@ -1145,7 +1143,7 @@ async function fetchWrapper(requestOptions) {
1145
1143
  ]));
1146
1144
  let fetchResponse;
1147
1145
  try {
1148
- fetchResponse = await fetch(requestOptions.url, {
1146
+ fetchResponse = await fetch2(requestOptions.url, {
1149
1147
  method: requestOptions.method,
1150
1148
  body,
1151
1149
  redirect: requestOptions.request?.redirect,
@@ -1782,27 +1780,27 @@ function splitTableRow(row) {
1782
1780
  return parts.map((p) => p.split(PLACEHOLDER).join("|"));
1783
1781
  }
1784
1782
  // ../../packages/aeg-core/src/blast-radius-domains.ts
1785
- function resolveWorkspaceEntry(entry2, listDirs) {
1786
- if (entry2.endsWith("/*")) {
1787
- const baseDir = entry2.slice(0, -2);
1783
+ function resolveWorkspaceEntry(entry, listDirs) {
1784
+ if (entry.endsWith("/*")) {
1785
+ const baseDir = entry.slice(0, -2);
1788
1786
  return listDirs(baseDir).map((name) => `${baseDir}/${name}`);
1789
1787
  }
1790
- if (entry2.includes("*"))
1788
+ if (entry.includes("*"))
1791
1789
  return [];
1792
- return [entry2];
1790
+ return [entry];
1793
1791
  }
1794
1792
  // ../../packages/aeg-core/src/consumer-enumeration.ts
1795
1793
  function deriveWorkspaceMemberDirs(workspaces, listDirs) {
1796
- const positive = workspaces.filter((entry2) => !entry2.startsWith("!"));
1797
- const negative = workspaces.filter((entry2) => entry2.startsWith("!")).map((entry2) => entry2.slice(1));
1794
+ const positive = workspaces.filter((entry) => !entry.startsWith("!"));
1795
+ const negative = workspaces.filter((entry) => entry.startsWith("!")).map((entry) => entry.slice(1));
1798
1796
  const excluded = new Set;
1799
- for (const entry2 of negative) {
1800
- for (const member of resolveWorkspaceEntry(entry2, listDirs))
1797
+ for (const entry of negative) {
1798
+ for (const member of resolveWorkspaceEntry(entry, listDirs))
1801
1799
  excluded.add(member);
1802
1800
  }
1803
1801
  const members = new Set;
1804
- for (const entry2 of positive) {
1805
- for (const member of resolveWorkspaceEntry(entry2, listDirs)) {
1802
+ for (const entry of positive) {
1803
+ for (const member of resolveWorkspaceEntry(entry, listDirs)) {
1806
1804
  if (!excluded.has(member))
1807
1805
  members.add(member);
1808
1806
  }
@@ -2126,15 +2124,15 @@ function summarizeTranscript(jsonl) {
2126
2124
  const line = rawLine.trim();
2127
2125
  if (!line)
2128
2126
  continue;
2129
- let entry2;
2127
+ let entry;
2130
2128
  try {
2131
- entry2 = JSON.parse(line);
2129
+ entry = JSON.parse(line);
2132
2130
  } catch {
2133
2131
  continue;
2134
2132
  }
2135
- if (!entry2 || typeof entry2 !== "object")
2133
+ if (!entry || typeof entry !== "object")
2136
2134
  continue;
2137
- const obj = entry2;
2135
+ const obj = entry;
2138
2136
  if (obj.type !== "assistant")
2139
2137
  continue;
2140
2138
  const message = obj.message;
@@ -2982,7 +2980,7 @@ function isStep0Block(content) {
2982
2980
  }
2983
2981
  function checkCommandsCarryOutput(prBody) {
2984
2982
  const errors = [];
2985
- for (const [label2, num] of [
2983
+ for (const [label, num] of [
2986
2984
  ["5", 5],
2987
2985
  ["6", 6]
2988
2986
  ]) {
@@ -2996,7 +2994,7 @@ function checkCommandsCarryOutput(prBody) {
2996
2994
  continue;
2997
2995
  const next = blocks[i + 1];
2998
2996
  if (!next || isCommandBlock(next.content)) {
2999
- errors.push(`brief-validation commands carry output: §${label2} has a command block ("${firstNonBlankLine(block.content)}") not immediately followed by a non-command output block — the very next fenced block must hold that command's actual output, not another command.`);
2997
+ errors.push(`brief-validation commands carry output: §${label} has a command block ("${firstNonBlankLine(block.content)}") not immediately followed by a non-command output block — the very next fenced block must hold that command's actual output, not another command.`);
3000
2998
  }
3001
2999
  }
3002
3000
  }
@@ -3433,8 +3431,8 @@ function stripPartBackticks(text) {
3433
3431
  function partWordCount(text) {
3434
3432
  return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3435
3433
  }
3436
- function looksLikeFilePath(entry2) {
3437
- const stripped = entry2.replace(/\/\*\*?$/, "");
3434
+ function looksLikeFilePath(entry) {
3435
+ const stripped = entry.replace(/\/\*\*?$/, "");
3438
3436
  const lastSegment = stripped.split("/").pop() ?? stripped;
3439
3437
  const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3440
3438
  return extMatch !== null && extMatch.index > 0;
@@ -3920,14 +3918,14 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3920
3918
  const referenced = extractClosesReferences(prBody);
3921
3919
  if (taskIssueRefs) {
3922
3920
  for (const n of referenced) {
3923
- const ref2 = taskIssueRefs.get(n);
3924
- if (!ref2)
3921
+ const ref = taskIssueRefs.get(n);
3922
+ if (!ref)
3925
3923
  continue;
3926
- const expectedBranch = `task/${ref2.trancheSlug}/${ref2.taskId}`;
3924
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3927
3925
  if (branch !== expectedBranch) {
3928
3926
  return {
3929
3927
  ok: false,
3930
- message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref2.taskId} of tranche "${ref2.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
3928
+ message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref.taskId} of tranche "${ref.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
3931
3929
  };
3932
3930
  }
3933
3931
  }
@@ -3936,15 +3934,15 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3936
3934
  if (!ref)
3937
3935
  return { ok: true };
3938
3936
  if (ref.kind === "issue") {
3939
- const expectedIssue2 = ref.issueNumber;
3940
- if (!referenced.has(expectedIssue2)) {
3937
+ const expectedIssue = ref.issueNumber;
3938
+ if (!referenced.has(expectedIssue)) {
3941
3939
  return {
3942
3940
  ok: false,
3943
- expectedIssue: expectedIssue2,
3944
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue2}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3941
+ expectedIssue,
3942
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3945
3943
  };
3946
3944
  }
3947
- return { ok: true, expectedIssue: expectedIssue2 };
3945
+ return { ok: true, expectedIssue };
3948
3946
  }
3949
3947
  const trancheSlug = ref.tranche;
3950
3948
  const taskId = ref.taskId;
@@ -3990,8 +3988,8 @@ function extractIssue(body) {
3990
3988
  const anchorNums = closesRefs(anchored);
3991
3989
  if (anchorNums.length === 0)
3992
3990
  return { issue: null, extraIssues: bodyNums, outsideHeader: false };
3993
- const issue2 = anchorNums[0];
3994
- return { issue: issue2, extraIssues: bodyNums.filter((n) => n !== issue2), outsideHeader: false };
3991
+ const issue = anchorNums[0];
3992
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3995
3993
  }
3996
3994
  const headerNums = closesRefs(headerRegion(stripped));
3997
3995
  if (bodyNums.length === 0)
@@ -4060,15 +4058,15 @@ function compareManifest(echoed, current, patchIdOf) {
4060
4058
  const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4061
4059
  const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4062
4060
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4063
- const objectivesVersion2 = isBoundToObjectives(echoed, current.objectivesVersion);
4061
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4064
4062
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4065
4063
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4066
4064
  return {
4067
- bound: head && base && briefHashBound && objectivesVersion2 && rulingOrdinal && policyDigestBound,
4065
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4068
4066
  head,
4069
4067
  base,
4070
4068
  briefHash: briefHashBound,
4071
- objectivesVersion: objectivesVersion2,
4069
+ objectivesVersion,
4072
4070
  rulingOrdinal,
4073
4071
  policyDigest: policyDigestBound
4074
4072
  };
@@ -5500,6 +5498,10 @@ function findWorkspaceEscapes(files, knownPaths, workspaceDirs = DEFAULT_WORKSPA
5500
5498
  }
5501
5499
  return findings;
5502
5500
  }
5501
+ // ../../packages/aeg-core/src/dev-review-loop/types.ts
5502
+ var SEVERITY_COLUMNS = ["blocker", "major", "minor", "critical", "high", "medium", "low"];
5503
+ // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
5504
+ var SUMMARY_TABLE_HEADER = `| round | ${SEVERITY_COLUMNS.join(" | ")} | confidence | outcome |`;
5503
5505
  // ../../packages/aeg-core/src/log/envelope.ts
5504
5506
  import { createHash as createHash5 } from "node:crypto";
5505
5507
 
@@ -6038,6 +6040,7 @@ function redact(value, home) {
6038
6040
  return value;
6039
6041
  }
6040
6042
  // ../../packages/aeg-core/src/log/store.ts
6043
+ var KNOWN_SCHEMA_VERSIONS = [1, 2];
6041
6044
  function metaOf(obj) {
6042
6045
  if (obj === null || typeof obj !== "object")
6043
6046
  return null;
@@ -6060,11 +6063,61 @@ function recordIdentity(obj) {
6060
6063
  }
6061
6064
  return null;
6062
6065
  }
6063
-
6064
- // ../../packages/aeg-core/src/log/artifact.ts
6065
- var TASK_LOG_ARTIFACT_MAX_BYTES = 8 * 1024 * 1024;
6066
- // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
6067
- var STOPPED_CONDITIONS = new Set(["confidence", "reappearance", "no_progress", "max_rounds"]);
6066
+ function schemaVersionOf(obj) {
6067
+ const meta = metaOf(obj);
6068
+ const schema = meta?.schema;
6069
+ return typeof schema === "number" ? schema : null;
6070
+ }
6071
+ function isKnownSchema(version) {
6072
+ return version !== null && KNOWN_SCHEMA_VERSIONS.includes(version);
6073
+ }
6074
+ function classifyStoredLine(raw, home) {
6075
+ let obj;
6076
+ try {
6077
+ obj = JSON.parse(raw);
6078
+ } catch {
6079
+ return { status: "invalid", identity: null, raw, reason: "not valid JSON" };
6080
+ }
6081
+ const version = schemaVersionOf(obj);
6082
+ if (version === null) {
6083
+ return { status: "invalid", identity: recordIdentity(obj), raw, reason: "no readable meta.schema" };
6084
+ }
6085
+ if (!isKnownSchema(version)) {
6086
+ return {
6087
+ status: "unknown_version",
6088
+ identity: recordIdentity(obj),
6089
+ schema: version,
6090
+ raw,
6091
+ reason: `schema version ${version} is not one this build validates (${KNOWN_SCHEMA_VERSIONS.join(", ")}) — kept for diagnosis`
6092
+ };
6093
+ }
6094
+ const result = LogEventSchema.safeParse(obj);
6095
+ if (!result.success) {
6096
+ return {
6097
+ status: "invalid",
6098
+ identity: recordIdentity(obj),
6099
+ raw,
6100
+ reason: result.error.issues[0]?.message ?? "schema violation"
6101
+ };
6102
+ }
6103
+ const event = result.data;
6104
+ const identity = recordIdentity(event);
6105
+ if (identity === null) {
6106
+ return { status: "invalid", identity: null, raw, reason: "valid event with no derivable identity" };
6107
+ }
6108
+ const redacted = redact(event, home);
6109
+ const provenance = version === 2 ? event.meta.provenance ?? null : null;
6110
+ return {
6111
+ status: "ok",
6112
+ identity,
6113
+ runId: event.meta.run_id,
6114
+ seq: event.meta.seq,
6115
+ schema: version,
6116
+ provenance,
6117
+ event,
6118
+ postLine: JSON.stringify(redacted)
6119
+ };
6120
+ }
6068
6121
  // ../../packages/aeg-core/src/control-store/records.ts
6069
6122
  import { z as z3 } from "zod";
6070
6123
  var isoTimestamp = z3.string().min(1);
@@ -6195,11 +6248,12 @@ var ResolutionRecordSchema = z3.object({
6195
6248
  consumedAt: isoTimestamp
6196
6249
  }).strict();
6197
6250
  // src/lib/diff-evidence.ts
6198
- import { execFileSync as execFileSync6 } from "node:child_process";
6199
- import { join as join5, relative, resolve as resolve2 } from "node:path";
6251
+ import { execFileSync as execFileSync5 } from "node:child_process";
6252
+ import { join as join8, relative, resolve as resolve2 } from "node:path";
6200
6253
 
6201
6254
  // src/lib/config.ts
6202
- import { execFileSync as execFileSync2 } from "node:child_process";
6255
+ import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6256
+ import { promisify as promisify4 } from "node:util";
6203
6257
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6204
6258
  import { homedir } from "node:os";
6205
6259
  import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -6226,10 +6280,10 @@ var CheckEntrySchema = z4.object({
6226
6280
  ownWorkflow: z4.boolean().optional(),
6227
6281
  principalOwed: z4.literal(true).optional(),
6228
6282
  validates: z4.enum(["body", "issue"]).optional()
6229
- }).superRefine((entry2, ctx) => {
6230
- if (!entry2.env)
6283
+ }).superRefine((entry, ctx) => {
6284
+ if (!entry.env)
6231
6285
  return;
6232
- for (const [key, value] of Object.entries(entry2.env)) {
6286
+ for (const [key, value] of Object.entries(entry.env)) {
6233
6287
  if (typeof value !== "object" || value === null || !("anyOf" in value))
6234
6288
  continue;
6235
6289
  const members = value.anyOf;
@@ -6386,18 +6440,19 @@ var VinayaConfigSchema = z4.object({
6386
6440
  });
6387
6441
  }
6388
6442
  }).optional(),
6389
- logPublish: z4.object({
6390
- issue: z4.number().int().positive().optional(),
6391
- pr: z4.number().int().positive().optional(),
6392
- webhookUrl: z4.string().url().optional(),
6393
- headers: z4.record(z4.string()).optional(),
6394
- maxChunksPerFlush: z4.number().int().positive().optional()
6395
- }).refine((v) => [v.issue, v.pr, v.webhookUrl].filter((x) => x !== undefined).length <= 1, {
6396
- message: "logPublish: set at most one of issue/pr/webhookUrl"
6397
- }).refine((v) => v.headers === undefined || v.webhookUrl !== undefined, {
6398
- message: "logPublish: headers requires webhookUrl"
6399
- }).optional(),
6400
- runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional()
6443
+ logPublish: z4.unknown().refine((v) => v === undefined, {
6444
+ message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
6445
+ }),
6446
+ runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
6447
+ logs: z4.object({
6448
+ folder: z4.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
6449
+ url: z4.string().url().optional(),
6450
+ headers: z4.record(z4.string()).optional()
6451
+ }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
6452
+ message: "logs: set at most one of folder/url"
6453
+ }).refine((v) => v.headers === undefined || v.url !== undefined, {
6454
+ message: "logs: headers requires url"
6455
+ }).optional()
6401
6456
  });
6402
6457
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
6403
6458
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
@@ -6442,32 +6497,39 @@ function globalTokensCollectIgnoredWarning(path) {
6442
6497
  function globalRuntimeDirIgnoredWarning(path) {
6443
6498
  return `${path}: "runtimeDir" in the global config is ignored — it carries no repository segment, so a machine-wide value would collapse every repository's task folders into one tree. Declare it from a repo-local vinaya.config.json.`;
6444
6499
  }
6500
+ var emittedGlobalKeyWarnings = new Set;
6501
+ function warnGlobalKeyIgnoredOnce(message) {
6502
+ if (emittedGlobalKeyWarnings.has(message))
6503
+ return;
6504
+ emittedGlobalKeyWarnings.add(message);
6505
+ console.error(`⚠ ${message}`);
6506
+ }
6445
6507
  function stripGlobalOnlyKeys(config, path) {
6446
6508
  if (path !== GLOBAL_CONFIG_PATH)
6447
6509
  return config;
6448
6510
  let result = config;
6449
6511
  if (result.checks && Object.keys(result.checks).length > 0) {
6450
- console.error(`⚠ ${globalChecksIgnoredWarning(path)}`);
6512
+ warnGlobalKeyIgnoredOnce(globalChecksIgnoredWarning(path));
6451
6513
  result = { ...result, checks: undefined };
6452
6514
  }
6453
6515
  if (result.roles && Object.keys(result.roles).length > 0) {
6454
- console.error(`⚠ ${globalRolesIgnoredWarning(path)}`);
6516
+ warnGlobalKeyIgnoredOnce(globalRolesIgnoredWarning(path));
6455
6517
  result = { ...result, roles: undefined };
6456
6518
  }
6457
6519
  if (result.principals && result.principals.length > 0) {
6458
- console.error(`⚠ ${globalPrincipalsIgnoredWarning(path)}`);
6520
+ warnGlobalKeyIgnoredOnce(globalPrincipalsIgnoredWarning(path));
6459
6521
  result = { ...result, principals: undefined };
6460
6522
  }
6461
6523
  if (result.releaseActor) {
6462
- console.error(`⚠ ${globalReleaseActorIgnoredWarning(path)}`);
6524
+ warnGlobalKeyIgnoredOnce(globalReleaseActorIgnoredWarning(path));
6463
6525
  result = { ...result, releaseActor: undefined };
6464
6526
  }
6465
6527
  if (result.tokens) {
6466
- console.error(`⚠ ${globalTokensCollectIgnoredWarning(path)}`);
6528
+ warnGlobalKeyIgnoredOnce(globalTokensCollectIgnoredWarning(path));
6467
6529
  result = { ...result, tokens: undefined };
6468
6530
  }
6469
6531
  if (result.runtimeDir) {
6470
- console.error(`⚠ ${globalRuntimeDirIgnoredWarning(path)}`);
6532
+ warnGlobalKeyIgnoredOnce(globalRuntimeDirIgnoredWarning(path));
6471
6533
  result = { ...result, runtimeDir: undefined };
6472
6534
  }
6473
6535
  return result;
@@ -6500,25 +6562,80 @@ function resolveReviewPolicy(config) {
6500
6562
  maxRounds
6501
6563
  };
6502
6564
  }
6503
- function trustAnchorRepo() {
6504
- const wellFormed = (slug) => /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
6505
- const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
6506
- if (fromRunner) {
6507
- const validated = wellFormed(fromRunner);
6508
- if (validated)
6509
- return validated;
6565
+ function resolveRuntimeDirSetting(config) {
6566
+ return config?.runtimeDir ?? null;
6567
+ }
6568
+ function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
6569
+ const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
6570
+ return anchored !== null && anchored === localRuntimeDir ? anchored : null;
6571
+ }
6572
+ function resolveLogsSetting(config) {
6573
+ const raw = config?.logs;
6574
+ if (!raw)
6575
+ return null;
6576
+ if (raw.url !== undefined)
6577
+ return { url: raw.url, headers: raw.headers };
6578
+ if (raw.folder !== undefined)
6579
+ return { folder: raw.folder };
6580
+ return null;
6581
+ }
6582
+ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
6583
+ const anchored = resolveLogsSetting(trustAnchorConfig);
6584
+ if (!anchored)
6585
+ return null;
6586
+ if ("url" in local)
6587
+ return "url" in anchored && anchored.url === local.url ? anchored : null;
6588
+ return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
6589
+ }
6590
+ function resolveLogsHeaderValues(headers, env) {
6591
+ if (!headers)
6592
+ return;
6593
+ const resolved = {};
6594
+ for (const [key, value] of Object.entries(headers)) {
6595
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
6510
6596
  }
6597
+ return resolved;
6598
+ }
6599
+ function trustAnchorRepo() {
6600
+ const fromRunner = trustAnchorRepoFromRunner();
6601
+ if (fromRunner)
6602
+ return fromRunner;
6511
6603
  try {
6512
6604
  const url = execFileSync2("git", ["remote", "get-url", "origin"], {
6513
6605
  encoding: "utf-8",
6514
6606
  stdio: ["ignore", "pipe", "pipe"]
6515
- }).trim();
6516
- const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
6517
- return m?.[1] && m[2] ? wellFormed(`${m[1]}/${m[2]}`) : null;
6607
+ });
6608
+ return trustAnchorRepoFromRemoteUrl(url);
6609
+ } catch {
6610
+ return null;
6611
+ }
6612
+ }
6613
+ async function trustAnchorRepoAsync() {
6614
+ const fromRunner = trustAnchorRepoFromRunner();
6615
+ if (fromRunner)
6616
+ return fromRunner;
6617
+ try {
6618
+ const { stdout } = await execFileAsync4("git", ["remote", "get-url", "origin"], {
6619
+ encoding: "utf-8",
6620
+ timeout: 1e4
6621
+ });
6622
+ return trustAnchorRepoFromRemoteUrl(stdout);
6518
6623
  } catch {
6519
6624
  return null;
6520
6625
  }
6521
6626
  }
6627
+ function wellFormedRepoSlug(slug) {
6628
+ return /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
6629
+ }
6630
+ function trustAnchorRepoFromRunner() {
6631
+ const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
6632
+ return fromRunner ? wellFormedRepoSlug(fromRunner) : null;
6633
+ }
6634
+ function trustAnchorRepoFromRemoteUrl(url) {
6635
+ const m = url.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
6636
+ return m?.[1] && m[2] ? wellFormedRepoSlug(`${m[1]}/${m[2]}`) : null;
6637
+ }
6638
+ var execFileAsync4 = promisify4(execFile4);
6522
6639
  function ghFetchTrustAnchorConfig() {
6523
6640
  const repo = trustAnchorRepo();
6524
6641
  if (!repo)
@@ -6528,6 +6645,13 @@ function ghFetchTrustAnchorConfig() {
6528
6645
  stdio: ["ignore", "pipe", "pipe"]
6529
6646
  });
6530
6647
  }
6648
+ async function ghFetchTrustAnchorConfigAsync() {
6649
+ const repo = await trustAnchorRepoAsync();
6650
+ if (!repo)
6651
+ throw new Error("could not resolve repo identity for the trust-anchor read");
6652
+ const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4 });
6653
+ return stdout;
6654
+ }
6531
6655
  function firstLine(err) {
6532
6656
  return err?.message?.split(`
6533
6657
  `)[0] ?? "unknown error";
@@ -6542,16 +6666,35 @@ function isMissingFileError(err) {
6542
6666
  return /\b404\b|not found/i.test(haystack);
6543
6667
  }
6544
6668
  function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
6545
- const warn = (why) => process.stdout.write(`⚠ could not read the trust-anchor config (\`principals\`/\`releaseActor\`) from the default branch (${why}) — falling back to vinaya's built-in defaults.
6546
- `);
6547
6669
  let base64;
6548
6670
  try {
6549
- base64 = fetcher().trim();
6671
+ base64 = fetcher();
6550
6672
  } catch (err) {
6551
- if (!isMissingFileError(err))
6552
- warn(firstLine(err));
6553
- return null;
6673
+ return trustAnchorFetchFailed(err);
6554
6674
  }
6675
+ return parseTrustAnchorContent(base64);
6676
+ }
6677
+ async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
6678
+ const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
6679
+ let base64;
6680
+ try {
6681
+ base64 = await fetcher();
6682
+ } catch (err) {
6683
+ return trustAnchorFetchFailed(err, warn);
6684
+ }
6685
+ return parseTrustAnchorContent(base64, warn);
6686
+ }
6687
+ function warnTrustAnchorFallback(why) {
6688
+ process.stdout.write(`⚠ could not read the trust-anchor config (\`principals\`/\`releaseActor\`) from the default branch (${why}) — falling back to vinaya's built-in defaults.
6689
+ `);
6690
+ }
6691
+ function trustAnchorFetchFailed(err, warn = warnTrustAnchorFallback) {
6692
+ if (!isMissingFileError(err))
6693
+ warn(firstLine(err));
6694
+ return null;
6695
+ }
6696
+ function parseTrustAnchorContent(content, warn = warnTrustAnchorFallback) {
6697
+ const base64 = content.trim();
6555
6698
  if (!base64)
6556
6699
  return null;
6557
6700
  try {
@@ -6581,6 +6724,8 @@ var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.j
6581
6724
 
6582
6725
  // src/lib/brief-assembly.ts
6583
6726
  import { execFileSync as execFileSync4 } from "node:child_process";
6727
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "node:fs";
6728
+ import { join as join3 } from "node:path";
6584
6729
 
6585
6730
  // ../../packages/sources/src/commands.ts
6586
6731
  var COMMANDS = [
@@ -6733,10 +6878,10 @@ var COMMANDS = [
6733
6878
  }
6734
6879
  ],
6735
6880
  details: [
6736
- "Composes `task brief`'s own preparation (`prepareTask`) with `dev-review-loop` (`devReviewLoop`) — nothing else. Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
6881
+ "Composes `task brief`'s own preparation (`prepareTask`) with the watching driver (`runDriverLoop`, `dev-review-loop.ts`) — nothing else. Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
6737
6882
  "A brief already frozen on the Issue is reused, never re-posted — the second `task dispatch`/`task brief` call this composes around does not fail the whole run, it just skips straight to running the loop. A task whose Issue refuses preparation (a missing brief section, an unmet dispatch gate) is refused before any agent starts, with nothing posted.",
6738
- "Refuses when the frozen brief's developer branch already has an open pull request — the old `task dispatch` followed by `task run` cannot start two developers this way.",
6739
- "Exit and printed summary distinguish a published, reviewed pull request (exit `0`, the PR URL) from a pause (exit `1`, with the exact `vinaya dev-review-loop --resume <pr>` command to continue), a usage/argv error (exit `2`), and any other failure (exit `3`) — never sharing `1` with a pause, so an unattended host tells them apart from the exit code alone. A run that pauses is resumed with the loop's own existing `--resume <pr>` flag, never a flag on this command."
6883
+ "Refuses when the frozen brief's developer branch already has an open pull request AND a driver is still live for it — a driver that crashed or was killed leaves its PR behind, and this command is the one that revives it, in any state, pause held or not.",
6884
+ "issue-711 O4: a pause never ends this process — it keeps running and watches the pull request, continuing on its own once a newer Principal ruling appears (or, for an `'infrastructure'`/`'stale_driver'` pause, after a bounded backoff), with no `--resume` command needed for the ordinary case. Exit and printed summary distinguish a published pull request OR a watched pause's own genuine end — merged, closed, or an operator's own `--cancel` (exit `0` either way, the PR URL) — from the one pause this process can never watch (no pull request exists yet — exit `1`, with the exact `vinaya task run <tranche> <n>` command to continue by hand), a usage/argv error (exit `2`), and any other failure (exit `3`)."
6740
6885
  ],
6741
6886
  status: "shipped"
6742
6887
  },
@@ -6905,48 +7050,6 @@ var COMMANDS = [
6905
7050
  ],
6906
7051
  status: "shipped"
6907
7052
  },
6908
- {
6909
- name: "log flush",
6910
- description: "Post a target Issue or PR's outbox as one or more marked comments, then truncate what the forge confirmed",
6911
- flags: [
6912
- { flag: "--issue", description: "Flush this Issue's outbox (`~/.vinaya/outbox/<owner>-<repo>/<n>.ndjson`)" },
6913
- {
6914
- flag: "--pr",
6915
- description: "Flush the Issue named by this PR's `Closes #N` line, posting the comments on the PR"
6916
- },
6917
- { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
6918
- ],
6919
- details: [
6920
- "Exactly one of `--issue`/`--pr` is required. `--pr` resolves the Issue from the PR body's `Closes #N` line — the same anchor every gate reads — and refuses with a check error naming the missing line when the body carries none.",
6921
- "Splits the outbox first at `run_id` boundaries (a maximal run of consecutive lines sharing one `run_id`, never a global group-by, so an interleaved outbox never produces a range spanning a gap), then at `FORGE_COMMENT_MAX_CHARS` (65536) within each run. Each comment opens with `<!-- aeg:log:<run_id>:<seq_from>-<seq_to> -->` on its own line, then one fenced `ndjson` block, one outbox line per line, verbatim. A single line too large to fit alone is refused by name, never split across two comments.",
6922
- "Logs its own `forge_write` line — `validated` before posting, `written` (with every returned comment id) after the last post succeeds, or `refused` (with gh's error) on any failure — through the same `log()` every other family uses, into the same outbox, before truncating. The outbox is truncated only to the lines confirmed posted; a failed chunk's lines, and anything appended to the outbox during the flush (including the flush's own `validated`/`written`/`refused` line), always survive to ride the next flush."
6923
- ],
6924
- status: "shipped"
6925
- },
6926
- {
6927
- name: "log export-artifact",
6928
- description: "Copy this run's own local outbox into a file, for the generated task-path workflow's own upload step",
6929
- flags: [],
6930
- details: [
6931
- "Concatenates every `*.ndjson` file under `~/.vinaya/outbox/` into `<dest>`, verbatim — no filtering, no second redaction pass (lines are already redacted at `log()`'s own write boundary). Writes nothing when the outbox is empty, and exits 0 either way: no gate events this run is a legitimate outcome, never a failure.",
6932
- "Runs inside the generated `vinaya-checks.yml` job, which holds no forge-write credential — this command never calls the forge. Both this step and the `actions/upload-artifact` step after it run `if: always()`, so a cancelled or failed job still exports whatever partial outbox it has."
6933
- ],
6934
- status: "shipped"
6935
- },
6936
- {
6937
- name: "log collect-artifact",
6938
- description: "Validate a downloaded task-log artifact and publish the valid records through the existing flush path",
6939
- flags: [
6940
- { flag: "--pr", description: "The pull request this artifact belongs to" },
6941
- { flag: "--repo", description: "Expected `owner/repo` — a provenance cross-check against each record" }
6942
- ],
6943
- details: [
6944
- "Runs inside the generated `vinaya-task-log-collector.yml` workflow — a `workflow_run`-triggered job on the default branch, holding the write credential the task-path job that produced the artifact never gets. `<path>` is already downloaded by that workflow, scoped to a specific, API-verified run id — a provenance guarantee this command never re-derives from the artifact bytes.",
6945
- "Never executes, imports, or evaluates the artifact's content: every line is read as text and validated (schema, an 8 MiB whole-artifact size cap, redaction, and a repo cross-check) before anything is trusted. A rejected line becomes a named gap — printed, never a silent drop — and the artifact is never partially trusted past that check into executing anything.",
6946
- "The valid, re-redacted survivors are appended into the same local outbox `vinaya log flush` would read for that PR's Issue, then published through the existing `flushOutbox` unmodified — reusing its chunking, its `<!-- aeg:log:… -->` marker, and its idempotent-retry read, rather than a second publisher. A retried collector run (a fresh runner, the same forge state) therefore dedupes for free: the marker already on the forge is acknowledged, never re-posted."
6947
- ],
6948
- status: "shipped"
6949
- },
6950
7053
  {
6951
7054
  name: "milestone create",
6952
7055
  description: "Create a GitHub Milestone from a validated body",
@@ -7276,7 +7379,7 @@ var COMMANDS = [
7276
7379
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
7277
7380
  {
7278
7381
  flag: "--pr",
7279
- description: "Flush the outbox to this PR's Issue after the dispatch — mutually exclusive with `--task`"
7382
+ description: "This dispatch's pull request number, for attribution — mutually exclusive with `--task`"
7280
7383
  },
7281
7384
  { flag: "--round", description: "Round number, for a dispatch inside a review loop" },
7282
7385
  {
@@ -7288,7 +7391,7 @@ var COMMANDS = [
7288
7391
  details: [
7289
7392
  "Sets `VINAYA_RUN_ID`/`VINAYA_ROLE`/`VINAYA_TASK`/`VINAYA_ROUND` on the child only — never on this process's own environment — and refuses by name, before any spawn attempt, when the named vendor binary is absent from `PATH` or present but not executable.",
7290
7393
  "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, or `refused`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
7291
- "When `--task` or `--pr` is given, flushes that outbox via `vinaya log flush` immediately after the child settles — `--task` and `--pr` are mutually exclusive here, matching `log flush`'s own single-target rule. Without either, the dispatch still runs and logs; nothing is flushed, and the lines ride to the next flush.",
7394
+ "Runs no flush of its own after the dispatch returns: every log line `dispatchRole` emits reaches its configured `logs` destination live, as it is emitted, so there is nothing left to ship in a trailing step. `--task`/`--pr` are attribution only, and remain mutually exclusive.",
7292
7395
  "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude/gemini: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`; `gemini ... --resume <id> ...`) in place of its first-dispatch args."
7293
7396
  ],
7294
7397
  status: "shipped"
@@ -7308,7 +7411,8 @@ var COMMANDS = [
7308
7411
  "Dispatches the developer through `dispatchRole` with the brief read from the Issue, waits for the PR it opens, then runs `assessRound` (`@attalabs/aeg-core`) — the entire policy — against observations this command reads from the forge: the head via `git ls-remote` only (never `gh pr view headRefOid`, which can lag a push), CI conclusion via the check-runs API (never run locally), and ruling comments matching `<!-- aeg:principal:ruling:<pr>-<k> -->`.",
7309
7412
  "Nothing is posted to the PR before the policy decides `publish`: each round's reviewer and security verdicts are dispatched fresh (never a resumed session) through `dispatchRole`, rendered through `review post`'s own render functions, and written to a local file under the outbox — never `gh pr comment`/`gh pr review`. Posting the held verdicts is a separate, later task.",
7310
7413
  "The developer's session is resumed every round via `dispatchRole`'s `resumeId` — never a fresh session — for every vendor; a round whose resume fails for a vendor that resumed successfully the round before stops the loop rather than silently falling back to a fresh developer session.",
7311
- "Every dispatch and round transition is a log line through the Vinaya Log, flushed to the forge at each round boundary."
7414
+ "Every dispatch and round transition is a log line through the Vinaya Log, delivered live to its configured `logs` destination as it is emitted — never a tracker comment.",
7415
+ "issue-711 O4: this command — `--task <n>`, `--resume <pr>`, `--cancel <pr>` alike — stays `task run`'s own one-shot debug/direct entry; the watching driver that survives a pause and continues on its own is `task run`'s (see that command's own entry)."
7312
7416
  ],
7313
7417
  status: "shipped"
7314
7418
  }
@@ -7445,25 +7549,6 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
7445
7549
  };
7446
7550
  }
7447
7551
 
7448
- // src/lib/brief-assembly.ts
7449
- function git(args) {
7450
- try {
7451
- return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7452
- } catch {
7453
- return "";
7454
- }
7455
- }
7456
- function expandGlob(glob) {
7457
- const out = git(["ls-files", "--", glob]);
7458
- return out.split(`
7459
- `).map((s) => s.trim()).filter(Boolean);
7460
- }
7461
- var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
7462
-
7463
- // src/checks/registry.ts
7464
- import { existsSync as existsSync3 } from "node:fs";
7465
- import { join as join3 } from "node:path";
7466
-
7467
7552
  // src/lib/package-root.ts
7468
7553
  import { existsSync as existsSync2 } from "node:fs";
7469
7554
  import { dirname as dirname2, join as join2 } from "node:path";
@@ -7481,13 +7566,33 @@ function packageRoot(moduleUrl) {
7481
7566
  return dir;
7482
7567
  }
7483
7568
 
7569
+ // src/lib/brief-assembly.ts
7570
+ var PACKAGE_ROOT = packageRoot(import.meta.url);
7571
+ var PACKAGED_TEMPLATE_PATH = join3(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
7572
+ var TEMPLATE_PATH = existsSync3(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join3(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
7573
+ function git(args) {
7574
+ try {
7575
+ return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7576
+ } catch {
7577
+ return "";
7578
+ }
7579
+ }
7580
+ function expandGlob(glob) {
7581
+ const out = git(["ls-files", "--", glob]);
7582
+ return out.split(`
7583
+ `).map((s) => s.trim()).filter(Boolean);
7584
+ }
7585
+ var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
7586
+
7484
7587
  // src/checks/registry.ts
7485
- var DIST_BIN_DIR = join3(packageRoot(import.meta.url), "dist", "checks", "bin");
7486
- var SRC_BIN_DIR = join3(packageRoot(import.meta.url), "src", "checks", "bin");
7487
- var BIN_DIR = existsSync3(DIST_BIN_DIR) ? DIST_BIN_DIR : SRC_BIN_DIR;
7588
+ import { existsSync as existsSync4 } from "node:fs";
7589
+ import { join as join4 } from "node:path";
7590
+ var DIST_BIN_DIR = join4(packageRoot(import.meta.url), "dist", "checks", "bin");
7591
+ var SRC_BIN_DIR = join4(packageRoot(import.meta.url), "src", "checks", "bin");
7592
+ var BIN_DIR = existsSync4(DIST_BIN_DIR) ? DIST_BIN_DIR : SRC_BIN_DIR;
7488
7593
  var BIN_EXT = BIN_DIR === DIST_BIN_DIR ? ".js" : ".ts";
7489
7594
  function bin(name) {
7490
- return join3(BIN_DIR, `${name}${BIN_EXT}`);
7595
+ return join4(BIN_DIR, `${name}${BIN_EXT}`);
7491
7596
  }
7492
7597
  var REGISTRY = [
7493
7598
  [
@@ -7899,6 +8004,16 @@ var REGISTRY = [
7899
8004
  },
7900
8005
  0
7901
8006
  ],
8007
+ [
8008
+ {
8009
+ name: "ci-shard-coverage",
8010
+ run: bin("check-ci-shard-coverage"),
8011
+ scope: "diff",
8012
+ timeoutMs: 15000,
8013
+ env: {}
8014
+ },
8015
+ 0
8016
+ ],
7902
8017
  [
7903
8018
  {
7904
8019
  name: "workspace-escape",
@@ -8036,42 +8151,382 @@ function coreCheckRegistry() {
8036
8151
  var CORE_CHECK_RING = Object.fromEntries(REGISTRY.map(([spec, ring]) => [spec.name, ring]));
8037
8152
 
8038
8153
  // src/lib/log-sink.ts
8039
- import { execFileSync as execFileSync5 } from "node:child_process";
8040
- import { randomUUID } from "node:crypto";
8154
+ import { execFile as execFile5 } from "node:child_process";
8155
+ import { randomUUID as randomUUID2 } from "node:crypto";
8156
+ import {
8157
+ closeSync as closeSync3,
8158
+ constants as fsConstants3,
8159
+ existsSync as existsSync6,
8160
+ fstatSync as fstatSync2,
8161
+ mkdirSync as mkdirSync3,
8162
+ openSync as openSync3,
8163
+ readFileSync as readFileSync5,
8164
+ renameSync as renameSync2,
8165
+ writeSync as writeSync2
8166
+ } from "node:fs";
8167
+ import { hostname as osHostname, homedir as homedir3 } from "node:os";
8168
+ import { dirname as dirname5, join as join7 } from "node:path";
8169
+ import { promisify as promisify5 } from "node:util";
8170
+
8171
+ // src/lib/run-paths.ts
8172
+ import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync2 } from "node:fs";
8173
+ import { dirname as dirname3, join as join5, resolve as resolvePath } from "node:path";
8174
+ var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8175
+ function isSafeRepoSegment(segment) {
8176
+ return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
8177
+ }
8178
+ function repoSegment(repo) {
8179
+ if (!repo || !isSafeRepoSegment(repo.owner) || !isSafeRepoSegment(repo.repo))
8180
+ return "unresolved";
8181
+ return `${repo.owner}-${repo.repo}`;
8182
+ }
8183
+ function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
8184
+ return join5(home, "runtime", repoSegment(repo));
8185
+ }
8186
+ function resolveRuntimeDir(input) {
8187
+ const local = resolveRuntimeDirSetting(input.localConfig);
8188
+ if (local === null)
8189
+ return defaultRuntimeDir(input.repo, input.home);
8190
+ if (isInsideRepo(local, input.repoRoot))
8191
+ return defaultRuntimeDir(input.repo, input.home);
8192
+ if (!input.unattended)
8193
+ return local;
8194
+ const anchored = resolveTrustAnchorRuntimeDir(local, input.trustAnchorConfig ?? null);
8195
+ return anchored ?? defaultRuntimeDir(input.repo, input.home);
8196
+ }
8197
+ function isInsideRepo(candidate, repoRoot) {
8198
+ if (!repoRoot)
8199
+ return false;
8200
+ const root = resolvePath(repoRoot);
8201
+ const target = resolvePath(candidate);
8202
+ return target === root || target.startsWith(`${root}/`);
8203
+ }
8204
+ var UNATTENDED_ENV_KEY = "VINAYA_UNATTENDED";
8205
+ var RUNTIME_DIR_ENV_KEY = "VINAYA_RUNTIME_DIR";
8206
+ function isUnattendedProcess(env = process.env) {
8207
+ return env[UNATTENDED_ENV_KEY] === "1" || (env.VINAYA_ROLE ?? "") !== "";
8208
+ }
8209
+ var memoized = null;
8210
+ async function runtimeDirForRepoAsync(repo) {
8211
+ const key = repoSegment(repo);
8212
+ if (memoized?.key === key)
8213
+ return memoized.value;
8214
+ const inputs = runtimeDirInputs();
8215
+ if (typeof inputs === "string")
8216
+ return inputs;
8217
+ const value = resolveRuntimeDir({
8218
+ repo,
8219
+ ...inputs.base,
8220
+ trustAnchorConfig: inputs.needsAnchor ? await loadTrustAnchorConfigAsync() : null
8221
+ });
8222
+ memoized = { key, value };
8223
+ return value;
8224
+ }
8225
+ function runtimeDirInputs() {
8226
+ const handedDown = process.env[RUNTIME_DIR_ENV_KEY];
8227
+ if (handedDown)
8228
+ return handedDown;
8229
+ const localConfig = loadConfig();
8230
+ const unattended = isUnattendedProcess();
8231
+ return {
8232
+ base: { localConfig, unattended, repoRoot: repoRootSync() },
8233
+ needsAnchor: unattended && resolveRuntimeDirSetting(localConfig) !== null
8234
+ };
8235
+ }
8236
+ function repoRootSync(start = process.cwd()) {
8237
+ let dir;
8238
+ try {
8239
+ dir = realpathSync2(start);
8240
+ } catch {
8241
+ return null;
8242
+ }
8243
+ for (;; ) {
8244
+ if (existsSync5(join5(dir, ".git")))
8245
+ return dir;
8246
+ const parent = dirname3(dir);
8247
+ if (parent === dir)
8248
+ return null;
8249
+ dir = parent;
8250
+ }
8251
+ }
8252
+
8253
+ // src/lib/log-webhook-drain.ts
8041
8254
  import {
8042
8255
  closeSync as closeSync2,
8043
8256
  constants as fsConstants2,
8044
- existsSync as existsSync4,
8045
- fstatSync as fstatSync2,
8257
+ lstatSync,
8046
8258
  mkdirSync as mkdirSync2,
8047
8259
  openSync as openSync2,
8048
- readFileSync as readFileSync3,
8260
+ linkSync,
8261
+ readFileSync as readFileSync4,
8049
8262
  renameSync,
8263
+ statSync,
8264
+ unlinkSync,
8265
+ writeFileSync as writeFileSync2,
8050
8266
  writeSync
8051
8267
  } from "node:fs";
8052
- import { hostname as osHostname, homedir as homedir2 } from "node:os";
8053
- import { dirname as dirname3, join as join4 } from "node:path";
8054
- var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8268
+ import { randomUUID } from "node:crypto";
8269
+ import { homedir as homedir2 } from "node:os";
8270
+ import { dirname as dirname4, join as join6 } from "node:path";
8271
+ var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
8272
+ var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
8273
+ var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8274
+ function isSafeRepoSegment2(segment) {
8275
+ return SAFE_PATH_SEGMENT2.test(segment) && !segment.includes("..");
8276
+ }
8277
+ function isErrnoCode(err, code) {
8278
+ return typeof err === "object" && err !== null && err.code === code;
8279
+ }
8055
8280
  function isEnoent(err) {
8281
+ return isErrnoCode(err, "ENOENT");
8282
+ }
8283
+ var WEBHOOK_DRAIN_LOCK_STALE_MS = 4 * WEBHOOK_FETCH_TIMEOUT_MS;
8284
+ function tryCreateLock(lockPath, token) {
8285
+ try {
8286
+ mkdirSync2(dirname4(lockPath), { recursive: true, mode: 448 });
8287
+ const fd = openSync2(lockPath, fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL, 384);
8288
+ try {
8289
+ writeSync(fd, `${token}
8290
+ `);
8291
+ } finally {
8292
+ closeSync2(fd);
8293
+ }
8294
+ return true;
8295
+ } catch (err) {
8296
+ if (isErrnoCode(err, "EEXIST"))
8297
+ return false;
8298
+ throw err;
8299
+ }
8300
+ }
8301
+ function acquireDrainLock(lockPath) {
8302
+ const token = `${process.pid}:${randomUUID()}`;
8303
+ if (tryCreateLock(lockPath, token))
8304
+ return token;
8305
+ let observedMtimeMs;
8306
+ try {
8307
+ observedMtimeMs = statSync(lockPath).mtimeMs;
8308
+ } catch (err) {
8309
+ if (!isEnoent(err))
8310
+ throw err;
8311
+ return tryCreateLock(lockPath, token) ? token : null;
8312
+ }
8313
+ if (Date.now() - observedMtimeMs <= WEBHOOK_DRAIN_LOCK_STALE_MS)
8314
+ return null;
8315
+ const claimed = `${lockPath}.claimed-${randomUUID()}`;
8316
+ try {
8317
+ renameSync(lockPath, claimed);
8318
+ } catch (err) {
8319
+ if (isEnoent(err))
8320
+ return null;
8321
+ throw err;
8322
+ }
8323
+ let claimedMtimeMs = null;
8324
+ try {
8325
+ claimedMtimeMs = statSync(claimed).mtimeMs;
8326
+ } catch (err) {
8327
+ if (!isEnoent(err))
8328
+ throw err;
8329
+ }
8330
+ if (claimedMtimeMs !== observedMtimeMs) {
8331
+ try {
8332
+ linkSync(claimed, lockPath);
8333
+ } catch (err) {
8334
+ if (!isErrnoCode(err, "EEXIST"))
8335
+ throw err;
8336
+ }
8337
+ try {
8338
+ unlinkSync(claimed);
8339
+ } catch (err) {
8340
+ if (!isEnoent(err))
8341
+ throw err;
8342
+ }
8343
+ return null;
8344
+ }
8345
+ unlinkSync(claimed);
8346
+ return tryCreateLock(lockPath, token) ? token : null;
8347
+ }
8348
+ function releaseDrainLock(lockPath, token) {
8349
+ try {
8350
+ const holder = readFileSync4(lockPath, "utf8").trim();
8351
+ if (holder !== token)
8352
+ return;
8353
+ unlinkSync(lockPath);
8354
+ } catch (err) {
8355
+ if (!isEnoent(err))
8356
+ throw err;
8357
+ }
8358
+ }
8359
+
8360
+ class WebhookDrainError extends Error {
8361
+ code;
8362
+ constructor(code, message) {
8363
+ super(message);
8364
+ this.code = code;
8365
+ }
8366
+ }
8367
+ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
8368
+ const resolved = await resolveRepo();
8369
+ const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
8370
+ const outboxRoot = () => join6(GLOBAL_VINAYA_HOME, "outbox");
8371
+ const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
8372
+ const lockPath = `${path}.flush-lock`;
8373
+ const lockToken = acquireDrainLock(lockPath);
8374
+ if (lockToken === null)
8375
+ return { flushed: false };
8376
+ try {
8377
+ let lstat;
8378
+ try {
8379
+ lstat = lstatSync(path);
8380
+ } catch (err) {
8381
+ if (!isEnoent(err))
8382
+ throw err;
8383
+ }
8384
+ if (lstat === undefined)
8385
+ return { flushed: false };
8386
+ if (!lstat.isFile()) {
8387
+ throw new WebhookDrainError("log-webhook-drain-symlink", `log webhook drain: outbox target is not a regular file (symlink, FIFO, or similar) — refusing to read: ${path}`);
8388
+ }
8389
+ const buf = readFileSync4(path);
8390
+ const startOffset = buf.byteLength;
8391
+ const rawLines = buf.toString("utf8").split(`
8392
+ `).filter((l) => l.length > 0);
8393
+ if (rawLines.length === 0)
8394
+ return { flushed: false };
8395
+ const postLines = [];
8396
+ for (let i = 0;i < rawLines.length; i++) {
8397
+ const record = classifyStoredLine(rawLines[i], homedir2());
8398
+ if (record.status !== "ok") {
8399
+ throw new WebhookDrainError("log-webhook-drain-corrupt-line", `log webhook drain: outbox line ${i} failed schema re-validation — ${record.reason}`);
8400
+ }
8401
+ postLines.push(record.postLine);
8402
+ }
8403
+ const body = `${postLines.join(`
8404
+ `)}
8405
+ `;
8406
+ const bytes = Buffer.byteLength(body, "utf8");
8407
+ if (bytes > MAX_WEBHOOK_BODY_BYTES) {
8408
+ throw new WebhookDrainError("log-webhook-drain-too-large", `log webhook drain: outbox body is ${bytes} byte(s), over the ${MAX_WEBHOOK_BODY_BYTES}-byte per-call cap — flush more often to drain it.`);
8409
+ }
8410
+ let response;
8411
+ try {
8412
+ response = await fetch(webhookUrl, {
8413
+ method: "POST",
8414
+ headers: { "content-type": "application/x-ndjson", ...headers },
8415
+ body,
8416
+ signal: AbortSignal.timeout(fetchTimeoutMs)
8417
+ });
8418
+ } catch (err) {
8419
+ const reason = err instanceof Error && err.name === "TimeoutError" ? `timed out after ${fetchTimeoutMs}ms` : err instanceof Error ? err.message : String(err);
8420
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} failed: ${reason}`);
8421
+ }
8422
+ if (!response.ok) {
8423
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} returned ${response.status} ${response.statusText}`);
8424
+ }
8425
+ const liveNow = readFileSync4(path);
8426
+ const tail = liveNow.subarray(Math.min(startOffset, liveNow.byteLength));
8427
+ writeFileSync2(path, tail);
8428
+ return { flushed: true, lineCount: postLines.length, bytes };
8429
+ } finally {
8430
+ releaseDrainLock(lockPath, lockToken);
8431
+ }
8432
+ }
8433
+
8434
+ // src/lib/log-sink.ts
8435
+ var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8436
+ var LOG_CONTEXT_LOOKUP_DEADLINE_MS = 3000;
8437
+ function withDeadline(work, ms, fallback) {
8438
+ return new Promise((resolve) => {
8439
+ const timer = setTimeout(() => resolve(fallback), ms);
8440
+ timer.unref?.();
8441
+ work.then((value) => {
8442
+ clearTimeout(timer);
8443
+ resolve(value);
8444
+ }, () => {
8445
+ clearTimeout(timer);
8446
+ resolve(fallback);
8447
+ });
8448
+ });
8449
+ }
8450
+ async function safeLoadTrustAnchorConfig() {
8451
+ return withDeadline(loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
8452
+ }
8453
+ function logsCredentialMissing(headers, env) {
8454
+ if (!headers)
8455
+ return false;
8456
+ const varPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
8457
+ for (const value of Object.values(headers)) {
8458
+ for (const match of value.matchAll(varPattern)) {
8459
+ if (!env[match[1]])
8460
+ return true;
8461
+ }
8462
+ }
8463
+ return false;
8464
+ }
8465
+ function resolveLogDestinationFrom(input) {
8466
+ const local = resolveLogsSetting(input.localConfig);
8467
+ let effective = null;
8468
+ if (input.unattended) {
8469
+ effective = local ? resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig) : resolveLogsSetting(input.trustAnchorConfig);
8470
+ } else {
8471
+ effective = local;
8472
+ }
8473
+ if (hostFromEnv(input.env) === "ci") {
8474
+ if (effective && "url" in effective) {
8475
+ if (logsCredentialMissing(effective.headers, input.env)) {
8476
+ return {
8477
+ kind: "none",
8478
+ reason: "a logs.url server destination is configured, but this job holds no delivery credential (a fork pull request, or a missing repository secret)"
8479
+ };
8480
+ }
8481
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
8482
+ }
8483
+ return {
8484
+ kind: "none",
8485
+ reason: "no server destination is configured for CI delivery (vinaya.config.json logs.url)"
8486
+ };
8487
+ }
8488
+ if (effective && "url" in effective) {
8489
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
8490
+ }
8491
+ if (effective && "folder" in effective && isInsideRepo(effective.folder, input.repoRoot)) {
8492
+ effective = null;
8493
+ }
8494
+ const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
8495
+ return { kind: "folder", folder };
8496
+ }
8497
+ var processTrustAnchorOnce;
8498
+ function processTrustAnchor() {
8499
+ if (processTrustAnchorOnce === undefined)
8500
+ processTrustAnchorOnce = safeLoadTrustAnchorConfig();
8501
+ return processTrustAnchorOnce;
8502
+ }
8503
+ async function defaultResolveLogDestination(repo, env) {
8504
+ const localConfig = loadConfig();
8505
+ const unattended = isUnattendedProcess(process.env);
8506
+ return resolveLogDestinationFrom({
8507
+ localConfig,
8508
+ trustAnchorConfig: unattended ? await processTrustAnchor() : null,
8509
+ unattended,
8510
+ env,
8511
+ defaultFolder: join7(await runtimeDirForRepoAsync(repo), "logs"),
8512
+ repoRoot: repoRootSync()
8513
+ });
8514
+ }
8515
+ function isEnoent2(err) {
8056
8516
  return typeof err === "object" && err !== null && err.code === "ENOENT";
8057
8517
  }
8058
- function resolveDoctrine(cwd, vinayaVersion) {
8518
+ var execFileAsync5 = promisify5(execFile5);
8519
+ async function resolveDoctrine(cwd, vinayaVersion) {
8059
8520
  let toplevel;
8060
8521
  try {
8061
- toplevel = execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
8062
- encoding: "utf8",
8063
- stdio: ["ignore", "pipe", "pipe"]
8064
- }).trim();
8522
+ toplevel = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
8065
8523
  } catch (err) {
8066
- return isEnoent(err) ? "unknown" : vinayaVersion;
8524
+ return isEnoent2(err) ? "unknown" : vinayaVersion;
8067
8525
  }
8068
- if (!existsSync4(join4(toplevel, "aeg-root", "roles")))
8526
+ if (!existsSync6(join7(toplevel, "aeg-root", "roles")))
8069
8527
  return vinayaVersion;
8070
8528
  try {
8071
- const sha = execFileSync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], {
8072
- encoding: "utf8",
8073
- stdio: ["ignore", "pipe", "pipe"]
8074
- }).trim();
8529
+ const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
8075
8530
  return `aeg-root@${sha}`;
8076
8531
  } catch {
8077
8532
  return vinayaVersion;
@@ -8079,20 +8534,20 @@ function resolveDoctrine(cwd, vinayaVersion) {
8079
8534
  }
8080
8535
  function readVinayaVersion() {
8081
8536
  try {
8082
- const pkg = JSON.parse(readFileSync3(join4(packageRoot(import.meta.url), "package.json"), "utf8"));
8537
+ const pkg = JSON.parse(readFileSync5(join7(packageRoot(import.meta.url), "package.json"), "utf8"));
8083
8538
  return pkg.version ?? "unknown";
8084
8539
  } catch {
8085
8540
  return "unknown";
8086
8541
  }
8087
8542
  }
8088
- var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8089
- function isSafeRepoSegment(segment) {
8090
- return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
8543
+ var SAFE_PATH_SEGMENT3 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8544
+ function isSafeRepoSegment3(segment) {
8545
+ return SAFE_PATH_SEGMENT3.test(segment) && !segment.includes("..");
8091
8546
  }
8092
8547
  function outboxPathFor(deps, repo, issue) {
8093
8548
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
8094
8549
  const fileName = `${issue ?? "none"}.ndjson`;
8095
- return join4(deps.outboxRoot(), dirName, fileName);
8550
+ return join7(deps.outboxRoot(), dirName, fileName);
8096
8551
  }
8097
8552
  function hostFromEnv(env) {
8098
8553
  if (env.GITHUB_ACTIONS)
@@ -8103,28 +8558,34 @@ function hostFromEnv(env) {
8103
8558
  return "loop";
8104
8559
  return "cli";
8105
8560
  }
8561
+ var warnedThisProcess = false;
8562
+ function defaultStderr(message) {
8563
+ if (warnedThisProcess)
8564
+ return;
8565
+ warnedThisProcess = true;
8566
+ process.stderr.write(message);
8567
+ }
8106
8568
  function defaultDeps() {
8107
8569
  return {
8108
- outboxRoot: () => join4(GLOBAL_VINAYA_HOME, "outbox"),
8109
- home: () => homedir2(),
8570
+ outboxRoot: () => join7(GLOBAL_VINAYA_HOME, "outbox"),
8571
+ home: () => homedir3(),
8110
8572
  hostname: () => osHostname(),
8111
8573
  cwd: () => process.cwd(),
8112
8574
  now: () => new Date,
8113
8575
  env: () => process.env,
8114
8576
  resolveRepo: () => resolveRepo(),
8115
8577
  vinayaVersion: () => readVinayaVersion(),
8116
- stderr: (message) => {
8117
- process.stderr.write(message);
8118
- },
8578
+ stderr: defaultStderr,
8119
8579
  inputVersions: () => {
8120
8580
  return;
8121
- }
8581
+ },
8582
+ resolveLogDestination: defaultResolveLogDestination
8122
8583
  };
8123
8584
  }
8124
- var APPEND_OPEN_FLAGS = fsConstants2.O_WRONLY | fsConstants2.O_APPEND | fsConstants2.O_CREAT | fsConstants2.O_NOFOLLOW | fsConstants2.O_NONBLOCK;
8585
+ var APPEND_OPEN_FLAGS = fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK;
8125
8586
  function guardedAppendOpen(path) {
8126
8587
  try {
8127
- return openSync2(path, APPEND_OPEN_FLAGS, 384);
8588
+ return openSync3(path, APPEND_OPEN_FLAGS, 384);
8128
8589
  } catch {
8129
8590
  return;
8130
8591
  }
@@ -8132,7 +8593,7 @@ function guardedAppendOpen(path) {
8132
8593
  function reportRotationOverflow(backupPath, warn) {
8133
8594
  let raw;
8134
8595
  try {
8135
- raw = readFileSync3(backupPath, "utf8");
8596
+ raw = readFileSync5(backupPath, "utf8");
8136
8597
  } catch {
8137
8598
  return;
8138
8599
  }
@@ -8155,7 +8616,7 @@ function reportRotationOverflow(backupPath, warn) {
8155
8616
  }
8156
8617
  function appendLine(path, line, warn) {
8157
8618
  try {
8158
- mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
8619
+ mkdirSync3(dirname5(path), { recursive: true, mode: 448 });
8159
8620
  let fd = guardedAppendOpen(path);
8160
8621
  if (fd === undefined) {
8161
8622
  warn(`vinaya: log outbox target could not be opened (symlink, FIFO, or unwritable) — refusing: ${path}
@@ -8171,11 +8632,11 @@ function appendLine(path, line, warn) {
8171
8632
  return;
8172
8633
  }
8173
8634
  if (stat.size > OUTBOX_MAX_BYTES) {
8174
- closeSync2(fd);
8635
+ closeSync3(fd);
8175
8636
  closed = true;
8176
8637
  const backupPath = path.replace(/\.ndjson$/, ".1.ndjson");
8177
8638
  reportRotationOverflow(backupPath, warn);
8178
- renameSync(path, backupPath);
8639
+ renameSync2(path, backupPath);
8179
8640
  const rotated = guardedAppendOpen(path);
8180
8641
  if (rotated === undefined) {
8181
8642
  warn(`vinaya: log outbox target could not be reopened after rotation — refusing: ${path}
@@ -8185,10 +8646,10 @@ function appendLine(path, line, warn) {
8185
8646
  fd = rotated;
8186
8647
  closed = false;
8187
8648
  }
8188
- writeSync(fd, line);
8649
+ writeSync2(fd, line);
8189
8650
  } finally {
8190
8651
  if (!closed)
8191
- closeSync2(fd);
8652
+ closeSync3(fd);
8192
8653
  }
8193
8654
  } catch (err) {
8194
8655
  warn(`vinaya: log outbox write failed — ${err instanceof Error ? err.message : String(err)}
@@ -8197,8 +8658,8 @@ function appendLine(path, line, warn) {
8197
8658
  }
8198
8659
  function createLogSink(overrides = {}) {
8199
8660
  const deps = { ...defaultDeps(), ...overrides };
8200
- const runId = deps.env().VINAYA_RUN_ID || randomUUID();
8201
- const processId = randomUUID();
8661
+ const runId = deps.env().VINAYA_RUN_ID || randomUUID2();
8662
+ const processId = randomUUID2();
8202
8663
  let seq = 0;
8203
8664
  let warned = false;
8204
8665
  const warnOnce = (message) => {
@@ -8211,8 +8672,9 @@ function createLogSink(overrides = {}) {
8211
8672
  };
8212
8673
  let doctrineCache;
8213
8674
  const doctrine = () => {
8214
- if (doctrineCache === undefined)
8215
- doctrineCache = resolveDoctrine(deps.cwd(), deps.vinayaVersion());
8675
+ if (doctrineCache === undefined) {
8676
+ doctrineCache = withDeadline(resolveDoctrine(deps.cwd(), deps.vinayaVersion()), LOG_CONTEXT_LOOKUP_DEADLINE_MS, deps.vinayaVersion());
8677
+ }
8216
8678
  return doctrineCache;
8217
8679
  };
8218
8680
  let resolveRepoCache;
@@ -8221,6 +8683,30 @@ function createLogSink(overrides = {}) {
8221
8683
  resolveRepoCache = deps.resolveRepo();
8222
8684
  return resolveRepoCache;
8223
8685
  };
8686
+ let contextCache;
8687
+ const context = () => {
8688
+ if (contextCache === undefined) {
8689
+ const env = deps.env();
8690
+ contextCache = Promise.all([
8691
+ withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
8692
+ doctrine()
8693
+ ]).then(async ([resolved, doctrineValue]) => {
8694
+ const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
8695
+ return { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
8696
+ });
8697
+ }
8698
+ return contextCache;
8699
+ };
8700
+ let drainChain = Promise.resolve();
8701
+ const pendingWrites = new Set;
8702
+ const scheduleWebhookDrain = (issue, url, headers) => {
8703
+ drainChain = drainChain.then(() => drainOutboxToWebhook(issue, url, headers)).then(() => {
8704
+ return;
8705
+ }).catch((err) => {
8706
+ warnOnce(`vinaya: log delivery to ${url} failed — queued in the local outbox, retried on the next event: ${err instanceof Error ? err.message : String(err)}
8707
+ `);
8708
+ });
8709
+ };
8224
8710
  function log(e) {
8225
8711
  try {
8226
8712
  const env = deps.env();
@@ -8235,22 +8721,26 @@ function createLogSink(overrides = {}) {
8235
8721
  attempt: env.VINAYA_ATTEMPT,
8236
8722
  parent: env.VINAYA_PARENT_EVENT
8237
8723
  };
8238
- resolveRepoOnce().then((resolved) => {
8239
- const repo = resolved && isSafeRepoSegment(resolved.owner) && isSafeRepoSegment(resolved.repo) ? resolved : null;
8724
+ const written = context().then(({ repo, doctrine: doctrineValue, destination: resolvedDestination }) => {
8240
8725
  const header = buildHeader({
8241
8726
  now,
8242
8727
  runId,
8243
8728
  seq: mySeq,
8244
8729
  repo: repo ? `${repo.owner}/${repo.repo}` : null,
8245
8730
  vinaya: deps.vinayaVersion(),
8246
- doctrine: doctrine(),
8731
+ doctrine: doctrineValue,
8247
8732
  host,
8248
8733
  hostname: deps.hostname(),
8249
8734
  env: envFields,
8250
- eventId: randomUUID(),
8735
+ eventId: randomUUID2(),
8251
8736
  processId,
8252
8737
  inputVersions: deps.inputVersions()
8253
8738
  });
8739
+ if (resolvedDestination.kind === "none") {
8740
+ warnOnce(`vinaya: not recording — ${resolvedDestination.reason}
8741
+ `);
8742
+ return;
8743
+ }
8254
8744
  const full = { ...e, ...header };
8255
8745
  const parsed = LogEventSchema.safeParse(full);
8256
8746
  if (!parsed.success) {
@@ -8260,25 +8750,42 @@ function createLogSink(overrides = {}) {
8260
8750
  }
8261
8751
  const line = `${JSON.stringify(redact(parsed.data, deps.home()))}
8262
8752
  `;
8263
- appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
8753
+ const destination = resolvedDestination;
8754
+ if (destination.kind === "server") {
8755
+ appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
8756
+ scheduleWebhookDrain(header.subject.issue, destination.url, destination.headers);
8757
+ } else {
8758
+ appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
8759
+ }
8264
8760
  }).catch((err) => {
8265
8761
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
8266
8762
  `);
8267
8763
  });
8764
+ pendingWrites.add(written);
8765
+ written.finally(() => pendingWrites.delete(written));
8268
8766
  } catch (err) {
8269
8767
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
8270
8768
  `);
8271
8769
  }
8272
8770
  }
8273
8771
  const warmup = () => {
8274
- doctrine();
8275
8772
  const originalWarn = console.warn;
8276
8773
  console.warn = () => {};
8277
8774
  resolveRepoOnce().finally(() => {
8278
8775
  console.warn = originalWarn;
8279
8776
  });
8777
+ context().catch(() => {
8778
+ return;
8779
+ });
8780
+ };
8781
+ const drain = async () => {
8782
+ if (pendingWrites.size > 0)
8783
+ await Promise.allSettled(Array.from(pendingWrites));
8784
+ await drainChain.catch(() => {
8785
+ return;
8786
+ });
8280
8787
  };
8281
- return { log, runId, warmup };
8788
+ return { log, runId, warmup, drain };
8282
8789
  }
8283
8790
  var defaultSink = createLogSink();
8284
8791
 
@@ -8329,7 +8836,7 @@ function parseChangedLineRanges(diffOutput) {
8329
8836
  function fileDiffAgainst(ref, path) {
8330
8837
  let out;
8331
8838
  try {
8332
- out = execFileSync6("git", ["diff", `${ref}...HEAD`, "--", path], {
8839
+ out = execFileSync5("git", ["diff", `${ref}...HEAD`, "--", path], {
8333
8840
  encoding: "utf8",
8334
8841
  stdio: ["ignore", "pipe", "pipe"]
8335
8842
  }).trim();
@@ -8340,7 +8847,7 @@ function fileDiffAgainst(ref, path) {
8340
8847
  }
8341
8848
  function revParse(ref) {
8342
8849
  try {
8343
- return execFileSync6("git", ["rev-parse", "--verify", ref], {
8850
+ return execFileSync5("git", ["rev-parse", "--verify", ref], {
8344
8851
  encoding: "utf8",
8345
8852
  stdio: ["ignore", "pipe", "pipe"]
8346
8853
  }).trim();
@@ -8350,7 +8857,7 @@ function revParse(ref) {
8350
8857
  }
8351
8858
  function repoRoot() {
8352
8859
  try {
8353
- return execFileSync6("git", ["rev-parse", "--show-toplevel"], {
8860
+ return execFileSync5("git", ["rev-parse", "--show-toplevel"], {
8354
8861
  encoding: "utf8",
8355
8862
  stdio: ["ignore", "pipe", "pipe"]
8356
8863
  }).trim();
@@ -8361,7 +8868,7 @@ function repoRoot() {
8361
8868
  function changedFiles(base) {
8362
8869
  let out;
8363
8870
  try {
8364
- out = execFileSync6("git", ["diff", "--name-only", `${base}...HEAD`], {
8871
+ out = execFileSync5("git", ["diff", "--name-only", `${base}...HEAD`], {
8365
8872
  encoding: "utf8",
8366
8873
  stdio: ["ignore", "pipe", "pipe"]
8367
8874
  }).trim();
@@ -8386,7 +8893,7 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
8386
8893
  const relPaths = changedFiles(ref);
8387
8894
  if (relPaths === null)
8388
8895
  continue;
8389
- return { base: ref, root, files: relPaths.map((p) => join5(root, p)) };
8896
+ return { base: ref, root, files: relPaths.map((p) => join8(root, p)) };
8390
8897
  }
8391
8898
  return null;
8392
8899
  }
@@ -8421,7 +8928,7 @@ function findingsInThisDiff(findings) {
8421
8928
  var CHECK_NAME = "doc-coverage";
8422
8929
  function git2(args) {
8423
8930
  try {
8424
- return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8931
+ return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8425
8932
  } catch {
8426
8933
  return "";
8427
8934
  }
@@ -8435,7 +8942,7 @@ function resolvePrBody() {
8435
8942
  return process.env.PR_BODY;
8436
8943
  if (process.env.PR_BODY_FILE) {
8437
8944
  try {
8438
- return readFileSync4(process.env.PR_BODY_FILE, "utf8");
8945
+ return readFileSync6(process.env.PR_BODY_FILE, "utf8");
8439
8946
  } catch {
8440
8947
  return "";
8441
8948
  }
@@ -8444,7 +8951,7 @@ function resolvePrBody() {
8444
8951
  }
8445
8952
  function fetchPrLabels(prNumber) {
8446
8953
  try {
8447
- const out = execFileSync7("gh", ["pr", "view", String(prNumber), "--json", "labels"], {
8954
+ const out = execFileSync6("gh", ["pr", "view", String(prNumber), "--json", "labels"], {
8448
8955
  encoding: "utf8",
8449
8956
  stdio: ["ignore", "pipe", "pipe"]
8450
8957
  });
@@ -8453,14 +8960,14 @@ function fetchPrLabels(prNumber) {
8453
8960
  return null;
8454
8961
  }
8455
8962
  }
8456
- function fetchWaiverLabelActor(prNumber, label2) {
8963
+ function fetchWaiverLabelActor(prNumber, label) {
8457
8964
  try {
8458
- const out = execFileSync7("gh", ["api", `repos/{owner}/{repo}/issues/${prNumber}/timeline`, "--paginate"], {
8965
+ const out = execFileSync6("gh", ["api", `repos/{owner}/{repo}/issues/${prNumber}/timeline`, "--paginate"], {
8459
8966
  encoding: "utf8",
8460
8967
  stdio: ["ignore", "pipe", "pipe"]
8461
8968
  });
8462
8969
  const events = JSON.parse(out);
8463
- const matches = events.filter((e) => e.event === "labeled" && e.label?.name === label2);
8970
+ const matches = events.filter((e) => e.event === "labeled" && e.label?.name === label);
8464
8971
  return matches[matches.length - 1]?.actor?.login ?? null;
8465
8972
  } catch {
8466
8973
  return null;
@@ -8493,8 +9000,8 @@ function main() {
8493
9000
  if (changed.length === 0) {
8494
9001
  process.exit(0);
8495
9002
  }
8496
- const content = existsSync5(DOC_OWNERS_PATH) ? readFileSync4(DOC_OWNERS_PATH, "utf8") : null;
8497
- const result = evaluateC5(changed, content, resolvePrBody(), existsSync5, waiverActive(), (p) => fileDiffAgainst(ref, p));
9003
+ const content = existsSync7(DOC_OWNERS_PATH) ? readFileSync6(DOC_OWNERS_PATH, "utf8") : null;
9004
+ const result = evaluateC5(changed, content, resolvePrBody(), existsSync7, waiverActive(), (p) => fileDiffAgainst(ref, p));
8498
9005
  if (result.errors.length > 0) {
8499
9006
  for (const message of result.errors) {
8500
9007
  emitCheckError({