pi-spine 2.14.1 → 2.16.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.
Files changed (36) hide show
  1. package/package.json +2 -2
  2. package/skills/spine-release-operator/SKILL.md +60 -7
  3. package/skills/spine-release-operator/references/issue-intake-checklist.md +1 -1
  4. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +1 -0
  5. package/src/batch/abort.mjs +82 -68
  6. package/src/batch/batch-id.mjs +103 -0
  7. package/src/batch/batch-state-lock.mjs +357 -0
  8. package/src/batch/contract-exec.mjs +12 -8
  9. package/src/batch/diagnosis.mjs +12 -7
  10. package/src/batch/engine-lanes/review-code.mjs +224 -0
  11. package/src/batch/engine-lanes/review-final.mjs +318 -0
  12. package/src/batch/engine-lanes/review-plan.mjs +315 -0
  13. package/src/batch/engine-lanes/review-poll.mjs +427 -0
  14. package/src/batch/engine-lanes/review-stub.mjs +146 -0
  15. package/src/batch/engine-lanes/review.mjs +4 -1532
  16. package/src/batch/engine.mjs +1 -1
  17. package/src/batch/journal.mjs +9 -32
  18. package/src/batch/lifecycle.mjs +106 -95
  19. package/src/batch/metrics.mjs +13 -26
  20. package/src/batch/reconcile-orphan.mjs +3 -2
  21. package/src/batch/salvage-batch-list.mjs +12 -1
  22. package/src/batch/state-guards.mjs +26 -3
  23. package/src/batch/state-io.mjs +101 -29
  24. package/src/batch/state.mjs +7 -13
  25. package/src/batch/worker-output.mjs +5 -16
  26. package/src/cli/handoff.mjs +10 -27
  27. package/src/cli/journal-follow.mjs +11 -2
  28. package/src/cli/lane-logs.mjs +9 -1
  29. package/src/config/cursor-rules/profile.mjs +5 -1
  30. package/src/config/defaults.mjs +10 -1
  31. package/src/config/settings-fields.mjs +14 -0
  32. package/src/planner/file-scope.mjs +109 -7
  33. package/src/process/liveness.mjs +188 -1
  34. package/src/tasks/analyze/index.mjs +14 -27
  35. package/src/tasks/packet/parse-prompt.mjs +138 -3
  36. package/src/util/secret-redact.mjs +140 -0
@@ -37,6 +37,112 @@ const CONTRACT_TABLE_HEADER_RE = /^\|\s*Field\s*\|\s*Value\s*\|$/i;
37
37
  const CONTRACT_TABLE_SEPARATOR_RE = /^\|[\s\-:|]+\|$/;
38
38
  const CONTRACT_TABLE_ROW_RE = /^\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|$/;
39
39
  const TEST_COMMAND_MAX_LENGTH = 500;
