neurastream 0.3.25 → 0.3.27

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.
@@ -13,7 +13,9 @@ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
13
13
  import { join } from "node:path";
14
14
  import type { Config } from "./config.ts";
15
15
  import { nowSec, strftime } from "./clock.ts";
16
- import { parseWhen, wallToEpoch } from "./reset-time.ts";
16
+ import { allowedAgents } from "./queue/lib.ts";
17
+ import { parseWhen, wallToEpoch, type WallTime } from "./reset-time.ts";
18
+ import { SPAWN_ROLES, type SpawnRole } from "./runner.ts";
17
19
 
18
20
  /** One recorded out-until: `until`/`at` are epoch seconds. */
19
21
  export interface OutRecord {
@@ -126,37 +128,422 @@ export function pinModel(cfg: Config, agent: string): string | null {
126
128
  }
127
129
 
128
130
  /**
129
- * The first reset time a text names, as epoch seconds, or null when it names none we can trust.
130
- * Reuses parseWhen/wallToEpoch: the wall time comes from capture group 1, the zone from group 2
131
- * when the text names one (Z/UTC/GMT, ±HH:MM) and `rule.zone` otherwise. reset-time.ts cannot
132
- * grow an export for this (the plan freezes that file), so the ±HH:MM arithmetic sits here.
131
+ * Resolves an agent's provider from `spawn.profiles[agent].provider`, falling back to the
132
+ * provider prefix of its pin file's `model:` line when unconfigured.
133
+ *
134
+ * Args:
135
+ * cfg (Config): Loaded configuration
136
+ * agent (string): Agent or profile name
137
+ *
138
+ * Returns:
139
+ * string | null: Provider slug, or null when neither profile nor pin names one
133
140
  */
134
- export function resetEpochFromText(text: string, rule: { pattern: string; zone: string }): number | null {
135
- let pattern: RegExp;
141
+ export function agentProvider(cfg: Config, agent: string): string | null {
142
+ const explicit = cfg.spawn.profiles[agent]?.provider?.trim();
143
+ if (explicit) return explicit;
144
+ return providerOfModel(pinModel(cfg, agent));
145
+ }
146
+
147
+ /**
148
+ * Resolves an agent's functional role from `spawn.profiles[agent].role`, defaulting to
149
+ * `"reviewer"` when listed in `review.agents` and `"implementer"` otherwise.
150
+ *
151
+ * Args:
152
+ * cfg (Config): Loaded configuration
153
+ * agent (string): Agent or profile name
154
+ *
155
+ * Returns:
156
+ * SpawnRole: Resolved role (`"implementer" | "planner" | "reviewer"`)
157
+ */
158
+ export function agentRole(cfg: Config, agent: string): SpawnRole {
159
+ const explicit = cfg.spawn.profiles[agent]?.role;
160
+ if (explicit) return explicit;
161
+ return cfg.review.agents.includes(agent) ? "reviewer" : "implementer";
162
+ }
163
+
164
+ function reachableAgentsByRole(cfg: Config, now: number): { byRole: Record<SpawnRole, string[]>; hasSignal: boolean } {
165
+ const byRole: Record<SpawnRole, string[]> = {
166
+ implementer: [],
167
+ planner: [],
168
+ reviewer: [],
169
+ };
170
+ const candidates = [...new Set([...cfg.ledger.prefer, ...Object.keys(cfg.spawn.profiles)])];
171
+ if (candidates.length === 0) return { byRole, hasSignal: false };
172
+ const allowed = allowedAgents(cfg.paths.subagents);
173
+ let hasSignal = false;
174
+ for (const agent of candidates) {
175
+ if (allowed.size > 0 && !allowed.has(agent)) continue;
176
+ const profile = cfg.spawn.profiles[agent];
177
+ const provider = agentProvider(cfg, agent);
178
+ const explicitRole = profile?.role;
179
+ if (provider === null && explicitRole === undefined) continue;
180
+ hasSignal = true;
181
+ if (provider !== null && outUntil(cfg, provider, now) !== null) continue;
182
+ byRole[agentRole(cfg, agent)].push(agent);
183
+ }
184
+ return { byRole, hasSignal };
185
+ }
186
+
187
+ /**
188
+ * Returns currently reachable agents for a given role in `ledger.prefer` order followed by
189
+ * remaining configured profiles, excluding agents whose provider is currently recorded out.
190
+ *
191
+ * Args:
192
+ * cfg (Config): Loaded configuration
193
+ * role (SpawnRole): Target role (`"implementer" | "planner" | "reviewer"`)
194
+ * now (number): Current unix epoch seconds
195
+ *
196
+ * Returns:
197
+ * string[]: Reachable agent names for the role
198
+ */
199
+ export function reachableAgentsForRole(cfg: Config, role: SpawnRole, now: number = nowSec()): string[] {
200
+ return reachableAgentsByRole(cfg, now).byRole[role];
201
+ }
202
+
203
+ /**
204
+ * Formats a single summary line of currently reachable agents grouped by role
205
+ * (`implementer`, `planner`, `reviewer`) in `ledger.prefer` order followed by configured profiles.
206
+ * Returns null when no profile or `ledger.prefer` entry defines a provider or role, or none are reachable.
207
+ *
208
+ * Args:
209
+ * cfg (Config): Loaded configuration
210
+ * now (number): Current unix epoch seconds
211
+ *
212
+ * Returns:
213
+ * string | null: Formatted `reachable: ...` line, or null when unavailable
214
+ */
215
+ export function reachableAgentsLine(cfg: Config, now: number = nowSec()): string | null {
216
+ const { byRole, hasSignal } = reachableAgentsByRole(cfg, now);
217
+ if (!hasSignal) return null;
218
+ const parts: string[] = [];
219
+ for (const role of SPAWN_ROLES) {
220
+ if (byRole[role].length > 0) parts.push(`${role}: ${byRole[role].join(", ")}`);
221
+ }
222
+ if (parts.length === 0) return null;
223
+ return `reachable: ${parts.join(" · ")}`;
224
+ }
225
+
226
+ const HUMAN_MONTHS: Record<string, number> = {
227
+ jan: 1,
228
+ january: 1,
229
+ feb: 2,
230
+ february: 2,
231
+ mar: 3,
232
+ march: 3,
233
+ apr: 4,
234
+ april: 4,
235
+ may: 5,
236
+ jun: 6,
237
+ june: 6,
238
+ jul: 7,
239
+ july: 7,
240
+ aug: 8,
241
+ august: 8,
242
+ sep: 9,
243
+ sept: 9,
244
+ september: 9,
245
+ oct: 10,
246
+ october: 10,
247
+ nov: 11,
248
+ november: 11,
249
+ dec: 12,
250
+ december: 12,
251
+ };
252
+
253
+ const DURATION_UNITS_SEC: Record<string, number> = {
254
+ d: 86400,
255
+ day: 86400,
256
+ days: 86400,
257
+ h: 3600,
258
+ hr: 3600,
259
+ hrs: 3600,
260
+ hour: 3600,
261
+ hours: 3600,
262
+ m: 60,
263
+ min: 60,
264
+ mins: 60,
265
+ minute: 60,
266
+ minutes: 60,
267
+ s: 1,
268
+ sec: 1,
269
+ secs: 1,
270
+ second: 1,
271
+ seconds: 1,
272
+ };
273
+
274
+ const ISO_RESET_RE = /\b(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?\s*(Z|[+-]\d{2}:?\d{2})(?![A-Za-z0-9])/i;
275
+ const RELATIVE_RESET_RE =
276
+ /(?:^|[\s(,.:;])(?:in|after)\s*~?\s*((?:\d+(?:\.\d+)?\s*(?:days?|d|hours?|hrs?|hr|h|minutes?|mins?|min|m|seconds?|secs?|sec|s)(?=\d|\s|$|[,.;:!?)\]])(?:\s*,?\s*(?:and\s+)?|\s*)?)+)/i;
277
+ const RELATIVE_TOKEN_RE = /(\d+(?:\.\d+)?)\s*(days?|d|hours?|hrs?|hr|h|minutes?|mins?|min|m|seconds?|secs?|sec|s)(?=\d|\s|$|[,.;:!?)\]])/gi;
278
+ const HUMAN_RESET_RE =
279
+ /\b(?:resets?(?:\s+(?:at|on))?|try\s+again(?:\s+(?:at|on))?|available(?:\s+(?:again\s+)?(?:at|on))?)\s+(?:(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?(?:\s*(?:,|at)\s*|\s+))?(?:(\d{1,2})(?::(\d{2})(?::(\d{2}))?)?\s*(am|pm)\b|(\d{1,2}):(\d{2})(?::(\d{2}))?\b)(?:\s*\(\s*(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Z]{2,5}|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+)\s*\)|\s+(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+))?/i;
280
+
281
+ /**
282
+ * Validates that a wall-clock tuple represents an existing calendar date and time.
283
+ *
284
+ * Args:
285
+ * wall (WallTime): Wall-clock components to validate
286
+ *
287
+ * Returns:
288
+ * boolean: True when calendar date and clock fields are in valid range
289
+ */
290
+ function isValidWall(wall: WallTime): boolean {
291
+ if (wall.mo < 1 || wall.mo > 12 || wall.d < 1 || wall.d > 31) return false;
292
+ if (wall.h < 0 || wall.h > 23 || wall.mi < 0 || wall.mi > 59 || wall.s < 0 || wall.s > 59) return false;
293
+ const check = new Date(Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s));
294
+ return (
295
+ check.getUTCFullYear() === wall.y &&
296
+ check.getUTCMonth() === wall.mo - 1 &&
297
+ check.getUTCDate() === wall.d &&
298
+ check.getUTCHours() === wall.h &&
299
+ check.getUTCMinutes() === wall.mi &&
300
+ check.getUTCSeconds() === wall.s
301
+ );
302
+ }
303
+
304
+ /**
305
+ * Converts a wall-clock time in an explicit zone (UTC, GMT, Z, ±HH:MM offset, or IANA zone)
306
+ * to unix epoch seconds.
307
+ *
308
+ * Args:
309
+ * wall (WallTime): Wall-clock components
310
+ * zone (string): Zone identifier or numeric UTC offset
311
+ *
312
+ * Returns:
313
+ * number | null: Unix epoch seconds, or null if the wall time or zone is invalid
314
+ */
315
+ function zoneToEpoch(wall: WallTime, zone: string): number | null {
316
+ if (!isValidWall(wall)) return null;
317
+ const z = zone.trim();
318
+ const upper = z.toUpperCase();
136
319
  try {
137
- pattern = new RegExp(rule.pattern);
320
+ if (upper === "Z" || upper === "UTC" || upper === "GMT") return wallToEpoch(wall, "UTC");
321
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(z);
322
+ if (offset) {
323
+ const hh = Number(offset[2]);
324
+ const mm = Number(offset[3]);
325
+ if (hh > 23 || mm > 59) return null;
326
+ const minutes = (hh * 60 + mm) * (offset[1] === "+" ? 1 : -1);
327
+ return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
328
+ }
329
+ return wallToEpoch(wall, z);
138
330
  } catch {
139
331
  return null;
140
332
  }
141
- const m = pattern.exec(text);
142
- if (!m) return null;
143
- const wall = m[1] ? parseWhen(m[1]) : null;
144
- if (!wall) return null;
145
- const zone = (m[2] ?? "").trim();
333
+ }
334
+
335
+ /**
336
+ * Resolves the wall-clock components at `epochSec` in the given zone or offset.
337
+ *
338
+ * Args:
339
+ * epochSec (number): Unix epoch seconds
340
+ * zone (string): Zone identifier or numeric UTC offset
341
+ *
342
+ * Returns:
343
+ * WallTime | null: Wall-clock components in `zone`, or null if `zone` is invalid
344
+ */
345
+ function wallInZone(epochSec: number, zone: string): WallTime | null {
346
+ const z = zone.trim();
347
+ const upper = z.toUpperCase();
146
348
  try {
147
- if (!zone || zone === rule.zone) return wallToEpoch(wall, rule.zone);
148
- if (zone === "Z" || zone === "UTC" || zone === "GMT") return wallToEpoch(wall, "UTC");
149
- const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(zone);
349
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(z);
150
350
  if (offset) {
151
- const minutes = (Number(offset[2]) * 60 + Number(offset[3])) * (offset[1] === "+" ? 1 : -1);
152
- return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
351
+ const hh = Number(offset[2]);
352
+ const mm = Number(offset[3]);
353
+ if (hh > 23 || mm > 59) return null;
354
+ const minutes = (hh * 60 + mm) * (offset[1] === "+" ? 1 : -1);
355
+ const d = new Date(Math.floor(epochSec) * 1000 + minutes * 60_000);
356
+ return {
357
+ y: d.getUTCFullYear(),
358
+ mo: d.getUTCMonth() + 1,
359
+ d: d.getUTCDate(),
360
+ h: d.getUTCHours(),
361
+ mi: d.getUTCMinutes(),
362
+ s: d.getUTCSeconds(),
363
+ };
153
364
  }
154
- return wallToEpoch(wall, zone);
365
+ const targetZone = upper === "Z" || upper === "UTC" || upper === "GMT" ? "UTC" : z;
366
+ const parts = new Intl.DateTimeFormat("en-US", {
367
+ timeZone: targetZone,
368
+ hourCycle: "h23",
369
+ year: "numeric",
370
+ month: "numeric",
371
+ day: "numeric",
372
+ hour: "numeric",
373
+ minute: "numeric",
374
+ second: "numeric",
375
+ }).formatToParts(new Date(Math.floor(epochSec) * 1000));
376
+ const get = (type: string): number => Number(parts.find(p => p.type === type)?.value);
377
+ return {
378
+ y: get("year"),
379
+ mo: get("month"),
380
+ d: get("day"),
381
+ h: get("hour"),
382
+ mi: get("minute"),
383
+ s: get("second"),
384
+ };
155
385
  } catch {
156
386
  return null;
157
387
  }
158
388
  }
