pi-spine 2.27.0 → 2.28.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 (71) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-tasks.mjs +1 -0
  3. package/bin/spine-worker-runner.mjs +17 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +77 -8
  9. package/skills/spine-release-operator/SKILL.md +43 -52
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-alternatives.mjs +16 -1
  16. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  17. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  18. package/src/batch/diagnosis-review-infra.mjs +144 -0
  19. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  20. package/src/batch/diagnosis.mjs +19 -20
  21. package/src/batch/engine-lanes/merge.mjs +0 -8
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  24. package/src/batch/engine-lanes/review-code.mjs +20 -0
  25. package/src/batch/engine-lanes/review-final.mjs +10 -2
  26. package/src/batch/engine-lanes/review-poll.mjs +37 -1
  27. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  28. package/src/batch/engine-lanes.mjs +18 -18
  29. package/src/batch/gate-posture-approve.mjs +154 -15
  30. package/src/batch/integrate-path-delete.mjs +85 -0
  31. package/src/batch/integrate-worktree.mjs +20 -27
  32. package/src/batch/journal.mjs +5 -3
  33. package/src/batch/metrics-rollup.mjs +98 -4
  34. package/src/batch/metrics.mjs +134 -9
  35. package/src/batch/provider-quota.mjs +156 -7
  36. package/src/batch/quota-fallback.mjs +87 -6
  37. package/src/batch/reconcile-diagnosis.mjs +24 -77
  38. package/src/batch/resume-lane-reviews.mjs +11 -10
  39. package/src/batch/retry-profile.mjs +77 -0
  40. package/src/batch/retry.mjs +32 -1
  41. package/src/batch/review-artifacts.mjs +3 -2
  42. package/src/batch/review-level-effective.mjs +19 -0
  43. package/src/batch/review-spawn.mjs +12 -1
  44. package/src/batch/review-step-run.mjs +18 -2
  45. package/src/batch/review-step.mjs +1 -0
  46. package/src/batch/reviewer-provider-error.mjs +153 -0
  47. package/src/batch/worker-heartbeat.mjs +10 -2
  48. package/src/batch/worker-host.mjs +1 -1
  49. package/src/batch/worker-prompt.mjs +9 -7
  50. package/src/cli/deps.mjs +3 -2
  51. package/src/config/agent-model-resolve.mjs +144 -8
  52. package/src/config/cursor-rules/discover.mjs +38 -1
  53. package/src/config/model-family.mjs +60 -0
  54. package/src/config/preflight/discovery.mjs +1 -0
  55. package/src/config/settings-fields.mjs +11 -0
  56. package/src/config/spine-config-schema.mjs +87 -0
  57. package/src/doctor/agent-model-inherit.mjs +78 -1
  58. package/src/doctor/pi-extension-hooks.mjs +322 -0
  59. package/src/doctor/run-doctor-checks.mjs +18 -2
  60. package/src/metrics/quota-cli.mjs +16 -0
  61. package/src/metrics/quota-probes.mjs +228 -31
  62. package/src/metrics/quota-snapshot.mjs +21 -2
  63. package/src/planner/graph.mjs +7 -5
  64. package/src/planner/pending.mjs +2 -2
  65. package/src/planner/scope.mjs +3 -3
  66. package/src/tasks/packet/parse-prompt.mjs +47 -0
  67. package/src/tasks/packet/validate-prompt.mjs +167 -2
  68. package/src/tasks/validate-contract-warn.mjs +16 -0
  69. package/templates/agents/reviewer.md +3 -1
  70. package/templates/agents/worker.md +15 -19
  71. package/templates/spine-config.json +1 -1
@@ -35,7 +35,7 @@ const DEFAULT_AUTH_PATH = path.join(os.homedir(), ".pi", "agent", "auth.json");
35
35
 
