@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,9 +1,7 @@
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-evidence-fresh.ts
6
- import { execFileSync as execFileSync8 } from "node:child_process";
4
+ import { execFileSync as execFileSync7 } from "node:child_process";
7
5
  // ../../packages/aeg-core/src/gate-audience.ts
8
6
  var GATE_AUDIENCE = {
9
7
  "check-branch-topology": { shippedAs: "branch-topology", ring: 0 },
@@ -1037,7 +1035,7 @@ function withDefaults(oldDefaults, newDefaults) {
1037
1035
  var endpoint = withDefaults(null, DEFAULTS);
1038
1036
 
1039
1037
  // ../../node_modules/fast-content-type-parse/index.js
1040
- var NullObject = function NullObject2() {};
1038
+ var NullObject = function NullObject() {};
1041
1039
  NullObject.prototype = Object.create(null);
1042
1040
  var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu;
1043
1041
  var quotedPairRE = /\\([\v\u0020-\u00ff])/gu;
@@ -1131,8 +1129,8 @@ function isPlainObject2(value) {
1131
1129
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
1132
1130
  }
1133
1131
  async function fetchWrapper(requestOptions) {
1134
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
1135
- if (!fetch) {
1132
+ const fetch2 = requestOptions.request?.fetch || globalThis.fetch;
1133
+ if (!fetch2) {
1136
1134
  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");
1137
1135
  }
1138
1136
  const log = requestOptions.request?.log || console;
@@ -1144,7 +1142,7 @@ async function fetchWrapper(requestOptions) {
1144
1142
  ]));
1145
1143
  let fetchResponse;
1146
1144
  try {
1147
- fetchResponse = await fetch(requestOptions.url, {
1145
+ fetchResponse = await fetch2(requestOptions.url, {
1148
1146
  method: requestOptions.method,
1149
1147
  body,
1150
1148
  redirect: requestOptions.request?.redirect,
@@ -1781,27 +1779,27 @@ function splitTableRow(row) {
1781
1779
  return parts.map((p) => p.split(PLACEHOLDER).join("|"));
1782
1780
  }
1783
1781
  // ../../packages/aeg-core/src/blast-radius-domains.ts
1784
- function resolveWorkspaceEntry(entry2, listDirs) {
1785
- if (entry2.endsWith("/*")) {
1786
- const baseDir = entry2.slice(0, -2);
1782
+ function resolveWorkspaceEntry(entry, listDirs) {
1783
+ if (entry.endsWith("/*")) {
1784
+ const baseDir = entry.slice(0, -2);
1787
1785
  return listDirs(baseDir).map((name) => `${baseDir}/${name}`);
1788
1786
  }
1789
- if (entry2.includes("*"))
1787
+ if (entry.includes("*"))
1790
1788
  return [];
1791
- return [entry2];
1789
+ return [entry];
1792
1790
  }
1793
1791
  // ../../packages/aeg-core/src/consumer-enumeration.ts
1794
1792
  function deriveWorkspaceMemberDirs(workspaces, listDirs) {
1795
- const positive = workspaces.filter((entry2) => !entry2.startsWith("!"));
1796
- const negative = workspaces.filter((entry2) => entry2.startsWith("!")).map((entry2) => entry2.slice(1));
1793
+ const positive = workspaces.filter((entry) => !entry.startsWith("!"));
1794
+ const negative = workspaces.filter((entry) => entry.startsWith("!")).map((entry) => entry.slice(1));
1797
1795
  const excluded = new Set;
1798
- for (const entry2 of negative) {
1799
- for (const member of resolveWorkspaceEntry(entry2, listDirs))
1796
+ for (const entry of negative) {
1797
+ for (const member of resolveWorkspaceEntry(entry, listDirs))
1800
1798
  excluded.add(member);
1801
1799
  }
1802
1800
  const members = new Set;
1803
- for (const entry2 of positive) {
1804
- for (const member of resolveWorkspaceEntry(entry2, listDirs)) {
1801
+ for (const entry of positive) {
1802
+ for (const member of resolveWorkspaceEntry(entry, listDirs)) {
1805
1803
  if (!excluded.has(member))
1806
1804
  members.add(member);
1807
1805
  }
@@ -2125,15 +2123,15 @@ function summarizeTranscript(jsonl) {
2125
2123
  const line = rawLine.trim();
2126
2124
  if (!line)
2127
2125
  continue;
2128
- let entry2;
2126
+ let entry;
2129
2127
  try {
2130
- entry2 = JSON.parse(line);
2128
+ entry = JSON.parse(line);
2131
2129
  } catch {
2132
2130
  continue;
2133
2131
  }
2134
- if (!entry2 || typeof entry2 !== "object")
2132
+ if (!entry || typeof entry !== "object")
2135
2133
  continue;
2136
- const obj = entry2;
2134
+ const obj = entry;
2137
2135
  if (obj.type !== "assistant")
2138
2136
  continue;
2139
2137
  const message = obj.message;
@@ -2981,7 +2979,7 @@ function isStep0Block(content) {
2981
2979
  }
2982
2980
  function checkCommandsCarryOutput(prBody) {
2983
2981
  const errors = [];
2984
- for (const [label2, num] of [
2982
+ for (const [label, num] of [
2985
2983
  ["5", 5],
2986
2984
  ["6", 6]
2987
2985
  ]) {
@@ -2995,7 +2993,7 @@ function checkCommandsCarryOutput(prBody) {
2995
2993
  continue;
2996
2994
  const next = blocks[i + 1];
2997
2995
  if (!next || isCommandBlock(next.content)) {
2998
- 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.`);
2996
+ 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.`);
2999
2997
  }
3000
2998
  }
3001
2999
  }
@@ -3432,8 +3430,8 @@ function stripPartBackticks(text) {
3432
3430
  function partWordCount(text) {
3433
3431
  return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3434
3432
  }
3435
- function looksLikeFilePath(entry2) {
3436
- const stripped = entry2.replace(/\/\*\*?$/, "");
3433
+ function looksLikeFilePath(entry) {
3434
+ const stripped = entry.replace(/\/\*\*?$/, "");
3437
3435
  const lastSegment = stripped.split("/").pop() ?? stripped;
3438
3436
  const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3439
3437
  return extMatch !== null && extMatch.index > 0;
@@ -3919,14 +3917,14 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3919
3917
  const referenced = extractClosesReferences(prBody);
3920
3918
  if (taskIssueRefs) {
3921
3919
  for (const n of referenced) {
3922
- const ref2 = taskIssueRefs.get(n);
3923
- if (!ref2)
3920
+ const ref = taskIssueRefs.get(n);
3921
+ if (!ref)
3924
3922
  continue;
3925
- const expectedBranch = `task/${ref2.trancheSlug}/${ref2.taskId}`;
3923
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3926
3924
  if (branch !== expectedBranch) {
3927
3925
  return {
3928
3926
  ok: false,
3929
- 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.`
3927
+ 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.`
3930
3928
  };
3931
3929
  }
3932
3930
  }
@@ -3935,15 +3933,15 @@ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3935
3933
  if (!ref)
3936
3934
  return { ok: true };
3937
3935
  if (ref.kind === "issue") {
3938
- const expectedIssue2 = ref.issueNumber;
3939
- if (!referenced.has(expectedIssue2)) {
3936
+ const expectedIssue = ref.issueNumber;
3937
+ if (!referenced.has(expectedIssue)) {
3940
3938
  return {
3941
3939
  ok: false,
3942
- expectedIssue: expectedIssue2,
3943
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue2}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3940
+ expectedIssue,
3941
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3944
3942
  };
3945
3943
  }
3946
- return { ok: true, expectedIssue: expectedIssue2 };
3944
+ return { ok: true, expectedIssue };
3947
3945
  }
3948
3946
  const trancheSlug = ref.tranche;
3949
3947
  const taskId = ref.taskId;
@@ -3989,8 +3987,8 @@ function extractIssue(body) {
3989
3987
  const anchorNums = closesRefs(anchored);
3990
3988
  if (anchorNums.length === 0)
3991
3989
  return { issue: null, extraIssues: bodyNums, outsideHeader: false };
3992
- const issue2 = anchorNums[0];
3993
- return { issue: issue2, extraIssues: bodyNums.filter((n) => n !== issue2), outsideHeader: false };
3990
+ const issue = anchorNums[0];
3991
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3994
3992
  }
3995
3993
  const headerNums = closesRefs(headerRegion(stripped));
3996
3994
  if (bodyNums.length === 0)
@@ -4059,15 +4057,15 @@ function compareManifest(echoed, current, patchIdOf) {
4059
4057
  const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4060
4058
  const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4061
4059
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4062
- const objectivesVersion2 = isBoundToObjectives(echoed, current.objectivesVersion);
4060
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4063
4061
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4064
4062
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4065
4063
  return {
4066
- bound: head && base && briefHashBound && objectivesVersion2 && rulingOrdinal && policyDigestBound,
4064
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4067
4065
  head,
4068
4066
  base,
4069
4067
  briefHash: briefHashBound,
4070
- objectivesVersion: objectivesVersion2,
4068
+ objectivesVersion,
4071
4069
  rulingOrdinal,
4072
4070
  policyDigest: policyDigestBound
4073
4071
  };
@@ -5499,6 +5497,10 @@ function findWorkspaceEscapes(files, knownPaths, workspaceDirs = DEFAULT_WORKSPA
5499
5497
  }
5500
5498
  return findings;
5501
5499
  }
5500
+ // ../../packages/aeg-core/src/dev-review-loop/types.ts
5501
+ var SEVERITY_COLUMNS = ["blocker", "major", "minor", "critical", "high", "medium", "low"];
5502
+ // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
5503
+ var SUMMARY_TABLE_HEADER = `| round | ${SEVERITY_COLUMNS.join(" | ")} | confidence | outcome |`;
5502
5504
  // ../../packages/aeg-core/src/log/envelope.ts
5503
5505
  import { createHash as createHash5 } from "node:crypto";
5504
5506
 
@@ -6037,6 +6039,7 @@ function redact(value, home) {
6037
6039
  return value;
6038
6040
  }
6039
6041
  // ../../packages/aeg-core/src/log/store.ts
6042
+ var KNOWN_SCHEMA_VERSIONS = [1, 2];
6040
6043
  function metaOf(obj) {
6041
6044
  if (obj === null || typeof obj !== "object")
6042
6045
  return null;
@@ -6059,11 +6062,61 @@ function recordIdentity(obj) {
6059
6062
  }
6060
6063
  return null;
6061
6064
  }
6062
-
6063
- // ../../packages/aeg-core/src/log/artifact.ts
6064
- var TASK_LOG_ARTIFACT_MAX_BYTES = 8 * 1024 * 1024;
6065
- // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
6066
- var STOPPED_CONDITIONS = new Set(["confidence", "reappearance", "no_progress", "max_rounds"]);
6065
+ function schemaVersionOf(obj) {
6066
+ const meta = metaOf(obj);
6067
+ const schema = meta?.schema;
6068
+ return typeof schema === "number" ? schema : null;
6069
+ }
6070
+ function isKnownSchema(version) {
6071
+ return version !== null && KNOWN_SCHEMA_VERSIONS.includes(version);
6072
+ }
6073
+ function classifyStoredLine(raw, home) {
6074
+ let obj;
6075
+ try {
6076
+ obj = JSON.parse(raw);
6077
+ } catch {
6078
+ return { status: "invalid", identity: null, raw, reason: "not valid JSON" };
6079
+ }
6080
+ const version = schemaVersionOf(obj);
6081
+ if (version === null) {
6082
+ return { status: "invalid", identity: recordIdentity(obj), raw, reason: "no readable meta.schema" };
6083
+ }
6084
+ if (!isKnownSchema(version)) {
6085
+ return {
6086
+ status: "unknown_version",
6087
+ identity: recordIdentity(obj),
6088
+ schema: version,
6089
+ raw,
6090
+ reason: `schema version ${version} is not one this build validates (${KNOWN_SCHEMA_VERSIONS.join(", ")}) — kept for diagnosis`
6091
+ };
6092
+ }
6093
+ const result = LogEventSchema.safeParse(obj);
6094
+ if (!result.success) {
6095
+ return {
6096
+ status: "invalid",
6097
+ identity: recordIdentity(obj),
6098
+ raw,
6099
+ reason: result.error.issues[0]?.message ?? "schema violation"
6100
+ };
6101
+ }
6102
+ const event = result.data;
6103
+ const identity = recordIdentity(event);
6104
+ if (identity === null) {
6105
+ return { status: "invalid", identity: null, raw, reason: "valid event with no derivable identity" };
6106
+ }
6107
+ const redacted = redact(event, home);
6108
+ const provenance = version === 2 ? event.meta.provenance ?? null : null;
6109
+ return {
6110
+ status: "ok",
6111
+ identity,
6112
+ runId: event.meta.run_id,
6113
+ seq: event.meta.seq,
6114
+ schema: version,
6115
+ provenance,
6116
+ event,
6117
+ postLine: JSON.stringify(redacted)
6118
+ };
6119
+ }
6067
6120
  // ../../packages/aeg-core/src/control-store/records.ts
6068
6121
  import { z as z3 } from "zod";
6069
6122
  var isoTimestamp = z3.string().min(1);
@@ -6193,6 +6246,10 @@ var ResolutionRecordSchema = z3.object({
6193
6246
  authenticatedFrom: z3.string().min(1),
6194
6247
  consumedAt: isoTimestamp
6195
6248
  }).strict();
6249
+ // src/lib/pr-report-engine.ts
6250
+ import { execFile as execFile6 } from "node:child_process";
6251
+ import { promisify as promisify6 } from "node:util";
6252
+
6196
6253
  // src/checks/registry.ts
6197
6254
  import { existsSync as existsSync2 } from "node:fs";
6198
6255
  import { join as join2 } from "node:path";
@@ -6632,6 +6689,16 @@ var REGISTRY = [
6632
6689
  },
6633
6690
  0
6634
6691
  ],
6692
+ [
6693
+ {
6694
+ name: "ci-shard-coverage",
6695
+ run: bin("check-ci-shard-coverage"),
6696
+ scope: "diff",
6697
+ timeoutMs: 15000,
6698
+ env: {}
6699
+ },
6700
+ 0
6701
+ ],
6635
6702
  [
6636
6703
  {
6637
6704
  name: "workspace-escape",
@@ -6769,24 +6836,26 @@ function coreCheckRegistry() {
6769
6836
  var CORE_CHECK_RING = Object.fromEntries(REGISTRY.map(([spec, ring]) => [spec.name, ring]));
6770
6837
 
6771
6838
  // src/lib/log-sink.ts
6772
- import { execFileSync as execFileSync3 } from "node:child_process";
6773
- import { randomUUID } from "node:crypto";
6839
+ import { execFile as execFile5 } from "node:child_process";
6840
+ import { randomUUID as randomUUID2 } from "node:crypto";
6774
6841
  import {
6775
- closeSync as closeSync2,
6776
- constants as fsConstants2,
6777
- existsSync as existsSync4,
6842
+ closeSync as closeSync3,
6843
+ constants as fsConstants3,
6844
+ existsSync as existsSync5,
6778
6845
  fstatSync as fstatSync2,
6779
- mkdirSync as mkdirSync2,
6780
- openSync as openSync2,
6781
- readFileSync as readFileSync3,
6782
- renameSync,
6783
- writeSync
6846
+ mkdirSync as mkdirSync3,
6847
+ openSync as openSync3,
6848
+ readFileSync as readFileSync4,
6849
+ renameSync as renameSync2,
6850
+ writeSync as writeSync2
6784
6851
  } from "node:fs";
6785
- import { hostname as osHostname, homedir as homedir2 } from "node:os";
6786
- import { dirname as dirname3, join as join4 } from "node:path";
6852
+ import { hostname as osHostname, homedir as homedir3 } from "node:os";
6853
+ import { dirname as dirname5, join as join6 } from "node:path";
6854
+ import { promisify as promisify5 } from "node:util";
6787
6855
 
6788
6856
  // src/lib/config.ts
6789
- import { execFileSync as execFileSync2 } from "node:child_process";
6857
+ import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6858
+ import { promisify as promisify4 } from "node:util";
6790
6859
  import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6791
6860
  import { homedir } from "node:os";
6792
6861
  import { dirname as dirname2, isAbsolute, join as join3, resolve } from "node:path";
@@ -6813,10 +6882,10 @@ var CheckEntrySchema = z4.object({
6813
6882
  ownWorkflow: z4.boolean().optional(),
6814
6883
  principalOwed: z4.literal(true).optional(),
6815
6884
  validates: z4.enum(["body", "issue"]).optional()
6816
- }).superRefine((entry2, ctx) => {
6817
- if (!entry2.env)
6885
+ }).superRefine((entry, ctx) => {
6886
+ if (!entry.env)
6818
6887
  return;
6819
- for (const [key, value] of Object.entries(entry2.env)) {
6888
+ for (const [key, value] of Object.entries(entry.env)) {
6820
6889
  if (typeof value !== "object" || value === null || !("anyOf" in value))
6821
6890
  continue;
6822
6891
  const members = value.anyOf;
@@ -6973,18 +7042,19 @@ var VinayaConfigSchema = z4.object({
6973
7042
  });
6974
7043
  }
6975
7044
  }).optional(),
6976
- logPublish: z4.object({
6977
- issue: z4.number().int().positive().optional(),
6978
- pr: z4.number().int().positive().optional(),
6979
- webhookUrl: z4.string().url().optional(),
6980
- headers: z4.record(z4.string()).optional(),
6981
- maxChunksPerFlush: z4.number().int().positive().optional()
6982
- }).refine((v) => [v.issue, v.pr, v.webhookUrl].filter((x) => x !== undefined).length <= 1, {
6983
- message: "logPublish: set at most one of issue/pr/webhookUrl"
6984
- }).refine((v) => v.headers === undefined || v.webhookUrl !== undefined, {
6985
- message: "logPublish: headers requires webhookUrl"
6986
- }).optional(),
6987
- runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional()
7045
+ logPublish: z4.unknown().refine((v) => v === undefined, {
7046
+ message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7047
+ }),
7048
+ runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7049
+ logs: z4.object({
7050
+ folder: z4.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7051
+ url: z4.string().url().optional(),
7052
+ headers: z4.record(z4.string()).optional()
7053
+ }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7054
+ message: "logs: set at most one of folder/url"
7055
+ }).refine((v) => v.headers === undefined || v.url !== undefined, {
7056
+ message: "logs: headers requires url"
7057
+ }).optional()
6988
7058
  });
6989
7059
  var GLOBAL_VINAYA_HOME = join3(homedir(), ".vinaya");
6990
7060
  var GLOBAL_CONFIG_PATH = join3(GLOBAL_VINAYA_HOME, "config.json");
@@ -7029,32 +7099,39 @@ function globalTokensCollectIgnoredWarning(path) {
7029
7099
  function globalRuntimeDirIgnoredWarning(path) {
7030
7100
  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.`;
7031
7101
  }
7102
+ var emittedGlobalKeyWarnings = new Set;
7103
+ function warnGlobalKeyIgnoredOnce(message) {
7104
+ if (emittedGlobalKeyWarnings.has(message))
7105
+ return;
7106
+ emittedGlobalKeyWarnings.add(message);
7107
+ console.error(`⚠ ${message}`);
7108
+ }
7032
7109
  function stripGlobalOnlyKeys(config, path) {
7033
7110
  if (path !== GLOBAL_CONFIG_PATH)
7034
7111
  return config;
7035
7112
  let result = config;
7036
7113
  if (result.checks && Object.keys(result.checks).length > 0) {
7037
- console.error(`⚠ ${globalChecksIgnoredWarning(path)}`);
7114
+ warnGlobalKeyIgnoredOnce(globalChecksIgnoredWarning(path));
7038
7115
  result = { ...result, checks: undefined };
7039
7116
  }
7040
7117
  if (result.roles && Object.keys(result.roles).length > 0) {
7041
- console.error(`⚠ ${globalRolesIgnoredWarning(path)}`);
7118
+ warnGlobalKeyIgnoredOnce(globalRolesIgnoredWarning(path));
7042
7119
  result = { ...result, roles: undefined };
7043
7120
  }
7044
7121
  if (result.principals && result.principals.length > 0) {
7045
- console.error(`⚠ ${globalPrincipalsIgnoredWarning(path)}`);
7122
+ warnGlobalKeyIgnoredOnce(globalPrincipalsIgnoredWarning(path));
7046
7123
  result = { ...result, principals: undefined };
7047
7124
  }
7048
7125
  if (result.releaseActor) {
7049
- console.error(`⚠ ${globalReleaseActorIgnoredWarning(path)}`);
7126
+ warnGlobalKeyIgnoredOnce(globalReleaseActorIgnoredWarning(path));
7050
7127
  result = { ...result, releaseActor: undefined };
7051
7128
  }
7052
7129
  if (result.tokens) {
7053
- console.error(`⚠ ${globalTokensCollectIgnoredWarning(path)}`);
7130
+ warnGlobalKeyIgnoredOnce(globalTokensCollectIgnoredWarning(path));
7054
7131
  result = { ...result, tokens: undefined };
7055
7132
  }
7056
7133
  if (result.runtimeDir) {
7057
- console.error(`⚠ ${globalRuntimeDirIgnoredWarning(path)}`);
7134
+ warnGlobalKeyIgnoredOnce(globalRuntimeDirIgnoredWarning(path));
7058
7135
  result = { ...result, runtimeDir: undefined };
7059
7136
  }
7060
7137
  return result;
@@ -7087,25 +7164,80 @@ function resolveReviewPolicy(config) {
7087
7164
  maxRounds
7088
7165
  };
7089
7166
  }
7090
- function trustAnchorRepo() {
7091
- const wellFormed = (slug) => /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
7092
- const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
7093
- if (fromRunner) {
7094
- const validated = wellFormed(fromRunner);
7095
- if (validated)
7096
- return validated;
7167
+ function resolveRuntimeDirSetting(config) {
7168
+ return config?.runtimeDir ?? null;
7169
+ }
7170
+ function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
7171
+ const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
7172
+ return anchored !== null && anchored === localRuntimeDir ? anchored : null;
7173
+ }
7174
+ function resolveLogsSetting(config) {
7175
+ const raw = config?.logs;
7176
+ if (!raw)
7177
+ return null;
7178
+ if (raw.url !== undefined)
7179
+ return { url: raw.url, headers: raw.headers };
7180
+ if (raw.folder !== undefined)
7181
+ return { folder: raw.folder };
7182
+ return null;
7183
+ }
7184
+ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
7185
+ const anchored = resolveLogsSetting(trustAnchorConfig);
7186
+ if (!anchored)
7187
+ return null;
7188
+ if ("url" in local)
7189
+ return "url" in anchored && anchored.url === local.url ? anchored : null;
7190
+ return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
7191
+ }
7192
+ function resolveLogsHeaderValues(headers, env) {
7193
+ if (!headers)
7194
+ return;
7195
+ const resolved = {};
7196
+ for (const [key, value] of Object.entries(headers)) {
7197
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
7097
7198
  }
7199
+ return resolved;
7200
+ }
7201
+ function trustAnchorRepo() {
7202
+ const fromRunner = trustAnchorRepoFromRunner();
7203
+ if (fromRunner)
7204
+ return fromRunner;
7098
7205
  try {
7099
7206
  const url = execFileSync2("git", ["remote", "get-url", "origin"], {
7100
7207
  encoding: "utf-8",
7101
7208
  stdio: ["ignore", "pipe", "pipe"]
7102
- }).trim();
7103
- const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
7104
- return m?.[1] && m[2] ? wellFormed(`${m[1]}/${m[2]}`) : null;
7209
+ });
7210
+ return trustAnchorRepoFromRemoteUrl(url);
7211
+ } catch {
7212
+ return null;
7213
+ }
7214
+ }
7215
+ async function trustAnchorRepoAsync() {
7216
+ const fromRunner = trustAnchorRepoFromRunner();
7217
+ if (fromRunner)
7218
+ return fromRunner;
7219
+ try {
7220
+ const { stdout } = await execFileAsync4("git", ["remote", "get-url", "origin"], {
7221
+ encoding: "utf-8",
7222
+ timeout: 1e4
7223
+ });
7224
+ return trustAnchorRepoFromRemoteUrl(stdout);
7105
7225
  } catch {
7106
7226
  return null;
7107
7227
  }
7108
7228
  }
7229
+ function wellFormedRepoSlug(slug) {
7230
+ return /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
7231
+ }
7232
+ function trustAnchorRepoFromRunner() {
7233
+ const fromRunner = process.env.GITHUB_REPOSITORY?.trim();
7234
+ return fromRunner ? wellFormedRepoSlug(fromRunner) : null;
7235
+ }
7236
+ function trustAnchorRepoFromRemoteUrl(url) {
7237
+ const m = url.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/);
7238
+ return m?.[1] && m[2] ? wellFormedRepoSlug(`${m[1]}/${m[2]}`) : null;
7239
+ }
7240
+ var execFileAsync4 = promisify4(execFile4);
7109
7241
  function ghFetchTrustAnchorConfig() {
7110
7242
  const repo = trustAnchorRepo();
7111
7243
  if (!repo)
@@ -7115,6 +7247,13 @@ function ghFetchTrustAnchorConfig() {
7115
7247
  stdio: ["ignore", "pipe", "pipe"]
7116
7248
  });
7117
7249
  }
7250
+ async function ghFetchTrustAnchorConfigAsync() {
7251
+ const repo = await trustAnchorRepoAsync();
7252
+ if (!repo)
7253
+ throw new Error("could not resolve repo identity for the trust-anchor read");
7254
+ const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4 });
7255
+ return stdout;
7256
+ }
7118
7257
  function firstLine(err) {
7119
7258
  return err?.message?.split(`
7120
7259
  `)[0] ?? "unknown error";
@@ -7129,16 +7268,35 @@ function isMissingFileError(err) {
7129
7268
  return /\b404\b|not found/i.test(haystack);
7130
7269
  }
7131
7270
  function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7132
- 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.
7133
- `);
7134
7271
  let base64;
7135
7272
  try {
7136
- base64 = fetcher().trim();
7273
+ base64 = fetcher();
7137
7274
  } catch (err) {
7138
- if (!isMissingFileError(err))
7139
- warn(firstLine(err));
7140
- return null;
7275
+ return trustAnchorFetchFailed(err);
7276
+ }
7277
+ return parseTrustAnchorContent(base64);
7278
+ }
7279
+ async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7280
+ const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7281
+ let base64;
7282
+ try {
7283
+ base64 = await fetcher();
7284
+ } catch (err) {
7285
+ return trustAnchorFetchFailed(err, warn);
7141
7286
  }
7287
+ return parseTrustAnchorContent(base64, warn);
7288
+ }
7289
+ function warnTrustAnchorFallback(why) {
7290
+ 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.
7291
+ `);
7292
+ }
7293
+ function trustAnchorFetchFailed(err, warn = warnTrustAnchorFallback) {
7294
+ if (!isMissingFileError(err))
7295
+ warn(firstLine(err));
7296
+ return null;
7297
+ }
7298
+ function parseTrustAnchorContent(content, warn = warnTrustAnchorFallback) {
7299
+ const base64 = content.trim();
7142
7300
  if (!base64)
7143
7301
  return null;
7144
7302
  try {
@@ -7166,28 +7324,365 @@ function loadConfig() {
7166
7324
  }
7167
7325
  var TOKENS_COLLECT_TRUST_PATH = join3(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7168
7326
 
7327
+ // src/lib/run-paths.ts
7328
+ import { chmodSync, existsSync as existsSync4, realpathSync as realpathSync2 } from "node:fs";
7329
+ import { dirname as dirname3, join as join4, resolve as resolvePath } from "node:path";
7330
+ var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
7331
+ function isSafeRepoSegment(segment) {
7332
+ return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
7333
+ }
7334
+ function repoSegment(repo) {
7335
+ if (!repo || !isSafeRepoSegment(repo.owner) || !isSafeRepoSegment(repo.repo))
7336
+ return "unresolved";
7337
+ return `${repo.owner}-${repo.repo}`;
7338
+ }
7339
+ function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
7340
+ return join4(home, "runtime", repoSegment(repo));
7341
+ }
7342
+ function resolveRuntimeDir(input) {
7343
+ const local = resolveRuntimeDirSetting(input.localConfig);
7344
+ if (local === null)
7345
+ return defaultRuntimeDir(input.repo, input.home);
7346
+ if (isInsideRepo(local, input.repoRoot))
7347
+ return defaultRuntimeDir(input.repo, input.home);
7348
+ if (!input.unattended)
7349
+ return local;
7350
+ const anchored = resolveTrustAnchorRuntimeDir(local, input.trustAnchorConfig ?? null);
7351
+ return anchored ?? defaultRuntimeDir(input.repo, input.home);
7352
+ }
7353
+ function isInsideRepo(candidate, repoRoot) {
7354
+ if (!repoRoot)
7355
+ return false;
7356
+ const root = resolvePath(repoRoot);
7357
+ const target = resolvePath(candidate);
7358
+ return target === root || target.startsWith(`${root}/`);
7359
+ }
7360
+ var UNATTENDED_ENV_KEY = "VINAYA_UNATTENDED";
7361
+ var RUNTIME_DIR_ENV_KEY = "VINAYA_RUNTIME_DIR";
7362
+ function isUnattendedProcess(env = process.env) {
7363
+ return env[UNATTENDED_ENV_KEY] === "1" || (env.VINAYA_ROLE ?? "") !== "";
7364
+ }
7365
+ var memoized = null;
7366
+ async function runtimeDirForRepoAsync(repo) {
7367
+ const key = repoSegment(repo);
7368
+ if (memoized?.key === key)
7369
+ return memoized.value;
7370
+ const inputs = runtimeDirInputs();
7371
+ if (typeof inputs === "string")
7372
+ return inputs;
7373
+ const value = resolveRuntimeDir({
7374
+ repo,
7375
+ ...inputs.base,
7376
+ trustAnchorConfig: inputs.needsAnchor ? await loadTrustAnchorConfigAsync() : null
7377
+ });
7378
+ memoized = { key, value };
7379
+ return value;
7380
+ }
7381
+ function runtimeDirInputs() {
7382
+ const handedDown = process.env[RUNTIME_DIR_ENV_KEY];
7383
+ if (handedDown)
7384
+ return handedDown;
7385
+ const localConfig = loadConfig();
7386
+ const unattended = isUnattendedProcess();
7387
+ return {
7388
+ base: { localConfig, unattended, repoRoot: repoRootSync() },
7389
+ needsAnchor: unattended && resolveRuntimeDirSetting(localConfig) !== null
7390
+ };
7391
+ }
7392
+ function repoRootSync(start = process.cwd()) {
7393
+ let dir;
7394
+ try {
7395
+ dir = realpathSync2(start);
7396
+ } catch {
7397
+ return null;
7398
+ }
7399
+ for (;; ) {
7400
+ if (existsSync4(join4(dir, ".git")))
7401
+ return dir;
7402
+ const parent = dirname3(dir);
7403
+ if (parent === dir)
7404
+ return null;
7405
+ dir = parent;
7406
+ }
7407
+ }
7408
+
7409
+ // src/lib/log-webhook-drain.ts
7410
+ import {
7411
+ closeSync as closeSync2,
7412
+ constants as fsConstants2,
7413
+ lstatSync,
7414
+ mkdirSync as mkdirSync2,
7415
+ openSync as openSync2,
7416
+ linkSync,
7417
+ readFileSync as readFileSync3,
7418
+ renameSync,
7419
+ statSync,
7420
+ unlinkSync,
7421
+ writeFileSync as writeFileSync2,
7422
+ writeSync
7423
+ } from "node:fs";
7424
+ import { randomUUID } from "node:crypto";
7425
+ import { homedir as homedir2 } from "node:os";
7426
+ import { dirname as dirname4, join as join5 } from "node:path";
7427
+ var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
7428
+ var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
7429
+ var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
7430
+ function isSafeRepoSegment2(segment) {
7431
+ return SAFE_PATH_SEGMENT2.test(segment) && !segment.includes("..");
7432
+ }
7433
+ function isErrnoCode(err, code) {
7434
+ return typeof err === "object" && err !== null && err.code === code;
7435
+ }
7436
+ function isEnoent(err) {
7437
+ return isErrnoCode(err, "ENOENT");
7438
+ }
7439
+ var WEBHOOK_DRAIN_LOCK_STALE_MS = 4 * WEBHOOK_FETCH_TIMEOUT_MS;
7440
+ function tryCreateLock(lockPath, token) {
7441
+ try {
7442
+ mkdirSync2(dirname4(lockPath), { recursive: true, mode: 448 });
7443
+ const fd = openSync2(lockPath, fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL, 384);
7444
+ try {
7445
+ writeSync(fd, `${token}
7446
+ `);
7447
+ } finally {
7448
+ closeSync2(fd);
7449
+ }
7450
+ return true;
7451
+ } catch (err) {
7452
+ if (isErrnoCode(err, "EEXIST"))
7453
+ return false;
7454
+ throw err;
7455
+ }
7456
+ }
7457
+ function acquireDrainLock(lockPath) {
7458
+ const token = `${process.pid}:${randomUUID()}`;
7459
+ if (tryCreateLock(lockPath, token))
7460
+ return token;
7461
+ let observedMtimeMs;
7462
+ try {
7463
+ observedMtimeMs = statSync(lockPath).mtimeMs;
7464
+ } catch (err) {
7465
+ if (!isEnoent(err))
7466
+ throw err;
7467
+ return tryCreateLock(lockPath, token) ? token : null;
7468
+ }
7469
+ if (Date.now() - observedMtimeMs <= WEBHOOK_DRAIN_LOCK_STALE_MS)
7470
+ return null;
7471
+ const claimed = `${lockPath}.claimed-${randomUUID()}`;
7472
+ try {
7473
+ renameSync(lockPath, claimed);
7474
+ } catch (err) {
7475
+ if (isEnoent(err))
7476
+ return null;
7477
+ throw err;
7478
+ }
7479
+ let claimedMtimeMs = null;
7480
+ try {
7481
+ claimedMtimeMs = statSync(claimed).mtimeMs;
7482
+ } catch (err) {
7483
+ if (!isEnoent(err))
7484
+ throw err;
7485
+ }
7486
+ if (claimedMtimeMs !== observedMtimeMs) {
7487
+ try {
7488
+ linkSync(claimed, lockPath);
7489
+ } catch (err) {
7490
+ if (!isErrnoCode(err, "EEXIST"))
7491
+ throw err;
7492
+ }
7493
+ try {
7494
+ unlinkSync(claimed);
7495
+ } catch (err) {
7496
+ if (!isEnoent(err))
7497
+ throw err;
7498
+ }
7499
+ return null;
7500
+ }
7501
+ unlinkSync(claimed);
7502
+ return tryCreateLock(lockPath, token) ? token : null;
7503
+ }
7504
+ function releaseDrainLock(lockPath, token) {
7505
+ try {
7506
+ const holder = readFileSync3(lockPath, "utf8").trim();
7507
+ if (holder !== token)
7508
+ return;
7509
+ unlinkSync(lockPath);
7510
+ } catch (err) {
7511
+ if (!isEnoent(err))
7512
+ throw err;
7513
+ }
7514
+ }
7515
+
7516
+ class WebhookDrainError extends Error {
7517
+ code;
7518
+ constructor(code, message) {
7519
+ super(message);
7520
+ this.code = code;
7521
+ }
7522
+ }
7523
+ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
7524
+ const resolved = await resolveRepo();
7525
+ const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
7526
+ const outboxRoot = () => join5(GLOBAL_VINAYA_HOME, "outbox");
7527
+ const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
7528
+ const lockPath = `${path}.flush-lock`;
7529
+ const lockToken = acquireDrainLock(lockPath);
7530
+ if (lockToken === null)
7531
+ return { flushed: false };
7532
+ try {
7533
+ let lstat;
7534
+ try {
7535
+ lstat = lstatSync(path);
7536
+ } catch (err) {
7537
+ if (!isEnoent(err))
7538
+ throw err;
7539
+ }
7540
+ if (lstat === undefined)
7541
+ return { flushed: false };
7542
+ if (!lstat.isFile()) {
7543
+ 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}`);
7544
+ }
7545
+ const buf = readFileSync3(path);
7546
+ const startOffset = buf.byteLength;
7547
+ const rawLines = buf.toString("utf8").split(`
7548
+ `).filter((l) => l.length > 0);
7549
+ if (rawLines.length === 0)
7550
+ return { flushed: false };
7551
+ const postLines = [];
7552
+ for (let i = 0;i < rawLines.length; i++) {
7553
+ const record = classifyStoredLine(rawLines[i], homedir2());
7554
+ if (record.status !== "ok") {
7555
+ throw new WebhookDrainError("log-webhook-drain-corrupt-line", `log webhook drain: outbox line ${i} failed schema re-validation — ${record.reason}`);
7556
+ }
7557
+ postLines.push(record.postLine);
7558
+ }
7559
+ const body = `${postLines.join(`
7560
+ `)}
7561
+ `;
7562
+ const bytes = Buffer.byteLength(body, "utf8");
7563
+ if (bytes > MAX_WEBHOOK_BODY_BYTES) {
7564
+ 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.`);
7565
+ }
7566
+ let response;
7567
+ try {
7568
+ response = await fetch(webhookUrl, {
7569
+ method: "POST",
7570
+ headers: { "content-type": "application/x-ndjson", ...headers },
7571
+ body,
7572
+ signal: AbortSignal.timeout(fetchTimeoutMs)
7573
+ });
7574
+ } catch (err) {
7575
+ const reason = err instanceof Error && err.name === "TimeoutError" ? `timed out after ${fetchTimeoutMs}ms` : err instanceof Error ? err.message : String(err);
7576
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} failed: ${reason}`);
7577
+ }
7578
+ if (!response.ok) {
7579
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} returned ${response.status} ${response.statusText}`);
7580
+ }
7581
+ const liveNow = readFileSync3(path);
7582
+ const tail = liveNow.subarray(Math.min(startOffset, liveNow.byteLength));
7583
+ writeFileSync2(path, tail);
7584
+ return { flushed: true, lineCount: postLines.length, bytes };
7585
+ } finally {
7586
+ releaseDrainLock(lockPath, lockToken);
7587
+ }
7588
+ }
7589
+
7169
7590
  // src/lib/log-sink.ts
7170
7591
  var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
7171
- function isEnoent(err) {
7592
+ var LOG_CONTEXT_LOOKUP_DEADLINE_MS = 3000;
7593
+ function withDeadline(work, ms, fallback) {
7594
+ return new Promise((resolve) => {
7595
+ const timer = setTimeout(() => resolve(fallback), ms);
7596
+ timer.unref?.();
7597
+ work.then((value) => {
7598
+ clearTimeout(timer);
7599
+ resolve(value);
7600
+ }, () => {
7601
+ clearTimeout(timer);
7602
+ resolve(fallback);
7603
+ });
7604
+ });
7605
+ }
7606
+ async function safeLoadTrustAnchorConfig() {
7607
+ return withDeadline(loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
7608
+ }
7609
+ function logsCredentialMissing(headers, env) {
7610
+ if (!headers)
7611
+ return false;
7612
+ const varPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
7613
+ for (const value of Object.values(headers)) {
7614
+ for (const match of value.matchAll(varPattern)) {
7615
+ if (!env[match[1]])
7616
+ return true;
7617
+ }
7618
+ }
7619
+ return false;
7620
+ }
7621
+ function resolveLogDestinationFrom(input) {
7622
+ const local = resolveLogsSetting(input.localConfig);
7623
+ let effective = null;
7624
+ if (input.unattended) {
7625
+ effective = local ? resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig) : resolveLogsSetting(input.trustAnchorConfig);
7626
+ } else {
7627
+ effective = local;
7628
+ }
7629
+ if (hostFromEnv(input.env) === "ci") {
7630
+ if (effective && "url" in effective) {
7631
+ if (logsCredentialMissing(effective.headers, input.env)) {
7632
+ return {
7633
+ kind: "none",
7634
+ reason: "a logs.url server destination is configured, but this job holds no delivery credential (a fork pull request, or a missing repository secret)"
7635
+ };
7636
+ }
7637
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
7638
+ }
7639
+ return {
7640
+ kind: "none",
7641
+ reason: "no server destination is configured for CI delivery (vinaya.config.json logs.url)"
7642
+ };
7643
+ }
7644
+ if (effective && "url" in effective) {
7645
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
7646
+ }
7647
+ if (effective && "folder" in effective && isInsideRepo(effective.folder, input.repoRoot)) {
7648
+ effective = null;
7649
+ }
7650
+ const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
7651
+ return { kind: "folder", folder };
7652
+ }
7653
+ var processTrustAnchorOnce;
7654
+ function processTrustAnchor() {
7655
+ if (processTrustAnchorOnce === undefined)
7656
+ processTrustAnchorOnce = safeLoadTrustAnchorConfig();
7657
+ return processTrustAnchorOnce;
7658
+ }
7659
+ async function defaultResolveLogDestination(repo, env) {
7660
+ const localConfig = loadConfig();
7661
+ const unattended = isUnattendedProcess(process.env);
7662
+ return resolveLogDestinationFrom({
7663
+ localConfig,
7664
+ trustAnchorConfig: unattended ? await processTrustAnchor() : null,
7665
+ unattended,
7666
+ env,
7667
+ defaultFolder: join6(await runtimeDirForRepoAsync(repo), "logs"),
7668
+ repoRoot: repoRootSync()
7669
+ });
7670
+ }
7671
+ function isEnoent2(err) {
7172
7672
  return typeof err === "object" && err !== null && err.code === "ENOENT";
7173
7673
  }
7174
- function resolveDoctrine(cwd, vinayaVersion) {
7674
+ var execFileAsync5 = promisify5(execFile5);
7675
+ async function resolveDoctrine(cwd, vinayaVersion) {
7175
7676
  let toplevel;
7176
7677
  try {
7177
- toplevel = execFileSync3("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
7178
- encoding: "utf8",
7179
- stdio: ["ignore", "pipe", "pipe"]
7180
- }).trim();
7678
+ toplevel = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
7181
7679
  } catch (err) {
7182
- return isEnoent(err) ? "unknown" : vinayaVersion;
7680
+ return isEnoent2(err) ? "unknown" : vinayaVersion;
7183
7681
  }
7184
- if (!existsSync4(join4(toplevel, "aeg-root", "roles")))
7682
+ if (!existsSync5(join6(toplevel, "aeg-root", "roles")))
7185
7683
  return vinayaVersion;
7186
7684
  try {
7187
- const sha = execFileSync3("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], {
7188
- encoding: "utf8",
7189
- stdio: ["ignore", "pipe", "pipe"]
7190
- }).trim();
7685
+ const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
7191
7686
  return `aeg-root@${sha}`;
7192
7687
  } catch {
7193
7688
  return vinayaVersion;
@@ -7195,20 +7690,20 @@ function resolveDoctrine(cwd, vinayaVersion) {
7195
7690
  }
7196
7691
  function readVinayaVersion() {
7197
7692
  try {
7198
- const pkg = JSON.parse(readFileSync3(join4(packageRoot(import.meta.url), "package.json"), "utf8"));
7693
+ const pkg = JSON.parse(readFileSync4(join6(packageRoot(import.meta.url), "package.json"), "utf8"));
7199
7694
  return pkg.version ?? "unknown";
7200
7695
  } catch {
7201
7696
  return "unknown";
7202
7697
  }
7203
7698
  }
7204
- var SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
7205
- function isSafeRepoSegment(segment) {
7206
- return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
7699
+ var SAFE_PATH_SEGMENT3 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
7700
+ function isSafeRepoSegment3(segment) {
7701
+ return SAFE_PATH_SEGMENT3.test(segment) && !segment.includes("..");
7207
7702
  }
7208
7703
  function outboxPathFor(deps, repo, issue) {
7209
7704
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
7210
7705
  const fileName = `${issue ?? "none"}.ndjson`;
7211
- return join4(deps.outboxRoot(), dirName, fileName);
7706
+ return join6(deps.outboxRoot(), dirName, fileName);
7212
7707
  }
7213
7708
  function hostFromEnv(env) {
7214
7709
  if (env.GITHUB_ACTIONS)
@@ -7219,28 +7714,34 @@ function hostFromEnv(env) {
7219
7714
  return "loop";
7220
7715
  return "cli";
7221
7716
  }
7717
+ var warnedThisProcess = false;
7718
+ function defaultStderr(message) {
7719
+ if (warnedThisProcess)
7720
+ return;
7721
+ warnedThisProcess = true;
7722
+ process.stderr.write(message);
7723
+ }
7222
7724
  function defaultDeps() {
7223
7725
  return {
7224
- outboxRoot: () => join4(GLOBAL_VINAYA_HOME, "outbox"),
7225
- home: () => homedir2(),
7726
+ outboxRoot: () => join6(GLOBAL_VINAYA_HOME, "outbox"),
7727
+ home: () => homedir3(),
7226
7728
  hostname: () => osHostname(),
7227
7729
  cwd: () => process.cwd(),
7228
7730
  now: () => new Date,
7229
7731
  env: () => process.env,
7230
7732
  resolveRepo: () => resolveRepo(),
7231
7733
  vinayaVersion: () => readVinayaVersion(),
7232
- stderr: (message) => {
7233
- process.stderr.write(message);
7234
- },
7734
+ stderr: defaultStderr,
7235
7735
  inputVersions: () => {
7236
7736
  return;
7237
- }
7737
+ },
7738
+ resolveLogDestination: defaultResolveLogDestination
7238
7739
  };
7239
7740
  }
7240
- var APPEND_OPEN_FLAGS = fsConstants2.O_WRONLY | fsConstants2.O_APPEND | fsConstants2.O_CREAT | fsConstants2.O_NOFOLLOW | fsConstants2.O_NONBLOCK;
7741
+ var APPEND_OPEN_FLAGS = fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK;
7241
7742
  function guardedAppendOpen(path) {
7242
7743
  try {
7243
- return openSync2(path, APPEND_OPEN_FLAGS, 384);
7744
+ return openSync3(path, APPEND_OPEN_FLAGS, 384);
7244
7745
  } catch {
7245
7746
  return;
7246
7747
  }
@@ -7248,7 +7749,7 @@ function guardedAppendOpen(path) {
7248
7749
  function reportRotationOverflow(backupPath, warn) {
7249
7750
  let raw;
7250
7751
  try {
7251
- raw = readFileSync3(backupPath, "utf8");
7752
+ raw = readFileSync4(backupPath, "utf8");
7252
7753
  } catch {
7253
7754
  return;
7254
7755
  }
@@ -7271,7 +7772,7 @@ function reportRotationOverflow(backupPath, warn) {
7271
7772
  }
7272
7773
  function appendLine(path, line, warn) {
7273
7774
  try {
7274
- mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
7775
+ mkdirSync3(dirname5(path), { recursive: true, mode: 448 });
7275
7776
  let fd = guardedAppendOpen(path);
7276
7777
  if (fd === undefined) {
7277
7778
  warn(`vinaya: log outbox target could not be opened (symlink, FIFO, or unwritable) — refusing: ${path}
@@ -7287,11 +7788,11 @@ function appendLine(path, line, warn) {
7287
7788
  return;
7288
7789
  }
7289
7790
  if (stat.size > OUTBOX_MAX_BYTES) {
7290
- closeSync2(fd);
7791
+ closeSync3(fd);
7291
7792
  closed = true;
7292
7793
  const backupPath = path.replace(/\.ndjson$/, ".1.ndjson");
7293
7794
  reportRotationOverflow(backupPath, warn);
7294
- renameSync(path, backupPath);
7795
+ renameSync2(path, backupPath);
7295
7796
  const rotated = guardedAppendOpen(path);
7296
7797
  if (rotated === undefined) {
7297
7798
  warn(`vinaya: log outbox target could not be reopened after rotation — refusing: ${path}
@@ -7301,10 +7802,10 @@ function appendLine(path, line, warn) {
7301
7802
  fd = rotated;
7302
7803
  closed = false;
7303
7804
  }
7304
- writeSync(fd, line);
7805
+ writeSync2(fd, line);
7305
7806
  } finally {
7306
7807
  if (!closed)
7307
- closeSync2(fd);
7808
+ closeSync3(fd);
7308
7809
  }
7309
7810
  } catch (err) {
7310
7811
  warn(`vinaya: log outbox write failed — ${err instanceof Error ? err.message : String(err)}
@@ -7313,8 +7814,8 @@ function appendLine(path, line, warn) {
7313
7814
  }
7314
7815
  function createLogSink(overrides = {}) {
7315
7816
  const deps = { ...defaultDeps(), ...overrides };
7316
- const runId = deps.env().VINAYA_RUN_ID || randomUUID();
7317
- const processId = randomUUID();
7817
+ const runId = deps.env().VINAYA_RUN_ID || randomUUID2();
7818
+ const processId = randomUUID2();
7318
7819
  let seq = 0;
7319
7820
  let warned = false;
7320
7821
  const warnOnce = (message) => {
@@ -7327,8 +7828,9 @@ function createLogSink(overrides = {}) {
7327
7828
  };
7328
7829
  let doctrineCache;
7329
7830
  const doctrine = () => {
7330
- if (doctrineCache === undefined)
7331
- doctrineCache = resolveDoctrine(deps.cwd(), deps.vinayaVersion());
7831
+ if (doctrineCache === undefined) {
7832
+ doctrineCache = withDeadline(resolveDoctrine(deps.cwd(), deps.vinayaVersion()), LOG_CONTEXT_LOOKUP_DEADLINE_MS, deps.vinayaVersion());
7833
+ }
7332
7834
  return doctrineCache;
7333
7835
  };
7334
7836
  let resolveRepoCache;
@@ -7337,6 +7839,30 @@ function createLogSink(overrides = {}) {
7337
7839
  resolveRepoCache = deps.resolveRepo();
7338
7840
  return resolveRepoCache;
7339
7841
  };
7842
+ let contextCache;
7843
+ const context = () => {
7844
+ if (contextCache === undefined) {
7845
+ const env = deps.env();
7846
+ contextCache = Promise.all([
7847
+ withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
7848
+ doctrine()
7849
+ ]).then(async ([resolved, doctrineValue]) => {
7850
+ const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
7851
+ return { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
7852
+ });
7853
+ }
7854
+ return contextCache;
7855
+ };
7856
+ let drainChain = Promise.resolve();
7857
+ const pendingWrites = new Set;
7858
+ const scheduleWebhookDrain = (issue, url, headers) => {
7859
+ drainChain = drainChain.then(() => drainOutboxToWebhook(issue, url, headers)).then(() => {
7860
+ return;
7861
+ }).catch((err) => {
7862
+ warnOnce(`vinaya: log delivery to ${url} failed — queued in the local outbox, retried on the next event: ${err instanceof Error ? err.message : String(err)}
7863
+ `);
7864
+ });
7865
+ };
7340
7866
  function log(e) {
7341
7867
  try {
7342
7868
  const env = deps.env();
@@ -7351,22 +7877,26 @@ function createLogSink(overrides = {}) {
7351
7877
  attempt: env.VINAYA_ATTEMPT,
7352
7878
  parent: env.VINAYA_PARENT_EVENT
7353
7879
  };
7354
- resolveRepoOnce().then((resolved) => {
7355
- const repo = resolved && isSafeRepoSegment(resolved.owner) && isSafeRepoSegment(resolved.repo) ? resolved : null;
7880
+ const written = context().then(({ repo, doctrine: doctrineValue, destination: resolvedDestination }) => {
7356
7881
  const header = buildHeader({
7357
7882
  now,
7358
7883
  runId,
7359
7884
  seq: mySeq,
7360
7885
  repo: repo ? `${repo.owner}/${repo.repo}` : null,
7361
7886
  vinaya: deps.vinayaVersion(),
7362
- doctrine: doctrine(),
7887
+ doctrine: doctrineValue,
7363
7888
  host,
7364
7889
  hostname: deps.hostname(),
7365
7890
  env: envFields,
7366
- eventId: randomUUID(),
7891
+ eventId: randomUUID2(),
7367
7892
  processId,
7368
7893
  inputVersions: deps.inputVersions()
7369
7894
  });
7895
+ if (resolvedDestination.kind === "none") {
7896
+ warnOnce(`vinaya: not recording — ${resolvedDestination.reason}
7897
+ `);
7898
+ return;
7899
+ }
7370
7900
  const full = { ...e, ...header };
7371
7901
  const parsed = LogEventSchema.safeParse(full);
7372
7902
  if (!parsed.success) {
@@ -7376,25 +7906,42 @@ function createLogSink(overrides = {}) {
7376
7906
  }
7377
7907
  const line = `${JSON.stringify(redact(parsed.data, deps.home()))}
7378
7908
  `;
7379
- appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
7909
+ const destination = resolvedDestination;
7910
+ if (destination.kind === "server") {
7911
+ appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
7912
+ scheduleWebhookDrain(header.subject.issue, destination.url, destination.headers);
7913
+ } else {
7914
+ appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
7915
+ }
7380
7916
  }).catch((err) => {
7381
7917
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
7382
7918
  `);
7383
7919
  });
7920
+ pendingWrites.add(written);
7921
+ written.finally(() => pendingWrites.delete(written));
7384
7922
  } catch (err) {
7385
7923
  warnOnce(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
7386
7924
  `);
7387
7925
  }
7388
7926
  }
7389
7927
  const warmup = () => {
7390
- doctrine();
7391
7928
  const originalWarn = console.warn;
7392
7929
  console.warn = () => {};
7393
7930
  resolveRepoOnce().finally(() => {
7394
7931
  console.warn = originalWarn;
7395
7932
  });
7933
+ context().catch(() => {
7934
+ return;
7935
+ });
7936
+ };
7937
+ const drain = async () => {
7938
+ if (pendingWrites.size > 0)
7939
+ await Promise.allSettled(Array.from(pendingWrites));
7940
+ await drainChain.catch(() => {
7941
+ return;
7942
+ });
7396
7943
  };
7397
- return { log, runId, warmup };
7944
+ return { log, runId, warmup, drain };
7398
7945
  }
7399
7946
  var defaultSink = createLogSink();
7400
7947
 
@@ -7425,8 +7972,8 @@ function summariseNumstat(numstat) {
7425
7972
  deleted += Number(d) || 0;
7426
7973
  }
7427
7974
  const files = `${rows.length} file${rows.length === 1 ? "" : "s"} changed`;
7428
- const bin2 = binary > 0 ? `, ${binary} binary` : "";
7429
- return `${files}, ${added} insertion${added === 1 ? "" : "s"}(+), ${deleted} deletion${deleted === 1 ? "" : "s"}(-)${bin2}`;
7975
+ const bin = binary > 0 ? `, ${binary} binary` : "";
7976
+ return `${files}, ${added} insertion${added === 1 ? "" : "s"}(+), ${deleted} deletion${deleted === 1 ? "" : "s"}(-)${bin}`;
7430
7977
  }
7431
7978
  var EVIDENCE_SUMMARY_PREFIX = "Summary: ";
7432
7979
 
@@ -7487,11 +8034,13 @@ function summaryLineIndex(maskedRegion) {
7487
8034
  var LOOP_LOG_MAX_BYTES = 8 * 1024 * 1024;
7488
8035
 
7489
8036
  // src/lib/diff-evidence.ts
7490
- import { execFileSync as execFileSync6 } from "node:child_process";
7491
- import { join as join5, relative, resolve as resolve2 } from "node:path";
8037
+ import { execFileSync as execFileSync5 } from "node:child_process";
8038
+ import { join as join8, relative, resolve as resolve2 } from "node:path";
7492
8039
 
7493
8040
  // src/lib/brief-assembly.ts
7494
- import { execFileSync as execFileSync5 } from "node:child_process";
8041
+ import { execFileSync as execFileSync4 } from "node:child_process";
8042
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync } from "node:fs";
8043
+ import { join as join7 } from "node:path";
7495
8044
 
7496
8045
  // ../../packages/sources/src/commands.ts
7497
8046
  var COMMANDS = [
@@ -7644,10 +8193,10 @@ var COMMANDS = [
7644
8193
  }
7645
8194
  ],
7646
8195
  details: [
7647
- "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.",
8196
+ "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.",
7648
8197
  "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.",
7649
- "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.",
7650
- "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."
8198
+ "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.",
8199
+ "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`)."
7651
8200
  ],
7652
8201
  status: "shipped"
7653
8202
  },
@@ -7816,48 +8365,6 @@ var COMMANDS = [
7816
8365
  ],
7817
8366
  status: "shipped"
7818
8367
  },
7819
- {
7820
- name: "log flush",
7821
- description: "Post a target Issue or PR's outbox as one or more marked comments, then truncate what the forge confirmed",
7822
- flags: [
7823
- { flag: "--issue", description: "Flush this Issue's outbox (`~/.vinaya/outbox/<owner>-<repo>/<n>.ndjson`)" },
7824
- {
7825
- flag: "--pr",
7826
- description: "Flush the Issue named by this PR's `Closes #N` line, posting the comments on the PR"
7827
- },
7828
- { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
7829
- ],
7830
- details: [
7831
- "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.",
7832
- "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.",
7833
- "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."
7834
- ],
7835
- status: "shipped"
7836
- },
7837
- {
7838
- name: "log export-artifact",
7839
- description: "Copy this run's own local outbox into a file, for the generated task-path workflow's own upload step",
7840
- flags: [],
7841
- details: [
7842
- "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.",
7843
- "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."
7844
- ],
7845
- status: "shipped"
7846
- },
7847
- {
7848
- name: "log collect-artifact",
7849
- description: "Validate a downloaded task-log artifact and publish the valid records through the existing flush path",
7850
- flags: [
7851
- { flag: "--pr", description: "The pull request this artifact belongs to" },
7852
- { flag: "--repo", description: "Expected `owner/repo` — a provenance cross-check against each record" }
7853
- ],
7854
- details: [
7855
- "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.",
7856
- "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.",
7857
- "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."
7858
- ],
7859
- status: "shipped"
7860
- },
7861
8368
  {
7862
8369
  name: "milestone create",
7863
8370
  description: "Create a GitHub Milestone from a validated body",
@@ -8187,7 +8694,7 @@ var COMMANDS = [
8187
8694
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
8188
8695
  {
8189
8696
  flag: "--pr",
8190
- description: "Flush the outbox to this PR's Issue after the dispatch — mutually exclusive with `--task`"
8697
+ description: "This dispatch's pull request number, for attribution — mutually exclusive with `--task`"
8191
8698
  },
8192
8699
  { flag: "--round", description: "Round number, for a dispatch inside a review loop" },
8193
8700
  {
@@ -8199,7 +8706,7 @@ var COMMANDS = [
8199
8706
  details: [
8200
8707
  "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.",
8201
8708
  "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`.",
8202
- "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.",
8709
+ "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.",
8203
8710
  "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."
8204
8711
  ],
8205
8712
  status: "shipped"
@@ -8219,7 +8726,8 @@ var COMMANDS = [
8219
8726
  "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> -->`.",
8220
8727
  "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.",
8221
8728
  "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.",
8222
- "Every dispatch and round transition is a log line through the Vinaya Log, flushed to the forge at each round boundary."
8729
+ "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.",
8730
+ "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)."
8223
8731
  ],
8224
8732
  status: "shipped"
8225
8733
  }
@@ -8239,7 +8747,7 @@ var StateSourceConfigSchema = z5.discriminatedUnion("kind", [
8239
8747
  z5.object({ kind: z5.literal("file"), root: z5.string().optional() })
8240
8748
  ]);
8241
8749
  // src/checks/edge-resolve.ts
8242
- import { execFileSync as execFileSync4 } from "node:child_process";
8750
+ import { execFileSync as execFileSync3 } from "node:child_process";
8243
8751
  var DIRECT_ISSUE_REF = /#(\d+)/;
8244
8752
  var issueCache = new Map;
8245
8753
  function fetchIssueState(num, repo) {
@@ -8248,7 +8756,7 @@ function fetchIssueState(num, repo) {
8248
8756
  return issueCache.get(key) ?? null;
8249
8757
  let out = null;
8250
8758
  try {
8251
- const raw = execFileSync4("gh", [
8759
+ const raw = execFileSync3("gh", [
8252
8760
  "issue",
8253
8761
  "view",
8254
8762
  String(num),
@@ -8357,9 +8865,12 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8357
8865
  }
8358
8866
 
8359
8867
  // src/lib/brief-assembly.ts
8868
+ var PACKAGE_ROOT = packageRoot(import.meta.url);
8869
+ var PACKAGED_TEMPLATE_PATH = join7(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
8870
+ var TEMPLATE_PATH = existsSync6(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join7(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
8360
8871
  function git(args) {
8361
8872
  try {
8362
- return execFileSync5("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
8873
+ return execFileSync4("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
8363
8874
  } catch {
8364
8875
  return "";
8365
8876
  }
@@ -8408,7 +8919,7 @@ function parseChangedLineRanges(diffOutput) {
8408
8919
  function fileDiffAgainst(ref, path) {
8409
8920
  let out;
8410
8921
  try {
8411
- out = execFileSync6("git", ["diff", `${ref}...HEAD`, "--", path], {
8922
+ out = execFileSync5("git", ["diff", `${ref}...HEAD`, "--", path], {
8412
8923
  encoding: "utf8",
8413
8924
  stdio: ["ignore", "pipe", "pipe"]
8414
8925
  }).trim();
@@ -8419,7 +8930,7 @@ function fileDiffAgainst(ref, path) {
8419
8930
  }
8420
8931
  function revParse(ref) {
8421
8932
  try {
8422
- return execFileSync6("git", ["rev-parse", "--verify", ref], {
8933
+ return execFileSync5("git", ["rev-parse", "--verify", ref], {
8423
8934
  encoding: "utf8",
8424
8935
  stdio: ["ignore", "pipe", "pipe"]
8425
8936
  }).trim();
@@ -8429,7 +8940,7 @@ function revParse(ref) {
8429
8940
  }
8430
8941
  function repoRoot() {
8431
8942
  try {
8432
- return execFileSync6("git", ["rev-parse", "--show-toplevel"], {
8943
+ return execFileSync5("git", ["rev-parse", "--show-toplevel"], {
8433
8944
  encoding: "utf8",
8434
8945
  stdio: ["ignore", "pipe", "pipe"]
8435
8946
  }).trim();
@@ -8440,7 +8951,7 @@ function repoRoot() {
8440
8951
  function changedFiles(base) {
8441
8952
  let out;
8442
8953
  try {
8443
- out = execFileSync6("git", ["diff", "--name-only", `${base}...HEAD`], {
8954
+ out = execFileSync5("git", ["diff", "--name-only", `${base}...HEAD`], {
8444
8955
  encoding: "utf8",
8445
8956
  stdio: ["ignore", "pipe", "pipe"]
8446
8957
  }).trim();
@@ -8465,7 +8976,7 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
8465
8976
  const relPaths = changedFiles(ref);
8466
8977
  if (relPaths === null)
8467
8978
  continue;
8468
- return { base: ref, root, files: relPaths.map((p) => join5(root, p)) };
8979
+ return { base: ref, root, files: relPaths.map((p) => join8(root, p)) };
8469
8980
  }
8470
8981
  return null;
8471
8982
  }
@@ -8521,11 +9032,13 @@ var USAGE = [
8521
9032
  `);
8522
9033
 
8523
9034
  // src/lib/pr-report-engine.ts
9035
+ var execFileAsync6 = promisify6(execFile6);
8524
9036
  var BODY_READING_CHECK_NAMES = new Set(coreCheckRegistry().filter((spec) => {
8525
9037
  const decl = spec.env?.PR_BODY;
8526
9038
  return decl === true || typeof decl === "object" && decl !== null && "optional" in decl;
8527
9039
  }).map((spec) => spec.name));
8528
9040
  var FAILING_STATUSES = new Set(["fail", "error", "timeout"]);
9041
+ var NUL = String.fromCharCode(0);
8529
9042
  function extractAgentCommandLines(prBody) {
8530
9043
  const located = locateTestPlanSection(prBody);
8531
9044
  if (!located.found)
@@ -8543,6 +9056,7 @@ function agentCommandText(line) {
8543
9056
  const idx = line.indexOf("→");
8544
9057
  return (idx === -1 ? line : line.slice(0, idx)).trim();
8545
9058
  }
9059
+ var AGENT_COMMAND_MAX_BUFFER_BYTES = 32 * 1024 * 1024;
8546
9060
  var TOKEN_ROW_REMEDY = [
8547
9061
  "Nothing here established that this host cannot meter — only that this session resolved no",
8548
9062
  "transcript of its own. Report real figures by naming your own transcript:",
@@ -8562,20 +9076,20 @@ var TOKEN_ROW_REMEDY = [
8562
9076
  var USAGE2 = "Usage: vinaya pr report [--write <body-file> | --push <pr> [--body-file <path>]] [--phase <phase>] " + "[--role <role>] [--model <id>] [--transcript <path>]";
8563
9077
 
8564
9078
  // src/lib/patch-id.ts
8565
- import { execFileSync as execFileSync7 } from "node:child_process";
9079
+ import { execFileSync as execFileSync6 } from "node:child_process";
8566
9080
  function patchIdAt(base, sha) {
8567
9081
  try {
8568
- execFileSync7("git", ["fetch", "--quiet", "origin", sha], { stdio: ["ignore", "ignore", "ignore"] });
9082
+ execFileSync6("git", ["fetch", "--quiet", "origin", sha], { stdio: ["ignore", "ignore", "ignore"] });
8569
9083
  } catch {}
8570
9084
  try {
8571
- const diff = execFileSync7("git", ["diff", `origin/${base}...${sha}`], {
9085
+ const diff = execFileSync6("git", ["diff", `origin/${base}...${sha}`], {
8572
9086
  encoding: "utf8",
8573
9087
  maxBuffer: 64 * 1024 * 1024,
8574
9088
  stdio: ["ignore", "pipe", "pipe"]
8575
9089
  });
8576
9090
  if (diff === "")
8577
9091
  return null;
8578
- const out = execFileSync7("git", ["patch-id", "--stable"], {
9092
+ const out = execFileSync6("git", ["patch-id", "--stable"], {
8579
9093
  input: diff,
8580
9094
  encoding: "utf8",
8581
9095
  stdio: ["pipe", "pipe", "pipe"]
@@ -8687,7 +9201,7 @@ function compareEvidenceBlock(resolved, resolvedHead, actualNumstat, expectedGro
8687
9201
  var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-\d+\s*-->/i;
8688
9202
  function fetchHasPriorDeveloperRound(prNumber) {
8689
9203
  try {
8690
- const out = execFileSync8("gh", ["pr", "view", String(prNumber), "--json", "comments"], {
9204
+ const out = execFileSync7("gh", ["pr", "view", String(prNumber), "--json", "comments"], {
8691
9205
  encoding: "utf8",
8692
9206
  stdio: ["ignore", "pipe", "pipe"]
8693
9207
  });
@@ -8701,7 +9215,7 @@ function fetchHasPriorDeveloperRound(prNumber) {
8701
9215
  var CHECK_NAME = "evidence-fresh";
8702
9216
  function git2(args) {
8703
9217
  try {
8704
- return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9218
+ return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8705
9219
  } catch {
8706
9220
  return "";
8707
9221
  }
@@ -8720,7 +9234,7 @@ class GitCommandError2 extends Error {
8720
9234
  }
8721
9235
  function gitStrict(args) {
8722
9236
  try {
8723
- return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9237
+ return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8724
9238
  } catch (err) {
8725
9239
  const stderr = err.stderr;
8726
9240
  throw new GitCommandError2(args, String(stderr ?? err.message).trim() || "non-zero exit");
@@ -8738,7 +9252,7 @@ function resolveMergeBase(head) {
8738
9252
  }
8739
9253
  function fetchPrRefs(prNumber) {
8740
9254
  try {
8741
- const out = execFileSync8("gh", ["pr", "view", String(prNumber), "--json", "headRefOid,baseRefName"], {
9255
+ const out = execFileSync7("gh", ["pr", "view", String(prNumber), "--json", "headRefOid,baseRefName"], {
8742
9256
  encoding: "utf8",
8743
9257
  stdio: ["ignore", "pipe", "pipe"]
8744
9258
  });