@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,11 +1,9 @@
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-doctrine-portability.ts
6
- import { execFileSync as execFileSync7 } from "node:child_process";
7
- import { readdirSync, readFileSync as readFileSync4, statSync } from "node:fs";
8
- import { join as join6 } from "node:path";
4
+ import { execFileSync as execFileSync6 } from "node:child_process";
5
+ import { readdirSync as readdirSync2, readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
6
+ import { join as join9 } from "node:path";
9
7
  // ../../packages/aeg-core/src/gate-audience.ts
10
8
  var GATE_AUDIENCE = {
11
9
  "check-branch-topology": { shippedAs: "branch-topology", ring: 0 },
@@ -1039,7 +1037,7 @@ function withDefaults(oldDefaults, newDefaults) {
1039
1037
  var endpoint = withDefaults(null, DEFAULTS);
1040
1038
 
1041
1039
  // ../../node_modules/fast-content-type-parse/index.js
1042
- var NullObject = function NullObject2() {};
1040
+ var NullObject = function NullObject() {};
1043
1041
  NullObject.prototype = Object.create(null);
1044
1042
  var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu;
1045
1043
  var quotedPairRE = /\\([\v\u0020-\u00ff])/gu;
@@ -1133,8 +1131,8 @@ function isPlainObject2(value) {
1133
1131
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
1134
1132
  }
1135
1133
  async function fetchWrapper(requestOptions) {
1136
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
1137
- if (!fetch) {
1134
+ const fetch2 = requestOptions.request?.fetch || globalThis.fetch;
1135
+ if (!fetch2) {
1138
1136
  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");
1139
1137
  }
1140
1138
  const log = requestOptions.request?.log || console;
@@ -1146,7 +1144,7 @@ async function fetchWrapper(requestOptions) {
1146
1144
  ]));
1147
1145
  let fetchResponse;
1148
1146
  try {
1149
- fetchResponse = await fetch(requestOptions.url, {
1147
+ fetchResponse = await fetch2(requestOptions.url, {
1150
1148
  method: requestOptions.method,
1151
1149
  body,
1152
1150
  redirect: requestOptions.request?.redirect,
@@ -1783,27 +1781,27 @@ function splitTableRow(row) {
1783
1781
  return parts.map((p) => p.split(PLACEHOLDER).join("|"));
1784
1782
  }
1785
1783
  // ../../packages/aeg-core/src/blast-radius-domains.ts
1786
- function resolveWorkspaceEntry(entry2, listDirs) {
1787
- if (entry2.endsWith("/*")) {
1788
- const baseDir = entry2.slice(0, -2);
1784
+ function resolveWorkspaceEntry(entry, listDirs) {
1785
+ if (entry.endsWith("/*")) {
1786
+ const baseDir = entry.slice(0, -2);
1789
1787
  return listDirs(baseDir).map((name) => `${baseDir}/${name}`);
1790
1788
  }
1791
- if (entry2.includes("*"))
1789
+ if (entry.includes("*"))
1792
1790
  return [];
1793
- return [entry2];
1791
+ return [entry];
1794
1792
  }
1795
1793
  // ../../packages/aeg-core/src/consumer-enumeration.ts
1796
1794
  function deriveWorkspaceMemberDirs(workspaces, listDirs) {
1797
- const positive = workspaces.filter((entry2) => !entry2.startsWith("!"));
1798
- const negative = workspaces.filter((entry2) => entry2.startsWith("!")).map((entry2) => entry2.slice(1));
1795
+ const positive = workspaces.filter((entry) => !entry.startsWith("!"));
1796
+ const negative = workspaces.filter((entry) => entry.startsWith("!")).map((entry) => entry.slice(1));
1799
1797
  const excluded = new Set;
1800
- for (const entry2 of negative) {
1801
- for (const member of resolveWorkspaceEntry(entry2, listDirs))
1798
+ for (const entry of negative) {
1799
+ for (const member of resolveWorkspaceEntry(entry, listDirs))
1802
1800
  excluded.add(member);
1803
1801
  }
1804
1802
  const members = new Set;
1805
- for (const entry2 of positive) {
1806
- for (const member of resolveWorkspaceEntry(entry2, listDirs)) {
1803
+ for (const entry of positive) {
1804
+ for (const member of resolveWorkspaceEntry(entry, listDirs)) {
1807
1805
  if (!excluded.has(member))
1808
1806
  members.add(member);
1809
1807
  }
@@ -2127,15 +2125,15 @@ function summarizeTranscript(jsonl) {
2127
2125
  const line = rawLine.trim();
2128
2126
  if (!line)
2129
2127
  continue;
2130
- let entry2;
2128
+ let entry;
2131
2129
  try {
2132
- entry2 = JSON.parse(line);
2130
+ entry = JSON.parse(line);
2133
2131
  } catch {
2134
2132
  continue;
2135
2133
  }
2136
- if (!entry2 || typeof entry2 !== "object")
2134
+ if (!entry || typeof entry !== "object")
2137
2135
  continue;
2138
- const obj = entry2;
2136
+ const obj = entry;
2139
2137
  if (obj.type !== "assistant")
2140
2138
  continue;
2141
2139
  const message = obj.message;
@@ -2983,7 +2981,7 @@ function isStep0Block(content) {
2983
2981
  }
2984
2982
  function checkCommandsCarryOutput(prBody) {
2985
2983
  const errors = [];
2986
- for (const [label2, num] of [
2984
+ for (const [label, num] of [
2987
2985
  ["5", 5],
2988
2986
  ["6", 6]
2989
2987
  ]) {
@@ -2997,7 +2995,7 @@ function checkCommandsCarryOutput(prBody) {
2997
2995
  continue;
2998
2996
  const next = blocks[i + 1];
2999
2997
  if (!next || isCommandBlock(next.content)) {
3000
- 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.`);
2998
+ 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.`);
3001
2999
  }
3002
3000
  }
3003
3001
  }
@@ -3434,8 +3432,8 @@ function stripPartBackticks(text) {
3434
3432
  function partWordCount(text) {
3435
3433
  return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3436
3434
  }
3437
- function looksLikeFilePath(entry2) {
3438
- const stripped = entry2.replace(/\/\*\*?$/, "");
3435
+ function looksLikeFilePath(entry) {
3436
+ const stripped = entry.replace(/\/\*\*?$/, "");
3439
3437
  const lastSegment = stripped.split("/").pop() ?? stripped;
3440
3438
  const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3441
3439
  return extMatch !== null && extMatch.index > 0;
@@ -3921,14 +3919,14 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3921
3919
  const referenced = extractClosesReferences(prBody);
3922
3920
  if (taskIssueRefs) {
3923
3921
  for (const n of referenced) {
3924
- const ref2 = taskIssueRefs.get(n);
3925
- if (!ref2)
3922
+ const ref = taskIssueRefs.get(n);
3923
+ if (!ref)
3926
3924
  continue;
3927
- const expectedBranch = `task/${ref2.trancheSlug}/${ref2.taskId}`;
3925
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3928
3926
  if (branch !== expectedBranch) {
3929
3927
  return {
3930
3928
  ok: false,
3931
- 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.`
3929
+ 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.`
3932
3930
  };
3933
3931
  }
3934
3932
  }
@@ -3937,15 +3935,15 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3937
3935
  if (!ref)
3938
3936
  return { ok: true };
3939
3937
  if (ref.kind === "issue") {
3940
- const expectedIssue2 = ref.issueNumber;
3941
- if (!referenced.has(expectedIssue2)) {
3938
+ const expectedIssue = ref.issueNumber;
3939
+ if (!referenced.has(expectedIssue)) {
3942
3940
  return {
3943
3941
  ok: false,
3944
- expectedIssue: expectedIssue2,
3945
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue2}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3942
+ expectedIssue,
3943
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3946
3944
  };
3947
3945
  }
3948
- return { ok: true, expectedIssue: expectedIssue2 };
3946
+ return { ok: true, expectedIssue };
3949
3947
  }
3950
3948
  const trancheSlug = ref.tranche;
3951
3949
  const taskId = ref.taskId;
@@ -3991,8 +3989,8 @@ function extractIssue(body) {
3991
3989
  const anchorNums = closesRefs(anchored);
3992
3990
  if (anchorNums.length === 0)
3993
3991
  return { issue: null, extraIssues: bodyNums, outsideHeader: false };
3994
- const issue2 = anchorNums[0];
3995
- return { issue: issue2, extraIssues: bodyNums.filter((n) => n !== issue2), outsideHeader: false };
3992
+ const issue = anchorNums[0];
3993
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3996
3994
  }
3997
3995
  const headerNums = closesRefs(headerRegion(stripped));
3998
3996
  if (bodyNums.length === 0)
@@ -4061,15 +4059,15 @@ function compareManifest(echoed, current, patchIdOf) {
4061
4059
  const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4062
4060
  const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4063
4061
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4064
- const objectivesVersion2 = isBoundToObjectives(echoed, current.objectivesVersion);
4062
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4065
4063
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4066
4064
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4067
4065
  return {
4068
- bound: head && base && briefHashBound && objectivesVersion2 && rulingOrdinal && policyDigestBound,
4066
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4069
4067
  head,
4070
4068
  base,
4071
4069
  briefHash: briefHashBound,
4072
- objectivesVersion: objectivesVersion2,
4070
+ objectivesVersion,
4073
4071
  rulingOrdinal,
4074
4072
  policyDigest: policyDigestBound
4075
4073
  };
@@ -5501,6 +5499,10 @@ function findWorkspaceEscapes(files, knownPaths, workspaceDirs = DEFAULT_WORKSPA
5501
5499
  }
5502
5500
  return findings;
5503
5501
  }
5502
+ // ../../packages/aeg-core/src/dev-review-loop/types.ts
5503
+ var SEVERITY_COLUMNS = ["blocker", "major", "minor", "critical", "high", "medium", "low"];
5504
+ // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
5505
+ var SUMMARY_TABLE_HEADER = `| round | ${SEVERITY_COLUMNS.join(" | ")} | confidence | outcome |`;
5504
5506
  // ../../packages/aeg-core/src/log/envelope.ts
5505
5507
  import { createHash as createHash5 } from "node:crypto";
5506
5508
 
@@ -6039,6 +6041,7 @@ function redact(value, home) {
6039
6041
  return value;
6040
6042
  }
6041
6043
  // ../../packages/aeg-core/src/log/store.ts
6044
+ var KNOWN_SCHEMA_VERSIONS = [1, 2];
6042
6045
  function metaOf(obj) {
6043
6046
  if (obj === null || typeof obj !== "object")
6044
6047
  return null;
@@ -6061,11 +6064,61 @@ function recordIdentity(obj) {
6061
6064
  }
6062
6065
  return null;
6063
6066
  }
6064
-
6065
- // ../../packages/aeg-core/src/log/artifact.ts
6066
- var TASK_LOG_ARTIFACT_MAX_BYTES = 8 * 1024 * 1024;
6067
- // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
6068
- var STOPPED_CONDITIONS = new Set(["confidence", "reappearance", "no_progress", "max_rounds"]);
6067
+ function schemaVersionOf(obj) {
6068
+ const meta = metaOf(obj);
6069
+ const schema = meta?.schema;
6070
+ return typeof schema === "number" ? schema : null;
6071
+ }
6072
+ function isKnownSchema(version) {
6073
+ return version !== null && KNOWN_SCHEMA_VERSIONS.includes(version);
6074
+ }
6075
+ function classifyStoredLine(raw, home) {
6076
+ let obj;
6077
+ try {
6078
+ obj = JSON.parse(raw);
6079
+ } catch {
6080
+ return { status: "invalid", identity: null, raw, reason: "not valid JSON" };
6081
+ }
6082
+ const version = schemaVersionOf(obj);
6083
+ if (version === null) {
6084
+ return { status: "invalid", identity: recordIdentity(obj), raw, reason: "no readable meta.schema" };
6085
+ }
6086
+ if (!isKnownSchema(version)) {
6087
+ return {
6088
+ status: "unknown_version",
6089
+ identity: recordIdentity(obj),
6090
+ schema: version,
6091
+ raw,
6092
+ reason: `schema version ${version} is not one this build validates (${KNOWN_SCHEMA_VERSIONS.join(", ")}) — kept for diagnosis`
6093
+ };
6094
+ }
6095
+ const result = LogEventSchema.safeParse(obj);
6096
+ if (!result.success) {
6097
+ return {
6098
+ status: "invalid",
6099
+ identity: recordIdentity(obj),
6100
+ raw,
6101
+ reason: result.error.issues[0]?.message ?? "schema violation"
6102
+ };
6103
+ }
6104
+ const event = result.data;
6105
+ const identity = recordIdentity(event);
6106
+ if (identity === null) {
6107
+ return { status: "invalid", identity: null, raw, reason: "valid event with no derivable identity" };
6108
+ }
6109
+ const redacted = redact(event, home);
6110
+ const provenance = version === 2 ? event.meta.provenance ?? null : null;
6111
+ return {
6112
+ status: "ok",
6113
+ identity,
6114
+ runId: event.meta.run_id,
6115
+ seq: event.meta.seq,
6116
+ schema: version,
6117
+ provenance,
6118
+ event,
6119
+ postLine: JSON.stringify(redacted)
6120
+ };
6121
+ }
6069
6122
  // ../../packages/aeg-core/src/control-store/records.ts
6070
6123
  import { z as z3 } from "zod";
6071
6124
  var isoTimestamp = z3.string().min(1);
@@ -6196,7 +6249,8 @@ var ResolutionRecordSchema = z3.object({
6196
6249
  consumedAt: isoTimestamp
6197
6250
  }).strict();
6198
6251
  // src/lib/config.ts
6199
- import { execFileSync as execFileSync2 } from "node:child_process";
6252
+ import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6253
+ import { promisify as promisify4 } from "node:util";
6200
6254
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6201
6255
  import { homedir } from "node:os";
6202
6256
  import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -6223,10 +6277,10 @@ var CheckEntrySchema = z4.object({
6223
6277
  ownWorkflow: z4.boolean().optional(),
6224
6278
  principalOwed: z4.literal(true).optional(),
6225
6279
  validates: z4.enum(["body", "issue"]).optional()
6226
- }).superRefine((entry2, ctx) => {
6227
- if (!entry2.env)
6280
+ }).superRefine((entry, ctx) => {
6281
+ if (!entry.env)
6228
6282
  return;
6229
- for (const [key, value] of Object.entries(entry2.env)) {
6283
+ for (const [key, value] of Object.entries(entry.env)) {
6230
6284
  if (typeof value !== "object" || value === null || !("anyOf" in value))
6231
6285
  continue;
6232
6286
  const members = value.anyOf;
@@ -6383,18 +6437,19 @@ var VinayaConfigSchema = z4.object({
6383
6437
  });
6384
6438
  }
6385
6439
  }).optional(),
6386
- logPublish: z4.object({
6387
- issue: z4.number().int().positive().optional(),
6388
- pr: z4.number().int().positive().optional(),
6389
- webhookUrl: z4.string().url().optional(),
6390
- headers: z4.record(z4.string()).optional(),
6391
- maxChunksPerFlush: z4.number().int().positive().optional()
6392
- }).refine((v) => [v.issue, v.pr, v.webhookUrl].filter((x) => x !== undefined).length <= 1, {
6393
- message: "logPublish: set at most one of issue/pr/webhookUrl"
6394
- }).refine((v) => v.headers === undefined || v.webhookUrl !== undefined, {
6395
- message: "logPublish: headers requires webhookUrl"
6396
- }).optional(),
6397
- runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional()
6440
+ logPublish: z4.unknown().refine((v) => v === undefined, {
6441
+ message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
6442
+ }),
6443
+ runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
6444
+ logs: z4.object({
6445
+ folder: z4.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
6446
+ url: z4.string().url().optional(),
6447
+ headers: z4.record(z4.string()).optional()
6448
+ }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
6449
+ message: "logs: set at most one of folder/url"
6450
+ }).refine((v) => v.headers === undefined || v.url !== undefined, {
6451
+ message: "logs: headers requires url"
6452
+ }).optional()
6398
6453
  });
6399
6454
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
6400
6455
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
@@ -6439,32 +6494,39 @@ function globalTokensCollectIgnoredWarning(path) {
6439
6494
  function globalRuntimeDirIgnoredWarning(path) {
6440
6495
  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.`;
6441
6496
  }
6497
+ var emittedGlobalKeyWarnings = new Set;
6498
+ function warnGlobalKeyIgnoredOnce(message) {
6499
+ if (emittedGlobalKeyWarnings.has(message))
6500
+ return;
6501
+ emittedGlobalKeyWarnings.add(message);
6502
+ console.error(`⚠ ${message}`);
6503
+ }
6442
6504
  function stripGlobalOnlyKeys(config, path) {
6443
6505
  if (path !== GLOBAL_CONFIG_PATH)
6444
6506
  return config;
6445
6507
  let result = config;
6446
6508
  if (result.checks && Object.keys(result.checks).length > 0) {
6447
- console.error(`⚠ ${globalChecksIgnoredWarning(path)}`);
6509
+ warnGlobalKeyIgnoredOnce(globalChecksIgnoredWarning(path));
6448
6510
  result = { ...result, checks: undefined };
6449
6511
  }
6450
6512
  if (result.roles && Object.keys(result.roles).length > 0) {
6451
- console.error(`⚠ ${globalRolesIgnoredWarning(path)}`);
6513
+ warnGlobalKeyIgnoredOnce(globalRolesIgnoredWarning(path));
6452
6514
  result = { ...result, roles: undefined };
6453
6515
  }
6454
6516
  if (result.principals && result.principals.length > 0) {
6455
- console.error(`⚠ ${globalPrincipalsIgnoredWarning(path)}`);
6517
+ warnGlobalKeyIgnoredOnce(globalPrincipalsIgnoredWarning(path));
6456
6518
  result = { ...result, principals: undefined };
6457
6519
  }
6458
6520
  if (result.releaseActor) {
6459
- console.error(`⚠ ${globalReleaseActorIgnoredWarning(path)}`);
6521
+ warnGlobalKeyIgnoredOnce(globalReleaseActorIgnoredWarning(path));
6460
6522
  result = { ...result, releaseActor: undefined };
6461
6523
  }
6462
6524
  if (result.tokens) {
6463
- console.error(`⚠ ${globalTokensCollectIgnoredWarning(path)}`);
6525
+ warnGlobalKeyIgnoredOnce(globalTokensCollectIgnoredWarning(path));
6464
6526
  result = { ...result, tokens: undefined };
6465
6527
  }
6466
6528
  if (result.runtimeDir) {
6467
- console.error(`⚠ ${globalRuntimeDirIgnoredWarning(path)}`);
6529
+ warnGlobalKeyIgnoredOnce(globalRuntimeDirIgnoredWarning(path));
6468
6530
  result = { ...result, runtimeDir: undefined };
6469
6531
  }
6470
6532
  return result;
@@ -6497,25 +6559,80 @@ function resolveReviewPolicy(config) {
6497
6559
  maxRounds
6498
6560
  };
6499
6561
  }
6500
- function trustAnchorRepo() {
6501
- const wellFormed = (slug) => /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
6502
- const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
6503
- if (fromRunner) {
6504
- const validated = wellFormed(fromRunner);
6505
- if (validated)
6506
- return validated;
6562
+ function resolveRuntimeDirSetting(config) {
6563
+ return config?.runtimeDir ?? null;
6564
+ }
6565
+ function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
6566
+ const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
6567
+ return anchored !== null && anchored === localRuntimeDir ? anchored : null;
6568
+ }
6569
+ function resolveLogsSetting(config) {
6570
+ const raw = config?.logs;
6571
+ if (!raw)
6572
+ return null;
6573
+ if (raw.url !== undefined)
6574
+ return { url: raw.url, headers: raw.headers };
6575
+ if (raw.folder !== undefined)
6576
+ return { folder: raw.folder };
6577
+ return null;
6578
+ }
6579
+ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
6580
+ const anchored = resolveLogsSetting(trustAnchorConfig);
6581
+ if (!anchored)
6582
+ return null;
6583
+ if ("url" in local)
6584
+ return "url" in anchored && anchored.url === local.url ? anchored : null;
6585
+ return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
6586
+ }
6587
+ function resolveLogsHeaderValues(headers, env) {
6588
+ if (!headers)
6589
+ return;
6590
+ const resolved = {};
6591
+ for (const [key, value] of Object.entries(headers)) {
6592
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
6507
6593
  }
6594
+ return resolved;
6595
+ }
6596
+ function trustAnchorRepo() {
6597
+ const fromRunner = trustAnchorRepoFromRunner();
6598
+ if (fromRunner)
6599
+ return fromRunner;
6508
6600
  try {
6509
6601
  const url = execFileSync2("git", ["remote", "get-url", "origin"], {
6510
6602
  encoding: "utf-8",
6511
6603
  stdio: ["ignore", "pipe", "pipe"]
6512
- }).trim();
6513
- const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
6514
- return m?.[1] && m[2] ? wellFormed(`${m[1]}/${m[2]}`) : null;
6604
+ });
6605
+ return trustAnchorRepoFromRemoteUrl(url);
6606
+ } catch {
6607
+ return null;
6608
+ }
6609
+ }
6610
+ async function trustAnchorRepoAsync() {
6611
+ const fromRunner = trustAnchorRepoFromRunner();
6612
+ if (fromRunner)
6613
+ return fromRunner;
6614
+ try {
6615
+ const { stdout } = await execFileAsync4("git", ["remote", "get-url", "origin"], {
6616
+ encoding: "utf-8",
6617
+ timeout: 1e4
6618
+ });
6619
+ return trustAnchorRepoFromRemoteUrl(stdout);
6515
6620
  } catch {
6516
6621
  return null;
6517
6622
  }
6518
6623
  }
6624
+ function wellFormedRepoSlug(slug) {
6625
+ return /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
6626
+ }
6627
+ function trustAnchorRepoFromRunner() {
6628
+ const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
6629
+ return fromRunner ? wellFormedRepoSlug(fromRunner) : null;
6630
+ }
6631
+ function trustAnchorRepoFromRemoteUrl(url) {
6632
+ const m = url.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
6633
+ return m?.[1] && m[2] ? wellFormedRepoSlug(`${m[1]}/${m[2]}`) : null;
6634
+ }
6635
+ var execFileAsync4 = promisify4(execFile4);
6519
6636
  function ghFetchTrustAnchorConfig() {
6520
6637
  const repo = trustAnchorRepo();
6521
6638
  if (!repo)
@@ -6525,6 +6642,13 @@ function ghFetchTrustAnchorConfig() {
6525
6642
  stdio: ["ignore", "pipe", "pipe"]
6526
6643
  });
6527
6644
  }
6645
+ async function ghFetchTrustAnchorConfigAsync() {
6646
+ const repo = await trustAnchorRepoAsync();
6647
+ if (!repo)
6648
+ throw new Error("could not resolve repo identity for the trust-anchor read");
6649
+ const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4 });
6650
+ return stdout;
6651
+ }
6528
6652
  function firstLine(err) {
6529
6653
  return err?.message?.split(`
6530
6654
  `)[0] ?? "unknown error";
@@ -6539,16 +6663,35 @@ function isMissingFileError(err) {
6539
6663
  return /\b404\b|not found/i.test(haystack);
6540
6664
  }
6541
6665
  function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
6542
- 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.
6543
- `);
6544
6666
  let base64;
6545
6667
  try {
6546
- base64 = fetcher().trim();
6668
+ base64 = fetcher();
6547
6669
  } catch (err) {
6548
- if (!isMissingFileError(err))
6549
- warn(firstLine(err));
6550
- return null;
6670
+ return trustAnchorFetchFailed(err);
6671
+ }
6672
+ return parseTrustAnchorContent(base64);
6673
+ }
6674
+ async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
6675
+ const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
6676
+ let base64;
6677
+ try {
6678
+ base64 = await fetcher();
6679
+ } catch (err) {
6680
+ return trustAnchorFetchFailed(err, warn);
6551
6681
  }
6682
+ return parseTrustAnchorContent(base64, warn);
6683
+ }
6684
+ function warnTrustAnchorFallback(why) {
6685
+ 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.
6686
+ `);
6687
+ }
6688
+ function trustAnchorFetchFailed(err, warn = warnTrustAnchorFallback) {
6689
+ if (!isMissingFileError(err))
6690
+ warn(firstLine(err));
6691
+ return null;
6692
+ }
6693
+ function parseTrustAnchorContent(content, warn = warnTrustAnchorFallback) {
6694
+ const base64 = content.trim();
6552
6695
  if (!base64)
6553
6696
  return null;
6554
6697
  try {
@@ -6577,11 +6720,13 @@ function loadConfig() {
6577
6720
  var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
6578
6721
 
6579
6722
  // src/lib/diff-evidence.ts
6580
- import { execFileSync as execFileSync6 } from "node:child_process";
6581
- import { join as join5, relative, resolve as resolve2 } from "node:path";
6723
+ import { execFileSync as execFileSync5 } from "node:child_process";
6724
+ import { join as join8, relative, resolve as resolve2 } from "node:path";
6582
6725
 
6583
6726
  // src/lib/brief-assembly.ts
6584
6727
  import { execFileSync as execFileSync4 } from "node:child_process";
6728
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "node:fs";
6729
+ import { join as join3 } from "node:path";
6585
6730
 
6586
6731
  // ../../packages/sources/src/commands.ts
6587
6732
  var COMMANDS = [
@@ -6734,10 +6879,10 @@ var COMMANDS = [
6734
6879
  }
6735
6880
  ],
6736
6881
  details: [
6737
- "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.",
6882
+ "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.",
6738
6883
  "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.",
6739
- "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.",
6740
- "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."
6884
+ "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.",
6885
+ "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`)."
6741
6886
  ],
6742
6887
  status: "shipped"
6743
6888
  },
@@ -6906,48 +7051,6 @@ var COMMANDS = [
6906
7051
  ],
6907
7052
  status: "shipped"
6908
7053
  },
6909
- {
6910
- name: "log flush",
6911
- description: "Post a target Issue or PR's outbox as one or more marked comments, then truncate what the forge confirmed",
6912
- flags: [
6913
- { flag: "--issue", description: "Flush this Issue's outbox (`~/.vinaya/outbox/<owner>-<repo>/<n>.ndjson`)" },
6914
- {
6915
- flag: "--pr",
6916
- description: "Flush the Issue named by this PR's `Closes #N` line, posting the comments on the PR"
6917
- },
6918
- { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
6919
- ],
6920
- details: [
6921
- "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.",
6922
- "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.",
6923
- "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."
6924
- ],
6925
- status: "shipped"
6926
- },
6927
- {
6928
- name: "log export-artifact",
6929
- description: "Copy this run's own local outbox into a file, for the generated task-path workflow's own upload step",
6930
- flags: [],
6931
- details: [
6932
- "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.",
6933
- "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."
6934
- ],
6935
- status: "shipped"
6936
- },
6937
- {
6938
- name: "log collect-artifact",
6939
- description: "Validate a downloaded task-log artifact and publish the valid records through the existing flush path",
6940
- flags: [
6941
- { flag: "--pr", description: "The pull request this artifact belongs to" },
6942
- { flag: "--repo", description: "Expected `owner/repo` — a provenance cross-check against each record" }
6943
- ],
6944
- details: [
6945
- "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.",
6946
- "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.",
6947
- "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."
6948
- ],
6949
- status: "shipped"
6950
- },
6951
7054
  {
6952
7055
  name: "milestone create",
6953
7056
  description: "Create a GitHub Milestone from a validated body",
@@ -7277,7 +7380,7 @@ var COMMANDS = [
7277
7380
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
7278
7381
  {
7279
7382
  flag: "--pr",
7280
- description: "Flush the outbox to this PR's Issue after the dispatch — mutually exclusive with `--task`"
7383
+ description: "This dispatch's pull request number, for attribution — mutually exclusive with `--task`"
7281
7384
  },
7282
7385
  { flag: "--round", description: "Round number, for a dispatch inside a review loop" },
7283
7386
  {
@@ -7289,7 +7392,7 @@ var COMMANDS = [
7289
7392
  details: [
7290
7393
  "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.",
7291
7394
  "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`.",
7292
- "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.",
7395
+ "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.",
7293
7396
  "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."
7294
7397
  ],
7295
7398
  status: "shipped"
@@ -7309,7 +7412,8 @@ var COMMANDS = [
7309
7412
  "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> -->`.",
7310
7413
  "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.",
7311
7414
  "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.",
7312
- "Every dispatch and round transition is a log line through the Vinaya Log, flushed to the forge at each round boundary."
7415
+ "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.",
7416
+ "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)."
7313
7417
  ],
7314
7418
  status: "shipped"
7315
7419
  }
@@ -7446,25 +7550,6 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
7446
7550
  };
7447
7551
  }
7448
7552
 
7449
- // src/lib/brief-assembly.ts
7450
- function git(args) {
7451
- try {
7452
- return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7453
- } catch {
7454
- return "";
7455
- }
7456
- }
7457
- function expandGlob(glob) {
7458
- const out = git(["ls-files", "--", glob]);
7459
- return out.split(`
7460
- `).map((s) => s.trim()).filter(Boolean);
7461
- }
7462
- var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
7463
-
7464
- // src/checks/registry.ts
7465
- import { existsSync as existsSync3 } from "node:fs";
7466
- import { join as join3 } from "node:path";
7467
-
7468
7553
  // src/lib/package-root.ts
7469
7554
  import { existsSync as existsSync2 } from "node:fs";
7470
7555
  import { dirname as dirname2, join as join2 } from "node:path";
@@ -7482,13 +7567,33 @@ function packageRoot(moduleUrl) {
7482
7567
  return dir;
7483
7568
  }
7484
7569
 
7570
+ // src/lib/brief-assembly.ts
7571
+ var PACKAGE_ROOT = packageRoot(import.meta.url);
7572
+ var PACKAGED_TEMPLATE_PATH = join3(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
7573
+ var TEMPLATE_PATH = existsSync3(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join3(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
7574
+ function git(args) {
7575
+ try {
7576
+ return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7577
+ } catch {
7578
+ return "";
7579
+ }
7580
+ }
7581
+ function expandGlob(glob) {
7582
+ const out = git(["ls-files", "--", glob]);
7583
+ return out.split(`
7584
+ `).map((s) => s.trim()).filter(Boolean);
7585
+ }
7586
+ var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
7587
+
7485
7588
  // src/checks/registry.ts
7486
- var DIST_BIN_DIR = join3(packageRoot(import.meta.url), "dist", "checks", "bin");
7487
- var SRC_BIN_DIR = join3(packageRoot(import.meta.url), "src", "checks", "bin");
7488
- var BIN_DIR = existsSync3(DIST_BIN_DIR) ? DIST_BIN_DIR : SRC_BIN_DIR;
7589
+ import { existsSync as existsSync4 } from "node:fs";
7590
+ import { join as join4 } from "node:path";
7591
+ var DIST_BIN_DIR = join4(packageRoot(import.meta.url), "dist", "checks", "bin");
7592
+ var SRC_BIN_DIR = join4(packageRoot(import.meta.url), "src", "checks", "bin");
7593
+ var BIN_DIR = existsSync4(DIST_BIN_DIR) ? DIST_BIN_DIR : SRC_BIN_DIR;
7489
7594
  var BIN_EXT = BIN_DIR === DIST_BIN_DIR ? ".js" : ".ts";
7490
7595
  function bin(name) {
7491
- return join3(BIN_DIR, `${name}${BIN_EXT}`);
7596
+ return join4(BIN_DIR, `${name}${BIN_EXT}`);
7492
7597
  }
7493
7598
  var REGISTRY = [
7494
7599
  [
@@ -7900,6 +8005,16 @@ var REGISTRY = [
7900
8005
  },
7901
8006
  0
7902
8007
  ],
8008
+ [
8009
+ {
8010
+ name: "ci-shard-coverage",
8011
+ run: bin("check-ci-shard-coverage"),
8012
+ scope: "diff",
8013
+ timeoutMs: 15000,
8014
+ env: {}
8015
+ },
8016
+ 0
8017
+ ],
7903
8018
  [
7904
8019
  {
7905
8020
  name: "workspace-escape",
@@ -8037,42 +8152,382 @@ function coreCheckRegistry() {
8037
8152
  var CORE_CHECK_RING = Object.fromEntries(REGISTRY.map(([spec, ring]) => [spec.name, ring]));
8038
8153
 
8039
8154
  // src/lib/log-sink.ts
8040
- import { execFileSync as execFileSync5 } from "node:child_process";
8041
- import { randomUUID } from "node:crypto";
8155
+ import { execFile as execFile5 } from "node:child_process";
8156
+ import { randomUUID as randomUUID2 } from "node:crypto";
8157
+ import {
8158
+ closeSync as closeSync3,
8159
+ constants as fsConstants3,
8160
+ existsSync as existsSync6,
8161
+ fstatSync as fstatSync2,
8162
+ mkdirSync as mkdirSync3,
8163
+ openSync as openSync3,
8164
+ readFileSync as readFileSync5,
8165
+ renameSync as renameSync2,
8166
+ writeSync as writeSync2
8167
+ } from "node:fs";
8168
+ import { hostname as osHostname, homedir as homedir3 } from "node:os";
8169
+ import { dirname as dirname5, join as join7 } from "node:path";
8170
+ import { promisify as promisify5 } from "node:util";
8171
+
8172
+ // src/lib/run-paths.ts
8173
+ import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync2 } from "node:fs";
8174
+ import { dirname as dirname3, join as join5, resolve as resolvePath } from "node:path";
8175
+ var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8176
+ function isSafeRepoSegment(segment) {
8177
+ return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
8178
+ }
8179
+ function repoSegment(repo) {
8180
+ if (!repo || !isSafeRepoSegment(repo.owner) || !isSafeRepoSegment(repo.repo))
8181
+ return "unresolved";
8182
+ return `${repo.owner}-${repo.repo}`;
8183
+ }
8184
+ function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
8185
+ return join5(home, "runtime", repoSegment(repo));
8186
+ }
8187
+ function resolveRuntimeDir(input) {
8188
+ const local = resolveRuntimeDirSetting(input.localConfig);
8189
+ if (local === null)
8190
+ return defaultRuntimeDir(input.repo, input.home);
8191
+ if (isInsideRepo(local, input.repoRoot))
8192
+ return defaultRuntimeDir(input.repo, input.home);
8193
+ if (!input.unattended)
8194
+ return local;
8195
+ const anchored = resolveTrustAnchorRuntimeDir(local, input.trustAnchorConfig ?? null);
8196
+ return anchored ?? defaultRuntimeDir(input.repo, input.home);
8197
+ }
8198
+ function isInsideRepo(candidate, repoRoot) {
8199
+ if (!repoRoot)
8200
+ return false;
8201
+ const root = resolvePath(repoRoot);
8202
+ const target = resolvePath(candidate);
8203
+ return target === root || target.startsWith(`${root}/`);
8204
+ }
8205
+ var UNATTENDED_ENV_KEY = "VINAYA_UNATTENDED";
8206
+ var RUNTIME_DIR_ENV_KEY = "VINAYA_RUNTIME_DIR";
8207
+ function isUnattendedProcess(env = process.env) {
8208
+ return env[UNATTENDED_ENV_KEY] === "1" || (env.VINAYA_ROLE ?? "") !== "";
8209
+ }
8210
+ var memoized = null;
8211
+ async function runtimeDirForRepoAsync(repo) {
8212
+ const key = repoSegment(repo);
8213
+ if (memoized?.key === key)
8214
+ return memoized.value;
8215
+ const inputs = runtimeDirInputs();
8216
+ if (typeof inputs === "string")
8217
+ return inputs;
8218
+ const value = resolveRuntimeDir({
8219
+ repo,
8220
+ ...inputs.base,
8221
+ trustAnchorConfig: inputs.needsAnchor ? await loadTrustAnchorConfigAsync() : null
8222
+ });
8223
+ memoized = { key, value };
8224
+ return value;
8225
+ }
8226
+ function runtimeDirInputs() {
8227
+ const handedDown = process.env[RUNTIME_DIR_ENV_KEY];
8228
+ if (handedDown)
8229
+ return handedDown;
8230
+ const localConfig = loadConfig();
8231
+ const unattended = isUnattendedProcess();
8232
+ return {
8233
+ base: { localConfig, unattended, repoRoot: repoRootSync() },
8234
+ needsAnchor: unattended && resolveRuntimeDirSetting(localConfig) !== null
8235
+ };
8236
+ }
8237
+ function repoRootSync(start = process.cwd()) {
8238
+ let dir;
8239
+ try {
8240
+ dir = realpathSync2(start);
8241
+ } catch {
8242
+ return null;
8243
+ }
8244
+ for (;; ) {
8245
+ if (existsSync5(join5(dir, ".git")))
8246
+ return dir;
8247
+ const parent = dirname3(dir);
8248
+ if (parent === dir)
8249
+ return null;
8250
+ dir = parent;
8251
+ }
8252
+ }
8253
+
8254
+ // src/lib/log-webhook-drain.ts
8042
8255
  import {
8043
8256
  closeSync as closeSync2,
8044
8257
  constants as fsConstants2,
8045
- existsSync as existsSync4,
8046
- fstatSync as fstatSync2,
8258
+ lstatSync,
8047
8259
  mkdirSync as mkdirSync2,
8048
8260
  openSync as openSync2,
8049
- readFileSync as readFileSync3,
8261
+ linkSync,
8262
+ readFileSync as readFileSync4,
8050
8263
  renameSync,
8264
+ statSync,
8265
+ unlinkSync,
8266
+ writeFileSync as writeFileSync2,
8051
8267
  writeSync
8052
8268
  } from "node:fs";
8053
- import { hostname as osHostname, homedir as homedir2 } from "node:os";
8054
- import { dirname as dirname3, join as join4 } from "node:path";
8055
- var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8269
+ import { randomUUID } from "node:crypto";
8270
+ import { homedir as homedir2 } from "node:os";
8271
+ import { dirname as dirname4, join as join6 } from "node:path";
8272
+ var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
8273
+ var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
8274
+ var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8275
+ function isSafeRepoSegment2(segment) {
8276
+ return SAFE_PATH_SEGMENT2.test(segment) && !segment.includes("..");
8277
+ }
8278
+ function isErrnoCode(err, code) {
8279
+ return typeof err === "object" && err !== null && err.code === code;
8280
+ }
8056
8281
  function isEnoent(err) {
8282
+ return isErrnoCode(err, "ENOENT");
8283
+ }
8284
+ var WEBHOOK_DRAIN_LOCK_STALE_MS = 4 * WEBHOOK_FETCH_TIMEOUT_MS;
8285
+ function tryCreateLock(lockPath, token) {
8286
+ try {
8287
+ mkdirSync2(dirname4(lockPath), { recursive: true, mode: 448 });
8288
+ const fd = openSync2(lockPath, fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL, 384);
8289
+ try {
8290
+ writeSync(fd, `${token}
8291
+ `);
8292
+ } finally {
8293
+ closeSync2(fd);
8294
+ }
8295
+ return true;
8296
+ } catch (err) {
8297
+ if (isErrnoCode(err, "EEXIST"))
8298
+ return false;
8299
+ throw err;
8300
+ }
8301
+ }
8302
+ function acquireDrainLock(lockPath) {
8303
+ const token = `${process.pid}:${randomUUID()}`;
8304
+ if (tryCreateLock(lockPath, token))
8305
+ return token;
8306
+ let observedMtimeMs;
8307
+ try {
8308
+ observedMtimeMs = statSync(lockPath).mtimeMs;
8309
+ } catch (err) {
8310
+ if (!isEnoent(err))
8311
+ throw err;
8312
+ return tryCreateLock(lockPath, token) ? token : null;
8313
+ }
8314
+ if (Date.now() - observedMtimeMs <= WEBHOOK_DRAIN_LOCK_STALE_MS)
8315
+ return null;
8316
+ const claimed = `${lockPath}.claimed-${randomUUID()}`;
8317
+ try {
8318
+ renameSync(lockPath, claimed);
8319
+ } catch (err) {
8320
+ if (isEnoent(err))
8321
+ return null;
8322
+ throw err;
8323
+ }
8324
+ let claimedMtimeMs = null;
8325
+ try {
8326
+ claimedMtimeMs = statSync(claimed).mtimeMs;
8327
+ } catch (err) {
8328
+ if (!isEnoent(err))
8329
+ throw err;
8330
+ }
8331
+ if (claimedMtimeMs !== observedMtimeMs) {
8332
+ try {
8333
+ linkSync(claimed, lockPath);
8334
+ } catch (err) {
8335
+ if (!isErrnoCode(err, "EEXIST"))
8336
+ throw err;
8337
+ }
8338
+ try {
8339
+ unlinkSync(claimed);
8340
+ } catch (err) {
8341
+ if (!isEnoent(err))
8342
+ throw err;
8343
+ }
8344
+ return null;
8345
+ }
8346
+ unlinkSync(claimed);
8347
+ return tryCreateLock(lockPath, token) ? token : null;
8348
+ }
8349
+ function releaseDrainLock(lockPath, token) {
8350
+ try {
8351
+ const holder = readFileSync4(lockPath, "utf8").trim();
8352
+ if (holder !== token)
8353
+ return;
8354
+ unlinkSync(lockPath);
8355
+ } catch (err) {
8356
+ if (!isEnoent(err))
8357
+ throw err;
8358
+ }
8359
+ }
8360
+
8361
+ class WebhookDrainError extends Error {
8362
+ code;
8363
+ constructor(code, message) {
8364
+ super(message);
8365
+ this.code = code;
8366
+ }
8367
+ }
8368
+ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
8369
+ const resolved = await resolveRepo();
8370
+ const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
8371
+ const outboxRoot = () => join6(GLOBAL_VINAYA_HOME, "outbox");
8372
+ const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
8373
+ const lockPath = `${path}.flush-lock`;
8374
+ const lockToken = acquireDrainLock(lockPath);
8375
+ if (lockToken === null)
8376
+ return { flushed: false };
8377
+ try {
8378
+ let lstat;
8379
+ try {
8380
+ lstat = lstatSync(path);
8381
+ } catch (err) {
8382
+ if (!isEnoent(err))
8383
+ throw err;
8384
+ }
8385
+ if (lstat === undefined)
8386
+ return { flushed: false };
8387
+ if (!lstat.isFile()) {
8388
+ 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}`);
8389
+ }
8390
+ const buf = readFileSync4(path);
8391
+ const startOffset = buf.byteLength;
8392
+ const rawLines = buf.toString("utf8").split(`
8393
+ `).filter((l) => l.length > 0);
8394
+ if (rawLines.length === 0)
8395
+ return { flushed: false };
8396
+ const postLines = [];
8397
+ for (let i = 0;i < rawLines.length; i++) {
8398
+ const record = classifyStoredLine(rawLines[i], homedir2());
8399
+ if (record.status !== "ok") {
8400
+ throw new WebhookDrainError("log-webhook-drain-corrupt-line", `log webhook drain: outbox line ${i} failed schema re-validation — ${record.reason}`);
8401
+ }
8402
+ postLines.push(record.postLine);
8403
+ }
8404
+ const body = `${postLines.join(`
8405
+ `)}
8406
+ `;
8407
+ const bytes = Buffer.byteLength(body, "utf8");
8408
+ if (bytes > MAX_WEBHOOK_BODY_BYTES) {
8409
+ 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.`);
8410
+ }
8411
+ let response;
8412
+ try {
8413
+ response = await fetch(webhookUrl, {
8414
+ method: "POST",
8415
+ headers: { "content-type": "application/x-ndjson", ...headers },
8416
+ body,
8417
+ signal: AbortSignal.timeout(fetchTimeoutMs)
8418
+ });
8419
+ } catch (err) {
8420
+ const reason = err instanceof Error && err.name === "TimeoutError" ? `timed out after ${fetchTimeoutMs}ms` : err instanceof Error ? err.message : String(err);
8421
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} failed: ${reason}`);
8422
+ }
8423
+ if (!response.ok) {
8424
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} returned ${response.status} ${response.statusText}`);
8425
+ }
8426
+ const liveNow = readFileSync4(path);
8427
+ const tail = liveNow.subarray(Math.min(startOffset, liveNow.byteLength));
8428
+ writeFileSync2(path, tail);
8429
+ return { flushed: true, lineCount: postLines.length, bytes };
8430
+ } finally {
8431
+ releaseDrainLock(lockPath, lockToken);
8432
+ }
8433
+ }
8434
+
8435
+ // src/lib/log-sink.ts
8436
+ var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8437
+ var LOG_CONTEXT_LOOKUP_DEADLINE_MS = 3000;
8438
+ function withDeadline(work, ms, fallback) {
8439
+ return new Promise((resolve) => {
8440
+ const timer = setTimeout(() => resolve(fallback), ms);
8441
+ timer.unref?.();
8442
+ work.then((value) => {
8443
+ clearTimeout(timer);
8444
+ resolve(value);
8445
+ }, () => {
8446
+ clearTimeout(timer);
8447
+ resolve(fallback);
8448
+ });
8449
+ });
8450
+ }
8451
+ async function safeLoadTrustAnchorConfig() {
8452
+ return withDeadline(loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
8453
+ }
8454
+ function logsCredentialMissing(headers, env) {
8455
+ if (!headers)
8456
+ return false;
8457
+ const varPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
8458
+ for (const value of Object.values(headers)) {
8459
+ for (const match of value.matchAll(varPattern)) {
8460
+ if (!env[match[1]])
8461
+ return true;
8462
+ }
8463
+ }
8464
+ return false;
8465
+ }
8466
+ function resolveLogDestinationFrom(input) {
8467
+ const local = resolveLogsSetting(input.localConfig);
8468
+ let effective = null;
8469
+ if (input.unattended) {
8470
+ effective = local ? resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig) : resolveLogsSetting(input.trustAnchorConfig);
8471
+ } else {
8472
+ effective = local;
8473
+ }
8474
+ if (hostFromEnv(input.env) === "ci") {
8475
+ if (effective && "url" in effective) {
8476
+ if (logsCredentialMissing(effective.headers, input.env)) {
8477
+ return {
8478
+ kind: "none",
8479
+ reason: "a logs.url server destination is configured, but this job holds no delivery credential (a fork pull request, or a missing repository secret)"
8480
+ };
8481
+ }
8482
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
8483
+ }
8484
+ return {
8485
+ kind: "none",
8486
+ reason: "no server destination is configured for CI delivery (vinaya.config.json logs.url)"
8487
+ };
8488
+ }
8489
+ if (effective && "url" in effective) {
8490
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
8491
+ }
8492
+ if (effective && "folder" in effective && isInsideRepo(effective.folder, input.repoRoot)) {
8493
+ effective = null;
8494
+ }
8495
+ const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
8496
+ return { kind: "folder", folder };
8497
+ }
8498
+ var processTrustAnchorOnce;
8499
+ function processTrustAnchor() {
8500
+ if (processTrustAnchorOnce === undefined)
8501
+ processTrustAnchorOnce = safeLoadTrustAnchorConfig();
8502
+ return processTrustAnchorOnce;
8503
+ }
8504
+ async function defaultResolveLogDestination(repo, env) {
8505
+ const localConfig = loadConfig();
8506
+ const unattended = isUnattendedProcess(process.env);
8507
+ return resolveLogDestinationFrom({
8508
+ localConfig,
8509
+ trustAnchorConfig: unattended ? await processTrustAnchor() : null,
8510
+ unattended,
8511
+ env,
8512
+ defaultFolder: join7(await runtimeDirForRepoAsync(repo), "logs"),
8513
+ repoRoot: repoRootSync()
8514
+ });
8515
+ }
8516
+ function isEnoent2(err) {
8057
8517
  return typeof err === "object" && err !== null && err.code === "ENOENT";
8058
8518
  }
8059
- function resolveDoctrine(cwd, vinayaVersion) {
8519
+ var execFileAsync5 = promisify5(execFile5);
8520
+ async function resolveDoctrine(cwd, vinayaVersion) {
8060
8521
  let toplevel;
8061
8522
  try {
8062
- toplevel = execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
8063
- encoding: "utf8",
8064
- stdio: ["ignore", "pipe", "pipe"]
8065
- }).trim();
8523
+ toplevel = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
8066
8524
  } catch (err) {
8067
- return isEnoent(err) ? "unknown" : vinayaVersion;
8525
+ return isEnoent2(err) ? "unknown" : vinayaVersion;
8068
8526
  }
8069
- if (!existsSync4(join4(toplevel, "aeg-root", "roles")))
8527
+ if (!existsSync6(join7(toplevel, "aeg-root", "roles")))
8070
8528
  return vinayaVersion;
8071
8529
  try {
8072
- const sha = execFileSync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], {
8073
- encoding: "utf8",
8074
- stdio: ["ignore", "pipe", "pipe"]
8075
- }).trim();
8530
+ const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
8076
8531
  return `aeg-root@${sha}`;
8077
8532
  } catch {
8078
8533
  return vinayaVersion;
@@ -8080,20 +8535,20 @@ function resolveDoctrine(cwd, vinayaVersion) {
8080
8535
  }
8081
8536
  function readVinayaVersion() {
8082
8537
  try {
8083
- const pkg = JSON.parse(readFileSync3(join4(packageRoot(import.meta.url), "package.json"), "utf8"));
8538
+ const pkg = JSON.parse(readFileSync5(join7(packageRoot(import.meta.url), "package.json"), "utf8"));
8084
8539
  return pkg.version ?? "unknown";
8085
8540
  } catch {
8086
8541
  return "unknown";
8087
8542
  }
8088
8543
  }
8089
- var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8090
- function isSafeRepoSegment(segment) {
8091
- return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
8544
+ var SAFE_PATH_SEGMENT3 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8545
+ function isSafeRepoSegment3(segment) {
8546
+ return SAFE_PATH_SEGMENT3.test(segment) && !segment.includes("..");
8092
8547
  }
8093
8548
  function outboxPathFor(deps, repo, issue) {
8094
8549
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
8095
8550
  const fileName = `${issue ?? "none"}.ndjson`;
8096
- return join4(deps.outboxRoot(), dirName, fileName);
8551
+ return join7(deps.outboxRoot(), dirName, fileName);
8097
8552
  }
8098
8553
  function hostFromEnv(env) {
8099
8554
  if (env.GITHUB_ACTIONS)
@@ -8104,28 +8559,34 @@ function hostFromEnv(env) {
8104
8559
  return "loop";
8105
8560
  return "cli";
8106
8561
  }
8562
+ var warnedThisProcess = false;
8563
+ function defaultStderr(message) {
8564
+ if (warnedThisProcess)
8565
+ return;
8566
+ warnedThisProcess = true;
8567
+ process.stderr.write(message);
8568
+ }
8107
8569
  function defaultDeps() {
8108
8570
  return {
8109
- outboxRoot: () => join4(GLOBAL_VINAYA_HOME, "outbox"),
8110
- home: () => homedir2(),
8571
+ outboxRoot: () => join7(GLOBAL_VINAYA_HOME, "outbox"),
8572
+ home: () => homedir3(),
8111
8573
  hostname: () => osHostname(),
8112
8574
  cwd: () => process.cwd(),
8113
8575
  now: () => new Date,
8114
8576
  env: () => process.env,
8115
8577
  resolveRepo: () => resolveRepo(),
8116
8578
  vinayaVersion: () => readVinayaVersion(),
8117
- stderr: (message) => {
8118
- process.stderr.write(message);
8119
- },
8579
+ stderr: defaultStderr,
8120
8580
  inputVersions: () => {
8121
8581
  return;
8122
- }
8582
+ },
8583
+ resolveLogDestination: defaultResolveLogDestination
8123
8584
  };
8124
8585
  }
8125
- var APPEND_OPEN_FLAGS = fsConstants2.O_WRONLY | fsConstants2.O_APPEND | fsConstants2.O_CREAT | fsConstants2.O_NOFOLLOW | fsConstants2.O_NONBLOCK;
8586
+ var APPEND_OPEN_FLAGS = fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK;
8126
8587
  function guardedAppendOpen(path) {
8127
8588
  try {
8128
- return openSync2(path, APPEND_OPEN_FLAGS, 384);
8589
+ return openSync3(path, APPEND_OPEN_FLAGS, 384);
8129
8590
  } catch {
8130
8591
  return;
8131
8592
  }
@@ -8133,7 +8594,7 @@ function guardedAppendOpen(path) {
8133
8594
  function reportRotationOverflow(backupPath, warn) {
8134
8595
  let raw;
8135
8596
  try {
8136
- raw = readFileSync3(backupPath, "utf8");
8597
+ raw = readFileSync5(backupPath, "utf8");
8137
8598
  } catch {
8138
8599
  return;
8139
8600
  }
@@ -8156,7 +8617,7 @@ function reportRotationOverflow(backupPath, warn) {
8156
8617
  }
8157
8618
  function appendLine(path, line, warn) {
8158
8619
  try {
8159
- mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
8620
+ mkdirSync3(dirname5(path), { recursive: true, mode: 448 });
8160
8621
  let fd = guardedAppendOpen(path);
8161
8622
  if (fd === undefined) {
8162
8623
  warn(`vinaya: log outbox target could not be opened (symlink, FIFO, or unwritable) — refusing: ${path}
@@ -8172,11 +8633,11 @@ function appendLine(path, line, warn) {
8172
8633
  return;
8173
8634
  }
8174
8635
  if (stat.size > OUTBOX_MAX_BYTES) {
8175
- closeSync2(fd);
8636
+ closeSync3(fd);
8176
8637
  closed = true;
8177
8638
  const backupPath = path.replace(/\.ndjson$/, ".1.ndjson");
8178
8639
  reportRotationOverflow(backupPath, warn);
8179
- renameSync(path, backupPath);
8640
+ renameSync2(path, backupPath);
8180
8641
  const rotated = guardedAppendOpen(path);
8181
8642
  if (rotated === undefined) {
8182
8643
  warn(`vinaya: log outbox target could not be reopened after rotation — refusing: ${path}
@@ -8186,10 +8647,10 @@ function appendLine(path, line, warn) {
8186
8647
  fd = rotated;
8187
8648
  closed = false;
8188
8649
  }
8189
- writeSync(fd, line);
8650
+ writeSync2(fd, line);
8190
8651
  } finally {
8191
8652
  if (!closed)
8192
- closeSync2(fd);
8653
+ closeSync3(fd);
8193
8654
  }
8194
8655
  } catch (err) {
8195
8656
  warn(`vinaya: log outbox write failed — ${err instanceof Error ? err.message : String(err)}
@@ -8198,8 +8659,8 @@ function appendLine(path, line, warn) {
8198
8659
  }
8199
8660
  function createLogSink(overrides = {}) {
8200
8661
  const deps = { ...defaultDeps(), ...overrides };
8201
- const runId = deps.env().VINAYA_RUN_ID || randomUUID();
8202
- const processId = randomUUID();
8662
+ const runId = deps.env().VINAYA_RUN_ID || randomUUID2();
8663
+ const processId = randomUUID2();
8203
8664
  let seq = 0;
8204
8665
  let warned = false;
8205
8666
  const warnOnce = (message) => {
@@ -8212,8 +8673,9 @@ function createLogSink(overrides = {}) {
8212
8673
  };
8213
8674
  let doctrineCache;
8214
8675
  const doctrine = () => {
8215
- if (doctrineCache === undefined)
8216
- doctrineCache = resolveDoctrine(deps.cwd(), deps.vinayaVersion());
8676
+ if (doctrineCache === undefined) {
8677
+ doctrineCache = withDeadline(resolveDoctrine(deps.cwd(), deps.vinayaVersion()), LOG_CONTEXT_LOOKUP_DEADLINE_MS, deps.vinayaVersion());
8678
+ }
8217
8679
  return doctrineCache;
8218
8680
  };
8219
8681
  let resolveRepoCache;
@@ -8222,6 +8684,30 @@ function createLogSink(overrides = {}) {
8222
8684
  resolveRepoCache = deps.resolveRepo();
8223
8685
  return resolveRepoCache;
8224
8686
  };
8687
+ let contextCache;
8688
+ const context = () => {
8689
+ if (contextCache === undefined) {
8690
+ const env = deps.env();
8691
+ contextCache = Promise.all([
8692
+ withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
8693
+ doctrine()
8694
+ ]).then(async ([resolved, doctrineValue]) => {
8695
+ const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
8696
+ return { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
8697
+ });
8698
+ }
8699
+ return contextCache;
8700
+ };
8701
+ let drainChain = Promise.resolve();
8702
+ const pendingWrites = new Set;
8703
+ const scheduleWebhookDrain = (issue, url, headers) => {
8704
+ drainChain = drainChain.then(() => drainOutboxToWebhook(issue, url, headers)).then(() => {
8705
+ return;
8706
+ }).catch((err) => {
8707
+ warnOnce(`vinaya: log delivery to ${url} failed — queued in the local outbox, retried on the next event: ${err instanceof Error ? err.message : String(err)}
8708
+ `);
8709
+ });
8710
+ };
8225
8711
  function log(e) {
8226
8712
  try {
8227
8713
  const env = deps.env();
@@ -8236,22 +8722,26 @@ function createLogSink(overrides = {}) {
8236
8722
  attempt: env.VINAYA_ATTEMPT,
8237
8723
  parent: env.VINAYA_PARENT_EVENT
8238
8724
  };
8239
- resolveRepoOnce().then((resolved) => {
8240
- const repo = resolved && isSafeRepoSegment(resolved.owner) && isSafeRepoSegment(resolved.repo) ? resolved : null;
8725
+ const written = context().then(({ repo, doctrine: doctrineValue, destination: resolvedDestination }) => {
8241
8726
  const header = buildHeader({
8242
8727
  now,
8243
8728
  runId,
8244
8729
  seq: mySeq,
8245
8730
  repo: repo ? `${repo.owner}/${repo.repo}` : null,
8246
8731
  vinaya: deps.vinayaVersion(),
8247
- doctrine: doctrine(),
8732
+ doctrine: doctrineValue,
8248
8733
  host,
8249
8734
  hostname: deps.hostname(),
8250
8735
  env: envFields,
8251
- eventId: randomUUID(),
8736
+ eventId: randomUUID2(),
8252
8737
  processId,
8253
8738
  inputVersions: deps.inputVersions()
8254
8739
  });
8740
+ if (resolvedDestination.kind === "none") {
8741
+ warnOnce(`vinaya: not recording — ${resolvedDestination.reason}
8742
+ `);
8743
+ return;
8744
+ }
8255
8745
  const full = { ...e, ...header };
8256
8746
  const parsed = LogEventSchema.safeParse(full);
8257
8747
  if (!parsed.success) {
@@ -8261,25 +8751,42 @@ function createLogSink(overrides = {}) {
8261
8751
  }
8262
8752
  const line = `${JSON.stringify(redact(parsed.data, deps.home()))}
8263
8753
  `;
8264
- appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
8754
+ const destination = resolvedDestination;
8755
+ if (destination.kind === "server") {
8756
+ appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
8757
+ scheduleWebhookDrain(header.subject.issue, destination.url, destination.headers);
8758
+ } else {
8759
+ appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
8760
+ }
8265
8761
  }).catch((err) => {
8266
8762
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
8267
8763
  `);
8268
8764
  });
8765
+ pendingWrites.add(written);
8766
+ written.finally(() => pendingWrites.delete(written));
8269
8767
  } catch (err) {
8270
8768
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
8271
8769
  `);
8272
8770
  }
8273
8771
  }
8274
8772
  const warmup = () => {
8275
- doctrine();
8276
8773
  const originalWarn = console.warn;
8277
8774
  console.warn = () => {};
8278
8775
  resolveRepoOnce().finally(() => {
8279
8776
  console.warn = originalWarn;
8280
8777
  });
8778
+ context().catch(() => {
8779
+ return;
8780
+ });
8781
+ };
8782
+ const drain = async () => {
8783
+ if (pendingWrites.size > 0)
8784
+ await Promise.allSettled(Array.from(pendingWrites));
8785
+ await drainChain.catch(() => {
8786
+ return;
8787
+ });
8281
8788
  };
8282
- return { log, runId, warmup };
8789
+ return { log, runId, warmup, drain };
8283
8790
  }
8284
8791
  var defaultSink = createLogSink();
8285
8792
 
@@ -8330,7 +8837,7 @@ function parseChangedLineRanges(diffOutput) {
8330
8837
  function fileDiffAgainst(ref, path) {
8331
8838
  let out;
8332
8839
  try {
8333
- out = execFileSync6("git", ["diff", `${ref}...HEAD`, "--", path], {
8840
+ out = execFileSync5("git", ["diff", `${ref}...HEAD`, "--", path], {
8334
8841
  encoding: "utf8",
8335
8842
  stdio: ["ignore", "pipe", "pipe"]
8336
8843
  }).trim();
@@ -8341,7 +8848,7 @@ function fileDiffAgainst(ref, path) {
8341
8848
  }
8342
8849
  function revParse(ref) {
8343
8850
  try {
8344
- return execFileSync6("git", ["rev-parse", "--verify", ref], {
8851
+ return execFileSync5("git", ["rev-parse", "--verify", ref], {
8345
8852
  encoding: "utf8",
8346
8853
  stdio: ["ignore", "pipe", "pipe"]
8347
8854
  }).trim();
@@ -8351,7 +8858,7 @@ function revParse(ref) {
8351
8858
  }
8352
8859
  function repoRoot() {
8353
8860
  try {
8354
- return execFileSync6("git", ["rev-parse", "--show-toplevel"], {
8861
+ return execFileSync5("git", ["rev-parse", "--show-toplevel"], {
8355
8862
  encoding: "utf8",
8356
8863
  stdio: ["ignore", "pipe", "pipe"]
8357
8864
  }).trim();
@@ -8362,7 +8869,7 @@ function repoRoot() {
8362
8869
  function changedFiles(base) {
8363
8870
  let out;
8364
8871
  try {
8365
- out = execFileSync6("git", ["diff", "--name-only", `${base}...HEAD`], {
8872
+ out = execFileSync5("git", ["diff", "--name-only", `${base}...HEAD`], {
8366
8873
  encoding: "utf8",
8367
8874
  stdio: ["ignore", "pipe", "pipe"]
8368
8875
  }).trim();
@@ -8387,7 +8894,7 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
8387
8894
  const relPaths = changedFiles(ref);
8388
8895
  if (relPaths === null)
8389
8896
  continue;
8390
- return { base: ref, root, files: relPaths.map((p) => join5(root, p)) };
8897
+ return { base: ref, root, files: relPaths.map((p) => join8(root, p)) };
8391
8898
  }
8392
8899
  return null;
8393
8900
  }
@@ -8424,7 +8931,7 @@ var DOCTRINE_ROOT = loadConfig()?.proseGates?.doctrineRoot ?? "aeg-root";
8424
8931
  var SHIPS_PREFIX2 = `${DOCTRINE_ROOT}/`;
8425
8932
  function git2(args) {
8426
8933
  try {
8427
- return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8934
+ return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8428
8935
  } catch {
8429
8936
  return "";
8430
8937
  }
@@ -8432,15 +8939,15 @@ function git2(args) {
8432
8939
  function collectWorkingTree(dir, out = []) {
8433
8940
  let entries;
8434
8941
  try {
8435
- entries = readdirSync(dir);
8942
+ entries = readdirSync2(dir);
8436
8943
  } catch {
8437
8944
  return out;
8438
8945
  }
8439
8946
  for (const name of entries) {
8440
- const full = join6(dir, name);
8947
+ const full = join9(dir, name);
8441
8948
  let isDir;
8442
8949
  try {
8443
- isDir = statSync(full).isDirectory();
8950
+ isDir = statSync2(full).isDirectory();
8444
8951
  } catch {
8445
8952
  continue;
8446
8953
  }
@@ -8455,7 +8962,7 @@ function collectWorkingTree(dir, out = []) {
8455
8962
  return out;
8456
8963
  }
8457
8964
  function readWorkingTree(paths) {
8458
- return paths.map((p) => ({ path: p, content: readFileSync4(p, "utf8") }));
8965
+ return paths.map((p) => ({ path: p, content: readFileSync6(p, "utf8") }));
8459
8966
  }
8460
8967
  function collectAtRef(ref, dir) {
8461
8968
  const listing = git2(["ls-tree", "-r", "--name-only", ref, "--", dir]);