40
+
41
+ /**
42
+ * Quote-aware scan for shell metacharacters forbidden in contract commands (#268).
43
+ *
44
+ * Contract testCommand / runCommand execute through a shell, so expansion and
45
+ * sequencing operators are an injection surface. Mirrors the #254 gate-evidence
46
+ * grammar: `&&` stays the only allowed chain separator (house style is
47
+ * `npm run typecheck && node --test …`), while `$`, backticks, `;`, `|` (which
48
+ * covers `||`), a lone `&`, and unquoted newlines fail closed. Single-quoted
49
+ * text is literal data (`printf '%s' 'a | b'` stays valid); `$` and backticks
50
+ * are rejected even inside double quotes because they still expand there;
51
+ * unclosed quotes fail closed.
52
+ *
53
+ * @param {string} command
54
+ * @returns {string | null} rejection reason, or null when the command is safe
55
+ */
56
+ export function findContractCommandMetacharIssue(command) {
57
+ const text = String(command ?? "");
58
+ /** @type {"'" | '"' | null} */
59
+ let quote = null;
60
+
61
+ for (let i = 0; i < text.length; i++) {
62
+ const ch = text[i];
63
+
64
+ if (quote === "'") {
65
+ // Single-quoted content is literal in POSIX shells; only the closing
66
+ // quote matters, so metacharacters there are data, not syntax.
67
+ if (ch === "'") quote = null;
68
+ continue;
69
+ }
70
+
71
+ if (ch === "\\" && i + 1 < text.length) {
72
+ // Escaped characters are literal outside quotes and inside double
73
+ // quotes, so `\;` / `\$` cannot sequence or expand anything.
74
+ i += 1;
75
+ continue;
76
+ }
77
+
78
+ if (quote === '"') {
79
+ if (ch === '"') {
80
+ quote = null;
81
+ continue;
82
+ }
83
+ // `$` and backticks expand inside double quotes; other characters are
84
+ // literal there, so quoted `;` / `|` data is allowed.
85
+ if (ch === "$") return "shell variable expansion ($ in double quotes)";
86
+ if (ch === "`") return "shell command substitution (backticks in double quotes)";
87
+ continue;
88
+ }
89
+
90
+ if (ch === "'") {
91
+ quote = "'";
92
+ continue;
93
+ }
94
+ if (ch === '"') {
95
+ quote = '"';
96
+ continue;
97
+ }
98
+ if (ch === "$") return "shell variable expansion ($)";
99
+ if (ch === "`") return "shell command substitution (backticks)";
100
+ if (ch === ";") return "shell sequencing (;)";
101
+ if (ch === "|") return "shell pipe (| or ||)";
102
+ if (ch === "\n" || ch === "\r") return "shell sequencing (newline)";
103
+ if (ch === "&") {
104
+ if (text[i + 1] === "&") {
105
+ // `&&` is the documented chain separator (mirrors #254 Phase B).
106
+ i += 1;
107
+ continue;
108
+ }
109
+ return "shell background operator (&)";
110
+ }
111
+ }
112
+
113
+ if (quote) return "unclosed quote";
114
+ return null;
115
+ }
116
+
117
+ /**
118
+ * Defense in depth: reject shell metacharacters in contract testCommand before the
119
+ * shell spawns (#268). `&&` chains stay allowed (mirrors the #254 gate-evidence
120
+ * grammar); `$`, backticks, `;`, `|`, `||`, and lone `&` fail closed. The runtime
121
+ * guard is the enforcement boundary because matrix row substitution can reintroduce
122
+ * metacharacters after parse-time validation.
123
+ *
124
+ * @param {string} command
125
+ * @returns {boolean}
126
+ */
127
+ export function isRefusedContractMetacharCommand(command) {
128
+ const trimmed = String(command ?? "").trim();
129
+ if (!trimmed || trimmed === "true") {
130
+ return false;
131
+ }
132
+ return findContractCommandMetacharIssue(trimmed) !== null;
133
+ }
134
+
135
+ /**
136
+ * Refusal copy for the contract verify path — deliberately distinct from the #254
137
+ * gate-evidence messages ("evidence command contains …").
138
+ *
139
+ * @param {string} command
140
+ * @returns {string}
141
+ */
142
+ export function formatRefusedContractMetacharMessage(command) {
143
+ const issue = findContractCommandMetacharIssue(String(command ?? "").trim());
144
+ return `Contract testCommand refused before spawn: ${issue ?? "shell metacharacters"} (command: ${command}). Contract testCommand runs through a shell; remove $, backticks, ;, |, || or lone & — && chains are allowed (#268).`;
145
+ }
40
146
  export const SEE_FILE_SCOPE_RE = /^see\s+file\s+scope$/i;
41
147
  const CONTRACT_EM_DASH_PLACEHOLDER_RE = /^[—\-]$/;
