pi-spine 2.18.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.
@@ -37,8 +37,24 @@ export function runSpineStatus(options) {
37
37
  lines.push(` Macro phase: ${result.macroPhaseLabel ?? result.macroPhase}`);
38
38
  }
39
39
 
40
- lines.push("", ` ${result.headline}`, "");
41
- lines.push(` → ${result.suggestedCommand}`);
40
+ if (diagnose && result.headline != null) {
41
+ // SBAR handoff layout (#278 / SP-745): Situation → Background → Assessment → Recommendation.
42
+ lines.push("", ` Situation: ${result.headline}`);
43
+ if (result.background?.length) {
44
+ lines.push("", " Background:");
45
+ for (const fact of result.background) {
46
+ lines.push(` • ${fact}`);
47
+ }
48
+ }
49
+ if (result.assessmentReason) {
50
+ lines.push("", ` Assessment: ${result.diagnosis} — ${result.assessmentReason}`);
51
+ }
52
+ lines.push("");
53
+ lines.push(` Recommendation: ${result.suggestedCommand}`);
54
+ } else {
55
+ lines.push("", ` ${result.headline}`, "");
56
+ lines.push(` → ${result.suggestedCommand}`);
57
+ }
42
58
 
43
59
  if (diagnose && result.mergeFailed) {
44
60
  lines.push("");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.18.0",
3
+ "version": "2.19.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -15,8 +15,11 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
15
15
 
16
16
  ## Review Level: [0-3] ([None | Plan Only | Plan and Code | Full])
17
17
 
18
- **Assessment:** [1-2 sentences explaining the score]
18
+ **Risk:** [1-2 sentences: severity/blast radius — what breaks and how far the change reaches]
19
19
  **Score:** [N]/8 — Blast radius: [N], Pattern novelty: [N], Security: [N], Reversibility: [N]
20
+ **Problem theory:** [Optional, bug-fix tasks — working diagnosis: why the fault occurs and why this change resolves it]
21
+
22
+ > **Assessment disambiguation ([#281](https://github.com/beettlle/pi-spine/issues/281)):** Use `**Risk:**` for severity/blast (pairs with **Score**) and `**Problem theory:**` for the working diagnosis. Legacy `**Assessment:**` alone remains accepted by tooling and validators — do not mass-rewrite historical packets.
20
23
 
21
24
  > **Real-pi batches (SP-195/SP-278):** Do **not** add per-step "Call `spine_review_step`" checkboxes for Review Level ≥ 1. The batch engine runs plan, code, and final reviews after worker `.DONE`. Stub batches (`SPINE_WORKER_STUB=1`) may still use in-worker stub plan review via the tool when a checkpoint marker requires it.
22
25
 
@@ -180,6 +183,18 @@ for this task MUST include the task ID for traceability:
180
183
 
181
184
  ---
182
185
 
186
+ ## Example — Review Level block fields ([#281](https://github.com/beettlle/pi-spine/issues/281))
187
+
188
+ Use unambiguous field names: `**Risk:**` for severity/blast (pairs with **Score**), `**Problem theory:**` for the working diagnosis. Legacy `**Assessment:**` alone remains valid — do not mass-rewrite historical packets.
189
+
190
+ ```markdown
191
+ **Risk:** Docs and templates only; no runtime code paths touched.
192
+ **Score:** 1/8 — Blast radius: 1, Pattern novelty: 0, Security: 0, Reversibility: 0
193
+ **Problem theory:** The `Assessment` field was overloaded — packets used it for score blurbs and fault theories interchangeably, so workers could not tell severity from diagnosis.
194
+ ```
195
+
196
+ ---
197
+
183
198
  # STATUS.md Template
184
199
 
185
200
  Create alongside PROMPT.md. If omitted, the execution engine may auto-generate
@@ -0,0 +1,148 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Diagnose handoff packet fields (#278 / SP-745) — SBAR Background + Assessment rationale.
4
+ * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
+ */
6
+
7
+ /**
8
+ * SBAR Background — short decision-relevant facts that explain the state the
9
+ * assessment was derived from. Facts are additive; consumers that ignore
10
+ * unknown fields keep working.
11
+ *
12
+ * @param {string} diagnosis
13
+ * @param {object} ctx
14
+ * @returns {string[]}
15
+ */
16
+ export function buildBackground(diagnosis, ctx = {}) {
17
+ const facts = [];
18
+ if (ctx.batchId) {
19
+ facts.push(`Batch: ${ctx.batchId}`);
20
+ }
21
+ if (ctx.phase || ctx.macroPhase) {
22
+ facts.push(`Phase: ${ctx.phase ?? "unknown"}${ctx.macroPhase ? ` (macro: ${ctx.macroPhase})` : ""}`);
23
+ }
24
+ if (ctx.totalTasks != null) {
25
+ const progressBits = [`${ctx.succeededTasks ?? 0}/${ctx.totalTasks} tasks succeeded`];
26
+ if (ctx.failedTasks) progressBits.push(`${ctx.failedTasks} failed`);
27
+ if (ctx.pendingTaskCount) progressBits.push(`${ctx.pendingTaskCount} pending`);
28
+ facts.push(`Progress: ${progressBits.join(", ")}`);
29
+ }
30
+ if (ctx.failedTaskId) {
31
+ facts.push(
32
+ `Failed task: ${ctx.failedTaskId}${ctx.exitReason ? ` (exit: ${ctx.exitReason})` : ""}`,
33
+ );
34
+ }
35
+ if (ctx.launchFailureKind) {
36
+ facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
37
+ }
38
+ if (ctx.engineStillRunning === true && ctx.enginePid != null) {
39
+ facts.push(`Engine PID ${ctx.enginePid} is still running`);
40
+ }
41
+ if (ctx.staleEnginePid === true && ctx.enginePid != null) {
42
+ facts.push(`Engine PID ${ctx.enginePid} is stale (process not alive)`);
43
+ }
44
+ if (ctx.engineOrphanCause) {
45
+ facts.push(`Engine orphan cause: ${ctx.engineOrphanCause}`);
46
+ }
47
+ if (ctx.mergeFailed) {
48
+ facts.push(
49
+ `Lane merge failed${ctx.failedWaveIndex != null ? ` (wave index ${ctx.failedWaveIndex})` : ""}`,
50
+ );
51
+ }
52
+ if (ctx.gitMerged === true) {
53
+ facts.push(`Orch branch already merged to ${ctx.baseBranch ?? "base"}`);
54
+ }
55
+ if (ctx.integrateGateOpen === true) {
56
+ facts.push("Integrate gate is open");
57
+ }
58
+ if (ctx.salvageRetryCommand) {
59
+ facts.push(`Tried: ${ctx.salvageRetryCommand}`);
60
+ }
61
+ if (Array.isArray(ctx.journalHints)) {
62
+ for (const hint of ctx.journalHints) {
63
+ if (typeof hint === "string") {
64
+ facts.push(`Journal: ${hint}`);
65
+ } else if (hint && typeof hint === "object" && (hint.summary || hint.type)) {
66
+ facts.push(`Journal: ${hint.type ?? "event"}${hint.summary ? ` — ${hint.summary}` : ""}`);
67
+ }
68
+ }
69
+ }
70
+ return facts;
71
+ }
72
+
73
+ /**
74
+ * SBAR Assessment rationale — why this diagnosis enum was selected from
75
+ * reconcile signals, not just its label.
76
+ *
77
+ * @param {string} diagnosis
78
+ * @param {object} ctx
79
+ * @returns {string}
80
+ */
81
+ export function buildAssessmentReason(diagnosis, ctx = {}) {
82
+ switch (diagnosis) {
83
+ case "engine_still_running":
84
+ return `Engine PID ${ctx.enginePid ?? "?"} is alive, so completion was refused to avoid clobbering an active run`;
85
+ case "limbo_stale":
86
+ return "Batch ended but state is stale and no engine or worker is active — only a dismiss can clear it";
87
+ case "completed_manual":
88
+ return "Work is already on the base branch while the batch record is still active — operator completed it manually";
89
+ case "needs_retry":
90
+ if (ctx.failedTaskId && ctx.exitReason) {
91
+ return `Task ${ctx.failedTaskId} exited "${ctx.exitReason}" without completing its contract, so the batch cannot proceed until it is retried`;
92
+ }
93
+ if (ctx.failedTaskId) {
94
+ return `Worker for task ${ctx.failedTaskId} died before writing .DONE, so the batch cannot proceed until it is retried`;
95
+ }
96
+ return "Failed phase left only pending tasks with no live workers — retry limbo resolves as a retry";
97
+ case "state_drift":
98
+ return ctx.failedTaskId
99
+ ? `Journal history for task ${ctx.failedTaskId} disagrees with the batch-state cache — no single source of truth`
100
+ : "Journal history disagrees with the batch-state cache — no single source of truth";
101
+ case "worker_orphaned":
102
+ if (ctx.engineDead) {
103
+ return `Engine and lane worker both died while task ${ctx.failedTaskId ?? "?"} was still running`;
104
+ }
105
+ if (ctx.ghostRunningCluster) {
106
+ return `Lane worker died but multiple tasks are still marked running (ghost running cluster)${ctx.failedTaskId ? `, e.g. ${ctx.failedTaskId}` : ""}`;
107
+ }
108
+ return `Lane worker stopped while task ${ctx.failedTaskId ?? "?"} was still marked running — heartbeats ended without a terminal journal event`;
109
+ case "worker_done_missing":
110
+ return `Task ${ctx.failedTaskId ?? "?"} reported progress in the journal but no .DONE file was found in the lane or batch tasks root`;
111
+ case "engine_orphaned":
112
+ if (ctx.engineOrphanCause) {
113
+ return `Engine process is gone (${ctx.engineOrphanCause}) while tasks were still running`;
114
+ }
115
+ return `Engine process died mid-run${ctx.failedTaskId ? ` with task ${ctx.failedTaskId} still running` : ""} — journal has no engine shutdown event`;
116
+ case "needs_merge":
117
+ return "All assigned tasks finished in their lanes, but lane merges into the orch branch are still pending";
118
+ case "needs_integrate":
119
+ if (ctx.integrateGateOpen) {
120
+ return "Land loop is paused at the integrate gate with the gate open — approval continues the land";
121
+ }
122
+ return `Tasks are terminal-success and merged to the orch branch, which is not yet integrated into ${ctx.baseBranch ?? "base"}`;
123
+ case "needs_replan":
124
+ return ctx.failedTaskId
125
+ ? `Task ${ctx.failedTaskId} failed in a way that requires a contract (PROMPT.md) change, not just a retry`
126
+ : "Failed tasks require a contract (PROMPT.md) change, not just a retry";
127
+ case "running":
128
+ return "Engine and workers are alive with no failure, drift, or orphan signals observed";
129
+ case "paused":
130
+ return `Batch was paused by an operator or gate with ${ctx.pendingTaskCount ?? 0} task(s) pending — resume continues from journal state`;
131
+ case "failed":
132
+ return `Batch recorded failure in phase ${ctx.phase ?? "unknown"} (${ctx.failedTasks ?? 0} failed task(s)) with no recoverable retry path`;
133
+ case "aborted":
134
+ return "Batch was aborted by an operator; state remains for audit";
135
+ case "completed":
136
+ return `All tasks succeeded and the orch branch landed on ${ctx.baseBranch ?? "base"}`;
137
+ case "human_base_diverged": {
138
+ const overlapCount = Array.isArray(ctx.overlapPaths) ? ctx.overlapPaths.length : 0;
139
+ return `Human commits on ${ctx.baseBranch ?? "base"} overlap orch land${overlapCount > 0 ? ` (${overlapCount} path(s))` : ""} — reconciliation needs a human sync decision`;
140
+ }
141
+ case "integrate_isolated_ok":
142
+ return "Isolated integrate landed cleanly; the human checkout only needs a sync with base";
143
+ case "pending_lane_land":
144
+ return "Done-in-lane work is sitting in lane worktrees waiting to be landed";
145
+ default:
146
+ return `Reconcile signals selected "${diagnosis}" for phase ${ctx.phase ?? "unknown"}`;
147
+ }
148
+ }
@@ -0,0 +1,177 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Operator suggestedCommand builders — extracted from diagnosis.mjs for phase23 LOC.
4
+ */
5
+ import { buildWorkerDoneMissingSuggestedCommand } from "./diagnosis-worker-done-missing.mjs";
6
+ import {
7
+ buildFailedPhasePendingOnlySuggestedCommand,
8
+ isFailedPhasePendingOnlyLimbo,
9
+ } from "./diagnosis-retry-limbo.mjs";
10
+ import {
11
+ buildGitignoredMergeRepairCommand,
12
+ shouldPreferPrimaryOverGitignoredHeadline,
13
+ } from "./diagnosis-merge-failure.mjs";
14
+ import {
15
+ buildStubFailureSuggestedCommand,
16
+ STUB_EXIT_REASONS,
17
+ } from "./diagnosis-stub.mjs";
18
+ import { buildPrimaryFailureSuggestedCommand } from "./diagnosis-primary-failure.mjs";
19
+ import { buildEngineOrphanParentExitSuggestedCommand } from "./diagnosis-parent-exit.mjs";
20
+ import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
21
+ import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.mjs";
22
+
23
+ /**
24
+ * @param {string} diagnosis
25
+ * @param {object} [ctx]
26
+ * @param {string|null} [ctx.failedTaskId]
27
+ * @param {string|null} [ctx.batchId]
28
+ * @param {string|null} [ctx.salvageRetryCommand]
29
+ * @param {string|null} [ctx.exitReason]
30
+ * @param {string|null} [ctx.launchFailureKind]
31
+ * @param {boolean} [ctx.mergeGitignoredFailure]
32
+ * @param {boolean} [ctx.mergeFailed]
33
+ * @param {string|null} [ctx.taskBranch]
34
+ * @param {string[]|null} [ctx.gitignoredPaths]
35
+ * @param {object[]} [ctx.pendingLaneLandTasks]
36
+ */
37
+ export function buildSuggestedCommand(diagnosis, ctx = {}) {
38
+ const preferPrimaryOverGitignored = shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx);
39
+ // Prefer gate-approve / orphan primary over recovered merge/gitignored repair (#195 / #205).
40
+ if (ctx.mergeGitignoredFailure && !preferPrimaryOverGitignored) {
41
+ return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
42
+ }
43
+ if (
44
+ ctx.mergeFailed &&
45
+ !preferPrimaryOverGitignored &&
46
+ (diagnosis === "failed" || diagnosis === "needs_retry")
47
+ ) {
48
+ return "spine batch resume --force";
49
+ }
50
+ if (ctx.phase === "merge_blocked") {
51
+ return "spine batch resume --force";
52
+ }
53
+
54
+ switch (diagnosis) {
55
+ case "engine_still_running":
56
+ return "spine wait --until completed,failed,needs_integrate --timeout 2h";
57
+ case "limbo_stale":
58
+ case "completed_manual":
59
+ return "spine batch dismiss";
60
+ case "state_drift":
61
+ // Agent-safe detached recovery (#196 / SP-613) — never suggest --attached.
62
+ if (
63
+ ctx.phase === "running" ||
64
+ ctx.staleEnginePid === true ||
65
+ ctx.engineDead === true ||
66
+ ctx.allTasksTerminalSuccess === true
67
+ ) {
68
+ return "spine batch resume --force";
69
+ }
70
+ if (ctx.failedTaskId) {
71
+ const driftStatus = String(ctx.driftTaskStatus ?? "").toLowerCase();
72
+ if (driftStatus === "running") {
73
+ return "spine batch resume --force";
74
+ }
75
+ return `spine batch retry ${ctx.failedTaskId}`;
76
+ }
77
+ return "spine status --diagnose";
78
+ case "needs_retry":
79
+ if (STUB_EXIT_REASONS.has(ctx.exitReason ?? "")) {
80
+ return buildStubFailureSuggestedCommand(ctx);
81
+ }
82
+ const primaryCommand = buildPrimaryFailureSuggestedCommand(ctx);
83
+ if (primaryCommand) return primaryCommand;
84
+ if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
85
+ return "spine doctor";
86
+ }
87
+ if (ctx.launchFailureKind === "worktree_unhealthy") {
88
+ return "spine doctor";
89
+ }
90
+ if (ctx.salvageRetryCommand) {
91
+ return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
92
+ }
93
+ if (isFailedPhasePendingOnlyLimbo(ctx)) {
94
+ return buildFailedPhasePendingOnlySuggestedCommand(ctx);
95
+ }
96
+ return ctx.failedTaskId
97
+ ? `spine batch retry ${ctx.failedTaskId}`
98
+ : "spine status --diagnose";
99
+ case "worker_orphaned":
100
+ if (ctx.planReviewNestedSpawnBlocked) {
101
+ if (ctx.stalePathSpine) {
102
+ return ctx.failedTaskId
103
+ ? `node bin/spine.mjs batch retry ${ctx.failedTaskId}`
104
+ : "npm link && spine batch resume --attached";
105
+ }
106
+ if (ctx.failedTaskId) {
107
+ return `spine batch retry ${ctx.failedTaskId}`;
108
+ }
109
+ }
110
+ if (ctx.engineDead) {
111
+ return "spine batch resume --attached --force";
112
+ }
113
+ if (ctx.ghostRunningCluster) return "spine batch abort";
114
+ if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
115
+ return "spine doctor";
116
+ }
117
+ if (ctx.launchFailureKind === "worktree_unhealthy") {
118
+ return "spine doctor";
119
+ }
120
+ if (ctx.salvageRetryCommand) {
121
+ return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
122
+ }
123
+ return ctx.failedTaskId
124
+ ? `spine batch retry ${ctx.failedTaskId}`
125
+ : "spine batch abort";
126
+ case "worker_done_missing":
127
+ return buildWorkerDoneMissingSuggestedCommand(ctx);
128
+ case "engine_orphaned": {
129
+ const parentExitCommand = buildEngineOrphanParentExitSuggestedCommand(ctx);
130
+ if (parentExitCommand) return parentExitCommand;
131
+ // Terminal-success / doneInLane heal with dead engine — detached resume (#196 / #163).
132
+ if (ctx.allTasksTerminalSuccess === true) {
133
+ return "spine batch resume --force";
134
+ }
135
+ return ctx.failedTaskId
136
+ ? `spine batch retry ${ctx.failedTaskId}`
137
+ : "spine batch resume --attached";
138
+ }
139
+ case "needs_merge":
140
+ return "spine batch resume --force";
141
+ case "needs_integrate":
142
+ if (ctx.integrateGateOpen) {
143
+ return "spine gate approve";
144
+ }
145
+ if (ctx.postMergeLimbo && ctx.phase === "running") {
146
+ if (ctx.stalePathSpine) {
147
+ return "node bin/spine.mjs batch resume --attached";
148
+ }
149
+ return "spine batch resume --force";
150
+ }
151
+ return "spine integrate";
152
+ case "needs_replan": {
153
+ const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
154
+ return ctx.failedTaskId
155
+ ? `edit ${tasksRoot}/${ctx.failedTaskId}/PROMPT.md then spine batch retry ${ctx.failedTaskId}`
156
+ : "spine status --diagnose";
157
+ }
158
+ case "running":
159
+ return "/spine-status --diagnose";
160
+ case "paused":
161
+ return "spine batch resume";
162
+ case "failed":
163
+ return "spine status --diagnose";
164
+ case "aborted":
165
+ return "spine batch dismiss";
166
+ case "completed":
167
+ return "spine preflight";
168
+ case "human_base_diverged":
169
+ return "spine sync-base";
170
+ case "integrate_isolated_ok":
171
+ return "spine sync-base";
172
+ case "pending_lane_land":
173
+ return buildPendingLaneLandSuggestedCommand(ctx.batchId, ctx.pendingLaneLandTasks ?? []);
174
+ default:
175
+ return "spine status --diagnose";
176
+ }
177
+ }
@@ -4,18 +4,15 @@
4
4
  */
5
5
  import {
6
6
  buildWorkerDoneMissingHeadline,
7
- buildWorkerDoneMissingSuggestedCommand,
8
7
  } from "./diagnosis-worker-done-missing.mjs";
9
8
  import {
10
9
  buildFailedPhasePendingOnlyHeadline,
11
- buildFailedPhasePendingOnlySuggestedCommand,
12
10
  isFailedPhasePendingOnlyLimbo,
13
11
  } from "./diagnosis-retry-limbo.mjs";
14
12
  import { buildAlternatives } from "./diagnosis-alternatives.mjs";
15
13
  export { buildAlternatives } from "./diagnosis-alternatives.mjs";
16
14
  import {
17
15
  buildMergeFailureHeadline,
18
- buildGitignoredMergeRepairCommand,
19
16
  shouldPreferPrimaryOverGitignoredHeadline,
20
17
  } from "./diagnosis-merge-failure.mjs";
21
18
  export {
@@ -36,7 +33,6 @@ export {
36
33
  export { buildReviewHonorHeadlineSuffix, findLatestReviewHonorSignal } from "./review.mjs";
37
34
  import {
38
35
  buildStubFailureHeadline,
39
- buildStubFailureSuggestedCommand,
40
36
  STUB_EXIT_REASONS,
41
37
  } from "./diagnosis-stub.mjs";
42
38
  /** @typedef {import("./reconcile.mjs").ReconciliationResult} ReconciliationResult */
@@ -48,11 +44,9 @@ export {
48
44
  } from "./diagnosis-task-done.mjs";
49
45
  import {
50
46
  buildPrimaryFailureHeadline,
51
- buildPrimaryFailureSuggestedCommand,
52
47
  } from "./diagnosis-primary-failure.mjs";
53
48
  import {
54
49
  buildEngineOrphanParentExitHeadline,
55
- buildEngineOrphanParentExitSuggestedCommand,
56
50
  } from "./diagnosis-parent-exit.mjs";
57
51
  export {
58
52
  inferEngineOrphanCause,
@@ -63,11 +57,9 @@ import { buildReviewHonorHeadlineSuffix } from "./review.mjs";
63
57
  export { inferLaunchFailureFromWorkerOutputTail, inferLaunchFailureKind } from "./diagnosis-launch-failure.mjs";
64
58
  import { isGateReadyHeadlineContext } from "./diagnosis-gate-ready.mjs";
65
59
  export { isGateReadyHeadlineContext };
66
- import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
67
- export { sanitizeRetrySuggestedCommand };
60
+ export { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
68
61
  import {
69
62
  buildPendingLaneLandHeadline,
70
- buildPendingLaneLandSuggestedCommand,
71
63
  } from "./diagnosis-pending-lane.mjs";
72
64
  export {
73
65
  buildPendingLaneLandHeadline,
@@ -75,6 +67,10 @@ export {
75
67
  findPendingLaneLandTasks,
76
68
  shouldDiagnosePendingLaneLand,
77
69
  } from "./diagnosis-pending-lane.mjs";
70
+ export { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
71
+ import { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
72
+ export { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
73
+ import { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
78
74
 
79
75
  export const DIAGNOSIS_TAXONOMY = [
80
76
  "running",
@@ -113,162 +109,6 @@ const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
113
109
  "final_review_timeout",
114
110
  ]);
115
111
 
116
- /**
117
- * @param {string} diagnosis
118
- * @param {object} [ctx]
119
- * @param {string|null} [ctx.failedTaskId]
120
- * @param {string|null} [ctx.batchId]
121
- * @param {string|null} [ctx.salvageRetryCommand]
122
- * @param {string|null} [ctx.exitReason]
123
- * @param {string|null} [ctx.launchFailureKind]
124
- * @param {boolean} [ctx.mergeGitignoredFailure]
125
- * @param {boolean} [ctx.mergeFailed]
126
- * @param {string|null} [ctx.taskBranch]
127
- * @param {string[]|null} [ctx.gitignoredPaths]
128
- * @param {object[]} [ctx.pendingLaneLandTasks]
129
- */
130
- export function buildSuggestedCommand(diagnosis, ctx = {}) {
131
- const preferPrimaryOverGitignored = shouldPreferPrimaryOverGitignoredHeadline(diagnosis, ctx);
132
- // Prefer gate-approve / orphan primary over recovered merge/gitignored repair (#195 / #205).
133
- if (ctx.mergeGitignoredFailure && !preferPrimaryOverGitignored) {
134
- return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
135
- }
136
- if (
137
- ctx.mergeFailed &&
138
- !preferPrimaryOverGitignored &&
139
- (diagnosis === "failed" || diagnosis === "needs_retry")
140
- ) {
141
- return "spine batch resume --force";
142
- }
143
- if (ctx.phase === "merge_blocked") {
144
- return "spine batch resume --force";
145
- }
146
-
147
- switch (diagnosis) {
148
- case "engine_still_running":
149
- return "spine wait --until completed,failed,needs_integrate --timeout 2h";
150
- case "limbo_stale":
151
- case "completed_manual":
152
- return "spine batch dismiss";
153
- case "state_drift":
154
- // Agent-safe detached recovery (#196 / SP-613) — never suggest --attached.
155
- if (
156
- ctx.phase === "running" ||
157
- ctx.staleEnginePid === true ||
158
- ctx.engineDead === true ||
159
- ctx.allTasksTerminalSuccess === true
160
- ) {
161
- return "spine batch resume --force";
162
- }
163
- if (ctx.failedTaskId) {
164
- const driftStatus = String(ctx.driftTaskStatus ?? "").toLowerCase();
165
- if (driftStatus === "running") {
166
- return "spine batch resume --force";
167
- }
168
- return `spine batch retry ${ctx.failedTaskId}`;
169
- }
170
- return "spine status --diagnose";
171
- case "needs_retry":
172
- if (STUB_EXIT_REASONS.has(ctx.exitReason ?? "")) {
173
- return buildStubFailureSuggestedCommand(ctx);
174
- }
175
- const primaryCommand = buildPrimaryFailureSuggestedCommand(ctx);
176
- if (primaryCommand) return primaryCommand;
177
- if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
178
- return "spine doctor";
179
- }
180
- if (ctx.launchFailureKind === "worktree_unhealthy") {
181
- return "spine doctor";
182
- }
183
- if (ctx.salvageRetryCommand) {
184
- return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
185
- }
186
- if (isFailedPhasePendingOnlyLimbo(ctx)) {
187
- return buildFailedPhasePendingOnlySuggestedCommand(ctx);
188
- }
189
- return ctx.failedTaskId
190
- ? `spine batch retry ${ctx.failedTaskId}`
191
- : "spine status --diagnose";
192
- case "worker_orphaned":
193
- if (ctx.planReviewNestedSpawnBlocked) {
194
- if (ctx.stalePathSpine) {
195
- return ctx.failedTaskId
196
- ? `node bin/spine.mjs batch retry ${ctx.failedTaskId}`
197
- : "npm link && spine batch resume --attached";
198
- }
199
- if (ctx.failedTaskId) {
200
- return `spine batch retry ${ctx.failedTaskId}`;
201
- }
202
- }
203
- if (ctx.engineDead) {
204
- return "spine batch resume --attached --force";
205
- }
206
- if (ctx.ghostRunningCluster) return "spine batch abort";
207
- if (ctx.launchFailureKind === "pi_spine_root" || ctx.launchFailureKind === "launch_failed") {
208
- return "spine doctor";
209
- }
210
- if (ctx.launchFailureKind === "worktree_unhealthy") {
211
- return "spine doctor";
212
- }
213
- if (ctx.salvageRetryCommand) {
214
- return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
215
- }
216
- return ctx.failedTaskId
217
- ? `spine batch retry ${ctx.failedTaskId}`
218
- : "spine batch abort";
219
- case "worker_done_missing":
220
- return buildWorkerDoneMissingSuggestedCommand(ctx);
221
- case "engine_orphaned": {
222
- const parentExitCommand = buildEngineOrphanParentExitSuggestedCommand(ctx);
223
- if (parentExitCommand) return parentExitCommand;
224
- // Terminal-success / doneInLane heal with dead engine — detached resume (#196 / #163).
225
- if (ctx.allTasksTerminalSuccess === true) {
226
- return "spine batch resume --force";
227
- }
228
- return ctx.failedTaskId
229
- ? `spine batch retry ${ctx.failedTaskId}`
230
- : "spine batch resume --attached";
231
- }
232
- case "needs_merge":
233
- return "spine batch resume --force";
234
- case "needs_integrate":
235
- if (ctx.integrateGateOpen) {
236
- return "spine gate approve";
237
- }
238
- if (ctx.postMergeLimbo && ctx.phase === "running") {
239
- if (ctx.stalePathSpine) {
240
- return "node bin/spine.mjs batch resume --attached";
241
- }
242
- return "spine batch resume --force";
243
- }
244
- return "spine integrate";
245
- case "needs_replan": {
246
- const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
247
- return ctx.failedTaskId
248
- ? `edit ${tasksRoot}/${ctx.failedTaskId}/PROMPT.md then spine batch retry ${ctx.failedTaskId}`
249
- : "spine status --diagnose";
250
- }
251
- case "running":
252
- return "/spine-status --diagnose";
253
- case "paused":
254
- return "spine batch resume";
255
- case "failed":
256
- return "spine status --diagnose";
257
- case "aborted":
258
- return "spine batch dismiss";
259
- case "completed":
260
- return "spine preflight";
261
- case "human_base_diverged":
262
- return "spine sync-base";
263
- case "integrate_isolated_ok":
264
- return "spine sync-base";
265
- case "pending_lane_land":
266
- return buildPendingLaneLandSuggestedCommand(ctx.batchId, ctx.pendingLaneLandTasks ?? []);
267
- default:
268
- return "spine status --diagnose";
269
- }
270
- }
271
-
272
112
  /**
273
113
  * @param {string} diagnosis
274
114
  * @param {object} ctx
@@ -340,13 +180,13 @@ export function buildHeadline(diagnosis, ctx = {}) {
340
180
  const isFinal = ctx.exitReason.startsWith("final_review");
341
181
  const isTimeout = ctx.exitReason.endsWith("_timeout");
342
182
  const reviewKind = isFinal ? "final review" : "code review";
343
-
183
+
344
184
  if (isTimeout) {
345
185
  return ctx.failedTaskId
346
186
  ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
347
187
  : `${batchLabel} reviewer spawn timed out — retry`;
348
188
  }
349
-
189
+
350
190
  return ctx.failedTaskId
351
191
  ? `${batchLabel} ${reviewKind} spawn failed for task ${ctx.failedTaskId} — retry`
352
192
  : `${batchLabel} reviewer spawn failed — retry`;
@@ -482,7 +322,7 @@ export function resolveEffectiveDiagnosis(diagnosis, ctx = {}) {
482
322
  /**
483
323
  * @param {string} diagnosis
484
324
  * @param {object} ctx
485
- * @returns {Pick<ReconciliationResult, "diagnosis" | "headline" | "suggestedCommand" | "alternatives">}
325
+ * @returns {Pick<ReconciliationResult, "diagnosis" | "headline" | "suggestedCommand" | "alternatives"> & { background: string[], assessmentReason: string }}
486
326
  */
487
327
  export function buildDiagnosisOutput(diagnosis, ctx = {}) {
488
328
  const effectiveDiagnosis = resolveEffectiveDiagnosis(diagnosis, ctx);
@@ -491,5 +331,9 @@ export function buildDiagnosisOutput(diagnosis, ctx = {}) {
491
331
  headline: buildHeadline(effectiveDiagnosis, ctx),
492
332
  suggestedCommand: buildSuggestedCommand(effectiveDiagnosis, ctx),
493
333
  alternatives: buildAlternatives(effectiveDiagnosis, ctx),
334
+ // Additive SBAR fields (#278 / SP-745) — appended after legacy keys so
335
+ // consumers reading positional or partial fields are unaffected.
336
+ background: buildBackground(effectiveDiagnosis, ctx),
337
+ assessmentReason: buildAssessmentReason(effectiveDiagnosis, ctx),
494
338
  };
495
339
  }
@@ -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)",
@@ -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.