@lsctech/polaris 0.5.7 → 0.5.9

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 (36) hide show
  1. package/dist/autoresearch/index.js +30 -1
  2. package/dist/autoresearch/sol-evaluation-writer.js +135 -0
  3. package/dist/autoresearch/sol-evidence-normalizer.js +337 -0
  4. package/dist/autoresearch/sol-recommendations.js +130 -0
  5. package/dist/autoresearch/sol-report-renderer.js +282 -0
  6. package/dist/autoresearch/sol-run-health-bridge.js +246 -0
  7. package/dist/autoresearch/sol-scorecard-calculator.js +865 -0
  8. package/dist/cli/autoresearch.js +77 -0
  9. package/dist/cli/medic.js +65 -0
  10. package/dist/cluster-state/store.js +56 -0
  11. package/dist/config/defaults.js +3 -0
  12. package/dist/config/validator.js +141 -0
  13. package/dist/finalize/artifact-policy.js +2 -0
  14. package/dist/finalize/github.js +13 -9
  15. package/dist/finalize/index.js +231 -5
  16. package/dist/finalize/linear.js +8 -4
  17. package/dist/finalize/medic-gate.js +42 -0
  18. package/dist/finalize/steps/08-create-pr.js +2 -2
  19. package/dist/finalize/steps/11-update-linear.js +2 -2
  20. package/dist/loop/parent.js +234 -28
  21. package/dist/loop/worker-packet.js +19 -1
  22. package/dist/medic/run-health-consult.js +381 -0
  23. package/dist/medic/treatment-packets.js +169 -0
  24. package/dist/qc/artifacts.js +27 -0
  25. package/dist/qc/orchestration.js +3 -2
  26. package/dist/qc/providers/coderabbit.js +114 -11
  27. package/dist/qc/repair-loop.js +49 -14
  28. package/dist/qc/runner.js +10 -2
  29. package/dist/qc/schemas.js +1 -0
  30. package/dist/run-health/foreman-symptoms.js +100 -0
  31. package/dist/run-health/index.js +301 -0
  32. package/dist/run-health/qc-escalation.js +155 -0
  33. package/dist/run-health/schema.js +123 -0
  34. package/dist/types/sol-metrics.js +108 -0
  35. package/dist/types/sol-scorecard.js +148 -0
  36. package/package.json +1 -1
@@ -1,5 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateStateFileAuthority = validateStateFileAuthority;
4
+ exports.validateQcRepairLoopGate = validateQcRepairLoopGate;
5
+ exports.warnOnMissingQcArtifacts = warnOnMissingQcArtifacts;
6
+ exports.validateAuthoritativeChildState = validateAuthoritativeChildState;
3
7
  exports.runFinalize = runFinalize;
4
8
  exports.createFinalizeCommand = createFinalizeCommand;
5
9
  const commander_1 = require("commander");
@@ -12,6 +16,7 @@ const checkpoint_js_1 = require("../loop/checkpoint.js");
12
16
  const artifact_policy_js_1 = require("./artifact-policy.js");
13
17
  const git_custody_js_1 = require("../loop/git-custody.js");
14
18
  const store_js_1 = require("../cluster-state/store.js");
19
+ const artifacts_js_1 = require("../qc/artifacts.js");
15
20
  const canon_check_js_1 = require("../smartdocs-engine/canon-check.js");
16
21
  const _01_map_update_js_1 = require("./steps/01-map-update.js");
17
22
  const _02_map_validate_js_1 = require("./steps/02-map-validate.js");
@@ -29,6 +34,7 @@ const local_graph_js_1 = require("../tracker/local-graph.js");
29
34
  const index_js_1 = require("../tracker/sync/index.js");
30
35
  const finalize_evidence_js_1 = require("../loop/finalize-evidence.js");
31
36
  const delivery_integrity_js_1 = require("./delivery-integrity.js");
37
+ const medic_gate_js_1 = require("./medic-gate.js");
32
38
  const index_js_2 = require("../qc/index.js");
