pi-spine 2.24.0 → 2.26.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 (53) hide show
  1. package/bin/spine-worker-runner.mjs +2 -1
  2. package/package.json +1 -1
  3. package/src/batch/abort.mjs +74 -38
  4. package/src/batch/attached-engine-handoff.mjs +2 -2
  5. package/src/batch/attached-runner-promote.mjs +15 -1
  6. package/src/batch/attached-runner-reconcile.mjs +1 -1
  7. package/src/batch/batch-meta-reconstruct.mjs +6 -1
  8. package/src/batch/batch-state-io.mjs +120 -45
  9. package/src/batch/batch-state-lock.mjs +173 -31
  10. package/src/batch/contract-exec.mjs +46 -45
  11. package/src/batch/contract-spawn.mjs +225 -0
  12. package/src/batch/contract-verify.mjs +2 -1
  13. package/src/batch/detached-wait.mjs +1 -1
  14. package/src/batch/engine-crash-guard.mjs +143 -0
  15. package/src/batch/engine-lanes/matrix-run.mjs +34 -8
  16. package/src/batch/engine-lanes/matrix.mjs +143 -8
  17. package/src/batch/engine-lanes/merge.mjs +135 -34
  18. package/src/batch/engine-lanes/review-final.mjs +1 -1
  19. package/src/batch/engine-lanes.mjs +11 -9
  20. package/src/batch/engine.mjs +10 -10
  21. package/src/batch/integrate-dirty-overlap.mjs +35 -0
  22. package/src/batch/integrate-worktree.mjs +106 -13
  23. package/src/batch/integrate.mjs +34 -93
  24. package/src/batch/journal-checksum.mjs +26 -0
  25. package/src/batch/journal.mjs +32 -13
  26. package/src/batch/lifecycle-archive.mjs +84 -3
  27. package/src/batch/lifecycle-cleanup.mjs +110 -0
  28. package/src/batch/lifecycle.mjs +100 -72
  29. package/src/batch/parent-session-monitor.mjs +77 -70
  30. package/src/batch/pause.mjs +92 -25
  31. package/src/batch/post-merge-limbo.mjs +35 -5
  32. package/src/batch/reconcile-batch.mjs +13 -1
  33. package/src/batch/resume-gate-reopen.mjs +24 -8
  34. package/src/batch/resume-multi.mjs +1 -1
  35. package/src/batch/resume.mjs +1 -1
  36. package/src/batch/salvage-batch-integrate.mjs +13 -17
  37. package/src/batch/sequence-run.mjs +26 -8
  38. package/src/batch/sequence-wait.mjs +87 -8
  39. package/src/batch/state-guards.mjs +39 -7
  40. package/src/batch/state-io.mjs +131 -17
  41. package/src/batch/state.mjs +23 -1
  42. package/src/batch/worker-heartbeat.mjs +29 -8
  43. package/src/batch/worker-host.mjs +61 -8
  44. package/src/batch/worker-output.mjs +9 -6
  45. package/src/batch/worker-prompt.mjs +4 -2
  46. package/src/batch/worker-spawn.mjs +99 -12
  47. package/src/config/defaults.mjs +15 -1
  48. package/src/config/preflight/discovery.mjs +20 -12
  49. package/src/config/preflight/git-batch.mjs +47 -0
  50. package/src/config/spine-config-schema.mjs +67 -1
  51. package/src/fs/atomic-write.mjs +37 -1
  52. package/src/planner/scope.mjs +3 -1
  53. package/src/tasks/packet/discover.mjs +59 -3
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { spawn } from "node:child_process";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { startAgentSessionWorker } from "./agent-session-worker.mjs";
10
+ import { DEFAULT_MAX_BYTES } from "./worker-output.mjs";
10
11
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
11
12
  import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
12
13
  import { resolveSafeWorkerLaunchScript } from "../config/worker-launch-script.mjs";
@@ -215,12 +216,13 @@ export function spawnExecutionOnlyHandle({
215
216
  config,
216
217
  });
