pi-spine 2.31.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.31.0",
3
+ "version": "2.32.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -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
  /**
@@ -8,6 +8,7 @@
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
10
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
11
+ import { withBatchStateLock } from "./batch-state-lock.mjs";
11
12
  import { GATE_CATEGORIES } from "./gate-posture-defaults.mjs";
12
13
 
13
14
  /** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
@@ -33,6 +34,33 @@ export const GATE_POSTURE_STREAK_REL = path.join(
33
34
 
34
35
  const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
35
36
 
37
+ /**
38
+ * SP-868 / #314 — serialize streak read-modify-write across processes.
39
+ *
40
+ * The streak store is project-wide JSON under `.spine/runtime/` while approve /
41
+ * reject / auto-approve decisions run in separate processes (CLI, engine,
42
+ * supervisor). Without a lock, a concurrent increment and reset can both read
43
+ * the same prev count and the last writer wins whole-file — a lost reset leaves
44
+ * a stale high streak that unlocks auto-approve early.
45
+ *
46
+ * Uses the same project-local lock primitive as the batch-state writers
47
+ * (`withBatchStateLock`: exclusive lock file published via temp + `linkSync`,
48
+ * PID-liveness stale breaking, token-gated release, per-process re-entrancy).
49
+ * Sharing that lock file also serializes streak RMWs against batch-state
50
+ * writers, and any caller already inside a batch-state critical section
51
+ * composes re-entrantly instead of deadlocking. Streak critical sections never
52
+ * acquire the resume handoff lock, so the SP-722 lock-ordering rules hold.
53
+ *
54
+ * @template T
55
+ * @param {string} projectRoot
56
+ * @param {() => T} fn synchronous critical section
57
+ * @param {{ timeoutMs?: number }} [options]
58
+ * @returns {T} `fn`'s return value
59
+ */
60
+ export function withGatePostureStreakLock(projectRoot, fn, options = {}) {
61
+ return /** @type {T} */ (withBatchStateLock(projectRoot, fn, options));
62
+ }
63
+
36
64
  /**
37
65
  * Absolute path to the streak JSON file.
38
66
  * @param {string} projectRoot
@@ -182,23 +210,27 @@ export function getKindStreak(projectRoot, kind) {
182
210
 
183
211
  /**
184
212
  * Increment category streak after an approval. Returns the new count.
213
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
185
214
  * @param {string} projectRoot
186
215
  * @param {GateCategory | string} category
187
216
  * @returns {number}
188
217
  */
189
218
  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;
219
+ return withGatePostureStreakLock(projectRoot, () => {
220
+ const state = loadGatePostureStreaks(projectRoot);
221
+ const prevRaw = state.categories[category];
222
+ const prev =
223
+ typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
224
+ const next = prev + 1;
225
+ state.categories[category] = next;
226
+ saveGatePostureStreaks(projectRoot, state);
227
+ return next;
228
+ });
198
229
  }
199
230
 
200
231
  /**
201
232
  * Increment kind streak after an approval. Returns the new count.
233
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
202
234
  * @param {string} projectRoot
203
235
  * @param {string} kind
204
236
  * @returns {number}
@@ -207,40 +239,48 @@ export function incrementKindStreak(projectRoot, kind) {
207
239
  if (typeof kind !== "string" || kind.trim() === "") {
208
240
  throw new Error("gate posture kind streak key must be a non-empty string");
209
241
  }
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;
242
+ return withGatePostureStreakLock(projectRoot, () => {
243
+ const state = loadGatePostureStreaks(projectRoot);
244
+ const prevRaw = state.kinds[kind];
245
+ const prev =
246
+ typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
247
+ const next = prev + 1;
248
+ state.kinds[kind] = next;
249
+ saveGatePostureStreaks(projectRoot, state);
250
+ return next;
251
+ });
218
252
  }
219
253
 
220
254
  /**
221
255
  * Reset category streak on reject or manual break.
256
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
222
257
  * @param {string} projectRoot
223
258
  * @param {GateCategory | string} category
224
259
  * @returns {number} Always 0 after reset
225
260
  */
