@attalabs/vinaya 0.44.0 → 0.47.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 (144) hide show
  1. package/README.md +6 -4
  2. package/dist/checks/bin/check-body-bare-digits.js +262 -201
  3. package/dist/checks/bin/check-branch-topology.js +70 -23
  4. package/dist/checks/bin/check-brief-shape.js +262 -201
  5. package/dist/checks/bin/check-changeset-coverage.js +94 -16
  6. package/dist/checks/bin/check-ci-shard-coverage.js +3 -0
  7. package/dist/checks/bin/check-closes-n.js +157 -40
  8. package/dist/checks/bin/check-coherence.js +365 -251
  9. package/dist/checks/bin/check-dispatch-readiness.js +3654 -469
  10. package/dist/checks/bin/check-doc-claims.js +262 -201
  11. package/dist/checks/bin/check-doc-coverage-push.js +272 -202
  12. package/dist/checks/bin/check-doc-coverage.js +272 -202
  13. package/dist/checks/bin/check-doctrine-no-procedures.js +262 -201
  14. package/dist/checks/bin/check-doctrine-portability.js +262 -201
  15. package/dist/checks/bin/check-evidence-fresh.js +10138 -2126
  16. package/dist/checks/bin/check-exec-bits.js +3 -0
  17. package/dist/checks/bin/check-first-push-dispatch.js +330 -230
  18. package/dist/checks/bin/check-issue-milestone-attach.js +94 -16
  19. package/dist/checks/bin/check-issue-objectives-numbering.js +262 -201
  20. package/dist/checks/bin/check-issue-parts-coverage.js +94 -16
  21. package/dist/checks/bin/check-issue-surface-globs.js +1062 -242
  22. package/dist/checks/bin/check-issue-title-grammar.js +21 -5
  23. package/dist/checks/bin/check-no-disk-state.js +5 -1
  24. package/dist/checks/bin/check-pr-premise-reassert.js +22 -2
  25. package/dist/checks/bin/check-pr-report-density.js +5 -1
  26. package/dist/checks/bin/check-principal-test-plan-wait.js +282 -207
  27. package/dist/checks/bin/check-quoted-command.js +262 -201
  28. package/dist/checks/bin/check-reader-resolvable-prose.js +262 -201
  29. package/dist/checks/bin/check-registry-gates.js +131 -34
  30. package/dist/checks/bin/check-retired-vocabulary.js +262 -201
  31. package/dist/checks/bin/check-review-gate.js +262 -201
  32. package/dist/checks/bin/check-single-plan-pr.js +5 -1
  33. package/dist/checks/bin/check-surface-scope.js +136 -38
  34. package/dist/checks/bin/check-test-plan.js +282 -207
  35. package/dist/checks/bin/check-token-collection-wired.js +3 -0
  36. package/dist/checks/bin/check-workspace-escape.js +3 -0
  37. package/dist/checks/bin/verify-coherence.js +237 -148
  38. package/dist/checks/bin/verify-dispatch.js +870 -66
  39. package/dist/checks/bin/verify-docs.js +13 -6
  40. package/dist/harness.js +57 -10
  41. package/dist/index.js +16670 -7196
  42. package/dist/lib/pre-push-cache-test-run.js +4488 -2170
  43. package/dist/lib/pre-push-changed-files.js +251 -12
  44. package/dist/lib/pre-push-mode.js +69 -19
  45. package/dist/lib/pre-push-progress-dir.js +10265 -2853
  46. package/dist/lib/pre-push-record-tests.js +67 -19
  47. package/dist/lib/pre-push-select-tests.js +520 -222
  48. package/dist/lib/push-progress-observer.js +9176 -1757
  49. package/dist/process.js +2 -0
  50. package/dist/programs/archive.js +8948 -1547
  51. package/dist/programs/audit.js +9176 -1772
  52. package/dist/programs/check.js +9248 -1845
  53. package/dist/programs/commit-msg.js +8984 -1583
  54. package/dist/programs/dev-review-loop.js +15621 -7626
  55. package/dist/programs/dispatch.js +9977 -2726
  56. package/dist/programs/log-emit.js +9011 -1660
  57. package/dist/programs/log-selftest.js +8908 -1507
  58. package/dist/programs/log-send.js +9081 -1594
  59. package/dist/programs/pr-report.js +9477 -1820
  60. package/dist/programs/pr-snapshot.js +8916 -1515
  61. package/dist/programs/pr-verify-evidence.js +9482 -1825
  62. package/dist/programs/pr.js +11773 -4082
  63. package/dist/programs/review-post.js +11141 -3496
  64. package/dist/programs/review-status.js +8997 -1533
  65. package/dist/programs/run-engine.js +22149 -18798
  66. package/dist/programs/sync.js +9030 -1629
  67. package/dist/programs/task-brief.js +10234 -1827
  68. package/dist/programs/task-sweep.js +9267 -1621
  69. package/dist/programs/task-tools-serve.js +77141 -16659
  70. package/dist/programs/tokens.js +8966 -1565
  71. package/dist/programs/waiver.js +8983 -1582
  72. package/dist/types/harness/kernel/dev-process-socket/loader/load-process.d.ts +1 -1
  73. package/dist/types/harness/processes/vinaya-strict/tools/legacy-markers.d.ts +8 -0
  74. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/brief-validation.d.ts +17 -10
  75. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/objectives.d.ts +5 -6
  76. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/premise-check.d.ts +14 -0
  77. package/dist/vinaya-strict/checks/registry.ts +2 -2
  78. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +8 -0
  79. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +1 -1
  80. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +2 -2
  81. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +30 -20
  82. package/dist/vinaya-strict/executing/developer/reference.md +5 -3
  83. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +29 -7
  84. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +4 -4
  85. package/dist/vinaya-strict/integration/process/process-integration.ts +5 -1
  86. package/dist/vinaya-strict/process.yaml +6 -1
  87. package/dist/vinaya-strict/thinking/plan-reviewer/doctrine.md +68 -0
  88. package/dist/vinaya-strict/thinking/plan-reviewer/grants.yaml +19 -0
  89. package/dist/vinaya-strict/thinking/plan-reviewer/output.schema.json +388 -0
  90. package/dist/vinaya-strict/thinking/planner/doctrine.md +4 -1
  91. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +10 -2
  92. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +5 -1
  93. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +198 -34
  94. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +120 -193
  95. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +629 -15
  96. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +726 -62
  97. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +505 -5
  98. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +636 -21
  99. package/package.json +3 -2
  100. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  101. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  102. package/studio-standalone/apps/vinaya-studio/.next/prerender-manifest.json +3 -3
  103. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  104. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  105. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  106. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  107. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  108. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  109. package/studio-standalone/apps/vinaya-studio/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  110. package/studio-standalone/apps/vinaya-studio/.next/server/app/milestones/page_client-reference-manifest.js +1 -1
  111. package/studio-standalone/apps/vinaya-studio/.next/server/app/page_client-reference-manifest.js +1 -1
  112. package/studio-standalone/apps/vinaya-studio/.next/server/app/tasks/page_client-reference-manifest.js +1 -1
  113. package/studio-standalone/apps/vinaya-studio/.next/server/chunks/209.js +2 -2
  114. package/studio-standalone/apps/vinaya-studio/.next/server/chunks/951.js +1 -1
  115. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  116. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  117. package/studio-standalone/apps/vinaya-studio/.next/server/preview-props.json +3 -3
  118. package/studio-standalone/apps/vinaya-studio/.next/server/server-reference-manifest.json +1 -1
  119. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/151-c365f0ef8268ad13.js +1 -0
  120. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/19-aa314f13784dcc58.js +4 -0
  121. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/{layout-dfa2186095e797bd.js → layout-f038e8deecb2bf5f.js} +1 -1
  122. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/milestones/{page-2fffb49104860a15.js → page-12314f4deb06a414.js} +1 -1
  123. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/{page-6ae258f663623b2a.js → page-7a06aa3cdd046fa8.js} +1 -1
  124. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/tasks/{page-2fffb49104860a15.js → page-12314f4deb06a414.js} +1 -1
  125. package/studio-standalone/apps/vinaya-studio/.next/static/css/8eb5ed5b65b9692e.css +1 -0
  126. package/studio-standalone/apps/vinaya-studio/log-follow.mjs +708 -93
  127. package/studio-standalone/apps/vinaya-studio/log-sync-folder-source.mjs +699 -84
  128. package/studio-standalone/apps/vinaya-studio/studio-server.mjs +4692 -3116
  129. package/vinaya-strict/artifacts/templates/brief-template.md +6 -0
  130. package/vinaya-strict/artifacts/templates/issue-rationale-template.md +7 -3
  131. package/vinaya-strict/artifacts/templates/pr-report-template.md +1 -1
  132. package/vinaya-strict/doctrine/contracts/planner-developer.md +4 -3
  133. package/vinaya-strict/doctrine/enforcement.md +4 -4
  134. package/vinaya-strict/doctrine/roles/principal.md +1 -1
  135. package/vinaya-strict/doctrine/state-machine.md +7 -2
  136. package/vinaya-strict/executing/developer/reference.md +5 -3
  137. package/vinaya-strict/thinking/plan-reviewer/doctrine.md +68 -0
  138. package/vinaya-strict/thinking/planner/doctrine.md +4 -1
  139. package/vinaya-strict/thinking/planner/reference.md +30 -9
  140. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/151-23bea4cac9687151.js +0 -1
  141. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/853-1d5548ff3a55a75f.js +0 -4
  142. package/studio-standalone/apps/vinaya-studio/.next/static/css/fb16828fc3128d4c.css +0 -1
  143. /package/studio-standalone/apps/vinaya-studio/.next/static/{_r9iZDxlkoek85d_3oaxL → bJrgAp9Kl4JsCUYkeAYez}/_buildManifest.js +0 -0
  144. /package/studio-standalone/apps/vinaya-studio/.next/static/{_r9iZDxlkoek85d_3oaxL → bJrgAp9Kl4JsCUYkeAYez}/_ssgManifest.js +0 -0
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -23,6 +24,7 @@ var __toCommonJS = (from) => {
23
24
  return entry;
24
25
  };
25
26
  var __moduleCache;
27
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
26
28
  var __returnValue = (v) => v;
27
29
  function __exportSetter(name, newValue) {
28
30
  this[name] = __returnValue.bind(null, newValue);
@@ -47,6 +49,7 @@ var __esm = (fn, res, err) => () => {
47
49
  throw err[0];
48
50
  return res;
49
51
  };
52
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
50
53
 
51
54
  // ../../harness/processes/vinaya-strict/tools/task-contract/forge/parse-rationale-deps.ts
52
55
  function splitSlugQualifiedEdge(edge) {
@@ -392,6 +395,23 @@ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
392
395
  }
393
396
  throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
394
397
  }