42
148
  const CONTRACT_NONE_VALUES = new Set([
@@ -298,6 +404,9 @@ export function resolveContractFileScopeReferences(parsed, fileScopePaths) {
298
404
  parsed.fileScopeMustChange = [...new Set(expanded)];
299
405
  }
300
406
 
407
+ const CONTRACT_METACHAR_FIX_HINT =
408
+ "contract commands reject $, backticks, ;, |, || and lone & — && chains are allowed (#268)";
409
+
301
410
  /**
302
411
  * @param {ReturnType<typeof parseContract>} parsed
303
412
  * @param {string} field
@@ -320,6 +429,13 @@ function applyContractField(parsed, field, rawValue) {
320
429
  parsed.errors.push(`Contract testCommand exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
321
430
  return;
322
431
  }
432
+ const testCommandIssue = findContractCommandMetacharIssue(command);
433
+ if (testCommandIssue) {
434
+ parsed.errors.push(
435
+ `Contract testCommand contains forbidden shell metacharacters: ${testCommandIssue}; ${CONTRACT_METACHAR_FIX_HINT}`,
436
+ );
437
+ return;
438
+ }
323
439
  parsed.testCommand = command;
324
440
  return;
325
441
  }
@@ -333,6 +449,13 @@ function applyContractField(parsed, field, rawValue) {
333
449
  parsed.errors.push(`Contract runCommand exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
334
450
  return;
335
451
  }
452
+ const runCommandIssue = findContractCommandMetacharIssue(command);
453
+ if (runCommandIssue) {
454
+ parsed.errors.push(
455
+ `Contract runCommand contains forbidden shell metacharacters: ${runCommandIssue}; ${CONTRACT_METACHAR_FIX_HINT}`,
456
+ );
457
+ return;
458
+ }
336
459
  parsed.runCommand = command;
337
460
  return;
338
461
  }
@@ -511,19 +634,31 @@ export function parsePromptDependencies(depsSection) {
511
634
  }
512
635
 
513
636
  const ids = [];
637
+ // Set-backed membership so dedup is O(1) per line instead of O(N) (#271);
638
+ // `ids` keeps first-seen bullet order for the return value.
639
+ const seenIds = new Set();
514
640
  for (const line of depsSection.split(/\r?\n/)) {
515
641
  const bullet = line.match(/^-\s+\*{0,2}([A-Z][A-Z0-9]*-\d+)\*{0,2}/);
516
642
  if (bullet) {
517
- if (!ids.includes(bullet[1])) ids.push(bullet[1]);
643
+ if (!seenIds.has(bullet[1])) {
644
+ seenIds.add(bullet[1]);
645
+ ids.push(bullet[1]);
646
+ }
518
647
  continue;
519
648
  }
520
649
  const bare = line.match(/^-\s+([A-Z][A-Z0-9]*-\d+)\b/);
521
650
  if (bare) {
522
- if (!ids.includes(bare[1])) ids.push(bare[1]);
651
+ if (!seenIds.has(bare[1])) {
652
+ seenIds.add(bare[1]);
653
+ ids.push(bare[1]);
654
+ }
523
655
  continue;
524
656
  }
525
657
  const requires = line.match(/\*+Requires:\*+\s*(?:[a-z0-9-]+\/)?([A-Z][A-Z0-9]*-\d+)/i);
526
- if (requires && !ids.includes(requires[1])) ids.push(requires[1]);
658
+ if (requires && !seenIds.has(requires[1])) {
659
+ seenIds.add(requires[1]);
660
+ ids.push(requires[1]);
661
+ }
527
662
  }
528
663
  return ids;
529
664
  }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Unified secret redaction policy shared across journal, worker-output,
3
+ * handoff, and metrics channels (SP-716, closes #260).
4
+ *
5
+ * Two complementary mechanisms:
6
+ * 1. Key denylist — object keys matching REDACT_KEY_PATTERN have their
7
+ * values replaced wholesale (see redactSecretsDeep).
8
+ * 2. Value patterns — well-known secret shapes (sk-, ghp_, bearer headers,
9
+ * connection strings, ENV-style assignments) are masked inside free
10
+ * text (see redactTextSecrets).
11
+ */
12
+
13
+ export const REDACTED = "[REDACTED]";
14
+
15
+ /**
16
+ * Keys whose values are always redacted, matched case-insensitively.
17
+ * Must stay non-global: it is used with RegExp.prototype.test, which is
18
+ * stateful for global regexes.
19
+ */
20
+ export const REDACT_KEY_PATTERN = /key|token|secret|password/i;
21
+
22
+ /**
23
+ * Value-shaped secret patterns, ordered most-specific first so that
24
+ * assignment-shaped matches (e.g. OPENAI_API_KEY=sk-...) are consumed whole
25
+ * before the generic key:value fallback can leave partial fragments behind.
26
+ *
27
+ * Safety: these regexes carry the global flag and are only safe to use with
28
+ * String.prototype.replace, which resets lastIndex before iterating. Do not
29
+ * use them with .test() or .exec().
30
+ */
31
+ export const SECRET_VALUE_PATTERNS = Object.freeze([
32
+ // ENV-style assignments: OPENAI_API_KEY=..., GITHUB_TOKEN = ...
33
+ /\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*\s*=\s*\S+/g,
34
+ // Bearer authorization headers.
35
+ /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/g,
36
+ // Database connection strings embed credentials.
37
+ /(?:postgres|mysql|mongodb)(?:\+srv)?:\/\/[^\s]+/gi,
38
+ /\bDATABASE_URL=\S+/gi,
39
+ // Well-known token shapes.
40
+ /\bsk-[A-Za-z0-9_-]{8,}/g,
41
+ /\bghp_[A-Za-z0-9]{8,}/g,
42
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
43
+ /\bAKIA[0-9A-Z]{16}/g,
44
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
45
+ // Generic key:value / key=value fallback.
46
+ /\b(?:bearer|token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi,
47
+ ]);
48
+
49
+ /**
50
+ * Mask value-shaped secrets in free text. Extra caller-supplied patterns
51
+ * (e.g. workerOutputDenyPatterns from config) run after the builtin set.
52
+ *
53
+ * @param {unknown} text
54
+ * @param {RegExp[]} [extraPatterns]
55
+ * @returns {unknown}
56
+ */
57
+ export function redactTextSecrets(text, extraPatterns = []) {
58
+ if (typeof text !== "string" || !text) return text;
59
+ let out = text;
60
+ for (const pattern of SECRET_VALUE_PATTERNS) {
61
+ out = out.replace(pattern, REDACTED);
62
+ }
63
+ for (const pattern of extraPatterns) {
64
+ out = out.replace(pattern, REDACTED);
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Recursively redact secrets in a JSON-shaped value:
71
+ * - object keys matching the key denylist are replaced wholesale,
72
+ * - string values are scanned for value-shaped secrets,
73
+ * - arrays and nested objects are traversed.
74
+ *
75
+ * @param {unknown} value
76
+ * @param {object} [options]
77
+ * @param {RegExp} [options.keyPattern] Override key denylist (must be
78
+ * non-global; RegExp.prototype.test is stateful for global regexes).
79
+ * @param {Set<string>} [options.allowedKeys] Keys exempt from the denylist
80
+ * (e.g. usage counters like tokensIn).
81
+ * @param {RegExp[]} [options.extraPatterns] Additional value patterns.
82
+ * @returns {unknown}
83
+ */
84
+ export function redactSecretsDeep(value, options = {}) {
85
+ const keyPattern = options.keyPattern ?? REDACT_KEY_PATTERN;
86
+ const allowedKeys = options.allowedKeys ?? null;
87
+ const extraPatterns = Array.isArray(options.extraPatterns) ? options.extraPatterns : [];
88
+
89
+ if (typeof value === "string") {
90
+ return redactTextSecrets(value, extraPatterns);
91
+ }
92
+ if (value == null || typeof value !== "object") {
93
+ return value;
94
+ }
95
+ if (Array.isArray(value)) {
96
+ return value.map((entry) => redactSecretsDeep(entry, options));
97
+ }
98
+
99
+ /** @type {Record<string, unknown>} */
100
+ const out = {};
101
+ for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
102
+ if (keyPattern.test(key) && !(allowedKeys && allowedKeys.has(key))) {
103
+ out[key] = REDACTED;
104
+ } else {
105
+ out[key] = redactSecretsDeep(entry, options);
106
+ }
107
+ }
108
+ return out;
109
+ }
110
+
111
+ /**
112
+ * Cap a JSON-serializable payload by UTF-8 bytes — not string length — so
113
+ * multi-byte characters cannot push the serialized record past the budget.
114
+ * Returns the payload unchanged when it already fits; otherwise returns a
115
+ * truncation marker record whose preview is sliced on byte boundaries.
116
+ *
117
+ * @param {Record<string, unknown>} payload
118
+ * @param {number} maxBytes
119
+ * @returns {Record<string, unknown>}
120
+ */
121
+ export function capPayloadBytes(payload, maxBytes) {
122
+ const serialized = JSON.stringify(payload);
123
+ const originalBytes = Buffer.byteLength(serialized, "utf-8");
124
+ if (originalBytes <= maxBytes) {
125
+ return payload;
126
+ }
127
+
128
+ // Reserve 256 bytes of headroom for the truncation wrapper so the
129
+ // re-serialized record stays near maxBytes. Buffer.subarray slices on byte
130
+ // boundaries; decoding never emits invalid UTF-8 (partial trailing
131
+ // sequences become U+FFFD).
132
+ const budget = Math.max(0, maxBytes - 256);
133
+ const preview = Buffer.from(serialized, "utf-8").subarray(0, budget).toString("utf-8");
134
+ return {
135
+ _truncated: true,
136
+ _originalBytes: originalBytes,
137
+ _maxBytes: maxBytes,
138
+ preview,
139
+ };
140
+ }