pi-spine 2.13.0 → 2.14.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.13.0",
3
+ "version": "2.14.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -436,13 +436,25 @@ COMMIT=$(git rev-parse HEAD)
436
436
  gh run list --workflow ci.yml --commit "$COMMIT" --json databaseId,conclusion,status --limit 5
437
437
  ```
438
438
 
439
- **Fail closed** when no run has `conclusion: success`. If the latest run is `in_progress` or `queued`, wait:
439
+ **Fail closed** when no run has `conclusion: success`. **Cancelled or absent CI is no signal** — neither green nor red (post-mortem v2.12.3 F-C). Branch by run state:
440
+
441
+ - **`in_progress` / `queued`:** wait:
442
+
443
+ ```bash
444
+ gh run watch --exit-status <run-id>
445
+ ```
446
+
447
+ - **`cancelled` or no run exists for `HEAD`:** re-run **CI** via `workflow_dispatch` (trigger added in `edb7919d`), then wait for `conclusion: success` on current `HEAD`:
440
448
 
441
449
  ```bash
450
+ gh workflow run ci.yml
451
+ gh run list --workflow ci.yml --commit "$COMMIT" --json databaseId,conclusion,status --limit 5
442
452
  gh run watch --exit-status <run-id>
443
453
  ```
444
454
 
445
- If CI **failed** or **no CI run** exists for `HEAD`, **STOP** — fix CI on `main`, re-run Phase 5, then re-attempt this gate. Do not `npm version` or `git push --tags`.
455
+ Never treat a cancelled run as green or as a reason to skip this gate.
456
+
457
+ If CI **failed**, **STOP** — fix CI on `main`, re-run Phase 5, then re-attempt this gate. Do not `npm version` or `git push --tags` until a green CI run exists on `HEAD`.
446
458
 
447
459
  Only after Phase 5 **and** pre-tag CI gate pass:
448
460
 
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Journal event checksums and bounded jsonl append (extracted from journal.mjs
3
+ * so the facade stays under the Phase 23 500 LOC cap).
4
+ */
5
+
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+
10
+ /** Bounded retry policy for transient append failures (EBUSY/ENOENT). */
11
+ const APPEND_RETRY_ATTEMPTS = 3;
12
+ const APPEND_RETRY_DELAY_MS = 25;
13
+ const RETRYABLE_APPEND_CODES = new Set(["EBUSY", "ENOENT"]);
14
+
15
+ /**
16
+ * Synchronous sleep for retry backoff. Atomics.wait is permitted on the Node
17
+ * main thread (unlike browsers), so this works in the sync append path.
18
+ * @param {number} ms
19
+ */
20
+ function sleepSync(ms) {
21
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
22
+ }
23
+
24
+ /**
25
+ * SHA-256 integrity checksum for new journal events. Computed over the
26
+ * canonical JSON of the entry without the checksum field; the field is
27
+ * appended last so JSON.parse preserves key order and readers can recompute
28
+ * by stripping `checksum` and re-stringifying. Legacy lines without the
29
+ * field remain valid.
30
+ * @param {Record<string, unknown>} entry Entry without a checksum field.
31
+ * @returns {string} Hex digest.
32
+ */
33
+ export function computeJournalChecksum(entry) {
34
+ return crypto.createHash("sha256").update(JSON.stringify(entry), "utf-8").digest("hex");
35
+ }
36
+
37
+ /**
38
+ * Verify a parsed journal line's checksum when present.
39
+ * @param {Record<string, unknown>} event
40
+ * @returns {boolean} True when checksum is absent (legacy) or matches.
41
+ */
42
+ export function verifyJournalChecksum(event) {
43
+ if (!event || typeof event !== "object") return false;
44
+ const { checksum, ...rest } = event;
45
+ if (typeof checksum !== "string" || !checksum) return true;
46
+ return computeJournalChecksum(rest) === checksum;
47
+ }
48
+
49
+ /**
50
+ * Append one jsonl line with fsync and bounded EBUSY/ENOENT retry.
51
+ * Does not rewrite the journal file. In-process callers remain serialized
52
+ * because this function is fully synchronous.
53
+ * @param {string} filePath
54
+ * @param {string} line
55
+ */
56
+ export function appendJsonlLineSync(filePath, line) {
57
+ let lastError;
58
+ let appended = false;
59
+ for (let attempt = 1; attempt <= APPEND_RETRY_ATTEMPTS; attempt += 1) {
60
+ try {
61
+ if (!appended) {
62
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
63
+ fs.appendFileSync(filePath, line, "utf-8");
64
+ appended = true;
65
+ }
66
+
67
+ const fd = fs.openSync(filePath, "r+");
68
+ try {
69
+ fs.fsyncSync(fd);
70
+ } finally {
71
+ fs.closeSync(fd);
72
+ }
73
+ return;
74
+ } catch (error) {
75
+ lastError = error;
76
+ const code = error && /** @type {NodeJS.ErrnoException} */ (error).code;
77
+ if (typeof code !== "string" || !RETRYABLE_APPEND_CODES.has(code) || attempt === APPEND_RETRY_ATTEMPTS) {
78
+ throw error;
79
+ }
80
+ sleepSync(APPEND_RETRY_DELAY_MS);
81
+ }
82
+ }
83
+ throw lastError;
84
+ }
@@ -6,6 +6,13 @@
6
6
  import crypto from "node:crypto";
7
7
  import fs from "node:fs";
8
8
  import path from "node:path";
9
+ import {
10
+ appendJsonlLineSync,
11
+ computeJournalChecksum,
12
+ verifyJournalChecksum,
13
+ } from "./journal-checksum.mjs";
14
+
15
+ export { verifyJournalChecksum };
9
16
 
10
17
  export const JOURNAL_SCHEMA_VERSION = 1;
11
18
  export const MAX_PAYLOAD_BYTES = 32 * 1024;
@@ -169,7 +176,6 @@ export function normalizeJournalEvent(line) {
169
176
  */
170
177
  export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
171
178
  const filePath = journalPath(projectRoot, batchId);
172
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
173
179
 
174
180
  const rawPayload = extractPayload(options);
175
181
  const payload = capPayloadSize(redactSecrets(rawPayload));
@@ -194,16 +200,16 @@ export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
194
200
  const taskId = options.taskId;
195
201
  if (typeof taskId === "string" && taskId) entry.taskId = taskId;
196
202
 
197
- const line = `${JSON.stringify(entry)}\n`;
198
- fs.appendFileSync(filePath, line, "utf-8");
203
+ // checksum: SHA-256 hex of the canonical JSON of the entry without this
204
+ // field. Added last so readers recompute by stripping `checksum` and
205
+ // re-stringifying; absent on legacy lines.
206
+ entry.checksum = computeJournalChecksum(entry);
199
207
 
200
- const fd = fs.openSync(filePath, "r+");
201
- try {
202
- fs.fsyncSync(fd);
203
- } finally {
204
- fs.closeSync(fd);
205
- }
208
+ const line = `${JSON.stringify(entry)}\n`;
206
209
 
210
+ // In-process serialization: appendJsonlLineSync is fully synchronous, so
211
+ // concurrent event-loop callers cannot interleave partial jsonl lines.
212
+ appendJsonlLineSync(filePath, line);
207
213
  return entry;
208
214
  }
209
215
 
@@ -227,6 +233,22 @@ export function exportJournalJsonl(projectRoot, batchId) {
227
233
  return fs.readFileSync(filePath, "utf-8");
228
234
  }
229
235
 
236
+ /**
237
+ * Parse jsonl journal content into normalized events. Lines whose checksum is
238
+ * present but mismatches are skipped (fail-closed per-line) without
239
+ * discarding the rest of the file; legacy lines without checksum load as-is.
240
+ * @param {string} content Raw jsonl content.
241
+ * @returns {object[]}
242
+ */
243
+ function parseJournalLines(content) {
244
+ return content
245
+ .split("\n")
246
+ .filter(Boolean)
247
+ .map((line) => JSON.parse(line))
248
+ .filter((parsed) => verifyJournalChecksum(parsed))
249
+ .map((parsed) => normalizeJournalEvent(parsed));
250
+ }
251
+
230
252
  /**
231
253
  * @param {string} projectRoot
232
254
  * @param {string} batchId
@@ -236,11 +258,7 @@ export function readJournalEvents(projectRoot, batchId) {
236
258
  const filePath = journalPath(projectRoot, batchId);
237
259
  if (!fs.existsSync(filePath)) return [];
238
260
 
239
- return fs
240
- .readFileSync(filePath, "utf-8")
241
- .split("\n")
242
- .filter(Boolean)
243
- .map((line) => normalizeJournalEvent(JSON.parse(line)));
261
+ return parseJournalLines(fs.readFileSync(filePath, "utf-8"));
244
262
  }
245
263
 
246
264
  /**
@@ -273,11 +291,7 @@ export function readJournalEventsCached(projectRoot, batchId) {
273
291
  return _journalCache.events;
274
292
  }
275
293
 
276
- const events = fs
277
- .readFileSync(filePath, "utf-8")
278
- .split("\n")
279
- .filter(Boolean)
280
- .map((line) => normalizeJournalEvent(JSON.parse(line)));
294
+ const events = parseJournalLines(fs.readFileSync(filePath, "utf-8"));
281
295
 
282
296
  _journalCache.filePath = filePath;
283
297
  _journalCache.mtimeMs = stat.mtimeMs;
@@ -98,6 +98,9 @@ function extractSummary(reviewContent) {
98
98
  export function parseReviewVerdict(reviewContent, options = {}) {
99
99
  const reviewType = options.reviewType ?? "code";
100
100
  const isFinal = reviewType === "final";
101
+ // A json fence signals structured-output intent; if it cannot yield a valid
102
+ // verdict, fail closed instead of salvaging a verdict from prose heuristics.
103
+ const hasJsonFence = /```json/i.test(reviewContent);
101
104
 
102
105
  const jsonMatch = reviewContent.match(/```json\s*\n([\s\S]*?)\n```/i);
103
106
  if (jsonMatch) {
@@ -126,6 +129,10 @@ export function parseReviewVerdict(reviewContent, options = {}) {
126
129
  };
127
130
  }
128
131
 
132
+ if (hasJsonFence) {
133
+ return { verdict: null, feedback: extractSummary(reviewContent) };
134
+ }
135
+
129
136
  const lower = reviewContent.toLowerCase();
130
137
  if (
131
138
  lower.includes("changes requested") ||