@dev-loops/core 0.6.0 → 0.7.1

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.
@@ -1,4 +1,4 @@
1
- import { DISPOSITION, STATE } from "./copilot-loop-state.mjs";
1
+ import { DISPOSITION, isCopilotRoundCapReached, STATE } from "./copilot-loop-state.mjs";
2
2
  import { findBlockingTitleMarkers } from "./pr-title-markers.mjs";
3
3
  import { evaluateUiE2eScoping } from "./ui-e2e-scoping.mjs";
4
4
 
@@ -238,160 +238,6 @@ function buildRoundExhaustionGateEvidenceNote({ copilotReviewRoundCount, maxCopi
238
238
  return `Copilot review rounds exhausted (${copilotReviewRoundCount}/${maxCopilotRounds}); current head has zero unresolved threads and green or credibly green CI, so pre_approval_gate fallback is allowed without another Copilot re-request.`;
239
239
  }
240
240
 
241
- /**
242
- * Render the (user-authored) rawCallViolations array into a bounded, single-line
243
- * fragment for the gate failure reason. Collapses whitespace/newlines per entry,
244
- * caps per-entry length, and caps the number of entries shown so a large or
245
- * garbled checkpoint cannot bloat or break gate output. Still fails closed —
246
- * this only formats the reason; the violation count above does the gating.
247
- */
248
- function summarizeRawCallViolations(violations, { maxEntries = 10, maxEntryLen = 200 } = {}) {
249
- const shown = violations.slice(0, maxEntries).map((v) => {
250
- const flat = String(v).replace(/\s+/g, " ").trim();
251
- return flat.length > maxEntryLen ? `${flat.slice(0, maxEntryLen)}…` : flat;
252
- });
253
- const more = violations.length - shown.length;
254
- return more > 0 ? `${shown.join("; ")}; …(+${more} more)` : shown.join("; ");
255
- }
256
-
257
- function evaluateRetrospectiveMergeApproval(checkpoint, { developerMode = false } = {}) {
258
- if (!checkpoint || typeof checkpoint !== "object") {
259
- return { approved: false, reason: "No retrospective checkpoint was found." };
260
- }
261
-
262
- const state = typeof checkpoint.state === "string" ? checkpoint.state.trim().toLowerCase() : "";
263
- if (state !== "complete") {
264
- return { approved: false, reason: `Retrospective is not complete (state: ${state || "missing"}).` };
265
- }
266
-
267
- // Read merge approval from behavioralReview (existing format) or top-level (future flat format).
268
- const br = checkpoint.behavioralReview && typeof checkpoint.behavioralReview === "object"
269
- ? checkpoint.behavioralReview
270
- : null;
271
- const mergeApproved = br !== null ? br.mergeApproved : checkpoint.mergeApproved;
272
- if (mergeApproved !== true) {
273
- return { approved: false, reason: "Retrospective does not explicitly approve merge (`mergeApproved: true` is required)." };
274
- }
275
-
276
- // followedWorkingAgreement: required boolean (existing checkpoint uses behavioralReview.followedWorkingAgreement).
277
- const followedWorkingAgreement = br !== null
278
- ? br.followedWorkingAgreement
279
- : checkpoint.followedWorkingAgreement;
280
- if (typeof followedWorkingAgreement !== "boolean") {
281
- return { approved: false, reason: "Retrospective is missing `followedWorkingAgreement` (true/false)." };
282
- }
283
-
284
- // gateQuality: require gateQualityAcceptable=true AND non-empty notes (behavioralReview)
285
- // or explicit gateQuality string (flat format). Avoid empty-notes bypass.
286
- const gateQualityAcceptable = br !== null
287
- ? br.gateQualityAcceptable
288
- : checkpoint.gateQualityAcceptable;
289
- if (typeof gateQualityAcceptable !== "boolean" || gateQualityAcceptable !== true) {
290
- return { approved: false, reason: `Retrospective gate quality is not explicitly acceptable (gateQualityAcceptable: ${String(gateQualityAcceptable)}).` };
291
- }
292
- const gateQuality = typeof checkpoint.gateQuality === "string" && checkpoint.gateQuality.trim().length > 0
293
- ? checkpoint.gateQuality
294
- : null;
295
- if (!gateQuality) {
296
- return { approved: false, reason: "Retrospective is missing `gateQuality` details; provide a notes field with gate-quality assessment or an explicit gateQuality string." };
297
- }
298
-
299
- // unexpectedFindings: derive from behavioralReview.drifts if flat field absent. Empty array is valid (no findings).
300
- const unexpectedFindings = typeof checkpoint.unexpectedFindings === "string" && checkpoint.unexpectedFindings.trim().length > 0
301
- ? checkpoint.unexpectedFindings
302
- : (br !== null && Array.isArray(br.drifts)
303
- ? (br.drifts.length > 0 ? br.drifts.join("; ") : "none")
304
- : null);
305
- if (!unexpectedFindings) {
306
- return { approved: false, reason: "Retrospective is missing `unexpectedFindings` details." };
307
- }
308
-
309
- // mergeRecommendation: require explicit mergeRecommendation field (string).
310
- const mergeRecommendation = typeof checkpoint.mergeRecommendation === "string" && checkpoint.mergeRecommendation.trim().length > 0
311
- ? checkpoint.mergeRecommendation
312
- : null;
313
- if (!mergeRecommendation) {
314
- return { approved: false, reason: "Retrospective is missing explicit `mergeRecommendation`." };
315
- }
316
-
317
- // internalToolingOnly: the loop's own execution must have used internal dev-loops
318
- // tooling only — no agent-level raw `gh`/`python`/`python3`/`node -e` (issue #982).
319
- // This is a DEVELOPER-MODE retro step: it enforces the dev-loops maintainers'
320
- // own dogfooding discipline and is opt-in via `workflow.requireRetrospectiveInternalTooling`
321
- // (default OFF). CONSUMERS of the extension are never blocked by it — they may
322
- // legitimately use raw gh/python/node -e in their own workflow — so when the flag
323
- // is OFF these fields are neither required nor enforced (a complete checkpoint
324
- // without them passes exactly as it did before #982). When ON it fails closed:
325
- // a complete checkpoint must explicitly attest a clean tooling record, and an OLD
326
- // checkpoint missing `internalToolingOnly` fails (not a silent pass). Re-record the
327
- // retrospective with the new fields to clear it.
328
- if (developerMode) {
329
- const internalToolingOnly = br !== null ? br.internalToolingOnly : checkpoint.internalToolingOnly;
330
- if (internalToolingOnly !== true) {
331
- return {
332
- approved: false,
333
- reason: "Retrospective does not attest internal-tooling-only execution (`internalToolingOnly: true` is required in developer mode; agent-level raw gh/python/node -e is a violation). — re-record the retrospective with internalToolingOnly + rawCallViolations.",
334
- };
335
- }
336
- const rawCallViolations = br !== null ? br.rawCallViolations : checkpoint.rawCallViolations;
337
- if (!Array.isArray(rawCallViolations)) {
338
- return { approved: false, reason: "Retrospective is missing `rawCallViolations` (array; empty when clean). — re-record the retrospective with internalToolingOnly + rawCallViolations." };
339
- }
340
- if (rawCallViolations.length > 0) {
341
- return {
342
- approved: false,
343
- reason: `Retrospective records ${rawCallViolations.length} raw-call violation(s) (agent-level gh/python/node -e): ${summarizeRawCallViolations(rawCallViolations)}.`,
344
- };
345
- }
346
- }
347
-
348
- return { approved: true, reason: null };
349
- }
350
-
351
- function buildRetrospectiveGatePendingResult({
352
- input,
353
- currentHeadSha,
354
- draftGateAlreadySatisfied,
355
- draftGate,
356
- preApprovalGate,
357
- mergeStateStatus,
358
- conflictFiles,
359
- reason,
360
- refinementArtifact = null,
361
- }) {
362
- const allowedNextActions = [];
363
- const forbiddenActions = [];
364
- pushUnique(allowedNextActions, [PR_CHECKPOINT_ACTION.REPORT_BLOCKED]);
365
- pushUnique(forbiddenActions, [
366
- PR_CHECKPOINT_ACTION.RUN_DRAFT_GATE,
367
- PR_CHECKPOINT_ACTION.MARK_READY_FOR_REVIEW,
368
- PR_CHECKPOINT_ACTION.REQUEST_COPILOT_REVIEW,
369
- PR_CHECKPOINT_ACTION.RUN_PRE_APPROVAL_GATE,
370
- PR_CHECKPOINT_ACTION.AWAIT_FINAL_HUMAN_APPROVAL,
371
- PR_CHECKPOINT_ACTION.DECLARE_MERGE_READY,
372
- ]);
373
-
374
- return buildResult({
375
- repo: input.repo ?? null,
376
- pr: Number.isInteger(input.pr) ? input.pr : null,
377
- currentHeadSha,
378
- lifecycleState: "retrospective_gate_pending",
379
- loopDisposition: DISPOSITION.BLOCKED,
380
- gateBoundary: PR_CHECKPOINT.BLOCKED,
381
- draftGateAlreadySatisfied,
382
- draftGate,
383
- preApprovalGate,
384
- allowedNextActions,
385
- forbiddenActions,
386
- nextAction: PR_CHECKPOINT_ACTION.REPORT_BLOCKED,
387
- reason,
388
- mergeStateStatus,
389
- conflictFiles,
390
- refinementArtifact,
391
- });
392
- }
393
-
394
-
395
241
  /**
396
242
  * Blocked result for a PR that would otherwise reach final_approval_ready but
397
243
  * still carries a merge-blocking marker in its title (issue #842). The title is
@@ -551,6 +397,9 @@ function buildResult({
551
397
  * the current head, including a post-cap head Copilot has not (and will not)
552
398
  * re-review. No further Copilot round is permitted, so the formal-request guard
553
399
  * must not fire — the pre_approval_gate reviews the post-cap head (per #848).
400
+ * @param {boolean} [params.postConvergenceSignificantChange=false] - significant
401
+ * post-convergence changes on a newer head start a new review cycle and must
402
+ * not be treated as round-cap clean-fallback suppression.
554
403
  * @param {string} params.gateBoundary - current gate boundary
555
404
  * @returns {boolean}
556
405
  */
@@ -561,6 +410,7 @@ export function shouldGuardCopilotReviewRequest({
561
410
  maxCopilotRounds = null,
562
411
  sameHeadCleanConverged = false,
563
412
  roundCapCleanFallback = false,
413
+ postConvergenceSignificantChange = false,
564
414
  gateBoundary,
565
415
  }) {
566
416
  const gateBoundariesRequiringCopilotFormalRequest = new Set([
@@ -593,10 +443,12 @@ export function shouldGuardCopilotReviewRequest({
593
443
  // CI) but Copilot has NOT reviewed THIS head (e.g. a post-cap commit). No further
594
444
  // Copilot round is permitted, so forcing a formal request would dead-end the loop;
595
445
  // the pre_approval_gate reviews the post-cap head instead (per #848).
596
- const roundCapReached = maxCopilotRounds !== null
597
- && typeof copilotReviewRoundCount === "number"
598
- && copilotReviewRoundCount >= maxCopilotRounds;
599
- if (roundCapReached && (sameHeadCleanConverged || roundCapCleanFallback)) {
446
+ const roundCapReached = isCopilotRoundCapReached({ copilotReviewRoundCount, maxCopilotRounds });
447
+ if (
448
+ roundCapReached
449
+ && (sameHeadCleanConverged || roundCapCleanFallback)
450
+ && !postConvergenceSignificantChange
451
+ ) {
600
452
  return false;
601
453
  }
602
454
  return true;
@@ -683,12 +535,9 @@ function evaluatePrGateCoordinationCore(input = {}) {
683
535
  const draftGateRequireCi = input.draftGateRequireCi !== false;
684
536
  const copilotReviewRoundCount = normalizeNonNegativeInteger(input.copilotReviewRoundCount);
685
537
  const maxCopilotRounds = normalizePositiveInteger(input.maxCopilotRounds);
686
- const roundCapReached = maxCopilotRounds !== null && copilotReviewRoundCount >= maxCopilotRounds;
687
- const requireRetrospectiveGate = input.requireRetrospectiveGate === true;
688
- // Developer-mode flag (#982): only the dev-loops repo dogfooding itself enforces the
689
- // internal-tooling-only retro discipline. Default OFF so consumer state changes pass.
690
- const requireRetrospectiveInternalTooling = input.requireRetrospectiveInternalTooling === true;
691
- const retrospectiveCheckpoint = input.retrospectiveCheckpoint;
538
+ const roundCapReached = isCopilotRoundCapReached({ copilotReviewRoundCount, maxCopilotRounds });
539
+ const postConvergenceSignificantChange = input.postConvergenceSignificantChange === true;
540
+ const roundCapNewCycleRequired = roundCapReached && copilotReviewRoundCount > 0 && postConvergenceSignificantChange;
692
541
  const prTitle = typeof input.prTitle === "string" ? input.prTitle : "";
693
542
  // UI e2e auto-scoping (#976): the PR changed-file set + whether the shared UI
694
543
  // e2e suite passed for this head. Inclusion is path-triggered, never annotated.
@@ -849,7 +698,7 @@ function evaluatePrGateCoordinationCore(input = {}) {
849
698
  // registered in the shared UI e2e suite AND that suite must have passed for
850
699
  // this head. A rendered-artifact change with no registered/passing coverage
851
700
  // blocks here with a reason naming the artifact. Distinct seam from the
852
- // mergeability (#980) and retrospective (#982) preconditions to minimize
701
+ // mergeability (#980) preconditions to minimize
853
702
  // merge-time conflict. Non-UI changes pass through untouched (required=false).
854
703
  const uiE2eScoping = evaluateUiE2eScoping(changedFiles, { uiE2ePassed });
855
704
  if (uiE2eScoping.required && !uiE2eScoping.satisfied) {
@@ -1061,24 +910,6 @@ function evaluatePrGateCoordinationCore(input = {}) {
1061
910
  refinementArtifact,
1062
911
  });
1063
912
  }
1064
- if (requireRetrospectiveGate) {
1065
- const retrospectiveGate = evaluateRetrospectiveMergeApproval(retrospectiveCheckpoint, { developerMode: requireRetrospectiveInternalTooling });
1066
- if (!retrospectiveGate.approved) {
1067
- return buildRetrospectiveGatePendingResult({
1068
- input,
1069
- currentHeadSha,
1070
- draftGateAlreadySatisfied: roundCapReached ? true : draftGateAlreadySatisfied,
1071
- draftGate,
1072
- preApprovalGate,
1073
- mergeStateStatus,
1074
- conflictFiles,
1075
- reason: `Merge remains blocked: retrospective_gate_pending. ${retrospectiveGate.reason}`,
1076
- refinementArtifact,
1077
- });
1078
- }
1079
- }
1080
-
1081
-
1082
913
  if (!draftGate.cleanEvidenceExists) {
1083
914
  return buildDraftGateNeededForMergeResult({
1084
915
  input,
@@ -1291,11 +1122,11 @@ function evaluatePrGateCoordinationCore(input = {}) {
1291
1122
  });
1292
1123
  }
1293
1124
 
1294
- const roundExhaustionGateEvidenceNote = roundCapReached
1125
+ const roundExhaustionGateEvidenceNote = (roundCapReached && !roundCapNewCycleRequired)
1295
1126
  ? buildRoundExhaustionGateEvidenceNote({ copilotReviewRoundCount, maxCopilotRounds })
1296
1127
  : null;
1297
1128
 
1298
- if (!sameHeadCleanConverged && !roundCapReached) {
1129
+ if (!sameHeadCleanConverged && (!roundCapReached || roundCapNewCycleRequired)) {
1299
1130
  pushUnique(allowedNextActions, [PR_CHECKPOINT_ACTION.REREQUEST_COPILOT_REVIEW]);
1300
1131
  pushUnique(forbiddenActions, postDraftForbidden);
1301
1132
  return buildResult({
@@ -1311,7 +1142,9 @@ function evaluatePrGateCoordinationCore(input = {}) {
1311
1142
  allowedNextActions,
1312
1143
  forbiddenActions,
1313
1144
  nextAction: PR_CHECKPOINT_ACTION.REREQUEST_COPILOT_REVIEW,
1314
- reason: "The review loop is between passes, but the current head does not yet have a clean settled Copilot convergence point, so `pre_approval_gate` is still forbidden.",
1145
+ reason: roundCapNewCycleRequired
1146
+ ? "The previous Copilot cycle converged at the round cap, but significant post-convergence changes landed on a newer head; start a new Copilot review cycle and re-request review before `pre_approval_gate`."
1147
+ : "The review loop is between passes, but the current head does not yet have a clean settled Copilot convergence point, so `pre_approval_gate` is still forbidden.",
1315
1148
  mergeStateStatus,
1316
1149
  conflictFiles,
1317
1150
  refinementArtifact,
@@ -1333,23 +1166,6 @@ function evaluatePrGateCoordinationCore(input = {}) {
1333
1166
  refinementArtifact,
1334
1167
  });
1335
1168
  }
1336
- if (requireRetrospectiveGate) {
1337
- const retrospectiveGate = evaluateRetrospectiveMergeApproval(retrospectiveCheckpoint, { developerMode: requireRetrospectiveInternalTooling });
1338
- if (!retrospectiveGate.approved) {
1339
- return buildRetrospectiveGatePendingResult({
1340
- input,
1341
- currentHeadSha,
1342
- draftGateAlreadySatisfied: roundCapReached ? true : draftGateAlreadySatisfied,
1343
- draftGate,
1344
- preApprovalGate,
1345
- mergeStateStatus,
1346
- conflictFiles,
1347
- reason: `Merge remains blocked: retrospective_gate_pending. ${retrospectiveGate.reason}`,
1348
- refinementArtifact,
1349
- });
1350
- }
1351
- }
1352
-
1353
1169
 
1354
1170
  if (!draftGate.cleanEvidenceExists && !roundCapReached) {
1355
1171
  return buildDraftGateNeededForMergeResult({
@@ -1438,6 +1254,35 @@ function evaluatePrGateCoordinationCore(input = {}) {
1438
1254
  // blocked states are handled earlier, so genuinely-blocked states still forbid
1439
1255
  // pre_approval. Mirrors LOW_SIGNAL_CONVERGED routing with round-cap reasoning.
1440
1256
  if (effectiveLifecycleState === STATE.ROUND_CAP_CLEAN_FALLBACK) {
1257
+ if (roundCapNewCycleRequired) {
1258
+ pushUnique(allowedNextActions, [PR_CHECKPOINT_ACTION.REREQUEST_COPILOT_REVIEW]);
1259
+ pushUnique(forbiddenActions, [
1260
+ PR_CHECKPOINT_ACTION.RUN_DRAFT_GATE,
1261
+ PR_CHECKPOINT_ACTION.MARK_READY_FOR_REVIEW,
1262
+ PR_CHECKPOINT_ACTION.REQUEST_COPILOT_REVIEW,
1263
+ PR_CHECKPOINT_ACTION.RUN_PRE_APPROVAL_GATE,
1264
+ PR_CHECKPOINT_ACTION.DECLARE_MERGE_READY,
1265
+ ]);
1266
+ return buildResult({
1267
+ repo: input.repo ?? null,
1268
+ pr: Number.isInteger(input.pr) ? input.pr : null,
1269
+ currentHeadSha,
1270
+ lifecycleState: STATE.READY_TO_REREQUEST_REVIEW,
1271
+ loopDisposition: DISPOSITION.ACTION_REQUIRED,
1272
+ gateBoundary: PR_CHECKPOINT.POST_DRAFT_EXTERNAL_REVIEW,
1273
+ draftGateAlreadySatisfied: roundCapReached ? true : draftGateAlreadySatisfied,
1274
+ draftGate,
1275
+ preApprovalGate,
1276
+ allowedNextActions,
1277
+ forbiddenActions,
1278
+ nextAction: PR_CHECKPOINT_ACTION.REREQUEST_COPILOT_REVIEW,
1279
+ reason: `The previous Copilot cycle converged at the round cap (${copilotReviewRoundCount}/${maxCopilotRounds}), but significant post-convergence changes landed on the current head. Open a new cycle and re-request Copilot review before entering \`pre_approval_gate\`.`,
1280
+ mergeStateStatus,
1281
+ conflictFiles,
1282
+ refinementArtifact,
1283
+ copilotReviewRoundCount,
1284
+ });
1285
+ }
1441
1286
  if (ciStatus === "failure" || ciStatus === "crediblyGreen") {
1442
1287
  pushUnique(allowedNextActions, [PR_CHECKPOINT_ACTION.REPORT_BLOCKED]);
1443
1288
  pushUnique(forbiddenActions, postDraftForbidden);
@@ -1499,23 +1344,6 @@ function evaluatePrGateCoordinationCore(input = {}) {
1499
1344
  refinementArtifact,
1500
1345
  });
1501
1346
  }
1502
- if (requireRetrospectiveGate) {
1503
- const retrospectiveGate = evaluateRetrospectiveMergeApproval(retrospectiveCheckpoint, { developerMode: requireRetrospectiveInternalTooling });
1504
- if (!retrospectiveGate.approved) {
1505
- return buildRetrospectiveGatePendingResult({
1506
- input,
1507
- currentHeadSha,
1508
- draftGateAlreadySatisfied: true,
1509
- draftGate,
1510
- preApprovalGate,
1511
- mergeStateStatus,
1512
- conflictFiles,
1513
- reason: `Merge remains blocked: retrospective_gate_pending. ${retrospectiveGate.reason}`,
1514
- refinementArtifact,
1515
- });
1516
- }
1517
- }
1518
-
1519
1347
  // Mirror LOW_SIGNAL_CONVERGED (#579): a clean current head with no clean
1520
1348
  // draft_gate evidence must reconcile the draft gate rather than jump to
1521
1349
  // final approval. This keeps the core handler consistent with the
@@ -1659,23 +1487,6 @@ function evaluatePrGateCoordinationCore(input = {}) {
1659
1487
  refinementArtifact,
1660
1488
  });
1661
1489
  }
1662
- if (requireRetrospectiveGate) {
1663
- const retrospectiveGate = evaluateRetrospectiveMergeApproval(retrospectiveCheckpoint, { developerMode: requireRetrospectiveInternalTooling });
1664
- if (!retrospectiveGate.approved) {
1665
- return buildRetrospectiveGatePendingResult({
1666
- input,
1667
- currentHeadSha,
1668
- draftGateAlreadySatisfied: roundCapReached ? true : draftGateAlreadySatisfied,
1669
- draftGate,
1670
- preApprovalGate,
1671
- mergeStateStatus,
1672
- conflictFiles,
1673
- reason: `Merge remains blocked: retrospective_gate_pending. ${retrospectiveGate.reason}`,
1674
- refinementArtifact,
1675
- });
1676
- }
1677
- }
1678
-
1679
1490
 
1680
1491
  if (!draftGate.cleanEvidenceExists) {
1681
1492
  return buildDraftGateNeededForMergeResult({
@@ -1304,9 +1304,9 @@ export function resolveAuthoritativeStartupResumeBundle(input = {}) {
1304
1304
  }
1305
1305
 
1306
1306
 
1307
- const BUILT_IN_DEFAULT_TARGET_PREFERENCE = DEV_LOOP_TARGET_PREFERENCE.PREFER_GITHUB_FIRST;
1307
+ const BUILT_IN_DEFAULT_TARGET_PREFERENCE = DEV_LOOP_TARGET_PREFERENCE.PREFER_LOCAL;
1308
1308
 
1309
- // DEFAULT_TARGET_PREFERENCE uses the built-in default (github-first).
1309
+ // DEFAULT_TARGET_PREFERENCE uses the built-in default (local-first).
1310
1310
  // Config-based target preference is resolved by the startup resolver
1311
1311
  // (resolveTargetPreference in scripts/loop/resolve-dev-loop-startup.mjs)
1312
1312
  // and passed explicitly via input.targetPreference.
@@ -1,6 +1,35 @@
1
- import { loadBoardConfig, resolveProjectNumber } from "./queue-board-sync.mjs";
1
+ import { loadBoardConfig, resolveProjectNumber, loadStateColumnMap, LOGICAL_COLUMN } from "./queue-board-sync.mjs";
2
2
  import { main as listQueueItemsMain } from "../../../../scripts/projects/list-queue-items.mjs";
3
3
 
4
+ // Canonical fail-closed Next Up tokens — the SINGLE source of truth so the reason
5
+ // codes and the empty-queue message stay byte-identical across every layer that
6
+ // detects them (queue-driver, run-queue, resolve-active-board-item). These strings
7
+ // drifted twice before centralization (#1091); import them, never re-inline them.
8
+ export const REASON_NEXT_UP_EMPTY = "next-up-empty";
9
+ export const REASON_BOARD_QUERY_ERROR = "board-query-error";
10
+ export const REASON_NEXT_UP_TARGET_MISSING_LOCALLY = "next-up-target-missing-locally";
11
+ export const EMPTY_NEXT_UP_MESSAGE = "queue empty — prioritize Backlog items into Next Up";
12
+
13
+ /**
14
+ * Resolve the board's "Next Up" pickup order (issue #1091).
15
+ *
16
+ * Next Up is the NORMATIVE, fail-closed pickup source. This resolver reports
17
+ * enough to let the driver distinguish three cases cleanly (it never silently
18
+ * collapses them):
19
+ *
20
+ * - Board NOT configured → `{ ok:true, configured:false, order:[] }`. The
21
+ * Next Up concept does not exist; the driver keeps its legacy local order.
22
+ * - Board configured, Next Up query SUCCEEDS → `{ ok:true, configured:true,
23
+ * order:[…], reason:null }`. `order` may be empty (a genuinely empty Next
24
+ * Up → the driver fails closed / idles, it MUST NOT fall back to Backlog).
25
+ * - Board configured, query ERRORS (unreachable / project unresolvable / API
26
+ * failure) → `{ ok:false, configured:true, order:[], reason:<msg> }`. The
27
+ * driver surfaces the error and stops; it MUST NOT fall back to Backlog.
28
+ *
29
+ * `order` and `reason` are always present so the fail-open membership layer
30
+ * (queue-membership.mjs), which predates the `ok`/`configured` fields, keeps
31
+ * working unchanged (it reads `order`/`reason` only).
32
+ */
4
33
  export async function resolveNextUpOrder(
5
34
  repo,
6
35
  repoRoot,
@@ -9,19 +38,32 @@ export async function resolveNextUpOrder(
9
38
  ) {
10
39
  const config = loadBoardConfig(repoRoot);
11
40
  if (!config.enabled) {
12
- return { ok: true, order: [], reason: config.reason ?? "board not configured" };
41
+ return { ok: true, configured: false, order: [], reason: config.reason ?? "board not configured" };
13
42
  }
14
43
 
15
44
  let projectNumber;
16
45
  try {
17
46
  projectNumber = await resolveProjectNumber(repo, config, env, dependencies.runChild);
18
47
  } catch (err) {
19
- return { ok: true, order: [], reason: err.message ?? "board lookup failed" };
48
+ // Board IS configured but we cannot resolve/reach it: this is a query ERROR,
49
+ // not an empty Next Up. Fail closed at the driver, never Backlog fallback.
50
+ return { ok: false, configured: true, order: [], reason: err.message ?? "board lookup failed" };
20
51
  }
21
52
  if (!projectNumber) {
22
- return { ok: true, order: [], reason: "could not resolve board project" };
53
+ return { ok: false, configured: true, order: [], reason: "could not resolve board project" };
23
54
  }
24
55
 
56
+ // Resolve the logical next_up column through the SAME statusColumns mapping
57
+ // board-sync uses (#1098), so a renamed Next Up column (e.g. "Todo") is
58
+ // queried by its configured display name instead of the literal default.
59
+ // No config-error guard here: loadBoardConfig above already short-circuits any
60
+ // `.devloops` read/parse error to `enabled:false` (early return at the top of
61
+ // this function), so a malformed config never reaches this point. The
62
+ // fail-closed-on-config-error guard lives on the direct-read pickup path
63
+ // (resolve-active-board-item), which does NOT go through loadBoardConfig.
64
+ const { columnNames } = loadStateColumnMap(repoRoot);
65
+ const nextUpColumn = columnNames[LOGICAL_COLUMN.NEXT_UP];
66
+
25
67
  const listItems = dependencies.listQueueItems ?? listQueueItemsMain;
26
68
  try {
27
69
  const result = await listItems(
@@ -29,14 +71,16 @@ export async function resolveNextUpOrder(
29
71
  // resolveProjectNumber yields a number, so stringify it. Passing the raw
30
72
  // number trips parseProjectRef's `typeof raw !== "string"` guard, which
31
73
  // surfaces as a misleading "--project is required" (#901).
32
- { repo, project: String(projectNumber), column: "Next Up" },
74
+ { repo, project: String(projectNumber), column: nextUpColumn },
33
75
  { env, runChild: dependencies.runChild },
34
76
  );
35
77
  const order = (result?.items ?? [])
36
78
  .map((it) => it.issueNumber ?? it.prNumber)
37
79
  .filter((n) => typeof n === "number");
38
- return { ok: true, order, reason: null };
80
+ // Successful query — order may be empty (genuinely empty Next Up).
81
+ return { ok: true, configured: true, order, reason: null };
39
82
  } catch (err) {
40
- return { ok: true, order: [], reason: err.message ?? "Next Up query failed" };
83
+ // Query ERROR — surface it; the driver stops and never falls back.
84
+ return { ok: false, configured: true, order: [], reason: err.message ?? "Next Up query failed" };
41
85
  }
42
86
  }
@@ -107,6 +107,61 @@ export function boardColumnForLoopState(loopState, mapping = {}) {
107
107
  return columnNames[logical] ?? columnNames[DEFAULT_LOGICAL_COLUMN];
108
108
  }
109
109
 
110
+ /**
111
+ * Derive the board's target LOGICAL column for a queue item from live GitHub
112
+ * facts (#1069). Returns LOGICAL_COLUMN.DONE, LOGICAL_COLUMN.IN_PROGRESS, or
113
+ * null when the item should be left where it is (Backlog/Next Up untouched).
114
+ *
115
+ * facts: {
116
+ * itemKind: "issue" | "pr",
117
+ * issueState: "OPEN" | "CLOSED" | null, // for issue items
118
+ * prState: "OPEN" | "CLOSED" | "MERGED" | null, // item PR, or the issue's linked PR
119
+ * prIsDraft: boolean | null,
120
+ * }
121
+ */
122
+ export function deriveReconcileColumn(facts = {}) {
123
+ const { itemKind, issueState, prState, prIsDraft } = facts;
124
+ // Merged PR (item is a PR, or issue's linked PR merged) => Done.
125
+ if (prState === "MERGED") return LOGICAL_COLUMN.DONE;
126
+ if (itemKind === "issue" && issueState === "CLOSED") return LOGICAL_COLUMN.DONE;
127
+ // Open, ready (non-draft) PR => In Progress.
128
+ if (prState === "OPEN" && prIsDraft === false) return LOGICAL_COLUMN.IN_PROGRESS;
129
+ // Otherwise leave the item untouched (Backlog / Next Up ordering preserved).
130
+ return null;
131
+ }
132
+
133
+ /**
134
+ * Pure reconcile planner (#1069). Given listed board items, a map of live facts
135
+ * keyed by the item's stable GraphQL node id (`item.itemId`), and the resolved
136
+ * column display names, return the set of moves needed to converge the board and
137
+ * a count of items left unchanged. Idempotent: when every item already sits in
138
+ * its derived column, the moves array is empty.
139
+ *
140
+ * Keying by the stable `itemId` (not the bare issue/PR number) keeps reconcile
141
+ * deterministic on a multi-repo GitHub Projects board, where two items can share
142
+ * a number (repo-A PR #5 vs repo-B issue #5) — number-keying would collide and
143
+ * make moves order-dependent.
144
+ *
145
+ * items: [{ itemId, issueNumber, prNumber, status, ... }] (from list-queue-items)
146
+ * factsByItemId: Map<itemId, factsObject> (facts as consumed by deriveReconcileColumn)
147
+ * columnNames: { in_progress, done, ... } (LOGICAL_COLUMN -> display name)
148
+ */
149
+ export function planReconcile(items = [], factsByItemId = new Map(), columnNames = {}) {
150
+ const moves = [];
151
+ let unchanged = 0;
152
+ for (const item of items) {
153
+ const facts = factsByItemId.get(item.itemId);
154
+ const logical = facts ? deriveReconcileColumn(facts) : null;
155
+ if (logical == null) { unchanged += 1; continue; }
156
+ const target = columnNames[logical];
157
+ if (!target || item.status === target) { unchanged += 1; continue; }
158
+ // `number` is kept only for reporting; the move is applied by node id.
159
+ const number = item.prNumber != null ? item.prNumber : item.issueNumber;
160
+ moves.push({ itemId: item.itemId, number, from: item.status ?? null, to: target });
161
+ }
162
+ return { moves, unchanged };
163
+ }
164
+
110
165
  // ── Local config loader ─────────────────────────────────────────────────
111
166
 
112
167
  function readDevloopsSettings(repoRoot) {
@@ -169,7 +224,7 @@ export function loadBoardConfig(repoRoot) {
169
224
  * cannot pollute Object.prototype.
170
225
  */
171
226
  export function loadStateColumnMap(repoRoot) {
172
- const { settings: queue } = readDevloopsSettings(repoRoot);
227
+ const { settings: queue, error } = readDevloopsSettings(repoRoot);
173
228
  // Null-prototype objects: untrusted keys can never reach Object.prototype.
174
229
  const columnNames = Object.assign(Object.create(null), DEFAULT_STATE_COLUMN_NAMES);
175
230
  const stateColumnMap = Object.create(null);
@@ -200,7 +255,11 @@ export function loadStateColumnMap(repoRoot) {
200
255
  }
201
256
  }
202
257
 
203
- return { columnNames, stateColumnMap };
258
+ // Surface a non-ENOENT read/parse error (mirrors loadBoardConfig). Callers on
259
+ // the fail-closed next_up pickup path MUST honor it rather than silently
260
+ // querying the default literal column against a stale/renamed board (#1098).
261
+ // Existing `.columnNames`-only callers ignore this field and behave unchanged.
262
+ return { columnNames, stateColumnMap, error: error ?? null };
204
263
  }
205
264
 
206
265
  // ── Minimal project lookup (read-only, no create/repair) ────────────────