pi-spine 2.26.0 → 2.27.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.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +15 -1
  4. package/package.json +3 -3
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +72 -8
  9. package/skills/spine-release-operator/SKILL.md +33 -51
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/batch-meta-reconstruct.mjs +3 -0
  15. package/src/batch/contract-exec.mjs +2 -2
  16. package/src/batch/contract-parse.mjs +2 -2
  17. package/src/batch/contract-prelanded.mjs +2 -2
  18. package/src/batch/diagnosis-alternatives.mjs +16 -1
  19. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  20. package/src/batch/diagnosis-pending-lane.mjs +52 -1
  21. package/src/batch/diagnosis-review-infra.mjs +144 -0
  22. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  23. package/src/batch/diagnosis.mjs +19 -20
  24. package/src/batch/engine-lanes/merge.mjs +0 -8
  25. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  26. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  27. package/src/batch/engine-lanes/review-code.mjs +1 -0
  28. package/src/batch/engine-lanes/review-final.mjs +83 -46
  29. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  30. package/src/batch/engine-lanes/review-poll.mjs +51 -2
  31. package/src/batch/engine-lanes.mjs +6 -8
  32. package/src/batch/gate-posture-approve.mjs +154 -15
  33. package/src/batch/integrate-path-delete.mjs +85 -0
  34. package/src/batch/integrate-worktree.mjs +20 -27
  35. package/src/batch/journal.mjs +15 -0
  36. package/src/batch/metrics.mjs +13 -1
  37. package/src/batch/provider-quota.mjs +220 -0
  38. package/src/batch/quota-fallback.mjs +319 -0
  39. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  40. package/src/batch/reconcile-diagnosis.mjs +24 -77
  41. package/src/batch/resume-multi-queue.mjs +25 -10
  42. package/src/batch/review-artifacts.mjs +96 -17
  43. package/src/batch/review-level-effective.mjs +19 -0
  44. package/src/batch/review-spawn-retry.mjs +106 -0
  45. package/src/batch/review-spawn.mjs +60 -3
  46. package/src/batch/review-step-run.mjs +110 -8
  47. package/src/batch/reviewer-output.mjs +162 -0
  48. package/src/batch/reviewer-provider-error.mjs +153 -0
  49. package/src/batch/worker-host.mjs +49 -3
  50. package/src/batch/worker-prompt.mjs +5 -2
  51. package/src/config/cursor-rules/discover.mjs +40 -3
  52. package/src/config/cursor-rules/match-globs.mjs +6 -4
  53. package/src/config/env-overrides.mjs +41 -4
  54. package/src/config/settings-fields.mjs +11 -0
  55. package/src/config/spine-config-schema.mjs +62 -0
  56. package/src/doctor/pi-extension-hooks.mjs +322 -0
  57. package/src/doctor/quota-risk.mjs +45 -0
  58. package/src/doctor/run-doctor-checks.mjs +14 -1
  59. package/src/planner/file-scope.mjs +6 -6
  60. package/src/tasks/packet/validate-contract.mjs +3 -3
  61. package/src/tasks/packet/validate-prompt.mjs +11 -1
  62. package/src/tasks/validate-contract-warn.mjs +16 -0
  63. package/templates/spine-config.json +1 -1