159
389
 
390
+ /**
391
+ * Parses an ISO-8601 timestamp with explicit `Z` or `±HH:MM` offset into unix epoch seconds.
392
+ *
393
+ * Args:
394
+ * text (string): Error or status text
395
+ *
396
+ * Returns:
397
+ * number | null: Unix epoch seconds, or null when no valid ISO-8601 timestamp is present
398
+ */
399
+ function parseIsoResetEpoch(text: string): number | null {
400
+ const m = ISO_RESET_RE.exec(text);
401
+ if (!m?.[1] || !m[2]) return null;
402
+ const wall = parseWhen(m[1]);
403
+ if (!wall) return null;
404
+ return zoneToEpoch(wall, m[2]);
405
+ }
406
+
407
+ /**
408
+ * Parses a relative reset duration (`in ~42091 min`, `in 2 hours 15 minutes`, `after 4h23m12s`,
409
+ * `after 90 seconds`) relative to `now`.
410
+ *
411
+ * Args:
412
+ * text (string): Error or status text
413
+ * now (number): Reference unix epoch seconds
414
+ *
415
+ * Returns:
416
+ * number | null: Unix epoch seconds (`floor(now) + durationSeconds`), or null when none matched
417
+ */
418
+ function parseRelativeResetEpoch(text: string, now: number): number | null {
419
+ const m = RELATIVE_RESET_RE.exec(text);
420
+ if (!m?.[1]) return null;
421
+ let totalSec = 0;
422
+ let matched = false;
423
+ for (const tok of m[1].matchAll(RELATIVE_TOKEN_RE)) {
424
+ const num = Number(tok[1]);
425
+ const unit = (tok[2] ?? "").toLowerCase();
426
+ const mult = DURATION_UNITS_SEC[unit];
427
+ if (!Number.isFinite(num) || !mult) continue;
428
+ totalSec += num * mult;
429
+ matched = true;
430
+ }
431
+ if (!matched || totalSec <= 0) return null;
432
+ return Math.floor(now) + Math.round(totalSec);
433
+ }
434
+
435
+ /**
436
+ * Parses human-readable 12h/24h reset strings with optional month/day/year and optional zone,
437
+ * defaulting to the local timezone and rolling time-only timestamps forward by one day when past `now`.
438
+ *
439
+ * Args:
440
+ * text (string): Error or status text
441
+ * now (number): Reference unix epoch seconds
442
+ *
443
+ * Returns:
444
+ * number | null: Unix epoch seconds, or null when no valid human reset timestamp is present
445
+ */
446
+ function parseHumanResetEpoch(text: string, now: number): number | null {
447
+ const m = HUMAN_RESET_RE.exec(text);
448
+ if (!m) return null;
449
+ const monthName = m[1];
450
+ const dayStr = m[2];
451
+ const yearStr = m[3];
452
+ const h12Str = m[4];
453
+ const mi12Str = m[5];
454
+ const s12Str = m[6];
455
+ const ampm = m[7];
456
+ const h24Str = m[8];
457
+ const mi24Str = m[9];
458
+ const s24Str = m[10];
459
+ const explicitZone = (m[11] ?? m[12])?.trim();
460
+
461
+ let h: number;
462
+ let mi: number;
463
+ let s: number;
464
+ if (ampm && h12Str) {
465
+ const rawH = Number(h12Str);
466
+ mi = mi12Str ? Number(mi12Str) : 0;
467
+ s = s12Str ? Number(s12Str) : 0;
468
+ if (rawH < 1 || rawH > 12 || mi > 59 || s > 59) return null;
469
+ const lower = ampm.toLowerCase();
470
+ h = lower === "am" ? (rawH === 12 ? 0 : rawH) : (rawH === 12 ? 12 : rawH + 12);
471
+ } else if (h24Str && mi24Str) {
472
+ h = Number(h24Str);
473
+ mi = Number(mi24Str);
474
+ s = s24Str ? Number(s24Str) : 0;
475
+ if (h > 23 || mi > 59 || s > 59) return null;
476
+ } else {
477
+ return null;
478
+ }
479
+
480
+ const zone = explicitZone || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
481
+ const nowWall = wallInZone(now, zone);
482
+ if (!nowWall) return null;
483
+
484
+ if (monthName && dayStr) {
485
+ const mo = HUMAN_MONTHS[monthName.toLowerCase()];
486
+ const d = Number(dayStr);
487
+ if (!mo) return null;
488
+ if (yearStr) {
489
+ return zoneToEpoch({ y: Number(yearStr), mo, d, h, mi, s }, zone);
490
+ }
491
+ const thisYear = zoneToEpoch({ y: nowWall.y, mo, d, h, mi, s }, zone);
492
+ if (thisYear !== null && now - thisYear <= 180 * 86400) return thisYear;
493
+ return zoneToEpoch({ y: nowWall.y + 1, mo, d, h, mi, s }, zone);
494
+ }
495
+
496
+ const todayEpoch = zoneToEpoch({ y: nowWall.y, mo: nowWall.mo, d: nowWall.d, h, mi, s }, zone);
497
+ if (todayEpoch === null) return null;
498
+ if (todayEpoch > now) return todayEpoch;
499
+ const nextDay = new Date(Date.UTC(nowWall.y, nowWall.mo - 1, nowWall.d + 1));
500
+ return zoneToEpoch(
501
+ { y: nextDay.getUTCFullYear(), mo: nextDay.getUTCMonth() + 1, d: nextDay.getUTCDate(), h, mi, s },
502
+ zone,
503
+ );
504
+ }
505
+
506
+ /**
507
+ * Extracts the first rate-limit reset time from provider output/error text as unix epoch seconds.
508
+ * Checks in order: configured `rule.pattern` (defaulting bare timestamps to `rule.zone`),
509
+ * ISO-8601 timestamps with explicit `Z` or `±HH:MM` offsets, relative durations (`in`/`after`),
510
+ * and human 12h/24h clock/date reset phrases (defaulting bare times to local zone with +24h rollover).
511
+ *
512
+ * Args:
513
+ * text (string): Provider output or error text
514
+ * rule ({ pattern: string; zone: string }): Configured reset pattern and default zone
515
+ * now (number): Reference unix epoch seconds for relative and time-only rollover calculations
516
+ *
517
+ * Returns:
518
+ * number | null: Parsed reset unix epoch seconds, or null when no valid reset time is found
519
+ */
520
+ export function resetEpochFromText(text: string, rule: { pattern: string; zone: string }, now: number = nowSec()): number | null {
521
+ let pattern: RegExp | null = null;
522
+ try {
523
+ pattern = new RegExp(rule.pattern);
524
+ } catch {
525
+ pattern = null;
526
+ }
527
+ if (pattern) {
528
+ const m = pattern.exec(text);
529
+ if (m) {
530
+ const wall = m[1] ? parseWhen(m[1]) : null;
531
+ if (wall) {
532
+ const zone = (m[2] ?? "").trim();
533
+ if (zone && zone !== rule.zone) return zoneToEpoch(wall, zone);
534
+ const trailing = text.slice((m.index ?? 0) + m[0].length);
535
+ const parenZone = /^\(\s*(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Z]{2,5}|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+)\s*\)/.exec(trailing)?.[1];
536
+ if (parenZone) {
537
+ const explicitEpoch = zoneToEpoch(wall, parenZone);
538
+ if (explicitEpoch !== null) return explicitEpoch;
539
+ }
540
+ return zoneToEpoch(wall, rule.zone);
541
+ }
542
+ }
543
+ }
544
+ return parseIsoResetEpoch(text) ?? parseRelativeResetEpoch(text, now) ?? parseHumanResetEpoch(text, now);
545
+ }
546
+
160
547
  /** What a harness reports for one provider. `partial` is display-only and never an out-until. */
