pi-spine 2.17.0 → 2.19.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.
@@ -360,6 +360,62 @@ export function finalizeWorkerOutput({
360
360
  };
361
361
  }
362
362
 
363
+ /**
364
+ * Targeted `worker_done_missing` hint for backgrounded verifications (SP-741, #276).
365
+ * A worker that exits while a long verification is still running (waiting on a
366
+ * completion wake) cannot be resumed — the session dies with the turn.
367
+ */
368
+ export const BACKGROUND_VERIFICATION_HINT =
369
+ "backgrounded verification detected — long verifications must run in the foreground and finish in-session before .DONE";
370
+
371
+ /** Output phrases that on their own indicate background-and-exit behavior. */
372
+ const BACKGROUND_VERIFICATION_STRONG_MARKERS = [
373
+ "completion wake",
374
+ "running in the background",
375
+ "background monitor",
376
+ "backgrounded",
377
+ "monitorcreate",
378
+ ];
379
+
380
+ /** Output phrases indicating a verification has not finished yet. */
381
+ const BACKGROUND_VERIFICATION_PENDING_MARKERS = [
382
+ "still running",
383
+ "still in progress",
384
+ "not finished",
385
+ "hasn't finished",
386
+ "has not finished",
387
+ ];
388
+
389
+ /** Phrases that pair with pending work to indicate it was detached/backgrounded. */
390
+ const BACKGROUND_VERIFICATION_CONTEXT_MARKERS = [
391
+ "background",
392
+ "wake",
393
+ "monitor",
394
+ "redirected",
395
+ "detached",
396
+ ];
397
+
398
+ /**
399
+ * Detect worker output suggesting a long verification was backgrounded instead
400
+ * of run in the foreground (#276). Matched against the captured output tail
401
+ * at `worker_done_missing` diagnosis time; advisory only.
402
+ *
403
+ * @param {string|null|undefined} outputText
404
+ * @returns {boolean}
405
+ */
406
+ export function detectBackgroundedVerification(outputText) {
407
+ if (!outputText || !String(outputText).trim()) return false;
408
+ const normalized = String(outputText).toLowerCase();
409
+ if (BACKGROUND_VERIFICATION_STRONG_MARKERS.some((marker) => normalized.includes(marker))) {
410
+ return true;
411
+ }
412
+ const hasPending = BACKGROUND_VERIFICATION_PENDING_MARKERS.some((marker) =>
413
+ normalized.includes(marker),
414
+ );
415
+ if (!hasPending) return false;
416
+ return BACKGROUND_VERIFICATION_CONTEXT_MARKERS.some((marker) => normalized.includes(marker));
417
+ }
418
+
363
419
  /**
364
420
  * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
365
421
  *
@@ -123,6 +123,75 @@ function formatPendingTasks(pendingTasks) {
123
123
  );
124
124
  }
125
125
 
126
+ /**
127
+ * Derive SBAR Background facts from journal tail, phase, and pending tasks
128
+ * when the diagnose packet fields (#278 / SP-745) are absent.
129
+ *
130
+ * @param {{ phase?: string|null, pendingTasks?: object[], journalTail?: object[] }} data
131
+ * @returns {string[]}
132
+ */
133
+ function deriveBackgroundFacts(data) {
134
+ const facts = [];
135
+ if (data.phase) {
136
+ facts.push(`Phase: ${data.phase}`);
137
+ }
138
+ const pendingTaskIds = (data.pendingTasks ?? [])
139
+ .map((task) => task.taskId)
140
+ .filter((taskId) => typeof taskId === "string" && taskId.length > 0);
141
+ if (pendingTaskIds.length) {
142
+ facts.push(`Pending tasks: ${pendingTaskIds.join(", ")}`);
143
+ }
144
+ const journalTail = data.journalTail ?? [];
145
+ const lastEntry = journalTail[journalTail.length - 1];
146
+ if (lastEntry?.type) {
147
+ const suffix = lastEntry.taskId
148
+ ? ` ${lastEntry.taskId}`
149
+ : lastEntry.laneId
150
+ ? ` ${lastEntry.laneId}`
151
+ : "";
152
+ facts.push(`Last journal event: ${lastEntry.type}${suffix}`);
153
+ }
154
+ return facts;
155
+ }
156
+
157
+ /**
158
+ * Resolve SBAR Background facts: map the diagnose packet `background` field
159
+ * (#278 / SP-745) when present, else derive from journalTail + phase +
160
+ * pendingTasks. Returns an empty array when nothing decision-relevant is
161
+ * known — renderers must show explicit `(none)` in that case (#279).
162
+ *
163
+ * @param {{ background?: unknown, phase?: string|null, pendingTasks?: object[], journalTail?: object[] }} data
164
+ * @returns {string[]}
165
+ */
166
+ export function resolveBackgroundFacts(data) {
167
+ if (Array.isArray(data.background)) {
168
+ const mapped = data.background.filter(
169
+ (fact) => typeof fact === "string" && fact.trim().length > 0,
170
+ );
171
+ if (mapped.length) return mapped;
172
+ }
173
+ return deriveBackgroundFacts(data);
174
+ }
175
+
176
+ /**
177
+ * Resolve SBAR Assessment rationale: map the diagnose packet
178
+ * `assessmentReason` field (#278 / SP-745) when present, else derive from
179
+ * diagnosis + headline.
180
+ *
181
+ * @param {{ assessmentReason?: unknown, diagnosis?: string|null, headline?: string|null }} data
182
+ * @returns {string}
183
+ */
184
+ export function resolveAssessmentReason(data) {
185
+ if (typeof data.assessmentReason === "string" && data.assessmentReason.trim().length > 0) {
186
+ return data.assessmentReason;
187
+ }
188
+ const diagnosis = data.diagnosis ?? "idle";
189
+ if (diagnosis === "idle") {
190
+ return "No active batch signals observed; reconcile found nothing to recover";
191
+ }
192
+ return `Reconcile signals selected "${diagnosis}"${data.headline ? ` — ${data.headline}` : ""}`;
193
+ }
194
+
126
195
  /**
127
196
  * Assemble structured handoff data from reconciliation, batch-state, and journal.
128
197
  *
@@ -144,6 +213,16 @@ export function assembleHandoffData(projectRoot, batchId) {
144
213
  pendingTasks: [],
145
214
  laneSummary: [],
146
215
  journalTail: [],
216
+ background: resolveBackgroundFacts({
217
+ background: reconciliation.background,
218
+ pendingTasks: [],
219
+ journalTail: [],
220
+ }),
221
+ assessmentReason: resolveAssessmentReason({
222
+ assessmentReason: reconciliation.assessmentReason,
223
+ diagnosis: "idle",
224
+ headline: reconciliation.headline,
225
+ }),
147
226
  restoreCommands: buildRestoreCommands(reconciliation),
148
227
  idle: true,
149
228
  handoffPath: resolveHandoffPath(projectRoot),
@@ -183,6 +262,18 @@ export function assembleHandoffData(projectRoot, batchId) {
183
262
  const journalTail = readJournalTail(journalEvents, JOURNAL_TAIL_LIMIT).map(formatJournalTailEntry);
184
263
 
185
264
  const diagnosis = reconciliation.diagnosis ?? "idle";
265
+ const phase = reconciliation.phase ?? batch?.phase ?? null;
266
+ const background = resolveBackgroundFacts({
267
+ background: reconciliation.background,
268
+ phase,
269
+ pendingTasks,
270
+ journalTail,
271
+ });
272
+ const assessmentReason = resolveAssessmentReason({
273
+ assessmentReason: reconciliation.assessmentReason,
274
+ diagnosis,
275
+ headline: reconciliation.headline,
276
+ });
186
277
 
187
278
  return redactHandoffSecrets({
188
279
  generatedAt,
@@ -194,9 +285,11 @@ export function assembleHandoffData(projectRoot, batchId) {
194
285
  pendingTasks,
195
286
  laneSummary,
196
287
  journalTail,
288
+ background,
289
+ assessmentReason,
197
290
  restoreCommands: buildRestoreCommands(reconciliation),
198
291
  batchStatePath,
199
- phase: reconciliation.phase ?? batch?.phase ?? null,
292
+ phase,
200
293
  idle: diagnosis === "idle",
201
294
  handoffPath: resolveHandoffPath(projectRoot),
202
295
  });
@@ -215,6 +308,18 @@ function findLaneNumber(laneSummary, taskId) {
215
308
  return null;
216
309
  }
217
310
 
311
+ /**
312
+ * Render SBAR-shaped recommendation commands (suggested command + unique
313
+ * alternatives).
314
+ *
315
+ * @param {{ suggestedCommand?: string|null, alternatives?: string[] }} data
316
+ * @returns {string[]}
317
+ */
318
+ function buildRecommendationCommands(data) {
319
+ const candidates = [data.suggestedCommand, ...(data.alternatives ?? [])];
320
+ return [...new Set(candidates.filter((command) => typeof command === "string" && command.trim().length > 0))];
321
+ }
322
+
218
323
  /**
219
324
  * @param {ReturnType<typeof assembleHandoffData>} data
220
325
  */
