@attalabs/vinaya 0.44.1 → 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 (143) hide show
  1. package/README.md +6 -4
  2. package/dist/checks/bin/check-body-bare-digits.js +233 -195
  3. package/dist/checks/bin/check-branch-topology.js +70 -23
  4. package/dist/checks/bin/check-brief-shape.js +233 -195
  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 +128 -34
  8. package/dist/checks/bin/check-coherence.js +336 -245
  9. package/dist/checks/bin/check-dispatch-readiness.js +3623 -463
  10. package/dist/checks/bin/check-doc-claims.js +233 -195
  11. package/dist/checks/bin/check-doc-coverage-push.js +243 -196
  12. package/dist/checks/bin/check-doc-coverage.js +243 -196
  13. package/dist/checks/bin/check-doctrine-no-procedures.js +233 -195
  14. package/dist/checks/bin/check-doctrine-portability.js +233 -195
  15. package/dist/checks/bin/check-evidence-fresh.js +9983 -1995
  16. package/dist/checks/bin/check-exec-bits.js +3 -0
  17. package/dist/checks/bin/check-first-push-dispatch.js +301 -224
  18. package/dist/checks/bin/check-issue-milestone-attach.js +65 -10
  19. package/dist/checks/bin/check-issue-objectives-numbering.js +233 -195
  20. package/dist/checks/bin/check-issue-parts-coverage.js +65 -10
  21. package/dist/checks/bin/check-issue-surface-globs.js +1032 -236
  22. package/dist/checks/bin/check-issue-title-grammar.js +5 -1
  23. package/dist/checks/bin/check-no-disk-state.js +5 -1
  24. package/dist/checks/bin/check-pr-premise-reassert.js +10 -1
  25. package/dist/checks/bin/check-pr-report-density.js +5 -1
  26. package/dist/checks/bin/check-principal-test-plan-wait.js +253 -201
  27. package/dist/checks/bin/check-quoted-command.js +233 -195
  28. package/dist/checks/bin/check-reader-resolvable-prose.js +233 -195
  29. package/dist/checks/bin/check-registry-gates.js +131 -34
  30. package/dist/checks/bin/check-retired-vocabulary.js +233 -195
  31. package/dist/checks/bin/check-review-gate.js +233 -195
  32. package/dist/checks/bin/check-single-plan-pr.js +5 -1
  33. package/dist/checks/bin/check-surface-scope.js +107 -32
  34. package/dist/checks/bin/check-test-plan.js +253 -201
  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 +16617 -7187
  42. package/dist/lib/pre-push-cache-test-run.js +4487 -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 +15612 -7634
  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 +9476 -1820
  60. package/dist/programs/pr-snapshot.js +8916 -1515
  61. package/dist/programs/pr-verify-evidence.js +9481 -1825
  62. package/dist/programs/pr.js +11709 -4033
  63. package/dist/programs/review-post.js +11140 -3496
  64. package/dist/programs/review-status.js +8996 -1533
  65. package/dist/programs/run-engine.js +22031 -18759
  66. package/dist/programs/sync.js +9030 -1629
  67. package/dist/programs/task-brief.js +10185 -1821
  68. package/dist/programs/task-sweep.js +9266 -1621
  69. package/dist/programs/task-tools-serve.js +77118 -16678
  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 +3 -3
  75. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/objectives.d.ts +5 -6
  76. package/dist/vinaya-strict/checks/registry.ts +2 -2
  77. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +8 -0
  78. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +1 -1
  79. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +2 -2
  80. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +30 -20
  81. package/dist/vinaya-strict/executing/developer/reference.md +5 -3
  82. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +29 -7
  83. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +4 -4
  84. package/dist/vinaya-strict/integration/process/process-integration.ts +5 -1
  85. package/dist/vinaya-strict/process.yaml +6 -1
  86. package/dist/vinaya-strict/thinking/plan-reviewer/doctrine.md +68 -0
  87. package/dist/vinaya-strict/thinking/plan-reviewer/grants.yaml +19 -0
  88. package/dist/vinaya-strict/thinking/plan-reviewer/output.schema.json +388 -0
  89. package/dist/vinaya-strict/thinking/planner/doctrine.md +4 -1
  90. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +10 -2
  91. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +5 -1
  92. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +198 -34
  93. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +120 -193
  94. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +629 -15
  95. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +726 -62
  96. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +505 -5
  97. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +636 -21
  98. package/package.json +3 -2
  99. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  100. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  101. package/studio-standalone/apps/vinaya-studio/.next/prerender-manifest.json +3 -3
  102. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  103. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  104. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  105. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  106. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  107. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  108. package/studio-standalone/apps/vinaya-studio/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  109. package/studio-standalone/apps/vinaya-studio/.next/server/app/milestones/page_client-reference-manifest.js +1 -1
  110. package/studio-standalone/apps/vinaya-studio/.next/server/app/page_client-reference-manifest.js +1 -1
  111. package/studio-standalone/apps/vinaya-studio/.next/server/app/tasks/page_client-reference-manifest.js +1 -1
  112. package/studio-standalone/apps/vinaya-studio/.next/server/chunks/209.js +2 -2
  113. package/studio-standalone/apps/vinaya-studio/.next/server/chunks/951.js +1 -1
  114. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  115. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  116. package/studio-standalone/apps/vinaya-studio/.next/server/preview-props.json +3 -3
  117. package/studio-standalone/apps/vinaya-studio/.next/server/server-reference-manifest.json +1 -1
  118. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/151-c365f0ef8268ad13.js +1 -0
  119. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/19-aa314f13784dcc58.js +4 -0
  120. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/{layout-dfa2186095e797bd.js → layout-f038e8deecb2bf5f.js} +1 -1
  121. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/milestones/{page-2fffb49104860a15.js → page-12314f4deb06a414.js} +1 -1
  122. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/{page-6ae258f663623b2a.js → page-7a06aa3cdd046fa8.js} +1 -1
  123. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/tasks/{page-2fffb49104860a15.js → page-12314f4deb06a414.js} +1 -1
  124. package/studio-standalone/apps/vinaya-studio/.next/static/css/8eb5ed5b65b9692e.css +1 -0
  125. package/studio-standalone/apps/vinaya-studio/log-follow.mjs +708 -93
  126. package/studio-standalone/apps/vinaya-studio/log-sync-folder-source.mjs +699 -84
  127. package/studio-standalone/apps/vinaya-studio/studio-server.mjs +4692 -3116
  128. package/vinaya-strict/artifacts/templates/brief-template.md +4 -0
  129. package/vinaya-strict/artifacts/templates/issue-rationale-template.md +7 -3
  130. package/vinaya-strict/artifacts/templates/pr-report-template.md +1 -1
  131. package/vinaya-strict/doctrine/contracts/planner-developer.md +2 -1
  132. package/vinaya-strict/doctrine/enforcement.md +4 -4
  133. package/vinaya-strict/doctrine/roles/principal.md +1 -1
  134. package/vinaya-strict/doctrine/state-machine.md +7 -2
  135. package/vinaya-strict/executing/developer/reference.md +5 -3
  136. package/vinaya-strict/thinking/plan-reviewer/doctrine.md +68 -0
  137. package/vinaya-strict/thinking/planner/doctrine.md +4 -1
  138. package/vinaya-strict/thinking/planner/reference.md +29 -8
  139. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/151-23bea4cac9687151.js +0 -1
  140. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/853-1d5548ff3a55a75f.js +0 -4
  141. package/studio-standalone/apps/vinaya-studio/.next/static/css/fb16828fc3128d4c.css +0 -1
  142. /package/studio-standalone/apps/vinaya-studio/.next/static/{3URbt6IPajL5OOhijN1-x → bJrgAp9Kl4JsCUYkeAYez}/_buildManifest.js +0 -0
  143. /package/studio-standalone/apps/vinaya-studio/.next/static/{3URbt6IPajL5OOhijN1-x → 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];
@@ -1598,6 +1626,7 @@ var init_doctrine_map = __esm(() => {
1598
1626
  { key: "roles/developer.md", source: "executing/developer/doctrine.md", role: "developer", ships: true },
1599
1627
  { key: "roles/developer/reference.md", source: "executing/developer/reference.md", ships: true },
1600
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 },
1601
1630
  { key: "roles/planner.md", source: "thinking/planner/doctrine.md", role: "planner", ships: true },
1602
1631
  { key: "roles/planner/reference.md", source: "thinking/planner/reference.md", ships: true },
1603
1632
  { key: "roles/principal.md", source: "doctrine/roles/principal.md", role: "principal", ships: true },
@@ -2720,7 +2749,13 @@ function isMechanicallyNeutralDiff(diffText, path) {
2720
2749
  }
2721
2750
  return sawChange;
2722
2751
  }
