pi-spine 2.3.2 → 2.5.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.
@@ -0,0 +1,290 @@
1
+ // @ts-check
2
+ /**
3
+ * Persist consecutive approval streak counters for autoApproveAfterN (SP-631 / FR-REL250-09 / #123).
4
+ * Counts are keyed by gate category and/or gate kind under `.spine/runtime/`.
5
+ * No approve-path wiring — SP-632 consumes this API.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
11
+ import { GATE_CATEGORIES } from "./gate-posture-defaults.mjs";
12
+
13
+ /** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
14
+
15
+ /**
16
+ * @typedef {{
17
+ * version: number;
18
+ * categories: Record<string, number>;
19
+ * kinds: Record<string, number>;
20
+ * updatedAt: string;
21
+ * }} GatePostureStreakState
22
+ */
23
+
24
+ export const GATE_POSTURE_STREAK_VERSION = 1;
25
+
26
+ /** Relative path under project root for the streak store. */
27
+ export const GATE_POSTURE_STREAK_REL = path.join(
28
+ ".spine",
29
+ "runtime",
30
+ "gate-posture",
31
+ "streaks.json",
32
+ );
33
+
34
+ const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
35
+
36
+ /**
37
+ * Absolute path to the streak JSON file.
38
+ * @param {string} projectRoot
39
+ * @returns {string}
40
+ */
41
+ export function gatePostureStreakPath(projectRoot) {
42
+ return path.join(projectRoot, GATE_POSTURE_STREAK_REL);
43
+ }
44
+
45
+ /**
46
+ * Empty store with zero counts for every known category.
47
+ * @returns {GatePostureStreakState}
48
+ */
49
+ function emptyStreakState() {
50
+ /** @type {Record<string, number>} */
51
+ const categories = {};
52
+ for (const category of GATE_CATEGORIES) {
53
+ categories[category] = 0;
54
+ }
55
+ return {
56
+ version: GATE_POSTURE_STREAK_VERSION,
57
+ categories,
58
+ kinds: {},
59
+ updatedAt: new Date().toISOString(),
60
+ };
61
+ }
62
+
63
+ /**
64
+ * @param {unknown} value
65
+ * @returns {value is Record<string, unknown>}
66
+ */
67
+ function isPlainObject(value) {
68
+ return typeof value === "object" && value !== null && !Array.isArray(value);
69
+ }
70
+
71
+ /**
72
+ * Coerce a count map to non-negative integers; drop invalid keys/values.
73
+ * @param {unknown} raw
74
+ * @param {{ allowOnlyCategories?: boolean }} [opts]
75
+ * @returns {Record<string, number>}
76
+ */
77
+ function normalizeCountMap(raw, opts = {}) {
78
+ /** @type {Record<string, number>} */
79
+ const out = {};
80
+ if (!isPlainObject(raw)) {
81
+ return out;
82
+ }
83
+ for (const [key, value] of Object.entries(raw)) {
84
+ if (typeof key !== "string" || key.trim() === "") {
85
+ continue;
86
+ }
87
+ if (opts.allowOnlyCategories === true && !CATEGORY_SET.has(key)) {
88
+ continue;
89
+ }
90
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
91
+ continue;
92
+ }
93
+ out[key] = value;
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /**
99
+ * Normalize persisted JSON into a full streak state (fail-closed zeros on corruption).
100
+ * @param {unknown} raw
101
+ * @returns {GatePostureStreakState}
102
+ */
103
+ function normalizeStreakState(raw) {
104
+ const base = emptyStreakState();
105
+ if (!isPlainObject(raw)) {
106
+ return base;
107
+ }
108
+
109
+ const categories = normalizeCountMap(raw.categories, { allowOnlyCategories: true });
110
+ for (const category of GATE_CATEGORIES) {
111
+ if (category in categories) {
112
+ base.categories[category] = categories[category];
113
+ }
114
+ }
115
+
116
+ base.kinds = normalizeCountMap(raw.kinds);
117
+ if (typeof raw.updatedAt === "string" && raw.updatedAt.trim() !== "") {
118
+ base.updatedAt = raw.updatedAt;
119
+ }
120
+ return base;
121
+ }
122
+
123
+ /**
124
+ * Load streak state from runtime path. Missing or corrupt file → empty zeros.
125
+ * @param {string} projectRoot
126
+ * @returns {GatePostureStreakState}
127
+ */
128
+ export function loadGatePostureStreaks(projectRoot) {
129
+ const filePath = gatePostureStreakPath(projectRoot);
130
+ if (!fs.existsSync(filePath)) {
131
+ return emptyStreakState();
132
+ }
133
+ try {
134
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
135
+ return normalizeStreakState(raw);
136
+ } catch {
137
+ // Corrupt JSON must not unlock auto-approve — treat as zero streak.
138
+ return emptyStreakState();
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Persist streak state atomically under `.spine/runtime/`.
144
+ * @param {string} projectRoot
145
+ * @param {GatePostureStreakState} state
146
+ * @returns {GatePostureStreakState}
147
+ */
148
+ export function saveGatePostureStreaks(projectRoot, state) {
149
+ const next = {
150
+ version: GATE_POSTURE_STREAK_VERSION,
151
+ categories: { ...state.categories },
152
+ kinds: { ...state.kinds },
153
+ updatedAt: new Date().toISOString(),
154
+ };
155
+ writeJsonAtomic(gatePostureStreakPath(projectRoot), next);
156
+ return next;
157
+ }
158
+
159
+ /**
160
+ * Read consecutive approval count for a gate category.
161
+ * @param {string} projectRoot
162
+ * @param {GateCategory | string} category
163
+ * @returns {number}
164
+ */
165
+ export function getCategoryStreak(projectRoot, category) {
166
+ const state = loadGatePostureStreaks(projectRoot);
167
+ const count = state.categories[category];
168
+ return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : 0;
169
+ }
170
+
171
+ /**
172
+ * Read consecutive approval count for a gate kind (e.g. integrate).
173
+ * @param {string} projectRoot
174
+ * @param {string} kind
175
+ * @returns {number}
176
+ */
177
+ export function getKindStreak(projectRoot, kind) {
178
+ const state = loadGatePostureStreaks(projectRoot);
179
+ const count = state.kinds[kind];
180
+ return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : 0;
181
+ }
182
+
183
+ /**
184
+ * Increment category streak after an approval. Returns the new count.
185
+ * @param {string} projectRoot
186
+ * @param {GateCategory | string} category
187
+ * @returns {number}
188
+ */
189
+ export function incrementCategoryStreak(projectRoot, category) {
190
+ const state = loadGatePostureStreaks(projectRoot);
191
+ const prevRaw = state.categories[category];
192
+ const prev =
193
+ typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
194
+ const next = prev + 1;
195
+ state.categories[category] = next;
196
+ saveGatePostureStreaks(projectRoot, state);
197
+ return next;
198
+ }
199
+
200
+ /**
201
+ * Increment kind streak after an approval. Returns the new count.
202
+ * @param {string} projectRoot
203
+ * @param {string} kind
204
+ * @returns {number}
205
+ */
206
+ export function incrementKindStreak(projectRoot, kind) {
207
+ if (typeof kind !== "string" || kind.trim() === "") {
208
+ throw new Error("gate posture kind streak key must be a non-empty string");
209
+ }
210
+ const state = loadGatePostureStreaks(projectRoot);
211
+ const prevRaw = state.kinds[kind];
212
+ const prev =
213
+ typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
214
+ const next = prev + 1;
215
+ state.kinds[kind] = next;
216
+ saveGatePostureStreaks(projectRoot, state);
217
+ return next;
218
+ }
219
+
220
+ /**
221
+ * Reset category streak on reject or manual break.
222
+ * @param {string} projectRoot
223
+ * @param {GateCategory | string} category
224
+ * @returns {number} Always 0 after reset
225
+ */
226
+ export function resetCategoryStreak(projectRoot, category) {
227
+ const state = loadGatePostureStreaks(projectRoot);
228
+ state.categories[category] = 0;
229
+ saveGatePostureStreaks(projectRoot, state);
230
+ return 0;
231
+ }
232
+
233
+ /**
234
+ * Reset kind streak on reject or manual break.
235
+ * @param {string} projectRoot
236
+ * @param {string} kind
237
+ * @returns {number} Always 0 after reset
238
+ */
239
+ export function resetKindStreak(projectRoot, kind) {
240
+ const state = loadGatePostureStreaks(projectRoot);
241
+ state.kinds[kind] = 0;
242
+ saveGatePostureStreaks(projectRoot, state);
243
+ return 0;
244
+ }
245
+
246
+ /**
247
+ * Clear all category and kind streaks (manual break across the board).
248
+ * @param {string} projectRoot
249
+ * @returns {GatePostureStreakState}
250
+ */
251
+ export function resetAllStreaks(projectRoot) {
252
+ return saveGatePostureStreaks(projectRoot, emptyStreakState());
253
+ }
254
+
255
+ /**
256
+ * Whether a consecutive-approval count meets an autoApproveAfterN threshold.
257
+ * Null / non-positive thresholds never meet (fail-closed except explicit 0 = immediate).
258
+ * Callers treat threshold 0 as immediate auto via the evaluator; this helper returns true for 0.
259
+ *
260
+ * @param {number} consecutiveApprovals
261
+ * @param {number | null | undefined} autoApproveAfterN
262
+ * @returns {boolean}
263
+ */
264
+ export function streakMeetsThreshold(consecutiveApprovals, autoApproveAfterN) {
265
+ if (typeof consecutiveApprovals !== "number" || !Number.isInteger(consecutiveApprovals) || consecutiveApprovals < 0) {
266
+ return false;
267
+ }
268
+ if (typeof autoApproveAfterN !== "number" || !Number.isInteger(autoApproveAfterN) || autoApproveAfterN < 0) {
269
+ return false;
270
+ }
271
+ if (autoApproveAfterN === 0) {
272
+ return true;
273
+ }
274
+ return consecutiveApprovals >= autoApproveAfterN;
275
+ }
276
+
277
+ /**
278
+ * Load category streak and compare against threshold (threshold read convenience).
279
+ * @param {string} projectRoot
280
+ * @param {GateCategory | string} category
281
+ * @param {number | null | undefined} autoApproveAfterN
282
+ * @returns {{ count: number, meetsThreshold: boolean }}
283
+ */
284
+ export function readCategoryStreakThreshold(projectRoot, category, autoApproveAfterN) {
285
+ const count = getCategoryStreak(projectRoot, category);
286
+ return {
287
+ count,
288
+ meetsThreshold: streakMeetsThreshold(count, autoApproveAfterN),
289
+ };
290
+ }
@@ -0,0 +1,95 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Gate targetRevision helpers — orch tip SHA pinning at gate open (FR-REL250-01 / SP-623).
4
+ */
5
+
6
+ import { gitExec } from "./git-exec.mjs";
7
+
8
+ /**
9
+ * Resolve durable `targetRevision` as the orch tip SHA at gate open.
10
+ *
11
+ * Prefer `batchState.orchBranch` tip via `git rev-parse`. When that tip is
12
+ * missing or unreadable, fall back to project `HEAD` so the gate still pins a
13
+ * durable SHA. Fail closed only when no revision can be resolved.
14
+ *
15
+ * @param {string} projectRoot
16
+ * @param {object|null|undefined} batchState
17
+ * @returns {string} Full commit SHA
18
+ */
19
+ export function resolveGateTargetRevision(projectRoot, batchState) {
20
+ const orchBranch = String(batchState?.orchBranch ?? "").trim();
21
+ if (orchBranch) {
22
+ const orchSha = gitExec(projectRoot, ["rev-parse", "--verify", `${orchBranch}^{commit}`], {
23
+ throwOnError: false,
24
+ projectRoot,
25
+ });
26
+ if (orchSha) {
27
+ return orchSha;
28
+ }
29
+ }
30
+
31
+ // Documented fallback: pin HEAD when orch tip is absent or unreadable.
32
+ const headSha = gitExec(projectRoot, ["rev-parse", "--verify", "HEAD"], {
33
+ throwOnError: false,
34
+ projectRoot,
35
+ });
36
+ if (headSha) {
37
+ return headSha;
38
+ }
39
+
40
+ if (!orchBranch) {
41
+ throw new Error("Cannot resolve gate targetRevision: batchState.orchBranch is missing and HEAD is unreadable.");
42
+ }
43
+ throw new Error(
44
+ `Cannot resolve gate targetRevision: failed to read tip of ${orchBranch} and HEAD.`,
45
+ );
46
+ }
47
+
48
+ /**
49
+ * Compare a gate's pinned `targetRevision` to the current orch tip (same resolver as open).
50
+ * Fail closed when the pin is missing or drifts — caller must re-open/re-approve.
51
+ *
52
+ * @param {string} projectRoot
53
+ * @param {object|null|undefined} gate
54
+ * @param {object|null|undefined} batchState
55
+ * @returns {{ ok: true, currentRevision: string, pinnedRevision: string } | { ok: false, currentRevision: string|null, pinnedRevision: string, reason: "missing_pin"|"mismatch"|"unreadable", error: string }}
56
+ */
57
+ export function validateGateTargetRevision(projectRoot, gate, batchState) {
58
+ const pinnedRevision = String(gate?.targetRevision ?? "").trim();
59
+ if (!pinnedRevision) {
60
+ return {
61
+ ok: false,
62
+ currentRevision: null,
63
+ pinnedRevision: "",
64
+ reason: "missing_pin",
65
+ error:
66
+ "Integrate gate has no targetRevision pin — re-open and re-approve before integrating",
67
+ };
68
+ }
69
+
70
+ let currentRevision;
71
+ try {
72
+ currentRevision = resolveGateTargetRevision(projectRoot, batchState);
73
+ } catch (err) {
74
+ const message = err instanceof Error ? err.message : String(err);
75
+ return {
76
+ ok: false,
77
+ currentRevision: null,
78
+ pinnedRevision,
79
+ reason: "unreadable",
80
+ error: `Cannot verify gate targetRevision: ${message}`,
81
+ };
82
+ }
83
+
84
+ if (pinnedRevision !== currentRevision) {
85
+ return {
86
+ ok: false,
87
+ currentRevision,
88
+ pinnedRevision,
89
+ reason: "mismatch",
90
+ error: `Gate targetRevision drifted (pinned ${pinnedRevision}, current ${currentRevision}) — re-open and re-approve before integrating`,
91
+ };
92
+ }
93
+
94
+ return { ok: true, currentRevision, pinnedRevision };
95
+ }
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import crypto from "node:crypto";
7
+ import { resolveGatePostureConfig } from "../config/gate-posture-config.mjs";
7
8
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
9
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
9
10
  import {
@@ -19,9 +20,59 @@ import {
19
20
  gateRecordPath,
20
21
  loadGateRecord,
21
22
  } from "./gate-evidence-read.mjs";
23
+ import { loadBatchStateFile } from "./batch-state-io.mjs";
24
+ import { makeBlocker } from "./blocker-codes.mjs";
25
+ import { GATE_CATEGORIES } from "./gate-posture-defaults.mjs";
26
+ import { resolveGateTargetRevision, validateGateTargetRevision } from "./gate-revision.mjs";
22
27
  import { appendJournalEvent } from "./journal.mjs";
23
28
  import { reconcileBatch } from "./reconcile.mjs";
24
29
 
30
+ export {
31
+ approveIntegrateGate,
32
+ hasExplicitCategoryPostureOptIn,
33
+ maybeAutoApproveIntegrateGate,
34
+ rejectIntegrateGate,
35
+ } from "./gate-posture-approve.mjs";
36
+
37
+ /** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
38
+
39
+ /**
40
+ * Default category stamped on integrate gates (SP-630 / FR-REL250-08 / #123).
41
+ * Explore decision: execute mapped to locked posture until config opts in (SP-632).
42
+ */
43
+ export const DEFAULT_INTEGRATE_GATE_CATEGORY = /** @type {GateCategory} */ ("execute");
44
+
45
+ const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
46
+
47
+ /**
48
+ * Resolve integrate gate category from config overlay or fail-closed default.
49
+ * Valid `gates.integrateCategory` wins; unknown/missing → execute.
50
+ * Consults posture config so stamp stays aligned with defaults/config mapping.
51
+ *
52
+ * @param {unknown} config
53
+ * @returns {GateCategory}
54
+ */
55
+ export function resolveIntegrateGateCategory(config) {
56
+ const postureConfig = resolveGatePostureConfig(config);
57
+ /** @type {GateCategory} */
58
+ let category = DEFAULT_INTEGRATE_GATE_CATEGORY;
59
+
60
+ if (config && typeof config === "object" && !Array.isArray(config)) {
61
+ const gates = /** @type {{ integrateCategory?: unknown }} */ (config).gates;
62
+ if (gates && typeof gates === "object" && !Array.isArray(gates)) {
63
+ const raw = /** @type {{ integrateCategory?: unknown }} */ (gates).integrateCategory;
64
+ if (typeof raw === "string" && CATEGORY_SET.has(raw)) {
65
+ category = /** @type {GateCategory} */ (raw);
66
+ }
67
+ }
68
+ }
69
+
70
+ if (!(category in postureConfig.categories)) {
71
+ return DEFAULT_INTEGRATE_GATE_CATEGORY;
72
+ }
73
+ return category;
74
+ }
75
+
25
76
  export {
26
77
  collectCoreEvidenceBundle,
27
78
  collectExtendedEvidenceBundle,
@@ -57,17 +108,22 @@ export function openIntegrateGate(ctx) {
57
108
  return { gate: existing, opened: false, evidenceRefs: existing.evidenceRefs ?? [] };
58
109
  }
59
110
 
111
+ const targetRevision = resolveGateTargetRevision(projectRoot, batchState);
60
112
  const reconciliation = reconcileBatch({ projectRoot, batchState, verbose: true });
61
113
  const core = collectCoreEvidenceBundle({ projectRoot, batchId, batchState, config, reconciliation });
62
114
  /** @type {string[]} */
63
115
  let evidenceRefs = [...core.evidenceRefs];
116
+ // Stamp category only — do not auto-approve; locked posture until SP-632 config opt-in.
117
+ const category = resolveIntegrateGateCategory(config);
64
118
 
65
119
  const gate = {
66
120
  gateId: crypto.randomUUID(),
67
121
  batchId,
68
122
  kind: "integrate",
123
+ category,
69
124
  status: "pending",
70
125
  openedAt: new Date().toISOString(),
126
+ targetRevision,
71
127
  evidenceRefs,
72
128
  summary: formatGateSummary({ kind: "integrate", status: "pending", evidenceRefs }),
73
129
  };
@@ -76,6 +132,7 @@ export function openIntegrateGate(ctx) {
76
132
  appendJournalEvent(projectRoot, batchId, "gate.opened", {
77
133
  gateId: gate.gateId,
78
134
  kind: gate.kind,
135
+ category: gate.category,
79
136
  status: gate.status,
80
137
  evidenceRefs: gate.evidenceRefs,
81
138
  });
@@ -143,119 +200,6 @@ export function openIntegrateGateAfterBatchComplete(ctx) {
143
200
  };
144
201
  }
145
202
 
146
- /**
147
- * @param {object} ctx
148
- * @param {string} ctx.projectRoot
149
- * @param {string} ctx.batchId
150
- */
151
- export function approveIntegrateGate(ctx) {
152
- const { projectRoot, batchId } = ctx;
153
- const gate = loadGateRecord(projectRoot, batchId);
154
-
155
- if (!gate) {
156
- return {
157
- ok: false,
158
- exitCode: 1,
159
- error: "No integrate gate found for this batch",
160
- headline: "Cannot approve — gate not opened",
161
- suggestedCommand: "spine status --diagnose",
162
- };
163
- }
164
-
165
- if (gate.status === "approved") {
166
- return { ok: true, exitCode: 0, gate, headline: "Integrate gate already approved", alreadyDecided: true };
167
- }
168
-
169
- if (gate.status === "rejected") {
170
- return {
171
- ok: false,
172
- exitCode: 1,
173
- error: "Gate was rejected — reopen batch evidence or start a new gate cycle",
174
- headline: "Cannot approve a rejected gate",
175
- suggestedCommand: "spine gate status",
176
- gate,
177
- };
178
- }
179
-
180
- gate.status = "approved";
181
- gate.decidedAt = new Date().toISOString();
182
- gate.decidedBy = "human";
183
- saveGateRecord(projectRoot, gate);
184
-
185
- appendJournalEvent(projectRoot, batchId, "gate.approved", {
186
- gateId: gate.gateId,
187
- kind: gate.kind,
188
- status: gate.status,
189
- });
190
-
191
- return {
192
- ok: true,
193
- exitCode: 0,
194
- gate,
195
- headline: "Integrate gate approved",
196
- suggestedCommand: "spine integrate",
197
- alternatives: ["/spine-integrate"],
198
- };
199
- }
200
-
201
- /**
202
- * @param {object} ctx
203
- * @param {string} ctx.projectRoot
204
- * @param {string} ctx.batchId
205
- * @param {string} [ctx.reason]
206
- */
207
- export function rejectIntegrateGate(ctx) {
208
- const { projectRoot, batchId, reason } = ctx;
209
- const gate = loadGateRecord(projectRoot, batchId);
210
-
211
- if (!gate) {
212
- return {
213
- ok: false,
214
- exitCode: 1,
215
- error: "No integrate gate found for this batch",
216
- headline: "Cannot reject — gate not opened",
217
- suggestedCommand: "spine status --diagnose",
218
- };
219
- }
220
-
221
- if (gate.status === "rejected") {
222
- return { ok: true, exitCode: 0, gate, headline: "Integrate gate already rejected", alreadyDecided: true };
223
- }
224
-
225
- if (gate.status === "approved") {
226
- return {
227
- ok: false,
228
- exitCode: 1,
229
- error: "Gate already approved",
230
- headline: "Cannot reject an approved gate",
231
- suggestedCommand: "spine integrate",
232
- gate,
233
- };
234
- }
235
-
236
- gate.status = "rejected";
237
- gate.decidedAt = new Date().toISOString();
238
- gate.decidedBy = "human";
239
- if (reason) gate.rejectionReason = reason;
240
- saveGateRecord(projectRoot, gate);
241
-
242
- appendJournalEvent(projectRoot, batchId, "gate.rejected", {
243
- gateId: gate.gateId,
244
- kind: gate.kind,
245
- status: gate.status,
246
- reason: reason ?? null,
247
- });
248
-
249
- return {
250
- ok: true,
251
- exitCode: 0,
252
- gate,
253
- headline: "Integrate gate rejected",
254
- suggestedCommand: "spine status --diagnose",
255
- alternatives: ["/spine-gate status"],
256
- };
257
- }
258
-
259
203
  /**
260
204
  * @param {object} ctx
261
205
  * @param {string} ctx.projectRoot
@@ -298,6 +242,7 @@ export function getIntegrateGateStatus(ctx) {
298
242
  * @param {string} ctx.projectRoot
299
243
  * @param {string} ctx.batchId
300
244
  * @param {ReturnType<typeof loadSpineConfig>["config"]} [ctx.config]
245
+ * @param {object|null} [ctx.batchState]
301
246
  * @param {boolean} [ctx.forceIntegrate]
302
247
  * @param {boolean} [ctx.dryRun]
303
248
  */
@@ -312,14 +257,16 @@ export function checkIntegrateGate(ctx) {
312
257
 
313
258
  if (forceIntegrate) {
314
259
  if (process.env.SPINE_ALLOW_FORCE !== "1") {
260
+ const error = "Force integrate requires SPINE_ALLOW_FORCE=1";
315
261
  return {
316
262
  ok: false,
317
263
  required: true,
318
264
  exitCode: 2,
319
265
  failureClass: "GateBlocked",
320
- error: "Force integrate requires SPINE_ALLOW_FORCE=1",
266
+ error,
321
267
  headline: "Force integrate blocked — set SPINE_ALLOW_FORCE=1 to bypass gate",
322
268
  suggestedCommand: "spine gate approve",
269
+ blockers: [makeBlocker("force_integrate_blocked", error)],
323
270
  };
324
271
  }
325
272
 
@@ -335,45 +282,70 @@ export function checkIntegrateGate(ctx) {
335
282
 
336
283
  const gate = loadGateRecord(projectRoot, batchId);
337
284
  if (!gate) {
285
+ const error = "Integrate gate not opened — approve evidence before merging";
338
286
  return {
339
287
  ok: false,
340
288
  required: true,
341
289
  exitCode: 2,
342
290
  failureClass: "GateBlocked",
343
- error: "Integrate gate not opened — approve evidence before merging",
291
+ error,
344
292
  headline: "Integrate blocked — no gate record (run batch to completion or spine gate status)",
345
293
  suggestedCommand: "spine gate status",
346
294
  alternatives: ["/spine-gate"],
295
+ blockers: [makeBlocker("missing_gate", error)],
347
296
  };
348
297
  }
349
298
 
350
299
  if (gate.status === "approved") {
300
+ const batchState = ctx.batchState ?? loadBatchStateFile(projectRoot).raw ?? null;
301
+ const revisionCheck = validateGateTargetRevision(projectRoot, gate, batchState);
302
+ if (!revisionCheck.ok) {
303
+ const error = revisionCheck.error;
304
+ return {
305
+ ok: false,
306
+ required: true,
307
+ exitCode: 2,
308
+ failureClass: "GateBlocked",
309
+ error,
310
+ headline: "Integrate blocked — gate targetRevision stale; re-open and re-approve",
311
+ suggestedCommand: "spine gate status",
312
+ gate,
313
+ alternatives: ["/spine-gate status"],
314
+ pinnedRevision: revisionCheck.pinnedRevision,
315
+ currentRevision: revisionCheck.currentRevision,
316
+ blockers: [makeBlocker("stale_revision", error)],
317
+ };
318
+ }
351
319
  return { ok: true, required: true, gate };
352
320
  }
353
321
 
354
322
  if (gate.status === "rejected") {
323
+ const error = gate.rejectionReason ?? "Integrate gate was rejected";
355
324
  return {
356
325
  ok: false,
357
326
  required: true,
358
327
  exitCode: 2,
359
328
  failureClass: "GateBlocked",
360
- error: gate.rejectionReason ?? "Integrate gate was rejected",
329
+ error,
361
330
  headline: "Integrate blocked — gate rejected",
362
331
  suggestedCommand: "spine gate status",
363
332
  gate,
364
333
  alternatives: ["/spine-gate status"],
334
+ blockers: [makeBlocker("gate_rejected", error)],
365
335
  };
366
336
  }
367
337
 
338
+ const pendingError = "Integrate gate pending human approval";
368
339
  return {
369
340
  ok: false,
370
341
  required: true,
371
342
  exitCode: 2,
372
343
  failureClass: "GateBlocked",
373
- error: "Integrate gate pending human approval",
344
+ error: pendingError,
374
345
  headline: "Integrate blocked — gate pending approval",
375
346
  suggestedCommand: "spine gate approve",
376
347
  gate,
377
348
  alternatives: ["/spine-gate approve", "spine gate reject"],
349
+ blockers: [makeBlocker("gate_pending", pendingError)],
378
350
  };
379
351
  }
@@ -283,6 +283,7 @@ export function integrateOrchToBase(ctx) {
283
283
  projectRoot,
284
284
  batchId,
285
285
  config,
286
+ batchState: batch,
286
287
  forceIntegrate: Boolean(ctx.forceIntegrate),
287
288
  dryRun,
288
289
  });