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,345 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Integrate gate approve / reject / posture auto-approve (SP-632 / FR-REL250-10 / #123).
4
+ * Kept separate from gate.mjs so the open/check facade stays ≤500 LOC.
5
+ */
6
+
7
+ import { resolveGatePostureConfig } from "../config/gate-posture-config.mjs";
8
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
10
+ import { makeBlocker } from "./blocker-codes.mjs";
11
+ import { GATE_CATEGORIES, POSTURES } from "./gate-posture-defaults.mjs";
12
+ import { evaluateGatePosture } from "./gate-posture-evaluate.mjs";
13
+ import {
14
+ getCategoryStreak,
15
+ incrementCategoryStreak,
16
+ incrementKindStreak,
17
+ resetCategoryStreak,
18
+ resetKindStreak,
19
+ } from "./gate-posture-streak.mjs";
20
+ import { gateRecordPath, loadGateRecord } from "./gate-evidence-read.mjs";
21
+ import { appendJournalEvent } from "./journal.mjs";
22
+
23
+ /** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
24
+ /** @typedef {import("./gate-posture-evaluate.mjs").GatePostureEvaluateResult} GatePostureEvaluateResult */
25
+
26
+ /** Fail-closed integrate default — mirrors DEFAULT_INTEGRATE_GATE_CATEGORY in gate.mjs. */
27
+ const INTEGRATE_DEFAULT_CATEGORY = /** @type {GateCategory} */ ("execute");
28
+
29
+ const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
30
+
31
+ /**
32
+ * @param {string} projectRoot
33
+ * @param {object} gate
34
+ */
35
+ function saveGateRecord(projectRoot, gate) {
36
+ writeJsonAtomic(gateRecordPath(projectRoot, gate.batchId), gate);
37
+ }
38
+
39
+ /**
40
+ * True when config explicitly overlays a posture for this category.
41
+ * Integrate auto-approve requires opt-in — bare DEFAULT_POSTURES must not unlock.
42
+ *
43
+ * @param {unknown} config
44
+ * @param {string} category
45
+ * @returns {boolean}
46
+ */
47
+ export function hasExplicitCategoryPostureOptIn(config, category) {
48
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
49
+ return false;
50
+ }
51
+ const gates = /** @type {{ postures?: unknown }} */ (config).gates;
52
+ if (!gates || typeof gates !== "object" || Array.isArray(gates)) {
53
+ return false;
54
+ }
55
+ const postures = gates.postures;
56
+ if (!postures || typeof postures !== "object" || Array.isArray(postures)) {
57
+ return false;
58
+ }
59
+ if (typeof category !== "string" || category.trim() === "" || category === "alwaysBreakOn") {
60
+ return false;
61
+ }
62
+ if (!(category in postures)) {
63
+ return false;
64
+ }
65
+ const entry = /** @type {Record<string, unknown>} */ (postures)[category];
66
+ return typeof entry === "object" && entry !== null && !Array.isArray(entry);
67
+ }
68
+
69
+ /**
70
+ * Resolve category stamped on a gate, failing closed to the integrate default.
71
+ *
72
+ * @param {object|null|undefined} gate
73
+ * @returns {GateCategory}
74
+ */
75
+ function resolveGateCategory(gate) {
76
+ const raw = gate && typeof gate === "object" ? gate.category : null;
77
+ if (typeof raw === "string" && CATEGORY_SET.has(raw)) {
78
+ return /** @type {GateCategory} */ (raw);
79
+ }
80
+ return INTEGRATE_DEFAULT_CATEGORY;
81
+ }
82
+
83
+ /**
84
+ * Persist consecutive-approval streak after a successful approve.
85
+ * Failures must not undo the gate FSM decision.
86
+ *
87
+ * @param {string} projectRoot
88
+ * @param {object} gate
89
+ */
90
+ function recordApprovalStreak(projectRoot, gate) {
91
+ const category = resolveGateCategory(gate);
92
+ try {
93
+ incrementCategoryStreak(projectRoot, category);
94
+ if (typeof gate.kind === "string" && gate.kind.trim() !== "") {
95
+ incrementKindStreak(projectRoot, gate.kind);
96
+ }
97
+ } catch {
98
+ // Streak I/O must not reverse an already-persisted approval.
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Reset streak counters after a reject (breaks consecutive-approval chain).
104
+ *
105
+ * @param {string} projectRoot
106
+ * @param {object} gate
107
+ */
108
+ function recordRejectStreakReset(projectRoot, gate) {
109
+ const category = resolveGateCategory(gate);
110
+ try {
111
+ resetCategoryStreak(projectRoot, category);
112
+ if (typeof gate.kind === "string" && gate.kind.trim() !== "") {
113
+ resetKindStreak(projectRoot, gate.kind);
114
+ }
115
+ } catch {
116
+ // Streak reset failure must not reverse a persisted rejection.
117
+ }
118
+ }
119
+
120
+ /**
121
+ * @param {object} ctx
122
+ * @param {string} ctx.projectRoot
123
+ * @param {string} ctx.batchId
124
+ * @param {"human" | "auto"} [ctx.decidedBy]
125
+ * @param {GatePostureEvaluateResult | null} [ctx.postureEvaluation]
126
+ */
127
+ export function approveIntegrateGate(ctx) {
128
+ const { projectRoot, batchId, decidedBy = "human", postureEvaluation = null } = ctx;
129
+ const gate = loadGateRecord(projectRoot, batchId);
130
+
131
+ if (!gate) {
132
+ const error = "No integrate gate found for this batch";
133
+ return {
134
+ ok: false,
135
+ exitCode: 1,
136
+ error,
137
+ headline: "Cannot approve — gate not opened",
138
+ suggestedCommand: "spine status --diagnose",
139
+ blockers: [makeBlocker("missing_gate", error)],
140
+ };
141
+ }
142
+
143
+ if (gate.status === "approved") {
144
+ return { ok: true, exitCode: 0, gate, headline: "Integrate gate already approved", alreadyDecided: true };
145
+ }
146
+
147
+ if (gate.status === "rejected") {
148
+ const error = "Gate was rejected — reopen batch evidence or start a new gate cycle";
149
+ return {
150
+ ok: false,
151
+ exitCode: 1,
152
+ error,
153
+ headline: "Cannot approve a rejected gate",
154
+ suggestedCommand: "spine gate status",
155
+ gate,
156
+ blockers: [makeBlocker("gate_rejected", error)],
157
+ };
158
+ }
159
+
160
+ const actor = decidedBy === "auto" ? "auto" : "human";
161
+ gate.status = "approved";
162
+ gate.decidedAt = new Date().toISOString();
163
+ gate.decidedBy = actor;
164
+ saveGateRecord(projectRoot, gate);
165
+ recordApprovalStreak(projectRoot, gate);
166
+
167
+ /** @type {Record<string, unknown>} */
168
+ const journalPayload = {
169
+ gateId: gate.gateId,
170
+ kind: gate.kind,
171
+ category: gate.category ?? null,
172
+ status: gate.status,
173
+ decidedBy: actor,
174
+ };
175
+ if (postureEvaluation) {
176
+ journalPayload.postureDecision = postureEvaluation.decision;
177
+ journalPayload.postureReason = postureEvaluation.reason;
178
+ journalPayload.postureTier = postureEvaluation.tier;
179
+ }
180
+
181
+ appendJournalEvent(projectRoot, batchId, "gate.approved", journalPayload);
182
+
183
+ return {
184
+ ok: true,
185
+ exitCode: 0,
186
+ gate,
187
+ headline: actor === "auto" ? "Integrate gate auto-approved" : "Integrate gate approved",
188
+ suggestedCommand: "spine integrate",
189
+ alternatives: ["/spine-integrate"],
190
+ decidedBy: actor,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Evaluate posture and auto-approve a pending integrate gate when config opts in.
196
+ * Default (no explicit `gates.postures[category]`) stays locked — never auto.
197
+ * Does not bypass `validateSequenceAutoApproveGate` for the blunt CLI flag path.
198
+ *
199
+ * @param {object} ctx
200
+ * @param {string} ctx.projectRoot
201
+ * @param {string} ctx.batchId
202
+ * @param {ReturnType<typeof loadSpineConfig>["config"]} [ctx.config]
203
+ * @param {readonly string[]} [ctx.tags]
204
+ */
205
+ export function maybeAutoApproveIntegrateGate(ctx) {
206
+ const { projectRoot, batchId, tags = [] } = ctx;
207
+ const config = ctx.config ?? loadSpineConfig(projectRoot).config ?? null;
208
+ const gate = loadGateRecord(projectRoot, batchId);
209
+
210
+ if (!gate) {
211
+ return { ok: true, approved: false, skipped: true, reason: "no_gate" };
212
+ }
213
+ if (gate.status === "approved") {
214
+ return { ok: true, approved: false, skipped: true, reason: "already_approved", gate };
215
+ }
216
+ if (gate.status === "rejected") {
217
+ return { ok: true, approved: false, skipped: true, reason: "rejected", gate };
218
+ }
219
+ if (gate.status !== "pending") {
220
+ return { ok: true, approved: false, skipped: true, reason: "not_pending", gate };
221
+ }
222
+
223
+ const category = resolveGateCategory(gate);
224
+ const optedIn = hasExplicitCategoryPostureOptIn(config, category);
225
+ const postureConfig = resolveGatePostureConfig(config);
226
+ const categoryEntry = optedIn
227
+ ? postureConfig.categories[category]
228
+ : { posture: POSTURES.LOCKED, autoApproveAfterN: null };
229
+
230
+ const consecutiveApprovals = getCategoryStreak(projectRoot, category);
231
+ /** @type {string[]} */
232
+ const mergedTags = [];
233
+ if (Array.isArray(gate.tags)) {
234
+ for (const tag of gate.tags) {
235
+ if (typeof tag === "string") mergedTags.push(tag);
236
+ }
237
+ }
238
+ for (const tag of tags) {
239
+ if (typeof tag === "string") mergedTags.push(tag);
240
+ }
241
+
242
+ const evaluation = evaluateGatePosture({
243
+ category,
244
+ posture: categoryEntry.posture,
245
+ autoApproveAfterN: categoryEntry.autoApproveAfterN,
246
+ consecutiveApprovals,
247
+ tags: mergedTags,
248
+ alwaysBreakOn: postureConfig.alwaysBreakOn,
249
+ });
250
+
251
+ if (evaluation.decision !== "allow-auto") {
252
+ return {
253
+ ok: true,
254
+ approved: false,
255
+ evaluation,
256
+ optedIn,
257
+ category,
258
+ consecutiveApprovals,
259
+ reason: evaluation.reason,
260
+ gate,
261
+ };
262
+ }
263
+
264
+ const approved = approveIntegrateGate({
265
+ projectRoot,
266
+ batchId,
267
+ decidedBy: "auto",
268
+ postureEvaluation: evaluation,
269
+ });
270
+
271
+ return {
272
+ ok: approved.ok,
273
+ exitCode: approved.exitCode,
274
+ approved: approved.ok === true,
275
+ evaluation,
276
+ optedIn,
277
+ category,
278
+ decidedBy: "auto",
279
+ gate: approved.gate ?? gate,
280
+ headline: approved.headline,
281
+ error: approved.error,
282
+ blockers: approved.blockers,
283
+ };
284
+ }
285
+
286
+ /**
287
+ * @param {object} ctx
288
+ * @param {string} ctx.projectRoot
289
+ * @param {string} ctx.batchId
290
+ * @param {string} [ctx.reason]
291
+ */
292
+ export function rejectIntegrateGate(ctx) {
293
+ const { projectRoot, batchId, reason } = ctx;
294
+ const gate = loadGateRecord(projectRoot, batchId);
295
+
296
+ if (!gate) {
297
+ return {
298
+ ok: false,
299
+ exitCode: 1,
300
+ error: "No integrate gate found for this batch",
301
+ headline: "Cannot reject — gate not opened",
302
+ suggestedCommand: "spine status --diagnose",
303
+ };
304
+ }
305
+
306
+ if (gate.status === "rejected") {
307
+ return { ok: true, exitCode: 0, gate, headline: "Integrate gate already rejected", alreadyDecided: true };
308
+ }
309
+
310
+ if (gate.status === "approved") {
311
+ return {
312
+ ok: false,
313
+ exitCode: 1,
314
+ error: "Gate already approved",
315
+ headline: "Cannot reject an approved gate",
316
+ suggestedCommand: "spine integrate",
317
+ gate,
318
+ };
319
+ }
320
+
321
+ gate.status = "rejected";
322
+ gate.decidedAt = new Date().toISOString();
323
+ gate.decidedBy = "human";
324
+ if (reason) gate.rejectionReason = reason;
325
+ saveGateRecord(projectRoot, gate);
326
+ recordRejectStreakReset(projectRoot, gate);
327
+
328
+ appendJournalEvent(projectRoot, batchId, "gate.rejected", {
329
+ gateId: gate.gateId,
330
+ kind: gate.kind,
331
+ category: gate.category ?? null,
332
+ status: gate.status,
333
+ reason: reason ?? null,
334
+ decidedBy: "human",
335
+ });
336
+
337
+ return {
338
+ ok: true,
339
+ exitCode: 0,
340
+ gate,
341
+ headline: "Integrate gate rejected",
342
+ suggestedCommand: "spine status --diagnose",
343
+ alternatives: ["/spine-gate status"],
344
+ };
345
+ }
@@ -0,0 +1,64 @@
1
+ // @ts-check
2
+ /**
3
+ * Gate category postures and documented defaults (SP-627 / FR-REL250-05 / #123).
4
+ * Pure data only — no I/O and no auto-approve wiring.
5
+ */
6
+
7
+ /** @typedef {"read" | "write" | "execute" | "destroy" | "network" | "auth"} GateCategory */
8
+ /** @typedef {"permissive" | "cautious" | "guarded" | "locked"} GatePosture */
9
+
10
+ /**
11
+ * Categories for human-gate classification.
12
+ * @type {ReadonlyArray<GateCategory>}
13
+ */
14
+ export const GATE_CATEGORIES = Object.freeze([
15
+ "read",
16
+ "write",
17
+ "execute",
18
+ "destroy",
19
+ "network",
20
+ "auth",
21
+ ]);
22
+
23
+ /**
24
+ * Named approval postures (least → most restrictive).
25
+ * @type {Readonly<{ PERMISSIVE: "permissive"; CAUTIOUS: "cautious"; GUARDED: "guarded"; LOCKED: "locked" }>}
26
+ */
27
+ export const POSTURES = Object.freeze({
28
+ PERMISSIVE: "permissive",
29
+ CAUTIOUS: "cautious",
30
+ GUARDED: "guarded",
31
+ LOCKED: "locked",
32
+ });
33
+
34
+ /**
35
+ * Categories that must remain locked (never auto-approve).
36
+ * @type {ReadonlyArray<GateCategory>}
37
+ */
38
+ export const LOCKED_CATEGORIES = Object.freeze(
39
+ /** @type {GateCategory[]} */ (["destroy", "auth"]),
40
+ );
41
+
42
+ /**
43
+ * @typedef {{
44
+ * posture: GatePosture;
45
+ * autoApproveAfterN: number | null;
46
+ * }} CategoryPostureDefault
47
+ *
48
+ * `autoApproveAfterN` is null when posture is locked (always manual).
49
+ * Zero means immediate auto-approve once posture allows it.
50
+ */
51
+
52
+ /**
53
+ * Documented default postures from GitHub #123.
54
+ * destroy/auth stay locked; others are documented defaults for later config overlay.
55
+ * @type {Readonly<Record<GateCategory, Readonly<CategoryPostureDefault>>>}
56
+ */
57
+ export const DEFAULT_POSTURES = Object.freeze({
58
+ read: Object.freeze({ posture: POSTURES.PERMISSIVE, autoApproveAfterN: 0 }),
59
+ write: Object.freeze({ posture: POSTURES.CAUTIOUS, autoApproveAfterN: 3 }),
60
+ execute: Object.freeze({ posture: POSTURES.GUARDED, autoApproveAfterN: 5 }),
61
+ destroy: Object.freeze({ posture: POSTURES.LOCKED, autoApproveAfterN: null }),
62
+ network: Object.freeze({ posture: POSTURES.CAUTIOUS, autoApproveAfterN: 3 }),
63
+ auth: Object.freeze({ posture: POSTURES.LOCKED, autoApproveAfterN: null }),
64
+ });
@@ -0,0 +1,133 @@
1
+ // @ts-check
2
+ /**
3
+ * Pure gate posture evaluation cascade (SP-628 / FR-REL250-06 / #123).
4
+ * No filesystem I/O — callers supply streak and config fields.
5
+ *
6
+ * Cascade (highest precedence first):
7
+ * 1. posture locked
8
+ * 2. never-auto-approve (LOCKED_CATEGORIES or explicit flag)
9
+ * 3. alwaysBreakOn tag match
10
+ * 4. immediate auto (autoApproveAfterN === 0)
11
+ * 5. autoApproveAfterN streak threshold
12
+ */
13
+
14
+ import { LOCKED_CATEGORIES, POSTURES } from "./gate-posture-defaults.mjs";
15
+
16
+ /** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
17
+ /** @typedef {import("./gate-posture-defaults.mjs").GatePosture} GatePosture */
18
+
19
+ /**
20
+ * @typedef {"allow-auto" | "require-manual"} GatePostureDecision
21
+ */
22
+
23
+ /**
24
+ * Cascade tier that produced the decision (1–5), or null when no auto path matched.
25
+ * @typedef {1 | 2 | 3 | 4 | 5 | null} GatePostureTier
26
+ */
27
+
28
+ /**
29
+ * @typedef {{
30
+ * category: GateCategory;
31
+ * posture: GatePosture;
32
+ * autoApproveAfterN: number | null;
33
+ * consecutiveApprovals?: number;
34
+ * tags?: readonly string[];
35
+ * alwaysBreakOn?: readonly string[];
36
+ * neverAutoApprove?: boolean;
37
+ * }} GatePostureEvaluateInput
38
+ */
39
+
40
+ /**
41
+ * @typedef {{
42
+ * decision: GatePostureDecision;
43
+ * reason: string;
44
+ * tier: GatePostureTier;
45
+ * }} GatePostureEvaluateResult
46
+ */
47
+
48
+ /**
49
+ * Evaluate whether a gate may auto-approve under the 5-tier posture cascade.
50
+ * Fail-closed: unknown thresholds and insufficient streak require manual approval.
51
+ *
52
+ * @param {GatePostureEvaluateInput} input
53
+ * @returns {GatePostureEvaluateResult}
54
+ */
55
+ export function evaluateGatePosture(input) {
56
+ const {
57
+ category,
58
+ posture,
59
+ autoApproveAfterN,
60
+ consecutiveApprovals = 0,
61
+ tags = [],
62
+ alwaysBreakOn = [],
63
+ neverAutoApprove = false,
64
+ } = input;
65
+
66
+ // 1. Posture locked — always manual
67
+ if (posture === POSTURES.LOCKED) {
68
+ return {
69
+ decision: "require-manual",
70
+ reason: `Category '${category}' requires explicit human approval (posture: locked)`,
71
+ tier: 1,
72
+ };
73
+ }
74
+
75
+ // 2. Never-auto-approve — locked categories and explicit flags
76
+ if (LOCKED_CATEGORIES.includes(category) || neverAutoApprove === true) {
77
+ const why = neverAutoApprove === true
78
+ ? "neverAutoApprove flag"
79
+ : `category '${category}' is never auto-approved`;
80
+ return {
81
+ decision: "require-manual",
82
+ reason: `Blocked by never-auto-approve: ${why}`,
83
+ tier: 2,
84
+ };
85
+ }
86
+
87
+ // 3. alwaysBreakOn tag intersection
88
+ for (const breakTag of alwaysBreakOn) {
89
+ if (tags.includes(breakTag)) {
90
+ return {
91
+ decision: "require-manual",
92
+ reason: `Blocked by alwaysBreakOn tag: ${breakTag}`,
93
+ tier: 3,
94
+ };
95
+ }
96
+ }
97
+
98
+ // 4. Immediate auto when threshold is zero
99
+ if (autoApproveAfterN === 0) {
100
+ return {
101
+ decision: "allow-auto",
102
+ reason: "Immediate auto-approve (autoApproveAfterN: 0)",
103
+ tier: 4,
104
+ };
105
+ }
106
+
107
+ // 5. Streak threshold (null / non-positive fails closed to manual)
108
+ if (
109
+ typeof autoApproveAfterN === "number" &&
110
+ autoApproveAfterN > 0 &&
111
+ consecutiveApprovals >= autoApproveAfterN
112
+ ) {
113
+ return {
114
+ decision: "allow-auto",
115
+ reason: `Auto-approved after ${consecutiveApprovals} consecutive approvals (threshold: ${autoApproveAfterN})`,
116
+ tier: 5,
117
+ };
118
+ }
119
+
120
+ if (typeof autoApproveAfterN === "number" && autoApproveAfterN > 0) {
121
+ return {
122
+ decision: "require-manual",
123
+ reason: `Streak ${consecutiveApprovals} below autoApproveAfterN threshold ${autoApproveAfterN}`,
124
+ tier: 5,
125
+ };
126
+ }
127
+
128
+ return {
129
+ decision: "require-manual",
130
+ reason: "No matching auto-approval path",
131
+ tier: null,
132
+ };
133
+ }