2723
- 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) {
2724
2759
  const out = { errors: [], notes: [] };
2725
2760
  if (docOwnersContent === null)
2726
2761
  return out;
@@ -2760,24 +2795,28 @@ function evaluateC5(changed, docOwnersContent, prBody, fileExists, waiverActive,
2760
2795
  }
2761
2796
  if (changed.includes(pointerPath))
2762
2797
  continue;
2798
+ const evidenced = () => getDiff !== undefined && matchedFiles.every((f) => {
2799
+ const diff = getDiff(f);
2800
+ return diff !== null && isMechanicallyNeutralDiff(diff, f);
2801
+ });
2763
2802
  const declared = neutrals.find((n) => n.surface === b.pointer);
2764
2803
  if (declared) {
2765
- const evidenced = getDiff !== undefined && matchedFiles.every((f) => {
2766
- const diff = getDiff(f);
2767
- return diff !== null && isMechanicallyNeutralDiff(diff, f);
2768
- });
2769
- if (evidenced) {
2804
+ if (evidenced()) {
2770
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.`);
2771
2806
  continue;
2772
2807
  }
2773
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.`);
2774
2809
  continue;
2775
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
+ }
2776
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.`);
2777
2816
  }
2778
2817
  return out;
2779
2818
  }
2780
- 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:";
2781
2820
  var init_doc_owners = __esm(() => {
2782
2821
  init_file_classify();
2783
2822
  init_waiver_label();
@@ -2832,6 +2871,20 @@ var init_protected_paths = __esm(() => {
2832
2871
  ];
2833
2872
  });
2834
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
+
2835
2888
  // ../../harness/processes/vinaya-strict/tools/task-contract/issue-validation.ts
2836
2889
  function hasRationaleField(body, labelPattern) {
2837
2890
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -3030,7 +3083,7 @@ function checkPartsCiteDefinedObjectives(body) {
3030
3083
  return { status: errors.length > 0 ? "fail" : "pass", errors };
3031
3084
  }
3032
3085
  function liveCommand(text) {
3033
- const trimmed = text.trim();
3086
+ const trimmed = stripObjectiveIdSpans(text);
3034
3087
  const span = /^(`+)(.+)\1$/.exec(trimmed);
3035
3088
  return span ? span[2].trim() : trimmed;
3036
3089
  }
@@ -3165,11 +3218,13 @@ var init_issue_validation = __esm(() => {
3165
3218
  init_derive_section7();
3166
3219
  init_doctrine_map();
3167
3220
  init_objectives();
3221
+ init_waiver_label();
3168
3222
  init_issue_documentation();
3169
3223
  init_touched_path();
3170
3224
  init_protected_paths();
3171
3225
  init_quoted_command();
3172
3226
  init_test_plan_section();
3227
+ init_test_plan_proof();
3173
3228
  RATIONALE_FIELDS = [
3174
3229
  { name: "Boundary", pattern: "Boundary" },
3175
3230
  { name: "Sizing", pattern: "Sizing" },
@@ -3217,68 +3272,3223 @@ var init_issue_validation = __esm(() => {
3217
3272
  CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
3218
3273
  });
3219
3274
 
3220
- // ../../harness/kernel/gates/checks/contract.ts
3221
- function emitCheckError(error) {
3222
- process.stderr.write(`${JSON.stringify(error)}
3223
- `);
3224
- }
3225
- 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 = () => {};
3226
3313
 
3227
- // ../../harness/kernel/log/custom.ts
3314
+ // ../../harness/kernel/connectors/checkpoint/control-store/records.ts
3228
3315
  import { z } from "zod";
3229
- 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;
3230
- var init_custom = __esm(() => {
3231
- CUSTOM_EVENT_NAME_PATTERN = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_.]*$/;
3232
- CUSTOM_FIELD_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
3233
- CUSTOM_WORD_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
3234
- CustomFieldTypeSchema = z.union([z.enum(["text", "number", "boolean"]), z.array(z.string())]);
3235
- CustomEventDeclarationsSchema = z.record(z.string(), z.object({
3236
- fields: z.record(z.string(), CustomFieldTypeSchema)
3237
- }).strict()).superRefine((events, ctx) => {
3238
- for (const [name, declaration] of Object.entries(events)) {
3239
- const refuse = (message, path = []) => {
3240
- ctx.addIssue({
3241
- code: z.ZodIssueCode.custom,
3242
- path: [name, ...path],
3243
- message: `logs.events "${name}": ${message}`
3244
- });
3245
- };
3246
- if (name.length > CUSTOM_EVENT_NAME_MAX_LENGTH) {
3247
- 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)`);
3248
3569
  }
3249
- if (!CUSTOM_EVENT_NAME_PATTERN.test(name)) {
3250
- refuse("the name must be `<namespace>.<event>` — lowercase letters, digits and `_`, a dot between them");
3251
- } else if (name.split(".")[0] === CUSTOM_EVENT_RESERVED_NAMESPACE) {
3252
- 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)}`);
3253
3575
  }
3254
- const fieldEntries = Object.entries(declaration.fields);
3255
- if (fieldEntries.length > CUSTOM_EVENT_MAX_FIELDS) {
3256
- 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`);
3257
3578
  }
3258
- for (const [field, type] of fieldEntries) {
3259
- if (field.length > CUSTOM_FIELD_NAME_MAX_LENGTH || !CUSTOM_FIELD_NAME_PATTERN.test(field)) {
3260
- 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]);
3261
- }
3262
- if (typeof type === "string")
3263
- continue;
3264
- if (type.length === 0) {
3265
- refuse(`field "${field}": a list of words must name at least one word`, ["fields", field]);
3266
- }
3267
- if (type.length > CUSTOM_FIELD_MAX_WORDS) {
3268
- refuse(`field "${field}": a list of words may name at most ${CUSTOM_FIELD_MAX_WORDS}`, ["fields", field]);
3269
- }
3270
- const bad = type.filter((w) => w.length > CUSTOM_WORD_MAX_LENGTH || !CUSTOM_WORD_PATTERN.test(w));
3271
- if (bad.length > 0) {
3272
- refuse(`field "${field}": a listed word is lowercase letters, digits, \`_\` and \`-\`, at most ${CUSTOM_WORD_MAX_LENGTH} characters`, ["fields", field]);
3273
- }
3274
- if (new Set(type).size !== type.length) {
3275
- refuse(`field "${field}": a list of words names a word twice`, ["fields", field]);
3276
- }
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`);
3277
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`);
3278
3589
  }
3279
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();
3280
3804
  });
3281
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
+
3282
6492
  // ../../harness/kernel/adapters/agents/agent-vendors.ts
3283
6493
  var AGENT_VENDORS;