226
261
  export function resetCategoryStreak(projectRoot, category) {
227
- const state = loadGatePostureStreaks(projectRoot);
228
- state.categories[category] = 0;
229
- saveGatePostureStreaks(projectRoot, state);
230
- return 0;
262
+ return withGatePostureStreakLock(projectRoot, () => {
263
+ const state = loadGatePostureStreaks(projectRoot);
264
+ state.categories[category] = 0;
265
+ saveGatePostureStreaks(projectRoot, state);
266
+ return 0;
267
+ });
231
268
  }
232
269
 
233
270
  /**
234
271
  * Reset kind streak on reject or manual break.
272
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
235
273
  * @param {string} projectRoot
236
274
  * @param {string} kind
237
275
  * @returns {number} Always 0 after reset
238
276
  */
239
277
  export function resetKindStreak(projectRoot, kind) {
240
- const state = loadGatePostureStreaks(projectRoot);
241
- state.kinds[kind] = 0;
242
- saveGatePostureStreaks(projectRoot, state);
243
- return 0;
278
+ return withGatePostureStreakLock(projectRoot, () => {
279
+ const state = loadGatePostureStreaks(projectRoot);
280
+ state.kinds[kind] = 0;
281
+ saveGatePostureStreaks(projectRoot, state);
282
+ return 0;
283
+ });
244
284
  }
245
285
 
246
286
  /**
@@ -249,7 +289,11 @@ export function resetKindStreak(projectRoot, kind) {
249
289
  * @returns {GatePostureStreakState}
250
290
  */
251
291
  export function resetAllStreaks(projectRoot) {
252
- return saveGatePostureStreaks(projectRoot, emptyStreakState());
292
+ // Locked so a concurrent locked increment's read cannot straddle this whole
293
+ // store replacement and resurrect a stale-high count over it (SP-868 / #314).
294
+ return withGatePostureStreakLock(projectRoot, () =>
295
+ saveGatePostureStreaks(projectRoot, emptyStreakState()),
296
+ );
253
297
  }
254
298
 
255
299
  /**
@@ -422,6 +422,7 @@ export function integrateOrchToBase(ctx) {
422
422
  mergeCommit,
423
423
  commitsAhead,
424
424
  gateRequired: gateCheck.required ?? false,
425
+ gateForced: gateCheck.forced ?? false,
425
426
  headline: `Integrated ${orchBranch} into ${baseBranch}`,
426
427
  suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
427
428
  alternatives: waiting
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { parsePrompt } from "../tasks/packet/parse-prompt.mjs";
9
+ import { validateReviewBaseline } from "./batch-id.mjs";
9
10
 
10
11
  /**
11
12
  * Paths excluded from reviewer glob scope (runtime artifacts, not product code).
@@ -73,6 +74,8 @@ export function resolvePlanReviewScopePaths(taskFolder) {
73
74
  * @returns {string[]}
74
75
  */
