pi-spine 2.35.0 → 2.36.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.
@@ -63,9 +63,11 @@ export function resolveDashboardPort(projectRoot, cliPort) {
63
63
  * @param {object} options
64
64
  * @param {string} options.url
65
65
  * @param {string} options.host
66
- * @param {number} options.port
66
+ * @param {number} options.port Bound (listen) port — must match `url` (#388).
67
67
  * @param {string} [options.projectRoot]
68
68
  * @param {"cli"|"config"|"default"} [options.portSource]
69
+ * @param {number} [options.fallbackFromPort] Preferred port that was busy; when
70
+ * set, a busy→bound note is printed so the ephemeral move is never silent.
69
71
  * @returns {string}
70
72
  */
71
73
  export function formatDashboardStartupMessage({
@@ -73,6 +75,7 @@ export function formatDashboardStartupMessage({
73
75
  host,
74
76
  port,
75
77
  portSource = "default",
78
+ fallbackFromPort,
76
79
  }) {
77
80
  const base = url.endsWith("/") ? url.slice(0, -1) : url;
78
81
  const portNote = formatPortSourceNote(portSource);
@@ -84,6 +87,15 @@ export function formatDashboardStartupMessage({
84
87
  "",
85
88
  ` Open in browser: ${browserUrl}`,
86
89
  ` Listen: ${host}:${port}${portNote}`,
90
+ ];
91
+
92
+ if (fallbackFromPort != null) {
93
+ lines.push(
94
+ ` Note: preferred port ${fallbackFromPort} busy — bound ephemeral port ${port}`,
95
+ );
96
+ }
97
+
98
+ lines.push(
87
99
  "",
88
100
  " While running: keep this terminal open; dashboard updates via SSE (~2s)",
89
101
  "",
@@ -98,7 +110,7 @@ export function formatDashboardStartupMessage({
98
110
  "",
99
111
  " Stop: Ctrl+C",
100
112
  "",
101
- ];
113
+ );
102
114
 
103
115
  return lines.join("\n");
104
116
  }
@@ -126,6 +138,50 @@ Open in browser: ${browserUrl}
126
138
  CLI: \`spine dashboard\`${portHint}.`;
127
139
  }
128
140
 
141
+ /**
142
+ * Listen on the preferred port; on `EADDRINUSE` either fail with an
143
+ * operator-readable error (strict, for explicit `--port N > 0`) or retry on an
144
+ * OS-assigned ephemeral port (`port: 0`) and report the fallback (#388).
145
+ *
146
+ * The same server instance is reused for the retry: after a failed
147
+ * `listen()` the socket handle is released, so re-listening is safe.
148
+ *
149
+ * @param {object} options
150
+ * @param {import("node:http").Server} options.server
151
+ * @param {string} options.host
152
+ * @param {number} options.preferredPort
153
+ * @param {boolean} [options.strict]
154
+ * @returns {Promise<{ url: string, host: string, port: number, fallbackFromPort?: number }>}
155
+ * `fallbackFromPort` is set only when the preferred port was busy and the
156
+ * bind moved to an ephemeral port.
157
+ */
158
+ export async function listenDashboardWithFallback({
159
+ server,
160
+ host,
161
+ preferredPort,
162
+ strict = false,
163
+ }) {
164
+ try {
165
+ return await listenDashboardServer({ server, host, port: preferredPort });
166
+ } catch (err) {
167
+ if (err?.code !== "EADDRINUSE") throw err;
168
+
169
+ if (strict) {
170
+ const strictError = new Error(
171
+ `Dashboard port ${preferredPort} is already in use (--port ${preferredPort}). Free the port or run \`spine dashboard --port 0\` to bind an ephemeral port.`,
172
+ );
173
+ strictError.code = "EADDRINUSE";
174
+ strictError.cause = err;
175
+ throw strictError;
176
+ }
177
+
178
+ const bound = await listenDashboardServer({ server, host, port: 0 });
179
+ // A port-0 bind is already ephemeral; never print a nonsensical
180
+ // "preferred port 0 busy" note.
181
+ return preferredPort > 0 ? { ...bound, fallbackFromPort: preferredPort } : bound;
182
+ }
183
+ }
184
+
129
185
  /**
130
186
  * @param {object} options
131
187
  * @param {string} options.projectRoot
@@ -160,10 +216,37 @@ export async function runSpineDashboard({ projectRoot, args = [] }) {
160
216
  }
161
217
 
162
218
  const server = createDashboardServer({ projectRoot, host, port });
163
- const { url } = await listenDashboardServer({ server, host, port });
219
+ // Strict (no fallback) only when the operator pinned an explicit nonzero
220
+ // port: `--port N` with N > 0 (#388). Config/default preferred ports and
221
+ // `--port 0` may move to an ephemeral bind.
222
+ const strictPort = portSource === "cli" && port > 0;
223
+
224
+ let listenResult;
225
+ try {
226
+ listenResult = await listenDashboardWithFallback({
227
+ server,
228
+ host,
229
+ preferredPort: port,
230
+ strict: strictPort,
231
+ });
232
+ } catch (err) {
233
+ return {
234
+ exitCode: 1,
235
+ output: `${err instanceof Error ? err.message : String(err)}\n`,
236
+ };
237
+ }
238
+
239
+ const { url, port: boundPort, fallbackFromPort } = listenResult;
164
240
 
165
241
  process.stdout.write(
166
- `${formatDashboardStartupMessage({ url, host, port, projectRoot, portSource })}\n`,
242
+ `${formatDashboardStartupMessage({
243
+ url,
244
+ host,
245
+ port: boundPort,
246
+ projectRoot,
247
+ portSource,
248
+ fallbackFromPort,
249
+ })}\n`,
167
250
  );
168
251
 
169
252
  await new Promise((resolve) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.35.0",
3
+ "version": "2.36.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -205,6 +205,11 @@ export function recordPromptParseFailure({
205
205
  * @param {number} params.maxLaneNumber
206
206
  */
207
207
  export function buildTasksAndLanesFromPlan({ plan, discovered, projectRoot, batchId, maxLaneNumber }) {
208
+ // Plan-time stamping is advisory (#358): `buildTaskLaneAssignments` maps
209
+ // the planner's tick layout, which stays preview-only under slot-pool
210
+ // dispatch. These values are provisional until the first VL→slot bind —
211
+ // `applyVlSlotLaneBinding` (engine-scope.mjs) rewrites task.laneNumber,
212
+ // lane.taskIds, the journal, and saved state at dispatch time.
208
213
  const assignments = buildTaskLaneAssignments(plan);
209
214
  /** @type {string[]} */
210
215
  const taskIds = countPlanTasks(plan);
@@ -0,0 +1,227 @@
1
+ /**
2
+ * VL slot-pool dispatch helper (SP-897 / #358 partial).
3
+ *
4
+ * Selects the next ready virtual lane (VL) for a free physical slot in
5
+ * `1..lanes.maxParallel` so the engine can replace tick barriers with
6
+ * slot-pool dispatch (wire step is SP-903 — this module does not touch the
7
+ * engine tick loop).
8
+ *
9
+ * Invariants locked here:
10
+ *
11
+ * 1. `lanes.maxParallel` caps in-flight VLs (physical slot pool).
12
+ * 2. A ready VL whose scopes overlap any currently running VL's scopes is
13
+ * never dispatched while that work runs — never two overlapping VLs
14
+ * concurrent.
15
+ * 3. Same-VL serial queue semantics: a VL holds at most one slot at a time;
16
+ * its remaining tasks wait behind the running task on that VL. Mid-run
17
+ * steal across the same-VL serial queue is out of scope (#358).
18
+ * 4. Slot free but no dispatchable VL is distinguishable from true idle via
19
+ * a journalable conflict-wait payload (event `lane.slot_conflict_wait`).
20
+ *
21
+ * Slot mechanics mirror the matrix sub-lane pool
22
+ * (`acquireLaneSlot` / `releaseLaneSlot` in `matrix.mjs`): lowest free slot,
23
+ * FIFO wake on release, `maxParallel` clamped to at least 1. This module owns
24
+ * its pool instance (created by the caller) instead of a state-keyed WeakMap
25
+ * so matrix row scheduling stays untouched.
26
+ *
27
+ * Scope overlap delegates to the planner's glob-aware
28
+ * `fileScopesOverlap` (`src/planner/file-scope.mjs`) — the exact predicate the
29
+ * planner used to pack VLs — so dispatch can never run two VLs concurrently
30
+ * that packing would have serialized onto one lane.
31
+ */
32
+
33
+ import { fileScopesOverlap } from "../../planner/file-scope.mjs";
34
+
35
+ /**
36
+ * Journal event name for "slot free but every remaining ready VL conflicts".
37
+ * Emitted by the wire step (SP-903) via
38
+ * `appendJournalEvent(projectRoot, batchId, VL_SLOT_CONFLICT_WAIT_EVENT, buildConflictWaitPayload(...))`.
39
+ *
40
+ * @type {"lane.slot_conflict_wait"}
41
+ */
42
+ export const VL_SLOT_CONFLICT_WAIT_EVENT = "lane.slot_conflict_wait";
43
+
44
+ /**
45
+ * A dispatch-ready virtual lane entry.
46
+ *
47
+ * @typedef {Object} VlDispatchEntry
48
+ * @property {string | number | null} [vlId] Stable VL identity.
49
+ * @property {string[]} [scopes] Accumulated file scopes for the VL.
50
+ * @property {string[]} [taskIds] Ordered task queue for the VL (serial).
51
+ */
52
+
53
+ /**
54
+ * Selection result for `selectReadyVl`.
55
+ *
56
+ * @typedef {Object} VlSelection
57
+ * @property {"dispatch" | "conflict-wait" | "idle"} status
58
+ * - `dispatch`: `vl` is the ready VL to bind to a free slot.
59
+ * - `conflict-wait`: slot would be free but nothing dispatchable — every
60
+ * remaining ready VL either overlaps running scopes (`blocked`) or is
61
+ * already running its own serial queue (`waitingOn`).
62
+ * - `idle`: no ready VLs at all.
63
+ * @property {VlDispatchEntry | null} vl Selected VL when `status` is `dispatch`.
64
+ * @property {Array<{ vlId: string | number | null, overlapsWith: string | number | null }>} blocked
65
+ * Ready VLs skipped because their scopes overlap running work (in ready order).
66
+ * @property {Array<string | number | null>} waitingOn
67
+ * Ready VL ids already running — their remaining tasks stay serial-queued.
68
+ */
69
+
70
+ /**
71
+ * Whether two scope lists overlap, using the planner's glob-aware overlap
72
+ * predicate (directory prefixes, `*`/`**` globs, brace expansion). Empty or
73
+ * missing scope lists never overlap anything.
74
+ *
75
+ * @param {unknown} scopesA First scope list.
76
+ * @param {unknown} scopesB Second scope list.
77
+ * @returns {boolean}
78
+ */
79
+ export function scopesOverlap(scopesA, scopesB) {
80
+ const left = Array.isArray(scopesA) ? scopesA : [];
81
+ const right = Array.isArray(scopesB) ? scopesB : [];
82
+ if (left.length === 0 || right.length === 0) return false;
83
+ return fileScopesOverlap(left, right);
84
+ }
85
+
86
+ /**
87
+ * Select the next ready VL to bind to a free physical slot.
88
+ *
89
+ * Scans `readyVls` in queue order and returns the first VL that (a) is not
90
+ * already running (same-VL serial queue) and (b) does not overlap any
91
+ * currently running VL's scopes. VLs skipped along the way are reported in
92
+ * `blocked` / `waitingOn` so callers can journal exactly why a free slot
93
+ * could not take work.
94
+ *
95
+ * @param {VlDispatchEntry[]} readyVls Ready VLs in dispatch-priority order.
96
+ * @param {VlDispatchEntry[]} [runningVls] VLs currently holding slots.
97
+ * @returns {VlSelection}
98
+ */
99
+ export function selectReadyVl(readyVls, runningVls = []) {
100
+ const ready = Array.isArray(readyVls) ? readyVls.filter(Boolean) : [];
101
+ const running = Array.isArray(runningVls) ? runningVls.filter(Boolean) : [];
102
+ if (ready.length === 0) {
103
+ return { status: "idle", vl: null, blocked: [], waitingOn: [] };
104
+ }
105
+
106
+ const runningIds = new Set(running.map((vl) => vl?.vlId));
107
+ /** @type {Array<{ vlId: string | number | null, overlapsWith: string | number | null }>} */
108
+ const blocked = [];
109
+ /** @type {Array<string | number | null>} */
110
+ const waitingOn = [];
111
+
112
+ for (const vl of ready) {
113
+ const vlId = vl?.vlId ?? null;
114
+ if (runningIds.has(vlId)) {
115
+ waitingOn.push(vlId);
116
+ continue;
117
+ }
118
+ const conflicting = running.find((runVl) => scopesOverlap(vl?.scopes, runVl?.scopes));
119
+ if (conflicting) {
120
+ blocked.push({ vlId, overlapsWith: conflicting.vlId ?? null });
121
+ continue;
122
+ }
123
+ return { status: "dispatch", vl, blocked, waitingOn };
124
+ }
125
+
126
+ return { status: "conflict-wait", vl: null, blocked, waitingOn };
127
+ }
128
+
129
+ /**
130
+ * Physical slot pool sized `1..maxParallel` (matrix pool semantics, owned
131
+ * instance). `acquire` waits FIFO when the pool is full; `release` hands the
132
+ * freed slot to the oldest waiter.
133
+ *
134
+ * @typedef {Object} VlSlotPool
135
+ * @property {number} max Configured pool size (clamped to ≥ 1).
136
+ * @property {() => number | null} tryAcquire Take the lowest free slot now, or null.
137
+ * @property {() => Promise<number>} acquire Take the lowest free slot, waiting FIFO until one frees.
138
+ * @property {(slot: number) => void} release Return a slot; wakes the oldest waiter (FIFO).
139
+ * @property {() => number} runningCount Slots currently in use.
140
+ * @property {() => number} freeSlotCount Slots currently free.
141
+ */
142
+
143
+ /**
144
+ * Create a VL slot pool. Missing/zero/negative `maxParallel` clamps to a
145
+ * single slot (mirrors the matrix pool).
146
+ *
147
+ * @param {number} maxParallel Configured `lanes.maxParallel`.
148
+ * @returns {VlSlotPool}
149
+ */
150
+ export function createVlSlotPool(maxParallel) {
151
+ const max = Math.max(1, Math.floor(Number(maxParallel) || 1));
152
+ /** @type {Set<number>} */
153
+ const inUse = new Set();
154
+ /** @type {Array<(slot: number) => void>} */
155
+ const waiters = [];
156
+
157
+ return {
158
+ get max() {
159
+ return max;
160
+ },
161
+ tryAcquire() {
162
+ for (let slot = 1; slot <= max; slot++) {
163
+ if (!inUse.has(slot)) {
164
+ inUse.add(slot);
165
+ return slot;
166
+ }
167
+ }
168
+ return null;
169
+ },
170
+ acquire() {
171
+ const slot = this.tryAcquire();
172
+ if (slot !== null) return Promise.resolve(slot);
173
+ return new Promise((resolve) => {
174
+ waiters.push(resolve);
175
+ });
176
+ },
177
+ release(slot) {
178
+ const slotNumber = Number(slot);
179
+ if (!Number.isInteger(slotNumber) || slotNumber < 1 || !inUse.has(slotNumber)) return;
180
+ inUse.delete(slotNumber);
181
+ const next = waiters.shift();
182
+ if (next) {
183
+ inUse.add(slotNumber);
184
+ next(slotNumber);
185
+ }
186
+ },
187
+ runningCount() {
188
+ return inUse.size;
189
+ },
190
+ freeSlotCount() {
191
+ return max - inUse.size;
192
+ },
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Journalable payload for a conflict-wait: a physical slot is free but no
198
+ * ready VL can take it. Data only — pass alongside
199
+ * `VL_SLOT_CONFLICT_WAIT_EVENT` to `appendJournalEvent`.
200
+ *
201
+ * @param {object} [params]
202
+ * @param {number | null} [params.slot] Free slot number, when known.
203
+ * @param {Array<{ vlId: string | number | null, overlapsWith: string | number | null }>} [params.blocked]
204
+ * Ready VLs skipped for scope overlap (from `selectReadyVl`).
205
+ * @param {Array<string | number | null>} [params.waitingOn]
206
+ * Ready VL ids serial-queued behind their own running task.
207
+ * @param {Array<string | number | null>} [params.runningVlIds] VL ids holding slots.
208
+ * @param {number} [params.readyCount] Ready VLs remaining (dispatchable + blocked).
209
+ * @returns {{ event: typeof VL_SLOT_CONFLICT_WAIT_EVENT, slot: number | null, reason: "scope_conflict", blockedByOverlap: Array<{ vlId: string | number | null, overlapsWith: string | number | null }>, queuedBehindRunning: Array<string | number | null>, runningVlIds: Array<string | number | null>, readyCount: number }}
210
+ */
211
+ export function buildConflictWaitPayload({
212
+ slot = null,
213
+ blocked = [],
214
+ waitingOn = [],
215
+ runningVlIds = [],
216
+ readyCount = 0,
217
+ } = {}) {
218
+ return {
219
+ event: VL_SLOT_CONFLICT_WAIT_EVENT,
220
+ slot,
221
+ reason: "scope_conflict",
222
+ blockedByOverlap: Array.isArray(blocked) ? blocked : [],
223
+ queuedBehindRunning: Array.isArray(waitingOn) ? waitingOn : [],
224
+ runningVlIds: Array.isArray(runningVlIds) ? runningVlIds : [],
225
+ readyCount: Math.max(0, Math.floor(Number(readyCount) || 0)),
226
+ };
227
+ }