36
36
  const PROBE_URLS = {
37
37
  zai: "https://api.z.ai/api/monitor/usage/quota/limit",
38
- "kimi-coding": "https://api.moonshot.ai/v1/users/me/balance",
38
+ "kimi-coding": "https://api.kimi.com/coding/v1/usages",
39
39
  cursor: "https://api.cursor.com/teams/daily-usage-data",
40
40
  anthropic: "https://api.anthropic.com/v1/organizations/usage_report/messages",
41
41
  };
@@ -61,14 +61,34 @@ export const PROBE_POOLS = {
61
61
  */
62
62
 
63
63
  /**
64
+ * One quota window reported by a provider (for example the 5-hour or weekly
65
+ * window). `percentUsed` is 0-100 and is only set from provider-reported data.
66
+ *
67
+ * @typedef {object} QuotaWindow
68
+ * @property {string} window Window id: `"5h"`, `"weekly"`, or `"monthly_tool_calls"`.
69
+ * @property {number} percentUsed
70
+ * @property {number} [used]
71
+ * @property {number} [limit]
72
+ * @property {string} [resetAt] ISO 8601 reset time.
73
+ */
74
+
75
+ /**
76
+ * `source` is `"live"` only when at least one window or usage value was
77
+ * parsed. A successful HTTP response with no recognised quota fields is
78
+ * `"unparsed"`; missing credentials, non-2xx responses, and network errors are
79
+ * `"absent"`.
80
+ *
64
81
  * @typedef {object} ProbeResult
65
82
  * @property {string} poolId
66
- * @property {"live" | "absent"} source
83
+ * @property {"live" | "absent" | "unparsed"} source
67
84
  * @property {PoolUsage} [usage]
68
85
  * @property {number} [limit]
69
- * @property {Error} [error]
86
+ * @property {QuotaWindow[]} [windows]
87
+ * @property {Error | string} [error]
70
88
  */
71
89
 
90
+ const UNPARSED_ERROR = "HTTP 200 but no quota fields recognised";
91
+
72
92
  /**
73
93
  * Read and parse the pi agent auth file, returning `null` when it is missing
74
94
  * or unreadable so callers fail closed.
@@ -197,6 +217,24 @@ async function fetchJsonWithBearer(url, key, fetch) {
197
217
  return fetchJsonWithHeaders(url, { Authorization: `Bearer ${key}` }, fetch);
198
218
  }
199
219
 
220
+ /**
221
+ * Coerce a provider value to a finite non-negative number. Numeric strings
222
+ * (`"63"`) are accepted because some providers serialise counters as strings.
223
+ *
224
+ * @param {unknown} value
225
+ * @returns {number | undefined}
226
+ */
227
+ function toNonNegativeNumber(value) {
228
+ if (typeof value === "number") {
229
+ return Number.isFinite(value) && value >= 0 ? value : undefined;
230
+ }
231
+ if (typeof value === "string" && value.trim() !== "") {
232
+ const parsed = Number(value);
233
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
234
+ }
235
+ return undefined;
236
+ }
237
+
200
238
  /**
201
239
  * Extract a numeric limit from a provider response when it is explicitly
202
240
  * present; otherwise return `undefined` so the snapshot does not invent one.
@@ -208,8 +246,8 @@ async function fetchJsonWithBearer(url, key, fetch) {
208
246
  function extractLimit(data, fields) {
209
247
  if (!data || typeof data !== "object") return undefined;
210
248
  for (const field of fields) {
211
- const value = data[field];
212
- if (Number.isFinite(value) && value >= 0) return value;
249
+ const value = toNonNegativeNumber(data[field]);
250
+ if (value !== undefined) return value;
213
251
  }
214
252
  return undefined;
215
253
  }
@@ -223,19 +261,183 @@ function extractLimit(data, fields) {
223
261
  * @returns {number | undefined}
224
262
  */
225
263
  function extractNumber(data, fields) {
226
- if (!data || typeof data !== "object") return undefined;
227
- for (const field of fields) {
228
- const value = data[field];
229
- if (Number.isFinite(value) && value >= 0) return value;
264
+ return extractLimit(data, fields);
265
+ }
266
+
267
+ /**
268
+ * Round a percentage to two decimals so float noise (62.74999999999999) does
269
+ * not reach reports.
270
+ *
271
+ * @param {number} value
272
+ * @returns {number}
273
+ */
274
+ function roundPercent(value) {
275
+ return Math.round(value * 100) / 100;
276
+ }
277
+
278
+ /**
279
+ * Normalise a reset time (epoch milliseconds as number or numeric string, or
280
+ * an ISO 8601 string) to an ISO string. Returns `undefined` when unparseable.
281
+ *
282
+ * @param {unknown} value
283
+ * @returns {string | undefined}
284
+ */
285
+ function toIsoTime(value) {
286
+ if (value === undefined || value === null || value === "") return undefined;
287
+ const epoch = toNonNegativeNumber(value);
288
+ const date = new Date(epoch !== undefined ? epoch : /** @type {string} */ (value));
289
+ if (Number.isNaN(date.getTime())) return undefined;
290
+ return date.toISOString();
291
+ }
292
+
293
+ /**
294
+ * Build a window entry, omitting fields the provider did not report.
295
+ *
296
+ * @param {string} window
297
+ * @param {number | undefined} percentUsed
298
+ * @param {{ used?: number, limit?: number, resetAt?: string }} [extra]
299
+ * @returns {QuotaWindow | undefined}
300
+ */
301
+ function makeWindow(window, percentUsed, extra = {}) {
302
+ if (percentUsed === undefined) return undefined;
303
+ /** @type {QuotaWindow} */
304
+ const entry = { window, percentUsed: roundPercent(percentUsed) };
305
+ if (extra.used !== undefined) entry.used = extra.used;
306
+ if (extra.limit !== undefined) entry.limit = extra.limit;
307
+ if (extra.resetAt !== undefined) entry.resetAt = extra.resetAt;
308
+ return entry;
309
+ }
310
+
311
+ /**
312
+ * Percentage from explicit `used` / `limit` counters; `undefined` when the
313
+ * limit is missing or zero.
314
+ *
315
+ * @param {number | undefined} used
316
+ * @param {number | undefined} limit
317
+ * @returns {number | undefined}
318
+ */
319
+ function percentFromCounts(used, limit) {
320
+ if (used === undefined || limit === undefined || limit <= 0) return undefined;
321
+ return (used / limit) * 100;
322
+ }
323
+
324
+ /**
325
+ * Parse Z.ai `data.limits[]` into quota windows. `TOKENS_LIMIT` entries map by
326
+ * `unit`/`number` (3/5 = 5-hour, 6/1 = weekly); `TIME_LIMIT` is the monthly
327
+ * tool-call allowance. Unknown entries are skipped, never guessed.
328
+ *
329
+ * @param {unknown} limits
330
+ * @returns {QuotaWindow[]}
331
+ */
332
+ function parseZaiWindows(limits) {
333
+ if (!Array.isArray(limits)) return [];
334
+ /** @type {QuotaWindow[]} */
335
+ const windows = [];
336
+ const seen = new Set();
337
+ for (const item of limits) {
338
+ if (!item || typeof item !== "object") continue;
339
+ let id;
340
+ if (item.type === "TOKENS_LIMIT") {
341
+ const unit = toNonNegativeNumber(item.unit);
342
+ const number = toNonNegativeNumber(item.number);
343
+ if (unit === 3 && number === 5) id = "5h";
344
+ else if (unit === 6 && number === 1) id = "weekly";
345
+ } else if (item.type === "TIME_LIMIT") {
346
+ id = "monthly_tool_calls";
347
+ }
348
+ if (!id || seen.has(id)) continue;
349
+
350
+ // For TIME_LIMIT, `usage` is the allowance and `currentValue` the count used.
351
+ const limit = id === "monthly_tool_calls" ? toNonNegativeNumber(item.usage) : undefined;
352
+ const used = id === "monthly_tool_calls" ? toNonNegativeNumber(item.currentValue) : undefined;
353
+ const percent = toNonNegativeNumber(item.percentage) ?? percentFromCounts(used, limit);
354
+ const entry = makeWindow(id, percent, { used, limit, resetAt: toIsoTime(item.nextResetTime) });
355
+ if (!entry) continue;
356
+ seen.add(id);
357
+ windows.push(entry);
230
358
  }
231
- return undefined;
359
+ return windows;
360
+ }
361
+
362
+ /**
363
+ * True when a Kimi `limits[]` window descriptor is the 5-hour window
364
+ * (300 minutes or 5 hours).
365
+ *
366
+ * @param {object | undefined} win
367
+ * @returns {boolean}
368
+ */
369
+ function isKimiFiveHourWindow(win) {
370
+ if (!win || typeof win !== "object") return false;
371
+ const duration = toNonNegativeNumber(win.duration);
372
+ if (duration === undefined) return false;
373
+ if (win.timeUnit === "TIME_UNIT_MINUTE") return duration === 300;
374
+ if (win.timeUnit === "TIME_UNIT_HOUR") return duration === 5;
375
+ return false;
376
+ }
377
+
378
+ /**
379
+ * Build a window from a Kimi `{ used, limit, resetTime }` counter block.
380
+ *
381
+ * @param {string} id
382
+ * @param {object | undefined} block
383
+ * @returns {QuotaWindow | undefined}
384
+ */
385
+ function kimiCounterWindow(id, block) {
386
+ if (!block || typeof block !== "object") return undefined;
387
+ const used = toNonNegativeNumber(block.used);
388
+ const limit = toNonNegativeNumber(block.limit);
389
+ return makeWindow(id, percentFromCounts(used, limit), {
390
+ used,
391
+ limit,
392
+ resetAt: toIsoTime(block.resetTime),
393
+ });
394
+ }
395
+
396
+ /**
397
+ * Parse the Kimi Coding `/coding/v1/usages` response. `usages.limit_5h` and
398
+ * `usages.limit_7d` (`used_ratio`, `reset_time`) are preferred; `limits[]`
399
+ * detail (5-hour) and top-level `usage` (weekly) are fallbacks.
400
+ *
401
+ * @param {object} data
402
+ * @returns {QuotaWindow[]}
403
+ */
404
+ function parseKimiWindows(data) {
405
+ /** @type {QuotaWindow[]} */
406
+ const windows = [];
407
+ const usages = data.usages && typeof data.usages === "object" ? data.usages : {};
408
+
409
+ const ratioWindow = (id, block) => {
410
+ if (!block || typeof block !== "object") return undefined;
411
+ const ratio = toNonNegativeNumber(block.used_ratio);
412
+ return makeWindow(id, ratio === undefined ? undefined : ratio * 100, {
413
+ resetAt: toIsoTime(block.reset_time),
414
+ });
415
+ };
416
+
417
+ let fiveHour = ratioWindow("5h", usages.limit_5h);
418
+ if (!fiveHour && Array.isArray(data.limits)) {
419
+ for (const item of data.limits) {
420
+ if (!item || typeof item !== "object" || !isKimiFiveHourWindow(item.window)) continue;
421
+ fiveHour = kimiCounterWindow("5h", item.detail);
422
+ if (fiveHour) break;
423
+ }
424
+ }
425
+ if (fiveHour) windows.push(fiveHour);
426
+
427
+ const weekly = ratioWindow("weekly", usages.limit_7d) ?? kimiCounterWindow("weekly", data.usage);
428
+ if (weekly) windows.push(weekly);
429
+
430
+ return windows;
232
431
  }
233
432
 
234
433
  /**
235
434
  * Z.ai probe — uses the bearer key from `auth.json` to request the quota
236
435
  * monitor endpoint.
237
436
  *
238
- * Expected shape (used by mocked tests): `{ used: number, total: number }`.
437
+ * Real shape: `{ data: { limits: [{ type, unit, number, percentage,
438
+ * nextResetTime }] } }` (see #351). Flat `{ used, total }` bodies are still
439
+ * read when present. A 2xx response with nothing recognised is `"unparsed"`,
440
+ * never `"live"`.
239
441
  *
240
442
  * @param {object | null} auth
241
443
  * @param {typeof globalThis.fetch} fetch
@@ -259,8 +461,14 @@ async function probeZai(auth, fetch) {
259
461
  extractLimit(data, ["total", "total_tokens", "limit"]) ??
260
462
  extractLimit(data.data, ["total", "total_tokens", "limit"]);
261
463
 
464
+ const windows = parseZaiWindows(data.data?.limits);
465
+
466
+ if (used === undefined && windows.length === 0) {
467
+ return { poolId: "zai", source: "unparsed", error: UNPARSED_ERROR };
468
+ }
262
469
  const result = { poolId: "zai", source: "live", usage };
263
470
  if (limit !== undefined) result.limit = limit;
471
+ if (windows.length > 0) result.windows = windows;
264
472
  return result;
265
473
  } catch (error) {
266
474
  return { poolId: "zai", source: "absent", error };
@@ -268,10 +476,10 @@ async function probeZai(auth, fetch) {
268
476
  }
269
477
 
270
478
  /**
271
- * Kimi (Moonshot) probe — uses the bearer key from `auth.json` to request the
272
- * balance endpoint.
273
- *
274
- * Expected shape (used by mocked tests): `{ used: number, total: number }`.
479
+ * Kimi Coding probe — uses the bearer key from `auth.json` to request the
480
+ * `/coding/v1/usages` endpoint (the Moonshot platform balance endpoint rejects
481
+ * Kimi Coding plan keys). Numbers arrive as strings. A 2xx response with
482
+ * nothing recognised is `"unparsed"`, never `"live"`.
275
483
  *
276
484
  * @param {object | null} auth
277
485
  * @param {typeof globalThis.fetch} fetch
@@ -285,24 +493,13 @@ async function probeKimi(auth, fetch) {
285
493
  const data = await fetchJsonWithBearer(PROBE_URLS["kimi-coding"], key, fetch);
286
494
  if (!data) return { poolId: "kimi-coding", source: "absent" };
287
495
 
496
+ const windows = parseKimiWindows(data);
497
+ if (windows.length === 0) {
498
+ return { poolId: "kimi-coding", source: "unparsed", error: UNPARSED_ERROR };
499
+ }
288
500
  /** @type {PoolUsage} */
289
501
  const usage = { taskCount: 0, durationMs: 0 };
290
- const used = extractNumber(data, ["used", "used_tokens"])
291
- ?? extractNumber(data.data, ["used", "used_tokens"]);
292
- if (used !== undefined) usage.tokensOut = used;
293
-
294
- const balance =
295
- extractNumber(data, ["balance", "cash"]) ??
296
- extractNumber(data.data, ["balance", "cash"]);
297
- if (balance !== undefined) usage.estimatedUsd = balance;
298
-
299
- const limit =
300
- extractLimit(data, ["total", "total_tokens", "limit"]) ??
301
- extractLimit(data.data, ["total", "total_tokens", "limit"]);
302
-
303
- const result = { poolId: "kimi-coding", source: "live", usage };
304
- if (limit !== undefined) result.limit = limit;
305
- return result;
502
+ return { poolId: "kimi-coding", source: "live", usage, windows };
306
503
  } catch (error) {
307
504
  return { poolId: "kimi-coding", source: "absent", error };
308
505
  }
@@ -93,6 +93,7 @@ export function collectExpectedModels(config) {
93
93
  /**
94
94
  * @typedef {object} PoolUsage
95
95
  * @property {number} taskCount
96
+ * @property {number} [reviewCount] Reviewer rows (SP-837); present only when > 0, not part of `taskCount`.
96
97
  * @property {number} durationMs
97
98
  * @property {number} [tokensIn]
98
99
  * @property {number} [tokensOut]
@@ -118,7 +119,11 @@ export function aggregatePoolUsage(records) {
118
119
 
119
120
  for (const record of records) {
120
121
  if (!record || typeof record !== "object") continue;
121
- usage.taskCount += 1;
122
+ if (record.recordType === "review") {
123
+ usage.reviewCount = (usage.reviewCount ?? 0) + 1;
124
+ } else {
125
+ usage.taskCount += 1;
126
+ }
122
127
  if (Number.isFinite(record.durationMs)) {
123
128
  usage.durationMs += Math.max(0, record.durationMs);
124
129
  }
@@ -166,6 +171,7 @@ function buildPoolDrift(expectedModels, observedModels) {
166
171
  * @property {string[]} observedModels
167
172
  * @property {PoolUsage} usage
168
173
  * @property {number} [limit]
174
+ * @property {import("./quota-probes.mjs").QuotaWindow[]} [windows] Per-window percent/reset from a live probe.
169
175
  * @property {{unexpectedModels: string[], missingModels: string[]}} drift
170
176
  */
171
177
 
@@ -195,8 +201,11 @@ export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeRes
195
201
  const filePath = metricsFilePath(projectRoot, config);
196
202
  lines = readMetricsLines(filePath);
197
203
  }
204
+ // SP-837 (#325): reviewer rows count toward observed models and pool usage;
205
+ // aggregatePoolUsage keeps them out of taskCount.
198
206
  const taskRecords = (lines ?? []).filter(
199
- (line) => line && typeof line === "object" && line.recordType === "task",
207
+ (line) =>
208
+ line && typeof line === "object" && (line.recordType === "task" || line.recordType === "review"),
200
209
  );
201
210
 
202
211
  const expectedModels = collectExpectedModels(config);
@@ -239,11 +248,20 @@ export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeRes
239
248
  /** @type {PoolUsage} */
240
249
  let usage = aggregatePoolUsage(observedRecords);
241
250
  let limit;
251
+ let windows;
242
252
 
253
+ // Only a "live" probe enriches the pool. "unparsed" (HTTP 200 with no
254
+ // recognised quota fields) and "absent" both fall back to the estimate.
243
255
  if (probe?.source === "live") {
244
256
  source = "live";
245
257
  usage = probe.usage && typeof probe.usage === "object" ? probe.usage : usage;
246
258
  if (Number.isFinite(probe.limit) && probe.limit >= 0) limit = probe.limit;
259
+ if (Array.isArray(probe.windows)) {
260
+ const valid = probe.windows.filter(
261
+ (w) => w && typeof w.window === "string" && Number.isFinite(w.percentUsed),
262
+ );
263
+ if (valid.length > 0) windows = valid;
264
+ }
247
265
  }
248
266
 
249
267
  if (source === "live") overallHasLive = true;
@@ -259,6 +277,7 @@ export function buildQuotaSnapshot({ projectRoot, config, metricsLines, probeRes
259
277
  drift: buildPoolDrift([...expectedSet], [...observedSet]),
260
278
  };
261
279
  if (limit !== undefined) pool.limit = limit;
280
+ if (windows !== undefined) pool.windows = windows;
262
281
  pools[poolId] = pool;
263
282
  }
264
283
 
@@ -10,6 +10,8 @@
10
10
  * included in the graph.
11
11
  */
12
12
 
13
+ import { compareTaskIds } from '../tasks/packet/discover.mjs';
14
+
13
15
  /**
14
16
  * @param {Record<string, string[]>} depsByTask
15
17
  * @returns {{ nodes: string[], depsByTask: Record<string, string[]>, dependentsByTask: Record<string, string[]> }}
@@ -37,9 +39,9 @@ export function buildGraph(depsByTask) {
37
39
  if (!dependentsByTask[id]) dependentsByTask[id] = [];
38
40
  }
39
41
 
40
- const nodes = Array.from(nodesSet).sort();
42
+ const nodes = Array.from(nodesSet).sort(compareTaskIds);
41
43
  for (const id of Object.keys(dependentsByTask)) {
42
- dependentsByTask[id].sort();
44
+ dependentsByTask[id].sort(compareTaskIds);
43
45
  }
44
46
 
45
47
  return { nodes, depsByTask: normalized, dependentsByTask };
@@ -69,7 +71,7 @@ export function topoWaves(graph) {
69
71
  const zero = Array.from(indegree.entries())
70
72
  .filter(([, deg]) => deg === 0)
71
73
  .map(([id]) => id)
72
- .sort();
74
+ .sort(compareTaskIds);
73
75
 
74
76
  const waves = [];
75
77
  let current = zero;
@@ -88,13 +90,13 @@ export function topoWaves(graph) {
88
90
  }
89
91
  }
90
92
 
91
- current = next.sort();
93
+ current = next.sort(compareTaskIds);
92
94
  }
93
95
 
94
96
  const remainingWithDeps = Array.from(indegree.entries())
95
97
  .filter(([, deg]) => deg > 0)
96
98
  .map(([id]) => id)
97
- .sort();
99
+ .sort(compareTaskIds);
98
100
 
99
101
  return { waves, remainingWithDeps };
100
102
  }
@@ -4,7 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
- import { TASK_ID_RE } from "./scope.mjs";
7
+ import { TASK_ID_RE, compareTaskIds } from "../tasks/packet/discover.mjs";
8
8
 
9
9
  /**
10
10
  * @param {Array<{ taskId: string, folderPath: string }>} discoveredTasks
@@ -23,7 +23,7 @@ export function filterPendingTaskIds(discoveredTasks, tasksRoot) {
23
23
  }
24
24
  }
25
25
 
26
- return pending.sort();
26
+ return pending.sort(compareTaskIds);
27
27
  }
28
28
 
29
29
  /**
@@ -13,7 +13,7 @@ import path from 'node:path';
13
13
  import { summarizePendingScope } from './pending.mjs';
14
14
 
15
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';
16
+ import { TASK_ID_RE, compareTaskIds } from '../tasks/packet/discover.mjs';
17
17
  export { TASK_ID_RE };
18
18
 
19
19
  export const NO_PENDING_TASKS_ERROR = 'No pending tasks (all discovered tasks have .DONE).';
@@ -74,7 +74,7 @@ function tokenizeScope(scope) {
74
74
  * @returns {{ mode: 'all'|'pending'|'ids'|'glob'|'custom', taskIds: string[], excludedCount?: number }}
75
75
  */
76
76
  export function parseScope(scopeArg, { tasksRoot, discoveredTasks }) {
77
- const allTaskIds = discoveredTasks.map((t) => t.taskId).sort();
77
+ const allTaskIds = discoveredTasks.map((t) => t.taskId).sort(compareTaskIds);
78
78
  const tasksRootPosix = String(tasksRoot).replace(/\\/g, '/');
79
79
  const tasksRootBase = path.posix.basename(tasksRootPosix);
80
80
 
@@ -135,7 +135,7 @@ export function parseScope(scopeArg, { tasksRoot, discoveredTasks }) {
135
135
 
136
136
  const resolved = Array.from(selected)
137
137
  .filter((id) => allTaskIds.includes(id))
138
- .sort();
138
+ .sort(compareTaskIds);
139
139
 
140
140
  if (resolved.length === 0) {
141
141
  throw new Error(`Scope did not match any discovered task(s): ${String(scopeArg)}`);
@@ -144,6 +144,31 @@ export function formatRefusedContractMetacharMessage(command) {
144
144
  const issue = findContractCommandMetacharIssue(String(command ?? "").trim());
145
145
  return `Contract testCommand refused before spawn: ${issue ?? "shell metacharacters"} (command: ${command}). Contract testCommand runs through a shell; remove $, backticks, ;, |, || or lone & — && chains are allowed (#268).`;
146
146
  }
147
+ /** Allowed `**Thinking:**` levels (SP-833 / #340). */
148
+ export const PROMPT_THINKING_LEVELS = Object.freeze([
149
+ "off",
150
+ "minimal",
151
+ "low",
152
+ "medium",
153
+ "high",
154
+ "xhigh",
155
+ ]);
156
+ /** Profile names accepted by `**Profile:**` / `**Reviewer Profile:**`. */
157
+ export const PROMPT_PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
158
+ const PROFILE_LINE_RE = /^\*\*Profile:\*\*[ \t]*(.*?)[ \t]*$/im;
159
+ const THINKING_LINE_RE = /^\*\*Thinking:\*\*[ \t]*(.*?)[ \t]*$/im;
160
+ const REVIEWER_PROFILE_LINE_RE = /^\*\*Reviewer Profile:\*\*[ \t]*(.*?)[ \t]*$/im;
161
+
162
+ /**
163
+ * @param {RegExp} re
164
+ * @param {string} markdown
165
+ * @returns {string|null} Trimmed value, or null when absent/empty
166
+ */
167
+ function parseHeaderValue(re, markdown) {
168
+ const value = re.exec(markdown)?.[1]?.trim();
169
+ return value ? value : null;
170
+ }
171
+
147
172
  export const SEE_FILE_SCOPE_RE = /^see\s+file\s+scope$/i;
148
173
  const CONTRACT_EM_DASH_PLACEHOLDER_RE = /^[—\-]$/;
149
174
  const CONTRACT_NONE_VALUES = new Set([
@@ -177,6 +202,9 @@ export function parsePrompt(markdown) {
177
202
  const size = parseSizeLineFromMarkdown(markdown);
178
203
  const typeMatch = /^\*\*Type:\*\*\s*(llm|execute)\s*$/im.exec(markdown);
179
204
  const type = typeMatch ? typeMatch[1].toLowerCase() : "llm";
205
+ const profile = parseHeaderValue(PROFILE_LINE_RE, markdown);
206
+ const thinking = parseHeaderValue(THINKING_LINE_RE, markdown);
207
+ const reviewerProfile = parseHeaderValue(REVIEWER_PROFILE_LINE_RE, markdown);
180
208
 
181
209
  let matrix = null;
182
210
  let matrixColumns = null;
@@ -193,6 +221,9 @@ export function parsePrompt(markdown) {
193
221
  title,
194
222
  size,
195
223
  type,
224
+ profile,
225
+ thinking,
226
+ reviewerProfile,
196
227
  headingLine,
197
228
  sections,
198
229
  steps,
@@ -237,6 +268,22 @@ export function validatePrompt(markdown) {
237
268
 
238
269
  errors.push(...collectDuplicateStepNumberErrors(prompt.steps));
239
270
 
271
+ if (prompt.thinking !== null && !PROMPT_THINKING_LEVELS.includes(prompt.thinking)) {
272
+ errors.push(
273
+ `**Thinking:** must be one of ${PROMPT_THINKING_LEVELS.join("|")} (got "${prompt.thinking}")`,
274
+ );
275
+ }
276
+ for (const [label, value] of [
277
+ ["Profile", prompt.profile],
278
+ ["Reviewer Profile", prompt.reviewerProfile],
279
+ ]) {
280
+ if (value !== null && !PROMPT_PROFILE_NAME_RE.test(value)) {
281
+ errors.push(
282
+ `**${label}:** malformed profile name "${value}" (allowed characters: A-Z a-z 0-9 . _ -)`,
283
+ );
284
+ }
285
+ }
286
+
240
287
  if (prompt.type === "execute") {
241
288
  const contract = parseContract(markdown);
242
289
  if (!contract.testCommand && !contract.runCommand) {