@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-exec-bits.ts
6
- import { execFileSync as execFileSync7 } from "node:child_process";
7
- import { readFileSync as readFileSync4 } from "node:fs";
4
+ import { execFileSync as execFileSync6 } from "node:child_process";
5
+ import { readFileSync as readFileSync6 } from "node:fs";
8
6
 
9
7
  // src/checks/contract.ts
10
8
  var CHECK_SCHEMA_VERSION = 1;
@@ -14,8 +12,8 @@ function emitCheckError(error) {
14
12
  }
15
13
 
16
14
  // src/lib/diff-evidence.ts
17
- import { execFileSync as execFileSync6 } from "node:child_process";
18
- import { join as join5, relative, resolve as resolve2 } from "node:path";
15
+ import { execFileSync as execFileSync5 } from "node:child_process";
16
+ import { join as join8, relative, resolve as resolve2 } from "node:path";
19
17
  // ../../packages/aeg-core/src/gate-audience.ts
20
18
  var GATE_AUDIENCE = {
21
19
  "check-branch-topology": { shippedAs: "branch-topology", ring: 0 },
@@ -1049,7 +1047,7 @@ function withDefaults(oldDefaults, newDefaults) {
1049
1047
  var endpoint = withDefaults(null, DEFAULTS);
1050
1048
 
1051
1049
  // ../../node_modules/fast-content-type-parse/index.js
1052
- var NullObject = function NullObject2() {};
1050
+ var NullObject = function NullObject() {};
1053
1051
  NullObject.prototype = Object.create(null);
1054
1052
  var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu;
1055
1053
  var quotedPairRE = /\\([\v\u0020-\u00ff])/gu;
@@ -1143,8 +1141,8 @@ function isPlainObject2(value) {
1143
1141
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
1144
1142
  }
1145
1143
  async function fetchWrapper(requestOptions) {
1146
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
1147
- if (!fetch) {
1144
+ const fetch2 = requestOptions.request?.fetch || globalThis.fetch;
1145
+ if (!fetch2) {
1148
1146
  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");
1149
1147
  }
1150
1148
  const log = requestOptions.request?.log || console;
@@ -1156,7 +1154,7 @@ async function fetchWrapper(requestOptions) {
1156
1154
  ]));
1157
1155
  let fetchResponse;
1158
1156
  try {
1159
- fetchResponse = await fetch(requestOptions.url, {
1157
+ fetchResponse = await fetch2(requestOptions.url, {
1160
1158
  method: requestOptions.method,
1161
1159
  body,
1162
1160
  redirect: requestOptions.request?.redirect,
@@ -1793,27 +1791,27 @@ function splitTableRow(row) {
1793
1791
  return parts.map((p) => p.split(PLACEHOLDER).join("|"));
1794
1792
  }
1795
1793
  // ../../packages/aeg-core/src/blast-radius-domains.ts
1796
- function resolveWorkspaceEntry(entry2, listDirs) {
1797
- if (entry2.endsWith("/*")) {
1798
- const baseDir = entry2.slice(0, -2);
1794
+ function resolveWorkspaceEntry(entry, listDirs) {
1795
+ if (entry.endsWith("/*")) {
1796
+ const baseDir = entry.slice(0, -2);
1799
1797
  return listDirs(baseDir).map((name) => `${baseDir}/${name}`);
1800
1798
  }
1801
- if (entry2.includes("*"))
1799
+ if (entry.includes("*"))
1802
1800
  return [];
1803
- return [entry2];
1801
+ return [entry];
1804
1802
  }
1805
1803
  // ../../packages/aeg-core/src/consumer-enumeration.ts
1806
1804
  function deriveWorkspaceMemberDirs(workspaces, listDirs) {
1807
- const positive = workspaces.filter((entry2) => !entry2.startsWith("!"));
1808
- const negative = workspaces.filter((entry2) => entry2.startsWith("!")).map((entry2) => entry2.slice(1));
1805
+ const positive = workspaces.filter((entry) => !entry.startsWith("!"));
1806
+ const negative = workspaces.filter((entry) => entry.startsWith("!")).map((entry) => entry.slice(1));
1809
1807
  const excluded = new Set;
1810
- for (const entry2 of negative) {
1811
- for (const member of resolveWorkspaceEntry(entry2, listDirs))
1808
+ for (const entry of negative) {
1809
+ for (const member of resolveWorkspaceEntry(entry, listDirs))
1812
1810
  excluded.add(member);
1813
1811
  }
1814
1812
  const members = new Set;
1815
- for (const entry2 of positive) {
1816
- for (const member of resolveWorkspaceEntry(entry2, listDirs)) {
1813
+ for (const entry of positive) {
1814
+ for (const member of resolveWorkspaceEntry(entry, listDirs)) {
1817
1815
  if (!excluded.has(member))
1818
1816
  members.add(member);
1819
1817
  }
@@ -2137,15 +2135,15 @@ function summarizeTranscript(jsonl) {
2137
2135
  const line = rawLine.trim();
2138
2136
  if (!line)
2139
2137
  continue;
2140
- let entry2;
2138
+ let entry;
2141
2139
  try {
2142
- entry2 = JSON.parse(line);
2140
+ entry = JSON.parse(line);
2143
2141
  } catch {
2144
2142
  continue;
2145
2143
  }
2146
- if (!entry2 || typeof entry2 !== "object")
2144
+ if (!entry || typeof entry !== "object")
2147
2145
  continue;
2148
- const obj = entry2;
2146
+ const obj = entry;
2149
2147
  if (obj.type !== "assistant")
2150
2148
  continue;
2151
2149
  const message = obj.message;
@@ -2993,7 +2991,7 @@ function isStep0Block(content) {
2993
2991
  }
2994
2992
  function checkCommandsCarryOutput(prBody) {
2995
2993
  const errors = [];
2996
- for (const [label2, num] of [
2994
+ for (const [label, num] of [
2997
2995
  ["5", 5],
2998
2996
  ["6", 6]
2999
2997
  ]) {
@@ -3007,7 +3005,7 @@ function checkCommandsCarryOutput(prBody) {
3007
3005
  continue;
3008
3006
  const next = blocks[i + 1];
3009
3007
  if (!next || isCommandBlock(next.content)) {
3010
- 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.`);
3008
+ 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.`);
3011
3009
  }
3012
3010
  }
3013
3011
  }
@@ -3444,8 +3442,8 @@ function stripPartBackticks(text) {
3444
3442
  function partWordCount(text) {
3445
3443
  return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3446
3444
  }
3447
- function looksLikeFilePath(entry2) {
3448
- const stripped = entry2.replace(/\/\*\*?$/, "");
3445
+ function looksLikeFilePath(entry) {
3446
+ const stripped = entry.replace(/\/\*\*?$/, "");
3449
3447
  const lastSegment = stripped.split("/").pop() ?? stripped;
3450
3448
  const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3451
3449
  return extMatch !== null && extMatch.index > 0;
@@ -3931,14 +3929,14 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3931
3929
  const referenced = extractClosesReferences(prBody);
3932
3930
  if (taskIssueRefs) {
3933
3931
  for (const n of referenced) {
3934
- const ref2 = taskIssueRefs.get(n);
3935
- if (!ref2)
3932
+ const ref = taskIssueRefs.get(n);
3933
+ if (!ref)
3936
3934
  continue;
3937
- const expectedBranch = `task/${ref2.trancheSlug}/${ref2.taskId}`;
3935
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3938
3936
  if (branch !== expectedBranch) {
3939
3937
  return {
3940
3938
  ok: false,
3941
- 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.`
3939
+ 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.`
3942
3940
  };
3943
3941
  }
3944
3942
  }
@@ -3947,15 +3945,15 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3947
3945
  if (!ref)
3948
3946
  return { ok: true };
3949
3947
  if (ref.kind === "issue") {
3950
- const expectedIssue2 = ref.issueNumber;
3951
- if (!referenced.has(expectedIssue2)) {
3948
+ const expectedIssue = ref.issueNumber;
3949
+ if (!referenced.has(expectedIssue)) {
3952
3950
  return {
3953
3951
  ok: false,
3954
- expectedIssue: expectedIssue2,
3955
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue2}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3952
+ expectedIssue,
3953
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3956
3954
  };
3957
3955
  }
3958
- return { ok: true, expectedIssue: expectedIssue2 };
3956
+ return { ok: true, expectedIssue };
3959
3957
  }
3960
3958
  const trancheSlug = ref.tranche;
3961
3959
  const taskId = ref.taskId;
@@ -4001,8 +3999,8 @@ function extractIssue(body) {
4001
3999
  const anchorNums = closesRefs(anchored);
4002
4000
  if (anchorNums.length === 0)
4003
4001
  return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4004
- const issue2 = anchorNums[0];
4005
- return { issue: issue2, extraIssues: bodyNums.filter((n) => n !== issue2), outsideHeader: false };
4002
+ const issue = anchorNums[0];
4003
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
4006
4004
  }
4007
4005
  const headerNums = closesRefs(headerRegion(stripped));
4008
4006
  if (bodyNums.length === 0)
@@ -4071,15 +4069,15 @@ function compareManifest(echoed, current, patchIdOf) {
4071
4069
  const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4072
4070
  const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4073
4071
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4074
- const objectivesVersion2 = isBoundToObjectives(echoed, current.objectivesVersion);
4072
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4075
4073
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4076
4074
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4077
4075
  return {
4078
- bound: head && base && briefHashBound && objectivesVersion2 && rulingOrdinal && policyDigestBound,
4076
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4079
4077
  head,
4080
4078
  base,
4081
4079
  briefHash: briefHashBound,
4082
- objectivesVersion: objectivesVersion2,
4080
+ objectivesVersion,
4083
4081
  rulingOrdinal,
4084
4082
  policyDigest: policyDigestBound
4085
4083
  };
@@ -5511,6 +5509,10 @@ function findWorkspaceEscapes(files, knownPaths, workspaceDirs = DEFAULT_WORKSPA
5511
5509
  }
5512
5510
  return findings;
5513
5511
  }
5512
+ // ../../packages/aeg-core/src/dev-review-loop/types.ts
5513
+ var SEVERITY_COLUMNS = ["blocker", "major", "minor", "critical", "high", "medium", "low"];
5514
+ // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
5515
+ var SUMMARY_TABLE_HEADER = `| round | ${SEVERITY_COLUMNS.join(" | ")} | confidence | outcome |`;
5514
5516
  // ../../packages/aeg-core/src/log/envelope.ts
5515
5517
  import { createHash as createHash5 } from "node:crypto";
5516
5518
 
@@ -6049,6 +6051,7 @@ function redact(value, home) {
6049
6051
  return value;
6050
6052
  }
6051
6053
  // ../../packages/aeg-core/src/log/store.ts
6054
+ var KNOWN_SCHEMA_VERSIONS = [1, 2];
6052
6055
  function metaOf(obj) {
6053
6056
  if (obj === null || typeof obj !== "object")
6054
6057
  return null;
@@ -6071,11 +6074,61 @@ function recordIdentity(obj) {
6071
6074
  }
6072
6075
  return null;
6073
6076
  }
6074
-
6075
- // ../../packages/aeg-core/src/log/artifact.ts
6076
- var TASK_LOG_ARTIFACT_MAX_BYTES = 8 * 1024 * 1024;
6077
- // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
6078
- var STOPPED_CONDITIONS = new Set(["confidence", "reappearance", "no_progress", "max_rounds"]);
6077
+ function schemaVersionOf(obj) {
6078
+ const meta = metaOf(obj);
6079
+ const schema = meta?.schema;
6080
+ return typeof schema === "number" ? schema : null;
6081
+ }
6082
+ function isKnownSchema(version) {
6083
+ return version !== null && KNOWN_SCHEMA_VERSIONS.includes(version);
6084
+ }
6085
+ function classifyStoredLine(raw, home) {
6086
+ let obj;
6087
+ try {
6088
+ obj = JSON.parse(raw);
6089
+ } catch {
6090
+ return { status: "invalid", identity: null, raw, reason: "not valid JSON" };
6091
+ }
6092
+ const version = schemaVersionOf(obj);
6093
+ if (version === null) {
6094
+ return { status: "invalid", identity: recordIdentity(obj), raw, reason: "no readable meta.schema" };
6095
+ }
6096
+ if (!isKnownSchema(version)) {
6097
+ return {
6098
+ status: "unknown_version",
6099
+ identity: recordIdentity(obj),
6100
+ schema: version,
6101
+ raw,
6102
+ reason: `schema version ${version} is not one this build validates (${KNOWN_SCHEMA_VERSIONS.join(", ")}) — kept for diagnosis`
6103
+ };
6104
+ }
6105
+ const result = LogEventSchema.safeParse(obj);
6106
+ if (!result.success) {
6107
+ return {
6108
+ status: "invalid",
6109
+ identity: recordIdentity(obj),
6110
+ raw,
6111
+ reason: result.error.issues[0]?.message ?? "schema violation"
6112
+ };
6113
+ }
6114
+ const event = result.data;
6115
+ const identity = recordIdentity(event);
6116
+ if (identity === null) {
6117
+ return { status: "invalid", identity: null, raw, reason: "valid event with no derivable identity" };
6118
+ }
6119
+ const redacted = redact(event, home);
6120
+ const provenance = version === 2 ? event.meta.provenance ?? null : null;
6121
+ return {
6122
+ status: "ok",
6123
+ identity,
6124
+ runId: event.meta.run_id,
6125
+ seq: event.meta.seq,
6126
+ schema: version,
6127
+ provenance,
6128
+ event,
6129
+ postLine: JSON.stringify(redacted)
6130
+ };
6131
+ }
6079
6132
  // ../../packages/aeg-core/src/control-store/records.ts
6080
6133
  import { z as z3 } from "zod";
6081
6134
  var isoTimestamp = z3.string().min(1);
@@ -6206,7 +6259,8 @@ var ResolutionRecordSchema = z3.object({
6206
6259
  consumedAt: isoTimestamp
6207
6260
  }).strict();
6208
6261
  // src/lib/config.ts
6209
- import { execFileSync as execFileSync2 } from "node:child_process";
6262
+ import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6263
+ import { promisify as promisify4 } from "node:util";
6210
6264
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6211
6265
  import { homedir } from "node:os";
6212
6266
  import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -6233,10 +6287,10 @@ var CheckEntrySchema = z4.object({
6233
6287
  ownWorkflow: z4.boolean().optional(),
6234
6288
  principalOwed: z4.literal(true).optional(),
6235
6289
  validates: z4.enum(["body", "issue"]).optional()
6236
- }).superRefine((entry2, ctx) => {
6237
- if (!entry2.env)
6290
+ }).superRefine((entry, ctx) => {
6291
+ if (!entry.env)
6238
6292
  return;
6239
- for (const [key, value] of Object.entries(entry2.env)) {
6293
+ for (const [key, value] of Object.entries(entry.env)) {
6240
6294
  if (typeof value !== "object" || value === null || !("anyOf" in value))
6241
6295
  continue;
6242
6296
  const members = value.anyOf;
@@ -6393,18 +6447,19 @@ var VinayaConfigSchema = z4.object({
6393
6447
  });
6394
6448
  }
6395
6449
  }).optional(),
6396
- logPublish: z4.object({
6397
- issue: z4.number().int().positive().optional(),
6398
- pr: z4.number().int().positive().optional(),
6399
- webhookUrl: z4.string().url().optional(),
6400
- headers: z4.record(z4.string()).optional(),
6401
- maxChunksPerFlush: z4.number().int().positive().optional()
6402
- }).refine((v) => [v.issue, v.pr, v.webhookUrl].filter((x) => x !== undefined).length <= 1, {
6403
- message: "logPublish: set at most one of issue/pr/webhookUrl"
6404
- }).refine((v) => v.headers === undefined || v.webhookUrl !== undefined, {
6405
- message: "logPublish: headers requires webhookUrl"
6406
- }).optional(),
6407
- runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional()
6450
+ logPublish: z4.unknown().refine((v) => v === undefined, {
6451
+ message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
6452
+ }),
6453
+ runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
6454
+ logs: z4.object({
6455
+ folder: z4.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
6456
+ url: z4.string().url().optional(),
6457
+ headers: z4.record(z4.string()).optional()
6458
+ }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
6459
+ message: "logs: set at most one of folder/url"
6460
+ }).refine((v) => v.headers === undefined || v.url !== undefined, {
6461
+ message: "logs: headers requires url"
6462
+ }).optional()
6408
6463
  });
6409
6464
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
6410
6465
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
@@ -6449,32 +6504,39 @@ function globalTokensCollectIgnoredWarning(path) {
6449
6504
  function globalRuntimeDirIgnoredWarning(path) {
6450
6505
  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.`;
6451
6506
  }
6507
+ var emittedGlobalKeyWarnings = new Set;
6508
+ function warnGlobalKeyIgnoredOnce(message) {
6509
+ if (emittedGlobalKeyWarnings.has(message))
6510
+ return;
6511
+ emittedGlobalKeyWarnings.add(message);
6512
+ console.error(`⚠ ${message}`);
6513
+ }
6452
6514
  function stripGlobalOnlyKeys(config, path) {
6453
6515
  if (path !== GLOBAL_CONFIG_PATH)
6454
6516
  return config;
6455
6517
  let result = config;
6456
6518
  if (result.checks && Object.keys(result.checks).length > 0) {
6457
- console.error(`⚠ ${globalChecksIgnoredWarning(path)}`);
6519
+ warnGlobalKeyIgnoredOnce(globalChecksIgnoredWarning(path));
6458
6520
  result = { ...result, checks: undefined };
6459
6521
  }
6460
6522
  if (result.roles && Object.keys(result.roles).length > 0) {
6461
- console.error(`⚠ ${globalRolesIgnoredWarning(path)}`);
6523
+ warnGlobalKeyIgnoredOnce(globalRolesIgnoredWarning(path));
6462
6524
  result = { ...result, roles: undefined };
6463
6525
  }
6464
6526
  if (result.principals && result.principals.length > 0) {
6465
- console.error(`⚠ ${globalPrincipalsIgnoredWarning(path)}`);
6527
+ warnGlobalKeyIgnoredOnce(globalPrincipalsIgnoredWarning(path));
6466
6528
  result = { ...result, principals: undefined };
6467
6529
  }
6468
6530
  if (result.releaseActor) {
6469
- console.error(`⚠ ${globalReleaseActorIgnoredWarning(path)}`);
6531
+ warnGlobalKeyIgnoredOnce(globalReleaseActorIgnoredWarning(path));
6470
6532
  result = { ...result, releaseActor: undefined };
6471
6533
  }
6472
6534
  if (result.tokens) {
6473
- console.error(`⚠ ${globalTokensCollectIgnoredWarning(path)}`);
6535
+ warnGlobalKeyIgnoredOnce(globalTokensCollectIgnoredWarning(path));
6474
6536
  result = { ...result, tokens: undefined };
6475
6537
  }
6476
6538
  if (result.runtimeDir) {
6477
- console.error(`⚠ ${globalRuntimeDirIgnoredWarning(path)}`);
6539
+ warnGlobalKeyIgnoredOnce(globalRuntimeDirIgnoredWarning(path));
6478
6540
  result = { ...result, runtimeDir: undefined };
6479
6541
  }
6480
6542
  return result;
@@ -6507,25 +6569,80 @@ function resolveReviewPolicy(config) {
6507
6569
  maxRounds
6508
6570
  };
6509
6571
  }
6510
- function trustAnchorRepo() {
6511
- const wellFormed = (slug) => /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
6512
- const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
6513
- if (fromRunner) {
6514
- const validated = wellFormed(fromRunner);
6515
- if (validated)
6516
- return validated;
6572
+ function resolveRuntimeDirSetting(config) {
6573
+ return config?.runtimeDir ?? null;
6574
+ }
6575
+ function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
6576
+ const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
6577
+ return anchored !== null && anchored === localRuntimeDir ? anchored : null;
6578
+ }
6579
+ function resolveLogsSetting(config) {
6580
+ const raw = config?.logs;
6581
+ if (!raw)
6582
+ return null;
6583
+ if (raw.url !== undefined)
6584
+ return { url: raw.url, headers: raw.headers };
6585
+ if (raw.folder !== undefined)
6586
+ return { folder: raw.folder };
6587
+ return null;
6588
+ }
6589
+ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
6590
+ const anchored = resolveLogsSetting(trustAnchorConfig);
6591
+ if (!anchored)
6592
+ return null;
6593
+ if ("url" in local)
6594
+ return "url" in anchored && anchored.url === local.url ? anchored : null;
6595
+ return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
6596
+ }
6597
+ function resolveLogsHeaderValues(headers, env) {
6598
+ if (!headers)
6599
+ return;
6600
+ const resolved = {};
6601
+ for (const [key, value] of Object.entries(headers)) {
6602
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
6517
6603
  }
6604
+ return resolved;
6605
+ }
6606
+ function trustAnchorRepo() {
6607
+ const fromRunner = trustAnchorRepoFromRunner();
6608
+ if (fromRunner)
6609
+ return fromRunner;
6518
6610
  try {
6519
6611
  const url = execFileSync2("git", ["remote", "get-url", "origin"], {
6520
6612
  encoding: "utf-8",
6521
6613
  stdio: ["ignore", "pipe", "pipe"]
6522
- }).trim();
6523
- const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
6524
- return m?.[1] && m[2] ? wellFormed(`${m[1]}/${m[2]}`) : null;
6614
+ });
6615
+ return trustAnchorRepoFromRemoteUrl(url);
6616
+ } catch {
6617
+ return null;
6618
+ }
6619
+ }
6620
+ async function trustAnchorRepoAsync() {
6621
+ const fromRunner = trustAnchorRepoFromRunner();
6622
+ if (fromRunner)
6623
+ return fromRunner;
6624
+ try {
6625
+ const { stdout } = await execFileAsync4("git", ["remote", "get-url", "origin"], {
6626
+ encoding: "utf-8",
6627
+ timeout: 1e4
6628
+ });
6629
+ return trustAnchorRepoFromRemoteUrl(stdout);
6525
6630
  } catch {
6526
6631
  return null;
6527
6632
  }
6528
6633
  }
6634
+ function wellFormedRepoSlug(slug) {
6635
+ return /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
6636
+ }
6637
+ function trustAnchorRepoFromRunner() {
6638
+ const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
6639
+ return fromRunner ? wellFormedRepoSlug(fromRunner) : null;
6640
+ }
6641
+ function trustAnchorRepoFromRemoteUrl(url) {
6642
+ const m = url.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
6643
+ return m?.[1] && m[2] ? wellFormedRepoSlug(`${m[1]}/${m[2]}`) : null;
6644
+ }
6645
+ var execFileAsync4 = promisify4(execFile4);
6529
6646
  function ghFetchTrustAnchorConfig() {
6530
6647
  const repo = trustAnchorRepo();
6531
6648
  if (!repo)
@@ -6535,6 +6652,13 @@ function ghFetchTrustAnchorConfig() {
6535
6652
  stdio: ["ignore", "pipe", "pipe"]
6536
6653
  });
6537
6654
  }
6655
+ async function ghFetchTrustAnchorConfigAsync() {
6656
+ const repo = await trustAnchorRepoAsync();
6657
+ if (!repo)
6658
+ throw new Error("could not resolve repo identity for the trust-anchor read");
6659
+ const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4 });
6660
+ return stdout;
6661
+ }
6538
6662
  function firstLine(err) {
6539
6663
  return err?.message?.split(`
6540
6664
  `)[0] ?? "unknown error";
@@ -6549,16 +6673,35 @@ function isMissingFileError(err) {
6549
6673
  return /\b404\b|not found/i.test(haystack);
6550
6674
  }
6551
6675
  function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
6552
- 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.
6553
- `);
6554
6676
  let base64;
6555
6677
  try {
6556
- base64 = fetcher().trim();
6678
+ base64 = fetcher();
6557
6679
  } catch (err) {
6558
- if (!isMissingFileError(err))
6559
- warn(firstLine(err));
6560
- return null;
6680
+ return trustAnchorFetchFailed(err);
6561
6681
  }
6682
+ return parseTrustAnchorContent(base64);
6683
+ }
6684
+ async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
6685
+ const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
6686
+ let base64;
6687
+ try {
6688
+ base64 = await fetcher();
6689
+ } catch (err) {
6690
+ return trustAnchorFetchFailed(err, warn);
6691
+ }
6692
+ return parseTrustAnchorContent(base64, warn);
6693
+ }
6694
+ function warnTrustAnchorFallback(why) {
6695
+ 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.
6696
+ `);
6697
+ }
6698
+ function trustAnchorFetchFailed(err, warn = warnTrustAnchorFallback) {
6699
+ if (!isMissingFileError(err))
6700
+ warn(firstLine(err));
6701
+ return null;
6702
+ }
6703
+ function parseTrustAnchorContent(content, warn = warnTrustAnchorFallback) {
6704
+ const base64 = content.trim();
6562
6705
  if (!base64)
6563
6706
  return null;
6564
6707
  try {
@@ -6588,6 +6731,8 @@ var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.j
6588
6731
 
6589
6732
  // src/lib/brief-assembly.ts
6590
6733
  import { execFileSync as execFileSync4 } from "node:child_process";
6734
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "node:fs";
6735
+ import { join as join3 } from "node:path";
6591
6736
 
6592
6737
  // ../../packages/sources/src/commands.ts
6593
6738
  var COMMANDS = [
@@ -6740,10 +6885,10 @@ var COMMANDS = [
6740
6885
  }
6741
6886
  ],
6742
6887
  details: [
6743
- "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.",
6888
+ "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.",
6744
6889
  "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.",
6745
- "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.",
6746
- "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."
6890
+ "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.",
6891
+ "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`)."
6747
6892
  ],
6748
6893
  status: "shipped"
6749
6894
  },
@@ -6912,48 +7057,6 @@ var COMMANDS = [
6912
7057
  ],
6913
7058
  status: "shipped"
6914
7059
  },
6915
- {
6916
- name: "log flush",
6917
- description: "Post a target Issue or PR's outbox as one or more marked comments, then truncate what the forge confirmed",
6918
- flags: [
6919
- { flag: "--issue", description: "Flush this Issue's outbox (`~/.vinaya/outbox/<owner>-<repo>/<n>.ndjson`)" },
6920
- {
6921
- flag: "--pr",
6922
- description: "Flush the Issue named by this PR's `Closes #N` line, posting the comments on the PR"
6923
- },
6924
- { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
6925
- ],
6926
- details: [
6927
- "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.",
6928
- "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.",
6929
- "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."
6930
- ],
6931
- status: "shipped"
6932
- },
6933
- {
6934
- name: "log export-artifact",
6935
- description: "Copy this run's own local outbox into a file, for the generated task-path workflow's own upload step",
6936
- flags: [],
6937
- details: [
6938
- "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.",
6939
- "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."
6940
- ],
6941
- status: "shipped"
6942
- },
6943
- {
6944
- name: "log collect-artifact",
6945
- description: "Validate a downloaded task-log artifact and publish the valid records through the existing flush path",
6946
- flags: [
6947
- { flag: "--pr", description: "The pull request this artifact belongs to" },
6948
- { flag: "--repo", description: "Expected `owner/repo` — a provenance cross-check against each record" }
6949
- ],
6950
- details: [
6951
- "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.",
6952
- "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.",
6953
- "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."
6954
- ],
6955
- status: "shipped"
6956
- },
6957
7060
  {
6958
7061
  name: "milestone create",
6959
7062
  description: "Create a GitHub Milestone from a validated body",
@@ -7283,7 +7386,7 @@ var COMMANDS = [
7283
7386
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
7284
7387
  {
7285
7388
  flag: "--pr",
7286
- description: "Flush the outbox to this PR's Issue after the dispatch — mutually exclusive with `--task`"
7389
+ description: "This dispatch's pull request number, for attribution — mutually exclusive with `--task`"
7287
7390
  },
7288
7391
  { flag: "--round", description: "Round number, for a dispatch inside a review loop" },
7289
7392
  {
@@ -7295,7 +7398,7 @@ var COMMANDS = [
7295
7398
  details: [
7296
7399
  "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.",
7297
7400
  "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`.",
7298
- "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.",
7401
+ "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.",
7299
7402
  "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."
7300
7403
  ],
7301
7404
  status: "shipped"
@@ -7315,7 +7418,8 @@ var COMMANDS = [
7315
7418
  "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> -->`.",
7316
7419
  "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.",
7317
7420
  "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.",
7318
- "Every dispatch and round transition is a log line through the Vinaya Log, flushed to the forge at each round boundary."
7421
+ "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.",
7422
+ "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)."
7319
7423
  ],
7320
7424
  status: "shipped"
7321
7425
  }
@@ -7452,25 +7556,6 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
7452
7556
  };
7453
7557
  }
7454
7558
 
7455
- // src/lib/brief-assembly.ts
7456
- function git(args) {
7457
- try {
7458
- return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7459
- } catch {
7460
- return "";
7461
- }
7462
- }
7463
- function expandGlob(glob) {
7464
- const out = git(["ls-files", "--", glob]);
7465
- return out.split(`
7466
- `).map((s) => s.trim()).filter(Boolean);
7467
- }
7468
- var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
7469
-
7470
- // src/checks/registry.ts
7471
- import { existsSync as existsSync3 } from "node:fs";
7472
- import { join as join3 } from "node:path";
7473
-
7474
7559
  // src/lib/package-root.ts
7475
7560
  import { existsSync as existsSync2 } from "node:fs";
7476
7561
  import { dirname as dirname2, join as join2 } from "node:path";
@@ -7488,13 +7573,33 @@ function packageRoot(moduleUrl) {
7488
7573
  return dir;
7489
7574
  }
7490
7575
 
7576
+ // src/lib/brief-assembly.ts
7577
+ var PACKAGE_ROOT = packageRoot(import.meta.url);
7578
+ var PACKAGED_TEMPLATE_PATH = join3(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
7579
+ var TEMPLATE_PATH = existsSync3(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join3(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
7580
+ function git(args) {
7581
+ try {
7582
+ return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7583
+ } catch {
7584
+ return "";
7585
+ }
7586
+ }
7587
+ function expandGlob(glob) {
7588
+ const out = git(["ls-files", "--", glob]);
7589
+ return out.split(`
7590
+ `).map((s) => s.trim()).filter(Boolean);
7591
+ }
7592
+ var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
7593
+
7491
7594
  // src/checks/registry.ts
7492
- var DIST_BIN_DIR = join3(packageRoot(import.meta.url), "dist", "checks", "bin");
7493
- var SRC_BIN_DIR = join3(packageRoot(import.meta.url), "src", "checks", "bin");
7494
- var BIN_DIR = existsSync3(DIST_BIN_DIR) ? DIST_BIN_DIR : SRC_BIN_DIR;
7595
+ import { existsSync as existsSync4 } from "node:fs";
7596
+ import { join as join4 } from "node:path";
7597
+ var DIST_BIN_DIR = join4(packageRoot(import.meta.url), "dist", "checks", "bin");
7598
+ var SRC_BIN_DIR = join4(packageRoot(import.meta.url), "src", "checks", "bin");
7599
+ var BIN_DIR = existsSync4(DIST_BIN_DIR) ? DIST_BIN_DIR : SRC_BIN_DIR;
7495
7600
  var BIN_EXT = BIN_DIR === DIST_BIN_DIR ? ".js" : ".ts";
7496
7601
  function bin(name) {
7497
- return join3(BIN_DIR, `${name}${BIN_EXT}`);
7602
+ return join4(BIN_DIR, `${name}${BIN_EXT}`);
7498
7603
  }
7499
7604
  var REGISTRY = [
7500
7605
  [
@@ -7906,6 +8011,16 @@ var REGISTRY = [
7906
8011
  },
7907
8012
  0
7908
8013
  ],
8014
+ [
8015
+ {
8016
+ name: "ci-shard-coverage",
8017
+ run: bin("check-ci-shard-coverage"),
8018
+ scope: "diff",
8019
+ timeoutMs: 15000,
8020
+ env: {}
8021
+ },
8022
+ 0
8023
+ ],
7909
8024
  [
7910
8025
  {
7911
8026
  name: "workspace-escape",
@@ -8043,42 +8158,382 @@ function coreCheckRegistry() {
8043
8158
  var CORE_CHECK_RING = Object.fromEntries(REGISTRY.map(([spec, ring]) => [spec.name, ring]));
8044
8159
 
8045
8160
  // src/lib/log-sink.ts
8046
- import { execFileSync as execFileSync5 } from "node:child_process";
8047
- import { randomUUID } from "node:crypto";
8161
+ import { execFile as execFile5 } from "node:child_process";
8162
+ import { randomUUID as randomUUID2 } from "node:crypto";
8163
+ import {
8164
+ closeSync as closeSync3,
8165
+ constants as fsConstants3,
8166
+ existsSync as existsSync6,
8167
+ fstatSync as fstatSync2,
8168
+ mkdirSync as mkdirSync3,
8169
+ openSync as openSync3,
8170
+ readFileSync as readFileSync5,
8171
+ renameSync as renameSync2,
8172
+ writeSync as writeSync2
8173
+ } from "node:fs";
8174
+ import { hostname as osHostname, homedir as homedir3 } from "node:os";
8175
+ import { dirname as dirname5, join as join7 } from "node:path";
8176
+ import { promisify as promisify5 } from "node:util";
8177
+
8178
+ // src/lib/run-paths.ts
8179
+ import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync2 } from "node:fs";
8180
+ import { dirname as dirname3, join as join5, resolve as resolvePath } from "node:path";
8181
+ var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8182
+ function isSafeRepoSegment(segment) {
8183
+ return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
8184
+ }
8185
+ function repoSegment(repo) {
8186
+ if (!repo || !isSafeRepoSegment(repo.owner) || !isSafeRepoSegment(repo.repo))
8187
+ return "unresolved";
8188
+ return `${repo.owner}-${repo.repo}`;
8189
+ }
8190
+ function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
8191
+ return join5(home, "runtime", repoSegment(repo));
8192
+ }
8193
+ function resolveRuntimeDir(input) {
8194
+ const local = resolveRuntimeDirSetting(input.localConfig);
8195
+ if (local === null)
8196
+ return defaultRuntimeDir(input.repo, input.home);
8197
+ if (isInsideRepo(local, input.repoRoot))
8198
+ return defaultRuntimeDir(input.repo, input.home);
8199
+ if (!input.unattended)
8200
+ return local;
8201
+ const anchored = resolveTrustAnchorRuntimeDir(local, input.trustAnchorConfig ?? null);
8202
+ return anchored ?? defaultRuntimeDir(input.repo, input.home);
8203
+ }
8204
+ function isInsideRepo(candidate, repoRoot) {
8205
+ if (!repoRoot)
8206
+ return false;
8207
+ const root = resolvePath(repoRoot);
8208
+ const target = resolvePath(candidate);
8209
+ return target === root || target.startsWith(`${root}/`);
8210
+ }
8211
+ var UNATTENDED_ENV_KEY = "VINAYA_UNATTENDED";
8212
+ var RUNTIME_DIR_ENV_KEY = "VINAYA_RUNTIME_DIR";
8213
+ function isUnattendedProcess(env = process.env) {
8214
+ return env[UNATTENDED_ENV_KEY] === "1" || (env.VINAYA_ROLE ?? "") !== "";
8215
+ }
8216
+ var memoized = null;
8217
+ async function runtimeDirForRepoAsync(repo) {
8218
+ const key = repoSegment(repo);
8219
+ if (memoized?.key === key)
8220
+ return memoized.value;
8221
+ const inputs = runtimeDirInputs();
8222
+ if (typeof inputs === "string")
8223
+ return inputs;
8224
+ const value = resolveRuntimeDir({
8225
+ repo,
8226
+ ...inputs.base,
8227
+ trustAnchorConfig: inputs.needsAnchor ? await loadTrustAnchorConfigAsync() : null
8228
+ });
8229
+ memoized = { key, value };
8230
+ return value;
8231
+ }
8232
+ function runtimeDirInputs() {
8233
+ const handedDown = process.env[RUNTIME_DIR_ENV_KEY];
8234
+ if (handedDown)
8235
+ return handedDown;
8236
+ const localConfig = loadConfig();
8237
+ const unattended = isUnattendedProcess();
8238
+ return {
8239
+ base: { localConfig, unattended, repoRoot: repoRootSync() },
8240
+ needsAnchor: unattended && resolveRuntimeDirSetting(localConfig) !== null
8241
+ };
8242
+ }
8243
+ function repoRootSync(start = process.cwd()) {
8244
+ let dir;
8245
+ try {
8246
+ dir = realpathSync2(start);
8247
+ } catch {
8248
+ return null;
8249
+ }
8250
+ for (;; ) {
8251
+ if (existsSync5(join5(dir, ".git")))
8252
+ return dir;
8253
+ const parent = dirname3(dir);
8254
+ if (parent === dir)
8255
+ return null;
8256
+ dir = parent;
8257
+ }
8258
+ }
8259
+
8260
+ // src/lib/log-webhook-drain.ts
8048
8261
  import {
8049
8262
  closeSync as closeSync2,
8050
8263
  constants as fsConstants2,
8051
- existsSync as existsSync4,
8052
- fstatSync as fstatSync2,
8264
+ lstatSync,
8053
8265
  mkdirSync as mkdirSync2,
8054
8266
  openSync as openSync2,
8055
- readFileSync as readFileSync3,
8267
+ linkSync,
8268
+ readFileSync as readFileSync4,
8056
8269
  renameSync,
8270
+ statSync,
8271
+ unlinkSync,
8272
+ writeFileSync as writeFileSync2,
8057
8273
  writeSync
8058
8274
  } from "node:fs";
8059
- import { hostname as osHostname, homedir as homedir2 } from "node:os";
8060
- import { dirname as dirname3, join as join4 } from "node:path";
8061
- var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8275
+ import { randomUUID } from "node:crypto";
8276
+ import { homedir as homedir2 } from "node:os";
8277
+ import { dirname as dirname4, join as join6 } from "node:path";
8278
+ var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
8279
+ var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
8280
+ var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8281
+ function isSafeRepoSegment2(segment) {
8282
+ return SAFE_PATH_SEGMENT2.test(segment) && !segment.includes("..");
8283
+ }
8284
+ function isErrnoCode(err, code) {
8285
+ return typeof err === "object" && err !== null && err.code === code;
8286
+ }
8062
8287
  function isEnoent(err) {
8288
+ return isErrnoCode(err, "ENOENT");
8289
+ }
8290
+ var WEBHOOK_DRAIN_LOCK_STALE_MS = 4 * WEBHOOK_FETCH_TIMEOUT_MS;
8291
+ function tryCreateLock(lockPath, token) {
8292
+ try {
8293
+ mkdirSync2(dirname4(lockPath), { recursive: true, mode: 448 });
8294
+ const fd = openSync2(lockPath, fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL, 384);
8295
+ try {
8296
+ writeSync(fd, `${token}
8297
+ `);
8298
+ } finally {
8299
+ closeSync2(fd);
8300
+ }
8301
+ return true;
8302
+ } catch (err) {
8303
+ if (isErrnoCode(err, "EEXIST"))
8304
+ return false;
8305
+ throw err;
8306
+ }
8307
+ }
8308
+ function acquireDrainLock(lockPath) {
8309
+ const token = `${process.pid}:${randomUUID()}`;
8310
+ if (tryCreateLock(lockPath, token))
8311
+ return token;
8312
+ let observedMtimeMs;
8313
+ try {
8314
+ observedMtimeMs = statSync(lockPath).mtimeMs;
8315
+ } catch (err) {
8316
+ if (!isEnoent(err))
8317
+ throw err;
8318
+ return tryCreateLock(lockPath, token) ? token : null;
8319
+ }
8320
+ if (Date.now() - observedMtimeMs <= WEBHOOK_DRAIN_LOCK_STALE_MS)
8321
+ return null;
8322
+ const claimed = `${lockPath}.claimed-${randomUUID()}`;
8323
+ try {
8324
+ renameSync(lockPath, claimed);
8325
+ } catch (err) {
8326
+ if (isEnoent(err))
8327
+ return null;
8328
+ throw err;
8329
+ }
8330
+ let claimedMtimeMs = null;
8331
+ try {
8332
+ claimedMtimeMs = statSync(claimed).mtimeMs;
8333
+ } catch (err) {
8334
+ if (!isEnoent(err))
8335
+ throw err;
8336
+ }
8337
+ if (claimedMtimeMs !== observedMtimeMs) {
8338
+ try {
8339
+ linkSync(claimed, lockPath);
8340
+ } catch (err) {
8341
+ if (!isErrnoCode(err, "EEXIST"))
8342
+ throw err;
8343
+ }
8344
+ try {
8345
+ unlinkSync(claimed);
8346
+ } catch (err) {
8347
+ if (!isEnoent(err))
8348
+ throw err;
8349
+ }
8350
+ return null;
8351
+ }
8352
+ unlinkSync(claimed);
8353
+ return tryCreateLock(lockPath, token) ? token : null;
8354
+ }
8355
+ function releaseDrainLock(lockPath, token) {
8356
+ try {
8357
+ const holder = readFileSync4(lockPath, "utf8").trim();
8358
+ if (holder !== token)
8359
+ return;
8360
+ unlinkSync(lockPath);
8361
+ } catch (err) {
8362
+ if (!isEnoent(err))
8363
+ throw err;
8364
+ }
8365
+ }
8366
+
8367
+ class WebhookDrainError extends Error {
8368
+ code;
8369
+ constructor(code, message) {
8370
+ super(message);
8371
+ this.code = code;
8372
+ }
8373
+ }
8374
+ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
8375
+ const resolved = await resolveRepo();
8376
+ const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
8377
+ const outboxRoot = () => join6(GLOBAL_VINAYA_HOME, "outbox");
8378
+ const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
8379
+ const lockPath = `${path}.flush-lock`;
8380
+ const lockToken = acquireDrainLock(lockPath);
8381
+ if (lockToken === null)
8382
+ return { flushed: false };
8383
+ try {
8384
+ let lstat;
8385
+ try {
8386
+ lstat = lstatSync(path);
8387
+ } catch (err) {
8388
+ if (!isEnoent(err))
8389
+ throw err;
8390
+ }
8391
+ if (lstat === undefined)
8392
+ return { flushed: false };
8393
+ if (!lstat.isFile()) {
8394
+ 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}`);
8395
+ }
8396
+ const buf = readFileSync4(path);
8397
+ const startOffset = buf.byteLength;
8398
+ const rawLines = buf.toString("utf8").split(`
8399
+ `).filter((l) => l.length > 0);
8400
+ if (rawLines.length === 0)
8401
+ return { flushed: false };
8402
+ const postLines = [];
8403
+ for (let i = 0;i < rawLines.length; i++) {
8404
+ const record = classifyStoredLine(rawLines[i], homedir2());
8405
+ if (record.status !== "ok") {
8406
+ throw new WebhookDrainError("log-webhook-drain-corrupt-line", `log webhook drain: outbox line ${i} failed schema re-validation — ${record.reason}`);
8407
+ }
8408
+ postLines.push(record.postLine);
8409
+ }
8410
+ const body = `${postLines.join(`
8411
+ `)}
8412
+ `;
8413
+ const bytes = Buffer.byteLength(body, "utf8");
8414
+ if (bytes > MAX_WEBHOOK_BODY_BYTES) {
8415
+ 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.`);
8416
+ }
8417
+ let response;
8418
+ try {
8419
+ response = await fetch(webhookUrl, {
8420
+ method: "POST",
8421
+ headers: { "content-type": "application/x-ndjson", ...headers },
8422
+ body,
8423
+ signal: AbortSignal.timeout(fetchTimeoutMs)
8424
+ });
8425
+ } catch (err) {
8426
+ const reason = err instanceof Error && err.name === "TimeoutError" ? `timed out after ${fetchTimeoutMs}ms` : err instanceof Error ? err.message : String(err);
8427
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} failed: ${reason}`);
8428
+ }
8429
+ if (!response.ok) {
8430
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} returned ${response.status} ${response.statusText}`);
8431
+ }
8432
+ const liveNow = readFileSync4(path);
8433
+ const tail = liveNow.subarray(Math.min(startOffset, liveNow.byteLength));
8434
+ writeFileSync2(path, tail);
8435
+ return { flushed: true, lineCount: postLines.length, bytes };
8436
+ } finally {
8437
+ releaseDrainLock(lockPath, lockToken);
8438
+ }
8439
+ }
8440
+
8441
+ // src/lib/log-sink.ts
8442
+ var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8443
+ var LOG_CONTEXT_LOOKUP_DEADLINE_MS = 3000;
8444
+ function withDeadline(work, ms, fallback) {
8445
+ return new Promise((resolve) => {
8446
+ const timer = setTimeout(() => resolve(fallback), ms);
8447
+ timer.unref?.();
8448
+ work.then((value) => {
8449
+ clearTimeout(timer);
8450
+ resolve(value);
8451
+ }, () => {
8452
+ clearTimeout(timer);
8453
+ resolve(fallback);
8454
+ });
8455
+ });
8456
+ }
8457
+ async function safeLoadTrustAnchorConfig() {
8458
+ return withDeadline(loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
8459
+ }
8460
+ function logsCredentialMissing(headers, env) {
8461
+ if (!headers)
8462
+ return false;
8463
+ const varPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
8464
+ for (const value of Object.values(headers)) {
8465
+ for (const match of value.matchAll(varPattern)) {
8466
+ if (!env[match[1]])
8467
+ return true;
8468
+ }
8469
+ }
8470
+ return false;
8471
+ }
8472
+ function resolveLogDestinationFrom(input) {
8473
+ const local = resolveLogsSetting(input.localConfig);
8474
+ let effective = null;
8475
+ if (input.unattended) {
8476
+ effective = local ? resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig) : resolveLogsSetting(input.trustAnchorConfig);
8477
+ } else {
8478
+ effective = local;
8479
+ }
8480
+ if (hostFromEnv(input.env) === "ci") {
8481
+ if (effective && "url" in effective) {
8482
+ if (logsCredentialMissing(effective.headers, input.env)) {
8483
+ return {
8484
+ kind: "none",
8485
+ reason: "a logs.url server destination is configured, but this job holds no delivery credential (a fork pull request, or a missing repository secret)"
8486
+ };
8487
+ }
8488
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
8489
+ }
8490
+ return {
8491
+ kind: "none",
8492
+ reason: "no server destination is configured for CI delivery (vinaya.config.json logs.url)"
8493
+ };
8494
+ }
8495
+ if (effective && "url" in effective) {
8496
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
8497
+ }
8498
+ if (effective && "folder" in effective && isInsideRepo(effective.folder, input.repoRoot)) {
8499
+ effective = null;
8500
+ }
8501
+ const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
8502
+ return { kind: "folder", folder };
8503
+ }
8504
+ var processTrustAnchorOnce;
8505
+ function processTrustAnchor() {
8506
+ if (processTrustAnchorOnce === undefined)
8507
+ processTrustAnchorOnce = safeLoadTrustAnchorConfig();
8508
+ return processTrustAnchorOnce;
8509
+ }
8510
+ async function defaultResolveLogDestination(repo, env) {
8511
+ const localConfig = loadConfig();
8512
+ const unattended = isUnattendedProcess(process.env);
8513
+ return resolveLogDestinationFrom({
8514
+ localConfig,
8515
+ trustAnchorConfig: unattended ? await processTrustAnchor() : null,
8516
+ unattended,
8517
+ env,
8518
+ defaultFolder: join7(await runtimeDirForRepoAsync(repo), "logs"),
8519
+ repoRoot: repoRootSync()
8520
+ });
8521
+ }
8522
+ function isEnoent2(err) {
8063
8523
  return typeof err === "object" && err !== null && err.code === "ENOENT";
8064
8524
  }
8065
- function resolveDoctrine(cwd, vinayaVersion) {
8525
+ var execFileAsync5 = promisify5(execFile5);
8526
+ async function resolveDoctrine(cwd, vinayaVersion) {
8066
8527
  let toplevel;
8067
8528
  try {
8068
- toplevel = execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
8069
- encoding: "utf8",
8070
- stdio: ["ignore", "pipe", "pipe"]
8071
- }).trim();
8529
+ toplevel = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
8072
8530
  } catch (err) {
8073
- return isEnoent(err) ? "unknown" : vinayaVersion;
8531
+ return isEnoent2(err) ? "unknown" : vinayaVersion;
8074
8532
  }
8075
- if (!existsSync4(join4(toplevel, "aeg-root", "roles")))
8533
+ if (!existsSync6(join7(toplevel, "aeg-root", "roles")))
8076
8534
  return vinayaVersion;
8077
8535
  try {
8078
- const sha = execFileSync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], {
8079
- encoding: "utf8",
8080
- stdio: ["ignore", "pipe", "pipe"]
8081
- }).trim();
8536
+ const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
8082
8537
  return `aeg-root@${sha}`;
8083
8538
  } catch {
8084
8539
  return vinayaVersion;
@@ -8086,20 +8541,20 @@ function resolveDoctrine(cwd, vinayaVersion) {
8086
8541
  }
8087
8542
  function readVinayaVersion() {
8088
8543
  try {
8089
- const pkg = JSON.parse(readFileSync3(join4(packageRoot(import.meta.url), "package.json"), "utf8"));
8544
+ const pkg = JSON.parse(readFileSync5(join7(packageRoot(import.meta.url), "package.json"), "utf8"));
8090
8545
  return pkg.version ?? "unknown";
8091
8546
  } catch {
8092
8547
  return "unknown";
8093
8548
  }
8094
8549
  }
8095
- var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8096
- function isSafeRepoSegment(segment) {
8097
- return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
8550
+ var SAFE_PATH_SEGMENT3 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
8551
+ function isSafeRepoSegment3(segment) {
8552
+ return SAFE_PATH_SEGMENT3.test(segment) && !segment.includes("..");
8098
8553
  }
8099
8554
  function outboxPathFor(deps, repo, issue) {
8100
8555
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
8101
8556
  const fileName = `${issue ?? "none"}.ndjson`;
8102
- return join4(deps.outboxRoot(), dirName, fileName);
8557
+ return join7(deps.outboxRoot(), dirName, fileName);
8103
8558
  }
8104
8559
  function hostFromEnv(env) {
8105
8560
  if (env.GITHUB_ACTIONS)
@@ -8110,28 +8565,34 @@ function hostFromEnv(env) {
8110
8565
  return "loop";
8111
8566
  return "cli";
8112
8567
  }
8568
+ var warnedThisProcess = false;
8569
+ function defaultStderr(message) {
8570
+ if (warnedThisProcess)
8571
+ return;
8572
+ warnedThisProcess = true;
8573
+ process.stderr.write(message);
8574
+ }
8113
8575
  function defaultDeps() {
8114
8576
  return {
8115
- outboxRoot: () => join4(GLOBAL_VINAYA_HOME, "outbox"),
8116
- home: () => homedir2(),
8577
+ outboxRoot: () => join7(GLOBAL_VINAYA_HOME, "outbox"),
8578
+ home: () => homedir3(),
8117
8579
  hostname: () => osHostname(),
8118
8580
  cwd: () => process.cwd(),
8119
8581
  now: () => new Date,
8120
8582
  env: () => process.env,
8121
8583
  resolveRepo: () => resolveRepo(),
8122
8584
  vinayaVersion: () => readVinayaVersion(),
8123
- stderr: (message) => {
8124
- process.stderr.write(message);
8125
- },
8585
+ stderr: defaultStderr,
8126
8586
  inputVersions: () => {
8127
8587
  return;
8128
- }
8588
+ },
8589
+ resolveLogDestination: defaultResolveLogDestination
8129
8590
  };
8130
8591
  }
8131
- var APPEND_OPEN_FLAGS = fsConstants2.O_WRONLY | fsConstants2.O_APPEND | fsConstants2.O_CREAT | fsConstants2.O_NOFOLLOW | fsConstants2.O_NONBLOCK;
8592
+ var APPEND_OPEN_FLAGS = fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK;
8132
8593
  function guardedAppendOpen(path) {
8133
8594
  try {
8134
- return openSync2(path, APPEND_OPEN_FLAGS, 384);
8595
+ return openSync3(path, APPEND_OPEN_FLAGS, 384);
8135
8596
  } catch {
8136
8597
  return;
8137
8598
  }
@@ -8139,7 +8600,7 @@ function guardedAppendOpen(path) {
8139
8600
  function reportRotationOverflow(backupPath, warn) {
8140
8601
  let raw;
8141
8602
  try {
8142
- raw = readFileSync3(backupPath, "utf8");
8603
+ raw = readFileSync5(backupPath, "utf8");
8143
8604
  } catch {
8144
8605
  return;
8145
8606
  }
@@ -8162,7 +8623,7 @@ function reportRotationOverflow(backupPath, warn) {
8162
8623
  }
8163
8624
  function appendLine(path, line, warn) {
8164
8625
  try {
8165
- mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
8626
+ mkdirSync3(dirname5(path), { recursive: true, mode: 448 });
8166
8627
  let fd = guardedAppendOpen(path);
8167
8628
  if (fd === undefined) {
8168
8629
  warn(`vinaya: log outbox target could not be opened (symlink, FIFO, or unwritable) — refusing: ${path}
@@ -8178,11 +8639,11 @@ function appendLine(path, line, warn) {
8178
8639
  return;
8179
8640
  }
8180
8641
  if (stat.size > OUTBOX_MAX_BYTES) {
8181
- closeSync2(fd);
8642
+ closeSync3(fd);
8182
8643
  closed = true;
8183
8644
  const backupPath = path.replace(/\.ndjson$/, ".1.ndjson");
8184
8645
  reportRotationOverflow(backupPath, warn);
8185
- renameSync(path, backupPath);
8646
+ renameSync2(path, backupPath);
8186
8647
  const rotated = guardedAppendOpen(path);
8187
8648
  if (rotated === undefined) {
8188
8649
  warn(`vinaya: log outbox target could not be reopened after rotation — refusing: ${path}
@@ -8192,10 +8653,10 @@ function appendLine(path, line, warn) {
8192
8653
  fd = rotated;
8193
8654
  closed = false;
8194
8655
  }
8195
- writeSync(fd, line);
8656
+ writeSync2(fd, line);
8196
8657
  } finally {
8197
8658
  if (!closed)
8198
- closeSync2(fd);
8659
+ closeSync3(fd);
8199
8660
  }
8200
8661
  } catch (err) {
8201
8662
  warn(`vinaya: log outbox write failed — ${err instanceof Error ? err.message : String(err)}
@@ -8204,8 +8665,8 @@ function appendLine(path, line, warn) {
8204
8665
  }
8205
8666
  function createLogSink(overrides = {}) {
8206
8667
  const deps = { ...defaultDeps(), ...overrides };
8207
- const runId = deps.env().VINAYA_RUN_ID || randomUUID();
8208
- const processId = randomUUID();
8668
+ const runId = deps.env().VINAYA_RUN_ID || randomUUID2();
8669
+ const processId = randomUUID2();
8209
8670
  let seq = 0;
8210
8671
  let warned = false;
8211
8672
  const warnOnce = (message) => {
@@ -8218,8 +8679,9 @@ function createLogSink(overrides = {}) {
8218
8679
  };
8219
8680
  let doctrineCache;
8220
8681
  const doctrine = () => {
8221
- if (doctrineCache === undefined)
8222
- doctrineCache = resolveDoctrine(deps.cwd(), deps.vinayaVersion());
8682
+ if (doctrineCache === undefined) {
8683
+ doctrineCache = withDeadline(resolveDoctrine(deps.cwd(), deps.vinayaVersion()), LOG_CONTEXT_LOOKUP_DEADLINE_MS, deps.vinayaVersion());
8684
+ }
8223
8685
  return doctrineCache;
8224
8686
  };
8225
8687
  let resolveRepoCache;
@@ -8228,6 +8690,30 @@ function createLogSink(overrides = {}) {
8228
8690
  resolveRepoCache = deps.resolveRepo();
8229
8691
  return resolveRepoCache;
8230
8692
  };
8693
+ let contextCache;
8694
+ const context = () => {
8695
+ if (contextCache === undefined) {
8696
+ const env = deps.env();
8697
+ contextCache = Promise.all([
8698
+ withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
8699
+ doctrine()
8700
+ ]).then(async ([resolved, doctrineValue]) => {
8701
+ const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
8702
+ return { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
8703
+ });
8704
+ }
8705
+ return contextCache;
8706
+ };
8707
+ let drainChain = Promise.resolve();
8708
+ const pendingWrites = new Set;
8709
+ const scheduleWebhookDrain = (issue, url, headers) => {
8710
+ drainChain = drainChain.then(() => drainOutboxToWebhook(issue, url, headers)).then(() => {
8711
+ return;
8712
+ }).catch((err) => {
8713
+ warnOnce(`vinaya: log delivery to ${url} failed — queued in the local outbox, retried on the next event: ${err instanceof Error ? err.message : String(err)}
8714
+ `);
8715
+ });
8716
+ };
8231
8717
  function log(e) {
8232
8718
  try {
8233
8719
  const env = deps.env();
@@ -8242,22 +8728,26 @@ function createLogSink(overrides = {}) {
8242
8728
  attempt: env.VINAYA_ATTEMPT,
8243
8729
  parent: env.VINAYA_PARENT_EVENT
8244
8730
  };
8245
- resolveRepoOnce().then((resolved) => {
8246
- const repo = resolved && isSafeRepoSegment(resolved.owner) && isSafeRepoSegment(resolved.repo) ? resolved : null;
8731
+ const written = context().then(({ repo, doctrine: doctrineValue, destination: resolvedDestination }) => {
8247
8732
  const header = buildHeader({
8248
8733
  now,
8249
8734
  runId,
8250
8735
  seq: mySeq,
8251
8736
  repo: repo ? `${repo.owner}/${repo.repo}` : null,
8252
8737
  vinaya: deps.vinayaVersion(),
8253
- doctrine: doctrine(),
8738
+ doctrine: doctrineValue,
8254
8739
  host,
8255
8740
  hostname: deps.hostname(),
8256
8741
  env: envFields,
8257
- eventId: randomUUID(),
8742
+ eventId: randomUUID2(),
8258
8743
  processId,
8259
8744
  inputVersions: deps.inputVersions()
8260
8745
  });
8746
+ if (resolvedDestination.kind === "none") {
8747
+ warnOnce(`vinaya: not recording — ${resolvedDestination.reason}
8748
+ `);
8749
+ return;
8750
+ }
8261
8751
  const full = { ...e, ...header };
8262
8752
  const parsed = LogEventSchema.safeParse(full);
8263
8753
  if (!parsed.success) {
@@ -8267,25 +8757,42 @@ function createLogSink(overrides = {}) {
8267
8757
  }
8268
8758
  const line = `${JSON.stringify(redact(parsed.data, deps.home()))}
8269
8759
  `;
8270
- appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
8760
+ const destination = resolvedDestination;
8761
+ if (destination.kind === "server") {
8762
+ appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
8763
+ scheduleWebhookDrain(header.subject.issue, destination.url, destination.headers);
8764
+ } else {
8765
+ appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
8766
+ }
8271
8767
  }).catch((err) => {
8272
8768
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
8273
8769
  `);
8274
8770
  });
8771
+ pendingWrites.add(written);
8772
+ written.finally(() => pendingWrites.delete(written));
8275
8773
  } catch (err) {
8276
8774
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
8277
8775
  `);
8278
8776
  }
8279
8777
  }
8280
8778
  const warmup = () => {
8281
- doctrine();
8282
8779
  const originalWarn = console.warn;
8283
8780
  console.warn = () => {};
8284
8781
  resolveRepoOnce().finally(() => {
8285
8782
  console.warn = originalWarn;
8286
8783
  });
8784
+ context().catch(() => {
8785
+ return;
8786
+ });
8787
+ };
8788
+ const drain = async () => {
8789
+ if (pendingWrites.size > 0)
8790
+ await Promise.allSettled(Array.from(pendingWrites));
8791
+ await drainChain.catch(() => {
8792
+ return;
8793
+ });
8287
8794
  };
8288
- return { log, runId, warmup };
8795
+ return { log, runId, warmup, drain };
8289
8796
  }
8290
8797
  var defaultSink = createLogSink();
8291
8798
 
@@ -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
  }
@@ -8422,7 +8929,7 @@ var CHECK_NAME = "exec-bits";
8422
8929
  var EXECUTABLE_MODE = "100755";
8423
8930
  function git2(args) {
8424
8931
  try {
8425
- return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8932
+ return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8426
8933
  } catch {
8427
8934
  return null;
8428
8935
  }
@@ -8436,7 +8943,7 @@ function indexMode(path) {
8436
8943
  }
8437
8944
  function hasShebang(path) {
8438
8945
  try {
8439
- return readFileSync4(path, "utf8").startsWith("#!");
8946
+ return readFileSync6(path, "utf8").startsWith("#!");
8440
8947
  } catch {
8441
8948
  return false;
8442
8949
  }