pi-spine 2.30.0 → 2.32.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.
@@ -8,6 +8,7 @@ import {
8
8
  startBatchDetached,
9
9
  } from "../src/batch/detached-start.mjs";
10
10
  import { dismissBatch } from "../src/batch/lifecycle.mjs";
11
+ import { batchIdRejectionReason } from "../src/batch/batch-id.mjs";
11
12
  import { runBatchComplete } from "../src/cli/batch-complete.mjs";
12
13
  import { forceMergeWave, startBatch } from "../src/batch/engine.mjs";
13
14
  import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
@@ -158,8 +159,10 @@ export function parseBatchArgs(args) {
158
159
 
159
160
  let batchId = null;
160
161
  const batchIdx = args.indexOf("--batch");
161
- if (batchIdx >= 0 && args[batchIdx + 1]) {
162
- batchId = args[batchIdx + 1];
162
+ if (batchIdx >= 0) {
163
+ // SP-869 (#313): a bare `--batch` (flag without a value) must not fall
164
+ // through to active-batch fallbacks; capture "" so the validator rejects.
165
+ batchId = args[batchIdx + 1] ?? "";
163
166
  }
164
167
 
165
168
  let reason = null;
@@ -264,6 +267,17 @@ export async function runSpineBatch(options) {
264
267
  }
265
268
  const parsed = parseBatchArgs(args);
266
269
 
270
+ // SP-869 (#313): reject unsafe --batch IDs before any runtime path join.
271
+ if (parsed.batchId != null) {
272
+ const reason = batchIdRejectionReason(parsed.batchId);
273
+ if (reason) {
274
+ return {
275
+ exitCode: 1,
276
+ output: `Invalid batch ID ${JSON.stringify(String(parsed.batchId))}: ${reason}\n`,
277
+ };
278
+ }
279
+ }
280
+
267
281
  if (parsed.subcommand === "dismiss") {
268
282
  const result = dismissBatch({
269
283
  projectRoot,
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
8
8
  import { parseStrictArgs, strictArgsError } from "./spine-cli/cli-args.mjs";
9
+ import { validateBatchId } from "../src/batch/batch-id.mjs";
9
10
  import { loadBatchStateFile } from "../src/batch/reconcile.mjs";
10
11
  import {
11
12
  approveIntegrateGate,
@@ -79,7 +80,8 @@ export function formatGateHuman(result, json = false) {
79
80
  * @param {string|null} batchId
80
81
  */
81
82
  function resolveActiveBatchId(projectRoot, batchId) {
82
- if (batchId) return batchId;
83
+ // SP-869 (#313): reject unsafe --batch IDs before any .spine/runtime path join.
84
+ if (batchId) return validateBatchId(batchId);
83
85
  const loaded = loadBatchStateFile(projectRoot, null);
84
86
  if (!loaded.raw) return null;
85
87
  return String(loaded.raw.batchId ?? loaded.raw.id ?? "");
@@ -104,7 +106,27 @@ export function runSpineGate(options) {
104
106
  const action = parsed.positional[0] ?? "status";
105
107
  const reason = parsed.values.get("--reason") ?? null;
106
108
  const synthesis = parsed.values.get("--synthesis") ?? null;
107
- const batchId = resolveActiveBatchId(projectRoot, parsed.values.get("--batch") ?? null);
109
+
110
+ let batchId;
111
+ try {
112
+ batchId = resolveActiveBatchId(projectRoot, parsed.values.get("--batch") ?? null);
113
+ } catch (err) {
114
+ // SP-869 (#313): invalid --batch exits non-zero with a clear error instead
115
+ // of interpolating raw input into runtime paths.
116
+ const error = err instanceof Error ? err.message : String(err);
117
+ const result = {
118
+ ok: false,
119
+ exitCode: 2,
120
+ headline: "Invalid --batch ID",
121
+ suggestedCommand: "spine gate status --batch <ID>",
122
+ error,
123
+ };
124
+ return {
125
+ exitCode: result.exitCode,
126
+ output: formatGateHuman(result, flags.has("--json")),
127
+ result,
128
+ };
129
+ }
108
130
  if (!batchId) {
109
131
  const result = {
110
132
  ok: false,
@@ -1,4 +1,5 @@
1
1
  import { integrateOrchToBase } from "../src/batch/integrate.mjs";
2
+ import { validateBatchId } from "../src/batch/batch-id.mjs";
2
3
  import { parseStrictArgs, strictArgsError } from "./spine-cli/cli-args.mjs";
3
4
 
4
5
  const INTEGRATE_USAGE = `
@@ -41,11 +42,15 @@ export function formatIntegrateHuman(result, json = false) {
41
42
  if (result.mergePlan) {
42
43
  lines.push(` Plan: ${result.mergePlan}`);
43
44
  }
44
- if (result.gateRequired) {
45
- lines.push("", " Gate: approval required before integrate");
46
- }
47
45
  if (result.failureClass === "GateBlocked") {
46
+ // Integrate actually stopped for a pending/missing/rejected gate (#359).
48
47
  lines.push("", " Gate: integrate blocked until approved");
48
+ } else if (result.dryRun && result.gatePending) {
49
+ // Dry-run plan: approval will be required before the real merge.
50
+ lines.push("", " Gate: approval required before integrate");
51
+ } else if (result.ok && result.gateRequired && !result.gateForced) {
52
+ // Successful merge with a configured gate — it was satisfied, not pending (#359).
53
+ lines.push("", " Gate: approved");
49
54
  }
50
55
 
51
56
  lines.push("", ` → ${result.suggestedCommand}`);
@@ -83,6 +88,21 @@ export function runSpineIntegrate(options) {
83
88
  return { exitCode: 2, output: `${usageError}\n${INTEGRATE_USAGE}`, result: { ok: false, error: usageError } };
84
89
  }
85
90
 
91
+ // SP-869 (#313): reject unsafe --batch IDs before runtime path joins.
92
+ const batchArg = parsed.values.get("--batch") ?? null;
93
+ if (batchArg) {
94
+ try {
95
+ validateBatchId(batchArg);
96
+ } catch (err) {
97
+ const error = err instanceof Error ? err.message : String(err);
98
+ return {
99
+ exitCode: 2,
100
+ output: `${error}\n${INTEGRATE_USAGE}`,
101
+ result: { ok: false, error },
102
+ };
103
+ }
104
+ }
105
+
86
106
  const result = integrateOrchToBase({
87
107
  projectRoot,
88
108
  dryRun: flags.has("--dry-run"),
@@ -6,6 +6,7 @@ import {
6
6
  readJournalEvents,
7
7
  summarizeJournalEvent,
8
8
  } from "../src/batch/journal.mjs";
9
+ import { batchIdRejectionReason } from "../src/batch/batch-id.mjs";
9
10
 
10
11
  /**
11
12
  * @param {string} timestamp
@@ -90,7 +91,18 @@ const JOURNAL_USAGE =
90
91
  */
91
92
  function runJournalReplay(projectRoot, args) {
92
93
  const batchIdx = args.indexOf("--batch");
93
- const batchId = batchIdx >= 0 ? args[batchIdx + 1] : null;
94
+ const batchId = batchIdx >= 0 ? (args[batchIdx + 1] ?? "") : null;
95
+ // SP-869 (#313): reject unsafe --batch IDs (including a bare flag with no
96
+ // value, captured as "") before journal path joins.
97
+ if (batchId != null) {
98
+ const reason = batchIdRejectionReason(batchId);
99
+ if (reason) {
100
+ return {
101
+ exitCode: 1,
102
+ output: `Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}\n${JOURNAL_USAGE}`,
103
+ };
104
+ }
105
+ }
94
106
  const json = args.includes("--json");
95
107
 
96
108
  if (!batchId) {
@@ -130,7 +142,18 @@ function runJournalExport(projectRoot, args) {
130
142
  const exportUsage =
131
143
  "Usage: spine journal export --batch {id} --format markdown|jsonl [--output path]\n";
132
144
  const batchIdx = args.indexOf("--batch");
133
- const batchId = batchIdx >= 0 ? args[batchIdx + 1] : null;
145
+ const batchId = batchIdx >= 0 ? (args[batchIdx + 1] ?? "") : null;
146
+ // SP-869 (#313): reject unsafe --batch IDs (including a bare flag with no
147
+ // value, captured as "") before journal path joins.
148
+ if (batchId != null) {
149
+ const reason = batchIdRejectionReason(batchId);
150
+ if (reason) {
151
+ return {
152
+ exitCode: 1,
153
+ output: `Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}\n${exportUsage}`,
154
+ };
155
+ }
156
+ }
134
157
  const formatIdx = args.indexOf("--format");
135
158
  const format = formatIdx >= 0 ? args[formatIdx + 1] : null;
136
159
  const outputIdx = args.indexOf("--output");
@@ -4,6 +4,7 @@ import {
4
4
  resolveBatchStateFileForValidation,
5
5
  validateBatchState,
6
6
  } from "../src/batch/state.mjs";
7
+ import { batchIdRejectionReason } from "../src/batch/batch-id.mjs";
7
8
 
8
9
  /**
9
10
  * @param {object} options
@@ -22,10 +23,30 @@ export function runSpineState(options) {
22
23
  }
23
24
 
24
25
  const batchIdx = args.indexOf("--batch");
25
- const batchId = batchIdx >= 0 ? args[batchIdx + 1] : null;
26
+ // SP-869 (#313): a bare `--batch` (flag without a value) is captured as ""
27
+ // so the validator below rejects it instead of falling back silently.
28
+ const batchId = batchIdx >= 0 ? (args[batchIdx + 1] ?? "") : null;
26
29
  const json = args.includes("--json");
27
30
  const diagnose = args.includes("--diagnose");
28
31
 
32
+ // SP-869 (#313): reject unsafe --batch IDs before state file path joins.
33
+ if (batchId != null) {
34
+ const reason = batchIdRejectionReason(batchId);
35
+ if (reason) {
36
+ const message = `Invalid batch ID ${JSON.stringify(String(batchId))}: ${reason}`;
37
+ if (json) {
38
+ return {
39
+ exitCode: 1,
40
+ output: `${JSON.stringify({ ok: false, error: message }, null, 2)}\n`,
41
+ };
42
+ }
43
+ return {
44
+ exitCode: 1,
45
+ output: `❌ ${message}\n → spine state validate --batch <ID>\n`,
46
+ };
47
+ }
48
+ }
49
+
29
50
  const resolved = resolveBatchStateFileForValidation(projectRoot, batchId);
30
51
  if (!resolved.path) {
31
52
  const message = resolved.error ?? "No batch-state file found";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.30.0",
3
+ "version": "2.32.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,9 +72,9 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^1.4.0",
75
+ "@earendil-works/pi-coding-agent": "^1.5.2",
76
76
  "@types/node": "^22.20.4",
77
- "eslint": "^10.14.0",
77
+ "eslint": "^10.15.0",
78
78
  "globals": "^17.14.0",
79
79
  "typebox": "1.3.34",
80
80
  "typescript": "6.0.3"
@@ -143,10 +143,37 @@ export function releaseResumeHandoffLock(projectRoot, batchId) {
143
143
  */
144
144
  const LIVE_RESUME_OWNER_PHASES = new Set(["running", "gating"]);
145
145
 
146
+ /**
147
+ * True when the engine acknowledged the current pause episode: an
148
+ * `engine.pause_observed` journal event exists after the latest `batch.resumed`
149
+ * (SP-861 / #376). `pauseBatch` journals `batch.paused` only after the engine
150
+ * persisted phase: paused, and that engine-side persist also journals
151
+ * `engine.pause_observed` right before the engine loop stops — so after a
152
+ * confirmed pause the recorded enginePid belongs to a winding-down process that
153
+ * no longer drives the batch, i.e. a stale attached-child bookkeeping bit, not
154
+ * a live owner.
155
+ *
156
+ * @param {string} projectRoot
157
+ * @param {string} batchId
158
+ */
159
+ function hasEngineAcknowledgedPause(projectRoot, batchId) {
160
+ const events = readJournalEvents(projectRoot, batchId);
161
+ let lastResumedIdx = -1;
162
+ let lastObservedIdx = -1;
163
+ for (let i = 0; i < events.length; i++) {
164
+ const type = String(events[i].type ?? "");
165
+ if (type === "batch.resumed") lastResumedIdx = i;
166
+ if (type === "engine.pause_observed") lastObservedIdx = i;
167
+ }
168
+ return lastObservedIdx >= 0 && lastObservedIdx > lastResumedIdx;
169
+ }
170
+
146
171
  /**
147
172
  * Reject a second attached engine when resilience.enginePid is alive (SP-434, GitHub #89).
148
173
  * Serialized forced resume handoff when another resume --force is in flight (SP-533, #167).
149
174
  * Fail-fast while a live engine already owns a running batch (SP-660, #207).
175
+ * A paused batch whose engine acknowledged the pause hands recovery to the
176
+ * operator instead of refusing (SP-861, #376).
150
177
  *
151
178
  * @param {object} params
152
179
  * @param {string} params.projectRoot
@@ -239,6 +266,22 @@ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, o
239
266
  };
240
267
  }
241
268
 
269
+ // A paused batch whose engine acknowledged the pause has no live owner
270
+ // (SP-861 / #376): the recorded pid is a stale attached-child bookkeeping bit
271
+ // left behind by the pause handoff. Detached recovery must not be refused
272
+ // with a false "Attached batch engine already running" — clear the stale
273
+ // ownership instead so the resuming engine takes over cleanly. A live pid on
274
+ // a non-paused batch (engine still driving) keeps the refuse below.
275
+ if (fromPhase === "paused" && hasEngineAcknowledgedPause(projectRoot, batchId)) {
276
+ clearBatchEnginePid(state);
277
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
278
+ appendJournalEvent(projectRoot, batchId, "engine.stale_ownership_cleared", {
279
+ stalePid: enginePid,
280
+ fromPhase,
281
+ });
282
+ return releaseResumeLock ? { ok: true, releaseResumeLock } : { ok: true };
283
+ }
284
+
242
285
  const operationLabel = operation === "start" ? "start" : "resume";
243
286
  const output =
244
287
  `Attached batch engine already running (PID ${enginePid}, batch ${batchId}).\n` +
@@ -68,6 +68,61 @@ export function validateBatchId(batchId) {
68
68
  return /** @type {string} */ (batchId);
69
69
  }
70
70
 
71
+ /**
72
+ * Allowlist pattern for review baselines (SP-869, issue #313).
73
+ *
74
+ * A baseline is interpolated into `git diff <baseline>..HEAD` argv
75
+ * (review-scope) and reviewer prompt text (review-step), so it must be a safe
76
+ * git object name: a full/short commit SHA or a plain ref (`main`,
77
+ * `origin/main`, `v1.2.3`). The first character must be alphanumeric so
78
+ * option-like values (`-`, `--output=…`) and absolute/traversal paths can
79
+ * never pass; the remainder allows only letters, digits, dot, dash, and
80
+ * slash. Whitespace, newlines, backslashes, and revision metacharacters
81
+ * (`~`, `^`, `:`, `@{`) are excluded.
82
+ */
83
+ export const REVIEW_BASELINE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
84
+
85
+ /**
86
+ * @param {unknown} baseline
87
+ * @returns {string|null} rejection reason, or null when the baseline is valid
88
+ */
89
+ export function reviewBaselineRejectionReason(baseline) {
90
+ if (typeof baseline !== "string" || baseline.trim().length === 0) {
91
+ return "must be a non-empty string";
92
+ }
93
+ if (/^-/.test(baseline)) {
94
+ return "must not look like a command-line option";
95
+ }
96
+ if (/\s/.test(baseline)) {
97
+ return "must not contain whitespace or newlines";
98
+ }
99
+ if (baseline.includes("..")) {
100
+ return 'must not contain ".." path traversal sequences';
101
+ }
102
+ if (!REVIEW_BASELINE_PATTERN.test(baseline)) {
103
+ return (
104
+ `must match ${REVIEW_BASELINE_PATTERN} ` +
105
+ "(full/short commit SHA or plain git ref: letters, digits, dot, dash, slash)"
106
+ );
107
+ }
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * Assert a review baseline is safe for `git diff <baseline>..HEAD` argv and
113
+ * reviewer prompt text; throw otherwise (SP-869, issue #313).
114
+ *
115
+ * @param {unknown} baseline
116
+ * @returns {string} the validated baseline
117
+ */
118
+ export function validateReviewBaseline(baseline) {
119
+ const reason = reviewBaselineRejectionReason(baseline);
120
+ if (reason) {
121
+ throw new Error(`Invalid review baseline ${JSON.stringify(String(baseline))}: ${reason}`);
122
+ }
123
+ return /** @type {string} */ (baseline);
124
+ }
125
+
71
126
  const MAX_UNIQUIFY_ATTEMPTS = 64;
72
127
 
73
128
  /**
@@ -5,7 +5,6 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { setTimeout as sleep } from "node:timers/promises";
8
- import picomatch from "picomatch";
9
8
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
9
  import {
11
10
  isBaseFileScopeSatisfied,
@@ -24,6 +23,7 @@ import {
24
23
  import {
25
24
  NPM_TEST_DASH_DASH_RE,
26
25
  TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
26
+ findArtifactMatch,
27
27
  } from "../tasks/validate-contract-warn.mjs";
28
28
  import { formatRefusedContractMetacharMessage, isRefusedContractMetacharCommand } from "../tasks/packet/parse-prompt.mjs";
29
29
  import { buildContractTestEnv, runShellCommandAsync } from "./contract-spawn.mjs";
@@ -209,48 +209,6 @@ async function resolveLineCoverage(worktreePath, parsedContract, config, testCom
209
209
  return parseAggregateLineCoverage(output);
210
210
  }
211
211
 
212
- /**
213
- * @param {string} worktreePath
214
- * @param {string} artifactPattern
215
- * @returns {{ ok: boolean, matchedPath?: string }}
216
- */
217
- function findArtifactMatch(worktreePath, artifactPattern) {
218
- const normalized = String(artifactPattern ?? "").replace(/\\/g, "/");
219
- if (!normalized) {
220
- return { ok: false };
221
- }
222
-
223
- if (!/[*?[\]{}]/.test(normalized)) {
224
- const fullPath = path.join(worktreePath, normalized);
225
- return fs.existsSync(fullPath) ? { ok: true, matchedPath: normalized } : { ok: false };
226
- }
227
-
228
- const baseDir = path.dirname(normalized);
229
- const searchRoot = path.join(worktreePath, baseDir);
230
- if (!fs.existsSync(searchRoot)) {
231
- return { ok: false };
232
- }
233
-
234
- /** @type {Array<{ abs: string, rel: string }>} */
235
- const stack = [{ abs: searchRoot, rel: baseDir === "." ? "" : baseDir }];
236
- while (stack.length > 0) {
237
- const { abs, rel } = /** @type {{ abs: string, rel: string }} */ (stack.pop());
238
- for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
239
- const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
240
- const entryAbs = path.join(abs, entry.name);
241
- if (entry.isDirectory()) {
242
- stack.push({ abs: entryAbs, rel: entryRel });
243
- continue;
244
- }
245
- if (picomatch(normalized, { dot: true })(entryRel)) {
246
- return { ok: true, matchedPath: entryRel };
247
- }
248
- }
249
- }
250
-
251
- return { ok: false };
252
- }
253
-
254
212
  /**
255
213
  * Prepare lane worktree before contract testCommand (Flutter analyzer hygiene #78).
256
214
  *
@@ -298,6 +256,29 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
298
256
  maxBuffer: CONTRACT_TEST_COMMAND_MAX_BUFFER,
299
257
  });
300
258
  const indexAndWorktreeFiles = diffResult.exitCode === 0 ? diffResult.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean) : [];
259
+ // Fail-closed (#309): a failed/timed-out `git diff` must not pass must-not-change
260
+ // on an empty file list. Only enforced when the contract declares patterns —
261
+ // without patterns there is no scope to verify either way.
262
+ const mustNotChangePatterns = parsedContract.fileScopeMustNotChange ?? [];
263
+ const diffFailed = diffResult.exitCode !== 0;
264
+
265
+ // Fail-closed (#309): `listChangedFiles` (contract-parse.mjs) swallows git
266
+ // errors into an empty or partial committed-file list, so a failed committed
267
+ // lookup could let must-not-change pass on incomplete evidence. Re-run the
268
+ // same committed range with a visible exit code — gated on declared
269
+ // must-not-change patterns (same scoping as the diffFailed gate).
270
+ const scopedSince = String(sinceCommit ?? "").trim();
271
+ const committedRange = scopedSince ? `${scopedSince}..HEAD` : `${baseBranch}...HEAD`;
272
+ const committedProbeCommand = `git diff --name-only ${committedRange}`;
273
+ const committedProbe = mustNotChangePatterns.length > 0 &&
274
+ !isRefusedContractMetacharCommand(committedProbeCommand)
275
+ ? await runShellCommandAsync(worktreePath, committedProbeCommand, {
276
+ timeoutMs: 30 * 1000,
277
+ maxBuffer: CONTRACT_TEST_COMMAND_MAX_BUFFER,
278
+ })
279
+ : null;
280
+ const committedLookupFailed = mustNotChangePatterns.length > 0 &&
281
+ (committedProbe == null || committedProbe.exitCode !== 0);
301
282
 
302
283
  const changedFiles = [...new Set([...committedFiles, ...indexAndWorktreeFiles])];
303
284
 
@@ -424,21 +405,46 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
424
405
  });
425
406
  }
426
407
 
427
- for (const pattern of parsedContract.fileScopeMustNotChange ?? []) {
428
- const forbidden = changedFiles.filter((file) => matchesContractPattern(file, pattern));
429
- if (forbidden.length === 0) {
430
- checks.push({
431
- field: "fileScopeMustNotChange",
432
- ok: true,
433
- message: `fileScopeMustNotChange respected: ${pattern}`,
434
- });
435
- } else {
436
- for (const file of forbidden) {
408
+ if (mustNotChangePatterns.length > 0 && (diffFailed || committedLookupFailed)) {
409
+ const failureReasons = [];
410
+ if (diffFailed) {
411
+ failureReasons.push(
412
+ `git diff --name-only HEAD failed (${
413
+ diffResult.timedOut ? "timed out" : `exit ${diffResult.exitCode}`
414
+ })`,
415
+ );
416
+ }
417
+ if (committedLookupFailed) {
418
+ failureReasons.push(
419
+ committedProbe == null
420
+ ? `git diff --name-only ${committedRange} refused (unsafe range)`
421
+ : `git diff --name-only ${committedRange} failed (${
422
+ committedProbe.timedOut ? "timed out" : `exit ${committedProbe.exitCode}`
423
+ })`,
424
+ );
425
+ }
426
+ checks.push({
427
+ field: "fileScopeMustNotChange",
428
+ ok: false,
429
+ message: `Contract fileScopeMustNotChange: ${failureReasons.join("; ")} — cannot verify must-not-change scope, failing closed (#309)`,
430
+ });
431
+ } else {
432
+ for (const pattern of mustNotChangePatterns) {
433
+ const forbidden = changedFiles.filter((file) => matchesContractPattern(file, pattern));
434
+ if (forbidden.length === 0) {
437
435
  checks.push({
438
436
  field: "fileScopeMustNotChange",
439
- ok: false,
440
- message: `Contract fileScopeMustNotChange: forbidden change ${file}`,
437
+ ok: true,
438
+ message: `fileScopeMustNotChange respected: ${pattern}`,
441
439
  });
440
+ } else {
441
+ for (const file of forbidden) {
442
+ checks.push({
443
+ field: "fileScopeMustNotChange",
444
+ ok: false,
445
+ message: `Contract fileScopeMustNotChange: forbidden change ${file}`,
446
+ });
447
+ }
442
448
  }
443
449
  }
444
450
  }
@@ -471,7 +477,9 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
471
477
  ok: match.ok,
472
478
  message: match.ok
473
479
  ? `artifact exists: ${match.matchedPath ?? artifactPath}`
474
- : `Contract artifactsMustExist: missing ${artifactPath}`,
480
+ : match.unsafe
481
+ ? `Contract artifactsMustExist: rejected unsafe pattern ${artifactPath} — parent-directory traversal outside the lane worktree is not allowed (#309)`
482
+ : `Contract artifactsMustExist: missing ${artifactPath}`,
475
483
  });
476
484
  }
477
485
 
@@ -19,6 +19,7 @@ import {
19
19
  incrementKindStreak,
20
20
  resetCategoryStreak,
21
21
  resetKindStreak,
22
+ withGatePostureStreakLock,
22
23
  } from "./gate-posture-streak.mjs";
23
24
  import { gateRecordPath, loadGateRecord } from "./gate-evidence-read.mjs";
24
25
  import { appendJournalEvent } from "./journal.mjs";
@@ -373,61 +374,61 @@ export function maybeAutoApproveIntegrateGate(ctx) {
373
374
  };
374
375
  }
375
376
 
376
- const consecutiveApprovals = getCategoryStreak(projectRoot, category);
377
- /** @type {string[]} */
378
- const mergedTags = [];
379
- if (Array.isArray(gate.tags)) {
380
- for (const tag of gate.tags) {
381
- if (typeof tag === "string") mergedTags.push(tag);
377
+ // SP-868 / #314: streak read → decision → auto-approve + increment must be
378
+ // atomic against concurrent locked streak RMWs, or a stale high count read
379
+ // before a reset could unlock auto-approve. Lock-acquisition failure
380
+ // propagates (no auto-approve happened — fail-closed), matching batch-state
381
+ // writer behavior; production streak I/O re-enters this hold harmlessly.
382
+ return withGatePostureStreakLock(projectRoot, () => {
383
+ const consecutiveApprovals = getCategoryStreak(projectRoot, category);
384
+ const mergedTags = [...(Array.isArray(gate.tags) ? gate.tags : []), ...tags].filter(
385
+ (tag) => typeof tag === "string",
386
+ );
387
+
388
+ const evaluation = evaluateGatePosture({
389
+ category,
390
+ posture: categoryEntry.posture,
391
+ autoApproveAfterN: categoryEntry.autoApproveAfterN,
392
+ consecutiveApprovals,
393
+ tags: mergedTags,
394
+ alwaysBreakOn: postureConfig.alwaysBreakOn,
395
+ });
396
+
397
+ if (evaluation.decision !== "allow-auto") {
398
+ return {
399
+ ok: true,
400
+ approved: false,
401
+ evaluation,
402
+ optedIn,
403
+ category,
404
+ consecutiveApprovals,
405
+ reason: evaluation.reason,
406
+ gate,
407
+ };
382
408
  }
383
- }
384
- for (const tag of tags) {
385
- if (typeof tag === "string") mergedTags.push(tag);
386
- }
387
409
 
388
- const evaluation = evaluateGatePosture({
389
- category,
390
- posture: categoryEntry.posture,
391
- autoApproveAfterN: categoryEntry.autoApproveAfterN,
392
- consecutiveApprovals,
393
- tags: mergedTags,
394
- alwaysBreakOn: postureConfig.alwaysBreakOn,
395
- });
410
+ const approved = approveIntegrateGate({
411
+ projectRoot,
412
+ batchId,
413
+ decidedBy: "auto",
414
+ postureEvaluation: evaluation,
415
+ streakIo,
416
+ });
396
417
 
397
- if (evaluation.decision !== "allow-auto") {
398
418
  return {
399
- ok: true,
400
- approved: false,
419
+ ok: approved.ok,
420
+ exitCode: approved.exitCode,
421
+ approved: approved.ok === true,
401
422
  evaluation,
402
423
  optedIn,
403
424
  category,
404
- consecutiveApprovals,
405
- reason: evaluation.reason,
406
- gate,
425
+ decidedBy: "auto",
426
+ gate: approved.gate ?? gate,
427
+ headline: approved.headline,
428
+ error: approved.error,
429
+ blockers: approved.blockers,
407
430
  };
408
- }
409
-
410
- const approved = approveIntegrateGate({
411
- projectRoot,
412
- batchId,
413
- decidedBy: "auto",
414
- postureEvaluation: evaluation,
415
- streakIo,
416
431
  });
417
-
418
- return {
419
- ok: approved.ok,
420
- exitCode: approved.exitCode,
421
- approved: approved.ok === true,
422
- evaluation,
423
- optedIn,
424
- category,
425
- decidedBy: "auto",
426
- gate: approved.gate ?? gate,
427
- headline: approved.headline,
428
- error: approved.error,
429
- blockers: approved.blockers,
430
- };
431
432
  }
432
433
 
433
434
  /**