3284
6494
  var init_agent_vendors = __esm(() => {
@@ -3286,10 +6496,10 @@ var init_agent_vendors = __esm(() => {
3286
6496
  });
3287
6497
 
3288
6498
  // ../../harness/kernel/config/loader/config-loader.ts
3289
- import { execFile as execFile3, execFileSync as execFileSync2 } from "node:child_process";
3290
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync as realpathSync2, writeFileSync } from "node:fs";
3291
- import { basename as basename2, dirname, join, resolve } from "node:path";
3292
- 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";
3293
6503
  function firstLine(err) {
3294
6504
  return err?.message?.split(`
3295
6505
  `)[0] ?? "unknown error";
@@ -3325,7 +6535,7 @@ function trustAnchorRepo() {
3325
6535
  if (fromRunner)
3326
6536
  return fromRunner;
3327
6537
  try {
3328
- const url = execFileSync2("git", ["remote", "get-url", "origin"], {
6538
+ const url = execFileSync4("git", ["remote", "get-url", "origin"], {
3329
6539
  encoding: "utf-8",
3330
6540
  stdio: ["ignore", "pipe", "pipe"]
3331
6541
  });
@@ -3339,7 +6549,7 @@ async function trustAnchorRepoAsync() {
3339
6549
  if (fromRunner)
3340
6550
  return fromRunner;
3341
6551
  try {
3342
- const { stdout } = await execFileAsync3("git", ["remote", "get-url", "origin"], {
6552
+ const { stdout } = await execFileAsync5("git", ["remote", "get-url", "origin"], {
3343
6553
  encoding: "utf-8",
3344
6554
  timeout: 1e4,
3345
6555
  killSignal: "SIGKILL"
@@ -3359,9 +6569,9 @@ function resolveCiTrustAnchorProbeRef(env, probeRefVariable) {
3359
6569
  return null;
3360
6570
  return ref;
3361
6571
  }
3362
- function gitCommonDir(cwd = process.cwd()) {
6572
+ function gitCommonDir2(cwd = process.cwd()) {
3363
6573
  try {
3364
- const raw = execFileSync2("git", ["rev-parse", "--git-common-dir"], {
6574
+ const raw = execFileSync4("git", ["rev-parse", "--git-common-dir"], {
3365
6575
  cwd,
3366
6576
  encoding: "utf-8",
3367
6577
  stdio: ["ignore", "pipe", "pipe"],
@@ -3369,20 +6579,20 @@ function gitCommonDir(cwd = process.cwd()) {
3369
6579
  }).trim();
3370
6580
  if (!raw)
3371
6581
  return null;
3372
- return realpathSync2(resolve(cwd, raw));
6582
+ return realpathSync4(resolve2(cwd, raw));
3373
6583
  } catch {
3374
6584
  return null;
3375
6585
  }
3376
6586
  }
3377
6587
  function gitAbsoluteDir(cwd) {
3378
6588
  try {
3379
- const raw = execFileSync2("git", ["rev-parse", "--absolute-git-dir"], {
6589
+ const raw = execFileSync4("git", ["rev-parse", "--absolute-git-dir"], {
3380
6590
  cwd,
3381
6591
  encoding: "utf-8",
3382
6592
  stdio: ["ignore", "pipe", "pipe"],
3383
6593
  timeout: GIT_IDENTITY_TIMEOUT_MS
3384
6594
  }).trim();
3385
- return raw ? realpathSync2(raw) : null;
6595
+ return raw ? realpathSync4(raw) : null;
3386
6596
  } catch {
3387
6597
  return null;
3388
6598
  }
@@ -3398,16 +6608,16 @@ function flattenKeys(value, prefix, out) {
3398
6608
  function readLocalOverrideFile(options, cwd = process.cwd()) {
3399
6609
  if (options.suppressedBy.some((name) => process.env[name]))
3400
6610
  return null;
3401
- const common = gitCommonDir(cwd);
6611
+ const common = gitCommonDir2(cwd);
3402
6612
  if (!common || basename2(common) !== ".git")
3403
6613
  return null;
3404
- const root = dirname(common);
6614
+ const root = dirname7(common);
3405
6615
  if (gitAbsoluteDir(cwd) !== common)
3406
6616
  return null;
3407
- const path = join(root, options.fileName);
6617
+ const path = join7(root, options.fileName);
3408
6618
  let stat;
3409
6619
  try {
3410
- stat = lstatSync(path);
6620
+ stat = lstatSync4(path);
3411
6621
  } catch {
3412
6622
  return null;
3413
6623
  }
@@ -3415,7 +6625,7 @@ function readLocalOverrideFile(options, cwd = process.cwd()) {
3415
6625
  return null;
3416
6626
  let raw;
3417
6627
  try {
3418
- raw = JSON.parse(readFileSync(path, "utf-8"));
6628
+ raw = JSON.parse(readFileSync6(path, "utf-8"));
3419
6629
  } catch (err) {
3420
6630
  throw new Error(`${options.fileName}: invalid JSON — ${err.message}`);
3421
6631
  }
@@ -3439,16 +6649,16 @@ function schemaIssueDetail(error) {
3439
6649
  }
3440
6650
  function createConfigLoader(options) {
3441
6651
  const { schema, localFileName, homeDir } = options;
3442
- const globalConfigPath = join(homeDir, options.globalFileName);
6652
+ const globalConfigPath = join7(homeDir, options.globalFileName);
3443
6653
  function findLocalConfig() {
3444
6654
  let dir = process.cwd();
3445
6655
  while (true) {
3446
- const candidate = join(dir, localFileName);
3447
- if (existsSync(candidate))
6656
+ const candidate = join7(dir, localFileName);
6657
+ if (existsSync5(candidate))
3448
6658
  return candidate;
3449
- if (existsSync(join(dir, ".git")))
6659
+ if (existsSync5(join7(dir, ".git")))
3450
6660
  return null;
3451
- const parent = dirname(dir);
6661
+ const parent = dirname7(dir);
3452
6662
  if (parent === dir)
3453
6663
  return null;
3454
6664
  dir = parent;
@@ -3458,13 +6668,13 @@ function createConfigLoader(options) {
3458
6668
  const local = findLocalConfig();
3459
6669
  if (local)
3460
6670
  return local;
3461
- if (existsSync(globalConfigPath))
6671
+ if (existsSync5(globalConfigPath))
3462
6672
  return globalConfigPath;
3463
6673
  return null;
3464
6674
  }
3465
6675
  function repoLocalConfigDir() {
3466
6676
  const local = findLocalConfig();
3467
- return local ? dirname(local) : null;
6677
+ return local ? dirname7(local) : null;
3468
6678
  }
3469
6679
  const emittedGlobalKeyWarnings = new Set;
3470
6680
  function warnGlobalKeyIgnoredOnce(message) {
@@ -3500,7 +6710,7 @@ ${detail}`;
3500
6710
  return null;
3501
6711
  let text;
3502
6712
  try {
3503
- text = readFileSync(path, "utf-8");
6713
+ text = readFileSync6(path, "utf-8");
3504
6714
  } catch (err) {
3505
6715
  reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
3506
6716
  return null;
@@ -3525,7 +6735,7 @@ ${detail}`;
3525
6735
  return { ok: true, config: null };
3526
6736
  let raw;
3527
6737
  try {
3528
- raw = JSON.parse(readFileSync(path, "utf-8"));
6738
+ raw = JSON.parse(readFileSync6(path, "utf-8"));
3529
6739
  } catch (err) {
3530
6740
  return { ok: false, path, error: `invalid JSON: ${err.message}` };
3531
6741
  }
@@ -3536,11 +6746,11 @@ ${detail}`;
3536
6746
  return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
3537
6747
  }
3538
6748
  function readRepoConfig(repoRoot) {
3539
- const p = join(repoRoot, localFileName);
3540
- if (!existsSync(p))
6749
+ const p = join7(repoRoot, localFileName);
6750
+ if (!existsSync5(p))
3541
6751
  return null;
3542
6752
  try {
3543
- return schema.parse(JSON.parse(readFileSync(p, "utf-8")));
6753
+ return schema.parse(JSON.parse(readFileSync6(p, "utf-8")));
3544
6754
  } catch {
3545
6755
  return null;
3546
6756
  }
@@ -3549,17 +6759,17 @@ ${detail}`;
3549
6759
  let targetPath;
3550
6760
  if (scope === "local") {
3551
6761
  const base = repoRoot ?? process.cwd();
3552
- targetPath = join(base, localFileName);
6762
+ targetPath = join7(base, localFileName);
3553
6763
  } else {
3554
- if (!existsSync(homeDir)) {
3555
- mkdirSync(homeDir, { recursive: true });
6764
+ if (!existsSync5(homeDir)) {
6765
+ mkdirSync5(homeDir, { recursive: true });
3556
6766
  }
3557
6767
  targetPath = globalConfigPath;
3558
6768
  }
3559
- writeFileSync(targetPath, JSON.stringify(config, null, 2), "utf-8");
6769
+ writeFileSync3(targetPath, JSON.stringify(config, null, 2), "utf-8");
3560
6770
  }
3561
6771
  function readTrustAnchorConfigAtRef(ref) {
3562
- const raw = execFileSync2("git", ["show", `${ref}:${localFileName}`], {
6772
+ const raw = execFileSync4("git", ["show", `${ref}:${localFileName}`], {
3563
6773
  encoding: "utf-8",
3564
6774
  stdio: ["ignore", "pipe", "pipe"],
3565
6775
  timeout: 1e4
@@ -3573,7 +6783,7 @@ ${detail}`;
3573
6783
  const repo = trustAnchorRepo();
3574
6784
  if (!repo)
3575
6785
  throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
3576
- return execFileSync2("gh", ["api", `repos/${repo}/contents/${localFileName}`, "--jq", ".content"], {
6786
+ return execFileSync4("gh", ["api", `repos/${repo}/contents/${localFileName}`, "--jq", ".content"], {
3577
6787
  encoding: "utf-8",
3578
6788
  stdio: ["ignore", "pipe", "pipe"]
3579
6789
  });
@@ -3581,7 +6791,7 @@ ${detail}`;
3581
6791
  async function fetchTrustAnchorConfigAsync() {
3582
6792
  const probeRef = resolveCiTrustAnchorProbeRef(process.env, options.probeRefVariable);
3583
6793
  if (probeRef) {
3584
- const { stdout } = await execFileAsync3("git", ["show", `${probeRef}:${localFileName}`], {
6794
+ const { stdout } = await execFileAsync5("git", ["show", `${probeRef}:${localFileName}`], {
3585
6795
  encoding: "utf-8",
3586
6796
  timeout: 1e4
3587
6797
  });
@@ -3590,7 +6800,7 @@ ${detail}`;
3590
6800
  const repo = await trustAnchorRepoAsync();
3591
6801
  if (!repo)
3592
6802
  throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
3593
- 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" });
3594
6804
  return stdout;
3595
6805
  }
3596
6806
  function warnTrustAnchorFallback(why) {
@@ -3617,14 +6827,15 @@ ${detail}`;
3617
6827
  return null;
3618
6828
  }
3619
6829
  }
3620
- function loadTrustAnchorConfig(fetcher = fetchTrustAnchorConfig) {
6830
+ function loadTrustAnchorConfig(fetcher = fetchTrustAnchorConfig, loadOptions = {}) {
6831
+ const warn = loadOptions.quiet ? () => {} : warnTrustAnchorFallback;
3621
6832
  let base64;
3622
6833
  try {
3623
6834
  base64 = fetcher();
3624
6835
  } catch (err) {
3625
- return trustAnchorFetchFailed(err);
6836
+ return trustAnchorFetchFailed(err, warn);
3626
6837
  }
3627
- return parseTrustAnchorContent(base64);
6838
+ return parseTrustAnchorContent(base64, warn);
3628
6839
  }
3629
6840
  function loadTrustAnchorConfigOrThrow(fetcher = fetchTrustAnchorConfig) {
3630
6841
  let base64;
@@ -3664,173 +6875,12 @@ ${detail}`;
3664
6875
  loadTrustAnchorConfigAsync
3665
6876
  };
3666
6877
  }
3667
- 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;
3668
6879
  var init_config_loader = __esm(() => {
3669
- execFileAsync3 = promisify3(execFile3);
6880
+ execFileAsync5 = promisify5(execFile5);
3670
6881
  emittedLocalOverrideWarnings = new Set;
3671
6882
  });
3672
6883
 
3673
- // ../../harness/kernel/config/loader/config-provider.ts
3674
- function installConfigProvider(provider) {
3675
- installed = provider;
3676
- }
3677
- function configProvider() {
3678
- if (!installed)
3679
- throw new Error(NO_CONFIG_PROVIDER_MESSAGE);
3680
- return installed;
3681
- }
3682
- var installed = null, NO_CONFIG_PROVIDER_MESSAGE = "no configuration provider is installed — a composition root must call installConfigProvider() before any configuration read";
3683
-
3684
- // ../../harness/kernel/config/schema/config-schema.ts
3685
- import { isAbsolute } from "node:path";
3686
- import { z as z2 } from "zod";
3687
- function checkEntrySchema(fields) {
3688
- return z2.object(fields).superRefine((entry, ctx) => {
3689
- const env = entry.env;
3690
- if (!env)
3691
- return;
3692
- for (const [key, value] of Object.entries(env)) {
3693
- if (typeof value !== "object" || value === null || !("anyOf" in value))
3694
- continue;
3695
- const members = value.anyOf;
3696
- if (new Set(members).size !== members.length) {
3697
- ctx.addIssue({
3698
- code: z2.ZodIssueCode.custom,
3699
- message: `env.${key}.anyOf has duplicate members`,
3700
- path: ["env", key, "anyOf"]
3701
- });
3702
- }
3703
- if (!members.includes(key)) {
3704
- ctx.addIssue({
3705
- code: z2.ZodIssueCode.custom,
3706
- message: `env.${key}.anyOf must include "${key}" itself as a member`,
3707
- path: ["env", key, "anyOf"]
3708
- });
3709
- }
3710
- }
3711
- });
3712
- }
3713
- function isSafeRepoRelPath(p) {
3714
- if (p.length === 0)
3715
- return false;
3716
- if (p.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(p))
3717
- return false;
3718
- return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
3719
- }
3720
- function hookBlockPathRule(prefixes) {
3721
- const isCanonical = (p) => prefixes.some((prefix) => p.startsWith(prefix) && p.length > prefix.length);
3722
- const schema = SafeRepoRelPath.refine(isCanonical, {
3723
- message: `must start with one of ${prefixes.join(", ")} (byte-exact, case-sensitive)`
3724
- });
3725
- return { isCanonical, schema };
3726
- }
3727
- function managedManifestSchemas(agentVendors, hookBlockPrefixes) {
3728
- const block = z2.object({
3729
- path: hookBlockPathRule(hookBlockPrefixes).schema,
3730
- marker: z2.string(),
3731
- comment: z2.enum(["hash", "html"])
3732
- });
3733
- const manifest = z2.object({
3734
- version: z2.number().int().positive(),
3735
- files: z2.array(SafeRepoRelPath),
3736
- blocks: z2.array(block),
3737
- labels: z2.array(z2.string()),
3738
- agents: z2.array(z2.enum(agentVendors)).optional()
3739
- });
3740
- return { block, manifest };
3741
- }
3742
- function logsSchema(events) {
3743
- return z2.object({
3744
- folder: z2.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
3745
- url: z2.string().url().optional(),
3746
- headers: z2.record(z2.string()).optional(),
3747
- readHeaders: z2.record(z2.string()).optional(),
3748
- events: events.optional()
3749
- }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
3750
- message: "logs: set at most one of folder/url"
3751
- }).refine((v) => v.headers === undefined || v.url !== undefined, {
3752
- message: "logs: headers requires url"
3753
- }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
3754
- message: "logs: readHeaders requires url"
3755
- }).or(z2.literal(false)).optional();
3756
- }
3757
- function kernelConfigFragment(leaves) {
3758
- return {
3759
- rings: z2.object({
3760
- ring1_forgeWriteInterception: z2.boolean(),
3761
- ring2_asyncAudits: z2.boolean()
3762
- }).optional(),
3763
- checks: z2.record(z2.string(), checkEntrySchema(leaves.checkEntryFields)).optional(),
3764
- managed: managedManifestSchemas(leaves.agentVendors, leaves.hookBlockPrefixes).manifest.optional(),
3765
- ci: z2.object({ setup: z2.string().min(1) }).optional(),
3766
- logPublish: z2.unknown().refine((v) => v === undefined, {
3767
- message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
3768
- }),
3769
- runtimeDir: z2.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
3770
- runner: z2.enum(["standalone", "atta-engine"]).optional(),
3771
- logs: logsSchema(leaves.logEvents)
3772
- };
3773
- }
3774
- function resolveRuntimeDirSetting(config) {
3775
- return config?.runtimeDir ?? null;
3776
- }
3777
- function resolveTrustAnchorRuntimeDir(localRuntimeDir, trustAnchorConfig) {
3778
- const anchored = resolveRuntimeDirSetting(trustAnchorConfig);
3779
- return anchored !== null && anchored === localRuntimeDir ? anchored : null;
3780
- }
3781
- function resolveLogsSetting(config) {
3782
- const raw = config?.logs;
3783
- if (!raw)
3784
- return null;
3785
- if (raw.url !== undefined)
3786
- return { url: raw.url, headers: raw.headers };
3787
- if (raw.folder !== undefined)
3788
- return { folder: raw.folder };
3789
- return null;
3790
- }
3791
- function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
3792
- const anchored = resolveLogsSetting(trustAnchorConfig);
3793
- if (!anchored)
3794
- return null;
3795
- if ("url" in local)
3796
- return "url" in anchored && anchored.url === local.url ? anchored : null;
3797
- return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
3798
- }
3799
- function resolveLogsHeaderValues(headers, env) {
3800
- if (!headers)
3801
- return;
3802
- const resolved = {};
3803
- for (const [key, value] of Object.entries(headers)) {
3804
- resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
3805
- }
3806
- return resolved;
3807
- }
3808
- var EnvEntrySchema, KERNEL_CHECK_ENTRY_FIELDS, SafeRepoRelPath, KERNEL_CONFIG_REFINEMENTS;
3809
- var init_config_schema = __esm(() => {
3810
- EnvEntrySchema = z2.union([
3811
- z2.literal(true),
3812
- z2.object({ optional: z2.literal(true) }),
3813
- z2.object({ anyOf: z2.array(z2.string()).min(2) }),
3814
- z2.string()
3815
- ]);
3816
- KERNEL_CHECK_ENTRY_FIELDS = {
3817
- run: z2.string(),
3818
- scope: z2.enum(["diff", "full"]),
3819
- include: z2.array(z2.string()).optional(),
3820
- args: z2.array(z2.string()).optional(),
3821
- timeoutMs: z2.number().optional(),
3822
- env: z2.record(z2.string(), EnvEntrySchema).optional(),
3823
- requiresOpenPr: z2.boolean().optional(),
3824
- ownWorkflow: z2.boolean().optional(),
3825
- validates: z2.enum(["body", "issue"]).optional(),
3826
- advisory: z2.literal(true).optional()
3827
- };
3828
- SafeRepoRelPath = z2.string().refine(isSafeRepoRelPath, {
3829
- message: "must be a repo-root-relative path with no `..` segment or absolute root"
3830
- });
3831
- KERNEL_CONFIG_REFINEMENTS = [];
3832
- });
3833
-
3834
6884
  // ../../harness/kernel/config/schema/process-config-section.ts
3835
6885
  function orderedShape(order, ...fragments) {
3836
6886
  const owners = new Map;
@@ -4143,16 +7193,16 @@ var init_ruling_ordinal = __esm(() => {
4143
7193
  });
4144
7194
 
4145
7195
  // ../../harness/processes/vinaya-strict/tools/task-contract/review-input-manifest.ts
4146
- import { createHash as createHash3 } from "node:crypto";
7196
+ import { createHash as createHash5 } from "node:crypto";
4147
7197
  function pauseBoundRulingDigest(rulingText) {
4148
- return createHash3("sha256").update(rulingText).digest("hex");
7198
+ return createHash5("sha256").update(rulingText).digest("hex");
4149
7199
  }
4150
7200
  function briefHash(brief) {
4151
- return createHash3("sha256").update(`${brief}
7201
+ return createHash5("sha256").update(`${brief}
4152
7202
  `).digest("hex");
4153
7203
  }
4154
7204
  function policyDigest(policy) {
4155
- return createHash3("sha256").update(JSON.stringify({
7205
+ return createHash5("sha256").update(JSON.stringify({
4156
7206
  codeReviewThreshold: policy.codeReviewThreshold,
4157
7207
  securityThreshold: policy.securityThreshold
4158
7208
  })).digest("hex");
@@ -4393,7 +7443,7 @@ var init_review_gate = __esm(() => {
4393
7443
 
4394
7444
  // ../../harness/processes/vinaya-strict/tools/prose-rules-config.ts
4395
7445
  import safeRegex from "safe-regex2";
4396
- import { z as z3 } from "zod";
7446
+ import { z as z4 } from "zod";
4397
7447
  function isPlainObject3(value) {
4398
7448
  return typeof value === "object" && value !== null && !Array.isArray(value);
4399
7449
  }
@@ -4663,18 +7713,18 @@ var init_prose_rules_config = __esm(() => {
4663
7713
  FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
4664
7714
  CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
4665
7715
  DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
4666
- RepoRelativePathSchema = z3.string().min(1).superRefine((entry, ctx) => {
7716
+ RepoRelativePathSchema = z4.string().min(1).superRefine((entry, ctx) => {
4667
7717
  const reason = outsideRepositoryReason(entry);
4668
7718
  if (reason)
4669
- ctx.addIssue({ code: z3.ZodIssueCode.custom, message: reason });
7719
+ ctx.addIssue({ code: z4.ZodIssueCode.custom, message: reason });
4670
7720
  });
4671
- ProseRulesSchema = z3.unknown().superRefine((value, ctx) => {
7721
+ ProseRulesSchema = z4.unknown().superRefine((value, ctx) => {
4672
7722
  for (const issue of proseRulesIssues(value)) {
4673
- 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 });
4674
7724
  }
4675
7725
  }).transform((value) => value);
4676
- PublishedProseSchema = z3.object({
4677
- allow: z3.array(z3.string().min(1)).optional()
7726
+ PublishedProseSchema = z4.object({
7727
+ allow: z4.array(z4.string().min(1)).optional()
4678
7728
  }).strict();
4679
7729
  });
4680
7730
 
@@ -4689,10 +7739,13 @@ var exports_vinaya_config_section = {};
4689
7739
  __export(exports_vinaya_config_section, {
4690
7740
  BRIEF_BUILTINS: () => BRIEF_BUILTINS,
4691
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,
4692
7744
  LOCAL_OVERRIDABLE_KEYS: () => LOCAL_OVERRIDABLE_KEYS,
4693
7745
  LOCAL_OVERRIDE_FILENAME: () => LOCAL_OVERRIDE_FILENAME,
4694
7746
  PRINCIPALS_FIX: () => PRINCIPALS_FIX,
4695
7747
  PrincipalsUnresolvedError: () => PrincipalsUnresolvedError,
7748
+ REVIEW_AGENT_SETTINGS: () => REVIEW_AGENT_SETTINGS,
4696
7749
  VINAYA_CHECK_ENTRY_FIELDS: () => VINAYA_CHECK_ENTRY_FIELDS,
4697
7750
  VINAYA_CONFIG_FILENAME: () => VINAYA_CONFIG_FILENAME,
4698
7751
  VINAYA_CONFIG_FRAGMENT: () => VINAYA_CONFIG_FRAGMENT,
@@ -4714,18 +7767,20 @@ __export(exports_vinaya_config_section, {
4714
7767
  resolveGateCutovers: () => resolveGateCutovers,
4715
7768
  resolveLocalPacingOverride: () => resolveLocalPacingOverride,
4716
7769
  resolveReleaseActor: () => resolveReleaseActor,
7770
+ resolveReviewAgent: () => resolveReviewAgent,
4717
7771
  resolveReviewPolicy: () => resolveReviewPolicy,
7772
+ resolveReviewRoundLimit: () => resolveReviewRoundLimit,
4718
7773
  resolveSecurityScanCommand: () => resolveSecurityScanCommand,
4719
7774
  tokensCollectTrustKey: () => tokensCollectTrustKey,
4720
7775
  trustAnchorFallbackWarning: () => trustAnchorFallbackWarning,
4721
7776
  trustTokensCollectCommand: () => trustTokensCollectCommand
4722
7777
  });
4723
- import { createHash as createHash4 } from "node:crypto";
4724
- import { execFileSync as execFileSync3 } from "node:child_process";
4725
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
4726
- import { homedir } from "node:os";
4727
- import { dirname as dirname2, join as join2 } from "node:path";
4728
- 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";
4729
7784
  function isDefaultedAgentVendorPath(path, manifest) {
4730
7785
  if (manifest.agents !== undefined)
4731
7786
  return false;
@@ -4759,7 +7814,7 @@ function decisionRecordsOutsideDoctrine(config, ctx) {
4759
7814
  return;
4760
7815
  const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
4761
7816
  if (issue)
4762
- ctx.addIssue({ code: z4.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
7817
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
4763
7818
  }
4764
7819
  function globalPrincipalsIgnoredWarning(path) {
4765
7820
  return `${path}: "principals" in the global config is ignored — principals may only be declared from a repo-local vinaya.config.json.`;
@@ -4863,6 +7918,12 @@ function resolveGateCutovers(config) {
4863
7918
  function resolveCollisionThreshold(config) {
4864
7919
  return config?.planning?.collisionThreshold ?? DEFAULT_COLLISION_THRESHOLD;
4865
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
+ }
4866
7927
  function principalsNotConfigured(why) {
4867
7928
  return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
4868
7929
  }
@@ -4877,7 +7938,7 @@ function createTrustedPrincipalsResolver(reads) {
4877
7938
  }
4878
7939
  if (isMissingFileError(err))
4879
7940
  throw principalsNotConfigured("the default branch has no vinaya.config.json");
4880
- 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 });
4881
7942
  }
4882
7943
  const unusable = { why: "" };
4883
7944
  const config = reads.parse(content, (why) => {
@@ -4897,23 +7958,23 @@ function trustAnchorFallbackWarning(why) {
4897
7958
  }
4898
7959
  function readTokensCollectTrustStore(storePath) {
4899
7960
  try {
4900
- if (!existsSync2(storePath))
7961
+ if (!existsSync6(storePath))
4901
7962
  return {};
4902
- const raw = JSON.parse(readFileSync2(storePath, "utf-8"));
7963
+ const raw = JSON.parse(readFileSync7(storePath, "utf-8"));
4903
7964
  return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
4904
7965
  } catch {
4905
7966
  return {};
4906
7967
  }
4907
7968
  }
4908
7969
  function writeTokensCollectTrustStore(storePath, store) {
4909
- const dir = dirname2(storePath);
4910
- if (!existsSync2(dir))
4911
- mkdirSync2(dir, { recursive: true });
4912
- 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");
4913
7974
  }
4914
7975
  function gitBlobHash(absolutePath, cwd) {
4915
7976
  try {
4916
- const raw = execFileSync3("git", ["hash-object", absolutePath], {
7977
+ const raw = execFileSync5("git", ["hash-object", absolutePath], {
4917
7978
  cwd,
4918
7979
  encoding: "utf-8",
4919
7980
  stdio: ["ignore", "pipe", "pipe"],
@@ -4925,7 +7986,7 @@ function gitBlobHash(absolutePath, cwd) {
4925
7986
  }
4926
7987
  }
4927
7988
  function tokensCollectTrustKey(repoGitCommonDir, interpreter, script) {
4928
- return createHash4("sha256").update(JSON.stringify([repoGitCommonDir, interpreter, script])).digest("hex");
7989
+ return createHash6("sha256").update(JSON.stringify([repoGitCommonDir, interpreter, script])).digest("hex");
4929
7990
  }
4930
7991
  function getTokensCollectTrust(repoGitCommonDir, interpreter, script, storePath = TOKENS_COLLECT_TRUST_PATH) {
4931
7992
  const key = tokensCollectTrustKey(repoGitCommonDir, interpreter, script);
@@ -4937,7 +7998,7 @@ function trustTokensCollectCommand(repoGitCommonDir, interpreter, script, script
4937
7998
  store[key] = { interpreter, script, scriptBlobHash, trustedAt: new Date().toISOString() };
4938
7999
  writeTokensCollectTrustStore(storePath, store);
4939
8000
  }
4940
- 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;
4941
8002
  var init_vinaya_config_section = __esm(() => {
4942
8003
  init_review_policy();
4943
8004
  init_issue_validation();
@@ -4948,13 +8009,13 @@ var init_vinaya_config_section = __esm(() => {
4948
8009
  init_config_loader();
4949
8010
  init_config_schema();
4950
8011
  init_prose_rules_config();
4951
- VINAYA_HOME = join2(homedir(), ".vinaya");
8012
+ VINAYA_HOME = join8(homedir5(), ".vinaya");
4952
8013
  CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
4953
8014
  VINAYA_CHECK_ENTRY_FIELDS = {
4954
- principalOwed: z4.literal(true).optional()
8015
+ principalOwed: z5.literal(true).optional()
4955
8016
  };
4956
- RoleEntrySchema = z4.object({
4957
- contract: z4.string().refine((p) => p.includes("/"), {
8017
+ RoleEntrySchema = z5.object({
8018
+ contract: z5.string().refine((p) => p.includes("/"), {
4958
8019
  message: 'must be a path (contain at least one "/"), not a bare filename'
4959
8020
  })
4960
8021
  });
@@ -4977,102 +8038,104 @@ var init_vinaya_config_section = __esm(() => {
4977
8038
  "briefSections",
4978
8039
  "milestoneShape"
4979
8040
  ];
4980
- BriefSectionSchema = z4.union([
4981
- z4.object({ builtin: z4.enum(BRIEF_BUILTINS) }),
4982
- z4.object({ heading: z4.string().min(1), name: z4.string().optional() }),
4983
- z4.object({ field: z4.string().min(1), name: z4.string().optional() }),
4984
- 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() })
4985
8046
  ]);
4986
- BriefSchemaSchema = z4.object({
4987
- pr: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
4988
- issue: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
4989
- milestone: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
4990
- 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()
4991
8052
  });
4992
- ProjectEntrySchema = z4.object({
4993
- name: z4.string().min(1),
4994
- description: z4.string().min(1).optional(),
4995
- 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()
4996
8057
  });
4997
8058
  VINAYA_CONFIG_FRAGMENT = {
4998
- roles: z4.record(z4.string(), RoleEntrySchema).optional(),
8059
+ roles: z5.record(z5.string(), RoleEntrySchema).optional(),
4999
8060
  briefSchema: BriefSchemaSchema.optional(),
5000
- principals: z4.array(z4.string()).min(1).optional(),
5001
- releaseActor: z4.string().min(1).optional(),
5002
- tokens: z4.object({
5003
- 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, {
5004
8065
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
5005
8066
  })
5006
8067
  }).optional(),
5007
- blastRadius: z4.object({ extraDomains: z4.array(z4.string()).optional() }).optional(),
5008
- proseGates: z4.object({
5009
- doctrineRoot: z4.string().min(1).optional(),
5010
- readerFacingPrefix: z4.string().min(1).optional(),
5011
- readerFacingSuffix: z4.string().min(1).optional(),
5012
- legacySlugDir: z4.string().min(1).optional(),
5013
- sourceComments: z4.object({
5014
- globs: z4.array(z4.string().min(1)).optional(),
5015
- allowlist: z4.array(z4.string().min(1)).optional(),
5016
- 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()
5017
8078
  }).optional(),
5018
- specGrandfather: z4.union([z4.array(z4.string().min(1)), z4.record(z4.string().min(1), z4.number().int().min(0))]).optional(),
5019
- specPaths: z4.array(RepoRelativePathSchema).optional(),
5020
- 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(),
5021
8082
  published: PublishedProseSchema.optional(),
5022
8083
  rules: ProseRulesSchema.optional()
5023
8084
  }).optional(),
5024
- projects: z4.array(ProjectEntrySchema).optional(),
5025
- dispatch: z4.object({
5026
- timeoutMs: z4.number().int().positive().optional(),
5027
- reviewerTimeoutMs: z4.number().int().positive().optional(),
5028
- killGraceMs: z4.number().int().positive().optional(),
5029
- 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()
5030
8091
  }).optional(),
5031
- reviewPolicy: z4.object({
5032
- codeReviewThreshold: z4.string().min(1).optional(),
5033
- securityThreshold: z4.string().min(1).optional(),
5034
- maxRounds: z4.number().optional(),
5035
- maxTaskMinutes: z4.number().optional(),
5036
- 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()
5037
8098
  }).optional(),
5038
- securityScan: z4.object({
5039
- command: z4.array(z4.string().min(1)).min(1)
8099
+ securityScan: z5.object({
8100
+ command: z5.array(z5.string().min(1)).min(1)
5040
8101
  }).optional(),
5041
- gateCutovers: z4.object({
5042
- objectivesSinceIssue: z4.number().int().nonnegative().optional(),
5043
- briefSectionsSinceIssue: z4.number().int().nonnegative().optional(),
5044
- documentationSinceIssue: z4.number().int().nonnegative().optional(),
5045
- briefRulesSincePr: z4.number().int().nonnegative().optional(),
5046
- 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()
5047
8108
  }).optional(),
5048
- planning: z4.object({
5049
- 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()
5050
8113
  }).optional(),
5051
- prePush: z4.object({
5052
- alwaysRun: z4.array(z4.string()).optional(),
5053
- readyTests: z4.object({
5054
- mode: z4.literal("ci"),
5055
- workflow: z4.literal(".github/workflows/ci.yml"),
5056
- 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")
5057
8120
  }).strict().optional(),
5058
- requiredCi: z4.object({
5059
- workflow: z4.literal(".github/workflows/ci.yml"),
5060
- check: z4.literal("Vinaya CI")
8121
+ requiredCi: z5.object({
8122
+ workflow: z5.literal(".github/workflows/ci.yml"),
8123
+ check: z5.literal("Vinaya CI")
5061
8124
  }).strict().optional()
5062
8125
  }).optional(),
5063
- report: z4.object({
5064
- commandTimeoutMs: z4.number().int().positive().optional()
8126
+ report: z5.object({
8127
+ commandTimeoutMs: z5.number().int().positive().optional()
5065
8128
  }).superRefine((report, ctx) => {
5066
8129
  const commandTimeoutMs = report.commandTimeoutMs;
5067
8130
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
5068
8131
  ctx.addIssue({
5069
- code: z4.ZodIssueCode.custom,
8132
+ code: z5.ZodIssueCode.custom,
5070
8133
  path: ["commandTimeoutMs"],
5071
8134
  message: "must be at most 3600000 (1 hour)"
5072
8135
  });
5073
8136
  }
5074
8137
  }).optional(),
5075
- decisionRecords: z4.object({
8138
+ decisionRecords: z5.object({
5076
8139
  path: RepoRelativePathSchema
5077
8140
  }).strict().optional()
5078
8141
  };
@@ -5081,15 +8144,16 @@ var init_vinaya_config_section = __esm(() => {
5081
8144
  "reviewPolicy.maxTaskMinutes",
5082
8145
  "reviewPolicy.readyPushTimeoutMinutes"
5083
8146
  ];
8147
+ REVIEW_AGENT_SETTINGS = ["same", "different"];
5084
8148
  PrincipalsUnresolvedError = class PrincipalsUnresolvedError extends Error {
5085
8149
  kind;
5086
- constructor(kind, message) {
5087
- super(message);
8150
+ constructor(kind, message, options) {
8151
+ super(message, options);
5088
8152
  this.name = "PrincipalsUnresolvedError";
5089
8153
  this.kind = kind;
5090
8154
  }
5091
8155
  };
5092
- TOKENS_COLLECT_TRUST_PATH = join2(VINAYA_HOME, "tokens-collect-trust.json");
8156
+ TOKENS_COLLECT_TRUST_PATH = join8(VINAYA_HOME, "tokens-collect-trust.json");
5093
8157
  VINAYA_GLOBAL_ONLY_KEYS = {
5094
8158
  roles: {
5095
8159
  key: "roles",
@@ -5128,7 +8192,7 @@ var init_vinaya_config_section = __esm(() => {
5128
8192
  });
5129
8193
 
5130
8194
  // ../../harness/processes/vinaya-strict/integration/config/compose.ts
5131
- import { z as z5 } from "zod";
8195
+ import { z as z6 } from "zod";
5132
8196
  function globalChecksIgnoredWarning(path) {
5133
8197
  return `${path}: "checks" registration in the global config is ignored — checks may only be registered from a repo-local vinaya.config.json.`;
5134
8198
  }
@@ -5200,7 +8264,7 @@ var init_compose = __esm(() => {
5200
8264
  "logs",
5201
8265
  "decisionRecords"
5202
8266
  ];
5203
- 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));
5204
8268
  VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
5205
8269
  for (const refine of KERNEL_CONFIG_REFINEMENTS)
5206
8270
  refine(config, ctx);
@@ -5251,7 +8315,7 @@ var init_compose = __esm(() => {
5251
8315
  vinayaConfigProvider = {
5252
8316
  homeDir: VINAYA_HOME,
5253
8317
  loadConfig: () => loadConfig(),
5254
- loadTrustAnchorConfig: () => loadTrustAnchorConfig(),
8318
+ loadTrustAnchorConfig: (options) => loadTrustAnchorConfig(undefined, options),
5255
8319
  loadTrustAnchorConfigAsync: (fetcher, options) => loadTrustAnchorConfigAsync(fetcher, options)
5256
8320
  };
5257
8321
  installVinayaConfigProvider();
@@ -5274,10 +8338,10 @@ function isEntryPoint(moduleUrl, scriptName, startedOn = process.argv[1]) {
5274
8338
 
5275
8339
  // ../../harness/processes/vinaya-strict/checks/bin/check-dispatch-readiness.ts
5276
8340
  init_issue_validation();
5277
- import { execFile as execFile5, execFileSync as execFileSync6 } from "node:child_process";
5278
- import { existsSync as existsSync4, readFileSync as readFileSync5, realpathSync as realpathSync4 } from "node:fs";
5279
- import { sep as sep3 } from "node:path";
5280
- 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";
5281
8345
 
5282
8346
  // ../../node_modules/universal-user-agent/index.js
5283
8347
  function getUserAgent() {
@@ -5685,8 +8749,8 @@ function isPlainObject2(value) {
5685
8749
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
5686
8750
  }
5687
8751
  async function fetchWrapper(requestOptions) {
5688
- const fetch = requestOptions.request?.fetch || globalThis.fetch;
5689
- if (!fetch) {
8752
+ const fetch2 = requestOptions.request?.fetch || globalThis.fetch;
8753
+ if (!fetch2) {
5690
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");
5691
8755
  }
5692
8756
  const log = requestOptions.request?.log || console;
@@ -5698,7 +8762,7 @@ async function fetchWrapper(requestOptions) {
5698
8762
  ]));
5699
8763
  let fetchResponse;
5700
8764
  try {
5701
- fetchResponse = await fetch(requestOptions.url, {
8765
+ fetchResponse = await fetch2(requestOptions.url, {
5702
8766
  method: requestOptions.method,
5703
8767
  body,
5704
8768
  redirect: requestOptions.request?.redirect,
@@ -5926,10 +8990,23 @@ var graphql2 = withDefaults3(request, {
5926
8990
 
5927
8991
  // ../../harness/processes/vinaya-strict/tools/task-contract/forge/fetch-open-issues.ts
5928
8992
  init_labels();
5929
- 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) {
5930
9007
  const result = new Map;
5931
9008
  if (slugs.length === 0)
5932
- return result;
9009
+ return { ok: true, issues: result };
5933
9010
  const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
5934
9011
  const toAlias = (slug) => `tranche_${slug.replace(/-/g, "_")}`;
5935
9012
  const perSlug = slugs.map((slug) => `
@@ -5943,11 +9020,12 @@ async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
5943
9020
  let response;
5944
9021
  try {
5945
9022
  response = await client(query, { owner, repo });
5946
- } catch {
5947
- 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` };
5948
9028
  }
5949
- if (!response.repository)
5950
- return result;
5951
9029
  for (const slug of slugs) {
5952
9030
  const conn = response.repository[toAlias(slug)];
5953
9031
  const issues = (conn?.nodes ?? []).map((n) => ({
@@ -5957,7 +9035,7 @@ async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
5957
9035
  }));
5958
9036
  result.set(slug, issues);
5959
9037
  }
5960
- return result;
9038
+ return { ok: true, issues: result };
5961
9039
  }
5962
9040
 
5963
9041
  // ../../harness/processes/vinaya-strict/tools/task-contract/task-branch-identity.ts
@@ -5983,6 +9061,9 @@ function siblingsSharingConflictEdge(subject, siblings) {
5983
9061
  function isHandClosedByRecognizedPrincipal(dep, principalAllowlist) {
5984
9062
  return dep.issueState === "closed" && dep.stateReason === "completed" && isPrincipal(dep.closedByActor ?? null, principalAllowlist);
5985
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
+ }
5986
9067
  function isSelfDependency(dep, task, issue) {
5987
9068
  if (dep.issue !== null && issue !== null && dep.issue === issue.number)
5988
9069
  return true;
@@ -5999,6 +9080,8 @@ function checkDispatchReadiness(input) {
5999
9080
  };
6000
9081
  if (task.issue === null) {
6001
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));
6002
9085
  } else if (input.issue === null) {
6003
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).`);
6004
9087
  }
@@ -6039,11 +9122,61 @@ function checkDispatchReadiness(input) {
6039
9122
  return { ready: blockerDetails.length === 0, blockers: blockerDetails.map((b) => b.message), blockerDetails };
6040
9123
  }
6041
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
+
6042
9175
  // ../../harness/kernel/adapters/code-host/github/github-token.ts
6043
- import { execFile as execFile2 } from "node:child_process";
6044
- import { promisify as promisify2 } from "node:util";
6045
- var execFileAsync2 = promisify2(execFile2);
6046
- 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 = {
6047
9180
  ...process.env,
6048
9181
  PATH: [process.env.PATH, "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].filter(Boolean).join(":")
6049
9182
  };
@@ -6055,7 +9188,7 @@ async function resolveGithubToken(explicit) {
6055
9188
  if (process.env.GH_TOKEN)
6056
9189
  return process.env.GH_TOKEN;
6057
9190
  try {
6058
- const { stdout } = await execFileAsync2("gh", ["auth", "token"], { env: systemEnv2, timeout: 5000 });
9191
+ const { stdout } = await execFileAsync4("gh", ["auth", "token"], { env: systemEnv3, timeout: 5000 });
6059
9192
  const token = stdout.trim();
6060
9193
  return token.length > 0 ? token : null;
6061
9194
  } catch {
@@ -6333,6 +9466,19 @@ function lifecycleFromIssues(issues) {
6333
9466
  return "planned";
6334
9467
  return issues.some((i) => i.state === "OPEN") ? "active" : "complete";
6335
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;
6336
9482
  function goalFromMilestones(milestones, slug) {
6337
9483
  for (const m of milestones) {
6338
9484
  const goal = intentGoalForSlug(m.description ?? "", slug);
@@ -6359,11 +9505,21 @@ function trancheSlugsFromLabels(labels) {
6359
9505
  return slugs;
6360
9506
  }
6361
9507
  async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
6362
- const read = (fetch) => options.retryFailedReads ? retryOnce(fetch) : fetch();
6363
- const [milestones, labels] = await Promise.all([
9508
+ const read = (fetch2) => options.retryFailedReads ? retryOnce(fetch2) : fetch2();
9509
+ const [milestones, labels, counts] = await Promise.all([
6364
9510
  read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`)),
6365
- 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))
6366
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
+ };
6367
9523
  const active = [];
6368
9524
  const archived = [];
6369
9525
  const facts = new Map;
@@ -6371,33 +9527,21 @@ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
6371
9527
  const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
6372
9528
  const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
6373
9529
  const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
6374
- const uniqueLegacySlugs = [...legacySlugs];
6375
- const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
6376
- Promise.all(uniqueLegacySlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))),
6377
- Promise.all(uniqueNewPathSlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))))
6378
- ]);
6379
- const issuesBySlug = new Map;
6380
- uniqueLegacySlugs.forEach((slug, i) => {
6381
- issuesBySlug.set(slug, legacyIssuesBySlug[i] ?? []);
6382
- });
6383
- uniqueNewPathSlugs.forEach((slug, i) => {
6384
- issuesBySlug.set(slug, newPathIssuesBySlug[i] ?? []);
6385
- });
6386
- uniqueLegacySlugs.forEach((slug, i) => {
9530
+ for (const slug of legacySlugs) {
6387
9531
  const m = legacyMilestoneBySlug.get(slug);
6388
9532
  if (!m)
6389
- return;
9533
+ continue;
6390
9534
  const ref = { slug, goal: m.description ?? "" };
6391
- const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
9535
+ const c = countsByLabel.get(trancheLabel(slug));
9536
+ const f = resolveLegacyFactsFromCounts(m, c?.open ?? 0, c?.total ?? 0);
6392
9537
  if (f.lifecycle === "complete")
6393
9538
  archived.push(ref);
6394
9539
  else if (f.lifecycle === "active")
6395
9540
  active.push(ref);
6396
9541
  facts.set(slug, f);
6397
- });
6398
- uniqueNewPathSlugs.forEach((slug, i) => {
6399
- const issues = newPathIssuesBySlug[i] ?? [];
6400
- const lifecycle = lifecycleFromIssues(issues);
9542
+ }
9543
+ for (const slug of uniqueNewPathSlugs) {
9544
+ const lifecycle = lifecycleOf(slug);
6401
9545
  const goal = goalFromMilestones(milestones, slug);
6402
9546
  const f = { goal, lifecycle };
6403
9547
  facts.set(slug, f);
@@ -6405,14 +9549,23 @@ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
6405
9549
  active.push({ slug, goal });
6406
9550
  else if (lifecycle === "complete")
6407
9551
  archived.push({ slug, goal });
6408
- });
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
+ }
6409
9562
  return { active, archived, facts, legacySlugs, issuesBySlug };
6410
9563
  }
6411
- async function retryOnce(fetch) {
9564
+ async function retryOnce(fetch2) {
6412
9565
  try {
6413
- return await fetch();
9566
+ return await fetch2();
6414
9567
  } catch {
6415
- return fetch();
9568
+ return fetch2();
6416
9569
  }
6417
9570
  }
6418
9571
  async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
@@ -6527,8 +9680,8 @@ function createForgeSource(config) {
6527
9680
  init_compose();
6528
9681
 
6529
9682
  // ../../harness/kernel/adapters/code-host/github/forge-snapshot.ts
6530
- import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
6531
- 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";
6532
9685
 
6533
9686
  // ../../harness/kernel/adapters/code-host/github/extract-issue.ts
6534
9687
  init_anchored_region();
@@ -6557,10 +9710,10 @@ function headerRegion2(prBody) {
6557
9710
  return m?.index !== undefined ? prBody.slice(0, m.index) : prBody;
6558
9711
  }
6559
9712
  // ../../harness/kernel/adapters/code-host/github/forge-read.ts
6560
- import { execFileSync as execFileSync4 } from "node:child_process";
9713
+ import { execFileSync as execFileSync6 } from "node:child_process";
6561
9714
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
6562
9715
  var PAGE_SIZE = 100;
6563
- 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 });
6564
9717
 
6565
9718
  class ForgeReadOversizeError extends Error {
6566
9719
  subject;
@@ -6667,7 +9820,7 @@ class ForgeSnapshotIssueNotFoundError extends Error {
6667
9820
  function readSnapshotFile(dir, file) {
6668
9821
  let text;
6669
9822
  try {
6670
- text = readFileSync3(join3(dir, file), "utf8");
9823
+ text = readFileSync8(join9(dir, file), "utf8");
6671
9824
  } catch {
6672
9825
  throw new ForgeSnapshotIncompleteError(dir, file);
6673
9826
  }
@@ -6718,12 +9871,12 @@ function incompleteForgeSnapshot(env = process.env) {
6718
9871
  if (dir === null)
6719
9872
  return null;
6720
9873
  for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
6721
- if (!existsSync3(join3(dir, file)))
9874
+ if (!existsSync7(join9(dir, file)))
6722
9875
  return new ForgeSnapshotIncompleteError(dir, file).message;
6723
9876
  }
6724
9877
  try {
6725
9878
  const issue = readSnapshotFile(dir, ISSUE_FILE);
6726
- 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))) {
6727
9880
  return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
6728
9881
  }
6729
9882
  } catch (err) {
@@ -6747,21 +9900,21 @@ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
6747
9900
 
6748
9901
  // ../../harness/kernel/gates/ops.ts
6749
9902
  init_config_schema();
6750
- 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";
6751
9904
  function containedAbs(repoRoot, relPath) {
6752
- const root = resolve2(repoRoot);
6753
- const target = resolve2(root, relPath);
9905
+ const root = resolve3(repoRoot);
9906
+ const target = resolve3(root, relPath);
6754
9907
  if (target === root)
6755
9908
  return null;
6756
- return target === root || target.startsWith(root + sep) ? target : null;
9909
+ return target === root || target.startsWith(root + sep2) ? target : null;
6757
9910
  }
6758
9911
 
6759
9912
  // ../../harness/processes/vinaya-strict/tools/edge-resolve.ts
6760
- import { execFile as execFile4 } from "node:child_process";
6761
- import { promisify as promisify4 } from "node:util";
9913
+ import { execFile as execFile6 } from "node:child_process";
9914
+ import { promisify as promisify6 } from "node:util";
6762
9915
 
6763
9916
  // ../../harness/kernel/adapters/code-host/github/github-rate-limit.ts
6764
- import { execFileSync as execFileSync5 } from "node:child_process";
9917
+ import { execFileSync as execFileSync7 } from "node:child_process";
6765
9918
  var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
6766
9919
  var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
6767
9920
  function isGithubRateLimitError(text) {
@@ -6770,7 +9923,7 @@ function isGithubRateLimitError(text) {
6770
9923
  function rateLimitBudget(errorText) {
6771
9924
  return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
6772
9925
  }
6773
- 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"] });
6774
9927
  function readRateLimitReset(budget, read = defaultReader) {
6775
9928
  let parsed;
6776
9929
  try {
@@ -6810,8 +9963,8 @@ ${message}` : message;
6810
9963
  init_parse_rationale_deps();
6811
9964
  var DIRECT_ISSUE_REF = /#(\d+)/;
6812
9965
  var issueCache = new Map;
6813
- var execFileAsync4 = promisify4(execFile4);
6814
- 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;
6815
9968
  function fetchIssueState(num, repo) {
6816
9969
  const key = `${repo.owner}/${repo.repo}#${num}`;
6817
9970
  const cached = issueCache.get(key);
@@ -6823,7 +9976,7 @@ function fetchIssueState(num, repo) {
6823
9976
  }
6824
9977
  async function readIssueOnce(num, repo) {
6825
9978
  try {
6826
- const { stdout } = await execFileAsync4("gh", [
9979
+ const { stdout } = await execFileAsync6("gh", [
6827
9980
  "issue",
6828
9981
  "view",
6829
9982
  String(num),
@@ -6834,7 +9987,7 @@ async function readIssueOnce(num, repo) {
6834
9987
  ], { encoding: "utf8" });
6835
9988
  return { json: JSON.parse(stdout), readFailed: false };
6836
9989
  } catch (err) {
6837
- return { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
9990
+ return { json: null, readFailed: !ISSUE_NOT_FOUND2.test(execErrorText(err)) };
6838
9991
  }
6839
9992
  }
6840
9993
  var defaultResolveSiblingTranche = async (slug, repo) => {
@@ -6962,8 +10115,8 @@ async function resolveSiblingConflictFacts(subject, openIssues, alreadyResolved,
6962
10115
 
6963
10116
  // ../../harness/processes/vinaya-strict/tools/premise-reassert-logic.ts
6964
10117
  init_premise_check();
6965
- import { readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
6966
- 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";
6967
10120
  var CHECK_NAME = "pr-premise-reassert";
6968
10121
  function reassertPremiseFile(checkName, premiseFilePath, body, fileReader) {
6969
10122
  if (body === null) {
@@ -7017,9 +10170,9 @@ function containedRealPath(root, p) {
7017
10170
  if (abs === null)
7018
10171
  return null;
7019
10172
  try {
7020
- const real = realpathSync3(abs);
7021
- const realRoot = realpathSync3(root);
7022
- 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;
7023
10176
  } catch {
7024
10177
  return null;
7025
10178
  }
@@ -7029,7 +10182,7 @@ function defaultFileReader(p) {
7029
10182
  if (real === null)
7030
10183
  return null;
7031
10184
  try {
7032
- return readFileSync4(real, "utf8");
10185
+ return readFileSync9(real, "utf8");
7033
10186
  } catch {
7034
10187
  return null;
7035
10188
  }
@@ -7069,15 +10222,15 @@ function warnOnUnreadPrincipals(check, err) {
7069
10222
 
7070
10223
  // ../../harness/processes/vinaya-strict/checks/bin/check-dispatch-readiness.ts
7071
10224
  var CHECK_NAME2 = "dispatch-readiness";
7072
- var execFileAsync5 = promisify5(execFile5);
10225
+ var execFileAsync7 = promisify7(execFile7);
7073
10226
  function git(args) {
7074
10227
  try {
7075
- return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
10228
+ return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
7076
10229
  } catch {
7077
10230
  return "";
7078
10231
  }
7079
10232
  }
7080
- function resolveRepo() {
10233
+ function resolveRepo2() {
7081
10234
  const fromEnv = process.env.VINAYA_REPO;
7082
10235
  if (fromEnv) {
7083
10236
  const m = fromEnv.match(/^([^/]+)\/(.+)$/);
@@ -7099,7 +10252,7 @@ async function resolveToken() {
7099
10252
  if (process.env.GH_TOKEN)
7100
10253
  return process.env.GH_TOKEN;
7101
10254
  try {
7102
- const { stdout } = await execFileAsync5("gh", ["auth", "token"]);
10255
+ const { stdout } = await execFileAsync7("gh", ["auth", "token"]);
7103
10256
  const token = stdout.trim();
7104
10257
  return token.length > 0 ? token : null;
7105
10258
  } catch {
@@ -7123,13 +10276,13 @@ function checkPremiseReassertion() {
7123
10276
  const premiseFile = process.env.PREMISE_FILE;
7124
10277
  if (!premiseFile)
7125
10278
  return true;
7126
- const body = existsSync4(premiseFile) ? readFileSync5(premiseFile, "utf8") : null;
10279
+ const body = existsSync8(premiseFile) ? readFileSync10(premiseFile, "utf8") : null;
7127
10280
  const result = reassertPremiseFile(CHECK_NAME2, premiseFile, body, (p) => {
7128
10281
  const real = containedRealPath2(process.cwd(), p);
7129
10282
  if (real === null)
7130
10283
  return null;
7131
10284
  try {
7132
- return readFileSync5(real, "utf8");
10285
+ return readFileSync10(real, "utf8");
7133
10286
  } catch {
7134
10287
  return null;
7135
10288
  }
@@ -7143,9 +10296,9 @@ function containedRealPath2(root, p) {
7143
10296
  if (abs === null)
7144
10297
  return null;
7145
10298
  try {
7146
- const real = realpathSync4(abs);
7147
- const realRoot = realpathSync4(root);
7148
- 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;
7149
10302
  } catch {
7150
10303
  return null;
7151
10304
  }
@@ -7155,20 +10308,21 @@ function fetchIssueJson(issueNumber) {
7155
10308
  const fromSnapshot = snapshotIssue(issueNumber);
7156
10309
  if (fromSnapshot !== null) {
7157
10310
  return {
7158
- number: fromSnapshot.number,
7159
- state: fromSnapshot.state,
7160
- body: fromSnapshot.body,
7161
- 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
+ }
7162
10318
  };
7163
10319
  }
7164
- const out = execFileSync6("gh", ["issue", "view", String(issueNumber), "--json", "number,state,body,labels"], {
7165
- encoding: "utf8",
7166
- stdio: ["ignore", "pipe", "pipe"]
7167
- });
7168
- return JSON.parse(out);
7169
- } catch {
7170
- 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) };
7171
10324
  }
10325
+ return readTaskIssue(["issue", "view", String(issueNumber), "--json", "number,state,body,labels"]);
7172
10326
  }
7173
10327
  function resolveGatePrincipals() {
7174
10328
  try {
@@ -7215,14 +10369,18 @@ function exitWithGateVerdict(input, archival = { infraFailure: null }) {
7215
10369
  process.exit(ready ? 0 : 1);
7216
10370
  }
7217
10371
  async function runIssueMode(issueNumber) {
7218
- const issueJson = fetchIssueJson(issueNumber);
7219
- 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") {
7220
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`.");
7221
10378
  }
10379
+ const issueJson = issueRead.issue;
7222
10380
  if (issueJson.labels.some((l) => l.name.startsWith("vinaya/tranche:"))) {
7223
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.");
7224
10382
  }
7225
- const repo = resolveRepo();
10383
+ const repo = resolveRepo2();
7226
10384
  if (!repo) {
7227
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`.");
7228
10386
  }
@@ -7259,7 +10417,7 @@ async function runIssueMode(issueNumber) {
7259
10417
  });
7260
10418
  }
7261
10419
  async function runTrancheMode(trancheSlug, taskId) {
7262
- const repo = resolveRepo();
10420
+ const repo = resolveRepo2();
7263
10421
  if (!repo) {
7264
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`.");
7265
10423
  }
@@ -7359,6 +10517,8 @@ function recoveryPromptFor(blockerClass) {
7359
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.";
7360
10518
  case "issue-existence":
7361
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).";
7362
10522
  case "rationale":
7363
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`.";
7364
10524
  case "depends-on-unresolvable":