75
76
  export function resolveCodeReviewScopePaths(worktreePath, baseline, runGit = defaultRunGit) {
77
+ // SP-869 (#313): fail closed on unsafe baselines before git argv use.
78
+ if (baseline) validateReviewBaseline(baseline);
76
79
  const args = baseline ? ["diff", "--name-only", `${baseline}..HEAD`] : ["diff", "--name-only"];
77
80
  try {
78
81
  const output = runGit("git", args, worktreePath);
@@ -11,6 +11,7 @@ import { appendJournalEvent } from "./journal.mjs";
11
11
  import { loadSpineBatchState } from "./state.mjs";
12
12
  import { buildReviewerContext } from "../config/reviewer-context.mjs";
13
13
  import { resolveReviewScopePaths } from "./review-scope.mjs";
14
+ import { validateReviewBaseline } from "./batch-id.mjs";
14
15
  import { commandExists as pathCommandExists } from "../util/command-exists.mjs";
15
16
  import {
16
17
  ARTIFACT_READY_HONOR_REASON,
@@ -161,6 +162,8 @@ export function buildReviewRequest({
161
162
  ].join("\n");
162
163
  }
163
164
 
165
+ // SP-869 (#313): fail closed on unsafe baselines before prompt interpolation.
166
+ if (baseline) validateReviewBaseline(baseline);
164
167
  const diffNamesCmd = baseline ? `git diff ${baseline}..HEAD --name-only` : "git diff --name-only";
165
168
  const diffCmd = baseline ? `git diff ${baseline}..HEAD` : "git diff";
166
169
 
@@ -20,6 +20,7 @@ import {
20
20
  import { redactSecretsDeep, redactTextSecrets } from "../util/secret-redact.mjs";
21
21
  import { computePendingTasks } from "../batch/resume-multi-validate.mjs";
22
22
  import { formatJournalTailEntry } from "../dashboard/snapshot.mjs";
23
+ import { batchIdRejectionReason } from "../batch/batch-id.mjs";
23
24
 
24
25
  const JOURNAL_TAIL_LIMIT = 10;
25
26
 
@@ -429,7 +430,9 @@ export function parseHandoffArgs(argv) {
429
430
  const args = { batchId: null, json: false };
430
431
  for (let i = 0; i < argv.length; i++) {
431
432
  const arg = argv[i];
432
- if (arg === "--batch") args.batchId = argv[++i] ?? null;
433
+ // SP-869 (#313): a bare `--batch` (flag without a value) is captured as ""
434
+ // so the validator below rejects it instead of falling back silently.
435
+ if (arg === "--batch") args.batchId = argv[++i] ?? "";
433
436
  else if (arg === "--json") args.json = true;
434
437
  }
435
438
  return args;
@@ -443,6 +446,16 @@ export function parseHandoffArgs(argv) {
443
446
  export function runSpineHandoff(options) {
444
447
  const { projectRoot, args: argv = [] } = options;
445
448
  const args = parseHandoffArgs(argv);
449
+ // SP-869 (#313): reject unsafe --batch IDs before archive path joins.
450
+ if (args.batchId != null) {
451
+ const reason = batchIdRejectionReason(args.batchId);
452
+ if (reason) {
453
+ return {
454
+ exitCode: 1,
455
+ output: `Invalid batch ID ${JSON.stringify(String(args.batchId))}: ${reason}\n`,
456
+ };
457
+ }
458
+ }
446
459
  const data = assembleHandoffData(projectRoot, args.batchId ?? undefined);
447
460
  const handoffPath = path.resolve(projectRoot, data.handoffPath ?? resolveHandoffPath(projectRoot));
448
461
  const markdown = renderHandoffMarkdown(data);
@@ -39,11 +39,16 @@ export const RULES_PROFILE_REL_PATH = ".spine/rules-profile.json";
39
39
  * @property {RulesProfileDiscovery} discovery
40
40
  */
41
41
 
42
- /** Built-in profile when `.spine/rules-profile.json` is missing. */
42
+ /**
43
+ * Built-in profile when `.spine/rules-profile.json` is missing.
44
+ * SP-872: worker `alwaysInclude` is empty — spine-native workers get their
45
+ * context from `alwaysApply` rules + glob matching. Taskplane rules are opt-in
46
+ * via an explicit `alwaysInclude` in the project profile (#344).
47
+ */
43
48
  export const DEFAULT_RULES_PROFILE = Object.freeze({
44
49
  profileVersion: 1,
45
50
  worker: Object.freeze({
46
- alwaysInclude: Object.freeze(["taskplane-worker-cursor.mdc"]),
51
+ alwaysInclude: Object.freeze([]),
47
52
  neverInclude: Object.freeze([]),
48
53
  globMatch: true,
49
54
  }),
@@ -15,13 +15,16 @@ import {
15
15
  import { loadRulesProfile } from "./cursor-rules/profile.mjs";
16
16
  import { selectRulesForWorker } from "./cursor-rules/select.mjs";
17
17
 
18
- /** Default injected standards for pi-spine / JS-CLI projects (matches bootstrap checklist). */
18
+ /**
19
+ * Default injected standards for pi-spine / JS-CLI projects (matches bootstrap
20
+ * checklist). SP-872: Taskplane authoring/worker rules removed — spine-native
21
+ * defaults only; projects needing Taskplane opt in via `config.standards`
22
+ * (SP-093 superseded init seeding of this list; kept for static-context users).
23
+ */
19
24
  export const DEFAULT_SPINE_INIT_STANDARDS = [
20
25
  ".cursor/rules/javascript-3-development-standards.mdc",
21
26
  ".cursor/rules/general-llm-anti-patterns.mdc",
22
27
  ".cursor/rules/critical-rules-quick-reference.mdc",
23
- ".cursor/rules/taskplane-task-authoring.mdc",
24
- ".cursor/rules/taskplane-worker-cursor.mdc",
25
28
  ];
26
29
 
27
30
  export const DEFAULT_WORKER_CONTEXT_BYTE_CAP = 32_768;
@@ -19,6 +19,9 @@ export const DEFAULT_DASHBOARD_HOST = "127.0.0.1";
19
19
  export const DEFAULT_DASHBOARD_PORT = 8109;
20
20
  export const DEFAULT_DASHBOARD_POLL_MS = 2000;
21
21
 
22
+ /** Maximum concurrent SSE clients before new connections get 503. */
23
+ export const MAX_DASHBOARD_SSE_CLIENTS = 32;
24
+
22
25
  const STATIC_ROUTES = {
23
26
  "/": { file: "index.html", contentType: "text/html; charset=utf-8" },
24
27
  "/dashboard.css": { file: "dashboard.css", contentType: "text/css; charset=utf-8" },
@@ -76,6 +79,40 @@ export function assertLoopbackHost(host) {
76
79
  }
77
80
  }
78
81
 
82
+ /**
83
+ * Request-level Host allowlist (DNS-rebinding defense, #316).
84
+ *
85
+ * The bind host is loopback-checked separately via `assertLoopbackHost`; this
86
+ * guards the request `Host` header, which a browser sets from the page origin
87
+ * and cannot be overridden by attacker script. Only `127.0.0.1`, `localhost`,
88
+ * or those hostnames with an explicit port matching the listen port are
89
+ * allowed. Everything else — including IPv6 literals and look-alike domains —
90
+ * is rejected (deny by default).
91
+ *
92
+ * @param {string | undefined} hostHeader Raw `Host` header value.
93
+ * @param {number | undefined} listenPort Actual bound port (e.g. from `req.socket.localPort`).
94
+ * @returns {boolean} True when the Host header is loopback-only and port-consistent.
95
+ */
96
+ export function isAllowedRequestHost(hostHeader, listenPort) {
97
+ const raw = String(hostHeader ?? "")
98
+ .trim()
99
+ .toLowerCase();
100
+ if (raw === "") return false;
101
+
102
+ let hostname = raw;
103
+ let portSuffix = "";
104
+ const portMatch = raw.match(/^(.+):(\d+)$/);
105
+ if (portMatch) {
106
+ hostname = portMatch[1];
107
+ portSuffix = portMatch[2];
108
+ }
109
+
110
+ if (hostname.startsWith("[")) return false; // IPv6 literals are not allowlisted
111
+ if (hostname !== "127.0.0.1" && hostname !== "localhost") return false;
112
+ if (portSuffix === "") return true;
113
+ return Number(portSuffix) === Number(listenPort ?? DEFAULT_DASHBOARD_PORT);
114
+ }
115
+
79
116
  /**
80
117
  * @typedef {object} DashboardSseClient
81
118
  * @property {import("node:http").ServerResponse} res
@@ -88,7 +125,8 @@ export function assertLoopbackHost(host) {
88
125
  * @param {(projectRoot: string) => object} options.buildSnapshot
89
126
  * @returns {{
90
127
  * sseClients: Set<DashboardSseClient>,
91
- * attachSseClient: (res: import("node:http").ServerResponse) => void,
128
+ * hasSseCapacity: () => boolean,
129
+ * attachSseClient: (res: import("node:http").ServerResponse) => DashboardSseClient | null,
92
130
  * detachSseClient: (client: DashboardSseClient) => void,
93
131
  * refreshSharedSnapshot: () => { snapshot: object, serialized: string, generation: number },
94
132
  * getSharedSnapshot: () => { snapshot: object | null, serialized: string, generation: number },
@@ -145,7 +183,12 @@ export function createSharedSnapshotPollHub({
145
183
 
146
184
  const tick = () => {
147
185
  if (sseClients.size === 0) return;
148
- refreshSharedSnapshot();
186
+ try {
187
+ refreshSharedSnapshot();
188
+ } catch {
189
+ // Background poll: keep streaming the last good snapshot and retry on
190
+ // the next tick instead of crashing the server (SP-870 / #316).
191
+ }
149
192
  };
150
193
 
151
194
  const ensurePollTimer = () => {
@@ -159,7 +202,10 @@ export function createSharedSnapshotPollHub({
159
202
  pollTimer = null;
160
203
  };
161
204
 
205
+ const hasSseCapacity = () => sseClients.size < MAX_DASHBOARD_SSE_CLIENTS;
206
+
162
207
  const attachSseClient = (res) => {
208
+ if (!hasSseCapacity()) return null;
163
209
  const client = { res, lastSerialized: "" };
164
210
  sseClients.add(client);
165
211
  ensurePollTimer();
@@ -184,6 +230,7 @@ export function createSharedSnapshotPollHub({
184
230
 
185
231
  return {
186
232
  sseClients,
233
+ hasSseCapacity,
187
234
  attachSseClient,
188
235
  detachSseClient,
189
236
  refreshSharedSnapshot,
@@ -223,6 +270,12 @@ export function createDashboardServer({
223
270
 
224
271
  /** @type {import("node:http").Server} */
225
272
  const server = http.createServer((req, res) => {
273
+ if (!isAllowedRequestHost(req.headers.host, req.socket.localPort ?? port)) {
274
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
275
+ res.end("Invalid Host header\n");
276
+ return;
277
+ }
278
+
226
279
  const url = new URL(req.url ?? "/", `http://${host}:${port}`);
227
280
 
228
281
  if (req.method === "GET" && serveStaticAsset(res, url.pathname)) {
@@ -230,19 +283,58 @@ export function createDashboardServer({
230
283
  }
231
284
 
232
285
  if (req.method === "GET" && url.pathname === "/api/snapshot") {
233
- const snapshot = buildDashboardSnapshot(projectRoot);
286
+ let snapshot;
287
+ try {
288
+ snapshot = buildSnapshot(projectRoot);
289
+ } catch {
290
+ res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
291
+ res.end(
292
+ JSON.stringify({ error: "snapshot_failed", message: "Snapshot build failed" }),
293
+ );
294
+ return;
295
+ }
234
296
  res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
235
297
  res.end(JSON.stringify(snapshot));
236
298
  return;
237
299
  }
238
300
 
239
301
  if (req.method === "GET" && url.pathname === "/api/events") {
240
- writeSseHeaders(res);
241
- const client = pollHub.attachSseClient(res);
242
- req.on("close", () => {
243
- pollHub.detachSseClient(client);
244
- if (!res.writableEnded) res.end();
245
- });
302
+ if (!pollHub.hasSseCapacity()) {
303
+ res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
304
+ res.end("Too many dashboard SSE clients\n");
305
+ return;
306
+ }
307
+
308
+ // Build the initial snapshot BEFORE committing SSE headers: once
309
+ // writeHead runs, a 500 is no longer possible (ERR_HTTP_HEADERS_SENT).
310
+ const cached = pollHub.getSharedSnapshot();
311
+ if (!cached.snapshot) {
312
+ try {
313
+ pollHub.refreshSharedSnapshot();
314
+ } catch {
315
+ res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
316
+ res.end("Snapshot build failed\n");
317
+ return;
318
+ }
319
+ }
320
+
321
+ try {
322
+ writeSseHeaders(res);
323
+ const client = pollHub.attachSseClient(res);
324
+ if (!client) {
325
+ // Lost a capacity slot between the check and attach; end cleanly.
326
+ if (!res.writableEnded) res.end();
327
+ return;
328
+ }
329
+ req.on("close", () => {
330
+ pollHub.detachSseClient(client);
331
+ if (!res.writableEnded) res.end();
332
+ });
333
+ } catch {
334
+ // Headers are committed here; destroying the connection keeps the
335
+ // server alive without corrupting the response.
336
+ res.destroy();
337
+ }
246
338
  return;
247
339
  }
248
340
 
@@ -1,8 +1,14 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Validate-time warnings for Contract testCommand scope on patch-sized tasks (issue #141).
4
+ * Also hosts the shared artifact-pattern safety predicate + worktree matcher (#309)
5
+ * so src/batch modules stay under the 500-LOC policy (tests/cli/phase23-exit-verify).
4
6
  */
5
7
 
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import picomatch from "picomatch";
11
+
6
12
  /** S/M patch tasks should not chain the integrate-owned full coverage gate in Contract. */
7
13
  export const TEST_COMMAND_COVERAGE_FIX_HINT =
8
14
  "Remove coverage:check from Contract testCommand on S/M patch tasks; integrate gate runs full coverage at merge. Use scoped node --test for task tests.";
@@ -199,3 +205,118 @@ export function collectTestCommandScopeWarnings(parsed, options = {}) {
199
205
 
200
206
  return warnings;
201
207
  }
208
+
209
+ /**
210
+ * True when an artifact/scope pattern would resolve outside the lane worktree (#309):
211
+ * a `..` path segment (parent-directory traversal) or an absolute path
212
+ * (`/etc/...`, `C:/...`, `C:\\...`). Operates on the raw pattern string so both the
213
+ * validation collector and the runtime `findArtifactMatch` share one rule.
214
+ *
215
+ * @param {string | null | undefined} pattern
216
+ * @returns {boolean}
217
+ */
218
+ export function isUnsafeArtifactScopePattern(pattern) {
219
+ const normalized = String(pattern ?? "").replace(/\\/g, "/");
220
+ if (!normalized) {
221
+ return false;
222
+ }
223
+ if (normalized.split("/").includes("..")) {
224
+ return true;
225
+ }
226
+ return normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized);
227
+ }
228
+
229
+ /** Fix hint for artifactsMustExist patterns that escape the lane worktree (#309). */
230
+ export const ARTIFACT_TRAVERSAL_FIX_HINT =
231
+ "Use worktree-relative paths or globs without '..'; parent-directory traversal outside the lane worktree is rejected (#309).";
232
+
233
+ /**
234
+ * Warn when Contract artifactsMustExist patterns contain `..` traversal or are
235
+ * absolute paths — both resolve outside the lane worktree (#309).
236
+ *
237
+ * @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
238
+ * @returns {string[]}
239
+ */
240
+ export function collectArtifactTraversalWarnings(parsed) {
241
+ const patterns = parsed?.artifactsMustExist ?? [];
242
+ /** @type {string[]} */
243
+ const warnings = [];
244
+ for (const pattern of patterns) {
245
+ if (isUnsafeArtifactScopePattern(pattern)) {
246
+ warnings.push(
247
+ `Contract artifactsMustExist pattern escapes the lane worktree: ${pattern}. ${ARTIFACT_TRAVERSAL_FIX_HINT}`,
248
+ );
249
+ }
250
+ }
251
+ return warnings;
252
+ }
253
+
254
+ /** Matches any glob-magic character in a single path segment. */
255
+ const GLOB_MAGIC_RE = /[*?[\]{}]/;
256
+
257
+ /**
258
+ * Locate an artifact inside the lane worktree, literal path or glob (#309).
259
+ *
260
+ * Fail-closed: patterns containing `..` or resolving outside `worktreePath` are
261
+ * rejected with `unsafe: true` — they must never probe the host filesystem.
262
+ * Glob patterns walk from the longest literal prefix so double-star patterns
263
+ * match files under the worktree instead of a literal double-star segment.
264
+ *
265
+ * @param {string} worktreePath
266
+ * @param {string} artifactPattern
267
+ * @returns {{ ok: boolean, matchedPath?: string, unsafe?: boolean }}
268
+ */
269
+ export function findArtifactMatch(worktreePath, artifactPattern) {
270
+ // `src/**` + `/*.md` walks from `src/`, not from a literal `src/**` directory (#309).
271
+ const normalized = String(artifactPattern ?? "").replace(/\\/g, "/");
272
+ if (!normalized) {
273
+ return { ok: false };
274
+ }
275
+
276
+ if (isUnsafeArtifactScopePattern(normalized)) {
277
+ return { ok: false, unsafe: true };
278
+ }
279
+
280
+ // Containment guard: resolve against the worktree and require the result to stay inside it.
281
+ const worktreeRoot = path.resolve(worktreePath);
282
+ const resolved = path.resolve(worktreeRoot, normalized);
283
+ if (resolved !== worktreeRoot && !resolved.startsWith(worktreeRoot + path.sep)) {
284
+ return { ok: false, unsafe: true };
285
+ }
286
+
287
+ if (!GLOB_MAGIC_RE.test(normalized)) {
288
+ return fs.existsSync(resolved) ? { ok: true, matchedPath: normalized } : { ok: false };
289
+ }
290
+
291
+ // Longest literal prefix of glob segments is the search root, so a
292
+ // `src` + double-star + `*.md` pattern walks from `src/` (#309).
293
+ const segments = normalized.split("/");
294
+ let literalCount = 0;
295
+ while (literalCount < segments.length && !GLOB_MAGIC_RE.test(segments[literalCount])) {
296
+ literalCount += 1;
297
+ }
298
+ const baseDir = literalCount > 0 ? segments.slice(0, literalCount).join("/") : ".";
299
+ const searchRoot = path.join(worktreeRoot, baseDir);
300
+ if (!fs.existsSync(searchRoot)) {
301
+ return { ok: false };
302
+ }
303
+
304
+ /** @type {Array<{ abs: string, rel: string }>} */
305
+ const stack = [{ abs: searchRoot, rel: baseDir === "." ? "" : baseDir }];
306
+ while (stack.length > 0) {
307
+ const { abs, rel } = /** @type {{ abs: string, rel: string }} */ (stack.pop());
308
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
309
+ const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
310
+ const entryAbs = path.join(abs, entry.name);
311
+ if (entry.isDirectory()) {
312
+ stack.push({ abs: entryAbs, rel: entryRel });
313
+ continue;
314
+ }
315
+ if (picomatch(normalized, { dot: true })(entryRel)) {
316
+ return { ok: true, matchedPath: entryRel };
317
+ }
318
+ }
319
+ }
320
+
321
+ return { ok: false };
322
+ }
@@ -1,27 +1 @@
1
- {
2
- "profileVersion": 1,
3
- "worker": {
4
- "alwaysInclude": ["taskplane-worker-cursor.mdc"],
5
- "neverInclude": [],
6
- "globMatch": true
7
- },
8
- "reviewer": {
9
- "enabled": true,
10
- "alwaysInclude": [],
11
- "neverInclude": [
12
- "taskplane-worker-cursor.mdc",
13
- "taskplane-task-authoring.mdc"
14
- ],
15
- "globMatch": true,
16
- "maxRules": 32
17
- },
18
- "discovery": {
19
- "excludePatterns": ["*-brutal-audit"],
20
- "excludeRelPaths": [
21
- "audit-workflow.mdc",
22
- "cursor-integration.mdc",
23
- "taskplane/prompt-template.md",
24
- "taskplane/status-template.md"
25
- ]
26
- }
27
- }
1
+ {"profileVersion":1,"worker":{"alwaysInclude":[],"neverInclude":[],"globMatch":true},"reviewer":{"enabled":true,"alwaysInclude":[],"neverInclude":["taskplane-worker-cursor.mdc","taskplane-task-authoring.mdc"],"globMatch":true,"maxRules":32},"discovery":{"excludePatterns":["*-brutal-audit"],"excludeRelPaths":["audit-workflow.mdc","cursor-integration.mdc","taskplane/prompt-template.md","taskplane/status-template.md"]}}