@@ -225,18 +330,27 @@ export function renderHandoffMarkdown(data) {
225
330
  `**Generated at:** ${data.generatedAt}`,
226
331
  `**Batch ID:** ${data.batchId ?? "—"}`,
227
332
  "",
228
- "## Diagnosis",
229
- `**${data.diagnosis}** — ${data.headline}`,
230
- "",
231
- "## Suggested command",
232
- data.suggestedCommand,
333
+ // SBAR order (#279): Situation → Background → Assessment → Recommendation.
334
+ "## Situation",
335
+ `**${data.diagnosis ?? "idle"}** — ${data.headline ?? "—"}`,
233
336
  "",
234
- "## Alternatives",
337
+ "## Background",
235
338
  ];
236
339
 
237
- if (data.alternatives?.length) {
238
- for (const alt of data.alternatives) {
239
- lines.push(`- ${alt}`);
340
+ const backgroundFacts = resolveBackgroundFacts(data);
341
+ if (backgroundFacts.length) {
342
+ for (const fact of backgroundFacts) {
343
+ lines.push(`- ${fact}`);
344
+ }
345
+ } else {
346
+ lines.push("- (none)");
347
+ }
348
+
349
+ lines.push("", "## Assessment", resolveAssessmentReason(data), "", "## Recommendation");
350
+ const recommendations = buildRecommendationCommands(data);
351
+ if (recommendations.length) {
352
+ for (const command of recommendations) {
353
+ lines.push(`- ${command}`);
240
354
  }
241
355
  } else {
242
356
  lines.push("- (none)");
@@ -12,6 +12,8 @@ import {
12
12
  assembleHandoffData,
13
13
  redactHandoffSecrets,
14
14
  redactHandoffText,
15
+ resolveAssessmentReason,
16
+ resolveBackgroundFacts,
15
17
  } from "./handoff.mjs";
16
18
 
17
19
  const VALID_ISSUE_TYPES = new Set(["bug", "enhancement", "question"]);
@@ -36,13 +38,15 @@ function formatDoctorSummary(doctorResult) {
36
38
  }
37
39
 
38
40
  /**
41
+ * Situation block for the issue draft (#279): current-state snapshot without
42
+ * the suggested command, which the Recommendation section owns.
43
+ *
39
44
  * @param {ReturnType<typeof reconcileBatch>} reconciliation
40
45
  */
41
46
  function formatDiagnosisBlock(reconciliation) {
42
47
  const lines = [
43
48
  `- **Diagnosis:** ${reconciliation.diagnosis ?? "idle"}`,
44
49
  `- **Headline:** ${reconciliation.headline ?? "—"}`,
45
- `- **Suggested command:** ${reconciliation.suggestedCommand ?? "—"}`,
46
50
  ];
47
51
  if (reconciliation.batchId) {
48
52
  lines.push(`- **Batch ID:** ${reconciliation.batchId}`);
@@ -95,13 +99,34 @@ function readPackageVersion() {
95
99
  }
96
100
 
97
101
  /**
98
- * Render issue draft markdown sections for GitHub filing.
102
+ * Render a value as markdown bullet lines, or explicit `(none)` when empty.
103
+ *
104
+ * @param {unknown} value
105
+ * @returns {string}
106
+ */
107
+ function orNoneBullets(value) {
108
+ if (Array.isArray(value)) {
109
+ const entries = value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
110
+ return entries.length ? entries.map((entry) => `- ${entry}`).join("\n") : "(none)";
111
+ }
112
+ if (typeof value === "string" && value.trim().length > 0) {
113
+ return `- ${value}`;
114
+ }
115
+ return "(none)";
116
+ }
117
+
118
+ /**
119
+ * Render issue draft markdown sections for GitHub filing. SBAR-shaped per
120
+ * #279: Situation → Background → Assessment → Recommendation.
99
121
  *
100
122
  * @param {object} sections
101
123
  * @param {string} sections.summary
102
124
  * @param {string} sections.environment
125
+ * @param {string} sections.situation
126
+ * @param {unknown} [sections.background]
127
+ * @param {string} [sections.assessment]
128
+ * @param {unknown} [sections.recommendation]
103
129
  * @param {string} sections.commandsRun
104
- * @param {string} sections.diagnosis
105
130
  * @param {string} sections.journalExcerpt
106
131
  * @param {string} [sections.expected]
107
132
  * @param {string} [sections.actual]
@@ -114,12 +139,21 @@ export function formatIssueDraftMarkdown(sections) {
114
139
  "## Environment",
115
140
  sections.environment,
116
141
  "",
142
+ "## Situation",
143
+ sections.situation,
144
+ "",
145
+ "## Background",
146
+ orNoneBullets(sections.background),
147
+ "",
148
+ "## Assessment",
149
+ sections.assessment && sections.assessment.trim().length > 0 ? sections.assessment : "(none)",
150
+ "",
151
+ "## Recommendation",
152
+ orNoneBullets(sections.recommendation),
153
+ "",
117
154
  "## Commands run",
118
155
  sections.commandsRun,
119
156
  "",
120
- "## Diagnosis",
121
- sections.diagnosis,
122
- "",
123
157
  "## Journal excerpt",
124
158
  sections.journalExcerpt,
125
159
  "",
@@ -161,8 +195,26 @@ export function buildIssueDraftBody(options) {
161
195
  "",
162
196
  formatDoctorSummary(doctorResult),
163
197
  ].join("\n"),
198
+ situation: formatDiagnosisBlock(reconciliation),
199
+ background: resolveBackgroundFacts({
200
+ background: reconciliation.background,
201
+ phase: reconciliation.phase ?? null,
202
+ pendingTasks: handoff.pendingTasks,
203
+ journalTail: handoff.journalTail,
204
+ }),
205
+ assessment: resolveAssessmentReason({
206
+ assessmentReason: reconciliation.assessmentReason,
207
+ diagnosis: reconciliation.diagnosis,
208
+ headline: reconciliation.headline,
209
+ }),
210
+ recommendation: [
211
+ ...new Set(
212
+ [reconciliation.suggestedCommand, ...(reconciliation.alternatives ?? [])].filter(
213
+ (command) => typeof command === "string" && command.trim().length > 0,
214
+ ),
215
+ ),
216
+ ],
164
217
  commandsRun: formatCommandsRun(reconciliation),
165
- diagnosis: formatDiagnosisBlock(reconciliation),
166
218
  journalExcerpt: formatJournalExcerpt(handoff),
167
219
  expected: "(describe expected behavior)",
168
220
  actual: "(describe actual behavior)",
@@ -120,3 +120,27 @@ export function applyMatrixRowToSteps(steps, row) {
120
120
  body: substituteMatrixVariables(step.body, row),
121
121
  }));
122
122
  }
123
+
124
+ /**
125
+ * Substitute `{matrix.<column>}` placeholders across an entire raw PROMPT.md
126
+ * document for one matrix row. This is the LLM-row serving vehicle (#232):
127
+ * workers consume the raw markdown, so whole-document substitution is the
128
+ * composition of `applyMatrixRowToSteps` (step titles/bodies),
129
+ * `applyMatrixRowToContract` (contract table fields), and the File Scope paths
130
+ * in a single pass, with the same fail-loud semantics via
131
+ * `substituteMatrixVariables` — an unknown `{matrix.X}` reference throws.
132
+ *
133
+ * The input is returned unchanged when no row is supplied or the row is empty
134
+ * (non-matrix tasks keep their PROMPT verbatim), mirroring the guards on the
135
+ * structured helpers.
136
+ *
137
+ * @param {string} promptText Raw PROMPT.md content.
138
+ * @param {Record<string, string> | null | undefined} row Matrix row values keyed by column.
139
+ * @returns {string}
140
+ */
141
+ export function applyMatrixRowToPrompt(promptText, row) {
142
+ if (typeof promptText !== "string" || !row || Object.keys(row).length === 0) {
143
+ return promptText;
144
+ }
145
+ return substituteMatrixVariables(promptText, row);
146
+ }
@@ -44,7 +44,7 @@ The engine journals `supervisor.started` (batchId, model, pid) when the monitor
44
44
  | `limbo_stale` / `completed_manual` | `dismiss` or `complete --detect-manual-merge` |
45
45
  | `failed` / `aborted` | `retry`, `resume --force`, or `dismiss` |
46
46
 
47
- Full operator procedures: [operator runbook](../../docs/adoption/operator-runbook.md).
47
+ Full operator procedures: [operator runbook](../../docs/adoption/operator-runbook.md). Handoff quality bar (#282): incomplete handoff = missing any of Situation / Background / Assessment / Recommendation — see the [runbook handoff packet](../../docs/adoption/operator-runbook.md#operator-handoff-packet-282).
48
48
 
49
49
  In pi: `/spine-status` mirrors reconciliation; `/spine-dashboard` opens the dashboard.
50
50
 
@@ -18,6 +18,10 @@ Greenfield pi-spine project. Add phase tables and task rows as you decompose wor
18
18
 
19
19
  ---
20
20
 
21
+ ## Authoring notes
22
+
23
+ - New packets: use `**Risk:**` (severity/blast, pairs with **Score**) and `**Problem theory:**` (working diagnosis) in the Review Level block instead of the legacy overloaded `**Assessment:**` ([pi-spine #281](https://github.com/beettlle/pi-spine/issues/281)). Legacy `**Assessment:**` packets remain valid — do not rewrite them.
24
+
21
25
  ## Execution policy
22
26
 
23
27
  **Operator runbook:** [`docs/adoption/operator-runbook.md`](../docs/adoption/operator-runbook.md) — install, preflight, start/monitor, land loop, gate races, resume/dismiss/complete, dashboard, troubleshooting.