pi-spine 2.31.0 → 2.33.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.
@@ -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"]}}