398
+ async function ghLabelIssueCountsAsync(owner, repo, labelQuery) {
399
+ const stdout = await runAsync([
400
+ "api",
401
+ "graphql",
402
+ "--paginate",
403
+ "-f",
404
+ `query=${LABEL_ISSUE_COUNTS_QUERY.replace("$labelQuery", JSON.stringify(labelQuery))}`,
405
+ "-f",
406
+ `owner=${owner}`,
407
+ "-f",
408
+ `name=${repo}`,
409
+ "--jq",
410
+ ".data.repository.labels.nodes[] | {name, open: .open.totalCount, total: .all.totalCount}"
411
+ ]);
412
+ return stdout.split(`
413
+ `).filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
414
+ }
395
415
  function issueListByLabelArgs(owner, repo, label) {
396
416
  return [
397
417
  "issue",
@@ -425,7 +445,14 @@ async function ghIssueListByAnyLabelAsync(owner, repo, labels) {
425
445
  const perLabel = await Promise.all(labels.map((l) => ghIssueListByLabelAsync(owner, repo, l)));
426
446
  return dedupeByNumber(perLabel.flat());
427
447
  }
428
- var execFileAsync, systemEnv, MAX_PER_PAGE = 100, MAX_PAGES = 100;
448
+ var execFileAsync, systemEnv, MAX_PER_PAGE = 100, MAX_PAGES = 100, LABEL_ISSUE_COUNTS_QUERY = `query($owner: String!, $name: String!, $endCursor: String) {
449
+ repository(owner: $owner, name: $name) {
450
+ labels(first: 100, after: $endCursor, query: $labelQuery) {
451
+ pageInfo { hasNextPage endCursor }
452
+ nodes { name open: issues(states: OPEN) { totalCount } all: issues { totalCount } }
453
+ }
454
+ }
455
+ }`;
429
456
  var init_gh = __esm(() => {
430
457
  execFileAsync = promisify(execFile);
431
458
  systemEnv = {
@@ -766,7 +793,7 @@ function commentMarkerFamily(name) {
766
793
  function anchorAlternation(spellings) {
767
794
  return `(?:${spellings.map((spelling) => spelling.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`;
768
795
  }
769
- var REGION_PREFIX, PROVENANCE_HEADING, CLAIM_ANCHOR, QUOTES_FILE_ANCHOR, VENDOR_EXAMPLE_ANCHOR, COMMENT_MARKER_PREFIX, FROZEN_BRIEF_MARKER, DEVELOPER_ROUND_MARKER, DEVELOPER_STOP_MARKER, LOOP_PUBLISHED_MARKER, LOOP_PAUSED_MARKER, LOOP_UNPUSHED_WORK_RESUME_MARKER, PRINCIPAL_RULING_MARKER, OBJECTIVES_VERSION_MARKER, DEFERRED_FINDINGS_MARKER, COMMENT_MARKER_PREFIX_CURRENT, COMMENT_MARKER_PREFIXES, COMMENT_MARKER_PREFIX_PATTERN, REGION_PREFIX_CURRENT, REGION_PREFIXES, PROVENANCE_HEADINGS, CLAIM_ANCHORS, QUOTES_FILE_ANCHORS, VENDOR_EXAMPLE_ANCHORS;
796
+ var REGION_PREFIX, PROVENANCE_HEADING, CLAIM_ANCHOR, QUOTES_FILE_ANCHOR, VENDOR_EXAMPLE_ANCHOR, COMMENT_MARKER_PREFIX, FROZEN_BRIEF_MARKER, DEVELOPER_ROUND_MARKER, DEVELOPER_STOP_MARKER, LOOP_PUBLISHED_MARKER, LOOP_PAUSED_MARKER, LOOP_UNPUSHED_WORK_RESUME_MARKER, PRINCIPAL_RULING_MARKER, OBJECTIVES_VERSION_MARKER, DOCUMENTATION_EDIT_MARKER, DEFERRED_FINDINGS_MARKER, COMMENT_MARKER_PREFIX_CURRENT, COMMENT_MARKER_PREFIXES, COMMENT_MARKER_PREFIX_PATTERN, REGION_PREFIX_CURRENT, REGION_PREFIXES, PROVENANCE_HEADINGS, CLAIM_ANCHORS, QUOTES_FILE_ANCHORS, VENDOR_EXAMPLE_ANCHORS;
770
797
  var init_legacy_markers = __esm(() => {
771
798
  REGION_PREFIX = { old: "AEG", current: "VINAYA" };
772
799
  PROVENANCE_HEADING = {
@@ -788,6 +815,7 @@ var init_legacy_markers = __esm(() => {
788
815
  LOOP_UNPUSHED_WORK_RESUME_MARKER = commentMarkerFamily("loop:unpushed-work-resume");
789
816
  PRINCIPAL_RULING_MARKER = commentMarkerFamily("principal:ruling");
790
817
  OBJECTIVES_VERSION_MARKER = commentMarkerFamily("objectives");
818
+ DOCUMENTATION_EDIT_MARKER = commentMarkerFamily("documentation");
791
819
  DEFERRED_FINDINGS_MARKER = commentMarkerFamily("deferred-findings");
792
820
  COMMENT_MARKER_PREFIX_CURRENT = COMMENT_MARKER_PREFIX.current;
793
821
  COMMENT_MARKER_PREFIXES = [COMMENT_MARKER_PREFIX.current, COMMENT_MARKER_PREFIX.old];
@@ -949,6 +977,15 @@ function parsePremiseBlock(prBody) {
949
977
  }
950
978
  return assertions;
951
979
  }
980
+ function declaresNewFilesOnly(prBody) {
981
+ const searchIn = anchoredRegion(prBody, "PREMISE", REGION_PREFIXES) ?? prBody;
982
+ const lines = searchIn.split(/\r?\n/).map((l) => l.trim());
983
+ const header = lines.findIndex(isPremiseHeader);
984
+ if (header === -1)
985
+ return false;
986
+ const first = lines.slice(header + 1).find((l) => l !== "");
987
+ return first === NEW_FILES_ONLY_PREMISE && parsePremiseBlock(prBody).length === 0;
988
+ }
952
989
  function premiseBlockText(prBody) {
953
990
  const searchIn = anchoredRegion(prBody, "PREMISE", REGION_PREFIXES) ?? prBody;
954
991
  const lines = searchIn.split(/\r?\n/);
@@ -996,7 +1033,7 @@ function checkPremises(assertions, fileReader) {
996
1033
  }
997
1034
  return { pass: failures.length === 0, failures };
998
1035
  }
999
- var ASSERTION_KINDS, PREMISE_LINE;
1036
+ var ASSERTION_KINDS, NEW_FILES_ONLY_PREMISE = "- (no pin — every file this task names is new, so no existing content can be pinned)", PREMISE_LINE;
1000
1037
  var init_premise_check = __esm(() => {
1001
1038
  init_anchored_region();
1002
1039
  init_legacy_markers();
@@ -1138,13 +1175,16 @@ function checkSurfaceMap(prBody) {
1138
1175
  function checkDocUpdateList(prBody) {
1139
1176
  return headingCheck(prBody, "(?:documentation|doc)[- ]update(?:\\s+list)?", "Documentation-update list");
1140
1177
  }
1141
- function checkWorktreeStep0(prBody) {
1142
- if (/git worktree add/.test(prBody) || /cd \.worktrees\//.test(prBody) || /bun install --frozen-lockfile/.test(prBody))
1178
+ function checkWorktreeStep0(body) {
1179
+ const prBody = body.replaceAll(`\r
1180
+ `, `
1181
+ `);
1182
+ if (/git worktree add/.test(prBody) || /cd \.worktrees\//.test(prBody) || /bun install --frozen-lockfile/.test(prBody) || /\*\*Step 0 \(mandatory, verbatim\):\*\*\n\n```\n(?:npm ci|pnpm install --frozen-lockfile|yarn install --frozen-lockfile)\n```/.test(prBody))
1143
1183
  return { status: "pass", errors: [] };
1144
1184
  return {
1145
1185
  status: "fail",
1146
1186
  errors: [
1147
- "brief-validation worktree Step 0: no `git worktree add`, `cd .worktrees/`, or `bun install --frozen-lockfile` command found in the PR body."
1187
+ "brief-validation worktree Step 0: no `git worktree add`, `cd .worktrees/`, or frozen-lockfile install (`bun install --frozen-lockfile`, `npm ci`, `pnpm install --frozen-lockfile`, `yarn install --frozen-lockfile`) found in the PR body."
1148
1188
  ]
1149
1189
  };
1150
1190
  }
@@ -1586,6 +1626,7 @@ var init_doctrine_map = __esm(() => {
1586
1626
  { key: "roles/developer.md", source: "executing/developer/doctrine.md", role: "developer", ships: true },
1587
1627
  { key: "roles/developer/reference.md", source: "executing/developer/reference.md", ships: true },
1588
1628
  { key: "roles/operator.md", source: "executing/operator/doctrine.md", role: "operator", ships: true },
1629
+ { key: "roles/plan-reviewer.md", source: "thinking/plan-reviewer/doctrine.md", role: "plan-reviewer", ships: true },
1589
1630
  { key: "roles/planner.md", source: "thinking/planner/doctrine.md", role: "planner", ships: true },
1590
1631
  { key: "roles/planner/reference.md", source: "thinking/planner/reference.md", ships: true },
1591
1632
  { key: "roles/principal.md", source: "doctrine/roles/principal.md", role: "principal", ships: true },
@@ -2708,7 +2749,13 @@ function isMechanicallyNeutralDiff(diffText, path) {
2708
2749
  }
2709
2750
  return sawChange;
2710
2751
  }
2711
- function evaluateC5(changed, docOwnersContent, prBody, fileExists, waiverActive, getDiff) {
2752
+ function prBodyGiven(env = process.env) {
2753
+ return env.PR_BODY !== undefined || env.PR_BODY_FILE !== undefined;
2754
+ }
2755
+ function owedNeutralNotes(result) {
2756
+ return result.notes.filter((n) => n.startsWith(DOC_NEUTRAL_OWED_PREFIX));
2757
+ }
2758
+ function evaluateC5(changed, docOwnersContent, prBody, fileExists, waiverActive, getDiff, bodyGiven = true) {
2712
2759
  const out = { errors: [], notes: [] };
2713
2760
  if (docOwnersContent === null)
2714
2761
  return out;
@@ -2748,24 +2795,28 @@ function evaluateC5(changed, docOwnersContent, prBody, fileExists, waiverActive,
2748
2795
  }
2749
2796
  if (changed.includes(pointerPath))
2750
2797
  continue;
2798
+ const evidenced = () => getDiff !== undefined && matchedFiles.every((f) => {
2799
+ const diff = getDiff(f);
2800
+ return diff !== null && isMechanicallyNeutralDiff(diff, f);
2801
+ });
2751
2802
  const declared = neutrals.find((n) => n.surface === b.pointer);
2752
2803
  if (declared) {
2753
- const evidenced = getDiff !== undefined && matchedFiles.every((f) => {
2754
- const diff = getDiff(f);
2755
- return diff !== null && isMechanicallyNeutralDiff(diff, f);
2756
- });
2757
- if (evidenced) {
2804
+ if (evidenced()) {
2758
2805
  out.notes.push(`C5 doc-neutral: ${b.pointer} not required for ${DOC_OWNERS_PATH}:${b.lineNum} (glob \`${b.glob}\`) — declared neutral ("${declared.note}"), diff of ${matchedFiles.join(", ")} confirmed comment/whitespace-only.`);
2759
2806
  continue;
2760
2807
  }
2761
2808
  out.errors.push(`C5 doc-neutral-unverified: ${DOC_OWNERS_PATH}:${b.lineNum} (glob \`${b.glob}\` → ${b.pointer}) declared \`Doc-neutral: ${b.pointer} — ${declared.note}\`, but the diff of ${matchedFiles.join(", ")} contains changes beyond comments/whitespace. Update ${pointerPath}, or have a principal apply the \`${WAIVER_LABEL}\` label.`);
2762
2809
  continue;
2763
2810
  }
2811
+ if (!bodyGiven && evidenced()) {
2812
+ out.notes.push(`${DOC_NEUTRAL_OWED_PREFIX} ${b.pointer} not required in this run for ${DOC_OWNERS_PATH}:${b.lineNum} (glob \`${b.glob}\`) — no pull request body was given, and the diff of ${matchedFiles.join(", ")} is comment/whitespace-only. The pull request body owes \`Doc-neutral: ${b.pointer} — <why>\`.`);
2813
+ continue;
2814
+ }
2764
2815
  out.errors.push(`C5 doc-coverage: code change matched ${DOC_OWNERS_PATH}:${b.lineNum} (glob \`${b.glob}\` → ${b.pointer}), but ${pointerPath} is not in the PR diff. Update it, declare \`Doc-neutral: ${b.pointer} — <why>\` if the change is genuinely mechanically-neutral, or have a principal apply the \`${WAIVER_LABEL}\` label.`);
2765
2816
  }
2766
2817
  return out;
2767
2818
  }
2768
- var DOC_OWNERS_PATH = ".vinaya/doc-owners", SEPARATOR, LANGUAGE_COMMENT_PREFIXES;
2819
+ var DOC_OWNERS_PATH = ".vinaya/doc-owners", SEPARATOR, LANGUAGE_COMMENT_PREFIXES, DOC_NEUTRAL_OWED_PREFIX = "C5 doc-neutral-owed:";
2769
2820
  var init_doc_owners = __esm(() => {
2770
2821
  init_file_classify();
2771
2822
  init_waiver_label();
@@ -2820,6 +2871,20 @@ var init_protected_paths = __esm(() => {
2820
2871
  ];
2821
2872
  });
2822
2873
 
2874
+ // ../../harness/processes/vinaya-strict/tools/task-contract/test-plan-proof.ts
2875
+ function stripObjectiveIdSpans(text) {
2876
+ return text.replace(ITEM_IDS_SPAN_RE, "").trim();
2877
+ }
2878
+ var ID_LIST, LINE_IDS_RE, ITEM_IDS_SPAN_RE;
2879
+ var init_test_plan_proof = __esm(() => {
2880
+ init_brief_validation();
2881
+ init_objectives();
2882
+ init_test_plan_section();
2883
+ ID_LIST = String.raw`O\d+(?:\s*,\s*O\d+)*`;
2884
+ LINE_IDS_RE = new RegExp(String.raw`\(\s*(${ID_LIST})\s*\)\s*$`);
2885
+ ITEM_IDS_SPAN_RE = new RegExp(String.raw`(?<!\`)(\`+)\s*\(?\s*(${ID_LIST})\s*\)?\s*\1(?!\`)`, "g");
2886
+ });
2887
+
2823
2888
  // ../../harness/processes/vinaya-strict/tools/task-contract/issue-validation.ts
2824
2889
  function hasRationaleField(body, labelPattern) {
2825
2890
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -3018,7 +3083,7 @@ function checkPartsCiteDefinedObjectives(body) {
3018
3083
  return { status: errors.length > 0 ? "fail" : "pass", errors };
3019
3084
  }
3020
3085
  function liveCommand(text) {
3021
- const trimmed = text.trim();
3086
+ const trimmed = stripObjectiveIdSpans(text);
3022
3087
  const span = /^(`+)(.+)\1$/.exec(trimmed);
3023
3088
  return span ? span[2].trim() : trimmed;
3024
3089
  }
@@ -3127,9 +3192,19 @@ function namedPathsIn(text) {
3127
3192
  function boundaryPinnedFiles(body) {
3128
3193
  const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
3129
3194
  const excluded = new Set(namedPathsIn(boundaryOutText(body)));
3130
- return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
3195
+ const named = [...namedPathsIn(boundary), ...rootFilesPinnedIn(boundary)];
3196
+ return [...new Set(named)].filter((p) => looksLikeFilePath(p) && !excluded.has(p));
3197
+ }
3198
+ function rootFilesPinnedIn(boundary) {
3199
+ const start = boundary.search(/\bPinned files\s*:/i);
3200
+ if (start === -1)
3201
+ return [];
3202
+ const clause = boundary.slice(start);
3203
+ const out = BOUNDARY_OUT_RE.exec(clause);
3204
+ const pinned = out ? clause.slice(0, out.index) : clause;
3205
+ return [...pinned.matchAll(ROOT_FILE_RE_GLOBAL)].map((m) => m[1]);
3131
3206
  }
3132
- var RATIONALE_FIELDS, DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale", SINGLE_FIX_OPTIONAL_FIELDS, OBJECTIVES_SINCE_ISSUE = 404, PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3, ISSUE_PART_LINE_RE, ISSUE_LIVE_LINE_RE, TYPE_LABEL_IDS, PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" }), MESSAGE_VALUE_COUNT_MAX = 5, MESSAGE_VALUE_MAX = 64, DOC_PATH_RE, DOC_PATH_RE_GLOBAL, RATIONALE_PATH_RE_GLOBAL, DEFAULT_COLLISION_THRESHOLD = 3, BOUNDARY_OUT_RE, FILE_EXTENSIONS, CI_SHARD_DIR = "apps/cli/tests/ci-shards", CI_SHARD_PROBE;
3207
+ var RATIONALE_FIELDS, DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale", SINGLE_FIX_OPTIONAL_FIELDS, OBJECTIVES_SINCE_ISSUE = 404, PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3, ISSUE_PART_LINE_RE, ISSUE_LIVE_LINE_RE, TYPE_LABEL_IDS, PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" }), MESSAGE_VALUE_COUNT_MAX = 5, MESSAGE_VALUE_MAX = 64, DOC_PATH_RE, DOC_PATH_RE_GLOBAL, RATIONALE_PATH_RE_GLOBAL, DEFAULT_COLLISION_THRESHOLD = 3, BOUNDARY_OUT_RE, FILE_EXTENSIONS, ROOT_FILE_RE_GLOBAL, CI_SHARD_DIR = "apps/cli/tests/ci-shards", CI_SHARD_PROBE;
3133
3208
  var init_issue_validation = __esm(() => {
3134
3209
  init_parse_rationale_deps();
3135
3210
  init_labels();
@@ -3143,11 +3218,13 @@ var init_issue_validation = __esm(() => {
3143
3218
  init_derive_section7();
3144
3219
  init_doctrine_map();
3145
3220
  init_objectives();
3221
+ init_waiver_label();
3146
3222
  init_issue_documentation();
3147
3223
  init_touched_path();
3148
3224
  init_protected_paths();
3149
3225
  init_quoted_command();
3150
3226
  init_test_plan_section();
3227
+ init_test_plan_proof();
3151
3228
  RATIONALE_FIELDS = [
3152
3229
  { name: "Boundary", pattern: "Boundary" },
3153
3230
  { name: "Sizing", pattern: "Sizing" },
@@ -3191,71 +3268,3227 @@ var init_issue_validation = __esm(() => {
3191
3268
  "html",
3192
3269
  "css"
3193
3270
  ]);
3271
+ ROOT_FILE_RE_GLOBAL = /`([\w.@-]+\.(?:md|mdx|txt|json|jsonc|ts|tsx|js|jsx|mjs|cjs|mts|cts|yml|yaml|toml|lock|html|css|scss|sh|py|rb|go|rs|xml|ini|cfg|conf))`/g;
3194
3272
  CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
3195
3273
  });
3196
3274
 
3197
- // ../../harness/kernel/gates/checks/contract.ts
3198
- function emitCheckError(error) {
3199
- process.stderr.write(`${JSON.stringify(error)}
3200
- `);
3201
- }
3202
- var CHECK_SCHEMA_VERSION = 1;
3275
+ // ../../harness/kernel/log/schema.ts
3276
+ import {
3277
+ CODE_TOKEN_PATTERN,
3278
+ CONFIDENCE_REASON_MAX_LENGTH,
3279
+ CustomEventSchema,
3280
+ DevReviewLoopEventSchema,
3281
+ DispatchEventSchema,
3282
+ EffectEventSchema,
3283
+ FlowSchema,
3284
+ ForgeOpSchema,
3285
+ ForgeWriteEventSchema,
3286
+ GateEventSchema,
3287
+ GateOutcomeSchema,
3288
+ HandoffEventSchema,
3289
+ HeaderMetaSchema,
3290
+ HeaderMetaV1Schema,
3291
+ HeaderMetaV2Schema,
3292
+ HeaderMetaV3Schema,
3293
+ HeaderMetaV4Schema,
3294
+ HeaderSchema,
3295
+ HOST_VALUES,
3296
+ HostSchema,
3297
+ InputVersionsSchema,
3298
+ LineageSchema,
3299
+ LogEventSchema,
3300
+ OperationEventSchema,
3301
+ OperationResultSchema,
3302
+ ProvenanceSchema,
3303
+ processAndRunnerOf,
3304
+ REVIEW_FINDING_DESCRIPTION_MAX_LENGTH,
3305
+ ROLE_NAME_PATTERN,
3306
+ RoleAttemptEventSchema,
3307
+ RoleAttemptOutcomeSchema,
3308
+ RoleSchema,
3309
+ UsageEventSchema,
3310
+ WorkSchema
3311
+ } from "@attalabs/vinaya-log-sdk";
3312
+ var init_schema = () => {};
3203
3313
 
3204
- // ../../harness/kernel/log/custom.ts
3314
+ // ../../harness/kernel/connectors/checkpoint/control-store/records.ts
3205
3315
  import { z } from "zod";
3206
- var CUSTOM_EVENT_NAME_PATTERN, CUSTOM_EVENT_NAME_MAX_LENGTH = 64, CUSTOM_EVENT_RESERVED_NAMESPACE = "vinaya", CUSTOM_EVENT_MAX_FIELDS = 20, CUSTOM_FIELD_NAME_PATTERN, CUSTOM_FIELD_NAME_MAX_LENGTH = 64, CUSTOM_TEXT_MAX_LENGTH = 500, CUSTOM_WORD_PATTERN, CUSTOM_WORD_MAX_LENGTH = 64, CUSTOM_FIELD_MAX_WORDS = 50, CustomFieldTypeSchema, CustomEventDeclarationsSchema;
3207
- var init_custom = __esm(() => {
3208
- CUSTOM_EVENT_NAME_PATTERN = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_.]*$/;
3209
- CUSTOM_FIELD_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
3210
- CUSTOM_WORD_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
3211
- CustomFieldTypeSchema = z.union([z.enum(["text", "number", "boolean"]), z.array(z.string())]);
3212
- CustomEventDeclarationsSchema = z.record(z.string(), z.object({
3213
- fields: z.record(z.string(), CustomFieldTypeSchema)
3214
- }).strict()).superRefine((events, ctx) => {
3215
- for (const [name, declaration] of Object.entries(events)) {
3216
- const refuse = (message, path = []) => {
3217
- ctx.addIssue({
3218
- code: z.ZodIssueCode.custom,
3219
- path: [name, ...path],
3220
- message: `logs.events "${name}": ${message}`
3221
- });
3222
- };
3223
- if (name.length > CUSTOM_EVENT_NAME_MAX_LENGTH) {
3224
- refuse(`the name must be at most ${CUSTOM_EVENT_NAME_MAX_LENGTH} characters`);
3316
+ var isoTimestamp, taskId, epochNumber, RunRecordSchema, InputRecordSchema, OwnershipRecordSchema, TransitionRecordSchema, ManifestRecordSchema, roundHeadIdentity, LoopBudgetsSchema, LoopStateRecordSchema, EffectRecordSchema, EscalationRecordSchema, ResolutionRecordSchema, ExecutionRoundMirrorRecordSchema;
3317
+ var init_records = __esm(() => {
3318
+ isoTimestamp = z.string().min(1);
3319
+ taskId = z.number().int().positive();
3320
+ epochNumber = z.number().int().nonnegative();
3321
+ RunRecordSchema = z.object({
3322
+ version: z.literal(1),
3323
+ kind: z.literal("run"),
3324
+ task: taskId,
3325
+ runId: z.string().min(1),
3326
+ pid: z.number().int().positive(),
3327
+ host: z.string().min(1),
3328
+ startedAt: isoTimestamp,
3329
+ childStartedAt: z.string().min(1).nullable().optional(),
3330
+ childCommand: z.string().min(1).nullable().optional()
3331
+ }).strict();
3332
+ InputRecordSchema = z.object({
3333
+ version: z.literal(1),
3334
+ kind: z.literal("input"),
3335
+ task: taskId,
3336
+ runId: z.string().min(1),
3337
+ source: z.union([z.literal("fresh"), z.literal("resume")]),
3338
+ pr: z.number().int().positive().nullable(),
3339
+ round: z.number().int().nonnegative(),
3340
+ recordedAt: isoTimestamp
3341
+ }).strict();
3342
+ OwnershipRecordSchema = z.object({
3343
+ version: z.literal(1),
3344
+ kind: z.literal("ownership"),
3345
+ task: taskId,
3346
+ epoch: epochNumber,
3347
+ ownerId: z.string().min(1),
3348
+ pid: z.number().int().positive(),
3349
+ host: z.string().min(1),
3350
+ acquiredAt: isoTimestamp
3351
+ }).strict();
3352
+ TransitionRecordSchema = z.object({
3353
+ version: z.literal(1),
3354
+ kind: z.literal("transition"),
3355
+ task: taskId,
3356
+ epoch: epochNumber,
3357
+ seq: z.number().int().nonnegative(),
3358
+ from: z.string().min(1),
3359
+ to: z.string().min(1),
3360
+ detail: z.string().optional(),
3361
+ at: isoTimestamp
3362
+ }).strict();
3363
+ ManifestRecordSchema = z.object({
3364
+ version: z.literal(1),
3365
+ kind: z.literal("manifest"),
3366
+ task: taskId,
3367
+ round: epochNumber,
3368
+ repository: z.string().min(1),
3369
+ pr: z.number().int().positive(),
3370
+ branch: z.string().min(1),
3371
+ baseSha: z.string().min(1).nullable(),
3372
+ headSha: z.string().min(1),
3373
+ briefHash: z.string().min(1).nullable(),
3374
+ objectivesVersion: z.string().min(1).nullable(),
3375
+ rulingOrdinal: epochNumber,
3376
+ manifestVersion: z.literal(2).optional(),
3377
+ pauseBoundRuling: z.object({
3378
+ rulingId: z.string().min(1),
3379
+ pauseId: z.string().min(1),
3380
+ contentDigest: z.string().min(1)
3381
+ }).strict().nullable().optional(),
3382
+ policyDigest: z.string().min(1),
3383
+ recordedAt: isoTimestamp
3384
+ }).strict();
3385
+ roundHeadIdentity = z.object({ round: z.number().int().positive(), head: z.string().min(1) }).strict();
3386
+ LoopBudgetsSchema = z.object({
3387
+ mechanicalRetries: z.number().int().nonnegative(),
3388
+ reviewRounds: z.number().int().nonnegative(),
3389
+ infrastructureRetries: z.number().int().nonnegative()
3390
+ }).strict();
3391
+ LoopStateRecordSchema = z.object({
3392
+ version: z.literal(1),
3393
+ kind: z.literal("loop_state"),
3394
+ task: taskId,
3395
+ round: z.number().int().positive(),
3396
+ phase: z.string().min(1),
3397
+ pauseReason: z.string().min(1).nullable(),
3398
+ budgets: LoopBudgetsSchema,
3399
+ heldResult: roundHeadIdentity.nullable(),
3400
+ deliveredFindings: roundHeadIdentity.nullable(),
3401
+ repeatMemory: z.object({
3402
+ blockingFindings: z.array(z.string()),
3403
+ lastFailure: z.object({ signature: z.string(), message: z.string(), developerAttemptedSince: z.boolean().optional() }).nullable()
3404
+ }).strict().optional(),
3405
+ developerHandoff: z.object({
3406
+ findings: z.array(z.object({ id: z.string().min(1), description: z.string().min(1) }).strict()),
3407
+ failingChecks: z.array(z.string().min(1))
3408
+ }).strict().optional(),
3409
+ publicationExpectedBase: z.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
3410
+ taskStartedAt: isoTimestamp.optional(),
3411
+ phaseMs: z.record(z.string(), z.number().nonnegative()).optional(),
3412
+ recordedAt: isoTimestamp
3413
+ }).strict();
3414
+ EffectRecordSchema = z.object({
3415
+ version: z.literal(1),
3416
+ kind: z.literal("effect"),
3417
+ task: taskId,
3418
+ key: z.string().min(1),
3419
+ operation: z.string().min(1),
3420
+ target: z.string().min(1),
3421
+ inputVersion: z.number().int().nonnegative(),
3422
+ payloadDigest: z.string().min(1),
3423
+ status: z.union([z.literal("started"), z.literal("verified"), z.literal("uncertain")]),
3424
+ url: z.string().optional(),
3425
+ recordedAt: isoTimestamp
3426
+ }).strict();
3427
+ EscalationRecordSchema = z.object({
3428
+ version: z.literal(1),
3429
+ kind: z.literal("escalation"),
3430
+ task: taskId,
3431
+ escalationId: z.string().min(1),
3432
+ round: epochNumber,
3433
+ head: z.string().min(1),
3434
+ branch: z.string().min(1),
3435
+ pr: z.number().int().positive().nullable(),
3436
+ runId: z.string().min(1),
3437
+ pid: z.number().int().positive(),
3438
+ host: z.string().min(1),
3439
+ agent: z.string().min(1).optional(),
3440
+ reason: z.string().min(1),
3441
+ detail: z.string().optional(),
3442
+ evidence: z.string().optional(),
3443
+ attemptedRecovery: z.string().min(1),
3444
+ requestedDecision: z.string().min(1),
3445
+ recipient: z.string().min(1),
3446
+ briefHash: z.string().min(1).nullable(),
3447
+ objectivesVersion: z.string().min(1).nullable(),
3448
+ rulingOrdinal: epochNumber,
3449
+ policyDigest: z.string().min(1),
3450
+ recordedAt: isoTimestamp
3451
+ }).strict();
3452
+ ResolutionRecordSchema = z.object({
3453
+ version: z.literal(1),
3454
+ kind: z.literal("resolution"),
3455
+ task: taskId,
3456
+ escalationId: z.string().min(1),
3457
+ decision: z.union([z.literal("resume"), z.literal("cancel")]),
3458
+ authenticatedBy: z.string().min(1),
3459
+ authenticatedFrom: z.string().min(1),
3460
+ consumedAt: isoTimestamp
3461
+ }).strict();
3462
+ ExecutionRoundMirrorRecordSchema = z.object({
3463
+ version: z.literal(1),
3464
+ kind: z.literal("execution_round"),
3465
+ task: taskId,
3466
+ repository: z.string().min(1),
3467
+ threadId: z.string().min(1),
3468
+ checkpointId: z.string().min(1),
3469
+ round: z.number().int().positive(),
3470
+ recordedAt: isoTimestamp
3471
+ }).strict();
3472
+ });
3473
+
3474
+ // ../../harness/kernel/connectors/checkpoint/control-store/local.ts
3475
+ import {
3476
+ closeSync,
3477
+ constants as fsConstants,
3478
+ existsSync,
3479
+ fsyncSync,
3480
+ linkSync,
3481
+ lstatSync,
3482
+ mkdirSync,
3483
+ openSync,
3484
+ readdirSync,
3485
+ readFileSync,
3486
+ renameSync,
3487
+ statSync,
3488
+ unlinkSync,
3489
+ writeSync
3490
+ } from "node:fs";
3491
+ import { dirname, join, resolve, sep } from "node:path";
3492
+ function isErrnoException(err, code) {
3493
+ return typeof err === "object" && err !== null && err.code === code;
3494
+ }
3495
+ function isTrustedDirStat(stat, ownUid, trustedOverflowUid) {
3496
+ if (typeof ownUid !== "number")
3497
+ return true;
3498
+ if (stat.uid !== ownUid && stat.uid !== 0 && stat.uid !== trustedOverflowUid)
3499
+ return false;
3500
+ const worldWritable = (stat.mode & 2) !== 0;
3501
+ const sticky = (stat.mode & 512) !== 0;
3502
+ return !worldWritable || sticky;
3503
+ }
3504
+ function currentUid() {
3505
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
3506
+ }
3507
+ function uidMapLeavesRootUnmapped(uidMap) {
3508
+ const lines = uidMap.split(`
3509
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
3510
+ if (lines.length === 0)
3511
+ return false;
3512
+ for (const line of lines) {
3513
+ const fields = line.split(/\s+/);
3514
+ if (fields.length !== 3 || !fields.every((field) => /^\d+$/.test(field)))
3515
+ return false;
3516
+ const inside = Number(fields[0]);
3517
+ const count = Number(fields[2]);
3518
+ if (inside === 0 && count > 0)
3519
+ return false;
3520
+ }
3521
+ return true;
3522
+ }
3523
+ function readTrustedOverflowUid(readFile) {
3524
+ try {
3525
+ if (!uidMapLeavesRootUnmapped(readFile("/proc/self/uid_map")))
3526
+ return;
3527
+ const overflow = readFile("/proc/sys/kernel/overflowuid").trim();
3528
+ return /^\d+$/.test(overflow) ? Number(overflow) : undefined;
3529
+ } catch {
3530
+ return;
3531
+ }
3532
+ }
3533
+ function processTrustedOverflowUid() {
3534
+ cachedTrustedOverflowUid ??= { value: readTrustedOverflowUid((path) => readFileSync(path, "utf8")) };
3535
+ return cachedTrustedOverflowUid.value;
3536
+ }
3537
+ function isAtOrBelowTrustedRoot(index, rootSegmentCount) {
3538
+ return index >= rootSegmentCount - 1;
3539
+ }
3540
+ function segmentTrustedOverflowUid(index, rootSegmentCount, trustedOverflowUid) {
3541
+ return isAtOrBelowTrustedRoot(index, rootSegmentCount) ? undefined : trustedOverflowUid;
3542
+ }
3543
+ function mkdirNoSymlinks(dir, mode, trustedRoot) {
3544
+ const absolute = resolve(dir);
3545
+ const rootSegments = resolve(trustedRoot).split(sep).filter((s) => s.length > 0);
3546
+ const segments = absolute.split(sep).filter((s) => s.length > 0);
3547
+ const ownUid = currentUid();
3548
+ const trustedOverflowUid = typeof ownUid === "number" ? processTrustedOverflowUid() : undefined;
3549
+ let current = absolute.startsWith(sep) ? sep : "";
3550
+ const trustedRootPrefix = rootSegments.length === 0 ? sep : `${sep}${rootSegments.join(sep)}${sep}`;
3551
+ segments.forEach((segment, index) => {
3552
+ current = current === "" || current === sep ? `${current}${segment}` : `${current}${sep}${segment}`;
3553
+ const atOrBelowTrustedRoot = isAtOrBelowTrustedRoot(index, rootSegments.length);
3554
+ const overflowUid = segmentTrustedOverflowUid(index, rootSegments.length, trustedOverflowUid);
3555
+ let created = false;
3556
+ try {
3557
+ mkdirSync(current, { mode });
3558
+ created = true;
3559
+ } catch (err) {
3560
+ if (!isErrnoException(err, "EEXIST"))
3561
+ throw err;
3562
+ }
3563
+ if (created && current.startsWith(trustedRootPrefix))
3564
+ syncDirectory(dirname(current));
3565
+ const stat = lstatSync(current);
3566
+ if (stat.isSymbolicLink()) {
3567
+ if (atOrBelowTrustedRoot) {
3568
+ throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists and is not a real directory (a symlink or a file)`);
3225
3569
  }
3226
- if (!CUSTOM_EVENT_NAME_PATTERN.test(name)) {
3227
- refuse("the name must be `<namespace>.<event>` — lowercase letters, digits and `_`, a dot between them");
3228
- } else if (name.split(".")[0] === CUSTOM_EVENT_RESERVED_NAMESPACE) {
3229
- refuse(`the \`${CUSTOM_EVENT_RESERVED_NAMESPACE}.\` namespace is reserved for Vinaya's own events`);
3570
+ let real;
3571
+ try {
3572
+ real = statSync(current);
3573
+ } catch (err) {
3574
+ throw new Error(`control-store: refusing to create a run directory through ${current} — it is a symlink whose target could not be resolved: ${err instanceof Error ? err.message : String(err)}`);
3230
3575
  }
3231
- const fieldEntries = Object.entries(declaration.fields);
3232
- if (fieldEntries.length > CUSTOM_EVENT_MAX_FIELDS) {
3233
- refuse(`at most ${CUSTOM_EVENT_MAX_FIELDS} fields may be declared (found ${fieldEntries.length})`, ["fields"]);
3576
+ if (!real.isDirectory()) {
3577
+ throw new Error(`control-store: refusing to create a run directory through ${current} — it is a symlink that does not resolve to a real directory`);
3234
3578
  }
3235
- for (const [field, type] of fieldEntries) {
3236
- if (field.length > CUSTOM_FIELD_NAME_MAX_LENGTH || !CUSTOM_FIELD_NAME_PATTERN.test(field)) {
3237
- refuse(`field "${field}": a field name is lowercase letters, digits and \`_\`, starting with a letter, at most ${CUSTOM_FIELD_NAME_MAX_LENGTH} characters`, ["fields", field]);
3238
- }
3239
- if (typeof type === "string")
3240
- continue;
3241
- if (type.length === 0) {
3242
- refuse(`field "${field}": a list of words must name at least one word`, ["fields", field]);
3243
- }
3244
- if (type.length > CUSTOM_FIELD_MAX_WORDS) {
3245
- refuse(`field "${field}": a list of words may name at most ${CUSTOM_FIELD_MAX_WORDS}`, ["fields", field]);
3246
- }
3247
- const bad = type.filter((w) => w.length > CUSTOM_WORD_MAX_LENGTH || !CUSTOM_WORD_PATTERN.test(w));
3248
- if (bad.length > 0) {
3249
- refuse(`field "${field}": a listed word is lowercase letters, digits, \`_\` and \`-\`, at most ${CUSTOM_WORD_MAX_LENGTH} characters`, ["fields", field]);
3250
- }
3251
- if (new Set(type).size !== type.length) {
3252
- refuse(`field "${field}": a list of words names a word twice`, ["fields", field]);
3253
- }
3579
+ if (!isTrustedDirStat(real, ownUid, overflowUid)) {
3580
+ throw new Error(`control-store: refusing to create a run directory through ${current} — its symlink target is owned by uid ${real.uid} with mode ${(real.mode & 4095).toString(8)}, neither this process's own user nor a safe shared mode`);
3254
3581
  }
3582
+ return;
3583
+ }
3584
+ if (!stat.isDirectory()) {
3585
+ throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists and is not a real directory (a symlink or a file)`);
3586
+ }
3587
+ if (!isTrustedDirStat(stat, ownUid, overflowUid)) {
3588
+ throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists, owned by uid ${stat.uid} with mode ${(stat.mode & 4095).toString(8)}, neither this process's own user nor a safe shared mode`);
3255
3589
  }
3256
3590
  });
3591
+ }
3592
+ function syncDirectory(dir) {
3593
+ const fd = openSync(dir, fsConstants.O_RDONLY);
3594
+ try {
3595
+ fsyncSync(fd);
3596
+ } finally {
3597
+ closeSync(fd);
3598
+ }
3599
+ }
3600
+ var cachedTrustedOverflowUid, CONTROL_AREA_DIRNAME = "control";
3601
+ var init_local = __esm(() => {
3602
+ init_records();
3603
+ });
3604
+
3605
+ // ../../harness/kernel/connectors/checkpoint/control-store/migration.ts
3606
+ var init_migration = __esm(() => {
3607
+ init_local();
3608
+ });
3609
+ // ../../harness/kernel/connectors/checkpoint/control-store/index.ts
3610
+ var init_control_store = __esm(() => {
3611
+ init_records();
3612
+ init_local();
3613
+ init_migration();
3614
+ });
3615
+
3616
+ // ../../harness/kernel/adapters/code-host/github/resolve-repo.ts
3617
+ import { execFile as execFile2 } from "node:child_process";
3618
+ import { promisify as promisify2 } from "node:util";
3619
+ async function resolveRepo(exec = defaultExec) {
3620
+ if (cached !== undefined)
3621
+ return cached;
3622
+ const fromEnv = process.env.VINAYA_REPO;
3623
+ if (fromEnv) {
3624
+ const parsed = parseOwnerRepo(fromEnv);
3625
+ if (parsed) {
3626
+ cached = parsed;
3627
+ return cached;
3628
+ }
3629
+ }
3630
+ if (inflight)
3631
+ return inflight;
3632
+ inflight = (async () => {
3633
+ try {
3634
+ const { stdout } = await exec();
3635
+ cached = parseGitRemoteUrl(stdout.trim());
3636
+ return cached;
3637
+ } catch (err) {
3638
+ const message = err instanceof Error ? err.message : String(err);
3639
+ console.warn(`[resolve-repo] resolveRepo: git remote lookup failed (will retry): ${message}`);
3640
+ return null;
3641
+ } finally {
3642
+ inflight = undefined;
3643
+ }
3644
+ })();
3645
+ return inflight;
3646
+ }
3647
+ function parseGitRemoteUrl(url) {
3648
+ const ssh = url.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/);
3649
+ if (ssh?.[1] && ssh[2])
3650
+ return { owner: ssh[1], repo: ssh[2] };
3651
+ const https = url.match(/^https?:\/\/(?:[^@]+@)?github\.com\/([^/]+)\/(.+?)(?:\.git)?\/?$/);
3652
+ if (https?.[1] && https[2])
3653
+ return { owner: https[1], repo: https[2] };
3654
+ return null;
3655
+ }
3656
+ function parseOwnerRepo(value) {
3657
+ const match = value.match(/^([^/]+)\/(.+)$/);
3658
+ if (!match?.[1] || !match[2])
3659
+ return null;
3660
+ return { owner: match[1], repo: match[2] };
3661
+ }
3662
+ var execFileAsync2, systemEnv2, defaultExec = () => execFileAsync2("git", ["remote", "get-url", "origin"], { env: systemEnv2, timeout: 5000 }), cached, inflight;
3663
+ var init_resolve_repo = __esm(() => {
3664
+ execFileAsync2 = promisify2(execFile2);
3665
+ systemEnv2 = {
3666
+ ...process.env,
3667
+ PATH: [process.env.PATH, "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].filter(Boolean).join(":")
3668
+ };
3669
+ });
3670
+
3671
+ // ../../harness/kernel/log/roles.ts
3672
+ function registerRole(name, role) {
3673
+ roles.set(name, role);
3674
+ }
3675
+ function registerTitle(name, title) {
3676
+ titles.set(name, title);
3677
+ }
3678
+ function isRole(value) {
3679
+ return value !== undefined && roles.has(value);
3680
+ }
3681
+ function lookupRole(name) {
3682
+ return roles.get(name);
3683
+ }
3684
+ function lookupTitle(name) {
3685
+ return roles.get(name)?.title ?? titles.get(name);
3686
+ }
3687
+ function registeredRoles() {
3688
+ return [...roles.keys()];
3689
+ }
3690
+ var roles, titles;
3691
+ var init_roles = __esm(() => {
3692
+ roles = new Map;
3693
+ titles = new Map;
3694
+ });
3695
+
3696
+ // ../../harness/kernel/log/envelope.ts
3697
+ import { createHash as createHash3 } from "node:crypto";
3698
+ function actorIdFromEnv(role) {
3699
+ return role === undefined || role === "" ? null : role;
3700
+ }
3701
+ function lineageFieldFromEnv(value) {
3702
+ return value === undefined || value === "" ? null : value;
3703
+ }
3704
+ function attemptFromEnv(value) {
3705
+ if (value === undefined || value === "")
3706
+ return null;
3707
+ const n = Number(value);
3708
+ return Number.isInteger(n) ? n : null;
3709
+ }
3710
+ function provenanceFor(input) {
3711
+ if (input.provenance)
3712
+ return input.provenance;
3713
+ if (issueFromTask(input.env.task) === null && (input.branchIssue ?? null) !== null)
3714
+ return "unavailable";
3715
+ if (input.env.role || input.env.task)
3716
+ return "env_correlated";
3717
+ return "unavailable";
3718
+ }
3719
+ function issueFromTask(task) {
3720
+ if (task === undefined || task === "")
3721
+ return null;
3722
+ const n = Number(task);
3723
+ return Number.isInteger(n) ? n : null;
3724
+ }
3725
+ function roundFromEnv(round) {
3726
+ if (round === undefined || round === "")
3727
+ return;
3728
+ const n = Number(round);
3729
+ return Number.isInteger(n) ? n : undefined;
3730
+ }
3731
+ function prFromEnv(pr) {
3732
+ if (pr === undefined || pr === "")
3733
+ return;
3734
+ const n = Number(pr);
3735
+ return Number.isInteger(n) && n > 0 ? n : undefined;
3736
+ }
3737
+ function buildHeader(input) {
3738
+ const role = isRole(input.env.role) ? input.env.role : "unattributed";
3739
+ const round = roundFromEnv(input.env.round);
3740
+ const pr = prFromEnv(input.env.pr);
3741
+ const subject = {
3742
+ issue: issueFromTask(input.env.task) ?? input.branchIssue ?? null,
3743
+ role,
3744
+ ...round !== undefined ? { round } : {},
3745
+ ...pr !== undefined ? { pr } : {},
3746
+ ...input.subject ?? {}
3747
+ };
3748
+ const issue = subject.issue;
3749
+ return {
3750
+ meta: {
3751
+ schema: 4,
3752
+ ts: input.now.toISOString(),
3753
+ run_id: input.runId,
3754
+ seq: input.seq,
3755
+ repo: input.repo,
3756
+ vinaya: input.vinaya,
3757
+ doctrine: input.doctrine,
3758
+ host: input.host,
3759
+ machine: createHash3("sha256").update(input.hostname).digest("hex"),
3760
+ event_id: input.eventId,
3761
+ process_id: input.processId,
3762
+ actor_id: actorIdFromEnv(input.env.role),
3763
+ lineage: {
3764
+ run: lineageFieldFromEnv(input.env.run),
3765
+ attempt: attemptFromEnv(input.env.attempt),
3766
+ parent: lineageFieldFromEnv(input.env.parent)
3767
+ },
3768
+ input_versions: {
3769
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
3770
+ objectives_version: input.inputVersions?.objectivesVersion ?? null,
3771
+ brief_hash: input.inputVersions?.briefHash ?? null,
3772
+ ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
3773
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
3774
+ policy_digest: input.inputVersions?.policyDigest ?? null
3775
+ },
3776
+ provenance: provenanceFor(input),
3777
+ work: {
3778
+ ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
3779
+ repo: input.repo,
3780
+ change: pr === undefined ? null : String(pr),
3781
+ revision: input.revision ?? null
3782
+ },
3783
+ flow: {
3784
+ id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
3785
+ version: lineageFieldFromEnv(input.env.flowVersion)
3786
+ },
3787
+ runtime: lineageFieldFromEnv(input.env.runtime),
3788
+ process: {
3789
+ id: lineageFieldFromEnv(input.env.processId) ?? "vinaya",
3790
+ version: lineageFieldFromEnv(input.env.processVersion),
3791
+ digest: lineageFieldFromEnv(input.env.processDigest)
3792
+ },
3793
+ runner: {
3794
+ id: lineageFieldFromEnv(input.env.runnerId) ?? "standalone",
3795
+ version: lineageFieldFromEnv(input.env.runnerVersion)
3796
+ },
3797
+ source: lineageFieldFromEnv(input.env.source)
3798
+ },
3799
+ subject
3800
+ };
3801
+ }
3802
+ var init_envelope = __esm(() => {
3803
+ init_roles();
3257
3804
  });
3258
3805
 
3806
+ // ../../harness/kernel/log/store.ts
3807
+ import {
3808
+ classifyStoredLine,
3809
+ createFixtureStore,
3810
+ KNOWN_SCHEMA_VERSIONS,
3811
+ readPageFrom,
3812
+ recordIdentity
3813
+ } from "@attalabs/vinaya-log-sdk";
3814
+ var init_store = () => {};
3815
+
3816
+ // ../../harness/kernel/log/redact.ts
3817
+ import { redact } from "@attalabs/vinaya-log-sdk";
3818
+ var init_redact = () => {};
3819
+
3820
+ // ../../harness/kernel/log/deferred-sink-factory.ts
3821
+ function registerDeferredLogSinkFactory(load) {
3822
+ deferred = load;
3823
+ }
3824
+ function loadDeferredLogSinkFactory() {
3825
+ return deferred?.();
3826
+ }
3827
+ var deferred;
3828
+
3829
+ // ../../harness/kernel/config/loader/config-provider.ts
3830
+ function installConfigProvider(provider) {
3831
+ installed = provider;
3832
+ }
3833
+ function configProvider() {
3834
+ if (!installed)
3835
+ throw new Error(NO_CONFIG_PROVIDER_MESSAGE);
3836
+ return installed;
3837
+ }
3838
+ var installed = null, NO_CONFIG_PROVIDER_MESSAGE = "no configuration provider is installed — a composition root must call installConfigProvider() before any configuration read";
3839
+
3840
+ // ../../harness/kernel/config/schema/config-schema.ts
3841
+ import { isAbsolute } from "node:path";
3842
+ import { z as z2 } from "zod";
3843
+ function checkEntrySchema(fields) {
3844
+ return z2.object(fields).superRefine((entry, ctx) => {
3845
+ const env = entry.env;
3846
+ if (!env)
3847
+ return;
3848
+ for (const [key, value] of Object.entries(env)) {
3849
+ if (typeof value !== "object" || value === null || !("anyOf" in value))
3850
+ continue;
3851
+ const members = value.anyOf;
3852
+ if (new Set(members).size !== members.length) {
3853
+ ctx.addIssue({
3854
+ code: z2.ZodIssueCode.custom,
3855
+ message: `env.${key}.anyOf has duplicate members`,
3856
+ path: ["env", key, "anyOf"]
3857
+ });
3858
+ }
3859
+ if (!members.includes(key)) {
3860
+ ctx.addIssue({
3861
+ code: z2.ZodIssueCode.custom,
3862
+ message: `env.${key}.anyOf must include "${key}" itself as a member`,
3863
+ path: ["env", key, "anyOf"]
3864
+ });
3865
+ }
3866
+ }
3867
+ });
3868
+ }
3869
+ function isSafeRepoRelPath(p) {
3870
+ if (p.length === 0)
3871
+ return false;
3872
+ if (p.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(p))
3873
+ return false;
3874
+ return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
3875
+ }
3876
+ function hookBlockPathRule(prefixes) {
3877
+ const isCanonical = (p) => prefixes.some((prefix) => p.startsWith(prefix) && p.length > prefix.length);
3878
+ const schema = SafeRepoRelPath.refine(isCanonical, {
3879
+ message: `must start with one of ${prefixes.join(", ")} (byte-exact, case-sensitive)`
3880
+ });
3881
+ return { isCanonical, schema };
3882
+ }
3883
+ function managedManifestSchemas(agentVendors, hookBlockPrefixes) {
3884
+ const block = z2.object({
3885
+ path: hookBlockPathRule(hookBlockPrefixes).schema,
3886
+ marker: z2.string(),
3887
+ comment: z2.enum(["hash", "html"])
3888
+ });
3889
+ const manifest = z2.object({
3890
+ version: z2.number().int().positive(),
3891
+ files: z2.array(SafeRepoRelPath),
3892
+ blocks: z2.array(block),
3893
+ labels: z2.array(z2.string()),
3894
+ agents: z2.array(z2.enum(agentVendors)).optional()
3895
+ });
3896
+ return { block, manifest };
3897
+ }
3898
+ function logsSchema(events) {
3899
+ return z2.object({
3900
+ folder: z2.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
3901
+ url: z2.string().url().optional(),
3902
+ otlp: z2.object({
3903
+ url: z2.string().url().regex(/^https?:\/\//i),
3904
+ headers: z2.record(z2.string()).optional()
3905
+ }).strict().optional(),
3906
+ headers: z2.record(z2.string()).optional(),
3907
+ readHeaders: z2.record(z2.string()).optional(),
3908
+ keepDays: z2.number({ invalid_type_error: "must be a whole number of days" }).int({ message: "must be a whole number of days" }).min(1, { message: "must be at least 1" }).optional(),
3909
+ events: events.optional()
3910
+ }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
3911
+ message: "logs: set at most one of folder/url"
3912
+ }).refine((v) => v.headers === undefined || v.url !== undefined, {
3913
+ message: "logs: headers requires url"
3914
+ }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
3915
+ message: "logs: readHeaders requires url"
3916
+ }).or(z2.literal(false)).optional();
3917
+ }
3918
+ function kernelConfigFragment(leaves) {
3919
+ return {
3920
+ rings: z2.object({
3921
+ ring1_forgeWriteInterception: z2.boolean(),
3922
+ ring2_asyncAudits: z2.boolean()
3923
+ }).optional(),
3924
+ checks: z2.record(z2.string(), checkEntrySchema(leaves.checkEntryFields)).optional(),
3925
+ managed: managedManifestSchemas(leaves.agentVendors, leaves.hookBlockPrefixes).manifest.optional(),
3926
+ ci: z2.object({ setup: z2.string().min(1) }).optional(),
3927
+ logPublish: z2.unknown().refine((v) => v === undefined, {
3928
+ message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
3929
+ }),
3930
+ runtimeDir: z2.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
3931
+ runner: z2.enum(["standalone", "atta-engine"]).optional(),
3932
+ logs: logsSchema(leaves.logEvents)
3933
+ };
3934
+ }
3935
+ function resolveRuntimeDirSetting(config) {
3936
+ return config?.runtimeDir ?? null;
3937
+ }
3938
+ function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
3939
+ const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
3940
+ return anchored !== null && anchored === localRuntimeDir ? anchored : null;
3941
+ }
3942
+ function resolveLogsSetting(config) {
3943
+ const raw = config?.logs;
3944
+ if (!raw)
3945
+ return null;
3946
+ if (raw.url !== undefined)
3947
+ return { url: raw.url, headers: raw.headers };
3948
+ if (raw.folder !== undefined)
3949
+ return { folder: raw.folder };
3950
+ return null;
3951
+ }
3952
+ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
3953
+ const anchored = resolveLogsSetting(trustAnchorConfig);
3954
+ if (!anchored)
3955
+ return null;
3956
+ if ("url" in local)
3957
+ return "url" in anchored && anchored.url === local.url ? anchored : null;
3958
+ return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
3959
+ }
3960
+ function resolveLogsHeaderValues(headers, env) {
3961
+ if (!headers)
3962
+ return;
3963
+ const resolved = {};
3964
+ for (const [key, value] of Object.entries(headers)) {
3965
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
3966
+ }
3967
+ return resolved;
3968
+ }
3969
+ var EnvEntrySchema, KERNEL_CHECK_ENTRY_FIELDS, SafeRepoRelPath, KERNEL_CONFIG_REFINEMENTS;
3970
+ var init_config_schema = __esm(() => {
3971
+ EnvEntrySchema = z2.union([
3972
+ z2.literal(true),
3973
+ z2.object({ optional: z2.literal(true) }),
3974
+ z2.object({ anyOf: z2.array(z2.string()).min(2) }),
3975
+ z2.string()
3976
+ ]);
3977
+ KERNEL_CHECK_ENTRY_FIELDS = {
3978
+ run: z2.string(),
3979
+ scope: z2.enum(["diff", "full"]),
3980
+ include: z2.array(z2.string()).optional(),
3981
+ args: z2.array(z2.string()).optional(),
3982
+ timeoutMs: z2.number().optional(),
3983
+ env: z2.record(z2.string(), EnvEntrySchema).optional(),
3984
+ requiresOpenPr: z2.boolean().optional(),
3985
+ ownWorkflow: z2.boolean().optional(),
3986
+ validates: z2.enum(["body", "issue"]).optional(),
3987
+ advisory: z2.literal(true).optional()
3988
+ };
3989
+ SafeRepoRelPath = z2.string().refine(isSafeRepoRelPath, {
3990
+ message: "must be a repo-root-relative path with no `..` segment or absolute root"
3991
+ });
3992
+ KERNEL_CONFIG_REFINEMENTS = [];
3993
+ });
3994
+
3995
+ // ../../harness/kernel/run-paths.ts
3996
+ import { execFileSync as execFileSync2 } from "node:child_process";
3997
+ import { chmodSync, existsSync as existsSync2, realpathSync as realpathSync2 } from "node:fs";
3998
+ import { dirname as dirname2, join as join2, resolve as resolvePath } from "node:path";
3999
+ function isSafeRepoSegment(segment) {
4000
+ return SAFE_PATH_SEGMENT.test(segment) && !segment.includes("..");
4001
+ }
4002
+ function repoSegment(repo) {
4003
+ if (!repo || !isSafeRepoSegment(repo.owner) || !isSafeRepoSegment(repo.repo))
4004
+ return "unresolved";
4005
+ return `${repo.owner}-${repo.repo}`;
4006
+ }
4007
+ function defaultRuntimeDir(repo, home = configProvider().homeDir) {
4008
+ return join2(home, "runtime", repoSegment(repo));
4009
+ }
4010
+ function resolveRuntimeDir(input) {
4011
+ const local = resolveRuntimeDirSetting(input.localConfig);
4012
+ if (local === null)
4013
+ return defaultRuntimeDir(input.repo, input.home);
4014
+ if (isInsideRepo(local, input.repoRoot))
4015
+ return defaultRuntimeDir(input.repo, input.home);
4016
+ if (!input.unattended)
4017
+ return local;
4018
+ const anchored = resolveTrustAnchorRuntimeDir(local, input.trustAnchorConfig ?? null);
4019
+ return anchored ?? defaultRuntimeDir(input.repo, input.home);
4020
+ }
4021
+ function isInsideRepo(candidate, repoRoot) {
4022
+ if (!repoRoot)
4023
+ return false;
4024
+ const root = resolvePath(repoRoot);
4025
+ const target = resolvePath(candidate);
4026
+ return target === root || target.startsWith(`${root}/`);
4027
+ }
4028
+ function tasksExecutionRoot(runtimeDir) {
4029
+ return join2(runtimeDir, TASKS_EXECUTION_DIRNAME);
4030
+ }
4031
+ function runPath(runtimeDir, scope, location) {
4032
+ const dir = scopeDir(runtimeDir, scope);
4033
+ switch (location.area) {
4034
+ case "task":
4035
+ return location.file ? join2(dir, location.file) : dir;
4036
+ case "control": {
4037
+ const controlDir = join2(dir, RUN_AREA_DIRNAMES.control);
4038
+ return location.file ? join2(controlDir, location.file) : controlDir;
4039
+ }
4040
+ case "rounds":
4041
+ return join2(dir, RUN_AREA_DIRNAMES.rounds);
4042
+ case "round": {
4043
+ const roundDir = join2(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
4044
+ return location.file ? join2(roundDir, location.file) : roundDir;
4045
+ }
4046
+ case "developer": {
4047
+ const developerDir = join2(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
4048
+ return location.file ? join2(developerDir, location.file) : developerDir;
4049
+ }
4050
+ default: {
4051
+ const areaDir = join2(dir, RUN_AREA_DIRNAMES[location.area]);
4052
+ return location.file ? join2(areaDir, location.file) : areaDir;
4053
+ }
4054
+ }
4055
+ }
4056
+ function scopeDir(runtimeDir, scope) {
4057
+ if (typeof scope === "object" && "plan" in scope) {
4058
+ if (!isSafeRepoSegment(scope.plan)) {
4059
+ throw new Error(`a plan scope names a tranche slug that is not a safe path segment: ${JSON.stringify(scope.plan)}`);
4060
+ }
4061
+ return join2(runtimeDir, PLAN_DRAFTS_DIRNAME, scope.plan);
4062
+ }
4063
+ return join2(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
4064
+ }
4065
+ function scopeSegment(scope) {
4066
+ if (scope === "unscoped")
4067
+ return "unscoped";
4068
+ if (typeof scope === "number")
4069
+ return String(scope);
4070
+ return `pr-${scope.pr}`;
4071
+ }
4072
+ function scopeFromSegment(segment) {
4073
+ if (/^\d+$/.test(segment))
4074
+ return Number(segment);
4075
+ const pr = /^pr-(\d+)$/.exec(segment);
4076
+ if (pr)
4077
+ return { pr: Number(pr[1]) };
4078
+ return "unscoped";
4079
+ }
4080
+ function isUnattendedProcess(env = process.env) {
4081
+ return env[UNATTENDED_ENV_KEY] === "1" || (env.VINAYA_ROLE ?? "") !== "";
4082
+ }
4083
+ function runtimeDirForRepo(repo) {
4084
+ const key = repoSegment(repo);
4085
+ if (memoized?.key === key)
4086
+ return memoized.value;
4087
+ const value = resolveRuntimeDirUncached(repo);
4088
+ memoized = { key, value };
4089
+ return value;
4090
+ }
4091
+ async function runtimeDirForRepoAsync(repo) {
4092
+ const key = repoSegment(repo);
4093
+ if (memoized?.key === key)
4094
+ return memoized.value;
4095
+ const inputs = runtimeDirInputs();
4096
+ if (typeof inputs === "string")
4097
+ return inputs;
4098
+ const value = resolveRuntimeDir({
4099
+ repo,
4100
+ ...inputs.base,
4101
+ trustAnchorConfig: inputs.needsAnchor ? await configProvider().loadTrustAnchorConfigAsync() : null
4102
+ });
4103
+ memoized = { key, value };
4104
+ return value;
4105
+ }
4106
+ function resolveRuntimeDirUncached(repo) {
4107
+ const inputs = runtimeDirInputs();
4108
+ if (typeof inputs === "string")
4109
+ return inputs;
4110
+ return resolveRuntimeDir({
4111
+ repo,
4112
+ ...inputs.base,
4113
+ trustAnchorConfig: inputs.needsAnchor ? configProvider().loadTrustAnchorConfig() : null
4114
+ });
4115
+ }
4116
+ function runtimeDirInputs() {
4117
+ const handedDown = process.env[RUNTIME_DIR_ENV_KEY];
4118
+ if (handedDown)
4119
+ return handedDown;
4120
+ const localConfig = configProvider().loadConfig();
4121
+ const unattended = isUnattendedProcess();
4122
+ return {
4123
+ base: { localConfig, unattended, repoRoot: repoRootSync() },
4124
+ needsAnchor: unattended && resolveRuntimeDirSetting(localConfig) !== null
4125
+ };
4126
+ }
4127
+ function repoRootSync(start = process.cwd()) {
4128
+ let dir;
4129
+ try {
4130
+ dir = realpathSync2(start);
4131
+ } catch {
4132
+ return null;
4133
+ }
4134
+ for (;; ) {
4135
+ if (existsSync2(join2(dir, ".git")))
4136
+ return dir;
4137
+ const parent = dirname2(dir);
4138
+ if (parent === dir)
4139
+ return null;
4140
+ dir = parent;
4141
+ }
4142
+ }
4143
+ function resolveRepoSync() {
4144
+ const fromEnv = process.env.VINAYA_REPO;
4145
+ if (fromEnv) {
4146
+ const m = /^([^/]+)\/(.+)$/.exec(fromEnv);
4147
+ if (m?.[1] && m[2])
4148
+ return { owner: m[1], repo: m[2] };
4149
+ }
4150
+ let url;
4151
+ try {
4152
+ url = execFileSync2("git", ["remote", "get-url", "origin"], {
4153
+ encoding: "utf-8",
4154
+ stdio: ["ignore", "pipe", "pipe"]
4155
+ }).trim();
4156
+ } catch {
4157
+ return null;
4158
+ }
4159
+ const ssh = /^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/.exec(url);
4160
+ if (ssh?.[1] && ssh[2])
4161
+ return { owner: ssh[1], repo: ssh[2] };
4162
+ const https = /^https?:\/\/(?:[^@]+@)?github\.com\/([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(url);
4163
+ if (https?.[1] && https[2])
4164
+ return { owner: https[1], repo: https[2] };
4165
+ return null;
4166
+ }
4167
+ function runtimeDirForThisRepo() {
4168
+ if (memoizedThisRepo !== null)
4169
+ return memoizedThisRepo;
4170
+ memoizedThisRepo = runtimeDirForRepo(resolveRepoSync());
4171
+ return memoizedThisRepo;
4172
+ }
4173
+ function ensureRunDir(dir, runtimeDir) {
4174
+ mkdirNoSymlinks(dir, 448, runtimeDir);
4175
+ chmodSync(dir, 448);
4176
+ }
4177
+ var TASKS_EXECUTION_DIRNAME = "tasks-execution", RUN_AREA_DIRNAMES, PLAN_DRAFTS_DIRNAME = "plan-drafts", SAFE_PATH_SEGMENT, UNATTENDED_ENV_KEY = "VINAYA_UNATTENDED", RUNTIME_DIR_ENV_KEY = "VINAYA_RUNTIME_DIR", memoized = null, memoizedThisRepo = null;
4178
+ var init_run_paths = __esm(() => {
4179
+ init_control_store();
4180
+ init_config_schema();
4181
+ RUN_AREA_DIRNAMES = {
4182
+ control: CONTROL_AREA_DIRNAME,
4183
+ sessions: "sessions",
4184
+ hooks: "hooks",
4185
+ output: "output",
4186
+ rounds: "rounds"
4187
+ };
4188
+ SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
4189
+ });
4190
+
4191
+ // ../../harness/kernel/log/local-copy-writer.ts
4192
+ import { join as join3 } from "node:path";
4193
+ import {
4194
+ DEFAULT_KEEP_DAYS,
4195
+ defaultRuntimeDir as sdkDefaultRuntimeDir,
4196
+ resolveSettings as sdkResolveSettings,
4197
+ sendLocalCopy
4198
+ } from "@attalabs/vinaya-log-sdk";
4199
+ function recordingTurnedOff(inputs, vinayaHome, repository) {
4200
+ const resolved = sdkResolveSettings({
4201
+ repoRoot: inputs.cwd,
4202
+ ...repository === undefined ? {} : { repository },
4203
+ vinayaHome
4204
+ });
4205
+ if (resolved.ok && resolved.settings.logs === false)
4206
+ return true;
4207
+ return inputs.unattended && inputs.defaultBranchLogs?.()?.logs === false;
4208
+ }
4209
+ function resolveLocalCopySettings(inputs, repository) {
4210
+ const vinayaHome = join3(inputs.home, ".vinaya");
4211
+ if ((inputs.handedRuntimeDir || inputs.unattended) && recordingTurnedOff(inputs, vinayaHome, repository))
4212
+ return;
4213
+ if (inputs.handedRuntimeDir)
4214
+ return { folder: join3(inputs.handedRuntimeDir, "logs"), keepDays: DEFAULT_KEEP_DAYS };
4215
+ if (inputs.unattended)
4216
+ return { folder: join3(sdkDefaultRuntimeDir(repository, vinayaHome), "logs"), keepDays: DEFAULT_KEEP_DAYS };
4217
+ const resolved = sdkResolveSettings({
4218
+ repoRoot: inputs.cwd,
4219
+ ...repository === undefined ? {} : { repository },
4220
+ vinayaHome
4221
+ });
4222
+ if (!resolved.ok || resolved.settings.logs === false)
4223
+ return;
4224
+ const configured = (resolved.settings.logs || undefined)?.folder;
4225
+ return {
4226
+ folder: configured !== undefined && !isInsideRepo(configured, inputs.cwd) ? configured : join3(resolved.settings.runtimeDir, "logs"),
4227
+ keepDays: resolved.settings.keepDays
4228
+ };
4229
+ }
4230
+ function serialized(key, work) {
4231
+ const previous = folderSends.get(key) ?? Promise.resolve();
4232
+ const next = previous.then(work, work);
4233
+ const tracked = next.catch(() => {
4234
+ return;
4235
+ });
4236
+ folderSends.set(key, tracked);
4237
+ tracked.then(() => {
4238
+ if (folderSends.get(key) === tracked)
4239
+ folderSends.delete(key);
4240
+ });
4241
+ return next;
4242
+ }
4243
+ function createLocalCopySender(deps) {
4244
+ const bound = deps.sendBoundMs ?? LOCAL_COPY_SEND_BOUND_MS;
4245
+ const interval = deps.sendIntervalMs ?? LOCAL_COPY_SEND_INTERVAL_MS;
4246
+ const now = deps.now ?? Date.now;
4247
+ let warned = false;
4248
+ const warnOnce = (error) => {
4249
+ if (warned)
4250
+ return;
4251
+ warned = true;
4252
+ try {
4253
+ deps.warn(`vinaya: the OpenTelemetry local copy failed — ${error instanceof Error ? error.message : String(error)}
4254
+ `);
4255
+ } catch {}
4256
+ };
4257
+ let address;
4258
+ const resolved = () => {
4259
+ address ??= Promise.resolve().then(() => deps.address()).catch((error) => {
4260
+ warnOnce(error);
4261
+ return { kind: "none", reason: "the address could not be resolved" };
4262
+ });
4263
+ return address;
4264
+ };
4265
+ let inFlight;
4266
+ let timer;
4267
+ let dirty = false;
4268
+ let lastStart = Number.NEGATIVE_INFINITY;
4269
+ let target;
4270
+ async function sendOnce(deadline) {
4271
+ const place = target;
4272
+ if (place === undefined)
4273
+ return;
4274
+ const decision = await resolved();
4275
+ if (decision.kind !== "address")
4276
+ return;
4277
+ const report = await serialized(`${place.folder}\x00${place.repository ?? ""}`, () => sendLocalCopy({
4278
+ folder: place.folder,
4279
+ ...place.repository === undefined ? {} : { repository: place.repository },
4280
+ url: decision.url,
4281
+ ...decision.headers === undefined ? {} : { headers: decision.headers },
4282
+ ...deps.fetch === undefined ? {} : { fetch: deps.fetch },
4283
+ ...deadline === undefined ? {} : { deadline }
4284
+ }));
4285
+ const broken = report.failures.find((failure) => failure.reason.includes("unavailable"));
4286
+ if (broken !== undefined)
4287
+ warnOnce(new Error(broken.reason));
4288
+ }
4289
+ function runSend() {
4290
+ timer = undefined;
4291
+ dirty = false;
4292
+ lastStart = now();
4293
+ inFlight = sendOnce().catch(warnOnce).finally(() => {
4294
+ inFlight = undefined;
4295
+ if (dirty)
4296
+ requestSend();
4297
+ });
4298
+ }
4299
+ function requestSend() {
4300
+ if (inFlight !== undefined || timer !== undefined) {
4301
+ dirty = true;
4302
+ return;
4303
+ }
4304
+ timer = setTimeout(runSend, Math.max(0, lastStart + interval - now()));
4305
+ timer.unref?.();
4306
+ }
4307
+ return {
4308
+ request(place) {
4309
+ target = place;
4310
+ requestSend();
4311
+ },
4312
+ remember(place) {
4313
+ target = place;
4314
+ },
4315
+ async drain() {
4316
+ if (target === undefined)
4317
+ return;
4318
+ let expired;
4319
+ const deadline = now() + bound;
4320
+ try {
4321
+ await Promise.race([
4322
+ (async () => {
4323
+ if (timer !== undefined) {
4324
+ clearTimeout(timer);
4325
+ timer = undefined;
4326
+ }
4327
+ await inFlight;
4328
+ await sendOnce(deadline);
4329
+ })().catch(warnOnce),
4330
+ new Promise((resolve) => {
4331
+ expired = setTimeout(resolve, bound);
4332
+ })
4333
+ ]);
4334
+ } finally {
4335
+ clearTimeout(expired);
4336
+ }
4337
+ }
4338
+ };
4339
+ }
4340
+ var LOCAL_COPY_SEND_BOUND_MS = 3000, LOCAL_COPY_SEND_INTERVAL_MS = 2000, folderSends;
4341
+ var init_local_copy_writer = __esm(() => {
4342
+ init_run_paths();
4343
+ folderSends = new Map;
4344
+ });
4345
+
4346
+ // ../../harness/kernel/log/client/loop-log-append.ts
4347
+ import { closeSync as closeSync2, constants as fsConstants2, fstatSync, mkdirSync as mkdirSync2, openSync as openSync2, writeSync as writeSync2 } from "node:fs";
4348
+ import { dirname as dirname3 } from "node:path";
4349
+ function appendLoopLogLine(path, line) {
4350
+ try {
4351
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
4352
+ const fd = openSync2(path, fsConstants2.O_WRONLY | fsConstants2.O_APPEND | fsConstants2.O_CREAT | fsConstants2.O_NOFOLLOW, 384);
4353
+ try {
4354
+ const stat = fstatSync(fd);
4355
+ if (stat.isFile() && stat.size < LOOP_LOG_MAX_BYTES) {
4356
+ writeSync2(fd, `${line}
4357
+ `);
4358
+ }
4359
+ } finally {
4360
+ closeSync2(fd);
4361
+ }
4362
+ } catch {}
4363
+ }
4364
+ var LOOP_LOG_MAX_BYTES;
4365
+ var init_loop_log_append = __esm(() => {
4366
+ LOOP_LOG_MAX_BYTES = 8 * 1024 * 1024;
4367
+ });
4368
+
4369
+ // ../../harness/kernel/log/client/narration.ts
4370
+ import {
4371
+ createLineReader,
4372
+ narrate as sdkNarrate,
4373
+ NARRATION_KINDS,
4374
+ reasonWaitsOn
4375
+ } from "@attalabs/vinaya-log-sdk";
4376
+ function registeredSeats() {
4377
+ const seats = {};
4378
+ for (const name of registeredRoles()) {
4379
+ const role = lookupRole(name);
4380
+ if (role !== undefined)
4381
+ seats[name] = { reading: role.reading, reviews: role.reviews };
4382
+ }
4383
+ return seats;
4384
+ }
4385
+ function stored(record) {
4386
+ return JSON.stringify({ ...NO_HEADER, ...record });
4387
+ }
4388
+ function convert(event, earlier) {
4389
+ const lines = createLineReader("narration");
4390
+ const before = [];
4391
+ const needs = SPAN_ENDS.has(String(event.event));
4392
+ if (needs) {
4393
+ for (const previous of earlier) {
4394
+ if (typeof previous !== "object" || previous === null)
4395
+ continue;
4396
+ const read = lines.readLine(stored(previous)).records[0];
4397
+ if (read !== undefined)
4398
+ before.push(read);
4399
+ }
4400
+ }
4401
+ return { record: lines.readLine(stored(event)).records[0], before };
4402
+ }
4403
+ function narrate(record, earlier = []) {
4404
+ try {
4405
+ if (typeof record !== "object" || record === null)
4406
+ return null;
4407
+ const { kind, event } = record;
4408
+ if (typeof kind !== "string" || typeof event !== "string" || !WORDED[kind]?.has(event))
4409
+ return null;
4410
+ const { record: converted, before } = convert(record, Array.isArray(earlier) ? earlier : []);
4411
+ if (converted === undefined)
4412
+ return null;
4413
+ return sdkNarrate(converted, registeredSeats(), before);
4414
+ } catch {
4415
+ return null;
4416
+ }
4417
+ }
4418
+ var SPAN_ENDS, WORDED, NO_HEADER;
4419
+ var init_narration = __esm(() => {
4420
+ init_roles();
4421
+ SPAN_ENDS = new Set(["round_ended", "outcome_received"]);
4422
+ WORDED = {
4423
+ dev_review_loop: new Set([
4424
+ "round_started",
4425
+ "gate_result_read",
4426
+ "verdicts_read",
4427
+ "round_ended",
4428
+ "paused",
4429
+ "stop_condition_met",
4430
+ "driver_exited",
4431
+ "conflict_reentry"
4432
+ ]),
4433
+ dispatch: new Set(["dispatched", "outcome_received"])
4434
+ };
4435
+ NO_HEADER = {
4436
+ meta: {
4437
+ schema: 1,
4438
+ run_id: "narration",
4439
+ repo: "narration/narration",
4440
+ vinaya: "0.0.0",
4441
+ doctrine: "narration",
4442
+ host: "loop",
4443
+ machine: "narration",
4444
+ ts: "1970-01-01T00:00:00.000Z",
4445
+ seq: 0
4446
+ },
4447
+ subject: { issue: null, role: "unattributed" },
4448
+ payload: {}
4449
+ };
4450
+ });
4451
+
4452
+ // ../../harness/kernel/adapters/agents/agent-line.ts
4453
+ function roleLabel(role) {
4454
+ return lookupTitle(role) ?? role.replace(/-/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
4455
+ }
4456
+ function formatLineMeta(meta) {
4457
+ if (meta === undefined)
4458
+ return "";
4459
+ const fields = Object.entries(meta).filter(([key, value]) => META_KEY.test(key) && (value === true || META_VALUE.test(value))).map(([key, value]) => value === true ? key : `${key}=${value}`);
4460
+ return fields.length === 0 ? "" : ` [${fields.join(" ")}]`;
4461
+ }
4462
+ function formatAgentLine(role, words, options = {}) {
4463
+ const now = options.now ?? new Date;
4464
+ const time = options.log ? `${now.toISOString()}${formatLineMeta(options.meta)}` : now.toLocaleTimeString("en-GB", { hour12: false });
4465
+ const mark = options.unicode ?? true ? unicodeMarks[options.mark ?? "working"] : asciiMarks[options.mark ?? "working"];
4466
+ return `${time} ${mark} ${roleLabel(role)} ${words}`;
4467
+ }
4468
+ var unicodeMarks, asciiMarks, META_KEY, META_VALUE;
4469
+ var init_agent_line = __esm(() => {
4470
+ init_roles();
4471
+ unicodeMarks = { working: "▸", done: "✓", failed: "✕", waiting: "◌", round: "◆" };
4472
+ asciiMarks = { working: ">", done: "+", failed: "x", waiting: "~", round: "#" };
4473
+ META_KEY = /^[a-z]+$/;
4474
+ META_VALUE = /^[A-Za-z0-9_.:#-]{1,200}$/;
4475
+ });
4476
+
4477
+ // ../../harness/kernel/log/client/loop-log.ts
4478
+ var exports_loop_log = {};
4479
+ __export(exports_loop_log, {
4480
+ LOOP_LOG_MAX_BYTES: () => LOOP_LOG_MAX_BYTES,
4481
+ appendDriverLine: () => appendDriverLine,
4482
+ appendLoopLogLine: () => appendLoopLogLine,
4483
+ appendRoleLine: () => appendRoleLine,
4484
+ appendRunStartMarker: () => appendRunStartMarker,
4485
+ followLoopLog: () => followLoopLog,
4486
+ loopLogPathFor: () => loopLogPathFor,
4487
+ loopsRoot: () => loopsRoot,
4488
+ marksByKind: () => marksByKind,
4489
+ narrateDriverEvent: () => narrateDriverEvent
4490
+ });
4491
+ import { closeSync as closeSync3, existsSync as existsSync3, openSync as openSync3, readFileSync as readFileSync2, readSync, statSync as statSync2 } from "node:fs";
4492
+ import { homedir } from "node:os";
4493
+ function loopsRoot() {
4494
+ return runtimeDirForThisRepo();
4495
+ }
4496
+ function loopLogPathFor(_repo, issue, root = loopsRoot()) {
4497
+ return runPath(root, issue, { area: "output", file: "driver.log" });
4498
+ }
4499
+ function appendRoleLine(path, role, text, details = [], mark = "working", meta = {}) {
4500
+ appendLoopLogLine(path, formatAgentLine(role, redact(text, homedir()), {
4501
+ log: true,
4502
+ unicode: false,
4503
+ mark,
4504
+ ...meta.callId !== undefined ? { meta: { call: meta.callId } } : {}
4505
+ }));
4506
+ details.forEach((detail, index) => {
4507
+ if (!detail)
4508
+ return;
4509
+ const command = meta.commandFrom !== undefined && index >= meta.commandFrom;
4510
+ appendLoopLogLine(path, `${new Date().toISOString()}${command ? formatLineMeta({ command: true }) : ""} · ${redact(detail, homedir())}`);
4511
+ });
4512
+ }
4513
+ function appendRunStartMarker(path, detail) {
4514
+ appendLoopLogLine(path, formatAgentLine(detail.role, detail.resumed ? "Resumed" : "run started", {
4515
+ log: true,
4516
+ unicode: false,
4517
+ mark: "round"
4518
+ }));
4519
+ }
4520
+ function appendDriverLine(path, words, mark = "working") {
4521
+ const text = redact(words, homedir());
4522
+ appendLoopLogLine(path, formatAgentLine("dev-review-loop", text, { log: true, unicode: false, mark }));
4523
+ console.error(formatAgentLine("dev-review-loop", text, { mark, unicode: Boolean(process.stderr.isTTY) }));
4524
+ }
4525
+ function narrateDriverEvent(path, event, earlier, task) {
4526
+ const line = narrate(event, earlier);
4527
+ if (!line)
4528
+ return;
4529
+ const fields = event;
4530
+ const needsPerson = line.kind === "blocked" && (fields.event === "paused" || fields.event === "stop_condition_met");
4531
+ const pause = typeof fields.round === "number" ? `the pause at round ${fields.round}` : "this pause";
4532
+ const words = needsPerson ? `${line.text} The Operator's task_resume for task ${task} continues this run, bound to ${pause}, once the person has decided or repaired it.` : line.text;
4533
+ appendDriverLine(path, words, marksByKind[line.kind]);
4534
+ }
4535
+ async function followLoopLog(path, overrides = {}) {
4536
+ const deps = { ...defaultFollowLoopLogDeps, ...overrides };
4537
+ let lastSize = 0;
4538
+ if (existsSync3(path)) {
4539
+ const buf = readFileSync2(path);
4540
+ (deps.writeBacklog ?? deps.write)(buf);
4541
+ lastSize = buf.length;
4542
+ }
4543
+ while (!deps.shouldStop()) {
4544
+ await deps.sleep(deps.pollIntervalMs);
4545
+ readGrowth();
4546
+ deps.tick?.();
4547
+ }
4548
+ function readGrowth() {
4549
+ if (!existsSync3(path))
4550
+ return;
4551
+ const stat = statSync2(path);
4552
+ if (stat.size < lastSize)
4553
+ lastSize = 0;
4554
+ if (stat.size > lastSize) {
4555
+ const fd = openSync3(path, "r");
4556
+ try {
4557
+ const buf = Buffer.alloc(stat.size - lastSize);
4558
+ readSync(fd, buf, 0, buf.length, lastSize);
4559
+ deps.write(buf);
4560
+ lastSize = stat.size;
4561
+ } finally {
4562
+ closeSync3(fd);
4563
+ }
4564
+ }
4565
+ }
4566
+ }
4567
+ var marksByKind, defaultFollowLoopLogDeps;
4568
+ var init_loop_log = __esm(() => {
4569
+ init_redact();
4570
+ init_loop_log_append();
4571
+ init_narration();
4572
+ init_run_paths();
4573
+ init_agent_line();
4574
+ marksByKind = {
4575
+ starting: "round",
4576
+ working: "working",
4577
+ done: "done",
4578
+ failed: "failed",
4579
+ waiting: "waiting",
4580
+ paused: "waiting",
4581
+ blocked: "waiting",
4582
+ information: "working"
4583
+ };
4584
+ defaultFollowLoopLogDeps = {
4585
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
4586
+ write: (chunk) => {
4587
+ process.stdout.write(chunk);
4588
+ },
4589
+ shouldStop: () => false,
4590
+ pollIntervalMs: 500
4591
+ };
4592
+ });
4593
+
4594
+ // ../../harness/kernel/log/client/log-webhook-drain.ts
4595
+ var exports_log_webhook_drain = {};
4596
+ __export(exports_log_webhook_drain, {
4597
+ drainOutboxToWebhook: () => drainOutboxToWebhook
4598
+ });
4599
+ import {
4600
+ closeSync as closeSync4,
4601
+ constants as fsConstants3,
4602
+ lstatSync as lstatSync2,
4603
+ mkdirSync as mkdirSync3,
4604
+ openSync as openSync4,
4605
+ linkSync as linkSync2,
4606
+ readFileSync as readFileSync3,
4607
+ renameSync as renameSync2,
4608
+ statSync as statSync3,
4609
+ unlinkSync as unlinkSync2,
4610
+ utimesSync,
4611
+ writeFileSync,
4612
+ writeSync as writeSync3
4613
+ } from "node:fs";
4614
+ import { randomUUID } from "node:crypto";
4615
+ import { homedir as homedir2 } from "node:os";
4616
+ import { dirname as dirname4, join as join4 } from "node:path";
4617
+ function isSafeRepoSegment2(segment) {
4618
+ return SAFE_PATH_SEGMENT2.test(segment) && !segment.includes("..");
4619
+ }
4620
+ function isErrnoCode(err, code) {
4621
+ return typeof err === "object" && err !== null && err.code === code;
4622
+ }
4623
+ function isEnoent(err) {
4624
+ return isErrnoCode(err, "ENOENT");
4625
+ }
4626
+ function tryCreateLock(lockPath, token) {
4627
+ try {
4628
+ mkdirSync3(dirname4(lockPath), { recursive: true, mode: 448 });
4629
+ const fd = openSync4(lockPath, fsConstants3.O_WRONLY | fsConstants3.O_CREAT | fsConstants3.O_EXCL, 384);
4630
+ try {
4631
+ writeSync3(fd, `${token}
4632
+ `);
4633
+ } finally {
4634
+ closeSync4(fd);
4635
+ }
4636
+ return true;
4637
+ } catch (err) {
4638
+ if (isErrnoCode(err, "EEXIST"))
4639
+ return false;
4640
+ throw err;
4641
+ }
4642
+ }
4643
+ function acquireDrainLock(lockPath) {
4644
+ const token = `${process.pid}:${randomUUID()}`;
4645
+ if (tryCreateLock(lockPath, token))
4646
+ return token;
4647
+ let observedMtimeMs;
4648
+ try {
4649
+ observedMtimeMs = statSync3(lockPath).mtimeMs;
4650
+ } catch (err) {
4651
+ if (!isEnoent(err))
4652
+ throw err;
4653
+ return tryCreateLock(lockPath, token) ? token : null;
4654
+ }
4655
+ if (Date.now() - observedMtimeMs <= WEBHOOK_DRAIN_LOCK_STALE_MS)
4656
+ return null;
4657
+ const claimed = `${lockPath}.claimed-${randomUUID()}`;
4658
+ try {
4659
+ renameSync2(lockPath, claimed);
4660
+ } catch (err) {
4661
+ if (isEnoent(err))
4662
+ return null;
4663
+ throw err;
4664
+ }
4665
+ let claimedMtimeMs = null;
4666
+ try {
4667
+ claimedMtimeMs = statSync3(claimed).mtimeMs;
4668
+ } catch (err) {
4669
+ if (!isEnoent(err))
4670
+ throw err;
4671
+ }
4672
+ if (claimedMtimeMs !== observedMtimeMs) {
4673
+ try {
4674
+ linkSync2(claimed, lockPath);
4675
+ } catch (err) {
4676
+ if (!isErrnoCode(err, "EEXIST"))
4677
+ throw err;
4678
+ }
4679
+ try {
4680
+ unlinkSync2(claimed);
4681
+ } catch (err) {
4682
+ if (!isEnoent(err))
4683
+ throw err;
4684
+ }
4685
+ return null;
4686
+ }
4687
+ unlinkSync2(claimed);
4688
+ return tryCreateLock(lockPath, token) ? token : null;
4689
+ }
4690
+ function renewDrainLock(lockPath, token) {
4691
+ let holder;
4692
+ try {
4693
+ holder = readFileSync3(lockPath, "utf8").trim();
4694
+ } catch (err) {
4695
+ if (!isEnoent(err))
4696
+ throw err;
4697
+ return false;
4698
+ }
4699
+ if (holder !== token)
4700
+ return false;
4701
+ const now = new Date;
4702
+ try {
4703
+ utimesSync(lockPath, now, now);
4704
+ } catch (err) {
4705
+ if (!isEnoent(err))
4706
+ throw err;
4707
+ return false;
4708
+ }
4709
+ return true;
4710
+ }
4711
+ function releaseDrainLock(lockPath, token) {
4712
+ try {
4713
+ const holder = readFileSync3(lockPath, "utf8").trim();
4714
+ if (holder !== token)
4715
+ return;
4716
+ unlinkSync2(lockPath);
4717
+ } catch (err) {
4718
+ if (!isEnoent(err))
4719
+ throw err;
4720
+ }
4721
+ }
4722
+ function backupPathFor(queuePath) {
4723
+ return queuePath.replace(/\.ndjson$/, ".1.ndjson");
4724
+ }
4725
+ function drainingPathFor(queuePath) {
4726
+ return queuePath.replace(/\.ndjson$/, ".draining.ndjson");
4727
+ }
4728
+ function rejectedPathFor(queuePath) {
4729
+ return queuePath.replace(/\.ndjson$/, ".rejected.ndjson");
4730
+ }
4731
+ function warnRejectionOnce(message) {
4732
+ if (rejectionWarnedThisProcess)
4733
+ return;
4734
+ rejectionWarnedThisProcess = true;
4735
+ try {
4736
+ process.stderr.write(message);
4737
+ } catch {}
4738
+ }
4739
+ function queueLines(buf) {
4740
+ const lines = [];
4741
+ let start = 0;
4742
+ for (let i = 0;i < buf.byteLength; i++) {
4743
+ if (buf[i] !== 10)
4744
+ continue;
4745
+ if (i > start)
4746
+ lines.push({ raw: buf.toString("utf8", start, i), end: i + 1 });
4747
+ start = i + 1;
4748
+ }
4749
+ if (start < buf.byteLength)
4750
+ lines.push({ raw: buf.toString("utf8", start), end: buf.byteLength });
4751
+ return lines;
4752
+ }
4753
+ function removeQueueHead(path, cut) {
4754
+ const remaining = readFileSync3(path);
4755
+ writeFileSync(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
4756
+ }
4757
+ function queueBucketSize(path) {
4758
+ let lstat;
4759
+ try {
4760
+ lstat = lstatSync2(path);
4761
+ } catch (err) {
4762
+ if (!isEnoent(err))
4763
+ throw err;
4764
+ }
4765
+ if (lstat === undefined)
4766
+ return null;
4767
+ if (!lstat.isFile()) {
4768
+ 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}`);
4769
+ }
4770
+ return Number(lstat.size);
4771
+ }
4772
+ function readQueueFile(path) {
4773
+ if (queueBucketSize(path) === null)
4774
+ return null;
4775
+ return readFileSync3(path);
4776
+ }
4777
+ function rejectLine(rejectedPath, reason, status, identity, raw) {
4778
+ const record = JSON.stringify({
4779
+ rejected_at: new Date().toISOString(),
4780
+ status,
4781
+ reason,
4782
+ identity,
4783
+ bytes: Buffer.byteLength(raw, "utf8"),
4784
+ raw
4785
+ });
4786
+ const failure = appendHardenedLine(rejectedPath, `${record}
4787
+ `);
4788
+ if (failure !== null) {
4789
+ throw new WebhookDrainError("log-webhook-drain-rejected-write", `log webhook drain: a queued line failed re-validation (${reason}) and could not be set aside in ${rejectedPath} — ${failure}; the line stays queued`);
4790
+ }
4791
+ warnRejectionOnce(`vinaya: log delivery set a queued line aside in ${rejectedPath} — ${reason}; later lines keep delivering
4792
+ `);
4793
+ }
4794
+ async function postChunk(webhookUrl, headers, body, fetchTimeoutMs, chunksAlreadyDelivered) {
4795
+ const delivered = chunksAlreadyDelivered > 0 ? ` after delivering ${chunksAlreadyDelivered} chunk(s)` : "";
4796
+ let response;
4797
+ try {
4798
+ response = await fetch(webhookUrl, {
4799
+ method: "POST",
4800
+ headers: { "content-type": "application/x-ndjson", ...headers },
4801
+ body,
4802
+ signal: AbortSignal.timeout(fetchTimeoutMs)
4803
+ });
4804
+ } catch (err) {
4805
+ const reason = err instanceof Error && err.name === "TimeoutError" ? `timed out after ${fetchTimeoutMs}ms` : err instanceof Error ? err.message : String(err);
4806
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} failed${delivered}: ${reason}`);
4807
+ }
4808
+ if (!response.ok) {
4809
+ throw new WebhookDrainError("log-webhook-drain-failed", `log webhook drain: POST to ${webhookUrl} returned ${response.status} ${response.statusText}${delivered}`);
4810
+ }
4811
+ }
4812
+ async function drainQueueFile(args) {
4813
+ const { path, rejectedPath, webhookUrl, headers, fetchTimeoutMs, totals } = args;
4814
+ const buf = readQueueFile(path);
4815
+ if (buf === null || buf.byteLength === 0)
4816
+ return;
4817
+ const lines = queueLines(buf);
4818
+ if (lines.length === 0) {
4819
+ removeQueueHead(path, buf.byteLength);
4820
+ return;
4821
+ }
4822
+ let removed = 0;
4823
+ let pendingEnd = 0;
4824
+ let chunk = [];
4825
+ let chunkBytes = 0;
4826
+ const deliverChunk = async () => {
4827
+ const body = `${chunk.join(`
4828
+ `)}
4829
+ `;
4830
+ args.keepLock();
4831
+ await postChunk(webhookUrl, headers, body, fetchTimeoutMs, totals.chunks);
4832
+ totals.chunks += 1;
4833
+ totals.lineCount += chunk.length;
4834
+ totals.bytes += Buffer.byteLength(body, "utf8");
4835
+ removeQueueHead(path, pendingEnd - removed);
4836
+ removed = pendingEnd;
4837
+ chunk = [];
4838
+ chunkBytes = 0;
4839
+ };
4840
+ const setAside = async (reason, status, identity, line) => {
4841
+ if (chunk.length > 0)
4842
+ await deliverChunk();
4843
+ rejectLine(rejectedPath, reason, status, identity, line.raw);
4844
+ totals.rejected += 1;
4845
+ pendingEnd = line.end;
4846
+ removeQueueHead(path, pendingEnd - removed);
4847
+ removed = pendingEnd;
4848
+ };
4849
+ for (const line of lines) {
4850
+ const record = classifyStoredLine(line.raw, homedir2());
4851
+ if (record.status !== "ok") {
4852
+ await setAside(record.reason, record.status, record.identity, line);
4853
+ continue;
4854
+ }
4855
+ const lineBytes = Buffer.byteLength(record.postLine, "utf8") + 1;
4856
+ if (lineBytes > MAX_WEBHOOK_BODY_BYTES) {
4857
+ await setAside(`one line is ${lineBytes} byte(s), over the ${MAX_WEBHOOK_BODY_BYTES}-byte per-POST cap — no chunking can carry it`, "too_large", record.identity, line);
4858
+ continue;
4859
+ }
4860
+ if (chunk.length > 0 && chunkBytes + lineBytes > MAX_WEBHOOK_BODY_BYTES)
4861
+ await deliverChunk();
4862
+ chunk.push(record.postLine);
4863
+ chunkBytes += lineBytes;
4864
+ pendingEnd = line.end;
4865
+ }
4866
+ pendingEnd = buf.byteLength;
4867
+ if (chunk.length > 0) {
4868
+ await deliverChunk();
4869
+ return;
4870
+ }
4871
+ if (pendingEnd > removed)
4872
+ removeQueueHead(path, pendingEnd - removed);
4873
+ }
4874
+ async function drainRenamedAside(args, livePath, source) {
4875
+ args.keepLock();
4876
+ const draining = drainingPathFor(livePath);
4877
+ try {
4878
+ renameSync2(source, draining);
4879
+ } catch (err) {
4880
+ if (isEnoent(err))
4881
+ return;
4882
+ throw err;
4883
+ }
4884
+ await drainQueueFile({ ...args, path: draining });
4885
+ unlinkSync2(draining);
4886
+ }
4887
+ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
4888
+ const resolved = await resolveRepo();
4889
+ const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
4890
+ const outboxRoot = () => join4(configProvider().homeDir, "outbox");
4891
+ const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
4892
+ const lockPath = `${path}.flush-lock`;
4893
+ const lockToken = acquireDrainLock(lockPath);
4894
+ const totals = { lineCount: 0, bytes: 0, chunks: 0, rejected: 0 };
4895
+ if (lockToken === null)
4896
+ return { flushed: false, ...totals };
4897
+ try {
4898
+ const keepLock = () => {
4899
+ if (renewDrainLock(lockPath, lockToken))
4900
+ return;
4901
+ throw new WebhookDrainError("log-webhook-drain-lock-lost", `log webhook drain: this drain's lock on ${lockPath} was taken over by another process — stopping here; that process delivers the rest`);
4902
+ };
4903
+ const shared = {
4904
+ rejectedPath: rejectedPathFor(path),
4905
+ webhookUrl,
4906
+ headers,
4907
+ fetchTimeoutMs,
4908
+ totals,
4909
+ keepLock
4910
+ };
4911
+ const draining = drainingPathFor(path);
4912
+ if (queueBucketSize(draining) !== null) {
4913
+ keepLock();
4914
+ await drainQueueFile({ ...shared, path: draining });
4915
+ unlinkSync2(draining);
4916
+ }
4917
+ await drainRenamedAside(shared, path, backupPathFor(path));
4918
+ await drainRenamedAside(shared, path, path);
4919
+ return { flushed: totals.chunks > 0 || totals.rejected > 0, ...totals };
4920
+ } finally {
4921
+ releaseDrainLock(lockPath, lockToken);
4922
+ }
4923
+ }
4924
+ var MAX_WEBHOOK_BODY_BYTES, WEBHOOK_FETCH_TIMEOUT_MS = 30000, SAFE_PATH_SEGMENT2, WEBHOOK_DRAIN_LOCK_STALE_MS, WebhookDrainError, rejectionWarnedThisProcess = false;
4925
+ var init_log_webhook_drain = __esm(() => {
4926
+ init_resolve_repo();
4927
+ init_store();
4928
+ init_log_sink();
4929
+ MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
4930
+ SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
4931
+ WEBHOOK_DRAIN_LOCK_STALE_MS = 4 * WEBHOOK_FETCH_TIMEOUT_MS;
4932
+ WebhookDrainError = class WebhookDrainError extends Error {
4933
+ code;
4934
+ constructor(code, message) {
4935
+ super(message);
4936
+ this.code = code;
4937
+ }
4938
+ };
4939
+ });
4940
+
4941
+ // ../../harness/kernel/log/otlp-address.ts
4942
+ function resolveOtlpAddress(input) {
4943
+ const ci = Boolean(input.env.GITHUB_ACTIONS || input.env.CI);
4944
+ const anchored = input.unattended || ci;
4945
+ const config = anchored ? input.trustAnchorConfig : input.localConfig;
4946
+ if (input.localConfig?.logs === false || config?.logs === false) {
4947
+ return { kind: "none", reason: "logging is disabled" };
4948
+ }
4949
+ if (anchored && !config)
4950
+ return { kind: "none", reason: "default branch settings unavailable" };
4951
+ const address = config?.logs?.otlp;
4952
+ if (!address) {
4953
+ return { kind: "none", reason: anchored ? "default branch has no logs.otlp address" : "no logs.otlp address" };
4954
+ }
4955
+ if (logsCredentialMissing(address.headers, input.env)) {
4956
+ return {
4957
+ kind: "none",
4958
+ reason: ci ? "CI is missing an OpenTelemetry header credential" : "the logs.otlp headers name a credential variable that is not set"
4959
+ };
4960
+ }
4961
+ return { kind: "address", url: address.url, headers: resolveLogsHeaderValues(address.headers, input.env) };
4962
+ }
4963
+ var init_otlp_address = __esm(() => {
4964
+ init_config_schema();
4965
+ init_log_sink();
4966
+ });
4967
+
4968
+ // ../../harness/kernel/log/log-sink.ts
4969
+ import { execFile as execFile3 } from "node:child_process";
4970
+ import { randomUUID as randomUUID2 } from "node:crypto";
4971
+ import {
4972
+ appendFileSync,
4973
+ closeSync as closeSync5,
4974
+ constants as fsConstants4,
4975
+ fstatSync as fstatSync2,
4976
+ mkdirSync as mkdirSync4,
4977
+ lstatSync as lstatSync3,
4978
+ openSync as openSync5,
4979
+ readFileSync as readFileSync4,
4980
+ renameSync as renameSync3,
4981
+ writeFileSync as writeFileSync2,
4982
+ writeSync as writeSync4
4983
+ } from "node:fs";
4984
+ import { hostname as osHostname, homedir as homedir3 } from "node:os";
4985
+ import { dirname as dirname5, join as join5 } from "node:path";
4986
+ import { promisify as promisify3 } from "node:util";
4987
+ function isUnattributedStreamName(name) {
4988
+ return /^none-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name);
4989
+ }
4990
+ function describeFolderFallback(reason) {
4991
+ if (reason.kind === "anchor-unreadable") {
4992
+ return `not delivering to the configured log server ${reason.intendedUrl} — the default branch's ` + "vinaya.config.json could not be read to confirm it (the trust-anchor read via `gh` was offline, " + "unauthenticated, or slower than its deadline); events are written to the local folder and can be " + "delivered later with `vinaya-log-send`";
4993
+ }
4994
+ return `not delivering to the working-tree log server ${reason.intendedUrl} — the default branch's ` + "vinaya.config.json does not declare it, so an unattended run does not honour it (a pull request cannot " + "redirect telemetry); events are written to the local folder";
4995
+ }
4996
+ function withDeadline(work, ms, fallback) {
4997
+ return new Promise((resolve) => {
4998
+ let graceTimer;
4999
+ const timer = setTimeout(() => {
5000
+ graceTimer = setTimeout(() => resolve(fallback), WITH_DEADLINE_GRACE_MS);
5001
+ graceTimer.unref?.();
5002
+ }, ms);
5003
+ timer.unref?.();
5004
+ const settle = (answer) => {
5005
+ clearTimeout(timer);
5006
+ if (graceTimer !== undefined)
5007
+ clearTimeout(graceTimer);
5008
+ resolve(answer);
5009
+ };
5010
+ work.then((value) => settle(value), () => settle(fallback));
5011
+ });
5012
+ }
5013
+ async function safeLoadTrustAnchorConfig() {
5014
+ return withDeadline(configProvider().loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_DESTINATION_ANCHOR_DEADLINE_MS, null);
5015
+ }
5016
+ function logsCredentialMissing(headers, env) {
5017
+ if (!headers)
5018
+ return false;
5019
+ const varPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
5020
+ for (const value of Object.values(headers)) {
5021
+ for (const match of value.matchAll(varPattern)) {
5022
+ const name = match[1];
5023
+ if (env[name])
5024
+ continue;
5025
+ return true;
5026
+ }
5027
+ }
5028
+ return false;
5029
+ }
5030
+ function resolveLogDestinationFrom(input) {
5031
+ if (input.localConfig?.logs === false || input.unattended && input.trustAnchorConfig?.logs === false) {
5032
+ return { kind: "none", reason: "logs: false disables Log recording" };
5033
+ }
5034
+ const spoolDir = input.env.VINAYA_LOG_SPOOL_DIR;
5035
+ if (spoolDir !== undefined && spoolDir.trim() !== "") {
5036
+ return { kind: "folder", folder: spoolDir };
5037
+ }
5038
+ const local = resolveLogsSetting(input.localConfig);
5039
+ let effective = null;
5040
+ let fallbackReason;
5041
+ if (input.unattended) {
5042
+ if (local) {
5043
+ effective = resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig);
5044
+ if (effective === null && "url" in local) {
5045
+ fallbackReason = input.trustAnchorConfig === null ? { kind: "anchor-unreadable", intendedUrl: local.url } : { kind: "anchor-mismatch", intendedUrl: local.url };
5046
+ }
5047
+ } else {
5048
+ effective = resolveLogsSetting(input.trustAnchorConfig);
5049
+ }
5050
+ } else {
5051
+ effective = local;
5052
+ }
5053
+ if (input.folderOnly || input.env[LOG_FOLDER_ONLY_ENV] === "1") {
5054
+ const folder = effective && "folder" in effective && !isInsideRepo(effective.folder, input.repoRoot) ? effective.folder : input.defaultFolder;
5055
+ return { kind: "folder", folder };
5056
+ }
5057
+ if (hostFromEnv(input.env) === "ci") {
5058
+ if (effective && "url" in effective) {
5059
+ if (logsCredentialMissing(effective.headers, input.env)) {
5060
+ return {
5061
+ kind: "none",
5062
+ reason: "a logs.url server destination is configured, but this job holds no delivery credential (a fork pull request, or a missing repository secret)"
5063
+ };
5064
+ }
5065
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
5066
+ }
5067
+ return {
5068
+ kind: "none",
5069
+ reason: "no server destination is configured for CI delivery (vinaya.config.json logs.url)"
5070
+ };
5071
+ }
5072
+ if (effective && "url" in effective) {
5073
+ return { kind: "server", url: effective.url, headers: resolveLogsHeaderValues(effective.headers, input.env) };
5074
+ }
5075
+ if (effective && "folder" in effective && isInsideRepo(effective.folder, input.repoRoot)) {
5076
+ effective = null;
5077
+ }
5078
+ const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
5079
+ return fallbackReason ? { kind: "folder", folder, fallbackReason } : { kind: "folder", folder };
5080
+ }
5081
+ function createTrustAnchorCache(read, now = Date.now, bounds = {
5082
+ retryIntervalMs: LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS,
5083
+ maxRetries: LOG_DESTINATION_ANCHOR_MAX_RETRIES
5084
+ }) {
5085
+ const slots = new Map;
5086
+ const start = (repoRoot, retries) => {
5087
+ const slot = {
5088
+ reading: Promise.resolve().then(read).catch(() => null),
5089
+ retries,
5090
+ missedAt: null
5091
+ };
5092
+ slots.set(repoRoot, slot);
5093
+ slot.reading.then((config) => {
5094
+ if (config === null)
5095
+ slot.missedAt = now();
5096
+ });
5097
+ return slot.reading;
5098
+ };
5099
+ return {
5100
+ get: (repoRoot) => {
5101
+ const slot = slots.get(repoRoot);
5102
+ if (slot === undefined)
5103
+ return start(repoRoot, 0);
5104
+ if (slot.missedAt === null)
5105
+ return slot.reading;
5106
+ if (slot.retries >= bounds.maxRetries || now() - slot.missedAt < bounds.retryIntervalMs)
5107
+ return slot.reading;
5108
+ return start(repoRoot, slot.retries + 1);
5109
+ },
5110
+ clear: () => slots.clear()
5111
+ };
5112
+ }
5113
+ function processTrustAnchor(repoRoot) {
5114
+ return processTrustAnchorByRepo.get(repoRoot);
5115
+ }
5116
+ function defaultBranchSettingsNow(repoRoot) {
5117
+ if (defaultBranchSettingsByRepo.has(repoRoot))
5118
+ return defaultBranchSettingsByRepo.get(repoRoot) ?? null;
5119
+ let settings;
5120
+ try {
5121
+ settings = configProvider().loadTrustAnchorConfig({ quiet: true });
5122
+ } catch {
5123
+ settings = null;
5124
+ }
5125
+ defaultBranchSettingsByRepo.set(repoRoot, settings);
5126
+ return settings;
5127
+ }
5128
+ async function defaultResolveLogDestination(repo, env, folderOnly = false) {
5129
+ const localConfig = configProvider().loadConfig();
5130
+ const unattended = isUnattendedProcess(process.env);
5131
+ const repoRoot = repoRootSync();
5132
+ return resolveLogDestinationFrom({
5133
+ localConfig,
5134
+ folderOnly,
5135
+ trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
5136
+ unattended,
5137
+ env,
5138
+ defaultFolder: join5(await runtimeDirForRepoAsync(repo), "logs"),
5139
+ repoRoot
5140
+ });
5141
+ }
5142
+ function unresolvedLogDestination(env) {
5143
+ const loaded = configProvider().loadConfig();
5144
+ if (loaded?.logs === false)
5145
+ return { kind: "none", reason: "logs: false disables Log recording" };
5146
+ if (hostFromEnv(env) === "ci") {
5147
+ return {
5148
+ kind: "none",
5149
+ reason: "the process ended before its log destination was resolved, and a CI job never records to a folder"
5150
+ };
5151
+ }
5152
+ const localConfig = loaded?.logs && loaded.logs.url !== undefined ? { ...loaded, logs: undefined } : loaded;
5153
+ const unattended = isUnattendedProcess(process.env);
5154
+ const repoRoot = repoRootSync();
5155
+ const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
5156
+ const defaultFolder = join5(runtimeDir, "logs");
5157
+ const resolved = resolveLogDestinationFrom({
5158
+ localConfig,
5159
+ trustAnchorConfig: null,
5160
+ unattended,
5161
+ env,
5162
+ defaultFolder,
5163
+ repoRoot
5164
+ });
5165
+ return resolved.kind === "folder" ? resolved : { kind: "folder", folder: defaultFolder };
5166
+ }
5167
+ function folderFallbackStatePath(repo, stateRoot = configProvider().homeDir) {
5168
+ const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
5169
+ return join5(stateRoot, "fallback", `${dirName}.json`);
5170
+ }
5171
+ function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot = configProvider().homeDir) {
5172
+ const message = describeFolderFallback(reason);
5173
+ if (issue !== null) {
5174
+ const { appendLoopLogLine, loopLogPathFor } = loopLog();
5175
+ appendLoopLogLine(loopLogPathFor(repo, issue, runtimeDir), `[log] ${message}`);
5176
+ }
5177
+ try {
5178
+ const record = {
5179
+ at: now.toISOString(),
5180
+ reason: message,
5181
+ intendedUrl: reason.intendedUrl,
5182
+ kind: reason.kind
5183
+ };
5184
+ const path = folderFallbackStatePath(repo, stateRoot);
5185
+ mkdirSync4(dirname5(path), { recursive: true, mode: 448 });
5186
+ writeFileSync2(path, `${JSON.stringify(record)}
5187
+ `, { mode: 384 });
5188
+ } catch {}
5189
+ }
5190
+ function isSafeRepoSegment3(segment) {
5191
+ return SAFE_PATH_SEGMENT3.test(segment) && !segment.includes("..");
5192
+ }
5193
+ function safeRepoSlug(repo) {
5194
+ if (repo === null)
5195
+ return null;
5196
+ return isSafeRepoSegment3(repo.owner) && isSafeRepoSegment3(repo.repo) ? `${repo.owner}/${repo.repo}` : null;
5197
+ }
5198
+ function outboxPathFor(deps, repo, issue, unattributedStream) {
5199
+ const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
5200
+ const unattributed = unattributedStream !== undefined && isUnattributedStreamName(unattributedStream) ? unattributedStream : "none";
5201
+ const fileName = `${issue ?? unattributed}.ndjson`;
5202
+ return join5(deps.outboxRoot(), dirName, fileName);
5203
+ }
5204
+ async function resolveLogAppendPath(repo, issue, overrides) {
5205
+ requireBranchIssueResolver(overrides?.resolveBranchIssue, "resolveLogAppendPath");
5206
+ const deps = { ...defaultDeps(), ...overrides };
5207
+ const destination = await deps.resolveLogDestination(repo, deps.env());
5208
+ const root = destination.kind === "folder" ? destination.folder : deps.outboxRoot();
5209
+ if (destination.kind === "none")
5210
+ return outboxPathFor({ outboxRoot: () => root }, repo, issue);
5211
+ const branchIssue = issue === null && !deps.env().VINAYA_TASK && branchIssueFallbackEnabled ? await branchIssueRead(`${deps.cwd()}\x00${safeRepoSlug(repo) ?? ""}`, () => overrides.resolveBranchIssue(safeRepoSlug(repo)), overrides.shareBranchIssue === true) : null;
5212
+ return outboxPathFor({ outboxRoot: () => root }, repo, issue ?? branchIssue);
5213
+ }
5214
+ function hostFromEnv(env) {
5215
+ if (env.GITHUB_ACTIONS)
5216
+ return "ci";
5217
+ if (env.VINAYA_HOST === "hook")
5218
+ return "hook";
5219
+ if (env.VINAYA_HOST === "loop")
5220
+ return "loop";
5221
+ return "cli";
5222
+ }
5223
+ function defaultStderr(message, opts) {
5224
+ if (opts?.always === true) {
5225
+ process.stderr.write(message);
5226
+ return;
5227
+ }
5228
+ if (warnedThisProcess)
5229
+ return;
5230
+ warnedThisProcess = true;
5231
+ process.stderr.write(message);
5232
+ }
5233
+ function branchIssueRead(key, read, shared) {
5234
+ if (!shared)
5235
+ return withDeadline(Promise.resolve().then(read), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
5236
+ const cached = branchIssueByCwd.get(key);
5237
+ if (cached !== undefined)
5238
+ return cached;
5239
+ const reading = withDeadline(Promise.resolve().then(read), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
5240
+ branchIssueByCwd.set(key, reading);
5241
+ reading.then((value) => branchIssueSettledByCwd.set(key, value));
5242
+ return reading;
5243
+ }
5244
+ function headShaRead(key, read, shared) {
5245
+ if (!shared)
5246
+ return withDeadline(Promise.resolve().then(read), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
5247
+ const cached = headShaByCwd.get(key);
5248
+ if (cached !== undefined)
5249
+ return cached;
5250
+ const reading = withDeadline(Promise.resolve().then(read), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
5251
+ headShaByCwd.set(key, reading);
5252
+ reading.then((value) => headShaSettledByCwd.set(key, value));
5253
+ return reading;
5254
+ }
5255
+ async function resolveHeadSha(cwd) {
5256
+ try {
5257
+ const out = (await execFileAsync3("git", ["-C", cwd, "rev-parse", "HEAD"], { encoding: "utf8" })).stdout.trim();
5258
+ return /^[0-9a-f]{40}$/.test(out) ? out : null;
5259
+ } catch {
5260
+ return null;
5261
+ }
5262
+ }
5263
+ function requireBranchIssueResolver(resolver, builder) {
5264
+ if (typeof resolver !== "function") {
5265
+ throw new Error(`${builder}: the resolveBranchIssue dependency is required — build Log sinks through the installed log sink factory, which supplies it`);
5266
+ }
5267
+ }
5268
+ function defaultDeps() {
5269
+ return {
5270
+ readConfig: () => configProvider().loadConfig(),
5271
+ outboxRoot: () => join5(configProvider().homeDir, "outbox"),
5272
+ home: () => homedir3(),
5273
+ hostname: () => osHostname(),
5274
+ cwd: () => process.cwd(),
5275
+ now: () => new Date,
5276
+ env: () => process.env,
5277
+ resolveRepo: () => resolveRepo(),
5278
+ vinayaVersion: () => "unknown",
5279
+ stderr: defaultStderr,
5280
+ inputVersions: () => {
5281
+ return;
5282
+ },
5283
+ resolveLogDestination: defaultResolveLogDestination,
5284
+ unresolvedLogDestination
5285
+ };
5286
+ }
5287
+ function guardedAppendOpen(path) {
5288
+ try {
5289
+ return openSync5(path, APPEND_OPEN_FLAGS, 384);
5290
+ } catch {
5291
+ return;
5292
+ }
5293
+ }
5294
+ function appendHardenedLine(path, line) {
5295
+ try {
5296
+ mkdirSync4(dirname5(path), { recursive: true, mode: 448 });
5297
+ const fd = guardedAppendOpen(path);
5298
+ if (fd === undefined)
5299
+ return `target could not be opened (symlink, FIFO, or unwritable): ${path}`;
5300
+ try {
5301
+ if (!fstatSync2(fd).isFile())
5302
+ return `target is not a regular file: ${path}`;
5303
+ writeSync4(fd, line);
5304
+ } finally {
5305
+ closeSync5(fd);
5306
+ }
5307
+ return null;
5308
+ } catch (err) {
5309
+ return err instanceof Error ? err.message : String(err);
5310
+ }
5311
+ }
5312
+ function reportRotationOverflow(backupPath, warn) {
5313
+ let raw;
5314
+ try {
5315
+ raw = readFileSync4(backupPath, "utf8");
5316
+ } catch {
5317
+ return;
5318
+ }
5319
+ const lines = raw.split(`
5320
+ `).filter((l) => l.length > 0);
5321
+ if (lines.length === 0)
5322
+ return;
5323
+ const droppedIdentities = lines.map((line, i) => {
5324
+ try {
5325
+ return recordIdentity(JSON.parse(line)) ?? `unreadable:${i}`;
5326
+ } catch {
5327
+ return `unreadable:${i}`;
5328
+ }
5329
+ });
5330
+ const diagnostic = { reason: "capacity", dropped: droppedIdentities.length, droppedIdentities };
5331
+ const shown = diagnostic.droppedIdentities.slice(0, 20);
5332
+ const more = diagnostic.dropped > shown.length ? `, +${diagnostic.dropped - shown.length} more` : "";
5333
+ warn(`vinaya: log outbox rotation is overwriting ${backupPath} — ${diagnostic.dropped} record(s) permanently lost: ${shown.join(", ")}${more}
5334
+ `);
5335
+ }
5336
+ function appendLine(path, line, warn) {
5337
+ const refuse = (message) => {
5338
+ warn(message);
5339
+ return message;
5340
+ };
5341
+ try {
5342
+ mkdirSync4(dirname5(path), { recursive: true, mode: 448 });
5343
+ let fd = guardedAppendOpen(path);
5344
+ if (fd === undefined) {
5345
+ return refuse(`vinaya: log outbox target could not be opened (symlink, FIFO, or unwritable) — refusing: ${path}
5346
+ `);
5347
+ }
5348
+ let closed = false;
5349
+ try {
5350
+ const stat = fstatSync2(fd);
5351
+ if (!stat.isFile()) {
5352
+ return refuse(`vinaya: log outbox target is not a regular file — refusing to write: ${path}
5353
+ `);
5354
+ }
5355
+ if (stat.size > OUTBOX_MAX_BYTES) {
5356
+ closeSync5(fd);
5357
+ closed = true;
5358
+ const backupPath = path.replace(/\.ndjson$/, ".1.ndjson");
5359
+ reportRotationOverflow(backupPath, warn);
5360
+ renameSync3(path, backupPath);
5361
+ const rotated = guardedAppendOpen(path);
5362
+ if (rotated === undefined) {
5363
+ return refuse(`vinaya: log outbox target could not be reopened after rotation — refusing: ${path}
5364
+ `);
5365
+ }
5366
+ fd = rotated;
5367
+ closed = false;
5368
+ }
5369
+ writeSync4(fd, line);
5370
+ } finally {
5371
+ if (!closed)
5372
+ closeSync5(fd);
5373
+ }
5374
+ return;
5375
+ } catch (err) {
5376
+ return refuse(`vinaya: log outbox write failed — ${err instanceof Error ? err.message : String(err)}
5377
+ `);
5378
+ }
5379
+ }
5380
+ function createLogSink(overrides) {
5381
+ requireBranchIssueResolver(overrides?.resolveBranchIssue, "createLogSink");
5382
+ const deps = {
5383
+ ...defaultDeps(),
5384
+ resolveHeadSha: () => resolveHeadSha(deps.cwd()),
5385
+ ...overrides
5386
+ };
5387
+ const runId = overrides.runId ?? (deps.env().VINAYA_RUN_ID || randomUUID2());
5388
+ const processId = randomUUID2();
5389
+ let seq = 0;
5390
+ let warned = false;
5391
+ let folderFallbackRecorded = false;
5392
+ const warnOnce = (message) => {
5393
+ if (warned)
5394
+ return;
5395
+ warned = true;
5396
+ try {
5397
+ deps.stderr(message);
5398
+ } catch {}
5399
+ };
5400
+ let lostRecords = 0;
5401
+ let firstLossReason;
5402
+ const countLost = (message) => {
5403
+ lostRecords++;
5404
+ if (firstLossReason === undefined)
5405
+ firstLossReason = message.replace(/^vinaya: /, "").trimEnd();
5406
+ };
5407
+ const lose = (message) => {
5408
+ countLost(message);
5409
+ warnOnce(message);
5410
+ };
5411
+ const reportLostRecords = () => {
5412
+ if (lostRecords === 0)
5413
+ return;
5414
+ const count = lostRecords;
5415
+ const reason = firstLossReason ?? "unknown failure";
5416
+ lostRecords = 0;
5417
+ firstLossReason = undefined;
5418
+ try {
5419
+ deps.stderr(`vinaya: the log lost ${count} record(s) it could not write — first failure: ${reason}
5420
+ `, {
5421
+ always: true
5422
+ });
5423
+ } catch {}
5424
+ };
5425
+ let doctrineCache;
5426
+ const doctrine = () => {
5427
+ if (doctrineCache === undefined) {
5428
+ doctrineCache = withDeadline(deps.doctrineIdentity === undefined ? Promise.resolve(deps.vinayaVersion()) : deps.doctrineIdentity(deps.cwd(), deps.vinayaVersion()), LOG_CONTEXT_LOOKUP_DEADLINE_MS, deps.vinayaVersion());
5429
+ }
5430
+ return doctrineCache;
5431
+ };
5432
+ const readerIsReal = deps.shareBranchIssue === true;
5433
+ let ownBranchIssue;
5434
+ let ownBranchIssueSettled = null;
5435
+ const branchIssueOnce = (repo) => {
5436
+ if (!branchIssueFallbackEnabled)
5437
+ return Promise.resolve(null);
5438
+ const slug = safeRepoSlug(repo);
5439
+ const read = () => deps.resolveBranchIssue(slug);
5440
+ if (readerIsReal)
5441
+ return branchIssueRead(`${deps.cwd()}\x00${slug ?? ""}`, read, true);
5442
+ if (ownBranchIssue === undefined) {
5443
+ ownBranchIssue = branchIssueRead(deps.cwd(), read, false);
5444
+ ownBranchIssue.then((value) => {
5445
+ ownBranchIssueSettled = value;
5446
+ });
5447
+ }
5448
+ return ownBranchIssue;
5449
+ };
5450
+ const branchIssueIfSettled = (repo) => {
5451
+ if (!branchIssueFallbackEnabled)
5452
+ return null;
5453
+ if (!readerIsReal)
5454
+ return ownBranchIssueSettled;
5455
+ return branchIssueSettledByCwd.get(`${deps.cwd()}\x00${safeRepoSlug(repo) ?? ""}`) ?? null;
5456
+ };
5457
+ const headShaReaderIsReal = overrides.resolveHeadSha === undefined;
5458
+ let ownHeadSha;
5459
+ let ownHeadShaSettled = null;
5460
+ const headShaOnce = () => {
5461
+ if (headShaReaderIsReal)
5462
+ return headShaRead(deps.cwd(), deps.resolveHeadSha, true);
5463
+ if (ownHeadSha === undefined) {
5464
+ ownHeadSha = headShaRead(deps.cwd(), deps.resolveHeadSha, false);
5465
+ ownHeadSha.then((value) => {
5466
+ ownHeadShaSettled = value;
5467
+ });
5468
+ }
5469
+ return ownHeadSha;
5470
+ };
5471
+ const headShaIfSettled = () => headShaReaderIsReal ? headShaSettledByCwd.get(deps.cwd()) ?? null : ownHeadShaSettled;
5472
+ let resolveRepoCache;
5473
+ const resolveRepoOnce = () => {
5474
+ if (resolveRepoCache === undefined)
5475
+ resolveRepoCache = deps.resolveRepo();
5476
+ return resolveRepoCache;
5477
+ };
5478
+ let contextCache;
5479
+ let settledContext;
5480
+ let contextEnv = {};
5481
+ const resolveDestination = async (repo, env) => deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : await deps.resolveLogDestination(repo, env, deps.folderOnly);
5482
+ const context = () => {
5483
+ if (contextCache === undefined) {
5484
+ const env = deps.env();
5485
+ contextEnv = env;
5486
+ contextCache = Promise.all([
5487
+ withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
5488
+ doctrine()
5489
+ ]).then(async ([resolved, doctrineValue]) => {
5490
+ const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
5491
+ settledContext = { repo, doctrine: doctrineValue, destination: await resolveDestination(repo, env) };
5492
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
5493
+ return settledContext;
5494
+ });
5495
+ }
5496
+ return contextCache;
5497
+ };
5498
+ let destinationRetries = 0;
5499
+ let destinationRetryDueAt = 0;
5500
+ let destinationRetryInFlight = false;
5501
+ const retryDestinationIfDue = (ctx) => {
5502
+ if (ctx.destination.kind !== "folder" || ctx.destination.fallbackReason?.kind !== "anchor-unreadable")
5503
+ return;
5504
+ if (destinationRetryInFlight || destinationRetries >= LOG_DESTINATION_ANCHOR_MAX_RETRIES)
5505
+ return;
5506
+ if (deps.now().getTime() < destinationRetryDueAt)
5507
+ return;
5508
+ destinationRetryInFlight = true;
5509
+ destinationRetries++;
5510
+ const generation = contextCache;
5511
+ Promise.resolve().then(() => resolveDestination(ctx.repo, contextEnv)).then((destination) => {
5512
+ if (contextCache !== generation)
5513
+ return;
5514
+ if (destination.kind === "server") {
5515
+ settledContext = { ...ctx, destination };
5516
+ contextCache = Promise.resolve(settledContext);
5517
+ return;
5518
+ }
5519
+ if (destination.kind !== "folder" || destination.fallbackReason?.kind !== "anchor-unreadable") {
5520
+ destinationRetries = LOG_DESTINATION_ANCHOR_MAX_RETRIES;
5521
+ }
5522
+ }, () => {
5523
+ return;
5524
+ }).finally(() => {
5525
+ destinationRetryInFlight = false;
5526
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
5527
+ });
5528
+ };
5529
+ const resetContext = () => {
5530
+ contextCache = undefined;
5531
+ settledContext = undefined;
5532
+ destinationRetries = 0;
5533
+ };
5534
+ let drainChain = Promise.resolve();
5535
+ const pendingWrites = new Set;
5536
+ let writeChain = Promise.resolve();
5537
+ const scheduleWebhookDrain = (issue, url, headers) => {
5538
+ drainChain = drainChain.then(async () => (await Promise.resolve().then(() => (init_log_webhook_drain(), exports_log_webhook_drain))).drainOutboxToWebhook(issue, url, headers)).then(() => {
5539
+ return;
5540
+ }).catch((err) => {
5541
+ warnOnce(`vinaya: log delivery to ${url} failed — queued in the local outbox, retried on the next event: ${err instanceof Error ? err.message : String(err)}
5542
+ `);
5543
+ });
5544
+ };
5545
+ const snapshot = (attribution) => {
5546
+ const env = deps.env();
5547
+ return {
5548
+ attributed: attribution !== undefined,
5549
+ host: hostFromEnv(env),
5550
+ now: deps.now(),
5551
+ seq: seq++,
5552
+ envFields: {
5553
+ role: attribution?.role ?? env.VINAYA_ROLE,
5554
+ task: env.VINAYA_TASK,
5555
+ round: attribution ? String(attribution.round) : env.VINAYA_ROUND,
5556
+ pr: env.VINAYA_PR,
5557
+ run: env.VINAYA_RUN || runId,
5558
+ attempt: attribution ? String(attribution.attempt) : env.VINAYA_ATTEMPT,
5559
+ parent: env.VINAYA_PARENT_EVENT,
5560
+ workRef: env.VINAYA_WORK_REF,
5561
+ flow: env.VINAYA_FLOW,
5562
+ flowVersion: env.VINAYA_FLOW_VERSION,
5563
+ runtime: env.VINAYA_RUNTIME,
5564
+ processId: env.VINAYA_PROCESS_ID,
5565
+ processVersion: env.VINAYA_PROCESS_VERSION,
5566
+ processDigest: env.VINAYA_PROCESS_DIGEST,
5567
+ runnerId: env.VINAYA_RUNNER_ID,
5568
+ runnerVersion: env.VINAYA_RUNNER_VERSION,
5569
+ source: env.VINAYA_SOURCE
5570
+ }
5571
+ };
5572
+ };
5573
+ const writeEvent = (e, call, ctx, branchIssue, headSha, deliver, unattributedStream) => {
5574
+ const { repo, doctrine: doctrineValue, destination } = ctx;
5575
+ if (destination.kind === "none") {
5576
+ warnOnce(`vinaya: not recording — ${destination.reason}
5577
+ `);
5578
+ return;
5579
+ }
5580
+ if (destination.kind === "folder" && destination.fallbackReason) {
5581
+ warnOnce(`vinaya: ${describeFolderFallback(destination.fallbackReason)}
5582
+ `);
5583
+ }
5584
+ const built = buildHeader({
5585
+ now: call.now,
5586
+ runId,
5587
+ seq: call.seq,
5588
+ repo: repo ? `${repo.owner}/${repo.repo}` : null,
5589
+ vinaya: deps.vinayaVersion(),
5590
+ doctrine: doctrineValue,
5591
+ host: call.host,
5592
+ hostname: deps.hostname(),
5593
+ env: call.envFields,
5594
+ branchIssue,
5595
+ eventId: randomUUID2(),
5596
+ processId,
5597
+ revision: headSha,
5598
+ provenance: call.attributed ? "parent_attributed" : deps.provenance,
5599
+ inputVersions: deps.inputVersions()
5600
+ });
5601
+ const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
5602
+ if (destination.kind === "folder" && destination.fallbackReason && !folderFallbackRecorded) {
5603
+ folderFallbackRecorded = true;
5604
+ recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname5(destination.folder), join5(deps.home(), ".vinaya"));
5605
+ }
5606
+ const full = { ...e, ...header };
5607
+ const parsed = LogEventSchema.safeParse(full);
5608
+ if (!parsed.success) {
5609
+ lose(`vinaya: log() refused an invalid payload — ${parsed.error.issues[0]?.message ?? "schema violation"}
5610
+ `);
5611
+ return;
5612
+ }
5613
+ const redacted = redact(parsed.data, deps.home());
5614
+ const line = `${JSON.stringify(redacted)}
5615
+ `;
5616
+ if (destination.kind === "server") {
5617
+ const refused = appendLine(outboxPathFor(deps, repo, header.subject.issue), line, warnOnce);
5618
+ if (refused !== undefined)
5619
+ countLost(refused);
5620
+ if (deliver)
5621
+ scheduleWebhookDrain(header.subject.issue, destination.url, destination.headers);
5622
+ } else {
5623
+ const refused = appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue, unattributedStream), line, warnOnce);
5624
+ if (refused !== undefined)
5625
+ countLost(refused);
5626
+ }
5627
+ };
5628
+ function routed(e, repo) {
5629
+ if (deps.routeEvent === undefined)
5630
+ return false;
5631
+ try {
5632
+ return deps.routeEvent(e, { runId, repository: repo ? `${repo.owner}/${repo.repo}` : undefined });
5633
+ } catch (err) {
5634
+ lose(`vinaya: the run record failed — ${err instanceof Error ? err.message : String(err)}
5635
+ `);
5636
+ return true;
5637
+ }
5638
+ }
5639
+ function log(e, attribution, opts = {}) {
5640
+ try {
5641
+ const call = snapshot(attribution);
5642
+ const write = async () => {
5643
+ const ctx = await context();
5644
+ if (routed(e, ctx.repo))
5645
+ return;
5646
+ try {
5647
+ retryDestinationIfDue(ctx);
5648
+ } catch {}
5649
+ if (ctx.destination.kind === "none") {
5650
+ writeEvent(e, call, ctx, null, null, true);
5651
+ return;
5652
+ }
5653
+ const branchIssue = call.envFields.task ? null : await branchIssueOnce(ctx.repo);
5654
+ const headSha = e.kind === "gate" ? await headShaOnce() : null;
5655
+ writeEvent(e, call, ctx, branchIssue, headSha, true, opts.unattributedStream);
5656
+ };
5657
+ const written = writeChain.then(write).catch((err) => {
5658
+ lose(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
5659
+ `);
5660
+ });
5661
+ writeChain = written;
5662
+ pendingWrites.add(written);
5663
+ written.finally(() => pendingWrites.delete(written));
5664
+ } catch (err) {
5665
+ lose(`vinaya: log() failed — ${err instanceof Error ? err.message : String(err)}
5666
+ `);
5667
+ }
5668
+ }
5669
+ function logSync(e, opts = {}) {
5670
+ try {
5671
+ const call = snapshot();
5672
+ let ctx = deps.readConfig()?.logs === false ? {
5673
+ repo: null,
5674
+ doctrine: "unknown",
5675
+ destination: { kind: "none", reason: "logs: false disables Log recording" }
5676
+ } : settledContext;
5677
+ if (ctx === undefined) {
5678
+ const destination = deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : deps.unresolvedLogDestination(deps.env());
5679
+ if (destination.kind === "folder" && !opts.quiet) {
5680
+ warnOnce(`vinaya: the process ended before its log destination was resolved — the event is written to ${destination.folder}; \`vinaya-log-send\` delivers it to a configured server later
5681
+ `);
5682
+ }
5683
+ ctx = { repo: null, doctrine: "unknown", destination };
5684
+ }
5685
+ if (routed(e, ctx.repo))
5686
+ return;
5687
+ const branchIssue = ctx.destination.kind === "none" || call.envFields.task ? null : branchIssueIfSettled(ctx.repo);
5688
+ const headSha = e.kind === "gate" && ctx.destination.kind !== "none" ? headShaIfSettled() : null;
5689
+ writeEvent(e, call, ctx, branchIssue, headSha, false, opts.unattributedStream);
5690
+ } catch (err) {
5691
+ lose(`vinaya: logSync() failed — ${err instanceof Error ? err.message : String(err)}
5692
+ `);
5693
+ }
5694
+ }
5695
+ const warmup = () => {
5696
+ const originalWarn = console.warn;
5697
+ console.warn = () => {};
5698
+ resolveRepoOnce().finally(() => {
5699
+ console.warn = originalWarn;
5700
+ });
5701
+ context().catch(() => {
5702
+ return;
5703
+ });
5704
+ };
5705
+ const drain = async () => {
5706
+ if (pendingWrites.size > 0)
5707
+ await Promise.allSettled(Array.from(pendingWrites));
5708
+ await drainChain.catch(() => {
5709
+ return;
5710
+ });
5711
+ for (const drainExtra of extraDrains)
5712
+ await drainExtra().catch(() => {
5713
+ return;
5714
+ });
5715
+ reportLostRecords();
5716
+ };
5717
+ return { log, logSync, runId, warmup, drain, resetContext };
5718
+ }
5719
+ function createDefaultLogSinkSlot(runId) {
5720
+ let factory;
5721
+ let sink;
5722
+ return {
5723
+ install: (next) => {
5724
+ factory = next;
5725
+ },
5726
+ sink: () => {
5727
+ if (sink !== undefined)
5728
+ return sink;
5729
+ if (factory === undefined)
5730
+ factory = loadDeferredLogSinkFactory();
5731
+ if (factory === undefined) {
5732
+ throw new Error("vinaya log: no default log sink factory is installed — the entry point calls installDefaultLogSinkFactory before anything logs");
5733
+ }
5734
+ sink = factory({ runId });
5735
+ return sink;
5736
+ },
5737
+ built: () => sink,
5738
+ runId
5739
+ };
5740
+ }
5741
+ function installDefaultLogSinkFactory(factory) {
5742
+ defaultSinkSlot.install(factory);
5743
+ }
5744
+ function currentRunId() {
5745
+ return defaultSinkSlot.runId;
5746
+ }
5747
+ function registerLogDrain(drain) {
5748
+ extraDrains.add(drain);
5749
+ }
5750
+ async function resolveProcessOtlpAddress(source) {
5751
+ await Promise.resolve().then(() => init_otlp_address());
5752
+ const unattended = isUnattendedProcess(process.env);
5753
+ return resolveOtlpAddress({
5754
+ localConfig: source.readConfig(),
5755
+ trustAnchorConfig: unattended ? await processTrustAnchor(repoRootSync()) : null,
5756
+ unattended,
5757
+ env: source.env()
5758
+ });
5759
+ }
5760
+ function processLocalCopyPlace(repository) {
5761
+ const base = defaultDeps();
5762
+ const found = resolveLocalCopySettings({
5763
+ home: base.home(),
5764
+ cwd: base.cwd(),
5765
+ handedRuntimeDir: base.env()[RUNTIME_DIR_ENV_KEY],
5766
+ unattended: isUnattendedProcess(process.env),
5767
+ defaultBranchLogs: () => defaultBranchSettingsNow(repoRootSync())
5768
+ }, repository);
5769
+ return found === undefined ? undefined : { folder: found.folder, repository, keepDays: found.keepDays };
5770
+ }
5771
+ function processLocalCopySender() {
5772
+ processSender ??= createLocalCopySender({
5773
+ warn: (message) => void process.stderr.write(message),
5774
+ address: () => resolveProcessOtlpAddress(defaultDeps())
5775
+ });
5776
+ return processSender;
5777
+ }
5778
+ var loopLog = () => (init_loop_log(), __toCommonJS(exports_loop_log)), OUTBOX_MAX_BYTES, LOG_FOLDER_ONLY_ENV = "VINAYA_LOG_FOLDER_ONLY", LOG_CONTEXT_LOOKUP_DEADLINE_MS = 3000, LOG_DESTINATION_ANCHOR_DEADLINE_MS = 8000, WITH_DEADLINE_GRACE_MS = 100, LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS = 30000, LOG_DESTINATION_ANCHOR_MAX_RETRIES = 5, processTrustAnchorByRepo, defaultBranchSettingsByRepo, SAFE_PATH_SEGMENT3, warnedThisProcess = false, branchIssueFallbackEnabled = true, branchIssueByCwd, branchIssueSettledByCwd, headShaByCwd, headShaSettledByCwd, execFileAsync3, APPEND_OPEN_FLAGS, defaultSinkSlot, extraDrains, processSender;
5779
+ var init_log_sink = __esm(() => {
5780
+ init_resolve_repo();
5781
+ init_envelope();
5782
+ init_schema();
5783
+ init_store();
5784
+ init_redact();
5785
+ init_local_copy_writer();
5786
+ init_config_schema();
5787
+ init_run_paths();
5788
+ OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
5789
+ processTrustAnchorByRepo = createTrustAnchorCache(safeLoadTrustAnchorConfig);
5790
+ defaultBranchSettingsByRepo = new Map;
5791
+ SAFE_PATH_SEGMENT3 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
5792
+ branchIssueByCwd = new Map;
5793
+ branchIssueSettledByCwd = new Map;
5794
+ headShaByCwd = new Map;
5795
+ headShaSettledByCwd = new Map;
5796
+ execFileAsync3 = promisify3(execFile3);
5797
+ APPEND_OPEN_FLAGS = fsConstants4.O_WRONLY | fsConstants4.O_APPEND | fsConstants4.O_CREAT | fsConstants4.O_NOFOLLOW | fsConstants4.O_NONBLOCK;
5798
+ defaultSinkSlot = createDefaultLogSinkSlot(process.env.VINAYA_RUN_ID || randomUUID2());
5799
+ extraDrains = new Set;
5800
+ });
5801
+
5802
+ // ../../harness/kernel/log/run-identity.ts
5803
+ function registerCliVersionSource(read) {
5804
+ source = read;
5805
+ }
5806
+ function registeredCliVersion() {
5807
+ try {
5808
+ const version = source?.();
5809
+ return version === undefined || version === "" || version === "unknown" ? undefined : version;
5810
+ } catch {
5811
+ return;
5812
+ }
5813
+ }
5814
+ var source;
5815
+
5816
+ // ../../harness/kernel/log/run-recorder.ts
5817
+ import { createHash as createHash4 } from "node:crypto";
5818
+ import { existsSync as existsSync4, readFileSync as readFileSync5, realpathSync as realpathSync3 } from "node:fs";
5819
+ import { homedir as homedir4 } from "node:os";
5820
+ import { dirname as dirname6, join as join6, resolve as resolvePath2 } from "node:path";
5821
+ import {
5822
+ connect,
5823
+ EVENT_NAMES,
5824
+ SPAN_NAMES
5825
+ } from "@attalabs/vinaya-log-sdk";
5826
+ function settingsDigestOf(root) {
5827
+ try {
5828
+ return createHash4("sha256").update(readFileSync5(join6(root, SETTINGS_FILE))).digest("hex");
5829
+ } catch {
5830
+ return;
5831
+ }
5832
+ }
5833
+ function inputsKey(inputs) {
5834
+ if (inputs === undefined)
5835
+ return "";
5836
+ const { brief, objectives, ruling, policy } = inputs;
5837
+ if (brief === undefined && objectives === undefined && ruling === undefined && policy === undefined)
5838
+ return "";
5839
+ return JSON.stringify([brief ?? null, objectives ?? null, ruling ?? null, policy ?? null]);
5840
+ }
5841
+ function spanRecordOf(span) {
5842
+ return {
5843
+ kind: "span",
5844
+ name: span.name,
5845
+ startTime: nanosOf(span.startTime),
5846
+ time: nanosOf(span.endTime),
5847
+ attributes: span.attributes
5848
+ };
5849
+ }
5850
+ function startedRecordOf(record) {
5851
+ return {
5852
+ kind: "started",
5853
+ name: String(record.eventName ?? ""),
5854
+ startTime: null,
5855
+ time: nanosOf(record.hrTime),
5856
+ attributes: record.attributes
5857
+ };
5858
+ }
5859
+ function createRunRecorder(deps) {
5860
+ let reported = false;
5861
+ const report = (error) => {
5862
+ if (reported)
5863
+ return;
5864
+ reported = true;
5865
+ try {
5866
+ deps.onError(error);
5867
+ } catch {}
5868
+ };
5869
+ const bound = {};
5870
+ const narrators = new Map;
5871
+ let starting;
5872
+ const narrateRecord = (record, spanId) => {
5873
+ try {
5874
+ const narrate = starting !== undefined ? starting.narrate : spanId !== undefined && narrators.has(spanId) ? narrators.get(spanId) : bound.narrate;
5875
+ narrate?.(record);
5876
+ } catch (error) {
5877
+ report(error);
5878
+ }
5879
+ };
5880
+ let launches = false;
5881
+ const trustNow = () => {
5882
+ if (launches)
5883
+ return "parent_attributed";
5884
+ const env = deps.environment?.() ?? { role: process.env.VINAYA_ROLE, task: process.env.VINAYA_TASK };
5885
+ return env.role || env.task ? "env_correlated" : "unavailable";
5886
+ };
5887
+ const idleProcessor = { forceFlush: async () => {}, shutdown: async () => {} };
5888
+ const runIdNow = () => bound.runId ?? deps.runId();
5889
+ const handles = new Map;
5890
+ function open(runId, repository, workRefOverride, inputs) {
5891
+ const repo = repository ?? bound.repository ?? deps.repository();
5892
+ const place = deps.place(repo);
5893
+ if (place === undefined)
5894
+ return;
5895
+ const trust = trustNow();
5896
+ const versions = inputsKey(inputs);
5897
+ const key = `${runId}\x00${place.folder}\x00${repo ?? ""}\x00${workRefOverride ?? ""}\x00${trust}\x00${versions}`;
5898
+ const known = handles.get(key);
5899
+ if (known !== undefined)
5900
+ return known;
5901
+ const home = deps.home();
5902
+ const workRef = workRefOverride ?? deps.workRef();
5903
+ const identity = deps.processIdentity();
5904
+ const parts = deps.runIdentity?.() ?? {};
5905
+ const settingsDigest = settingsDigestOf(deps.cwd());
5906
+ const runIdentity = {
5907
+ ...parts.runnerName ? { runnerName: parts.runnerName } : {},
5908
+ ...parts.runnerVersion ? { runnerVersion: parts.runnerVersion } : {},
5909
+ ...parts.cliVersion ? { cliVersion: parts.cliVersion } : {},
5910
+ ...parts.flowId ? { flowId: parts.flowId } : {},
5911
+ ...parts.flowVersion ? { flowVersion: parts.flowVersion } : {},
5912
+ ...parts.processDigest ? { processDigest: parts.processDigest } : {},
5913
+ ...settingsDigest === undefined ? {} : { settingsDigest }
5914
+ };
5915
+ const log = (deps.connect ?? connect)({
5916
+ runId,
5917
+ ...repo === undefined ? {} : { repository: repo },
5918
+ repoRoot: deps.cwd(),
5919
+ destination: { folder: place.folder },
5920
+ ...place.keepDays === undefined ? {} : { keepDays: place.keepDays },
5921
+ vinayaHome: join6(home, ".vinaya"),
5922
+ home,
5923
+ provenance: "governed",
5924
+ trust,
5925
+ identity: runIdentity,
5926
+ ...identity === undefined ? {} : { processName: identity.name, serviceVersion: identity.version },
5927
+ ...workRef === undefined ? {} : { workRef },
5928
+ ...versions === "" || inputs === undefined ? {} : { inputs },
5929
+ spanProcessors: [
5930
+ {
5931
+ ...idleProcessor,
5932
+ onStart: () => {},
5933
+ onEnd: (span) => {
5934
+ if (span.name === SPAN_NAMES.agent || span.name.startsWith(`${SPAN_NAMES.agent} `))
5935
+ narrateRecord(spanRecordOf(span), span.spanContext().spanId);
5936
+ }
5937
+ }
5938
+ ],
5939
+ logRecordProcessors: [
5940
+ {
5941
+ ...idleProcessor,
5942
+ onEmit: (record) => {
5943
+ if (record.eventName === EVENT_NAMES.agentStarted)
5944
+ narrateRecord(startedRecordOf(record), record.spanContext?.spanId);
5945
+ }
5946
+ }
5947
+ ],
5948
+ onError: report
5949
+ });
5950
+ const made = { log, place };
5951
+ handles.set(key, made);
5952
+ return made;
5953
+ }
5954
+ const absent = { observe: () => {}, close: () => {} };
5955
+ function stepsUnder(opened, parent, key) {
5956
+ if (opened === undefined || parent === undefined)
5957
+ return absent;
5958
+ const { log } = opened;
5959
+ const open = new Map;
5960
+ return {
5961
+ observe(step) {
5962
+ try {
5963
+ if (step.type === "start") {
5964
+ if (open.has(step.id))
5965
+ return;
5966
+ const ref = log.agent.stepStarted({
5967
+ tool: step.tool,
5968
+ callId: step.id,
5969
+ kind: step.kind,
5970
+ target: step.target,
5971
+ parent,
5972
+ key: `step:${key}:${step.id}`,
5973
+ startTime: step.at
5974
+ });
5975
+ open.set(step.id, { ref, startedAt: step.at });
5976
+ return;
5977
+ }
5978
+ const started = open.get(step.id);
5979
+ if (started === undefined)
5980
+ return;
5981
+ open.delete(step.id);
5982
+ log.agent.stepEnded(started.ref, {
5983
+ endTime: started.startedAt + step.durationMs,
5984
+ ...step.ok ? {} : { errorType: step.failedTests === undefined ? "failed" : "tests_failed" },
5985
+ ...step.ok || step.failedTests === undefined ? {} : { errorLine: `${step.failedTests} failed` }
5986
+ });
5987
+ } catch (error) {
5988
+ report(error);
5989
+ }
5990
+ },
5991
+ close() {
5992
+ try {
5993
+ for (const [id, started] of open) {
5994
+ open.delete(id);
5995
+ log.agent.stepEnded(started.ref, { errorType: "interrupted" });
5996
+ }
5997
+ } catch (error) {
5998
+ report(error);
5999
+ }
6000
+ }
6001
+ };
6002
+ }
6003
+ const sendSoon = (place) => {
6004
+ try {
6005
+ deps.sender().request(place);
6006
+ } catch (error) {
6007
+ report(error);
6008
+ }
6009
+ };
6010
+ return {
6011
+ launching() {
6012
+ launches = true;
6013
+ },
6014
+ bind(run) {
6015
+ bound.runId = run.runId;
6016
+ bound.repository = run.repository;
6017
+ bound.narrate = run.narrate;
6018
+ bound.effort = run.effort;
6019
+ },
6020
+ handle(runId = runIdNow(), repository, workRef) {
6021
+ try {
6022
+ return open(runId, repository, workRef)?.log;
6023
+ } catch (error) {
6024
+ report(error);
6025
+ return;
6026
+ }
6027
+ },
6028
+ turn(start) {
6029
+ const runId = start.runId ?? runIdNow();
6030
+ let opened;
6031
+ let ref;
6032
+ try {
6033
+ opened = open(runId, start.repository, start.workRef, start.inputs);
6034
+ starting = { narrate: start.narrate ?? bound.narrate };
6035
+ ref = opened?.log.agent.sent({
6036
+ seat: start.seat,
6037
+ ...start.provider === undefined ? {} : { provider: start.provider },
6038
+ ...start.model === undefined ? {} : { model: start.model },
6039
+ ...start.codingAgent === undefined ? {} : { codingAgent: start.codingAgent },
6040
+ ...start.codingAgentVersion === undefined ? {} : { codingAgentVersion: start.codingAgentVersion },
6041
+ ...start.round === undefined || start.round === null ? {} : { round: start.round },
6042
+ effort: start.effort ?? bound.effort ?? DEFAULT_TURN_EFFORT,
6043
+ ...start.key === undefined ? {} : { key: `agent:${start.key}` },
6044
+ ...start.startTime === undefined ? {} : { startTime: start.startTime }
6045
+ }) ?? undefined;
6046
+ } catch (error) {
6047
+ report(error);
6048
+ } finally {
6049
+ if (ref !== undefined)
6050
+ narrators.set(ref.spanId, start.narrate ?? bound.narrate);
6051
+ starting = undefined;
6052
+ }
6053
+ const steps = stepsUnder(opened, ref, start.key ?? `${start.seat}:${Date.now()}`);
6054
+ const guarded = (work) => {
6055
+ try {
6056
+ if (opened === undefined || ref === undefined)
6057
+ return;
6058
+ work(opened.log, ref);
6059
+ } catch (error) {
6060
+ report(error);
6061
+ }
6062
+ };
6063
+ return {
6064
+ ref,
6065
+ steps,
6066
+ usage(usage) {
6067
+ guarded((log, agent) => {
6068
+ const known = (value) => value === null || value === undefined ? undefined : value;
6069
+ const unknownReason = usage.unknownReason ?? (known(usage.inputTokens) === undefined && known(usage.outputTokens) === undefined ? "no usage was reported" : undefined);
6070
+ log.usage.recorded({
6071
+ agent,
6072
+ ...unknownReason === undefined || unknownReason === null ? {} : { unknownReason },
6073
+ ...known(usage.inputTokens) === undefined ? {} : { inputTokens: known(usage.inputTokens) },
6074
+ ...known(usage.outputTokens) === undefined ? {} : { outputTokens: known(usage.outputTokens) },
6075
+ ...known(usage.cacheReadInputTokens) === undefined ? {} : { cacheReadInputTokens: known(usage.cacheReadInputTokens) },
6076
+ ...usage.cost === undefined ? {} : { cost: usage.cost },
6077
+ ...usage.costUnknownReason === undefined ? {} : { costUnknownReason: usage.costUnknownReason }
6078
+ });
6079
+ });
6080
+ },
6081
+ returned(end = {}) {
6082
+ steps.close();
6083
+ guarded((log, agent) => {
6084
+ log.agent.returned({
6085
+ agent,
6086
+ ...end.outcome === undefined ? {} : { outcome: end.outcome },
6087
+ ...end.attempt === undefined || end.attempt === null ? {} : { attempt: end.attempt },
6088
+ ...end.responseModel === undefined ? {} : { responseModel: end.responseModel },
6089
+ ...end.endTime === undefined ? {} : { endTime: end.endTime }
6090
+ });
6091
+ if (opened !== undefined)
6092
+ sendSoon(opened.place);
6093
+ });
6094
+ },
6095
+ failed(end) {
6096
+ steps.close();
6097
+ guarded((log, agent) => {
6098
+ log.agent.failed({
6099
+ agent,
6100
+ errorType: end.errorType,
6101
+ ...end.resetAt === undefined ? {} : { resetAt: end.resetAt },
6102
+ ...end.attempt === undefined || end.attempt === null ? {} : { attempt: end.attempt },
6103
+ ...end.endTime === undefined ? {} : { endTime: end.endTime }
6104
+ });
6105
+ if (opened !== undefined)
6106
+ sendSoon(opened.place);
6107
+ });
6108
+ }
6109
+ };
6110
+ },
6111
+ stageChanged(change, runId = runIdNow()) {
6112
+ try {
6113
+ open(runId)?.log.run.stageChanged({ to: change.stage, round: change.round });
6114
+ } catch (error) {
6115
+ report(error);
6116
+ }
6117
+ },
6118
+ async drain() {
6119
+ try {
6120
+ const places = [];
6121
+ for (const { log, place } of handles.values()) {
6122
+ await log.flush().catch(report);
6123
+ places.push(place);
6124
+ }
6125
+ const last = places[places.length - 1];
6126
+ if (last === undefined)
6127
+ return;
6128
+ deps.sender().remember(last);
6129
+ await deps.sender().drain();
6130
+ } catch (error) {
6131
+ report(error);
6132
+ }
6133
+ }
6134
+ };
6135
+ }
6136
+ function identityFromEnvironment() {
6137
+ const name = process.env.VINAYA_PROCESS_ID;
6138
+ const version = process.env.VINAYA_PROCESS_VERSION;
6139
+ return name && version ? { name, version } : undefined;
6140
+ }
6141
+ function runIdentityFromEnvironment() {
6142
+ const { VINAYA_RUNNER_ID, VINAYA_RUNNER_VERSION, VINAYA_FLOW, VINAYA_FLOW_VERSION, VINAYA_PROCESS_DIGEST } = process.env;
6143
+ const cliVersion = registeredCliVersion();
6144
+ return {
6145
+ ...VINAYA_RUNNER_ID ? { runnerName: VINAYA_RUNNER_ID } : {},
6146
+ ...VINAYA_RUNNER_VERSION ? { runnerVersion: VINAYA_RUNNER_VERSION } : {},
6147
+ ...cliVersion === undefined ? {} : { cliVersion },
6148
+ ...VINAYA_FLOW ? { flowId: VINAYA_FLOW } : {},
6149
+ ...VINAYA_FLOW_VERSION ? { flowVersion: VINAYA_FLOW_VERSION } : {},
6150
+ ...VINAYA_PROCESS_DIGEST ? { processDigest: VINAYA_PROCESS_DIGEST } : {}
6151
+ };
6152
+ }
6153
+ function githubRepositoryOf(url) {
6154
+ const match = /^git@github\.com:([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(url) ?? /^ssh:\/\/(?:[^@/]+@)?github\.com(?::\d+)?\/([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(url) ?? /^https?:\/\/(?:[^@/]+@)?github\.com\/([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(url);
6155
+ return match?.[1] && match[2] && !match[2].includes("/") ? `${match[1]}/${match[2]}` : undefined;
6156
+ }
6157
+ function originUrlOf(config) {
6158
+ let inOrigin = false;
6159
+ for (const raw of config.split(/\r?\n/)) {
6160
+ const line = raw.trim();
6161
+ if (line.startsWith("[")) {
6162
+ inOrigin = /^\[\s*remote\s+"origin"\s*\]$/.test(line);
6163
+ continue;
6164
+ }
6165
+ if (!inOrigin)
6166
+ continue;
6167
+ const entry = /^url\s*=\s*(.*)$/i.exec(line);
6168
+ if (entry?.[1] !== undefined)
6169
+ return entry[1].trim().replace(/^"(.*)"$/, "$1");
6170
+ }
6171
+ return;
6172
+ }
6173
+ function checkoutRepository(start, reader = fileReader) {
6174
+ try {
6175
+ let dir = reader.realpath(start);
6176
+ for (;; ) {
6177
+ const dotGit = join6(dir, ".git");
6178
+ if (reader.exists(dotGit)) {
6179
+ const url = originUrlOf(reader.readText(join6(gitCommonDir(dotGit, dir, reader), "config")));
6180
+ return url === undefined ? undefined : githubRepositoryOf(url);
6181
+ }
6182
+ const parent = dirname6(dir);
6183
+ if (parent === dir)
6184
+ return;
6185
+ dir = parent;
6186
+ }
6187
+ } catch {
6188
+ return;
6189
+ }
6190
+ }
6191
+ function gitCommonDir(dotGit, root, reader) {
6192
+ let pointer;
6193
+ try {
6194
+ pointer = reader.readText(dotGit);
6195
+ } catch {
6196
+ return dotGit;
6197
+ }
6198
+ const named = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
6199
+ if (named === undefined)
6200
+ return dotGit;
6201
+ const gitDir = resolvePath2(root, named);
6202
+ try {
6203
+ const common = reader.readText(join6(gitDir, "commondir")).trim();
6204
+ return common === "" ? gitDir : resolvePath2(gitDir, common);
6205
+ } catch {
6206
+ return gitDir;
6207
+ }
6208
+ }
6209
+ function processRepository(source = {
6210
+ env: () => process.env,
6211
+ cwd: () => process.cwd()
6212
+ }) {
6213
+ let checkout;
6214
+ return () => {
6215
+ const named = source.env().VINAYA_REPO;
6216
+ if (named)
6217
+ return named;
6218
+ checkout ??= { repository: checkoutRepository(source.cwd(), source.reader) };
6219
+ return checkout.repository;
6220
+ };
6221
+ }
6222
+ function runRecorder() {
6223
+ shared ??= createRunRecorder({
6224
+ runId: currentRunId,
6225
+ workRef: () => process.env.VINAYA_TASK || undefined,
6226
+ repository: processRepository(),
6227
+ place: processLocalCopyPlace,
6228
+ processIdentity: identityFromEnvironment,
6229
+ runIdentity: runIdentityFromEnvironment,
6230
+ sender: processLocalCopySender,
6231
+ home: () => homedir4(),
6232
+ cwd: () => process.cwd(),
6233
+ onError: (error) => void process.stderr.write(`vinaya: the OpenTelemetry run recorder failed — ${error instanceof Error ? error.message : String(error)}
6234
+ `)
6235
+ });
6236
+ const recorder = shared;
6237
+ registerLogDrain(() => recorder.drain());
6238
+ return shared;
6239
+ }
6240
+ var DEFAULT_TURN_EFFORT = "medium", SETTINGS_FILE = "vinaya.config.json", nanosOf = (time) => (BigInt(time[0]) * 1000000000n + BigInt(time[1])).toString(), shared, fileReader;
6241
+ var init_run_recorder = __esm(() => {
6242
+ init_log_sink();
6243
+ fileReader = {
6244
+ exists: (path) => existsSync4(path),
6245
+ readText: (path) => readFileSync5(path, "utf8"),
6246
+ realpath: (path) => realpathSync3(path)
6247
+ };
6248
+ });
6249
+
6250
+ // ../../harness/kernel/log/outside-log.ts
6251
+ function warnOnce(error) {
6252
+ if (warned)
6253
+ return;
6254
+ warned = true;
6255
+ try {
6256
+ process.stderr.write(`vinaya: a record could not be written to the Log — ${String(error)}
6257
+ `);
6258
+ } catch {}
6259
+ }
6260
+ function through(scope, write) {
6261
+ try {
6262
+ const handle = runRecorder().handle(scope?.runId, undefined, scope?.task === undefined ? undefined : String(scope.task));
6263
+ if (handle !== undefined)
6264
+ write(handle);
6265
+ } catch (error) {
6266
+ warnOnce(error);
6267
+ }
6268
+ }
6269
+ function writeForgeRefused(record, scope) {
6270
+ through(scope, (log) => log.forge.refused(record));
6271
+ }
6272
+ var warned = false;
6273
+ var init_outside_log = __esm(() => {
6274
+ init_run_recorder();
6275
+ });
6276
+
6277
+ // ../../harness/kernel/effects/effects.ts
6278
+ var init_effects = __esm(() => {
6279
+ init_control_store();
6280
+ init_outside_log();
6281
+ init_run_paths();
6282
+ });
6283
+
6284
+ // ../../harness/processes/vinaya-strict/executing/developer/developer-turn-result.ts
6285
+ import { z as z3 } from "zod/v4";
6286
+ var DEVELOPER_TURN_RESULT_SCHEMA_VERSION = 1, BLOCKER_KINDS, schemaVersion, summary, SourceUseSchema, ReportedCheckSchema, DeveloperTurnResultSchema, DeveloperTurnOutputSchema;
6287
+ var init_developer_turn_result = __esm(() => {
6288
+ init_schema();
6289
+ BLOCKER_KINDS = [
6290
+ "dependency_unmerged",
6291
+ "conflict_open",
6292
+ "preflight_failed",
6293
+ "premise_stale",
6294
+ "brief_contradicts_code",
6295
+ "test_failure",
6296
+ "destructive_unauthorized",
6297
+ "tooling_unavailable"
6298
+ ];
6299
+ schemaVersion = z3.literal(DEVELOPER_TURN_RESULT_SCHEMA_VERSION);
6300
+ summary = z3.string().min(1);
6301
+ SourceUseSchema = z3.object({
6302
+ source: z3.string().min(1),
6303
+ use: z3.string().min(1)
6304
+ }).strict();
6305
+ ReportedCheckSchema = z3.object({
6306
+ command: z3.string().min(1),
6307
+ outcome: z3.enum(["pass", "fail"])
6308
+ }).strict();
6309
+ DeveloperTurnResultSchema = z3.discriminatedUnion("status", [
6310
+ z3.object({
6311
+ schemaVersion,
6312
+ status: z3.literal("completed"),
6313
+ summary,
6314
+ confidence: z3.number().int().min(0).max(100),
6315
+ confidenceExplanation: z3.string().min(1).max(CONFIDENCE_REASON_MAX_LENGTH),
6316
+ addressedFindingIds: z3.array(z3.string().min(1)),
6317
+ sourceUses: z3.array(SourceUseSchema).nullable(),
6318
+ reportedChecks: z3.array(ReportedCheckSchema).nullable()
6319
+ }).strict(),
6320
+ z3.object({
6321
+ schemaVersion,
6322
+ status: z3.literal("blocked"),
6323
+ summary,
6324
+ blocker: z3.object({ kind: z3.enum(BLOCKER_KINDS), detail: z3.string().min(1) }).strict(),
6325
+ sourceUses: z3.array(SourceUseSchema).nullable()
6326
+ }).strict(),
6327
+ z3.object({
6328
+ schemaVersion,
6329
+ status: z3.literal("needs_ruling"),
6330
+ summary,
6331
+ rulingRequest: z3.object({ question: z3.string().min(1), decisions: z3.array(z3.string().min(1)) }).strict(),
6332
+ sourceUses: z3.array(SourceUseSchema).nullable()
6333
+ }).strict()
6334
+ ]);
6335
+ DeveloperTurnOutputSchema = z3.object({ turnResult: DeveloperTurnResultSchema }).strict();
6336
+ });
6337
+
6338
+ // ../../harness/processes/vinaya-strict/loops/dev-review/standalone/dev-review-loop/stop-decision.ts
6339
+ var CI_PARENT_WAIT_MAX_MS;
6340
+ var init_stop_decision = __esm(() => {
6341
+ init_round_assess();
6342
+ CI_PARENT_WAIT_MAX_MS = 90 * 60000;
6343
+ });
6344
+
6345
+ // ../../harness/processes/vinaya-strict/loops/dev-review/standalone/dev-review-loop/turn-result.ts
6346
+ var init_turn_result = __esm(() => {
6347
+ init_schema();
6348
+ init_developer_turn_result();
6349
+ init_run_paths();
6350
+ init_stop_decision();
6351
+ });
6352
+
6353
+ // ../../harness/processes/vinaya-strict/loops/dev-review/standalone/dev-review-loop/round-assess.ts
6354
+ function unreachedHostOfLine(line) {
6355
+ const ghDns = /^error connecting to (\S+)$/.exec(line);
6356
+ if (ghDns)
6357
+ return ghDns[1];
6358
+ const sshDns = /^ssh: Could not resolve hostname ([^:\s]+):/.exec(line);
6359
+ if (sshDns)
6360
+ return sshDns[1];
6361
+ const sshConnect = /^ssh: connect to host (\S+) port \d+: (.+)$/.exec(line);
6362
+ if (sshConnect)
6363
+ return NO_RESPONSE_CAUSE.test(sshConnect[2].trim()) ? sshConnect[1] : null;
6364
+ const urlError = /^(?:Get|Post|Put|Patch|Delete|Head) "(https?:\/\/[^"]+)": (.+)$/.exec(line) ?? /^fatal: unable to access '(https?:\/\/[^']+)': (.+)$/.exec(line);
6365
+ if (!urlError || !NO_RESPONSE_CAUSE.test(urlError[2].trim()))
6366
+ return null;
6367
+ try {
6368
+ return new URL(urlError[1]).hostname;
6369
+ } catch {
6370
+ return null;
6371
+ }
6372
+ }
6373
+ function isGitHubConnectionFailure(err) {
6374
+ let current = err;
6375
+ for (let depth = 0;depth < 5 && current instanceof Error; depth += 1) {
6376
+ if (current instanceof GitHubKeptAnswering)
6377
+ return false;
6378
+ const fields = current;
6379
+ if (typeof fields.code === "string" && NO_RESPONSE_CODES.has(fields.code)) {
6380
+ const where = [fields.hostname, fields.host, fields.path, fields.url].find((v) => typeof v === "string");
6381
+ if (typeof where === "string" && GITHUB_HOST.test(where))
6382
+ return true;
6383
+ }
6384
+ const stderr = fields.stderr === undefined ? "" : String(fields.stderr);
6385
+ for (const line of `${stderr}
6386
+ ${current.message}`.split(`
6387
+ `)) {
6388
+ const host = unreachedHostOfLine(line.trim());
6389
+ if (host !== null && GITHUB_HOST.test(host))
6390
+ return true;
6391
+ }
6392
+ current = current.cause;
6393
+ }
6394
+ return false;
6395
+ }
6396
+ function isRunLifecycleEvent(event) {
6397
+ return event.kind === "dev_review_loop" && typeof event.event === "string" && RUN_LIFECYCLE_EVENTS.has(event.event);
6398
+ }
6399
+ function isRoundOrChangeEvent(event) {
6400
+ return event.kind === "dev_review_loop" && typeof event.event === "string" && ROUND_AND_CHANGE_EVENTS.has(event.event);
6401
+ }
6402
+ function isHandleEvent(event) {
6403
+ return isRunLifecycleEvent(event) || isRoundOrChangeEvent(event);
6404
+ }
6405
+ var NO_RESPONSE_CODES, NO_RESPONSE_CAUSE, GITHUB_HOST, GitHubKeptAnswering, RATE_LIMIT_FALLBACK_WAIT_MS, RUN_LIFECYCLE_EVENTS, ROUND_AND_CHANGE_EVENTS, MAX_USAGE_LIMIT_AUTO_WAIT_MS;
6406
+ var init_round_assess = __esm(() => {
6407
+ init_schema();
6408
+ init_control_store();
6409
+ init_effects();
6410
+ init_turn_result();
6411
+ init_legacy_markers();
6412
+ NO_RESPONSE_CODES = new Set([
6413
+ "ENOTFOUND",
6414
+ "EAI_AGAIN",
6415
+ "ECONNREFUSED",
6416
+ "ECONNRESET",
6417
+ "ECONNABORTED",
6418
+ "ETIMEDOUT",
6419
+ "ENETUNREACH",
6420
+ "ENETDOWN",
6421
+ "EHOSTUNREACH",
6422
+ "EHOSTDOWN",
6423
+ "UND_ERR_CONNECT_TIMEOUT",
6424
+ "UND_ERR_SOCKET",
6425
+ "ConnectionRefused",
6426
+ "ConnectionClosed",
6427
+ "FailedToOpenSocket"
6428
+ ]);
6429
+ NO_RESPONSE_CAUSE = /dial tcp|i\/o timeout|connection refused|connection reset|no such host|network is unreachable|TLS handshake timeout|Client\.Timeout exceeded|server misbehaving|^EOF$|could not resolve host|failed to connect|couldn't connect to server|connection timed out|no route to host|operation timed out|resolving timed out/i;
6430
+ GITHUB_HOST = /github/i;
6431
+ GitHubKeptAnswering = class GitHubKeptAnswering extends Error {
6432
+ constructor(original) {
6433
+ super(`GitHub answered the reachability check, but this step's request kept failing: ${original instanceof Error ? original.message : String(original)}`);
6434
+ this.name = "GitHubKeptAnswering";
6435
+ }
6436
+ };
6437
+ RATE_LIMIT_FALLBACK_WAIT_MS = 5 * 60 * 1000;
6438
+ RUN_LIFECYCLE_EVENTS = new Set([
6439
+ "loop_started",
6440
+ "journal_finalized",
6441
+ "paused",
6442
+ "resumed",
6443
+ "cancelled",
6444
+ "infrastructure_retry",
6445
+ "stop_condition_met",
6446
+ "driver_exited"
6447
+ ]);
6448
+ ROUND_AND_CHANGE_EVENTS = new Set([
6449
+ "round_started",
6450
+ "round_ended",
6451
+ "phase_time",
6452
+ "verdicts_read",
6453
+ "findings_compared",
6454
+ "gate_result_read",
6455
+ "storage_push",
6456
+ "ready_push",
6457
+ "local_checks_run",
6458
+ "failed_tests_rerun",
6459
+ "ci_result_read",
6460
+ "pr_opened",
6461
+ "conflict_reentry",
6462
+ "unpushed_work_resume"
6463
+ ]);
6464
+ MAX_USAGE_LIMIT_AUTO_WAIT_MS = 6 * 60 * 60 * 1000;
6465
+ });
6466
+
6467
+ // ../../harness/kernel/gates/checks/contract.ts
6468
+ function emitCheckError(error) {
6469
+ process.stderr.write(`${JSON.stringify(error)}
6470
+ `);
6471
+ }
6472
+ var CHECK_SCHEMA_VERSION = 1;
6473
+
6474
+ // ../../harness/kernel/log/custom.ts
6475
+ import {
6476
+ CUSTOM_EVENT_MAX_FIELDS,
6477
+ CUSTOM_EVENT_NAME_MAX_LENGTH,
6478
+ CUSTOM_EVENT_NAME_PATTERN,
6479
+ CUSTOM_EVENT_RESERVED_NAMESPACE,
6480
+ CUSTOM_FIELD_MAX_WORDS,
6481
+ CUSTOM_FIELD_NAME_MAX_LENGTH,
6482
+ CUSTOM_FIELD_NAME_PATTERN,
6483
+ CUSTOM_TEXT_MAX_LENGTH,
6484
+ CUSTOM_WORD_MAX_LENGTH,
6485
+ CUSTOM_WORD_PATTERN,
6486
+ CustomEventDeclarationsSchema,
6487
+ checkCustomEvent,
6488
+ UNRECORDABLE_FIELD_NAME
6489
+ } from "@attalabs/vinaya-log-sdk";
6490
+ var init_custom = () => {};
6491
+
3259
6492
  // ../../harness/kernel/adapters/agents/agent-vendors.ts
3260
6493
  var AGENT_VENDORS;
3261
6494
  var init_agent_vendors = __esm(() => {
@@ -3263,10 +6496,10 @@ var init_agent_vendors = __esm(() => {
3263
6496
  });
3264
6497
 
3265
6498
  // ../../harness/kernel/config/loader/config-loader.ts
3266
- import { execFile as execFile3, execFileSync as execFileSync2 } from "node:child_process";
3267
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync as realpathSync2, writeFileSync } from "node:fs";
3268
- import { basename as basename2, dirname, join, resolve } from "node:path";
3269
- import { promisify as promisify3 } from "node:util";
6499
+ import { execFile as execFile5, execFileSync as execFileSync4 } from "node:child_process";
6500
+ import { existsSync as existsSync5, lstatSync as lstatSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync6, realpathSync as realpathSync4, writeFileSync as writeFileSync3 } from "node:fs";
6501
+ import { basename as basename2, dirname as dirname7, join as join7, resolve as resolve2 } from "node:path";
6502
+ import { promisify as promisify5 } from "node:util";
3270
6503
  function firstLine(err) {
3271
6504
  return err?.message?.split(`
3272
6505
  `)[0] ?? "unknown error";
@@ -3302,7 +6535,7 @@ function trustAnchorRepo() {
3302
6535
  if (fromRunner)
3303
6536
  return fromRunner;
3304
6537
  try {
3305
- const url = execFileSync2("git", ["remote", "get-url", "origin"], {
6538
+ const url = execFileSync4("git", ["remote", "get-url", "origin"], {
3306
6539
  encoding: "utf-8",
3307
6540
  stdio: ["ignore", "pipe", "pipe"]
3308
6541
  });
@@ -3316,7 +6549,7 @@ async function trustAnchorRepoAsync() {
3316
6549
  if (fromRunner)
3317
6550
  return fromRunner;
3318
6551
  try {
3319
- const { stdout } = await execFileAsync3("git", ["remote", "get-url", "origin"], {
6552
+ const { stdout } = await execFileAsync5("git", ["remote", "get-url", "origin"], {
3320
6553
  encoding: "utf-8",
3321
6554
  timeout: 1e4,
3322
6555
  killSignal: "SIGKILL"
@@ -3336,9 +6569,9 @@ function resolveCiTrustAnchorProbeRef(env, probeRefVariable) {
3336
6569
  return null;
3337
6570
  return ref;
3338
6571
  }
3339
- function gitCommonDir(cwd = process.cwd()) {
6572
+ function gitCommonDir2(cwd = process.cwd()) {
3340
6573
  try {
3341
- const raw = execFileSync2("git", ["rev-parse", "--git-common-dir"], {
6574
+ const raw = execFileSync4("git", ["rev-parse", "--git-common-dir"], {
3342
6575
  cwd,
3343
6576
  encoding: "utf-8",
3344
6577
  stdio: ["ignore", "pipe", "pipe"],
@@ -3346,20 +6579,20 @@ function gitCommonDir(cwd = process.cwd()) {
3346
6579
  }).trim();
3347
6580
  if (!raw)
3348
6581
  return null;
3349
- return realpathSync2(resolve(cwd, raw));
6582
+ return realpathSync4(resolve2(cwd, raw));
3350
6583
  } catch {
3351
6584
  return null;
3352
6585
  }
3353
6586
  }
3354
6587
  function gitAbsoluteDir(cwd) {
3355
6588
  try {
3356
- const raw = execFileSync2("git", ["rev-parse", "--absolute-git-dir"], {
6589
+ const raw = execFileSync4("git", ["rev-parse", "--absolute-git-dir"], {
3357
6590
  cwd,
3358
6591
  encoding: "utf-8",
3359
6592
  stdio: ["ignore", "pipe", "pipe"],
3360
6593
  timeout: GIT_IDENTITY_TIMEOUT_MS
3361
6594
  }).trim();
3362
- return raw ? realpathSync2(raw) : null;
6595
+ return raw ? realpathSync4(raw) : null;
3363
6596
  } catch {
3364
6597
  return null;
3365
6598
  }
@@ -3375,16 +6608,16 @@ function flattenKeys(value, prefix, out) {
3375
6608
  function readLocalOverrideFile(options, cwd = process.cwd()) {
3376
6609
  if (options.suppressedBy.some((name) => process.env[name]))
3377
6610
  return null;
3378
- const common = gitCommonDir(cwd);
6611
+ const common = gitCommonDir2(cwd);
3379
6612
  if (!common || basename2(common) !== ".git")
3380
6613
  return null;
3381
- const root = dirname(common);
6614
+ const root = dirname7(common);
3382
6615
  if (gitAbsoluteDir(cwd) !== common)
3383
6616
  return null;
3384
- const path = join(root, options.fileName);
6617
+ const path = join7(root, options.fileName);
3385
6618
  let stat;
3386
6619
  try {
3387
- stat = lstatSync(path);
6620
+ stat = lstatSync4(path);
3388
6621
  } catch {
3389
6622
  return null;
3390
6623
  }
@@ -3392,7 +6625,7 @@ function readLocalOverrideFile(options, cwd = process.cwd()) {
3392
6625
  return null;
3393
6626
  let raw;
3394
6627
  try {
3395
- raw = JSON.parse(readFileSync(path, "utf-8"));
6628
+ raw = JSON.parse(readFileSync6(path, "utf-8"));
3396
6629
  } catch (err) {
3397
6630
  throw new Error(`${options.fileName}: invalid JSON — ${err.message}`);
3398
6631
  }
@@ -3416,16 +6649,16 @@ function schemaIssueDetail(error) {
3416
6649
  }
3417
6650
  function createConfigLoader(options) {
3418
6651
  const { schema, localFileName, homeDir } = options;
3419
- const globalConfigPath = join(homeDir, options.globalFileName);
6652
+ const globalConfigPath = join7(homeDir, options.globalFileName);
3420
6653
  function findLocalConfig() {
3421
6654
  let dir = process.cwd();
3422
6655
  while (true) {
3423
- const candidate = join(dir, localFileName);
3424
- if (existsSync(candidate))
6656
+ const candidate = join7(dir, localFileName);
6657
+ if (existsSync5(candidate))
3425
6658
  return candidate;
3426
- if (existsSync(join(dir, ".git")))
6659
+ if (existsSync5(join7(dir, ".git")))
3427
6660
  return null;
3428
- const parent = dirname(dir);
6661
+ const parent = dirname7(dir);
3429
6662
  if (parent === dir)
3430
6663
  return null;
3431
6664
  dir = parent;
@@ -3435,13 +6668,13 @@ function createConfigLoader(options) {
3435
6668
  const local = findLocalConfig();
3436
6669
  if (local)
3437
6670
  return local;
3438
- if (existsSync(globalConfigPath))
6671
+ if (existsSync5(globalConfigPath))
3439
6672
  return globalConfigPath;
3440
6673
  return null;
3441
6674
  }
3442
6675
  function repoLocalConfigDir() {
3443
6676
  const local = findLocalConfig();
3444
- return local ? dirname(local) : null;
6677
+ return local ? dirname7(local) : null;
3445
6678
  }
3446
6679
  const emittedGlobalKeyWarnings = new Set;
3447
6680
  function warnGlobalKeyIgnoredOnce(message) {
@@ -3477,7 +6710,7 @@ ${detail}`;
3477
6710
  return null;
3478
6711
  let text;
3479
6712
  try {
3480
- text = readFileSync(path, "utf-8");
6713
+ text = readFileSync6(path, "utf-8");
3481
6714
  } catch (err) {
3482
6715
  reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
3483
6716
  return null;
@@ -3502,7 +6735,7 @@ ${detail}`;
3502
6735
  return { ok: true, config: null };
3503
6736
  let raw;
3504
6737
  try {
3505
- raw = JSON.parse(readFileSync(path, "utf-8"));
6738
+ raw = JSON.parse(readFileSync6(path, "utf-8"));
3506
6739
  } catch (err) {
3507
6740
  return { ok: false, path, error: `invalid JSON: ${err.message}` };
3508
6741
  }
@@ -3513,11 +6746,11 @@ ${detail}`;
3513
6746
  return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
3514
6747
  }
3515
6748
  function readRepoConfig(repoRoot) {
3516
- const p = join(repoRoot, localFileName);
3517
- if (!existsSync(p))
6749
+ const p = join7(repoRoot, localFileName);
6750
+ if (!existsSync5(p))
3518
6751
  return null;
3519
6752
  try {
3520
- return schema.parse(JSON.parse(readFileSync(p, "utf-8")));
6753
+ return schema.parse(JSON.parse(readFileSync6(p, "utf-8")));
3521
6754
  } catch {
3522
6755
  return null;
3523
6756
  }
@@ -3526,17 +6759,17 @@ ${detail}`;
3526
6759
  let targetPath;
3527
6760
  if (scope === "local") {
3528
6761
  const base = repoRoot ?? process.cwd();
3529
- targetPath = join(base, localFileName);
6762
+ targetPath = join7(base, localFileName);
3530
6763
  } else {
3531
- if (!existsSync(homeDir)) {
3532
- mkdirSync(homeDir, { recursive: true });
6764
+ if (!existsSync5(homeDir)) {
6765
+ mkdirSync5(homeDir, { recursive: true });
3533
6766
  }
3534
6767
  targetPath = globalConfigPath;
3535
6768
  }
3536
- writeFileSync(targetPath, JSON.stringify(config, null, 2), "utf-8");
6769
+ writeFileSync3(targetPath, JSON.stringify(config, null, 2), "utf-8");
3537
6770
  }
3538
6771
  function readTrustAnchorConfigAtRef(ref) {
3539
- const raw = execFileSync2("git", ["show", `${ref}:${localFileName}`], {
6772
+ const raw = execFileSync4("git", ["show", `${ref}:${localFileName}`], {
3540
6773
  encoding: "utf-8",
3541
6774
  stdio: ["ignore", "pipe", "pipe"],
3542
6775
  timeout: 1e4
@@ -3550,7 +6783,7 @@ ${detail}`;
3550
6783
  const repo = trustAnchorRepo();
3551
6784
  if (!repo)
3552
6785
  throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
3553
- return execFileSync2("gh", ["api", `repos/${repo}/contents/${localFileName}`, "--jq", ".content"], {
6786
+ return execFileSync4("gh", ["api", `repos/${repo}/contents/${localFileName}`, "--jq", ".content"], {
3554
6787
  encoding: "utf-8",
3555
6788
  stdio: ["ignore", "pipe", "pipe"]
3556
6789
  });
@@ -3558,7 +6791,7 @@ ${detail}`;
3558
6791
  async function fetchTrustAnchorConfigAsync() {
3559
6792
  const probeRef = resolveCiTrustAnchorProbeRef(process.env, options.probeRefVariable);
3560
6793
  if (probeRef) {
3561
- const { stdout } = await execFileAsync3("git", ["show", `${probeRef}:${localFileName}`], {
6794
+ const { stdout } = await execFileAsync5("git", ["show", `${probeRef}:${localFileName}`], {
3562
6795
  encoding: "utf-8",
3563
6796
  timeout: 1e4
3564
6797
  });
@@ -3567,7 +6800,7 @@ ${detail}`;
3567
6800
  const repo = await trustAnchorRepoAsync();
3568
6801
  if (!repo)
3569
6802
  throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
3570
- const { stdout } = await execFileAsync3("gh", ["api", `repos/${repo}/contents/${localFileName}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
6803
+ const { stdout } = await execFileAsync5("gh", ["api", `repos/${repo}/contents/${localFileName}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
3571
6804
  return stdout;
3572
6805
  }
3573
6806
  function warnTrustAnchorFallback(why) {
@@ -3594,14 +6827,15 @@ ${detail}`;
3594
6827
  return null;
3595
6828
  }
3596
6829
  }
3597
- function loadTrustAnchorConfig(fetcher = fetchTrustAnchorConfig) {
6830
+ function loadTrustAnchorConfig(fetcher = fetchTrustAnchorConfig, loadOptions = {}) {
6831
+ const warn = loadOptions.quiet ? () => {} : warnTrustAnchorFallback;
3598
6832
  let base64;
3599
6833
  try {
3600
6834
  base64 = fetcher();
3601
6835
  } catch (err) {
3602
- return trustAnchorFetchFailed(err);
6836
+ return trustAnchorFetchFailed(err, warn);
3603
6837
  }
3604
- return parseTrustAnchorContent(base64);
6838
+ return parseTrustAnchorContent(base64, warn);
3605
6839
  }
3606
6840
  function loadTrustAnchorConfigOrThrow(fetcher = fetchTrustAnchorConfig) {
3607
6841
  let base64;
@@ -3641,173 +6875,12 @@ ${detail}`;
3641
6875
  loadTrustAnchorConfigAsync
3642
6876
  };
3643
6877
  }
3644
- var execFileAsync3, GIT_IDENTITY_TIMEOUT_MS = 5000, NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read", emittedLocalOverrideWarnings;
6878
+ var execFileAsync5, GIT_IDENTITY_TIMEOUT_MS = 5000, NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read", emittedLocalOverrideWarnings;
3645
6879
  var init_config_loader = __esm(() => {
3646
- execFileAsync3 = promisify3(execFile3);
6880
+ execFileAsync5 = promisify5(execFile5);
3647
6881
  emittedLocalOverrideWarnings = new Set;
3648
6882
  });
3649
6883
 
3650
- // ../../harness/kernel/config/loader/config-provider.ts
3651
- function installConfigProvider(provider) {
3652
- installed = provider;
3653
- }
3654
- function configProvider() {
3655
- if (!installed)
3656
- throw new Error(NO_CONFIG_PROVIDER_MESSAGE);
3657
- return installed;
3658
- }
3659
- var installed = null, NO_CONFIG_PROVIDER_MESSAGE = "no configuration provider is installed — a composition root must call installConfigProvider() before any configuration read";
3660
-
3661
- // ../../harness/kernel/config/schema/config-schema.ts
3662
- import { isAbsolute } from "node:path";
3663
- import { z as z2 } from "zod";
3664
- function checkEntrySchema(fields) {
3665
- return z2.object(fields).superRefine((entry, ctx) => {
3666
- const env = entry.env;
3667
- if (!env)
3668
- return;
3669
- for (const [key, value] of Object.entries(env)) {
3670
- if (typeof value !== "object" || value === null || !("anyOf" in value))
3671
- continue;
3672
- const members = value.anyOf;
3673
- if (new Set(members).size !== members.length) {
3674
- ctx.addIssue({
3675
- code: z2.ZodIssueCode.custom,
3676
- message: `env.${key}.anyOf has duplicate members`,
3677
- path: ["env", key, "anyOf"]
3678
- });
3679
- }
3680
- if (!members.includes(key)) {
3681
- ctx.addIssue({
3682
- code: z2.ZodIssueCode.custom,
3683
- message: `env.${key}.anyOf must include "${key}" itself as a member`,
3684
- path: ["env", key, "anyOf"]
3685
- });
3686
- }
3687
- }
3688
- });
3689
- }
3690
- function isSafeRepoRelPath(p) {
3691
- if (p.length === 0)
3692
- return false;
3693
- if (p.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(p))
3694
- return false;
3695
- return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
3696
- }
3697
- function hookBlockPathRule(prefixes) {
3698
- const isCanonical = (p) => prefixes.some((prefix) => p.startsWith(prefix) && p.length > prefix.length);
3699
- const schema = SafeRepoRelPath.refine(isCanonical, {
3700
- message: `must start with one of ${prefixes.join(", ")} (byte-exact, case-sensitive)`
3701
- });
3702
- return { isCanonical, schema };
3703
- }
3704
- function managedManifestSchemas(agentVendors, hookBlockPrefixes) {
3705
- const block = z2.object({
3706
- path: hookBlockPathRule(hookBlockPrefixes).schema,
3707
- marker: z2.string(),
3708
- comment: z2.enum(["hash", "html"])
3709
- });
3710
- const manifest = z2.object({
3711
- version: z2.number().int().positive(),
3712
- files: z2.array(SafeRepoRelPath),
3713
- blocks: z2.array(block),
3714
- labels: z2.array(z2.string()),
3715
- agents: z2.array(z2.enum(agentVendors)).optional()
3716
- });
3717
- return { block, manifest };
3718
- }
3719
- function logsSchema(events) {
3720
- return z2.object({
3721
- folder: z2.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
3722
- url: z2.string().url().optional(),
3723
- headers: z2.record(z2.string()).optional(),
3724
- readHeaders: z2.record(z2.string()).optional(),
3725
- events: events.optional()
3726
- }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
3727
- message: "logs: set at most one of folder/url"
3728
- }).refine((v) => v.headers === undefined || v.url !== undefined, {
3729
- message: "logs: headers requires url"
3730
- }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
3731
- message: "logs: readHeaders requires url"
3732
- }).or(z2.literal(false)).optional();
3733
- }
3734
- function kernelConfigFragment(leaves) {
3735
- return {
3736
- rings: z2.object({
3737
- ring1_forgeWriteInterception: z2.boolean(),
3738
- ring2_asyncAudits: z2.boolean()
3739
- }).optional(),
3740
- checks: z2.record(z2.string(), checkEntrySchema(leaves.checkEntryFields)).optional(),
3741
- managed: managedManifestSchemas(leaves.agentVendors, leaves.hookBlockPrefixes).manifest.optional(),
3742
- ci: z2.object({ setup: z2.string().min(1) }).optional(),
3743
- logPublish: z2.unknown().refine((v) => v === undefined, {
3744
- message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
3745
- }),
3746
- runtimeDir: z2.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
3747
- runner: z2.enum(["standalone", "atta-engine"]).optional(),
3748
- logs: logsSchema(leaves.logEvents)
3749
- };
3750
- }
3751
- function resolveRuntimeDirSetting(config) {
3752
- return config?.runtimeDir ?? null;
3753
- }
3754
- function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
3755
- const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
3756
- return anchored !== null && anchored === localRuntimeDir ? anchored : null;
3757
- }
3758
- function resolveLogsSetting(config) {
3759
- const raw = config?.logs;
3760
- if (!raw)
3761
- return null;
3762
- if (raw.url !== undefined)
3763
- return { url: raw.url, headers: raw.headers };
3764
- if (raw.folder !== undefined)
3765
- return { folder: raw.folder };
3766
- return null;
3767
- }
3768
- function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
3769
- const anchored = resolveLogsSetting(trustAnchorConfig);
3770
- if (!anchored)
3771
- return null;
3772
- if ("url" in local)
3773
- return "url" in anchored && anchored.url === local.url ? anchored : null;
3774
- return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
3775
- }
3776
- function resolveLogsHeaderValues(headers, env) {
3777
- if (!headers)
3778
- return;
3779
- const resolved = {};
3780
- for (const [key, value] of Object.entries(headers)) {
3781
- resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
3782
- }
3783
- return resolved;
3784
- }
3785
- var EnvEntrySchema, KERNEL_CHECK_ENTRY_FIELDS, SafeRepoRelPath, KERNEL_CONFIG_REFINEMENTS;
3786
- var init_config_schema = __esm(() => {
3787
- EnvEntrySchema = z2.union([
3788
- z2.literal(true),
3789
- z2.object({ optional: z2.literal(true) }),
3790
- z2.object({ anyOf: z2.array(z2.string()).min(2) }),
3791
- z2.string()
3792
- ]);
3793
- KERNEL_CHECK_ENTRY_FIELDS = {
3794
- run: z2.string(),
3795
- scope: z2.enum(["diff", "full"]),
3796
- include: z2.array(z2.string()).optional(),
3797
- args: z2.array(z2.string()).optional(),
3798
- timeoutMs: z2.number().optional(),
3799
- env: z2.record(z2.string(), EnvEntrySchema).optional(),
3800
- requiresOpenPr: z2.boolean().optional(),
3801
- ownWorkflow: z2.boolean().optional(),
3802
- validates: z2.enum(["body", "issue"]).optional(),
3803
- advisory: z2.literal(true).optional()
3804
- };
3805
- SafeRepoRelPath = z2.string().refine(isSafeRepoRelPath, {
3806
- message: "must be a repo-root-relative path with no `..` segment or absolute root"
3807
- });
3808
- KERNEL_CONFIG_REFINEMENTS = [];
3809
- });
3810
-
3811
6884
  // ../../harness/kernel/config/schema/process-config-section.ts
3812
6885
  function orderedShape(order, ...fragments) {
3813
6886
  const owners = new Map;
@@ -4120,16 +7193,16 @@ var init_ruling_ordinal = __esm(() => {
4120
7193
  });
4121
7194
 
4122
7195
  // ../../harness/processes/vinaya-strict/tools/task-contract/review-input-manifest.ts
4123
- import { createHash as createHash3 } from "node:crypto";
7196
+ import { createHash as createHash5 } from "node:crypto";
4124
7197
  function pauseBoundRulingDigest(rulingText) {
4125
- return createHash3("sha256").update(rulingText).digest("hex");
7198
+ return createHash5("sha256").update(rulingText).digest("hex");
4126
7199
  }
4127
7200
  function briefHash(brief) {
4128
- return createHash3("sha256").update(`${brief}
7201
+ return createHash5("sha256").update(`${brief}
4129
7202
  `).digest("hex");
4130
7203
  }
4131
7204
  function policyDigest(policy) {
4132
- return createHash3("sha256").update(JSON.stringify({
7205
+ return createHash5("sha256").update(JSON.stringify({
4133
7206
  codeReviewThreshold: policy.codeReviewThreshold,
4134
7207
  securityThreshold: policy.securityThreshold
4135
7208
  })).digest("hex");
@@ -4370,7 +7443,7 @@ var init_review_gate = __esm(() => {
4370
7443
 
4371
7444
  // ../../harness/processes/vinaya-strict/tools/prose-rules-config.ts
4372
7445
  import safeRegex from "safe-regex2";
4373
- import { z as z3 } from "zod";
7446
+ import { z as z4 } from "zod";
4374
7447
  function isPlainObject3(value) {
4375
7448
  return typeof value === "object" && value !== null && !Array.isArray(value);
4376
7449
  }
@@ -4640,18 +7713,18 @@ var init_prose_rules_config = __esm(() => {
4640
7713
  FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
4641
7714
  CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
4642
7715
  DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
4643
- RepoRelativePathSchema = z3.string().min(1).superRefine((entry, ctx) => {
7716
+ RepoRelativePathSchema = z4.string().min(1).superRefine((entry, ctx) => {
4644
7717
  const reason = outsideRepositoryReason(entry);
4645
7718
  if (reason)
4646
- ctx.addIssue({ code: z3.ZodIssueCode.custom, message: reason });
7719
+ ctx.addIssue({ code: z4.ZodIssueCode.custom, message: reason });
4647
7720
  });
4648
- ProseRulesSchema = z3.unknown().superRefine((value, ctx) => {
7721
+ ProseRulesSchema = z4.unknown().superRefine((value, ctx) => {
4649
7722
  for (const issue of proseRulesIssues(value)) {
4650
- ctx.addIssue({ code: z3.ZodIssueCode.custom, path: issue.path, message: issue.message });
7723
+ ctx.addIssue({ code: z4.ZodIssueCode.custom, path: issue.path, message: issue.message });
4651
7724
  }
4652
7725
  }).transform((value) => value);
4653
- PublishedProseSchema = z3.object({
4654
- allow: z3.array(z3.string().min(1)).optional()
7726
+ PublishedProseSchema = z4.object({
7727
+ allow: z4.array(z4.string().min(1)).optional()
4655
7728
  }).strict();
4656
7729
  });
4657
7730
 
@@ -4666,10 +7739,13 @@ var exports_vinaya_config_section = {};
4666
7739
  __export(exports_vinaya_config_section, {
4667
7740
  BRIEF_BUILTINS: () => BRIEF_BUILTINS,
4668
7741
  CANONICAL_HOOK_BLOCK_PREFIXES: () => CANONICAL_HOOK_BLOCK_PREFIXES,
7742
+ DEFAULT_REVIEW_AGENT: () => DEFAULT_REVIEW_AGENT,
7743
+ DEFAULT_REVIEW_ROUND_LIMIT: () => DEFAULT_REVIEW_ROUND_LIMIT,
4669
7744
  LOCAL_OVERRIDABLE_KEYS: () => LOCAL_OVERRIDABLE_KEYS,
4670
7745
  LOCAL_OVERRIDE_FILENAME: () => LOCAL_OVERRIDE_FILENAME,
4671
7746
  PRINCIPALS_FIX: () => PRINCIPALS_FIX,
4672
7747
  PrincipalsUnresolvedError: () => PrincipalsUnresolvedError,
7748
+ REVIEW_AGENT_SETTINGS: () => REVIEW_AGENT_SETTINGS,
4673
7749
  VINAYA_CHECK_ENTRY_FIELDS: () => VINAYA_CHECK_ENTRY_FIELDS,
4674
7750
  VINAYA_CONFIG_FILENAME: () => VINAYA_CONFIG_FILENAME,
4675
7751
  VINAYA_CONFIG_FRAGMENT: () => VINAYA_CONFIG_FRAGMENT,
@@ -4691,18 +7767,20 @@ __export(exports_vinaya_config_section, {
4691
7767
  resolveGateCutovers: () => resolveGateCutovers,
4692
7768
  resolveLocalPacingOverride: () => resolveLocalPacingOverride,
4693
7769
  resolveReleaseActor: () => resolveReleaseActor,
7770
+ resolveReviewAgent: () => resolveReviewAgent,
4694
7771
  resolveReviewPolicy: () => resolveReviewPolicy,
7772
+ resolveReviewRoundLimit: () => resolveReviewRoundLimit,
4695
7773
  resolveSecurityScanCommand: () => resolveSecurityScanCommand,
4696
7774
  tokensCollectTrustKey: () => tokensCollectTrustKey,
4697
7775
  trustAnchorFallbackWarning: () => trustAnchorFallbackWarning,
4698
7776
  trustTokensCollectCommand: () => trustTokensCollectCommand
4699
7777
  });
4700
- import { createHash as createHash4 } from "node:crypto";
4701
- import { execFileSync as execFileSync3 } from "node:child_process";
4702
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
4703
- import { homedir } from "node:os";
4704
- import { dirname as dirname2, join as join2 } from "node:path";
4705
- import { z as z4 } from "zod";
7778
+ import { createHash as createHash6 } from "node:crypto";
7779
+ import { execFileSync as execFileSync5 } from "node:child_process";
7780
+ import { existsSync as existsSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "node:fs";
7781
+ import { homedir as homedir5 } from "node:os";
7782
+ import { dirname as dirname8, join as join8 } from "node:path";
7783
+ import { z as z5 } from "zod";
4706
7784
  function isDefaultedAgentVendorPath(path, manifest) {
4707
7785
  if (manifest.agents !== undefined)
4708
7786
  return false;
@@ -4736,7 +7814,7 @@ function decisionRecordsOutsideDoctrine(config, ctx) {
4736
7814
  return;
4737
7815
  const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
4738
7816
  if (issue)
4739
- ctx.addIssue({ code: z4.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
7817
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
4740
7818
  }
4741
7819
  function globalPrincipalsIgnoredWarning(path) {
4742
7820
  return `${path}: "principals" in the global config is ignored — principals may only be declared from a repo-local vinaya.config.json.`;
@@ -4840,6 +7918,12 @@ function resolveGateCutovers(config) {
4840
7918
  function resolveCollisionThreshold(config) {
4841
7919
  return config?.planning?.collisionThreshold ?? DEFAULT_COLLISION_THRESHOLD;
4842
7920
  }
7921
+ function resolveReviewRoundLimit(config) {
7922
+ return config?.planning?.reviewRoundLimit ?? DEFAULT_REVIEW_ROUND_LIMIT;
7923
+ }
7924
+ function resolveReviewAgent(config) {
7925
+ return config?.planning?.reviewAgent ?? DEFAULT_REVIEW_AGENT;
7926
+ }
4843
7927
  function principalsNotConfigured(why) {
4844
7928
  return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
4845
7929
  }
@@ -4854,7 +7938,7 @@ function createTrustedPrincipalsResolver(reads) {
4854
7938
  }
4855
7939
  if (isMissingFileError(err))
4856
7940
  throw principalsNotConfigured("the default branch has no vinaya.config.json");
4857
- throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
7941
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`, { cause: err });
4858
7942
  }
4859
7943
  const unusable = { why: "" };
4860
7944
  const config = reads.parse(content, (why) => {
@@ -4874,23 +7958,23 @@ function trustAnchorFallbackWarning(why) {
4874
7958
  }
4875
7959
  function readTokensCollectTrustStore(storePath) {
4876
7960
  try {
4877
- if (!existsSync2(storePath))
7961
+ if (!existsSync6(storePath))
4878
7962
  return {};
4879
- const raw = JSON.parse(readFileSync2(storePath, "utf-8"));
7963
+ const raw = JSON.parse(readFileSync7(storePath, "utf-8"));
4880
7964
  return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
4881
7965
  } catch {
4882
7966
  return {};
4883
7967
  }
4884
7968
  }
4885
7969
  function writeTokensCollectTrustStore(storePath, store) {
4886
- const dir = dirname2(storePath);
4887
- if (!existsSync2(dir))
4888
- mkdirSync2(dir, { recursive: true });
4889
- writeFileSync2(storePath, JSON.stringify(store, null, 2), "utf-8");
7970
+ const dir = dirname8(storePath);
7971
+ if (!existsSync6(dir))
7972
+ mkdirSync6(dir, { recursive: true });
7973
+ writeFileSync4(storePath, JSON.stringify(store, null, 2), "utf-8");
4890
7974
  }
4891
7975
  function gitBlobHash(absolutePath, cwd) {
4892
7976
  try {
4893
- const raw = execFileSync3("git", ["hash-object", absolutePath], {
7977
+ const raw = execFileSync5("git", ["hash-object", absolutePath], {
4894
7978
  cwd,
4895
7979
  encoding: "utf-8",
4896
7980
  stdio: ["ignore", "pipe", "pipe"],
@@ -4902,7 +7986,7 @@ function gitBlobHash(absolutePath, cwd) {
4902
7986
  }
4903
7987
  }
4904
7988
  function tokensCollectTrustKey(repoGitCommonDir, interpreter, script) {
4905
- return createHash4("sha256").update(JSON.stringify([repoGitCommonDir, interpreter, script])).digest("hex");
7989
+ return createHash6("sha256").update(JSON.stringify([repoGitCommonDir, interpreter, script])).digest("hex");
4906
7990
  }
4907
7991
  function getTokensCollectTrust(repoGitCommonDir, interpreter, script, storePath = TOKENS_COLLECT_TRUST_PATH) {
4908
7992
  const key = tokensCollectTrustKey(repoGitCommonDir, interpreter, script);
@@ -4914,7 +7998,7 @@ function trustTokensCollectCommand(repoGitCommonDir, interpreter, script, script
4914
7998
  store[key] = { interpreter, script, scriptBlobHash, trustedAt: new Date().toISOString() };
4915
7999
  writeTokensCollectTrustStore(storePath, store);
4916
8000
  }
4917
- var VINAYA_HOME, VINAYA_GLOBAL_CONFIG_FILENAME = "config.json", VINAYA_CONFIG_FILENAME = "vinaya.config.json", CANONICAL_HOOK_BLOCK_PREFIXES, VINAYA_CHECK_ENTRY_FIELDS, AGENTS_SKILLS_PREFIX = ".agents/skills/", CLAUDE_SKILLS_PREFIX = ".claude/skills/vinaya-", RoleEntrySchema, MAX_REPORT_COMMAND_TIMEOUT_MS = 3600000, BRIEF_BUILTINS, BriefSectionSchema, BriefSchemaSchema, ProjectEntrySchema, VINAYA_CONFIG_FRAGMENT, LOCAL_OVERRIDE_FILENAME = "vinaya.config.local.json", LOCAL_OVERRIDABLE_KEYS, PrincipalsUnresolvedError, PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch', TOKENS_COLLECT_TRUST_PATH, VINAYA_GLOBAL_ONLY_KEYS, VINAYA_CONFIG_SECTION;
8001
+ var VINAYA_HOME, VINAYA_GLOBAL_CONFIG_FILENAME = "config.json", VINAYA_CONFIG_FILENAME = "vinaya.config.json", CANONICAL_HOOK_BLOCK_PREFIXES, VINAYA_CHECK_ENTRY_FIELDS, AGENTS_SKILLS_PREFIX = ".agents/skills/", CLAUDE_SKILLS_PREFIX = ".claude/skills/vinaya-", RoleEntrySchema, MAX_REPORT_COMMAND_TIMEOUT_MS = 3600000, BRIEF_BUILTINS, BriefSectionSchema, BriefSchemaSchema, ProjectEntrySchema, VINAYA_CONFIG_FRAGMENT, LOCAL_OVERRIDE_FILENAME = "vinaya.config.local.json", LOCAL_OVERRIDABLE_KEYS, DEFAULT_REVIEW_ROUND_LIMIT = 2, REVIEW_AGENT_SETTINGS, DEFAULT_REVIEW_AGENT = "same", PrincipalsUnresolvedError, PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch', TOKENS_COLLECT_TRUST_PATH, VINAYA_GLOBAL_ONLY_KEYS, VINAYA_CONFIG_SECTION;
4918
8002
  var init_vinaya_config_section = __esm(() => {
4919
8003
  init_review_policy();
4920
8004
  init_issue_validation();
@@ -4925,13 +8009,13 @@ var init_vinaya_config_section = __esm(() => {
4925
8009
  init_config_loader();
4926
8010
  init_config_schema();
4927
8011
  init_prose_rules_config();
4928
- VINAYA_HOME = join2(homedir(), ".vinaya");
8012
+ VINAYA_HOME = join8(homedir5(), ".vinaya");
4929
8013
  CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
4930
8014
  VINAYA_CHECK_ENTRY_FIELDS = {
4931
- principalOwed: z4.literal(true).optional()
8015
+ principalOwed: z5.literal(true).optional()
4932
8016
  };
4933
- RoleEntrySchema = z4.object({
4934
- contract: z4.string().refine((p) => p.includes("/"), {
8017
+ RoleEntrySchema = z5.object({
8018
+ contract: z5.string().refine((p) => p.includes("/"), {
4935
8019
  message: 'must be a path (contain at least one "/"), not a bare filename'
4936
8020
  })
4937
8021
  });
@@ -4954,102 +8038,104 @@ var init_vinaya_config_section = __esm(() => {
4954
8038
  "briefSections",
4955
8039
  "milestoneShape"
4956
8040
  ];
4957
- BriefSectionSchema = z4.union([
4958
- z4.object({ builtin: z4.enum(BRIEF_BUILTINS) }),
4959
- z4.object({ heading: z4.string().min(1), name: z4.string().optional() }),
4960
- z4.object({ field: z4.string().min(1), name: z4.string().optional() }),
4961
- z4.object({ phrase: z4.string().min(1), name: z4.string().optional() })
8041
+ BriefSectionSchema = z5.union([
8042
+ z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
8043
+ z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
8044
+ z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
8045
+ z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
4962
8046
  ]);
4963
- BriefSchemaSchema = z4.object({
4964
- pr: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
4965
- issue: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
4966
- milestone: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
4967
- ack: z4.array(z4.enum(BRIEF_BUILTINS)).optional()
8047
+ BriefSchemaSchema = z5.object({
8048
+ pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
8049
+ issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
8050
+ milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
8051
+ ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
4968
8052
  });
4969
- ProjectEntrySchema = z4.object({
4970
- name: z4.string().min(1),
4971
- description: z4.string().min(1).optional(),
4972
- path: z4.string().min(1).optional()
8053
+ ProjectEntrySchema = z5.object({
8054
+ name: z5.string().min(1),
8055
+ description: z5.string().min(1).optional(),
8056
+ path: z5.string().min(1).optional()
4973
8057
  });
4974
8058
  VINAYA_CONFIG_FRAGMENT = {
4975
- roles: z4.record(z4.string(), RoleEntrySchema).optional(),
8059
+ roles: z5.record(z5.string(), RoleEntrySchema).optional(),
4976
8060
  briefSchema: BriefSchemaSchema.optional(),
4977
- principals: z4.array(z4.string()).min(1).optional(),
4978
- releaseActor: z4.string().min(1).optional(),
4979
- tokens: z4.object({
4980
- collect: z4.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8061
+ principals: z5.array(z5.string()).min(1).optional(),
8062
+ releaseActor: z5.string().min(1).optional(),
8063
+ tokens: z5.object({
8064
+ collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
4981
8065
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
4982
8066
  })
4983
8067
  }).optional(),
4984
- blastRadius: z4.object({ extraDomains: z4.array(z4.string()).optional() }).optional(),
4985
- proseGates: z4.object({
4986
- doctrineRoot: z4.string().min(1).optional(),
4987
- readerFacingPrefix: z4.string().min(1).optional(),
4988
- readerFacingSuffix: z4.string().min(1).optional(),
4989
- legacySlugDir: z4.string().min(1).optional(),
4990
- sourceComments: z4.object({
4991
- globs: z4.array(z4.string().min(1)).optional(),
4992
- allowlist: z4.array(z4.string().min(1)).optional(),
4993
- severity: z4.enum(["warning", "error"]).optional()
8068
+ blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
8069
+ proseGates: z5.object({
8070
+ doctrineRoot: z5.string().min(1).optional(),
8071
+ readerFacingPrefix: z5.string().min(1).optional(),
8072
+ readerFacingSuffix: z5.string().min(1).optional(),
8073
+ legacySlugDir: z5.string().min(1).optional(),
8074
+ sourceComments: z5.object({
8075
+ globs: z5.array(z5.string().min(1)).optional(),
8076
+ allowlist: z5.array(z5.string().min(1)).optional(),
8077
+ severity: z5.enum(["warning", "error"]).optional()
4994
8078
  }).optional(),
4995
- specGrandfather: z4.union([z4.array(z4.string().min(1)), z4.record(z4.string().min(1), z4.number().int().min(0))]).optional(),
4996
- specPaths: z4.array(RepoRelativePathSchema).optional(),
4997
- productPaths: z4.array(RepoRelativePathSchema).optional(),
8079
+ specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
8080
+ specPaths: z5.array(RepoRelativePathSchema).optional(),
8081
+ productPaths: z5.array(RepoRelativePathSchema).optional(),
4998
8082
  published: PublishedProseSchema.optional(),
4999
8083
  rules: ProseRulesSchema.optional()
5000
8084
  }).optional(),
5001
- projects: z4.array(ProjectEntrySchema).optional(),
5002
- dispatch: z4.object({
5003
- timeoutMs: z4.number().int().positive().optional(),
5004
- reviewerTimeoutMs: z4.number().int().positive().optional(),
5005
- killGraceMs: z4.number().int().positive().optional(),
5006
- agent: z4.enum(["claude", "codex"]).optional()
8085
+ projects: z5.array(ProjectEntrySchema).optional(),
8086
+ dispatch: z5.object({
8087
+ timeoutMs: z5.number().int().positive().optional(),
8088
+ reviewerTimeoutMs: z5.number().int().positive().optional(),
8089
+ killGraceMs: z5.number().int().positive().optional(),
8090
+ agent: z5.enum(["claude", "codex"]).optional()
5007
8091
  }).optional(),
5008
- reviewPolicy: z4.object({
5009
- codeReviewThreshold: z4.string().min(1).optional(),
5010
- securityThreshold: z4.string().min(1).optional(),
5011
- maxRounds: z4.number().optional(),
5012
- maxTaskMinutes: z4.number().optional(),
5013
- readyPushTimeoutMinutes: z4.number().optional()
8092
+ reviewPolicy: z5.object({
8093
+ codeReviewThreshold: z5.string().min(1).optional(),
8094
+ securityThreshold: z5.string().min(1).optional(),
8095
+ maxRounds: z5.number().optional(),
8096
+ maxTaskMinutes: z5.number().optional(),
8097
+ readyPushTimeoutMinutes: z5.number().optional()
5014
8098
  }).optional(),
5015
- securityScan: z4.object({
5016
- command: z4.array(z4.string().min(1)).min(1)
8099
+ securityScan: z5.object({
8100
+ command: z5.array(z5.string().min(1)).min(1)
5017
8101
  }).optional(),
5018
- gateCutovers: z4.object({
5019
- objectivesSinceIssue: z4.number().int().nonnegative().optional(),
5020
- briefSectionsSinceIssue: z4.number().int().nonnegative().optional(),
5021
- documentationSinceIssue: z4.number().int().nonnegative().optional(),
5022
- briefRulesSincePr: z4.number().int().nonnegative().optional(),
5023
- agentBoxesRefusedSincePr: z4.number().int().nonnegative().optional()
8102
+ gateCutovers: z5.object({
8103
+ objectivesSinceIssue: z5.number().int().nonnegative().optional(),
8104
+ briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
8105
+ documentationSinceIssue: z5.number().int().nonnegative().optional(),
8106
+ briefRulesSincePr: z5.number().int().nonnegative().optional(),
8107
+ agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
5024
8108
  }).optional(),
5025
- planning: z4.object({
5026
- collisionThreshold: z4.number().int().nonnegative().optional()
8109
+ planning: z5.object({
8110
+ collisionThreshold: z5.number().int().nonnegative().optional(),
8111
+ reviewRoundLimit: z5.number().int().positive().optional(),
8112
+ reviewAgent: z5.enum(["same", "different"]).optional()
5027
8113
  }).optional(),
5028
- prePush: z4.object({
5029
- alwaysRun: z4.array(z4.string()).optional(),
5030
- readyTests: z4.object({
5031
- mode: z4.literal("ci"),
5032
- workflow: z4.literal(".github/workflows/ci.yml"),
5033
- check: z4.literal("Vinaya CI")
8114
+ prePush: z5.object({
8115
+ alwaysRun: z5.array(z5.string()).optional(),
8116
+ readyTests: z5.object({
8117
+ mode: z5.literal("ci"),
8118
+ workflow: z5.literal(".github/workflows/ci.yml"),
8119
+ check: z5.literal("Vinaya CI")
5034
8120
  }).strict().optional(),
5035
- requiredCi: z4.object({
5036
- workflow: z4.literal(".github/workflows/ci.yml"),
5037
- check: z4.literal("Vinaya CI")
8121
+ requiredCi: z5.object({
8122
+ workflow: z5.literal(".github/workflows/ci.yml"),
8123
+ check: z5.literal("Vinaya CI")
5038
8124
  }).strict().optional()
5039
8125
  }).optional(),
5040
- report: z4.object({
5041
- commandTimeoutMs: z4.number().int().positive().optional()
8126
+ report: z5.object({
8127
+ commandTimeoutMs: z5.number().int().positive().optional()
5042
8128
  }).superRefine((report, ctx) => {
5043
8129
  const commandTimeoutMs = report.commandTimeoutMs;
5044
8130
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
5045
8131
  ctx.addIssue({
5046
- code: z4.ZodIssueCode.custom,
8132
+ code: z5.ZodIssueCode.custom,
5047
8133
  path: ["commandTimeoutMs"],
5048
8134
  message: "must be at most 3600000 (1 hour)"
5049
8135
  });
5050
8136
  }
5051
8137
  }).optional(),
5052
- decisionRecords: z4.object({
8138
+ decisionRecords: z5.object({
5053
8139
  path: RepoRelativePathSchema
5054
8140
  }).strict().optional()
5055
8141
  };
@@ -5058,15 +8144,16 @@ var init_vinaya_config_section = __esm(() => {
5058
8144
  "reviewPolicy.maxTaskMinutes",
5059
8145
  "reviewPolicy.readyPushTimeoutMinutes"
5060
8146
  ];
8147
+ REVIEW_AGENT_SETTINGS = ["same", "different"];
5061
8148
  PrincipalsUnresolvedError = class PrincipalsUnresolvedError extends Error {
5062
8149
  kind;
5063
- constructor(kind, message) {
5064
- super(message);
8150
+ constructor(kind, message, options) {
8151
+ super(message, options);
5065
8152
  this.name = "PrincipalsUnresolvedError";
5066
8153
  this.kind = kind;
5067
8154
  }
5068
8155
  };
5069
- TOKENS_COLLECT_TRUST_PATH = join2(VINAYA_HOME, "tokens-collect-trust.json");
8156
+ TOKENS_COLLECT_TRUST_PATH = join8(VINAYA_HOME, "tokens-collect-trust.json");
5070
8157
  VINAYA_GLOBAL_ONLY_KEYS = {
5071
8158
  roles: {
5072
8159
  key: "roles",
@@ -5105,7 +8192,7 @@ var init_vinaya_config_section = __esm(() => {
5105
8192
  });
5106
8193
 
5107
8194
  // ../../harness/processes/vinaya-strict/integration/config/compose.ts
5108
- import { z as z5 } from "zod";
8195
+ import { z as z6 } from "zod";
5109
8196
  function globalChecksIgnoredWarning(path) {
5110
8197
  return `${path}: "checks" registration in the global config is ignored — checks may only be registered from a repo-local vinaya.config.json.`;
5111
8198
  }
@@ -5177,7 +8264,7 @@ var init_compose = __esm(() => {
5177
8264
  "logs",
5178
8265
  "decisionRecords"
5179
8266
  ];
5180
- VinayaConfigObjectSchema = z5.object(orderedShape(CONFIG_KEY_ORDER, KERNEL_FRAGMENT, VINAYA_CONFIG_SECTION.fragment));
8267
+ VinayaConfigObjectSchema = z6.object(orderedShape(CONFIG_KEY_ORDER, KERNEL_FRAGMENT, VINAYA_CONFIG_SECTION.fragment));
5181
8268
  VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
5182
8269
  for (const refine of KERNEL_CONFIG_REFINEMENTS)
5183
8270
  refine(config, ctx);
@@ -5228,7 +8315,7 @@ var init_compose = __esm(() => {
5228
8315
  vinayaConfigProvider = {
5229
8316
  homeDir: VINAYA_HOME,
5230
8317
  loadConfig: () => loadConfig(),
5231
- loadTrustAnchorConfig: () => loadTrustAnchorConfig(),
8318
+ loadTrustAnchorConfig: (options) => loadTrustAnchorConfig(undefined, options),
5232
8319
  loadTrustAnchorConfigAsync: (fetcher, options) => loadTrustAnchorConfigAsync(fetcher, options)
5233
8320
  };
5234
8321
  installVinayaConfigProvider();
@@ -5251,10 +8338,10 @@ function isEntryPoint(moduleUrl, scriptName, startedOn = process.argv[1]) {
5251
8338
 
5252
8339
  // ../../harness/processes/vinaya-strict/checks/bin/check-dispatch-readiness.ts
5253
8340
  init_issue_validation();
5254
- import { execFile as execFile5, execFileSync as execFileSync6 } from "node:child_process";
5255
- import { existsSync as existsSync4, readFileSync as readFileSync5, realpathSync as realpathSync4 } from "node:fs";
5256
- import { sep as sep3 } from "node:path";
5257
- import { promisify as promisify5 } from "node:util";
8341
+ import { execFile as execFile7, execFileSync as execFileSync8 } from "node:child_process";
8342
+ import { existsSync as existsSync8, readFileSync as readFileSync10, realpathSync as realpathSync6 } from "node:fs";
8343
+ import { sep as sep4 } from "node:path";
8344
+ import { promisify as promisify7 } from "node:util";
5258
8345
 
5259
8346
  // ../../node_modules/universal-user-agent/index.js
5260
8347
  function getUserAgent() {
@@ -5662,8 +8749,8 @@ function isPlainObject2(value) {
5662
8749
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
5663
8750
  }
5664
8751
  async function fetchWrapper(requestOptions) {
5665
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
5666
- if (!fetch) {
8752
+ const fetch2 = requestOptions.request?.fetch || globalThis.fetch;
8753
+ if (!fetch2) {
5667
8754
  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");
5668
8755
  }
5669
8756
  const log = requestOptions.request?.log || console;
@@ -5675,7 +8762,7 @@ async function fetchWrapper(requestOptions) {
5675
8762
  ]));
5676
8763
  let fetchResponse;
5677
8764
  try {
5678
- fetchResponse = await fetch(requestOptions.url, {
8765
+ fetchResponse = await fetch2(requestOptions.url, {
5679
8766
  method: requestOptions.method,
5680
8767
  body,
5681
8768
  redirect: requestOptions.request?.redirect,
@@ -5903,10 +8990,23 @@ var graphql2 = withDefaults3(request, {
5903
8990
 
5904
8991
  // ../../harness/processes/vinaya-strict/tools/task-contract/forge/fetch-open-issues.ts
5905
8992
  init_labels();
5906
- async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
8993
+ function failureReason(err, token) {
8994
+ const message = err instanceof Error ? err.message : String(err);
8995
+ if (token.length > 0 && message.includes(token))
8996
+ return null;
8997
+ return message;
8998
+ }
8999
+ async function fetchOpenIssuesByLabel(slugs, owner, repo, token, onFailedRead) {
9000
+ const read = await readOpenIssuesByLabel(slugs, owner, repo, token);
9001
+ if (read.ok)
9002
+ return read.issues;
9003
+ onFailedRead?.(read.reason);
9004
+ return new Map;
9005
+ }
9006
+ async function readOpenIssuesByLabel(slugs, owner, repo, token) {
5907
9007
  const result = new Map;
5908
9008
  if (slugs.length === 0)
5909
- return result;
9009
+ return { ok: true, issues: result };
5910
9010
  const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
5911
9011
  const toAlias = (slug) => `tranche_${slug.replace(/-/g, "_")}`;
5912
9012
  const perSlug = slugs.map((slug) => `
@@ -5920,11 +9020,12 @@ async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
5920
9020
  let response;
5921
9021
  try {
5922
9022
  response = await client(query, { owner, repo });
5923
- } catch {
5924
- return result;
9023
+ } catch (err) {
9024
+ return { ok: false, reason: failureReason(err, token) };
9025
+ }
9026
+ if (!response.repository) {
9027
+ return { ok: false, reason: `the repository ${owner}/${repo} is not visible to the token` };
5925
9028
  }
5926
- if (!response.repository)
5927
- return result;
5928
9029
  for (const slug of slugs) {
5929
9030
  const conn = response.repository[toAlias(slug)];
5930
9031
  const issues = (conn?.nodes ?? []).map((n) => ({
@@ -5934,7 +9035,7 @@ async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
5934
9035
  }));
5935
9036
  result.set(slug, issues);
5936
9037
  }
5937
- return result;
9038
+ return { ok: true, issues: result };
5938
9039
  }
5939
9040
 
5940
9041
  // ../../harness/processes/vinaya-strict/tools/task-contract/task-branch-identity.ts
@@ -5960,6 +9061,9 @@ function siblingsSharingConflictEdge(subject, siblings) {
5960
9061
  function isHandClosedByRecognizedPrincipal(dep, principalAllowlist) {
5961
9062
  return dep.issueState === "closed" && dep.stateReason === "completed" && isPrincipal(dep.closedByActor ?? null, principalAllowlist);
5962
9063
  }
9064
+ function issueReadFailedMessage(prefix, issueNumber, error) {
9065
+ return `${prefix} issue-read-failed: the forge could not be read for Issue #${issueNumber}, so whether it exists is unknown — this is not a claim that the Issue is missing. gh reported: ${error}`;
9066
+ }
5963
9067
  function isSelfDependency(dep, task, issue) {
5964
9068
  if (dep.issue !== null && issue !== null && dep.issue === issue.number)
5965
9069
  return true;
@@ -5976,6 +9080,8 @@ function checkDispatchReadiness(input) {
5976
9080
  };
5977
9081
  if (task.issue === null) {
5978
9082
  push("issue-existence", `dispatch-gate issue-existence: ${taskLabel} has no Issue (#TBD or blank) in the topology — not dispatchable until the Planner cuts the Issue.`);
9083
+ } else if (input.issueReadFailed !== undefined) {
9084
+ push("issue-read-failed", issueReadFailedMessage("dispatch-gate", task.issue, input.issueReadFailed));
5979
9085
  } else if (input.issue === null) {
5980
9086
  push("issue-existence", `dispatch-gate issue-existence: ${taskLabel} names Issue #${task.issue}, but it does not resolve to a real GitHub Issue (phantom reference).`);
5981
9087
  }
@@ -6016,11 +9122,61 @@ function checkDispatchReadiness(input) {
6016
9122
  return { ready: blockerDetails.length === 0, blockers: blockerDetails.map((b) => b.message), blockerDetails };
6017
9123
  }
6018
9124
 
9125
+ // ../../harness/processes/vinaya-strict/tools/task-issue-read.ts
9126
+ init_round_assess();
9127
+ import { execFileSync as execFileSync3 } from "node:child_process";
9128
+ var RETRY_WAITS_MS = [1e4, 30000, 60000];
9129
+ var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
9130
+ var processCache = new Map;
9131
+ var runGh = (args) => {
9132
+ try {
9133
+ return execFileSync3("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
9134
+ } catch (err) {
9135
+ const stderr = err.stderr;
9136
+ const text = stderr === undefined || stderr === null ? "" : String(stderr);
9137
+ throw new Error(text !== "" ? text : err instanceof Error ? err.message : String(err));
9138
+ }
9139
+ };
9140
+ var blockingSleep = (ms) => {
9141
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
9142
+ };
9143
+ function readTaskIssue(args, deps = {}) {
9144
+ const run = deps.run ?? runGh;
9145
+ const sleep = deps.sleep ?? blockingSleep;
9146
+ const cache = deps.cache ?? processCache;
9147
+ const key = args.join("\x00");
9148
+ if (cache.has(key))
9149
+ return { outcome: "read", issue: cache.get(key) };
9150
+ const waits = deps.retry === false ? [] : RETRY_WAITS_MS;
9151
+ for (let attempt = 0;; attempt += 1) {
9152
+ let text;
9153
+ try {
9154
+ const out = run(args);
9155
+ let parsed;
9156
+ try {
9157
+ parsed = JSON.parse(out);
9158
+ } catch {
9159
+ return { outcome: "failed", error: `gh printed output that is not JSON: ${out}` };
9160
+ }
9161
+ cache.set(key, parsed);
9162
+ return { outcome: "read", issue: parsed };
9163
+ } catch (err) {
9164
+ text = err instanceof Error ? err.message : String(err);
9165
+ }
9166
+ if (ISSUE_NOT_FOUND.test(text))
9167
+ return { outcome: "missing" };
9168
+ const wait = waits[attempt];
9169
+ if (wait === undefined || !isGitHubConnectionFailure(new Error(text)))
9170
+ return { outcome: "failed", error: text };
9171
+ sleep(wait);
9172
+ }
9173
+ }
9174
+
6019
9175
  // ../../harness/kernel/adapters/code-host/github/github-token.ts
6020
- import { execFile as execFile2 } from "node:child_process";
6021
- import { promisify as promisify2 } from "node:util";
6022
- var execFileAsync2 = promisify2(execFile2);
6023
- var systemEnv2 = {
9176
+ import { execFile as execFile4 } from "node:child_process";
9177
+ import { promisify as promisify4 } from "node:util";
9178
+ var execFileAsync4 = promisify4(execFile4);
9179
+ var systemEnv3 = {
6024
9180
  ...process.env,
6025
9181
  PATH: [process.env.PATH, "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].filter(Boolean).join(":")
6026
9182
  };
@@ -6032,7 +9188,7 @@ async function resolveGithubToken(explicit) {
6032
9188
  if (process.env.GH_TOKEN)
6033
9189
  return process.env.GH_TOKEN;
6034
9190
  try {
6035
- const { stdout } = await execFileAsync2("gh", ["auth", "token"], { env: systemEnv2, timeout: 5000 });
9191
+ const { stdout } = await execFileAsync4("gh", ["auth", "token"], { env: systemEnv3, timeout: 5000 });
6036
9192
  const token = stdout.trim();
6037
9193
  return token.length > 0 ? token : null;
6038
9194
  } catch {
@@ -6310,6 +9466,19 @@ function lifecycleFromIssues(issues) {
6310
9466
  return "planned";
6311
9467
  return issues.some((i) => i.state === "OPEN") ? "active" : "complete";
6312
9468
  }
9469
+ function lifecycleFromCounts(open, total) {
9470
+ if (total === 0)
9471
+ return "planned";
9472
+ return open > 0 ? "active" : "complete";
9473
+ }
9474
+ function resolveLegacyFactsFromCounts(milestone, open, total) {
9475
+ if (milestone.state === "closed" && total > 0) {
9476
+ return { goal: milestone.description ?? "", lifecycle: lifecycleFromCounts(open, total) };
9477
+ }
9478
+ return factsFromLegacyMilestone(milestone);
9479
+ }
9480
+ var TRANCHE_LABEL_QUERY = "vinaya/tranche:";
9481
+ var ACTIVE_ISSUE_READ_CONCURRENCY = 4;
6313
9482
  function goalFromMilestones(milestones, slug) {
6314
9483
  for (const m of milestones) {
6315
9484
  const goal = intentGoalForSlug(m.description ?? "", slug);
@@ -6336,11 +9505,21 @@ function trancheSlugsFromLabels(labels) {
6336
9505
  return slugs;
6337
9506
  }
6338
9507
  async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
6339
- const read = (fetch) => options.retryFailedReads ? retryOnce(fetch) : fetch();
6340
- const [milestones, labels] = await Promise.all([
9508
+ const read = (fetch2) => options.retryFailedReads ? retryOnce(fetch2) : fetch2();
9509
+ const [milestones, labels, counts] = await Promise.all([
6341
9510
  read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`)),
6342
- read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`))
9511
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`)),
9512
+ read(() => ghLabelIssueCountsAsync(owner, repo, TRANCHE_LABEL_QUERY))
6343
9513
  ]);
9514
+ const countsByLabel = new Map(counts.map((c) => [c.name, c]));
9515
+ const uncounted = trancheSlugsFromLabels(labels).map((slug) => trancheLabel(slug)).filter((label) => !countsByLabel.has(label));
9516
+ if (uncounted.length > 0) {
9517
+ throw new Error(`the label Issue-count query returned no count for ${uncounted.join(", ")}`);
9518
+ }
9519
+ const lifecycleOf = (slug) => {
9520
+ const c = countsByLabel.get(trancheLabel(slug));
9521
+ return lifecycleFromCounts(c?.open ?? 0, c?.total ?? 0);
9522
+ };
6344
9523
  const active = [];
6345
9524
  const archived = [];
6346
9525
  const facts = new Map;
@@ -6348,33 +9527,21 @@ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
6348
9527
  const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
6349
9528
  const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
6350
9529
  const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
6351
- const uniqueLegacySlugs = [...legacySlugs];
6352
- const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
6353
- Promise.all(uniqueLegacySlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))),
6354
- Promise.all(uniqueNewPathSlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))))
6355
- ]);
6356
- const issuesBySlug = new Map;
6357
- uniqueLegacySlugs.forEach((slug, i) => {
6358
- issuesBySlug.set(slug, legacyIssuesBySlug[i] ?? []);
6359
- });
6360
- uniqueNewPathSlugs.forEach((slug, i) => {
6361
- issuesBySlug.set(slug, newPathIssuesBySlug[i] ?? []);
6362
- });
6363
- uniqueLegacySlugs.forEach((slug, i) => {
9530
+ for (const slug of legacySlugs) {
6364
9531
  const m = legacyMilestoneBySlug.get(slug);
6365
9532
  if (!m)
6366
- return;
9533
+ continue;
6367
9534
  const ref = { slug, goal: m.description ?? "" };
6368
- const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
9535
+ const c = countsByLabel.get(trancheLabel(slug));
9536
+ const f = resolveLegacyFactsFromCounts(m, c?.open ?? 0, c?.total ?? 0);
6369
9537
  if (f.lifecycle === "complete")
6370
9538
  archived.push(ref);
6371
9539
  else if (f.lifecycle === "active")
6372
9540
  active.push(ref);
6373
9541
  facts.set(slug, f);
6374
- });
6375
- uniqueNewPathSlugs.forEach((slug, i) => {
6376
- const issues = newPathIssuesBySlug[i] ?? [];
6377
- const lifecycle = lifecycleFromIssues(issues);
9542
+ }
9543
+ for (const slug of uniqueNewPathSlugs) {
9544
+ const lifecycle = lifecycleOf(slug);
6378
9545
  const goal = goalFromMilestones(milestones, slug);
6379
9546
  const f = { goal, lifecycle };
6380
9547
  facts.set(slug, f);
@@ -6382,14 +9549,23 @@ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
6382
9549
  active.push({ slug, goal });
6383
9550
  else if (lifecycle === "complete")
6384
9551
  archived.push({ slug, goal });
6385
- });
9552
+ }
9553
+ const issuesBySlug = new Map;
9554
+ const activeSlugs = active.map((r) => r.slug);
9555
+ for (let i = 0;i < activeSlugs.length; i += ACTIVE_ISSUE_READ_CONCURRENCY) {
9556
+ const batch = activeSlugs.slice(i, i + ACTIVE_ISSUE_READ_CONCURRENCY);
9557
+ const lists = await Promise.all(batch.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))));
9558
+ batch.forEach((slug, j) => {
9559
+ issuesBySlug.set(slug, lists[j] ?? []);
9560
+ });
9561
+ }
6386
9562
  return { active, archived, facts, legacySlugs, issuesBySlug };
6387
9563
  }
6388
- async function retryOnce(fetch) {
9564
+ async function retryOnce(fetch2) {
6389
9565
  try {
6390
- return await fetch();
9566
+ return await fetch2();
6391
9567
  } catch {
6392
- return fetch();
9568
+ return fetch2();
6393
9569
  }
6394
9570
  }
6395
9571
  async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
@@ -6504,8 +9680,8 @@ function createForgeSource(config) {
6504
9680
  init_compose();
6505
9681
 
6506
9682
  // ../../harness/kernel/adapters/code-host/github/forge-snapshot.ts
6507
- import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
6508
- import { join as join3 } from "node:path";
9683
+ import { existsSync as existsSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "node:fs";
9684
+ import { join as join9 } from "node:path";
6509
9685
 
6510
9686
  // ../../harness/kernel/adapters/code-host/github/extract-issue.ts
6511
9687
  init_anchored_region();
@@ -6534,10 +9710,10 @@ function headerRegion2(prBody) {
6534
9710
  return m?.index !== undefined ? prBody.slice(0, m.index) : prBody;
6535
9711
  }
6536
9712
  // ../../harness/kernel/adapters/code-host/github/forge-read.ts
6537
- import { execFileSync as execFileSync4 } from "node:child_process";
9713
+ import { execFileSync as execFileSync6 } from "node:child_process";
6538
9714
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
6539
9715
  var PAGE_SIZE = 100;
6540
- var ghRunner = (args, maxBuffer) => execFileSync4("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
9716
+ var ghRunner = (args, maxBuffer) => execFileSync6("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
6541
9717
 
6542
9718
  class ForgeReadOversizeError extends Error {
6543
9719
  subject;
@@ -6644,7 +9820,7 @@ class ForgeSnapshotIssueNotFoundError extends Error {
6644
9820
  function readSnapshotFile(dir, file) {
6645
9821
  let text;
6646
9822
  try {
6647
- text = readFileSync3(join3(dir, file), "utf8");
9823
+ text = readFileSync8(join9(dir, file), "utf8");
6648
9824
  } catch {
6649
9825
  throw new ForgeSnapshotIncompleteError(dir, file);
6650
9826
  }
@@ -6695,12 +9871,12 @@ function incompleteForgeSnapshot(env = process.env) {
6695
9871
  if (dir === null)
6696
9872
  return null;
6697
9873
  for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
6698
- if (!existsSync3(join3(dir, file)))
9874
+ if (!existsSync7(join9(dir, file)))
6699
9875
  return new ForgeSnapshotIncompleteError(dir, file).message;
6700
9876
  }
6701
9877
  try {
6702
9878
  const issue = readSnapshotFile(dir, ISSUE_FILE);
6703
- if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync3(join3(dir, ISSUE_COMMENTS_FILE))) {
9879
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync7(join9(dir, ISSUE_COMMENTS_FILE))) {
6704
9880
  return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
6705
9881
  }
6706
9882
  } catch (err) {
@@ -6724,21 +9900,21 @@ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
6724
9900
 
6725
9901
  // ../../harness/kernel/gates/ops.ts
6726
9902
  init_config_schema();
6727
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4, resolve as resolve2, sep } from "node:path";
9903
+ import { dirname as dirname9, isAbsolute as isAbsolute2, join as join10, resolve as resolve3, sep as sep2 } from "node:path";
6728
9904
  function containedAbs(repoRoot, relPath) {
6729
- const root = resolve2(repoRoot);
6730
- const target = resolve2(root, relPath);
9905
+ const root = resolve3(repoRoot);
9906
+ const target = resolve3(root, relPath);
6731
9907
  if (target === root)
6732
9908
  return null;
6733
- return target === root || target.startsWith(root + sep) ? target : null;
9909
+ return target === root || target.startsWith(root + sep2) ? target : null;
6734
9910
  }
6735
9911
 
6736
9912
  // ../../harness/processes/vinaya-strict/tools/edge-resolve.ts
6737
- import { execFile as execFile4 } from "node:child_process";
6738
- import { promisify as promisify4 } from "node:util";
9913
+ import { execFile as execFile6 } from "node:child_process";
9914
+ import { promisify as promisify6 } from "node:util";
6739
9915
 
6740
9916
  // ../../harness/kernel/adapters/code-host/github/github-rate-limit.ts
6741
- import { execFileSync as execFileSync5 } from "node:child_process";
9917
+ import { execFileSync as execFileSync7 } from "node:child_process";
6742
9918
  var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
6743
9919
  var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
6744
9920
  function isGithubRateLimitError(text) {
@@ -6747,7 +9923,7 @@ function isGithubRateLimitError(text) {
6747
9923
  function rateLimitBudget(errorText) {
6748
9924
  return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
6749
9925
  }
6750
- var defaultReader = () => execFileSync5("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
9926
+ var defaultReader = () => execFileSync7("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
6751
9927
  function readRateLimitReset(budget, read = defaultReader) {
6752
9928
  let parsed;
6753
9929
  try {
@@ -6787,8 +9963,8 @@ ${message}` : message;
6787
9963
  init_parse_rationale_deps();
6788
9964
  var DIRECT_ISSUE_REF = /#(\d+)/;
6789
9965
  var issueCache = new Map;
6790
- var execFileAsync4 = promisify4(execFile4);
6791
- var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
9966
+ var execFileAsync6 = promisify6(execFile6);
9967
+ var ISSUE_NOT_FOUND2 = /could not resolve to an issue/i;
6792
9968
  function fetchIssueState(num, repo) {
6793
9969
  const key = `${repo.owner}/${repo.repo}#${num}`;
6794
9970
  const cached = issueCache.get(key);
@@ -6800,7 +9976,7 @@ function fetchIssueState(num, repo) {
6800
9976
  }
6801
9977
  async function readIssueOnce(num, repo) {
6802
9978
  try {
6803
- const { stdout } = await execFileAsync4("gh", [
9979
+ const { stdout } = await execFileAsync6("gh", [
6804
9980
  "issue",
6805
9981
  "view",
6806
9982
  String(num),
@@ -6811,7 +9987,7 @@ async function readIssueOnce(num, repo) {
6811
9987
  ], { encoding: "utf8" });
6812
9988
  return { json: JSON.parse(stdout), readFailed: false };
6813
9989
  } catch (err) {
6814
- return { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
9990
+ return { json: null, readFailed: !ISSUE_NOT_FOUND2.test(execErrorText(err)) };
6815
9991
  }
6816
9992
  }
6817
9993
  var defaultResolveSiblingTranche = async (slug, repo) => {
@@ -6939,8 +10115,8 @@ async function resolveSiblingConflictFacts(subject, openIssues, alreadyResolved,
6939
10115
 
6940
10116
  // ../../harness/processes/vinaya-strict/tools/premise-reassert-logic.ts
6941
10117
  init_premise_check();
6942
- import { readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
6943
- import { sep as sep2 } from "node:path";
10118
+ import { readFileSync as readFileSync9, realpathSync as realpathSync5 } from "node:fs";
10119
+ import { sep as sep3 } from "node:path";
6944
10120
  var CHECK_NAME = "pr-premise-reassert";
6945
10121
  function reassertPremiseFile(checkName, premiseFilePath, body, fileReader) {
6946
10122
  if (body === null) {
@@ -6958,6 +10134,8 @@ function reassertPremiseFile(checkName, premiseFilePath, body, fileReader) {
6958
10134
  };
6959
10135
  }
6960
10136
  const assertions = parsePremiseBlock(body);
10137
+ if (assertions.length === 0 && declaresNewFilesOnly(body))
10138
+ return { pass: true, errors: [] };
6961
10139
  if (assertions.length === 0) {
6962
10140
  return {
6963
10141
  pass: false,
@@ -6992,9 +10170,9 @@ function containedRealPath(root, p) {
6992
10170
  if (abs === null)
6993
10171
  return null;
6994
10172
  try {
6995
- const real = realpathSync3(abs);
6996
- const realRoot = realpathSync3(root);
6997
- return real === realRoot || real.startsWith(realRoot + sep2) ? real : null;
10173
+ const real = realpathSync5(abs);
10174
+ const realRoot = realpathSync5(root);
10175
+ return real === realRoot || real.startsWith(realRoot + sep3) ? real : null;
6998
10176
  } catch {
6999
10177
  return null;
7000
10178
  }
@@ -7004,7 +10182,7 @@ function defaultFileReader(p) {
7004
10182
  if (real === null)
7005
10183
  return null;
7006
10184
  try {
7007
- return readFileSync4(real, "utf8");
10185
+ return readFileSync9(real, "utf8");
7008
10186
  } catch {
7009
10187
  return null;
7010
10188
  }
@@ -7044,15 +10222,15 @@ function warnOnUnreadPrincipals(check, err) {
7044
10222
 
7045
10223
  // ../../harness/processes/vinaya-strict/checks/bin/check-dispatch-readiness.ts
7046
10224
  var CHECK_NAME2 = "dispatch-readiness";
7047
- var execFileAsync5 = promisify5(execFile5);
10225
+ var execFileAsync7 = promisify7(execFile7);
7048
10226
  function git(args) {
7049
10227
  try {
7050
- return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
10228
+ return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
7051
10229
  } catch {
7052
10230
  return "";
7053
10231
  }
7054
10232
  }
7055
- function resolveRepo() {
10233
+ function resolveRepo2() {
7056
10234
  const fromEnv = process.env.VINAYA_REPO;
7057
10235
  if (fromEnv) {
7058
10236
  const m = fromEnv.match(/^([^/]+)\/(.+)$/);
@@ -7074,7 +10252,7 @@ async function resolveToken() {
7074
10252
  if (process.env.GH_TOKEN)
7075
10253
  return process.env.GH_TOKEN;
7076
10254
  try {
7077
- const { stdout } = await execFileAsync5("gh", ["auth", "token"]);
10255
+ const { stdout } = await execFileAsync7("gh", ["auth", "token"]);
7078
10256
  const token = stdout.trim();
7079
10257
  return token.length > 0 ? token : null;
7080
10258
  } catch {
@@ -7098,13 +10276,13 @@ function checkPremiseReassertion() {
7098
10276
  const premiseFile = process.env.PREMISE_FILE;
7099
10277
  if (!premiseFile)
7100
10278
  return true;
7101
- const body = existsSync4(premiseFile) ? readFileSync5(premiseFile, "utf8") : null;
10279
+ const body = existsSync8(premiseFile) ? readFileSync10(premiseFile, "utf8") : null;
7102
10280
  const result = reassertPremiseFile(CHECK_NAME2, premiseFile, body, (p) => {
7103
10281
  const real = containedRealPath2(process.cwd(), p);
7104
10282
  if (real === null)
7105
10283
  return null;
7106
10284
  try {
7107
- return readFileSync5(real, "utf8");
10285
+ return readFileSync10(real, "utf8");
7108
10286
  } catch {
7109
10287
  return null;
7110
10288
  }
@@ -7118,9 +10296,9 @@ function containedRealPath2(root, p) {
7118
10296
  if (abs === null)
7119
10297
  return null;
7120
10298
  try {
7121
- const real = realpathSync4(abs);
7122
- const realRoot = realpathSync4(root);
7123
- return real === realRoot || real.startsWith(realRoot + sep3) ? real : null;
10299
+ const real = realpathSync6(abs);
10300
+ const realRoot = realpathSync6(root);
10301
+ return real === realRoot || real.startsWith(realRoot + sep4) ? real : null;
7124
10302
  } catch {
7125
10303
  return null;
7126
10304
  }
@@ -7130,20 +10308,21 @@ function fetchIssueJson(issueNumber) {
7130
10308
  const fromSnapshot = snapshotIssue(issueNumber);
7131
10309
  if (fromSnapshot !== null) {
7132
10310
  return {
7133
- number: fromSnapshot.number,
7134
- state: fromSnapshot.state,
7135
- body: fromSnapshot.body,
7136
- labels: fromSnapshot.labels
10311
+ outcome: "read",
10312
+ issue: {
10313
+ number: fromSnapshot.number,
10314
+ state: fromSnapshot.state,
10315
+ body: fromSnapshot.body,
10316
+ labels: fromSnapshot.labels
10317
+ }
7137
10318
  };
7138
10319
  }
7139
- const out = execFileSync6("gh", ["issue", "view", String(issueNumber), "--json", "number,state,body,labels"], {
7140
- encoding: "utf8",
7141
- stdio: ["ignore", "pipe", "pipe"]
7142
- });
7143
- return JSON.parse(out);
7144
- } catch {
7145
- return null;
10320
+ } catch (err) {
10321
+ if (err instanceof ForgeSnapshotIssueNotFoundError)
10322
+ return { outcome: "missing" };
10323
+ return { outcome: "failed", error: err instanceof Error ? err.message : String(err) };
7146
10324
  }
10325
+ return readTaskIssue(["issue", "view", String(issueNumber), "--json", "number,state,body,labels"]);
7147
10326
  }
7148
10327
  function resolveGatePrincipals() {
7149
10328
  try {
@@ -7190,14 +10369,18 @@ function exitWithGateVerdict(input, archival = { infraFailure: null }) {
7190
10369
  process.exit(ready ? 0 : 1);
7191
10370
  }
7192
10371
  async function runIssueMode(issueNumber) {
7193
- const issueJson = fetchIssueJson(issueNumber);
7194
- if (!issueJson) {
10372
+ const issueRead = fetchIssueJson(issueNumber);
10373
+ if (issueRead.outcome === "failed") {
10374
+ fail(issueReadFailedMessage("dispatch-gate", issueNumber, issueRead.error), recoveryPromptFor("issue-read-failed"));
10375
+ }
10376
+ if (issueRead.outcome === "missing") {
7195
10377
  fail(`dispatch-gate issue-existence: Issue #${issueNumber} does not resolve on the forge.`, "Confirm the Issue number is correct and `gh auth status` passes, then re-run `vinaya-check dispatch-readiness`.");
7196
10378
  }
10379
+ const issueJson = issueRead.issue;
7197
10380
  if (issueJson.labels.some((l) => l.name.startsWith("vinaya/tranche:"))) {
7198
10381
  fail(`dispatch-gate: Issue #${issueNumber} carries a vinaya/tranche:* label — it belongs to a tranche, not the tranche-less backlog path.`, "This Issue has a real tranche home — run this check on its tranche-shaped branch instead.");
7199
10382
  }
7200
- const repo = resolveRepo();
10383
+ const repo = resolveRepo2();
7201
10384
  if (!repo) {
7202
10385
  fail("dispatch-gate severity:infra — could not resolve owner/repo.", "Set VINAYA_REPO=owner/repo, or confirm `git remote get-url origin` resolves to a GitHub URL, then re-run `vinaya-check dispatch-readiness`.");
7203
10386
  }
@@ -7234,7 +10417,7 @@ async function runIssueMode(issueNumber) {
7234
10417
  });
7235
10418
  }
7236
10419
  async function runTrancheMode(trancheSlug, taskId) {
7237
- const repo = resolveRepo();
10420
+ const repo = resolveRepo2();
7238
10421
  if (!repo) {
7239
10422
  fail("dispatch-gate severity:infra — could not resolve owner/repo.", "Set VINAYA_REPO=owner/repo, or confirm `git remote get-url origin` resolves to a GitHub URL, then re-run `vinaya-check dispatch-readiness`.");
7240
10423
  }
@@ -7334,6 +10517,8 @@ function recoveryPromptFor(blockerClass) {
7334
10517
  return "This is an INTERNAL parser-bug report, not a real dispatch gate — a task cannot depend on itself, so there is nothing here to wait for or resolve. Do NOT work around it and do NOT skip the hook. Report it upstream, and re-run once the rationale text is corrected or the parser fix ships.";
7335
10518
  case "issue-existence":
7336
10519
  return "This task has no resolvable Issue yet. Wait for the Planner to cut the Issue (or fix the phantom reference in the topology), then re-run `vinaya-check dispatch-readiness`.";
10520
+ case "issue-read-failed":
10521
+ return "The forge could not be read for this task's Issue, so whether it exists is unknown — this is not a claim that the Issue is missing. Re-run `vinaya-check dispatch-readiness` once the forge answers; if it keeps failing, check forge access (network, rate limit, credentials).";
7337
10522
  case "rationale":
7338
10523
  return "The task's Issue fails the rationale gate. Ask the Planner to complete the eight-field rationale on the Issue body, then re-run `vinaya-check dispatch-readiness`.";
7339
10524
  case "depends-on-unresolvable":