@@ -260,6 +260,77 @@ export async function runFinalReviewPhase({
260
260
  const stubVerdicts = shouldUseReviewStub() ? createPhaseStubVerdictQueue("final") : null;
261
261
 
262
262
  const journalEvents = readJournalEvents(projectRoot, batchId);
263
+
264
+ // SP-813 / #328: contract verification must run before the honor fast path
265
+ // so a task can never complete through an honored final-review verdict
266
+ // without `contract.verified` in the journal. The result computed here is
267
+ // consumed by the first poll-loop iteration (contractVerifiedPending) so
268
+ // the contract is verified exactly once per phase entry; rework iterations
269
+ // re-verify as before. Respects shouldRunContractVerifyForWorker, so stub
270
+ // batches (and contracts without verifiable fields) keep skipping.
271
+ let contractVerifyResult =
272
+ /** @type {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number } | null} */ (
273
+ null
274
+ );
275
+ let contractVerifiedPending = false;
276
+ const runContractVerifyGate = async () => {
277
+ contractVerifyResult = null;
278
+ contractVerifiedPending = true;
279
+ const promptMarkdown = fs.readFileSync(path.join(taskFolderInWorktree, "PROMPT.md"), "utf-8");
280
+ const parsedContract = parseContract(promptMarkdown);
281
+ if (shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config)) {
282
+ const events = readJournalEvents(projectRoot, batchId);
283
+ const sinceCommit = resolveTaskStartCommit({
284
+ journal: events,
285
+ taskId,
286
+ laneId: lane.laneId,
287
+ batchId,
288
+ worktreePath: wt,
289
+ });
290
+ const result = await verifyContract(wt, parsedContract, {
291
+ ...config,
292
+ baseBranch,
293
+ sinceCommit: sinceCommit ?? undefined,
294
+ projectRoot,
295
+ batchId,
296
+ taskId,
297
+ taskFolder: taskFolderInWorktree,
298
+ });
299
+ contractVerifyResult = result;
300
+ task.contractOk = result.ok;
301
+ saveSpineBatchState(projectRoot, state);
302
+ appendJournalEvent(projectRoot, batchId, "contract.verified", {
303
+ taskId,
304
+ laneNumber,
305
+ laneId: lane.laneId,
306
+ correlationId: laneCorrelationId,
307
+ ok: result.ok,
308
+ checks: result.checks,
309
+ });
310
+ if (!result.ok) {
311
+ removeDoneFile(taskFolderInWorktree);
312
+ recordContractVerifyTaskFailure({
313
+ projectRoot,
314
+ state,
315
+ batchId,
316
+ task,
317
+ lane,
318
+ laneCorrelationId,
319
+ contractVerifyResult: result,
320
+ config,
321
+ taskFolder: taskFolderInWorktree,
322
+ });
323
+ return { contractFailed: true };
324
+ }
325
+ }
326
+ return { contractFailed: false };
327
+ };
328
+
329
+ const preHonorContractGate = await runContractVerifyGate();
330
+ if (preHonorContractGate.contractFailed) {
331
+ return { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" };
332
+ }
333
+
263
334
  const honoredResult = honorCompletedReview({
264
335
  reviewType: "final",
265
336
  passVerdict: "PASS",
@@ -274,6 +345,7 @@ export async function runFinalReviewPhase({
274
345
  laneCorrelationId,
275
346
  taskFolder: taskFolderInWorktree,
276
347
  journalEvents,
348
+ worktreePath: wt,
277
349
  });
278
350
  if (honoredResult) return honoredResult;
279
351
 
@@ -289,52 +361,17 @@ export async function runFinalReviewPhase({
289
361
  invalidVerdictOutput: "final review artifact missing PASS, REVISE, or REPLAN verdict",
290
362
  allowReplan: true,
291
363
  beforeReview: async () => {
292
- let contractVerifyResult = null;
293
- const promptMarkdown = fs.readFileSync(path.join(taskFolderInWorktree, "PROMPT.md"), "utf-8");
294
- const parsedContract = parseContract(promptMarkdown);
295
- if (shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config)) {
296
- const events = readJournalEvents(projectRoot, batchId);
297
- const sinceCommit = resolveTaskStartCommit({
298
- journal: events,
299
- taskId,
300
- laneId: lane.laneId,
301
- batchId,
302
- worktreePath: wt,
303
- });
304
- contractVerifyResult = await verifyContract(wt, parsedContract, {
305
- ...config,
306
- baseBranch,
307
- sinceCommit: sinceCommit ?? undefined,
308
- projectRoot,
309
- batchId,
310
- taskId,
311
- taskFolder: taskFolderInWorktree,
312
- });
313
- task.contractOk = contractVerifyResult.ok;
314
- saveSpineBatchState(projectRoot, state);
315
- appendJournalEvent(projectRoot, batchId, "contract.verified", {
316
- taskId,
317
- laneNumber,
318
- laneId: lane.laneId,
319
- correlationId: laneCorrelationId,
320
- ok: contractVerifyResult.ok,
321
- checks: contractVerifyResult.checks,
322
- });
323
- if (!contractVerifyResult.ok) {
324
- removeDoneFile(taskFolderInWorktree);
325
- recordContractVerifyTaskFailure({
326
- projectRoot,
327
- state,
328
- batchId,
329
- task,
330
- lane,
331
- laneCorrelationId,
332
- contractVerifyResult,
333
- config,
334
- taskFolder: taskFolderInWorktree,
335
- });
336
- return { abort: { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" } };
337
- }
364
+ if (contractVerifiedPending) {
365
+ // Consume the phase-entry verification so the first poll iteration
366
+ // does not double-verify; later rework iterations run the full gate.
367
+ contractVerifiedPending = false;
368
+ return { extraReviewParams: { contractVerifyResult } };
369
+ }
370
+ const gate = await runContractVerifyGate();
371
+ if (gate.contractFailed) {
372
+ return {
373
+ abort: { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" },
374
+ };
338
375
  }
339
376
  return { extraReviewParams: { contractVerifyResult } };
340
377
  },
@@ -23,6 +23,7 @@ import {
23
23
  readReviewLevel,
24
24
  runStepReview,
25
25
  } from "../review.mjs";
26
+ import { isHonorableReviewEvent } from "../review-artifacts.mjs";
26
27
  import { honorCompletedReview, runReviewPollLoop } from "./review-poll.mjs";
27
28
  import {
28
29
  createPhaseStubVerdictQueue,
@@ -52,15 +53,26 @@ function findPlanReviewStepNumber(taskFolder) {
52
53
 
53
54
  /**
54
55
  * Resolve an existing worker or lane plan review from journal and/or artifacts.
55
- * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695).
56
+ * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695), including
57
+ * the honor guard for untrusted journal verdicts (SP-813 / #328).
56
58
  *
57
59
  * @param {object} params
58
60
  * @param {string} params.taskFolder
59
61
  * @param {Array<Record<string, any>>} [params.journalEvents]
60
62
  * @param {string} [params.taskId]
63
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
64
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
65
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
61
66
  * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
62
67
  */
63
- function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
68
+ function findCompletedPlanReview({
69
+ taskFolder,
70
+ journalEvents = [],
71
+ taskId,
72
+ worktreePath,
73
+ stubMode,
74
+ onReject,
75
+ }) {
64
76
  /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
65
77
  let journalMatch = null;
66
78
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -71,6 +83,13 @@ function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
71
83
  if (payload.reviewType !== "plan") continue;
72
84
  const verdict = normalizeCodeVerdict(payload.verdict);
73
85
  if (!verdict) continue;
86
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
87
+ if (!honorGuard.ok) {
88
+ // Untrusted event: skip it exactly as if it were absent so the scan
89
+ // still honors a later trustworthy event or the artifact fallback.
90
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
91
+ continue;
92
+ }
74
93
  journalMatch = {
75
94
  verdict,
76
95
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -313,6 +332,7 @@ export async function runPlanReviewPhase({
313
332
  laneCorrelationId,
314
333
  taskFolder: taskFolderInWorktree,
315
334
  journalEvents,
335
+ worktreePath: wt,
316
336
  });
317
337
  if (honoredResult) return honoredResult;
318
338
 
@@ -22,6 +22,8 @@ import {
22
22
  resolveReviewPassKind,
23
23
  shouldEmitReviewResumed,
24
24
  } from "../review.mjs";
25
+ import { shouldUseReviewStub } from "./review-stub.mjs";
26
+ import { REVIEW_PROVIDER_ERROR_REASON } from "../reviewer-provider-error.mjs";
25
27
 
26
28
  /**
27
29
  * @param {string} taskFolder
@@ -112,6 +114,7 @@ export function appendReviewHonorJournalEvents({
112
114
  * @param {string} params.laneCorrelationId
113
115
  * @param {string} params.taskFolder
114
116
  * @param {Array<Record<string, any>>} params.journalEvents
117
+ * @param {string} [params.worktreePath] Lane worktree; resolves relative journal artifact paths for the honor guard.
115
118
  * @returns {{ ok: boolean, [key: string]: any } | null}
116
119
  */
117
120
  export function honorCompletedReview({
@@ -128,11 +131,55 @@ export function honorCompletedReview({
128
131
  laneCorrelationId,
129
132
  taskFolder,
130
133
  journalEvents,
134
+ worktreePath,
131
135
  }) {
132
136
  const taskId = task.taskId;
133
137
  const laneNumber = lane.laneNumber;
134
138
  const reviewAttempt = task[attemptField] ?? 0;
135
- const honored = findCompletedReview({ taskFolder, journalEvents, taskId });
139
+ // #328: only honor verdicts the batch can trust. stubMode is computed once
140
+ // here (the caller of the finders) and passed down, covering both
141
+ // SPINE_WORKER_STUB and SPINE_REVIEW_STUB engine-stub modes.
142
+ const stubMode = shouldUseReviewStub();
143
+ const rejectedSourceIds = new Set(
144
+ journalEvents
145
+ .filter(
146
+ (event) =>
147
+ event.type === "review.honor_rejected" &&
148
+ (event.taskId === undefined || event.taskId === taskId),
149
+ )
150
+ .map((event) => event.payload?.sourceEventId)
151
+ .filter((id) => typeof id === "string" && id),
152
+ );
153
+ const honored = findCompletedReview({
154
+ taskFolder,
155
+ journalEvents,
156
+ taskId,
157
+ worktreePath,
158
+ stubMode,
159
+ onReject: (
160
+ /** @type {Record<string, any>} */ event,
161
+ /** @type {string} */ reason,
162
+ ) => {
163
+ const payload =
164
+ event.payload && typeof event.payload === "object" ? event.payload : {};
165
+ const sourceEventId =
166
+ typeof event.eventId === "string" && event.eventId ? event.eventId : event.timestamp;
167
+ // Dedupe by source event id so a rejected event journals once, not on
168
+ // every phase entry that rescans the journal.
169
+ if (rejectedSourceIds.has(sourceEventId)) return;
170
+ rejectedSourceIds.add(sourceEventId);
171
+ appendJournalEvent(projectRoot, batchId, "review.honor_rejected", {
172
+ taskId,
173
+ laneNumber,
174
+ laneId: lane.laneId,
175
+ correlationId: laneCorrelationId,
176
+ reviewType,
177
+ reason,
178
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
179
+ sourceEventId,
180
+ });
181
+ },
182
+ });
136
183
  if (honored?.verdict !== passVerdict) return null;
137
184
 
138
185
  const honorJournalEvent = resolveReviewHonorJournalEvent({
@@ -283,7 +330,9 @@ export async function runReviewPollLoop({
283
330
  const spawnExitReason =
284
331
  reviewResult.reason === REVIEW_TIMEOUT_REASON
285
332
  ? `${reviewType}_review_timeout`
286
- : `${reviewType}_review_spawn_failed`;
333
+ : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
334
+ ? `${reviewType}_review_provider_error`
335
+ : `${reviewType}_review_spawn_failed`;
287
336
  recordReviewTaskFailure({
288
337
  projectRoot,
289
338
  state,
@@ -31,12 +31,10 @@ import { runWorker } from "./worker-host.mjs";
31
31
  import { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase } from "./engine-lanes/review.mjs";
32
32
  import { ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
33
33
  import { resolveWorktreeSetupIgnorePaths } from "../config/spine-config-load.mjs";
34
- import {
35
- acquireLaneSlot,
36
- loadMatrixTaskRows,
37
- releaseLaneSlot,
38
- } from "./engine-lanes/matrix.mjs";
34
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
35
+ import { acquireLaneSlot, loadMatrixTaskRows, releaseLaneSlot } from "./engine-lanes/matrix.mjs";
39
36
  import { runMatrixTaskOnLane } from "./engine-lanes/matrix-run.mjs";
37
+ import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
40
38
 
41
39
  export {
42
40
  buildTasksAndLanesFromPlan,
@@ -59,7 +57,6 @@ export {
59
57
  mergeWaveLanesToOrch,
60
58
  resolveRulesManifestIntegrateDrift,
61
59
  tryAutoResolveMergeConflicts,
62
- tryAutoResolveRulesManifestMergeConflict,
63
60
  } from "./engine-lanes/merge.mjs";
64
61
 
65
62
  export { syncLaneWorktreeFromOrch } from "./worktree.mjs";
@@ -160,7 +157,8 @@ export async function runTaskOnLane({
160
157
 
161
158
  const laneSlot = await acquireLaneSlot(state, config?.lanes?.maxParallel ?? 1);
162
159
  try {
163
- return await runNonMatrixTaskOnLane({
160
+ // SP-809 (#329): single-hop quota fallback retry wraps the lane run.
161
+ return await runWithQuotaFallback(() => runNonMatrixTaskOnLane({
164
162
  projectRoot,
165
163
  state,
166
164
  batchId,
@@ -171,7 +169,7 @@ export async function runTaskOnLane({
171
169
  taskFolderRel,
172
170
  laneCorrelationId,
173
171
  fileScopePaths,
174
- });
172
+ }), { projectRoot, batchId, state, taskId: task.taskId, config, workerBackend: resolveWorkerBackend(config) });
175
173
  } finally {
176
174
  releaseLaneSlot(state, laneSlot);
177
175
  }
@@ -4,6 +4,8 @@
4
4
  * Kept separate from gate.mjs so the open/check facade stays ≤500 LOC.
5
5
  */
6
6
 
7
+ import fs from "node:fs";
8
+ import path from "node:path";
7
9
  import { resolveGatePostureConfig } from "../config/gate-posture-config.mjs";
8
10
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
11
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
@@ -11,6 +13,7 @@ import { makeBlocker } from "./blocker-codes.mjs";
11
13
  import { GATE_CATEGORIES, POSTURES } from "./gate-posture-defaults.mjs";
12
14
  import { evaluateGatePosture } from "./gate-posture-evaluate.mjs";
13
15
  import {
16
+ gatePostureStreakPath,
14
17
  getCategoryStreak,
15
18
  incrementCategoryStreak,
16
19
  incrementKindStreak,
@@ -28,6 +31,92 @@ const INTEGRATE_DEFAULT_CATEGORY = /** @type {GateCategory} */ ("execute");
28
31
 
29
32
  const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
30
33
 
34
+ /** Real streak I/O (SP-824). Tests may override any subset via `ctx.streakIo`. */
35
+ const DEFAULT_STREAK_IO = Object.freeze({
36
+ incrementCategoryStreak,
37
+ incrementKindStreak,
38
+ resetCategoryStreak,
39
+ resetKindStreak,
40
+ removeStreakFile(projectRoot) {
41
+ fs.rmSync(gatePostureStreakPath(projectRoot), { force: true });
42
+ },
43
+ });
44
+
45
+ /**
46
+ * @param {unknown} streakIo Optional partial override of streak I/O operations.
47
+ * @returns {typeof DEFAULT_STREAK_IO}
48
+ */
49
+ function resolveStreakIo(streakIo) {
50
+ if (!streakIo || typeof streakIo !== "object" || Array.isArray(streakIo)) {
51
+ return DEFAULT_STREAK_IO;
52
+ }
53
+ return { ...DEFAULT_STREAK_IO, ...streakIo };
54
+ }
55
+
56
+ /**
57
+ * Best-effort journal record of a streak I/O failure (SP-824 / #314).
58
+ * @param {string} projectRoot
59
+ * @param {string|null|undefined} batchId
60
+ * @param {Record<string, unknown>} payload
61
+ */
62
+ function journalStreakIoFailure(projectRoot, batchId, payload) {
63
+ if (typeof batchId !== "string" || batchId.trim() === "") return;
64
+ try {
65
+ appendJournalEvent(projectRoot, batchId, "gate.streak_io_failed", payload);
66
+ } catch {
67
+ // Journaling is best-effort — never throw out of a persisted gate decision.
68
+ }
69
+ }
70
+
71
+ /** @param {unknown} error @returns {string} */
72
+ function errorMessage(error) {
73
+ return error instanceof Error ? error.message : String(error);
74
+ }
75
+
76
+ /**
77
+ * SP-824 / #314 — does ANY batch journal record a streak reset whose fail-closed
78
+ * recovery (streak file removal) also failed? Streak state is project-wide while
79
+ * journals are per-batch, so scan `.spine/runtime/<batchId>/journal/events.jsonl`
80
+ * (substring pre-filter keeps JSON parsing to matching lines only).
81
+ * @param {string} projectRoot
82
+ * @returns {boolean}
83
+ */
84
+ function journalHasUnrecoveredStreakReset(projectRoot) {
85
+ const runtimeDir = path.join(projectRoot, ".spine", "runtime");
86
+ /** @type {string[]} */
87
+ let batchDirNames;
88
+ try {
89
+ batchDirNames = fs
90
+ .readdirSync(runtimeDir, { withFileTypes: true })
91
+ .filter((entry) => entry.isDirectory())
92
+ .map((entry) => entry.name);
93
+ } catch {
94
+ return false; // no runtime dir → no journals → no recorded unrecovered reset
95
+ }
96
+ return batchDirNames.some((batchId) => {
97
+ /** @type {string} */
98
+ let content;
99
+ try {
100
+ content = fs.readFileSync(path.join(runtimeDir, batchId, "journal", "events.jsonl"), "utf-8");
101
+ } catch {
102
+ return false; // unreadable journal — keep scanning the others
103
+ }
104
+ return content.split("\n").some((line) => {
105
+ if (!line.includes("gate.streak_io_failed")) return false;
106
+ try {
107
+ const { type, payload } = JSON.parse(line);
108
+ return (
109
+ type === "gate.streak_io_failed" &&
110
+ payload?.op === "reset" &&
111
+ payload?.recovered === false
112
+ );
113
+ } catch {
114
+ return false; // skip malformed journal line
115
+ }
116
+ });
117
+ });
118
+ }
119
+
31
120
  /**
32
121
  * @param {string} projectRoot
33
122
  * @param {object} gate
@@ -82,38 +171,69 @@ function resolveGateCategory(gate) {
82
171
 
83
172
  /**
84
173
  * Persist consecutive-approval streak after a successful approve.
85
- * Failures must not undo the gate FSM decision.
86
- *
174
+ * Failures must not undo the gate FSM decision; they are journaled instead
175
+ * (SP-824 / #314). A failed increment only delays auto-approval — the safe
176
+ * direction — so no recovery is attempted.
87
177
  * @param {string} projectRoot
88
178
  * @param {object} gate
179
+ * @param {string} batchId
180
+ * @param {typeof DEFAULT_STREAK_IO} streakIo
89
181
  */
90
- function recordApprovalStreak(projectRoot, gate) {
182
+ function recordApprovalStreak(projectRoot, gate, batchId, streakIo) {
91
183
  const category = resolveGateCategory(gate);
184
+ const kind = typeof gate.kind === "string" && gate.kind.trim() !== "" ? gate.kind : null;
92
185
  try {
93
- incrementCategoryStreak(projectRoot, category);
94
- if (typeof gate.kind === "string" && gate.kind.trim() !== "") {
95
- incrementKindStreak(projectRoot, gate.kind);
186
+ streakIo.incrementCategoryStreak(projectRoot, category);
187
+ if (kind !== null) {
188
+ streakIo.incrementKindStreak(projectRoot, kind);
96
189
  }
97
- } catch {
190
+ } catch (error) {
98
191
  // Streak I/O must not reverse an already-persisted approval.
192
+ journalStreakIoFailure(projectRoot, batchId, {
193
+ op: "increment",
194
+ category,
195
+ kind,
196
+ error: errorMessage(error),
197
+ });
99
198
  }
100
199
  }
101
200
 
102
201
  /**
103
202
  * Reset streak counters after a reject (breaks consecutive-approval chain).
104
- *
203
+ * A failed reset would leave a stale consecutive-approval count that could
204
+ * unlock a later auto-approve despite the rejection, so this fails closed:
205
+ * best-effort removal of the whole streak store (missing file → zero counts).
105
206
  * @param {string} projectRoot
106
207
  * @param {object} gate
208
+ * @param {string} batchId
209
+ * @param {typeof DEFAULT_STREAK_IO} streakIo
107
210
  */
108
- function recordRejectStreakReset(projectRoot, gate) {
211
+ function recordRejectStreakReset(projectRoot, gate, batchId, streakIo) {
109
212
  const category = resolveGateCategory(gate);
213
+ const kind = typeof gate.kind === "string" && gate.kind.trim() !== "" ? gate.kind : null;
110
214
  try {
111
- resetCategoryStreak(projectRoot, category);
112
- if (typeof gate.kind === "string" && gate.kind.trim() !== "") {
113
- resetKindStreak(projectRoot, gate.kind);
215
+ streakIo.resetCategoryStreak(projectRoot, category);
216
+ if (kind !== null) {
217
+ streakIo.resetKindStreak(projectRoot, kind);
114
218
  }
115
- } catch {
219
+ } catch (error) {
116
220
  // Streak reset failure must not reverse a persisted rejection.
221
+ let recovered = true;
222
+ let recoveryError;
223
+ try {
224
+ streakIo.removeStreakFile(projectRoot);
225
+ } catch (rmError) {
226
+ recovered = false;
227
+ recoveryError = errorMessage(rmError);
228
+ }
229
+ journalStreakIoFailure(projectRoot, batchId, {
230
+ op: "reset",
231
+ category,
232
+ kind,
233
+ error: errorMessage(error),
234
+ recovered,
235
+ ...(recovered ? {} : { recoveryError }),
236
+ });
117
237
  }
118
238
  }
119
239
 
@@ -127,6 +247,7 @@ function recordRejectStreakReset(projectRoot, gate) {
127
247
  */
128
248
  export function approveIntegrateGate(ctx) {
129
249
  const { projectRoot, batchId, decidedBy = "human", postureEvaluation = null, synthesis } = ctx;
250
+ const streakIo = resolveStreakIo(ctx.streakIo);
130
251
  const gate = loadGateRecord(projectRoot, batchId);
131
252
 
132
253
  if (!gate) {
@@ -168,7 +289,7 @@ export function approveIntegrateGate(ctx) {
168
289
  const synthesisNote = typeof synthesis === "string" && synthesis.trim() !== "" ? synthesis : null;
169
290
  if (synthesisNote) gate.synthesis = synthesisNote;
170
291
  saveGateRecord(projectRoot, gate);
171
- recordApprovalStreak(projectRoot, gate);
292
+ recordApprovalStreak(projectRoot, gate, batchId, streakIo);
172
293
 
173
294
  /** @type {Record<string, unknown>} */
174
295
  const journalPayload = {
@@ -213,6 +334,7 @@ export function approveIntegrateGate(ctx) {
213
334
  */
214
335
  export function maybeAutoApproveIntegrateGate(ctx) {
215
336
  const { projectRoot, batchId, tags = [] } = ctx;
337
+ const streakIo = resolveStreakIo(ctx.streakIo);
216
338
  const config = ctx.config ?? loadSpineConfig(projectRoot).config ?? null;
217
339
  const gate = loadGateRecord(projectRoot, batchId);
218
340
 
@@ -236,6 +358,21 @@ export function maybeAutoApproveIntegrateGate(ctx) {
236
358
  ? postureConfig.categories[category]
237
359
  : { posture: POSTURES.LOCKED, autoApproveAfterN: null };
238
360
 
361
+ // SP-824 / #314 fail-closed: a journal-recorded unrecovered streak reset makes
362
+ // the project-wide streak state untrustworthy — checked before reading it.
363
+ if (journalHasUnrecoveredStreakReset(projectRoot)) {
364
+ return {
365
+ ok: true,
366
+ approved: false,
367
+ evaluation: { decision: "require-manual", reason: "streak_unreliable", tier: null },
368
+ optedIn,
369
+ category,
370
+ consecutiveApprovals: null,
371
+ reason: "streak_unreliable",
372
+ gate,
373
+ };
374
+ }
375
+
239
376
  const consecutiveApprovals = getCategoryStreak(projectRoot, category);
240
377
  /** @type {string[]} */
241
378
  const mergedTags = [];
@@ -275,6 +412,7 @@ export function maybeAutoApproveIntegrateGate(ctx) {
275
412
  batchId,
276
413
  decidedBy: "auto",
277
414
  postureEvaluation: evaluation,
415
+ streakIo,
278
416
  });
279
417
 
280
418
  return {
@@ -336,7 +474,8 @@ export function rejectIntegrateGate(ctx) {
336
474
  const synthesisNote = typeof synthesis === "string" && synthesis.trim() !== "" ? synthesis : null;
337
475
  if (synthesisNote) gate.synthesis = synthesisNote;
338
476
  saveGateRecord(projectRoot, gate);
339
- recordRejectStreakReset(projectRoot, gate);
477
+ const streakIo = resolveStreakIo(ctx.streakIo);
478
+ recordRejectStreakReset(projectRoot, gate, batchId, streakIo);
340
479
 
341
480
  appendJournalEvent(projectRoot, batchId, "gate.rejected", {
342
481
  gateId: gate.gateId,
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Merge-deletion materialization for the post-merge base sync (SP-830, #346).
3
+ * Opt-in per call via `applyDeletions` on syncPlumbingMergePathsToWorktree;
4
+ * the human `spine sync-base` flow does not opt in and keeps the skip (SP-784).
5
+ * Deliberately does not import from integrate-worktree.mjs (no import cycle).
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { execFileSync } from "node:child_process";
11
+ import { resolveGitCommitEnv } from "./git-commit-env.mjs";
12
+
13
+ /**
14
+ * Timeout detection for execFileSync `timeout` kills; shared with the sync loop.
15
+ * @param {unknown} err
16
+ * @returns {boolean}
17
+ */
18
+ export function isTimeoutError(err) {
19
+ if (!err || typeof err !== "object") return false;
20
+ return /** @type {any} */ (err).killed === true || /** @type {any} */ (err).code === "ETIMEDOUT";
21
+ }
22
+
23
+ /**
24
+ * Remove from the checkout a path the merged tree deleted (SP-830). Untracks it
25
+ * with `git rm --cached`. Regular files are only removed when their worktree
26
+ * content matches the index (`git diff --quiet`): an unmodified stale entry is
27
+ * the ref-move artifact integrate leaves behind, while a modified or deleted
28
+ * file is operator work and is left alone. A `160000` gitlink directory is
29
+ * always kept on disk — it may host a live nested worktree. Paths never present
30
+ * at baseSha return `{ removed: false }` (caller keeps today's skip). Git
31
+ * failures return `{ removed: false }`; timeouts are rethrown so the caller
32
+ * reports `timedOut` like its other git calls.
33
+ *
34
+ * @param {string} projectRoot
35
+ * @param {string} baseSha
36
+ * @param {string} filePath
37
+ * @param {{ timeoutMs?: number }} [options]
38
+ * @returns {{ removed: boolean, gitlink?: boolean }}
39
+ */
40
+ export function removeMergeDeletedPath(projectRoot, baseSha, filePath, { timeoutMs } = {}) {
41
+ let entry = "";
42
+ try {
43
+ entry = execFileSync("git", ["ls-tree", baseSha, "--", filePath], {
44
+ cwd: projectRoot,
45
+ encoding: "utf-8",
46
+ stdio: ["ignore", "pipe", "pipe"],
47
+ timeout: timeoutMs,
48
+ env: { ...process.env, ...resolveGitCommitEnv(projectRoot) },
49
+ });
50
+ } catch (err) {
51
+ if (isTimeoutError(err)) throw err;
52
+ return { removed: false };
53
+ }
54
+ if (!entry.trim()) return { removed: false };
55
+ const gitlink = entry.startsWith("160000");
56
+ if (!gitlink) {
57
+ try {
58
+ execFileSync("git", ["diff", "--quiet", "--", filePath], {
59
+ cwd: projectRoot,
60
+ encoding: "utf-8",
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ timeout: timeoutMs,
63
+ env: { ...process.env, ...resolveGitCommitEnv(projectRoot) },
64
+ });
65
+ } catch (err) {
66
+ if (isTimeoutError(err)) throw err;
67
+ // exit 1: worktree differs from index — operator edit or local deletion.
68
+ return { removed: false };
69
+ }
70
+ }
71
+ try {
72
+ execFileSync("git", ["rm", "-q", "--cached", "--ignore-unmatch", "--", filePath], {
73
+ cwd: projectRoot,
74
+ encoding: "utf-8",
75
+ stdio: ["ignore", "pipe", "pipe"],
76
+ timeout: timeoutMs,
77
+ env: { ...process.env, ...resolveGitCommitEnv(projectRoot) },
78
+ });
79
+ } catch (err) {
80
+ if (isTimeoutError(err)) throw err;
81
+ return { removed: false };
82
+ }
83
+ if (!gitlink) fs.rmSync(path.join(projectRoot, filePath), { force: true });
84
+ return { removed: true, gitlink };
85
+ }