161
548
  export interface ProviderStatus {
162
549
  provider: string;
@@ -1253,8 +1253,8 @@ export function openWaits(p: Plan, plans: Plan[], rank: Map<string, number>): nu
1253
1253
  // result, or queue-check fails the plan; entries without a date or dated before it are grandfathered.
1254
1254
  export const DONE_CLAIM_SINCE = "2026-11-01";
1255
1255
 
1256
- // "Done check" is a plan section name, not a claim.
1257
- const DONE_WORD_SRC = String.raw`(?:done(?!\s+check)|completed?|nothing left|finished)`;
1256
+ // "Done check" (also "Done-check", "Done line", "Done command") names the plan section, not a claim.
1257
+ const DONE_WORD_SRC = String.raw`(?:done(?![\s-]+(?:check|line|command)\b)|completed?|nothing left|finished)`;
1258
1258
  const NOT_DONE = /\b(?:not|never)\s+(?:done|completed?|finished)\b/i;
1259
1259
  // A reviewer's PLAN/CODE REVIEW entry critiques a plan; it claims no phase done.
1260
1260
  const REVIEW_ENTRY = /\b(?:PLAN|CODE) REVIEW:/;
@@ -99,6 +99,10 @@ export function withUnanswered(resume: string, messages: readonly OwnerMessage[]
99
99
  return un.length === 0 ? resume : `${unansweredPrompt(un)}\n\n${resume}`;
100
100
  }
101
101
 
102
+ /** Fixed line above every handoff note: the note is old memory, the system prompt and live banner are current. */
103
+ export const HANDOFF_PRECEDENCE =
104
+ "Where this note contradicts the system prompt or the live per-prompt banner (tier, push rules, limits), the system prompt wins.";
105
+
102
106
  /**
103
107
  * The first user message of the new session: header, Main's note, generated state, owner message.
104
108
  * Every `(from: \`cmd\`)` in the note is listed under "## Numbers to re-run" right after it — re-run
@@ -112,6 +116,7 @@ export function buildHandoff(p: HandoffInput): string {
112
116
  `${HANDOFF_PREFIX} ${p.previousSessionFile}. Its full history stays there; this session continues from the handoff below.`,
113
117
  "",
114
118
  "## Main's handoff note (verbatim)",
119
+ HANDOFF_PRECEDENCE,
115
120
  note,
116
121
  ...(numbers.length > 0
117
122
  ? ["", "## Numbers to re-run", "re-run these before repeating any number", ...numbers.map((c) => `- \`${c}\``)]