33
39
  function getBranch(repoRoot) {
34
40
  try {
@@ -85,6 +91,60 @@ function validateStateBranchMatchesGitBranch(stateBranch, branch) {
85
91
  process.exit(1);
86
92
  }
87
93
  }
94
+ const CLUSTER_STATE_FILE_PATTERN = /[\\/]\.polaris[\\/]clusters[\\/][^\\/]+[\\/]state\.json$/;
95
+ function isClusterStateSnapshotFile(filePath) {
96
+ return CLUSTER_STATE_FILE_PATTERN.test(filePath.replace(/\\/g, "/"));
97
+ }
98
+ function computeRunStateFreshness(state) {
99
+ const s = state;
100
+ let score = 0;
101
+ score += (s.completed_children?.length ?? 0) * 10;
102
+ if (s.status === "complete")
103
+ score += 50;
104
+ if (s.pr_url)
105
+ score += 30;
106
+ if (s.qc_repair_loop?.terminal_outcome)
107
+ score += 40;
108
+ score += (s.dispatch_boundary?.dispatch_epoch ?? 0) * 5;
109
+ score += (s.context_budget?.children_completed ?? 0) * 2;
110
+ return score;
111
+ }
112
+ /**
113
+ * Refuse to use a promoted cluster state snapshot when the authoritative
114
+ * taskchain current-state.json is newer. Cluster snapshots under
115
+ * `.polaris/clusters/<id>/state.json` are secondary; the taskchain state
116
+ * owned by the parent loop is authoritative.
117
+ */
118
+ function validateStateFileAuthority(stateFile, state, repoRoot) {
119
+ if (!isClusterStateSnapshotFile(stateFile)) {
120
+ return;
121
+ }
122
+ const taskchainStateFile = (0, node_path_1.join)(repoRoot, ".taskchain_artifacts", "polaris-run", "current-state.json");
123
+ if (!(0, node_fs_1.existsSync)(taskchainStateFile)) {
124
+ return;
125
+ }
126
+ let taskchainState;
127
+ try {
128
+ taskchainState = (0, checkpoint_js_1.readState)(taskchainStateFile);
129
+ }
130
+ catch {
131
+ return;
132
+ }
133
+ if (taskchainState.run_id !== state.run_id ||
134
+ taskchainState.cluster_id !== state.cluster_id) {
135
+ return;
136
+ }
137
+ const taskchainFreshness = computeRunStateFreshness(taskchainState);
138
+ const snapshotFreshness = computeRunStateFreshness(state);
139
+ if (taskchainFreshness > snapshotFreshness) {
140
+ process.stderr.write(`finalize aborted: cluster state snapshot is stale.\n` +
141
+ ` Snapshot: ${stateFile}\n` +
142
+ ` Authoritative taskchain state: ${taskchainStateFile}\n` +
143
+ `The taskchain current-state.json is newer; use it instead, or ` +
144
+ `update the cluster snapshot before finalizing.\n`);
145
+ process.exit(1);
146
+ }
147
+ }
88
148
  /**
89
149
  * Check that the Closeout Librarian has run and its result passes the gate.
90
150
  * Returns null if finalize may proceed; returns a human-readable blocker string if not.
@@ -183,8 +243,106 @@ function resolveQcTelemetryFile(state, repoRoot) {
183
243
  const artifactDir = state.artifact_dir ?? (0, node_path_1.join)(repoRoot, ".taskchain_artifacts", "polaris-run");
184
244
  return (0, node_path_1.join)(artifactDir, "runs", state.run_id, "telemetry.jsonl");
185
245
  }
246
+ // ── QC repair-loop terminal state gate ────────────────────────────────────────
247
+ /**
248
+ * Trusted QC repair-loop terminal outcomes that allow finalize to proceed.
249
+ * "pass" = QC rerun passed; "qc-disabled" = QC was off; "no-repairable" = no
250
+ * findings routable to repair workers (follow-up-only or already resolved).
251
+ */
252
+ const TRUSTED_QC_REPAIR_OUTCOMES = new Set(["pass", "qc-disabled", "no-repairable"]);
253
+ /**
254
+ * Validate QC repair-loop terminal state when QC is enabled and repair routing
255
+ * is active. Returns null when finalize may proceed; returns a human-readable
256
+ * blocker string otherwise.
257
+ */
258
+ function validateQcRepairLoopGate(state, config) {
259
+ // Gate only applies when QC is enabled
260
+ if (!config.enabled)
261
+ return null;
262
+ // Gate only applies when repair routing is active (not "log" or "block")
263
+ const repairRouting = config.repairRouting ?? "route";
264
+ if (repairRouting !== "route" && repairRouting !== "follow-up")
265
+ return null;
266
+ const repairLoop = state.qc_repair_loop;
267
+ // No repair-loop state at all — the completed-cluster QC trigger ran but
268
+ // never entered the repair loop. This is a gap: finalize should not proceed.
269
+ if (!repairLoop) {
270
+ return ("QC is enabled with repair routing active, but no qc_repair_loop state " +
271
+ "was found in the run state. The parent loop must run the QC repair loop " +
272
+ "before finalize can proceed.");
273
+ }
274
+ const outcome = repairLoop.terminal_outcome;
275
+ if (outcome === null || outcome === undefined) {
276
+ return ("QC repair loop is still in-flight (terminal_outcome is null). " +
277
+ "Finalize cannot proceed until the repair loop reaches a terminal state.");
278
+ }
279
+ if (TRUSTED_QC_REPAIR_OUTCOMES.has(outcome))
280
+ return null;
281
+ return (`QC repair loop terminated with untrusted outcome: "${outcome}". ` +
282
+ `Only ${Array.from(TRUSTED_QC_REPAIR_OUTCOMES).join(", ")} outcomes allow finalize to proceed. ` +
283
+ `Resolve the repair loop before re-running finalize.`);
284
+ }
285
+ // ── Authoritative completed-child state cross-check ───────────────────────────
286
+ function warnOnMissingQcArtifacts(clusterState, repoRoot) {
287
+ if (!clusterState)
288
+ return;
289
+ const validation = (0, artifacts_js_1.validateQcArtifactPointers)(clusterState.qc_runs);
290
+ if (validation.ok)
291
+ return;
292
+ for (const missing of validation.missing) {
293
+ console.warn(`finalize warning: cluster-state QC pointer references missing artifact: ${missing}`);
294
+ }
295
+ for (const unavailable of validation.unavailable) {
296
+ console.warn(`finalize warning: QC audit artifact unavailable: ${unavailable}`);
297
+ }
298
+ }
299
+ /**
300
+ * Cross-check completed children in the loop state against the cluster-state
301
+ * child_states. Returns a diagnostic result — when `ok` is false, finalize
302
+ * should refuse PR creation.
303
+ */
304
+ function validateAuthoritativeChildState(state, repoRoot) {
305
+ const clusterState = (0, store_js_1.readClusterStateSync)(state.cluster_id, repoRoot);
306
+ const stateCount = state.completed_children.length;
307
+ // No cluster state available — backward-compat: trust the loop state.
308
+ if (!clusterState) {
309
+ return { ok: true, authoritativeCount: stateCount, stateCount };
310
+ }
311
+ const childStates = clusterState.child_states;
312
+ // No child_states array in cluster state — backward-compat: trust the loop state.
313
+ // This covers legacy cluster-state files that don't track individual child lifecycle.
314
+ if (!childStates || childStates.length === 0) {
315
+ return { ok: true, authoritativeCount: stateCount, stateCount };
316
+ }
317
+ const doneChildren = childStates.filter((c) => c.status === "done" || c.status === "reviewed" || c.status === "finalized");
318
+ const authoritativeCount = doneChildren.length;
319
+ // When cluster-state has tracked children but zero are done while loop state
320
+ // claims completions, the cluster state file is stale or was never updated.
321
+ if (authoritativeCount === 0 && stateCount > 0) {
322
+ return {
323
+ ok: false,
324
+ authoritativeCount,
325
+ stateCount,
326
+ reason: `Stale cluster state: cluster-state.json has 0 done children but ` +
327
+ `loop state claims ${stateCount} completed. ` +
328
+ `The cluster state file was never updated by worker completions.`,
329
+ };
330
+ }
331
+ // Significant mismatch: cluster-state has fewer done children than loop state
332
+ if (authoritativeCount < stateCount) {
333
+ return {
334
+ ok: false,
335
+ authoritativeCount,
336
+ stateCount,
337
+ reason: `Completed-child count mismatch: cluster-state has ${authoritativeCount} done ` +
338
+ `children but loop state has ${stateCount}. ` +
339
+ `The cluster state may be stale or child completions were not recorded properly.`,
340
+ };
341
+ }
342
+ return { ok: true, authoritativeCount, stateCount };
343
+ }
186
344
  async function runQcGate(options) {
187
- const { config, state, repoRoot, branch, trigger, prUrl, stepLabel } = options;
345
+ const { config, state, repoRoot, branch, baseRef, trigger, prUrl, stepLabel } = options;
188
346
  const registry = (0, index_js_2.createQcRegistry)(config);
189
347
  const result = await (0, index_js_2.runQcAtTrigger)({
190
348
  config,
@@ -195,6 +353,7 @@ async function runQcGate(options) {
195
353
  runId: state.run_id,
196
354
  clusterId: state.cluster_id,
197
355
  branch,
356
+ baseRef,
198
357
  telemetryFile: resolveQcTelemetryFile(state, repoRoot),
199
358
  state,
200
359
  });
@@ -210,7 +369,7 @@ async function runQcGate(options) {
210
369
  process.exit(1);
211
370
  }
212
371
  async function runFinalize(options) {
213
- const { repoRoot, stateFile, dryRun, skipDelivery, skipLibrarian } = options;
372
+ const { repoRoot, stateFile, dryRun, skipDelivery, skipLibrarian, bypassMedicReason } = options;
214
373
  const config = (0, loader_js_1.loadConfig)(repoRoot);
215
374
  // Step 1: polaris map update --changed
216
375
  console.log("[1/14] Updating map..."); // Step count updated
@@ -236,6 +395,7 @@ async function runFinalize(options) {
236
395
  validateStateFilePath(stateFile);
237
396
  validateClusterIdMatchesBranch(state.cluster_id, branch);
238
397
  validateStateBranchMatchesGitBranch(state.branch, branch);
398
+ validateStateFileAuthority(stateFile, state, repoRoot);
239
399
  // Step 4: Run configured checks
240
400
  const checks = config.finalize?.runChecks ?? [];
241
401
  if (checks.length > 0) {
@@ -322,6 +482,7 @@ async function runFinalize(options) {
322
482
  // loop.allowBranchDivergence is true (direct-main mode).
323
483
  {
324
484
  const clusterState = (0, store_js_1.readClusterStateSync)(state.cluster_id, repoRoot);
485
+ warnOnMissingQcArtifacts(clusterState, repoRoot);
325
486
  const baseBranch = clusterState?.base_branch;
326
487
  const deliveryBranch = clusterState?.delivery_branch;
327
488
  const directMainMode = config.loop?.allowBranchDivergence === true;
@@ -389,14 +550,60 @@ async function runFinalize(options) {
389
550
  }
390
551
  // Step 5.8: Completed-cluster QC trigger (when configured)
391
552
  // Runs after all authoritative gates and before final commit/delivery.
553
+ const clusterStateForQc = (0, store_js_1.readClusterStateSync)(state.cluster_id, repoRoot);
554
+ const qcBaseRef = clusterStateForQc?.base_branch ??
555
+ config.finalize?.targetBranch ??
556
+ "main";
392
557
  await runQcGate({
393
558
  config: config.qc,
394
559
  state,
395
560
  repoRoot,
396
561
  branch,
562
+ baseRef: qcBaseRef,
397
563
  trigger: "completed-cluster",
398
564
  stepLabel: "[5.8/14]",
399
565
  });
566
+ // Step 5.9: QC repair-loop terminal state gate
567
+ // When QC is enabled and repair routing is active, require a trusted
568
+ // terminal outcome from the QC repair loop before allowing PR creation.
569
+ {
570
+ const repairLoopBlocker = validateQcRepairLoopGate(state, config.qc);
571
+ if (repairLoopBlocker) {
572
+ process.stderr.write(`finalize aborted: QC repair-loop gate failed.\n${repairLoopBlocker}\n`);
573
+ process.exit(1);
574
+ }
575
+ }
576
+ // Step 5.10: Authoritative completed-child state cross-check
577
+ // Verify that the completed children claimed by the loop state match
578
+ // the cluster-state child_states. Blocks on stale or inconsistent state.
579
+ const authChildResult = validateAuthoritativeChildState(state, repoRoot);
580
+ if (!authChildResult.ok) {
581
+ process.stderr.write(`finalize aborted: authoritative child state mismatch.\n${authChildResult.reason}\n`);
582
+ process.exit(1);
583
+ }
584
+ // Step 5.11: Run-health Medic gate
585
+ // After all worker/QC evidence is available and before any final commit, push,
586
+ // PR creation, or tracker update, require a Medic consultation decision for any
587
+ // run that recorded health symptoms.
588
+ {
589
+ console.log("[5.11/14] Checking run-health Medic gate...");
590
+ const bypassPolicy = config.finalize?.medic?.bypassPolicy ?? "none";
591
+ if (dryRun && bypassMedicReason && bypassPolicy === "cli") {
592
+ console.warn(`Dry run: would write Medic bypass to run-health report for run "${state.run_id}" (reason: ${bypassMedicReason}).`);
593
+ }
594
+ const medicBlocker = (0, medic_gate_js_1.validateMedicGate)({
595
+ runId: state.run_id,
596
+ repoRoot,
597
+ bypassReason: bypassMedicReason,
598
+ bypassPolicy,
599
+ dryRun,
600
+ });
601
+ if (medicBlocker) {
602
+ process.stderr.write(`finalize aborted: run-health Medic gate failed.\n${medicBlocker}\n`);
603
+ process.exit(1);
604
+ }
605
+ console.log("[5.11/14] Run-health Medic gate passed.");
606
+ }
400
607
  // Step 6: Tracker Reconciliation
401
608
  // LinearAdapter is sync-in only; only McpBridgeAdapter supports full reconciliation.
402
609
  const trackerType = config.tracker?.adapter;
@@ -465,7 +672,7 @@ async function runFinalize(options) {
465
672
  // Step 10: Create draft PR
466
673
  const prDraft = config.finalize?.prDraft ?? true;
467
674
  console.log("[10/14] Creating draft PR...");
468
- const prUrl = (0, _08_create_pr_js_1.stepCreatePr)(repoRoot, branch, state, prDraft);
675
+ const prUrl = (0, _08_create_pr_js_1.stepCreatePr)(repoRoot, branch, state, prDraft, authChildResult.authoritativeCount);
469
676
  // Step 10.5: PR-required QC trigger (when configured)
470
677
  // Providers that require a PR URL run here after the PR is created.
471
678
  await runQcGate({
@@ -480,6 +687,17 @@ async function runFinalize(options) {
480
687
  // Step 11: Write PR URL to current-state.json
481
688
  console.log("[11/14] Writing PR URL to state...");
482
689
  state = (0, _09_update_state_js_1.stepUpdateState)(resolvedStateFile, state, prUrl);
690
+ // Promote the authoritative run state into the cluster snapshot so that
691
+ // `.polaris/clusters/<id>/state.json` preserves completed children, the
692
+ // dispatch boundary, QC repair-loop terminal state, and the PR URL.
693
+ try {
694
+ const clusterStateSnapshotPath = (0, node_path_1.join)(repoRoot, ".polaris", "clusters", state.cluster_id, "state.json");
695
+ (0, checkpoint_js_1.writeStateAtomic)(clusterStateSnapshotPath, state);
696
+ }
697
+ catch (snapshotError) {
698
+ process.stderr.write(`[11/14] WARNING: Failed to write cluster state snapshot: ${snapshotError instanceof Error ? snapshotError.message : String(snapshotError)}\n`);
699
+ process.stderr.write(`Delivery will proceed, but cluster state snapshot at .polaris/clusters/${state.cluster_id}/state.json may be incomplete.\n`);
700
+ }
483
701
  // Step 12: Append JSONL events
484
702
  console.log("[12/14] Appending JSONL events...");
485
703
  const artifactDir = state.artifact_dir ?? (0, node_path_1.join)(repoRoot, ".taskchain_artifacts", "polaris-run");
@@ -489,7 +707,7 @@ async function runFinalize(options) {
489
707
  console.log("[13/14] Updating Linear...");
490
708
  const linearEnabled = config.tracker?.linear?.enabled ?? false;
491
709
  const lifecyclePolicy = config.tracker?.lifecyclePolicy;
492
- await (0, _11_update_linear_js_1.stepUpdateLinear)(state, branch, prUrl, true, linearEnabled, state.cluster_id, lifecyclePolicy);
710
+ await (0, _11_update_linear_js_1.stepUpdateLinear)(state, branch, prUrl, true, linearEnabled, state.cluster_id, lifecyclePolicy, authChildResult.authoritativeCount);
493
711
  // Step 14: Archive run snapshot
494
712
  console.log("[14/14] Archiving run snapshot...");
495
713
  (0, _12_archive_js_1.stepArchive)(repoRoot, state, resolvedStateFile, reportPath);
@@ -521,11 +739,19 @@ function createFinalizeCommand(handlers = {}) {
521
739
  .option("--dry-run", "non-mutating preview: validate and generate report without committing or pushing")
522
740
  .option("--skip-delivery", "perform local finalize steps only; skip push/PR/Linear/archive")
523
741
  .option("--skip-librarian", "skip the Closeout Librarian gate (backward compatibility only)")
742
+ .option("--bypass-medic <reason>", "bypass the run-health Medic gate (requires finalize.medic.bypassPolicy=cli)")
524
743
  .action((options) => {
525
744
  const repoRoot = options.repoRoot;
526
745
  const stateFile = options.stateFile ??
527
746
  (0, node_path_1.join)(repoRoot, ".taskchain_artifacts", "polaris-run", "current-state.json");
528
- finalizeHandler({ repoRoot, stateFile, dryRun: options.dryRun, skipDelivery: options.skipDelivery, skipLibrarian: options.skipLibrarian })
747
+ finalizeHandler({
748
+ repoRoot,
749
+ stateFile,
750
+ dryRun: options.dryRun,
751
+ skipDelivery: options.skipDelivery,
752
+ skipLibrarian: options.skipLibrarian,
753
+ bypassMedicReason: options.bypassMedic,
754
+ })
529
755
  .catch((err) => {
530
756
  process.stderr.write(`finalize error: ${err instanceof Error ? err.message : String(err)}\n`);
531
757
  process.exit(1);
@@ -97,6 +97,7 @@ async function findReviewState(issueId, apiKey) {
97
97
  // Comment body builder
98
98
  // ──────────────────────────────────────────────────────────────────────────────
99
99
  function buildCommentBody(opts) {
100
+ const childCount = opts.authoritativeChildCount ?? opts.state.completed_children.length;
100
101
  const lines = [
101
102
  `**polaris finalize complete** — run \`${opts.state.run_id}\``,
102
103
  ``,
@@ -104,7 +105,7 @@ function buildCommentBody(opts) {
104
105
  `|---|---|`,
105
106
  `| Branch | \`${opts.branch}\` |`,
106
107
  `| PR | ${opts.prUrl} |`,
107
- `| Children completed | ${opts.state.completed_children.length} |`,
108
+ `| Children completed | ${childCount} |`,
108
109
  `| Map validation | ${opts.validationPassed ? "✓ passed" : "✗ failed"} |`,
109
110
  ];
110
111
  if (opts.reviewStateMissing) {
@@ -117,8 +118,8 @@ function buildCommentBody(opts) {
117
118
  // ──────────────────────────────────────────────────────────────────────────────
118
119
  /** Posts a finalize-complete comment without attempting a state transition. */
119
120
  async function postLinearComment(options) {
120
- const { issueId, state, branch, prUrl, validationPassed, apiKey } = options;
121
- const body = buildCommentBody({ state, branch, prUrl, validationPassed, reviewStateMissing: false });
121
+ const { issueId, state, branch, prUrl, validationPassed, apiKey, authoritativeChildCount } = options;
122
+ const body = buildCommentBody({ state, branch, prUrl, validationPassed, reviewStateMissing: false, authoritativeChildCount });
122
123
  const data = await linearGraphQL(`mutation CreateComment($issueId: String!, $body: String!) {
123
124
  commentCreate(input: { issueId: $issueId, body: $body }) { success }
124
125
  }`, { issueId, body }, apiKey);
@@ -140,7 +141,7 @@ async function postLinearComment(options) {
140
141
  * state ID. The assertNotDoneState guard enforces this at runtime.
141
142
  */
142
143
  async function updateLinearIssueAfterFinalize(options) {
143
- const { issueId, state, branch, prUrl, validationPassed, apiKey, lifecyclePolicy } = options;
144
+ const { issueId, state, branch, prUrl, validationPassed, apiKey, lifecyclePolicy, authoritativeChildCount } = options;
144
145
  // Resolve lifecycle transition from policy
145
146
  const lifecycleTransition = (0, lifecycle_policy_js_1.resolveLifecycleTransition)("parent-all-children-complete", lifecyclePolicy);
146
147
  // If policy says skip, skip the state transition entirely
@@ -152,6 +153,7 @@ async function updateLinearIssueAfterFinalize(options) {
152
153
  prUrl,
153
154
  validationPassed,
154
155
  reviewStateMissing: false,
156
+ authoritativeChildCount,
155
157
  });
156
158
  const commentData = await linearGraphQL(`mutation CreateComment($issueId: String!, $body: String!) {
157
159
  commentCreate(input: { issueId: $issueId, body: $body }) { success }
@@ -172,6 +174,7 @@ async function updateLinearIssueAfterFinalize(options) {
172
174
  prUrl,
173
175
  validationPassed,
174
176
  reviewStateMissing: false,
177
+ authoritativeChildCount,
175
178
  });
176
179
  const commentData = await linearGraphQL(`mutation CreateComment($issueId: String!, $body: String!) {
177
180
  commentCreate(input: { issueId: $issueId, body: $body }) { success }
@@ -205,6 +208,7 @@ async function updateLinearIssueAfterFinalize(options) {
205
208
  prUrl,
206
209
  validationPassed,
207
210
  reviewStateMissing: reviewState === null,
211
+ authoritativeChildCount,
208
212
  });
209
213
  const commentData = await linearGraphQL(`mutation CreateComment($issueId: String!, $body: String!) {
210
214
  commentCreate(input: { issueId: $issueId, body: $body }) { success }
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateMedicGate = validateMedicGate;
4
+ const index_js_1 = require("../run-health/index.js");
5
+ /**
6
+ * Validates that a run with a run-health report either has a Medic decision or
7
+ * an explicit, allowed policy bypass. Returns `null` when finalize may proceed;
8
+ * returns a human-readable blocker string otherwise.
9
+ *
10
+ * Fails closed: a report that exists but lacks a Medic decision/bypass blocks
11
+ * final commit, push, PR creation, and tracker update.
12
+ */
13
+ function validateMedicGate(options) {
14
+ const { runId, repoRoot, bypassReason, bypassPolicy = "none", dryRun = false } = options;
15
+ const reportPath = (0, index_js_1.getRunHealthReportPath)(runId, repoRoot);
16
+ const report = (0, index_js_1.readRunHealthReport)(runId, repoRoot);
17
+ // No report means no symptoms were recorded — gate does not apply.
18
+ if (!report)
19
+ return null;
20
+ if ((0, index_js_1.isMedicGateSatisfied)(report))
21
+ return null;
22
+ if (bypassReason) {
23
+ if (bypassPolicy !== "cli") {
24
+ return (`Run-health report at ${reportPath} requires Medic consultation, but a CLI bypass is not allowed ` +
25
+ `by finalize.medic.bypassPolicy (current: "${bypassPolicy}").`);
26
+ }
27
+ if (!dryRun) {
28
+ (0, index_js_1.markBypassed)(runId, {
29
+ reason: bypassReason,
30
+ bypassed_by: process.env.USER ?? process.env.LOGNAME ?? "operator",
31
+ bypassed_at: new Date().toISOString(),
32
+ }, repoRoot);
33
+ }
34
+ return null;
35
+ }
36
+ const bypassHint = bypassPolicy === "cli"
37
+ ? `To bypass this gate, use --bypass-medic "<reason>".`
38
+ : `Bypass is not enabled by finalize.medic.bypassPolicy (current: "${bypassPolicy}").`;
39
+ return (`Run-health report at ${reportPath} has recorded symptoms and requires a Medic consultation decision ` +
40
+ `(medic_consult.status "resolved" or "bypassed", or an explicit policy_bypass) before finalize can commit, push, ` +
41
+ `create a PR, or update the tracker.\n${bypassHint}`);
42
+ }
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.stepCreatePr = stepCreatePr;
4
4
  const github_js_1 = require("../github.js");
5
- function stepCreatePr(repoRoot, branch, state, draft) {
6
- const prUrl = (0, github_js_1.createDraftPr)({ repoRoot, branch, state, draft });
5
+ function stepCreatePr(repoRoot, branch, state, draft, authoritativeChildCount) {
6
+ const prUrl = (0, github_js_1.createDraftPr)({ repoRoot, branch, state, draft, authoritativeChildCount });
7
7
  console.log(`PR created: ${prUrl}`);
8
8
  return prUrl;
9
9
  }
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.stepUpdateLinear = stepUpdateLinear;
4
4
  const linear_js_1 = require("../linear.js");
5
- async function stepUpdateLinear(state, branch, prUrl, validationPassed, linearEnabled, parentIssueId, lifecyclePolicy) {
5
+ async function stepUpdateLinear(state, branch, prUrl, validationPassed, linearEnabled, parentIssueId, lifecyclePolicy, authoritativeChildCount) {
6
6
  if (!linearEnabled) {
7
7
  console.log("[11/12] Linear integration disabled — skipping.");
8
8
  return;
@@ -17,6 +17,6 @@ async function stepUpdateLinear(state, branch, prUrl, validationPassed, linearEn
17
17
  process.stderr.write("Warning: no Linear parent issue ID — skipping Linear update.\n");
18
18
  return;
19
19
  }
20
- await (0, linear_js_1.updateLinearIssueAfterFinalize)({ issueId, state, branch, prUrl, validationPassed, apiKey, lifecyclePolicy });
20
+ await (0, linear_js_1.updateLinearIssueAfterFinalize)({ issueId, state, branch, prUrl, validationPassed, apiKey, lifecyclePolicy, authoritativeChildCount });
21
21
  console.log(`Linear parent ${issueId} updated.`);
22
22
  }