217
218
 
218
- // Create a wrapper script that runs the command and then creates .DONE
219
- // This matches the behavior expected by the heartbeat loop.
220
- // We run `/bin/sh -c "<command> && touch .DONE"`
221
- const script = `${command} && touch "${path.join(taskFolder, ".DONE")}"`;
222
-
223
- return spawn("/bin/sh", ["-c", script], {
219
+ // Run the command, then create the .DONE marker. The path is passed as a
220
+ // positional parameter (`$1`) instead of being interpolated into the script
221
+ // string, so a task folder containing `"`, `$(`, or a backtick is never
222
+ // evaluated as shell code (SP-787 / #306). The third element is `$0`.
223
+ const donePath = path.join(taskFolder, ".DONE");
224
+
225
+ return spawn("/bin/sh", ["-c", `${command} && touch "$1"`, "sh", donePath], {
224
226
  cwd: worktreePath,
225
227
  env,
226
228
  stdio: ["ignore", "pipe", "pipe"],
@@ -286,28 +288,113 @@ export async function terminateHungWorkerChild(child, childDone) {
286
288
  }
287
289
 
288
290
  /**
291
+ * Append `text` to a bounded tail buffer, keeping only the last `maxBytes`.
292
+ *
293
+ * @param {Buffer<ArrayBufferLike>} tail
294
+ * @param {string} text
295
+ * @param {number} maxBytes
296
+ * @returns {Buffer<ArrayBufferLike>}
297
+ */
298
+ function appendToBoundedTail(tail, text, maxBytes) {
299
+ const chunk = Buffer.from(text, "utf-8");
300
+ if (maxBytes <= 0) return Buffer.alloc(0);
301
+ const combined = tail.byteLength === 0 ? chunk : Buffer.concat([tail, chunk]);
302
+ return combined.byteLength > maxBytes
303
+ ? combined.subarray(combined.byteLength - maxBytes)
304
+ : combined;
305
+ }
306
+
307
+ /**
308
+ * Collect child stdout/stderr into a bounded tail (SP-787 / #306) and settle
309
+ * on either `close` or a spawn `error`, whichever comes first. A child that
310
+ * never spawned (EACCES/ENOENT, missing execPath) emits `error` and then a
311
+ * synthetic `close`, so the error path resolves once with `spawnError: true`
312
+ * and the conventional exit code 127; the close handler is guarded so the
313
+ * later close cannot override the spawn failure. Without the `error` listener
314
+ * the engine itself would crash on the unhandled event and lose every lane.
315
+ *
289
316
  * @param {WorkerChildHandle} child
290
317
  * @param {{ append: (rawChunk: string) => void } | null} [liveLogWriter]
318
+ * @param {number} [maxBytes] Byte cap for the collected output tail; defaults
319
+ * to the worker output cap. Memory stays bounded regardless of child runtime.
320
+ * @returns {Promise<{ exitCode: number; output: string; spawnError?: boolean }>}
291
321
  */
292
- export function collectChildOutput(child, liveLogWriter) {
322
+ export function collectChildOutput(child, liveLogWriter, maxBytes) {
293
323
  if ("wait" in child && typeof child.wait === "function") {
294
324
  return child.wait();
295
325
  }
326
+ const cap =
327
+ typeof maxBytes === "number" && Number.isFinite(maxBytes) && maxBytes > 0
328
+ ? maxBytes
329
+ : DEFAULT_MAX_BYTES;
296
330
  return new Promise((resolve) => {
297
- let stdout = "";
298
- let stderr = "";
331
+ /** @type {Buffer<ArrayBufferLike>} */
332
+ let stdoutTail = Buffer.alloc(0);
333
+ /** @type {Buffer<ArrayBufferLike>} */
334
+ let stderrTail = Buffer.alloc(0);
335
+ /** @type {string|null} */
336
+ let spawnErrorMessage = null;
337
+ let settled = false;
338
+
339
+ // stdout-then-stderr order as before; the combined string keeps the last
340
+ // `cap` bytes overall.
341
+ const combinedOutput = () => {
342
+ const combined = Buffer.concat([stdoutTail, stderrTail]);
343
+ const bounded =
344
+ combined.byteLength > cap
345
+ ? combined.subarray(combined.byteLength - cap)
346
+ : combined;
347
+ return bounded.toString("utf-8");
348
+ };
349
+ const settle = (
350
+ /** @type {() => { exitCode: number; output: string; spawnError?: boolean }} */ build,
351
+ ) => {
352
+ if (settled) return;
353
+ settled = true;
354
+ resolve(build());
355
+ };
356
+ const spawnFailureResult = () => ({
357
+ exitCode: 127,
358
+ output: `${combinedOutput()}${spawnErrorMessage ?? ""}`,
359
+ spawnError: true,
360
+ });
361
+
299
362
  child.stdout?.on("data", (/** @type {Buffer | string} */ chunk) => {
300
363
  const text = chunk.toString();
301
- stdout += text;
364
+ stdoutTail = appendToBoundedTail(stdoutTail, text, cap);
302
365
  liveLogWriter?.append(text);
303
366
  });
304
367
  child.stderr?.on("data", (/** @type {Buffer | string} */ chunk) => {
305
368
  const text = chunk.toString();
306
- stderr += text;
369
+ stderrTail = appendToBoundedTail(stderrTail, text, cap);
307
370
  liveLogWriter?.append(text);
308
371
  });
372
+ child.on?.("error", (/** @type {unknown} */ err) => {
373
+ spawnErrorMessage = String(err);
374
+ // A child that failed to spawn has no real exit status. Flag the handle
375
+ // as settled so poll loops keyed on `exitCode` stop polling — older
376
+ // runtimes leave `exitCode` null on failed spawns (Node ≥22 sets a
377
+ // negative errno instead). The property is a plain writable own field.
378
+ if (child.exitCode === null || child.exitCode < 0) {
379
+ try {
380
+ // exitCode is readonly on the Node ChildProcess type; a failed spawn
381
+ // has no real status, so flagging it is safe and intentional.
382
+ const writableExitCode = /** @type {{ exitCode: number | null }} */ (
383
+ /** @type {unknown} */ (child)
384
+ );
385
+ writableExitCode.exitCode = 127;
386
+ } catch {
387
+ // Read-only test double; the resolved promise still settles the host.
388
+ }
389
+ }
390
+ settle(spawnFailureResult);
391
+ });
309
392
  child.on?.("close", (/** @type {number | null} */ code) => {
310
- resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
393
+ if (spawnErrorMessage !== null) {
394
+ settle(spawnFailureResult);
395
+ return;
396
+ }
397
+ settle(() => ({ exitCode: code ?? 1, output: combinedOutput() }));
311
398
  });
312
399
  });
313
400
  }
@@ -38,9 +38,23 @@ export const CONTRACT_DEFAULTS = Object.freeze({
38
38
  legacyTaskIdPrefixes: Object.freeze(["TP-"]),
39
39
  });
40
40
 
41
- /** @type {Readonly<{ cleanupWorktreesOnComplete: boolean }>} */
41
+ /**
42
+ * Conflicted paths outside a lane File Scope that keep prefer-orch auto-resolution
43
+ * (SP-798 / #304). A conflicted path outside File Scope is only auto-resolved when
44
+ * it matches one of these globs — and the discarded lane blob is journaled; every
45
+ * other out-of-scope conflict fails closed so lane-committed work is never silently
46
+ * discarded.
47
+ */
48
+ const OUT_OF_SCOPE_MERGE_ALLOW_LIST_DEFAULT = Object.freeze([
49
+ ".spine/rules-manifest.json",
50
+ "package-lock.json",
51
+ "**/package-lock.json",
52
+ ]);
53
+
54
+ /** @type {Readonly<{ cleanupWorktreesOnComplete: boolean; outOfScopeMergeAllowList: readonly string[] }>} */
42
55
  export const LANES_DEFAULTS = Object.freeze({
43
56
  cleanupWorktreesOnComplete: true,
57
+ outOfScopeMergeAllowList: OUT_OF_SCOPE_MERGE_ALLOW_LIST_DEFAULT,
44
58
  });
45
59
 
46
60
  /** @type {Readonly<{ isolatedWorktree: boolean; allowHumanOnBaseBranch: "warn" | "block" | "allow" }>} */
@@ -6,13 +6,12 @@ import { loadSpineConfig } from "../spine-config-load.mjs";
6
6
  import { missingConfigHint } from "../missing-config-hint.mjs";
7
7
  import { resolveTasksRootPath } from "../env-overrides.mjs";
8
8
  import { validateWorktreeSetupHookConfig } from "../worktree-setup-hook.mjs";
9
- import { discoverTasks } from "../../tasks/packet/discover.mjs";
9
+ import { discoverTasks, TASK_ID_RE, taskIdFromFolderName } from "../../tasks/packet/discover.mjs";
10
10
  import { NO_PENDING_TASKS_ERROR } from "../../planner/scope.mjs";
11
11
  import { summarizePendingScope } from "../../planner/pending.mjs";
12
12
  import { validatePrompt } from "../../tasks/packet/validate-prompt.mjs";
13
13
 
14
14
  const DEPENDENCIES_SCHEMA_VERSION = 1;
15
- const TASK_ID_PATTERN = /^[A-Z]{2,}-\d{3,}$/;
16
15
 
17
16
  function makeCheck(id, ok, message, extra = {}) {
18
17
  return { id, ok, message, ...extra };
@@ -31,24 +30,33 @@ export function resolveTasksRoot(projectRoot, configResult) {
31
30
  return resolveTasksRootPath(projectRoot, loaded.config);
32
31
  }
33
32
 
33
+ /**
34
+ * Task ID from a folder name — delegates to the shared pattern (SP-785, #300).
35
+ *
36
+ * @param {string} folderName
37
+ * @returns {string | null}
38
+ */
34
39
  export function taskIdFromFolder(folderName) {
35
- const match = String(folderName).match(/^([A-Z]{2,}-\d{3,})/);
36
- return match?.[1] ?? null;
40
+ return taskIdFromFolderName(folderName);
37
41
  }
38
42
 
43
+ /**
44
+ * Discoverable task folders (PREFIX-###-slug with PROMPT.md), numeric order.
45
+ * Delegates to the planner's discoverTasks so preflight and planner agree.
46
+ *
47
+ * @param {string} tasksRootPath
48
+ * @returns {string[]}
49
+ */
39
50
  export function discoverTaskFolders(tasksRootPath) {
40
51
  if (!tasksRootPath || !fs.existsSync(tasksRootPath)) return [];
41
52
 
42
- return fs
43
- .readdirSync(tasksRootPath, { withFileTypes: true })
44
- .filter((entry) => entry.isDirectory())
45
- .map((entry) => entry.name)
46
- .filter((name) => fs.existsSync(path.join(tasksRootPath, name, "PROMPT.md")))
47
- .sort();
53
+ return discoverTasks(tasksRootPath).map((task) => task.folderName);
48
54
  }
49
55
 
50
56
  export function discoverTaskIds(tasksRootPath) {
51
- return [...new Set(discoverTaskFolders(tasksRootPath).map(taskIdFromFolder).filter(Boolean))].sort();
57
+ if (!tasksRootPath || !fs.existsSync(tasksRootPath)) return [];
58
+
59
+ return discoverTasks(tasksRootPath).map((task) => task.taskId);
52
60
  }
53
61
 
54
62
  /**
@@ -148,7 +156,7 @@ export function checkDependenciesJson(ctx) {
148
156
  }
149
157
 
150
158
  const taskIds = Object.keys(parsed.tasks);
151
- const invalidIds = taskIds.filter((id) => !TASK_ID_PATTERN.test(id));
159
+ const invalidIds = taskIds.filter((id) => !TASK_ID_RE.test(id));
152
160
  if (invalidIds.length > 0) {
153
161
  return makeCheck(
154
162
  "dependencies-json",
@@ -4,6 +4,9 @@ import path from "node:path";
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { loadSpineConfig } from "../spine-config-load.mjs";
6
6
  import { runReconciliationCheck } from "../../batch/reconcile.mjs";
7
+ import { isBatchArchived } from "../../batch/state-guards.mjs";
8
+ import { loadGateRecord } from "../../batch/gate-evidence-read.mjs";
9
+ import { readJournalEvents } from "../../batch/journal.mjs";
7
10
  import {
8
11
  isRulesManifestGeneratedAtOnlyDrift,
9
12
  RULES_MANIFEST_REL_PATH,
@@ -130,6 +133,33 @@ function isHealthyActiveBatch(batchState) {
130
133
  return false;
131
134
  }
132
135
 
136
+ /**
137
+ * A terminal `completed` batch-state whose archive already exists (a phantom
138
+ * recreated by a late land-loop write, #293) or whose integrate gate was
139
+ * approved / integrate already ran needs `spine batch complete` to archive and
140
+ * clear the file — never a self-referential `spine preflight` suggestion
141
+ * (SP-790 / #293).
142
+ *
143
+ * @param {string} projectRoot
144
+ * @param {object} batchState
145
+ */
146
+ function completedBatchNeedsBatchComplete(projectRoot, batchState) {
147
+ const phase = String(batchState?.phase ?? batchState?.status ?? "");
148
+ if (phase !== "completed") return false;
149
+ const batchId = String(batchState?.batchId ?? batchState?.id ?? "");
150
+ if (!batchId) return false;
151
+ if (isBatchArchived(projectRoot, batchId)) return true;
152
+ const gate = loadGateRecord(projectRoot, batchId);
153
+ if (gate && String(gate.status ?? "") === "approved") return true;
154
+ try {
155
+ return readJournalEvents(projectRoot, batchId).some(
156
+ (event) => event.type === "integrate.completed",
157
+ );
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+
133
163
  /**
134
164
  * @param {object} ctx
135
165
  * @param {string} ctx.projectRoot
@@ -297,6 +327,23 @@ export function checkNoActiveBatch(ctx) {
297
327
  );
298
328
  }
299
329
 
330
+ if (completedBatchNeedsBatchComplete(ctx.projectRoot, batchState)) {
331
+ const batchId = batchState.batchId ?? batchState.id ?? "unknown";
332
+ return makeCheck(
333
+ "no-active-batch",
334
+ false,
335
+ `completed batch ${batchId} awaiting archive`,
336
+ {
337
+ details: {
338
+ batchStatePath: path.relative(ctx.projectRoot, batchStatePath),
339
+ batchId,
340
+ phase: "completed",
341
+ },
342
+ suggestedCommand: "spine batch complete",
343
+ },
344
+ );
345
+ }
346
+
300
347
  if (isHealthyActiveBatch(batchState)) {
301
348
  const batchId = batchState.batchId ?? batchState.id ?? "unknown";
302
349
  const phase = batchState.phase ?? batchState.status ?? "unknown";
@@ -12,17 +12,25 @@ export const DEFAULT_SEQUENCE_POLL_MS = 5_000;
12
12
  /** Default dashboard SSE poll interval (wired in SP-453). */
13
13
  export const DEFAULT_DASHBOARD_POLL_MS = 2_000;
14
14
 
15
+ /** Default hard cap for the sequence batch terminal wait (SP-802 / #307). */
16
+ export const DEFAULT_SEQUENCE_MAX_WAIT_MS = 24 * 60 * 60 * 1000;
17
+
18
+ /** Default no-progress window before the sequence wait exits as stalled (SP-802 / #307). */
19
+ export const DEFAULT_SEQUENCE_STALL_MS = 30 * 60 * 1000;
20
+
15
21
  /** Lower bound for orchestrator poll intervals. */
16
22
  export const MIN_ORCHESTRATOR_POLL_MS = 100;
17
23
 
18
24
  /** Upper bound for orchestrator poll intervals. */
19
25
  export const MAX_ORCHESTRATOR_POLL_MS = 60_000;
20
26
 
21
- /** @type {Readonly<{ attachedMilestonePollMs: number; sequencePollMs: number; dashboardPollMs: number }>} */
27
+ /** @type {Readonly<{ attachedMilestonePollMs: number; sequencePollMs: number; dashboardPollMs: number; sequenceMaxWaitMs: number; sequenceStallMs: number }>} */
22
28
  export const ORCHESTRATOR_DEFAULTS = Object.freeze({
23
29
  attachedMilestonePollMs: DEFAULT_ATTACHED_MILESTONE_POLL_MS,
24
30
  sequencePollMs: DEFAULT_SEQUENCE_POLL_MS,
25
31
  dashboardPollMs: DEFAULT_DASHBOARD_POLL_MS,
32
+ sequenceMaxWaitMs: DEFAULT_SEQUENCE_MAX_WAIT_MS,
33
+ sequenceStallMs: DEFAULT_SEQUENCE_STALL_MS,
26
34
  });
27
35
 
28
36
  /**
@@ -54,6 +62,30 @@ function validatePositivePollMs(value, fieldLabel) {
54
62
  return { ok: true, value: parsed };
55
63
  }
56
64
 
65
+ /**
66
+ * Positive-integer validation without the poll-interval range clamp: wait/stall
67
+ * budgets legitimately exceed MAX_ORCHESTRATOR_POLL_MS (SP-802 / #307).
68
+ *
69
+ * @param {unknown} value
70
+ * @param {string} fieldLabel
71
+ * @returns {{ ok: true, value: number } | { ok: false, code: string, message: string, suggestedCommand: string }}
72
+ */
73
+ function validatePositiveDurationMs(value, fieldLabel) {
74
+ if (value == null) {
75
+ return { ok: true, value: 0 };
76
+ }
77
+ const parsed = Number(value);
78
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed <= 0) {
79
+ return {
80
+ ok: false,
81
+ code: "CONFIG_ORCHESTRATOR_INVALID",
82
+ message: `${fieldLabel} must be a positive integer when set`,
83
+ suggestedCommand: "spine init --force",
84
+ };
85
+ }
86
+ return { ok: true, value: parsed };
87
+ }
88
+
57
89
  /**
58
90
  * @param {Record<string, any>} config
59
91
  * @returns {null | { code: string; message: string; suggestedCommand: string }}
@@ -82,6 +114,16 @@ export function validateOrchestratorConfig(config) {
82
114
  }
83
115
  }
84
116
 
117
+ for (const [key, label] of [
118
+ ["sequenceMaxWaitMs", "orchestrator.sequenceMaxWaitMs"],
119
+ ["sequenceStallMs", "orchestrator.sequenceStallMs"],
120
+ ]) {
121
+ const result = validatePositiveDurationMs(orchestrator[key], label);
122
+ if (!result.ok) {
123
+ return result;
124
+ }
125
+ }
126
+
85
127
  return null;
86
128
  }
87
129
 
@@ -121,6 +163,30 @@ export function resolveDashboardPollMs({ config = {} } = {}) {
121
163
  return DEFAULT_DASHBOARD_POLL_MS;
122
164
  }
123
165
 
166
+ /**
167
+ * @param {object} [params]
168
+ * @param {object} [params.config]
169
+ */
170
+ export function resolveSequenceMaxWaitMs({ config = {} } = {}) {
171
+ const configured = Number(config.orchestrator?.sequenceMaxWaitMs);
172
+ if (Number.isFinite(configured) && configured > 0) {
173
+ return configured;
174
+ }
175
+ return DEFAULT_SEQUENCE_MAX_WAIT_MS;
176
+ }
177
+
178
+ /**
179
+ * @param {object} [params]
180
+ * @param {object} [params.config]
181
+ */
182
+ export function resolveSequenceStallMs({ config = {} } = {}) {
183
+ const configured = Number(config.orchestrator?.sequenceStallMs);
184
+ if (Number.isFinite(configured) && configured > 0) {
185
+ return configured;
186
+ }
187
+ return DEFAULT_SEQUENCE_STALL_MS;
188
+ }
189
+
124
190
  // --- Named agent model profiles (SP-664 / GitHub #216) ---
125
191
 
126
192
  /**
@@ -14,6 +14,33 @@ export function makeAtomicTempPath(targetPath) {
14
14
  return `${targetPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
15
15
  }
16
16
 
17
+ const IGNORABLE_DIR_FSYNC_CODES = new Set(["EISDIR", "EPERM", "EINVAL", "EBADF"]);
18
+
19
+ /**
20
+ * Durability requires flushing the parent directory entry after the rename so
21
+ * the rename itself survives a crash. Some platforms (win32, network and
22
+ * exotic filesystems) cannot open or fsync a directory at all, so the four
23
+ * codes that indicate that situation are tolerated; anything else is real I/O
24
+ * trouble and propagates to the caller.
25
+ * @param {string} dir
26
+ */
27
+ function fsyncDirBestEffort(dir) {
28
+ let dirFd;
29
+ try {
30
+ dirFd = fs.openSync(dir, "r");
31
+ } catch (err) {
32
+ if (IGNORABLE_DIR_FSYNC_CODES.has(/** @type {any} */ (err)?.code)) return;
33
+ throw err;
34
+ }
35
+ try {
36
+ fs.fsyncSync(dirFd);
37
+ } catch (err) {
38
+ if (!IGNORABLE_DIR_FSYNC_CODES.has(/** @type {any} */ (err)?.code)) throw err;
39
+ } finally {
40
+ fs.closeSync(dirFd);
41
+ }
42
+ }
43
+
17
44
  /**
18
45
  * @param {string} filePath
19
46
  * @param {string} content
@@ -25,8 +52,17 @@ export function writeTextAtomic(filePath, content) {
25
52
  const tmpPath = makeAtomicTempPath(filePath);
26
53
 
27
54
  try {
28
- fs.writeFileSync(tmpPath, content, "utf-8");
55
+ // Durable temp write: fsync the file contents before the rename so the
56
+ // data reaches disk before the entry swap makes it authoritative (#302).
57
+ const fd = fs.openSync(tmpPath, "w");
58
+ try {
59
+ fs.writeSync(fd, content, null, "utf-8");
60
+ fs.fsyncSync(fd);
61
+ } finally {
62
+ fs.closeSync(fd);
63
+ }
29
64
  fs.renameSync(tmpPath, filePath);
65
+ fsyncDirBestEffort(dir);
30
66
  } catch (err) {
31
67
  try {
32
68
  if (fs.existsSync(tmpPath)) {
@@ -12,7 +12,9 @@
12
12
  import path from 'node:path';
13
13
  import { summarizePendingScope } from './pending.mjs';
14
14
 
15
- export const TASK_ID_RE = /^[A-Z][A-Z0-9]*-\d{3,}$/;
15
+ // Single source of truth (SP-785, #300): re-export the shared task-ID regex.
16
+ import { TASK_ID_RE } from '../tasks/packet/discover.mjs';
17
+ export { TASK_ID_RE };
16
18
 
17
19
  export const NO_PENDING_TASKS_ERROR = 'No pending tasks (all discovered tasks have .DONE).';
18
20
 
@@ -1,12 +1,68 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
+ /**
5
+ * Canonical task-ID discovery patterns (single source of truth).
6
+ * Closes #300: every discovery site (planner, preflight, worker runner)
7
+ * derives its patterns from here so SP-1000+ is found, sorted numerically,
8
+ * and non-task folders (`_explore`, `_authoring`, `_archive`) are excluded.
9
+ */
10
+
11
+ /** Source pattern for a task ID (PREFIX-###, three or more digits), for embedding in larger regexes. */
12
+ export const TASK_ID_PATTERN_SOURCE = "[A-Z][A-Z0-9]*-\\d{3,}";
13
+
14
+ /** Task ID: PREFIX-### (e.g. TP-007, SP-1000). Keeps the planner's existing prefix rule. */
15
+ export const TASK_ID_RE = new RegExp(`^${TASK_ID_PATTERN_SOURCE}$`);
16
+
4
17
  /** Folder name: PREFIX-###-slug (e.g. TP-007-taskplane-parsers). */
5
- export const TASK_FOLDER_RE = /^([A-Z][A-Z0-9]*-\d{3})-([a-z0-9][a-z0-9-]*)$/;
18
+ export const TASK_FOLDER_RE = new RegExp(
19
+ `^(${TASK_ID_PATTERN_SOURCE})-([a-z0-9][a-z0-9-]*)$`,
20
+ );
21
+
22
+ /** Prefix + digits of a conforming task ID, for numeric comparison. */
23
+ const TASK_ID_PARTS_RE = /^([A-Z][A-Z0-9]*)-(\d{3,})$/;
24
+
25
+ /**
26
+ * Extract the task ID from a folder name (PREFIX-###-slug or bare PREFIX-###).
27
+ * Returns null when the name is not a task folder (e.g. `_explore`).
28
+ *
29
+ * @param {string} name Folder name or path segment
30
+ * @returns {string | null}
31
+ */
32
+ export function taskIdFromFolderName(name) {
33
+ const base = String(name ?? "").split("/").pop() ?? "";
34
+ const folder = TASK_FOLDER_RE.exec(base);
35
+ if (folder) return folder[1];
36
+ const bare = TASK_ID_RE.exec(base);
37
+ return bare ? bare[0] : null;
38
+ }
39
+
40
+ /**
41
+ * Compare two task IDs: prefix first, then digits numerically.
42
+ * Non-conforming IDs sort after conforming ones, by string.
43
+ *
44
+ * @param {string} a
45
+ * @param {string} b
46
+ * @returns {number}
47
+ */
48
+ export function compareTaskIds(a, b) {
49
+ const pa = TASK_ID_PARTS_RE.exec(String(a ?? ""));
50
+ const pb = TASK_ID_PARTS_RE.exec(String(b ?? ""));
51
+ if (pa && pb) {
52
+ if (pa[1] !== pb[1]) return pa[1].localeCompare(pb[1]);
53
+ const da = Number(pa[2]);
54
+ const db = Number(pb[2]);
55
+ if (da !== db) return da - db;
56
+ return 0;
57
+ }
58
+ if (pa) return -1;
59
+ if (pb) return 1;
60
+ return String(a ?? "").localeCompare(String(b ?? ""));
61
+ }
6
62
 
7
63
  /**
8
64
  * Discover Taskplane task packets under `{tasksRoot}/{PREFIX-###-slug}/PROMPT.md`.
9
- * FR-TASK-01.
65
+ * FR-TASK-01. Results sort numerically: SP-099 < SP-999 < SP-1000.
10
66
  *
11
67
  * @param {string} tasksRoot Absolute or relative path to tasks root (e.g. spine-tasks)
12
68
  * @returns {Array<{ taskId: string, slug: string, folderName: string, folderPath: string, promptPath: string }>}
@@ -35,6 +91,6 @@ export function discoverTasks(tasksRoot) {
35
91
  });
36
92
  }
37
93
 
38
- tasks.sort((a, b) => a.taskId.localeCompare(b.taskId));
94
+ tasks.sort((a, b) => compareTaskIds(a.taskId, b.taskId));
39
95
  return tasks;
40
96
  }