counterparts 0.3.52 → 0.3.53
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.
- package/CHANGELOG.md +36 -0
- package/README.md +1 -1
- package/docs/manual.md +1 -1
- package/docs/module-map.md +1 -0
- package/package.json +1 -1
- package/src/adapters/lifecycle.ts +12 -1
- package/src/adapters/mcp/server-self-tools.ts +15 -2
- package/src/adapters/mcp/server-words.ts +2 -2
- package/src/adapters/mcp/server.ts +61 -0
- package/src/adapters/mcp/tools.ts +43 -2
- package/src/core/counterpart-wake-shape.ts +793 -53
- package/src/core/counterpart.ts +37 -6
- package/src/core/dream/CONTRACT.md +3 -0
- package/src/core/dream/NOTES.md +9 -0
- package/src/core/dream/night-line.ts +11 -2
- package/src/core/dream/reflect.ts +38 -3
- package/src/core/encode/NOTES.md +1 -0
- package/src/core/encode/secrets.ts +13 -0
- package/src/core/handoff/CONTRACT.md +3 -1
- package/src/core/handoff/last-exchange.ts +24 -4
- package/src/core/owner-waits.ts +246 -0
- package/src/core/recall/INTERFACE-GAPS.md +6 -0
- package/src/core/recall/index.ts +5 -0
- package/src/core/recall/steps.ts +2 -0
- package/src/core/self/CONTRACT.md +76 -0
- package/src/core/self/NOTES.md +178 -0
- package/src/core/self/index.ts +105 -5
- package/src/core/self/set-down.ts +774 -0
- package/src/core/self/stories.ts +79 -0
- package/src/core/self/tunables.ts +134 -0
- package/src/core/self/writer.ts +57 -8
- package/src/core/store/index.ts +5 -0
- package/src/core/store/reads-memories.ts +14 -0
|
@@ -66,8 +66,13 @@ import type { Kind } from "./types.js";
|
|
|
66
66
|
import type { MemoryRow } from "./store/index.js";
|
|
67
67
|
import { TOLD_SOURCE, isTold } from "./told.js";
|
|
68
68
|
import { OWN_PLUMBING_META_KEY } from "./remember/own-plumbing.js";
|
|
69
|
-
import { happenedAlready, sinceLastNight } from "./counterpart-wake-news.js";
|
|
69
|
+
import { happenedAlready, lastNightAt, sinceLastNight } from "./counterpart-wake-news.js";
|
|
70
|
+
import { SET_DOWN_HANDLE, SET_DOWN_TOLD_KEY, contentWords, lineOnPage, nightSetDowns, preparePage } from "./self/set-down.js";
|
|
71
|
+
import type { PreparedPage } from "./self/set-down.js";
|
|
70
72
|
import type { NewsItem } from "./counterpart-wake-news.js";
|
|
73
|
+
import { NO_TERMS, noteRaised, ownerParked, raiseRecord, raisesAt, sharedWeight, termsOf, touches, waitState, weighMany } from "./owner-waits.js";
|
|
74
|
+
import type { TermWeights } from "./owner-waits.js";
|
|
75
|
+
import { hashText } from "./store/prose.js";
|
|
71
76
|
|
|
72
77
|
/** The meta key that sets the shape for one store (`self/tunables.ts#WAKE_SHAPE_KEY`, where a new install's state can read it too). */
|
|
73
78
|
export { WAKE_SHAPE_KEY } from "./self/tunables.js";
|
|
@@ -101,6 +106,12 @@ interface Sec {
|
|
|
101
106
|
readonly handoffs?: readonly { readonly h: Handoff; readonly bytes: number }[];
|
|
102
107
|
readonly saidBytes?: number;
|
|
103
108
|
readonly chapters?: number;
|
|
109
|
+
/** The night whose set-downs this section told (PG1), so the delivery records them told once. */
|
|
110
|
+
readonly setDownNight?: string;
|
|
111
|
+
/** The least the one pass takes it down to: its door alone, when what is behind it must be said (WK3, overdue). */
|
|
112
|
+
readonly floor?: number;
|
|
113
|
+
/** The item waiting on the owner this section said (SO1 step 4), recorded as raised once the wake is delivered. */
|
|
114
|
+
readonly owed?: Owed;
|
|
104
115
|
}
|
|
105
116
|
type Budgets = Record<SectionKey, number>;
|
|
106
117
|
|
|
@@ -307,6 +318,8 @@ export function sinceHere(
|
|
|
307
318
|
readonly skip?: ReadonlySet<string>;
|
|
308
319
|
/** Every folder that counts as here: a joined folder's work is this one's (`PROJECTS_TRAVEL`). Absent: `scope` alone. */
|
|
309
320
|
readonly folders?: readonly string[];
|
|
321
|
+
/** Newer handoffs that sank below the lead (WK3): their own closing batches echo them, as the lead's does. */
|
|
322
|
+
readonly closing?: readonly { readonly session: string; readonly at: number }[];
|
|
310
323
|
},
|
|
311
324
|
): { items: (SinceItem & { readonly rank: number })[]; older: number; rawLater: number; skippedInLead: number } {
|
|
312
325
|
const store = cp.store;
|
|
@@ -336,6 +349,7 @@ export function sinceHere(
|
|
|
336
349
|
// A closing batch from the handoff's own session echoes its lead.
|
|
337
350
|
const at = r.created_at ?? 0;
|
|
338
351
|
if (opts.handoffSession !== null && r.origin_session === opts.handoffSession && opts.handoffAt !== null && at - opts.handoffAt <= SHAPE.SINCE_OWN_SESSION_MS) continue;
|
|
352
|
+
if (opts.closing?.some((h) => r.origin_session === h.session && at >= h.at && at - h.at <= SHAPE.SINCE_OWN_SESSION_MS) === true) continue;
|
|
339
353
|
// Since means changed, not written: a stated day before the handoff's is an older note.
|
|
340
354
|
if (handoffDay !== null) {
|
|
341
355
|
const stated = [r.occurred_on, r.happened_on, r.event_date, r.learned_on]
|
|
@@ -425,14 +439,24 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
425
439
|
if (room <= 0) return null;
|
|
426
440
|
|
|
427
441
|
// ── the facts, once per delivery: a read that fails costs its section, never the wake ──
|
|
428
|
-
|
|
442
|
+
// A joined folder is here (`PROJECTS_TRAVEL`): its work is "Since, here", its sessions "Open here now".
|
|
443
|
+
const hereFolders: readonly string[] = gate === null ? [scope] : [...gate.ours];
|
|
444
|
+
// The handoffs in the order the wake tells them (WK3): a stale wait on the
|
|
445
|
+
// owner sinks, and a week-old one nothing refers to isn't listed.
|
|
446
|
+
const sunkIds = new Set<string>();
|
|
447
|
+
const hs: readonly Handoff[] = scope.length === 0 ? [] : safe(() => handoffsTold(cp, cp.handoffs.readAll(scope), hereFolders, now, reader, sunkIds), []);
|
|
429
448
|
const newest = hs[0];
|
|
430
449
|
const newestAt = newest === undefined ? null : safe(() => cp.handoffs.writtenAt(newest), null);
|
|
431
450
|
const chaptersHere: readonly ChapterHere[] = scope.length === 0 ? [] : safe(() => cp.chaptersHereFor(scope, null, cp["chaptersInWindow"](day)).map((f) => f.chapter), []);
|
|
432
451
|
const since = newest === undefined ? sinceY : (newestAt ?? startOfLocalDay(newest.writtenOn, zone));
|
|
433
452
|
const lead5 = newest === undefined ? "" : leadOf(newest.body, SHAPE.LEAD_LINES, SHAPE.LEAD_BYTES).lines.join(" ");
|
|
434
|
-
// A
|
|
435
|
-
const
|
|
453
|
+
// A newer one that sank below this lead (WK3) is said, so "newest" is never untrue.
|
|
454
|
+
const sunkNewer = newest === undefined || newestAt === null ? 0 : hs.filter((h) => safe(() => cp.handoffs.writtenAt(h) ?? 0, 0) > newestAt).length;
|
|
455
|
+
const sunkClosing = newestAt === null ? [] : hs.flatMap((h) => {
|
|
456
|
+
const t = safe(() => cp.handoffs.writtenAt(h), null);
|
|
457
|
+
return h.session === null || t === null || t <= newestAt ? [] : [{ session: h.session, at: t }];
|
|
458
|
+
});
|
|
459
|
+
const amongWords = hs.length <= 1 ? "" : sunkNewer > 0 ? `; ${plural(sunkNewer, "newer one")} waiting on an answer, below` : `; newest of ${String(hs.length)}`;
|
|
436
460
|
const cues = safe(() => readCues(cp, at, here), [] as Cue[]);
|
|
437
461
|
const cueIds = new Set(cues.map((c) => c.id));
|
|
438
462
|
// SHOWN EARLIER TODAY (RF1, 2026-11-04): a plain reminder already told today
|
|
@@ -458,10 +482,25 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
458
482
|
if (session === null || !seenToday.has(session)) return false;
|
|
459
483
|
return c.personal || ourFolders.has(seenToday.get(session) ?? "");
|
|
460
484
|
};
|
|
461
|
-
|
|
462
|
-
|
|
485
|
+
//
|
|
486
|
+
// IN THIS SESSION'S CONTEXT, OR NOT SAID (WK3, 2026-11-09): "shown earlier"
|
|
487
|
+
// pointed at nothing four mornings running: the telling was in another
|
|
488
|
+
// session, which this one's model never saw. So only a telling in THIS
|
|
489
|
+
// session folds (a resume, whose model has the earlier wake above it); a
|
|
490
|
+
// telling in another session, or in this one before a compaction or a /clear
|
|
491
|
+
// emptied its context, shows the item again by title and id (`RETOLD_SHOWN`,
|
|
492
|
+
// the rest counted behind the door), never its whole body twice to the person.
|
|
493
|
+
// Only a start the host names as one that keeps the context (review of #792): no
|
|
494
|
+
// source is unknown, and unknown doesn't fold.
|
|
495
|
+
const contextKept = here?.source === "startup" || here?.source === "resume";
|
|
496
|
+
const toldToday = new Set(cues.filter((c) => c.plain && saysHere(c) && safe(() => cp.prospective.plainToldOn(c.id, at, byToday(c)), false)).map((c) => c.id));
|
|
497
|
+
const shownEarlier = new Set(
|
|
498
|
+
!contextKept || reader === null || !seenToday.has(reader) ? [] : cues.filter((c) => toldToday.has(c.id) && safe(() => cp.prospective.plainToldOn(c.id, at, (s) => s === reader), false)).map((c) => c.id),
|
|
499
|
+
);
|
|
500
|
+
const retold = new Set([...toldToday].filter((id) => !shownEarlier.has(id)));
|
|
501
|
+
const later = scope.length === 0 ? null : safe(() => sinceHere(cp, scope, since, { handoffSession: newest?.session ?? null, handoffAt: newestAt, reader, lead: lead5, chapters: chaptersHere, skip: cueIds, folders: hereFolders, closing: sunkClosing }), null);
|
|
463
502
|
const sinceAged = (later?.items ?? []).map((s) => ({ ...s, age: ageOf(s.chapter ? s.at : Math.min(s.at, factAt(s.id))) }));
|
|
464
|
-
const open = safe(() => cp.self.stillOpen(day, cp["threadReader"](here?.scope, here?.exportsFrom)), { items: [], parked: 0 });
|
|
503
|
+
const open = safe(() => cp.self.stillOpen(day, cp["threadReader"](here?.scope, here?.exportsFrom), ownerParked(store, day)), { items: [], parked: 0 });
|
|
465
504
|
const folders = ourFolders;
|
|
466
505
|
const rule = { craftTravels: cp.self.tunables.PROJECTS_TRAVEL, craftSince: craftSince(store) };
|
|
467
506
|
const openRows = open.items
|
|
@@ -472,6 +511,30 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
472
511
|
return { i, r, here: place === "here", at: Math.min(factAt(i.id), r?.created_at ?? Infinity) };
|
|
473
512
|
})
|
|
474
513
|
.sort((a, b) => Number(b.here) - Number(a.here) || b.at - a.at || (a.i.id < b.i.id ? -1 : 1));
|
|
514
|
+
// WAITING ON THE OWNER (SO1 step 4, revised; Mike 11-07): an `asked` item is
|
|
515
|
+
// not one of Still open's lines any more (it was in every wake, never parked).
|
|
516
|
+
// At most one item that waits on the owner is said per wake, the most relevant
|
|
517
|
+
// to this folder's week that its backoff lets through (`owner-waits.ts`), and
|
|
518
|
+
// only in a session someone attends; a sunk handoff (WK3) is a candidate too.
|
|
519
|
+
const attended = reader !== null && !headless.has(reader) && !cp.observer;
|
|
520
|
+
const owed = !attended
|
|
521
|
+
? null
|
|
522
|
+
: safe(
|
|
523
|
+
() =>
|
|
524
|
+
owedOne(cp, {
|
|
525
|
+
day,
|
|
526
|
+
now,
|
|
527
|
+
rows: openRows.filter((x) => x.r?.status === "asked" && !cueIds.has(x.i.id)).map((x) => ({ id: x.i.id, row: x.r as MemoryRow, settles: x.i.settlesWhen ?? null, at: x.at, here: x.here })),
|
|
528
|
+
handoffs: joinless(
|
|
529
|
+
cp,
|
|
530
|
+
hs.filter((h, i) => i > 0 && sunkIds.has(h.id)),
|
|
531
|
+
openRows.filter((x) => x.r?.status === "asked").map((x) => ({ id: x.i.id, text: `${x.r === undefined ? x.i.title : titleOfRow(x.r)} ${x.i.settlesWhen ?? ""}` })),
|
|
532
|
+
),
|
|
533
|
+
lead: lead5,
|
|
534
|
+
folders: hereFolders,
|
|
535
|
+
}),
|
|
536
|
+
null,
|
|
537
|
+
);
|
|
475
538
|
const summary = cp.self.tunables.YESTERDAY_FROM_SUMMARY ? safe(() => cp["daySummaryShown"](yest, here), null) : null;
|
|
476
539
|
const yestHere = scope.length === 0 ? [] : safe(() => chaptersOn(store, yest, { fromDay: Math.max(0, day - LAST_HERE_LIFE_DAYS) }).filter((c) => norm(c.scope ?? "") === scope), []);
|
|
477
540
|
const elsewhere = safe(() => elsewhereFacts(cp, gate, sessions, sinceY, now, reader, factAt), { list: [] as ElsewhereRow[], quiet: [] as string[] });
|
|
@@ -491,6 +554,13 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
491
554
|
// "Last night" — only items this folder's Still open would carry (its own,
|
|
492
555
|
// a joined folder's, a personal one), never another folder's work.
|
|
493
556
|
const closedLine = safe(() => nightClosedLine(cp, day, folders, rule), null);
|
|
557
|
+
// WHAT THE PAGE SET DOWN LAST NIGHT (PG1, 2026-11-09): once, on the
|
|
558
|
+
// morning after, by line; never a line on the page now or in the night's
|
|
559
|
+
// own words (WK3: a moment told once per wake).
|
|
560
|
+
// ONE TELLING OF A MOMENT (WK3): the night's own line, less what the page or
|
|
561
|
+
// day's end already says in this wake, and a clause the second morning running.
|
|
562
|
+
const ownLine = night === null ? null : safe(() => ownToldOnce(cp, night, [cp.self.page()?.body ?? "", summary ?? ""]), null);
|
|
563
|
+
const setDown = safe(() => setDownWakeLine(cp, now, ownLine), null);
|
|
494
564
|
const installed = here?.installed ?? null;
|
|
495
565
|
const news = safe(() => sinceLastNight(cp, at, here, { ours: new Set(hereFolders), skip: cueIds }), { items: [] as NewsItem[], since: 0, night: false });
|
|
496
566
|
|
|
@@ -525,7 +595,8 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
525
595
|
const leadBytes = spareOn.has("folder") ? SHAPE.LEAD_BYTES_SPARE : SHAPE.LEAD_BYTES;
|
|
526
596
|
const sinceLines = sinceAged.filter((s) => !claim.has(s.id));
|
|
527
597
|
const tail = here?.sessions === undefined ? null : openHereLine(liveHere, at, zone);
|
|
528
|
-
|
|
598
|
+
// A sunk handoff said as Still open's ask isn't also its pointer line here (SO1 step 4: shown once).
|
|
599
|
+
const olderPick = pickOlder(owed?.kind === "handoff" ? hs.filter((h) => h.id !== owed.id) : hs);
|
|
529
600
|
const build = (n: { lead: number; since: number; older: number; said: boolean }): { lines: string[]; leadBytes: number } => {
|
|
530
601
|
const out = ["Where this folder stands:"];
|
|
531
602
|
let leadSize = 0;
|
|
@@ -533,7 +604,7 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
533
604
|
if (newest === undefined) out.push("No handoff here. Leave one with session_end's handoff field when you stop.");
|
|
534
605
|
else if (stepDown) {
|
|
535
606
|
const seat = seatOf(newest.body) ?? `session ${shortSession(newest.session)}`;
|
|
536
|
-
stepped = `Last handoff, ${seat}, ${monthDay(newest.writtenOn)} (${ageOf(newestAt ?? startOfLocalDay(newest.writtenOn, zone))} old; ${plural(sinceSessions, "session")} here since${
|
|
607
|
+
stepped = `Last handoff, ${seat}, ${monthDay(newest.writtenOn)} (${ageOf(newestAt ?? startOfLocalDay(newest.writtenOn, zone))} old; ${plural(sinceSessions, "session")} here since${amongWords}): recall ${newest.id}`;
|
|
537
608
|
leadSize = byteLength(`${stepped}\n`);
|
|
538
609
|
} else {
|
|
539
610
|
const lead = leadOf(newest.body, n.lead, leadBytes);
|
|
@@ -541,7 +612,7 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
541
612
|
const when = `${monthDay(newest.writtenOn)}${newestAt === null ? "" : ` ${localStamp(newestAt, zone).split(" ")[1] ?? ""}`}`;
|
|
542
613
|
const written = newest.build ?? (newest.session !== null ? safe(() => here?.openedWith?.(newest.session as string) ?? null, null) : null);
|
|
543
614
|
const delta = written !== null && installed !== null && versionOlder(written, installed) ? `; ${written} then, ${installed} now` : "";
|
|
544
|
-
const head = `Handoff, ${seat}, ${when} (${ageOf(newestAt ?? startOfLocalDay(newest.writtenOn, zone))} old${delta}${
|
|
615
|
+
const head = `Handoff, ${seat}, ${when} (${ageOf(newestAt ?? startOfLocalDay(newest.writtenOn, zone))} old${delta}${amongWords}). ${lead.cut ? "whole: " : ""}recall ${newest.id}`;
|
|
545
616
|
out.push(head, ...lead.lines.map((l) => ` ${l}`));
|
|
546
617
|
leadSize = byteLength(`${head}\n`) + lead.lines.reduce((x, l) => x + byteLength(` ${l}\n`), 0);
|
|
547
618
|
}
|
|
@@ -613,10 +684,11 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
613
684
|
if (total === 0) return { text: "", ids: [], items: 0 };
|
|
614
685
|
const render = (k: number): string[] => {
|
|
615
686
|
const out = ["Elsewhere:"];
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
687
|
+
// EVERY LINE SAYS WHEN AND WHAT (WK3): its own age on each line, and a
|
|
688
|
+
// live folder with nothing written says since when and that it's quiet.
|
|
689
|
+
for (const e of list.slice(0, k)) {
|
|
690
|
+
if (e.title === null) out.push(`- ${e.place} (live): open since ${clockWords(e.since, at, zone)}, nothing written there since yesterday`);
|
|
691
|
+
else out.push(`- ${e.place}${e.live ? " (live)" : ""}: ${e.title} (${ageOf(e.fact)})`);
|
|
620
692
|
}
|
|
621
693
|
const rest = total - k;
|
|
622
694
|
if (rest > 0) out.push(`+${plural(rest, "more folder")}; recall "${ELSEWHERE_HANDLE}"`);
|
|
@@ -634,18 +706,23 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
634
706
|
// A plain reminder too (SO1 step 3, 2026-11-07): another folder's work is said in its own folder, not here; a personal one (me, us, owner) is `mine` everywhere.
|
|
635
707
|
const todayAll = live.filter((c) => c.today && saysHere(c));
|
|
636
708
|
const ranked = [...todayAll].sort(dueOrder);
|
|
637
|
-
const plain = ranked.filter((c) => c.plain && !shownEarlier.has(c.id));
|
|
709
|
+
const plain = ranked.filter((c) => c.plain && !shownEarlier.has(c.id) && !retold.has(c.id));
|
|
710
|
+
const again = ranked.filter((c) => retold.has(c.id));
|
|
638
711
|
const folded = live.filter((c) => shownEarlier.has(c.id)).length;
|
|
639
712
|
const rest = ranked.filter((c) => !c.plain);
|
|
640
713
|
const overdue = live.filter((c) => c.past && c.mine).sort((x, y) => String(y.due).localeCompare(String(x.due)));
|
|
641
714
|
const laterAll = live.filter((c) => !c.today && !c.past && c.mine).sort((x, y) => String(x.due ?? UNDATED_LAST).localeCompare(String(y.due ?? UNDATED_LAST)));
|
|
642
715
|
const other = live.filter((c) => !saysHere(c));
|
|
643
716
|
const laterCap = spareOn.has("coming") ? SHAPE.LATER_SHOWN_SPARE : SHAPE.LATER_SHOWN;
|
|
644
|
-
const
|
|
717
|
+
const settlesWords = (c: Cue): string => (c.settles === null ? "" : ` · settles when ${flatten(c.settles)}`);
|
|
718
|
+
const dueLine = (c: Cue): string => `- Due today · ${c.plain ? c.body : c.title}${settlesWords(c)} [${c.id}]`;
|
|
719
|
+
// Told in another session today: its title, not its whole body again (WK3).
|
|
720
|
+
const againLine = (c: Cue): string => `- Due today · ${c.title}${settlesWords(c)} [${c.id}]`;
|
|
645
721
|
const overdueLine = (c: Cue): string => `- ${c.due === null ? "Overdue" : `${plural(Math.max(1, daysBetween(c.due, at)), "day")} overdue`} · ${c.title} [${c.id}]`;
|
|
646
722
|
const laterLine = (c: Cue): string => `- ${c.due === null ? "Soon" : monthDay(c.due)}${c.every === null ? "" : ` (${c.every})`} · ${c.title} [${c.id}]`;
|
|
647
723
|
const order: { c: Cue; line: string }[] = [
|
|
648
724
|
...plain.map((c) => ({ c, line: dueLine(c) })),
|
|
725
|
+
...again.slice(0, SHAPE.RETOLD_SHOWN).map((c) => ({ c, line: againLine(c) })),
|
|
649
726
|
...rest.slice(0, SHAPE.DUE_TODAY_SHOWN).map((c) => ({ c, line: dueLine(c) })),
|
|
650
727
|
...overdue.slice(0, SHAPE.OVERDUE_SHOWN).map((c) => ({ c, line: overdueLine(c) })),
|
|
651
728
|
...laterAll.slice(0, laterCap).map((c) => ({ c, line: laterLine(c) })),
|
|
@@ -655,14 +732,29 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
655
732
|
const otherPlain = other.filter((c) => c.plain && c.today);
|
|
656
733
|
const among = [here?.scope ?? "", ...otherPlain.flatMap((c) => (c.folder === null ? [] : [c.folder]))];
|
|
657
734
|
const short = (t: string): string => (t.length <= PLAIN_OTHER_TITLE_CHARS ? t : `${t.slice(0, PLAIN_OTHER_TITLE_CHARS - 1).trimEnd()}…`);
|
|
658
|
-
const
|
|
659
|
-
const
|
|
735
|
+
const namedParts = otherPlain.length === 0 ? [] : [...otherPlain.slice(0, PLAIN_OTHER_NAMED).map((c) => `${c.folder === null ? "elsewhere" : placeWords(c.folder, among)}: ${short(flatten(c.title))}`), ...(otherPlain.length > PLAIN_OTHER_NAMED ? [`and ${String(otherPlain.length - PLAIN_OTHER_NAMED)} more`] : [])];
|
|
736
|
+
const namedOther = namedParts.join("; ");
|
|
737
|
+
// Overdue is said in other folders' count too (WK3): a count, never their lines (SO1 step 3).
|
|
738
|
+
const oldestOf = (cs: readonly Cue[]): string | null => cs.reduce<string | null>((o, c) => (c.due !== null && isDay(c.due) && (o === null || c.due < o) ? c.due : o), null);
|
|
739
|
+
const otherLate = other.filter((c) => c.past);
|
|
740
|
+
const otherOldest = oldestOf(otherLate);
|
|
741
|
+
const otherLateWords = otherLate.length === 0 ? "" : `${String(otherLate.length)} overdue${otherOldest === null ? "" : `, oldest ${monthDay(otherOldest)}`}`;
|
|
742
|
+
const otherWords = (named: boolean): string => {
|
|
743
|
+
const inside = [otherLateWords, ...(named ? namedParts : [])].filter((x) => x.length > 0);
|
|
744
|
+
return `${String(other.length)} in other folders${inside.length === 0 ? "" : ` (${inside.join("; ")})`}`;
|
|
745
|
+
};
|
|
746
|
+
const render = (shown: readonly { c: Cue; line: string }[], named = false, terse = false): string[] => {
|
|
660
747
|
const ids = new Set(shown.map((s) => s.c.id));
|
|
661
748
|
const hiddenToday = todayAll.filter((c) => !ids.has(c.id) && !shownEarlier.has(c.id)).length;
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
const
|
|
749
|
+
// OVERDUE IS SAID, NEVER FOLDED INTO "MORE HERE" (WK3): its own count, with
|
|
750
|
+
// the oldest date, so eleven overdue items can't read as a few later ones.
|
|
751
|
+
const lateHidden = overdue.filter((c) => !ids.has(c.id));
|
|
752
|
+
const oldest = oldestOf(lateHidden);
|
|
753
|
+
const lateWords = lateHidden.length === 0 ? "" : `${String(lateHidden.length)}${lateHidden.length < overdue.length ? " more" : ""} overdue${oldest === null || terse ? "" : ` (oldest ${monthDay(oldest)})`}`;
|
|
754
|
+
const hereMore = laterAll.filter((c) => !ids.has(c.id)).length;
|
|
755
|
+
const more = [hiddenToday > 0 ? `${String(hiddenToday)} more due today` : "", lateWords, hereMore > 0 ? `${String(hereMore)} more here` : "", other.length > 0 ? (terse ? `${String(other.length)} in other folders` : otherWords(named)) : ""].filter((x) => x.length > 0).join(", ");
|
|
756
|
+
// The fold is its own clause: "2 due today, shown earlier in this session; 1 more due today; recall …".
|
|
757
|
+
const words = [folded > 0 ? `${String(folded)} due today, shown earlier in this session` : "", more].filter((x) => x.length > 0).join("; ");
|
|
666
758
|
// Nothing to list and nothing behind the door: no section (WF1), not "Nothing dated."
|
|
667
759
|
if (shown.length === 0 && words.length === 0) return [];
|
|
668
760
|
const out = ["Coming up:", ...shown.map((s) => s.line)];
|
|
@@ -671,18 +763,37 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
671
763
|
};
|
|
672
764
|
// Whole lines in order; a line that doesn't fit goes behind the door, and a
|
|
673
765
|
// later one may still fit: a long plain reminder doesn't hide what's after it.
|
|
766
|
+
// A line due today comes before the overdue words (review of #792): short of
|
|
767
|
+
// room, the door drops its dates and other folders' overdue count to keep it.
|
|
768
|
+
const dueToday = new Set([...plain, ...again, ...rest].map((c) => c.id));
|
|
674
769
|
const shown: { c: Cue; line: string }[] = [];
|
|
675
|
-
|
|
770
|
+
let terse = false;
|
|
771
|
+
for (const o of order) {
|
|
772
|
+
if (byteLength(blockOf(render([...shown, o], false, terse))) <= b) shown.push(o);
|
|
773
|
+
else if (!terse && dueToday.has(o.c.id) && byteLength(blockOf(render([...shown, o], false, true))) <= b) {
|
|
774
|
+
terse = true;
|
|
775
|
+
shown.push(o);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
676
778
|
// The names ride only in room the lines didn't need: never a line for them.
|
|
677
779
|
const withNames = blockOf(render(shown, true));
|
|
678
|
-
const text = namedOther !== "" && byteLength(withNames) <= b ? withNames : blockOf(render(shown));
|
|
679
|
-
|
|
680
|
-
|
|
780
|
+
const text = !terse && namedOther !== "" && byteLength(withNames) <= b ? withNames : blockOf(render(shown, false, terse));
|
|
781
|
+
// Its door alone, what the one pass keeps when an overdue item is behind it (WK3: never silent).
|
|
782
|
+
// A plain reminder due today first, with the door at its tersest; else the door
|
|
783
|
+
// alone when something overdue is behind it (review of #792: never the other way).
|
|
784
|
+
const plainFirst = order.filter((o) => o.c.plain && dueToday.has(o.c.id));
|
|
785
|
+
const floor = plainFirst.length > 0 ? byteLength(blockOf(render(plainFirst, false, true))) : overdue.length + otherLate.length === 0 ? 0 : byteLength(blockOf(render([])));
|
|
786
|
+
if (byteLength(text) > b) return { text: "", ids: [], items: 0, floor };
|
|
787
|
+
return { text, ids: shown.map((s) => s.c.id), items: shown.length, lined: shown.map((s) => s.c.id), floor };
|
|
681
788
|
};
|
|
682
789
|
|
|
683
790
|
const openSec = (b: number, claim: ReadonlySet<string>): Sec => {
|
|
684
791
|
const cap = spareOn.has("open") ? SHAPE.OPEN_SHOWN_SPARE : SHAPE.OPEN_SHOWN;
|
|
685
|
-
|
|
792
|
+
// What waits on the owner is said once, as `owed`, or not at all (SO1 step 4).
|
|
793
|
+
const carried = openRows.filter((x) => !claim.has(x.i.id) && !cueIds.has(x.i.id) && x.r?.status !== "asked");
|
|
794
|
+
// A memory another section said is said; a sunk handoff's pointer line above isn't the ask, so it is still said here.
|
|
795
|
+
const owe = owed !== null && (owed.kind === "handoff" || !claim.has(owed.id)) ? owed : null;
|
|
796
|
+
const oweLines = owe === null ? [] : aged([{ text: owe.text, age: ageOf(owe.at), tail: owe.tail }]);
|
|
686
797
|
const lineOf = (x: (typeof carried)[number]): { text: string; age: string; tail: string } => ({
|
|
687
798
|
text: `- ${x.r === undefined ? x.i.title : titleOfRow(x.r)}`,
|
|
688
799
|
age: ageOf(x.at),
|
|
@@ -692,15 +803,17 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
692
803
|
const more = carried.length - k;
|
|
693
804
|
const door = more > 0 || open.parked > 0 ? `(${[more > 0 ? `${String(more)} more open` : "", open.parked > 0 ? `${String(open.parked)} parked` : ""].filter((w) => w.length > 0).join(", ")}; recall "still open")` : "";
|
|
694
805
|
// Nothing open and nothing parked: no section (WF1), not "Nothing open."
|
|
695
|
-
if (k === 0 && door === "") return [];
|
|
696
|
-
return ["Still open:", ...aged(carried.slice(0, k).map(lineOf)), ...(door === "" ? [] : [door])];
|
|
806
|
+
if (k === 0 && door === "" && oweLines.length === 0) return [];
|
|
807
|
+
return ["Still open:", ...oweLines, ...aged(carried.slice(0, k).map(lineOf)), ...(door === "" ? [] : [door])];
|
|
697
808
|
};
|
|
698
809
|
let k = Math.min(cap, carried.length);
|
|
699
810
|
while (k > 0 && byteLength(blockOf(render(k))) > b) k -= 1;
|
|
700
811
|
const text = blockOf(render(k));
|
|
701
812
|
if (byteLength(text) > b) return { text: "", ids: [], items: 0 };
|
|
702
|
-
const ids = carried.slice(0, k).map((x) => x.i.id);
|
|
703
|
-
|
|
813
|
+
const ids = [...(owe === null ? [] : [owe.id]), ...carried.slice(0, k).map((x) => x.i.id)];
|
|
814
|
+
// Open threads and the lookup ledger hold memory ids: a sunk handoff's id is claimed, not lined.
|
|
815
|
+
const lined = owe?.kind === "handoff" ? ids.filter((id) => id !== owe.id) : ids;
|
|
816
|
+
return { text, ids, items: ids.length, lined, ...(owe === null ? {} : { owed: owe }) };
|
|
704
817
|
};
|
|
705
818
|
|
|
706
819
|
const yesterdaySec = (b: number, claim: ReadonlySet<string>): Sec => {
|
|
@@ -721,23 +834,39 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
721
834
|
return { text: blockOf(render(k)), ids: list.slice(0, k).map((c) => c.id), items: k };
|
|
722
835
|
};
|
|
723
836
|
|
|
724
|
-
const nightSec = (b: number): Sec => {
|
|
837
|
+
const nightSec = (b: number, claim: ReadonlySet<string>): Sec => {
|
|
725
838
|
const closed = closedLine === null ? [] : [closedLine];
|
|
839
|
+
const down = setDown === null ? [] : [setDown.line];
|
|
840
|
+
// THE MOMENT WAS TOLD: CARRY SOMETHING ELSE FORWARD (review of #792). The
|
|
841
|
+
// night's own line said only what the wake already told, so the closing
|
|
842
|
+
// line is an open thread no section above showed, newest first.
|
|
843
|
+
const forward = ownLine !== null || night?.own === null || night === null ? null : (openRows.find((x) => !claim.has(x.i.id) && !cueIds.has(x.i.id)) ?? null);
|
|
844
|
+
const forwardLine = forward === null ? null : `Carried forward: ${forward.r === undefined ? forward.i.title : titleOfRow(forward.r)} [${forward.i.id}]`;
|
|
845
|
+
const as = (f: readonly string[]): Sec => {
|
|
846
|
+
const text = blockOf([...f]);
|
|
847
|
+
const fwd = forward !== null && forwardLine !== null && f.includes(forwardLine) ? [forward.i.id] : [];
|
|
848
|
+
return setDown !== null && f.includes(setDown.line) ? { text, ids: [...setDown.ids, ...fwd], items: fwd.length, setDownNight: setDown.night } : { text, ids: fwd, items: fwd.length, ...(fwd.length === 0 ? {} : { lined: fwd }) };
|
|
849
|
+
};
|
|
726
850
|
if (night === null) {
|
|
727
|
-
|
|
728
|
-
|
|
851
|
+
// Widest first: what it closed and what it set down; then each alone.
|
|
852
|
+
const forms = [[...closed, ...down], closed, down].filter((f) => f.length > 0);
|
|
853
|
+
for (const f of forms) if (byteLength(blockOf(f)) <= b) return as(f);
|
|
854
|
+
return { text: "", ids: [], items: 0 };
|
|
729
855
|
}
|
|
730
|
-
// Widest first: the line, the night's own words, what it closed
|
|
856
|
+
// Widest first: the line, the night's own words, what it closed, what it
|
|
857
|
+
// set down. Short of room, what it set down goes first (recall "set down"
|
|
858
|
+
// holds it), then what it closed; the night's own words, which have no
|
|
859
|
+
// door, are kept longest; then the line alone.
|
|
860
|
+
const own = ownLine !== null ? [ownLine] : forwardLine === null ? [] : [forwardLine];
|
|
731
861
|
const forms = [
|
|
732
|
-
|
|
733
|
-
...(
|
|
734
|
-
...(
|
|
862
|
+
[night.line, ...own, ...closed, ...down],
|
|
863
|
+
...(own.length === 0 || down.length === 0 ? [] : [[night.line, ...own, ...closed]]),
|
|
864
|
+
...(own.length === 0 || closed.length === 0 ? [] : [[night.line, ...own, ...down], [night.line, ...own]]),
|
|
865
|
+
...(closed.length + down.length === 0 ? [] : [[night.line, ...closed, ...down]]),
|
|
866
|
+
...(down.length === 0 ? [] : [[night.line, ...closed]]),
|
|
735
867
|
[night.line],
|
|
736
868
|
];
|
|
737
|
-
for (const f of forms)
|
|
738
|
-
const text = blockOf(f);
|
|
739
|
-
if (byteLength(text) <= b) return { text, ids: [], items: 0 };
|
|
740
|
-
}
|
|
869
|
+
for (const f of forms) if (byteLength(blockOf(f)) <= b) return as(f);
|
|
741
870
|
return { text: "", ids: [], items: 0 };
|
|
742
871
|
};
|
|
743
872
|
|
|
@@ -748,7 +877,7 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
748
877
|
coming: comingSec,
|
|
749
878
|
open: openSec,
|
|
750
879
|
yesterday: yesterdaySec,
|
|
751
|
-
night:
|
|
880
|
+
night: nightSec,
|
|
752
881
|
};
|
|
753
882
|
|
|
754
883
|
/** Sections in order, claiming ids into one set. A plain reminder due today is Coming up's whatever else could name it. */
|
|
@@ -766,7 +895,8 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
766
895
|
const used = (s: Record<SectionKey, Sec>): number => ORDER.reduce((n, k) => n + byteLength(s[k].text), 0);
|
|
767
896
|
const left = room - byteLength(self.text);
|
|
768
897
|
|
|
769
|
-
|
|
898
|
+
// A plain reminder's room: its whole body, or its title when told in another session (WK3).
|
|
899
|
+
const plainBytes = cues.filter((c) => c.plain && saysHere(c) && !shownEarlier.has(c.id)).reduce((n, c) => n + byteLength(`- Due today · ${retold.has(c.id) ? c.title : c.body}${c.settles === null ? "" : ` · settles when ${flatten(c.settles)}`} [${c.id}]\n`), byteLength("Coming up:\n\n"));
|
|
770
900
|
const summaryBytes = summary === null ? 0 : byteLength(`Yesterday, in day's end's words: ${flatten(summary)}\n\n`);
|
|
771
901
|
const budgets: Budgets = { ...SHAPE.ROOM, coming: Math.max(SHAPE.ROOM.coming, plainBytes + SHAPE.COMING_PAST_PLAIN), yesterday: Math.max(SHAPE.ROOM.yesterday, summaryBytes) };
|
|
772
902
|
let sec = compose(budgets);
|
|
@@ -777,7 +907,7 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
777
907
|
for (const key of GIVE) {
|
|
778
908
|
const over = used(sec) - left;
|
|
779
909
|
if (over <= 0) break;
|
|
780
|
-
const floor = pass === 0 && key === "coming" ? Math.min(plainBytes + SHAPE.COMING_PAST_PLAIN, byteLength(sec[key].text)) : 0;
|
|
910
|
+
const floor = pass === 0 && key === "coming" ? Math.min(Math.max(plainBytes + SHAPE.COMING_PAST_PLAIN, sec[key].floor ?? 0), byteLength(sec[key].text)) : Math.min(sec[key].floor ?? 0, byteLength(sec[key].text));
|
|
781
911
|
budgets[key] = Math.max(floor, byteLength(sec[key].text) - over);
|
|
782
912
|
sec = compose(budgets);
|
|
783
913
|
}
|
|
@@ -817,10 +947,11 @@ export function shapedDelivery(cp: Counterpart, delivery: WakeDelivery, here: Wa
|
|
|
817
947
|
closingBytes: byteLength(closing(elements, String(stated), self.rung !== null)),
|
|
818
948
|
rung: self.rung,
|
|
819
949
|
lined: [...self.lined, ...ORDER.flatMap((k) => sec[k].lined ?? [])],
|
|
820
|
-
threads: sec.open.
|
|
950
|
+
threads: sec.open.lined ?? [],
|
|
821
951
|
sec,
|
|
822
952
|
live: hs.length,
|
|
823
953
|
since: later?.items.length ?? 0,
|
|
954
|
+
hs,
|
|
824
955
|
});
|
|
825
956
|
}
|
|
826
957
|
|
|
@@ -840,6 +971,7 @@ function finish(
|
|
|
840
971
|
readonly sec: Record<SectionKey, Sec>;
|
|
841
972
|
readonly live: number;
|
|
842
973
|
readonly since: number;
|
|
974
|
+
readonly hs: readonly Handoff[];
|
|
843
975
|
},
|
|
844
976
|
): ShapedWake | null {
|
|
845
977
|
let result = cp.self.wake(delivery, w.body);
|
|
@@ -859,8 +991,27 @@ function finish(
|
|
|
859
991
|
w.sec.folder.handoffs?.forEach((s, i) => {
|
|
860
992
|
cp.handoffs.noteShown(s.h, { bytes: s.bytes, session: reader, among: w.live, ...(i === 0 ? { plans: w.since } : {}) });
|
|
861
993
|
});
|
|
994
|
+
const lead = w.sec.folder.handoffs?.[0];
|
|
995
|
+
// Counted by id whatever its shape, whole or the stepped-down pointer (review 2 of #792).
|
|
996
|
+
if (lead !== undefined) noteLed(cp, lead.h, reader, w.hs);
|
|
997
|
+
// RAISED (SO1 step 4): said in a delivered wake, in a session someone attends
|
|
998
|
+
// (`owed` is only chosen there), once per item per lived day store-wide.
|
|
999
|
+
const owed = w.sec.open.owed;
|
|
1000
|
+
if (owed !== undefined && reader !== null && !cp.observer) {
|
|
1001
|
+
noteRaised(cp.store, { id: owed.id, version: owed.version, kind: owed.kind, scope: owed.scope }, { day: cp.store.livedDay(), session: reader, via: "wake" });
|
|
1002
|
+
}
|
|
862
1003
|
if (w.sec.folder.saidBytes !== undefined) cp["emit"](w.sec.folder.saidBytes > 0 ? "counterpart.lastexchange.shown" : "counterpart.lastexchange.noroom", undefined, { bytes: w.sec.folder.saidBytes });
|
|
863
1004
|
if ((w.sec.folder.chapters ?? 0) > 0) cp["emit"]("counterpart.lasthere.shown", undefined, { bytes: 0, lines: w.sec.folder.chapters ?? 0 });
|
|
1005
|
+
// TOLD ONCE (PG1, review of #789): the night whose set-downs this wake
|
|
1006
|
+
// told, so a later session's wake doesn't tell them again.
|
|
1007
|
+
const toldNight = w.sec.night.setDownNight;
|
|
1008
|
+
if (toldNight !== undefined) {
|
|
1009
|
+
try {
|
|
1010
|
+
cp.store.setMeta(SET_DOWN_TOLD_KEY, toldNight);
|
|
1011
|
+
} catch {
|
|
1012
|
+
/* told, and not recorded: the next wake may tell it again */
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
864
1015
|
const others = Object.values(w.sections).reduce((n, b) => n + b, 0);
|
|
865
1016
|
return {
|
|
866
1017
|
result,
|
|
@@ -906,6 +1057,451 @@ function sessionsSince(
|
|
|
906
1057
|
return seen.size;
|
|
907
1058
|
}
|
|
908
1059
|
|
|
1060
|
+
/** The meta key recording which sessions' wakes each live handoff led (review of #792): `{ [id]: { version, sessions } }`. */
|
|
1061
|
+
export const HANDOFF_LED_KEY = "wake.handoff.led";
|
|
1062
|
+
|
|
1063
|
+
type LedRecord = Record<string, { readonly version: number; readonly sessions: readonly string[]; readonly scope?: string; readonly last?: number }>;
|
|
1064
|
+
|
|
1065
|
+
function ledRecord(store: Counterpart["store"]): LedRecord {
|
|
1066
|
+
try {
|
|
1067
|
+
const v = JSON.parse(store.getMeta(HANDOFF_LED_KEY) ?? "{}") as unknown;
|
|
1068
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as LedRecord) : {};
|
|
1069
|
+
} catch {
|
|
1070
|
+
return {};
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/** This session's wake led with `h`: recorded (one entry per live handoff, the sessions distinct, a few kept). Never throws. */
|
|
1075
|
+
function noteLed(cp: Counterpart, h: Handoff, session: string | null, live: readonly Handoff[]): void {
|
|
1076
|
+
if (session === null || cp.observer) return;
|
|
1077
|
+
try {
|
|
1078
|
+
const was = ledRecord(cp.store);
|
|
1079
|
+
const keep = new Set(live.map((x) => x.id));
|
|
1080
|
+
const out: LedRecord = {};
|
|
1081
|
+
// Only this folder's gone handoffs are pruned: another folder's record stands (review 2 of #792).
|
|
1082
|
+
for (const [id, r] of Object.entries(was)) if (id !== h.id && (keep.has(id) || (r.scope !== undefined && r.scope !== h.scope))) out[id] = r;
|
|
1083
|
+
const mine = was[h.id];
|
|
1084
|
+
const sessions = mine === undefined || mine.version !== h.version ? [] : mine.sessions.filter((x) => x !== session);
|
|
1085
|
+
out[h.id] = { version: h.version, sessions: [...sessions, session].slice(-SHAPE.LEAD_SHOWN_KEPT), scope: h.scope, last: cp["nowFn"]() as number };
|
|
1086
|
+
cp.store.setMeta(HANDOFF_LED_KEY, JSON.stringify(out));
|
|
1087
|
+
} catch {
|
|
1088
|
+
/* a lead not recorded only sinks later */
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/** The ids a line names (`mem_…`), for what a handoff's lead points at. */
|
|
1093
|
+
const MEMORY_ID = /\bmem_[0-9a-f]+\b/g;
|
|
1094
|
+
|
|
1095
|
+
/** The words a lead waits on the owner in, around the owner's name (`{owner}`): lightly held, read on invented and real leads alike. */
|
|
1096
|
+
const WAITING_WORDS: readonly string[] = [
|
|
1097
|
+
"\\b(?:waiting|waits|wait) (?:on|for) {owner}\\b",
|
|
1098
|
+
"\\bask {owner}\\b",
|
|
1099
|
+
"\\b{owner}'s (?:word|yes|go|call|answer|decision|pick|choice|review|ok)\\b",
|
|
1100
|
+
"\\b{owner} to (?:pick|decide|choose|answer|say|confirm|review|approve|publish|run)\\b",
|
|
1101
|
+
// No name (review of #792: "ask for his first" led three sessions).
|
|
1102
|
+
"\\bask (?:for )?(?:his|her|their)\\b",
|
|
1103
|
+
"\\b(?:his|her|their) (?:call|word|yes|go|answer|decision)\\b",
|
|
1104
|
+
"\\bwhen (?:he|she|they) (?:answers?|replies|reply|decides?|says?)\\b",
|
|
1105
|
+
];
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* DOES THIS HANDOFF'S LEAD WAIT ON THE OWNER (WK3, 2026-11-09)? Its lead, whole
|
|
1109
|
+
* (`leadOf`, not only its first sentence), names a memory marked `asked` (the store's
|
|
1110
|
+
* own mark for a question to the owner), or says it waits on the owner by name
|
|
1111
|
+
* (`WAITING_WORDS`, or "the owner"). THE SEAM FOR SO1 STEP 4 (2026-11-09):
|
|
1112
|
+
* a lead it answers for that has sunk is a candidate for the wake's one
|
|
1113
|
+
* "Waiting on …" mention (`owedOne`), raised and backed off like an `asked`
|
|
1114
|
+
* memory (`owner-waits.ts`); parked, it stays sunk and is no longer said. The
|
|
1115
|
+
* raise events don't feed back here: a raise says it was shown, not that the
|
|
1116
|
+
* lead waits. Never throws.
|
|
1117
|
+
*/
|
|
1118
|
+
export function waitsOnOwner(store: Counterpart["store"], h: Pick<Handoff, "body">, owner: string | null): boolean {
|
|
1119
|
+
// The whole lead, not its first sentence (review 2 of #792: the wait sat past it).
|
|
1120
|
+
const lead = leadOf(h.body, SHAPE.LEAD_LINES, SHAPE.LEAD_BYTES).lines.join(" ");
|
|
1121
|
+
try {
|
|
1122
|
+
for (const id of lead.match(MEMORY_ID) ?? []) if (store.row(id)?.status === "asked") return true;
|
|
1123
|
+
} catch {
|
|
1124
|
+
/* a row that won't read answers nothing */
|
|
1125
|
+
}
|
|
1126
|
+
const names: string[] = owner !== null && owner.trim().length > 0 ? [owner.trim(), "the owner"] : ["the owner"];
|
|
1127
|
+
const alt = names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
|
|
1128
|
+
return WAITING_WORDS.some((w) => new RegExp(w.replace("{owner}", `(?:${alt})`), "iu").test(lead));
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/** The one item waiting on the owner a wake says (SO1 step 4): its line, and what its raise records. */
|
|
1132
|
+
interface Owed {
|
|
1133
|
+
readonly id: string;
|
|
1134
|
+
readonly version: number;
|
|
1135
|
+
readonly kind: "memory" | "handoff";
|
|
1136
|
+
readonly scope: string | null;
|
|
1137
|
+
/** The line before its age: "- Waiting on <owner>, …: <title>". */
|
|
1138
|
+
readonly text: string;
|
|
1139
|
+
readonly at: number;
|
|
1140
|
+
/** After its age: what settles it, how often it was raised, its id. */
|
|
1141
|
+
readonly tail: string;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* THE ONE THING WAITING ON THE OWNER THIS WAKE SAYS (SO1 step 4, revised; Mike
|
|
1146
|
+
* 11-07: "raise by relevance, not schedule"; the coordinator's 11-09 note: a
|
|
1147
|
+
* sunk handoff too, or it is hidden for good). Candidates: this reader's open
|
|
1148
|
+
* memories marked `asked` (here, or personal) and this folder's handoffs WK3
|
|
1149
|
+
* sank, each due by its backoff (`owner-waits.ts#waitState`: at most once a
|
|
1150
|
+
* week at session start, 3/7/14 lived days after each unanswered raise, then
|
|
1151
|
+
* parked). The most RELEVANT first: the most of its content words (title, and
|
|
1152
|
+
* what settles it) found in this folder's week (the lead, and the titles and
|
|
1153
|
+
* bodies' first lines written here in `OWNER_CONTEXT_MS`, its own row aside);
|
|
1154
|
+
* then this folder's before a personal one, then the oldest, then by id. No
|
|
1155
|
+
* model, no write. Null when none is due. Never throws.
|
|
1156
|
+
*/
|
|
1157
|
+
function owedOne(
|
|
1158
|
+
cp: Counterpart,
|
|
1159
|
+
o: {
|
|
1160
|
+
readonly day: number;
|
|
1161
|
+
readonly now: number;
|
|
1162
|
+
readonly rows: readonly { readonly id: string; readonly row: MemoryRow; readonly settles: string | null; readonly at: number; readonly here: boolean }[];
|
|
1163
|
+
readonly handoffs: readonly Handoff[];
|
|
1164
|
+
readonly lead: string;
|
|
1165
|
+
readonly folders: readonly string[];
|
|
1166
|
+
},
|
|
1167
|
+
): Owed | null {
|
|
1168
|
+
const record = raiseRecord(cp.store);
|
|
1169
|
+
let owner: string | null = null;
|
|
1170
|
+
try {
|
|
1171
|
+
owner = cp.ownerDisplayName();
|
|
1172
|
+
} catch {
|
|
1173
|
+
owner = null;
|
|
1174
|
+
}
|
|
1175
|
+
const who = owner !== null && owner.trim().length > 0 ? owner.trim() : "the owner";
|
|
1176
|
+
type Cand = Owed & { readonly words: ReadonlySet<string>; readonly here: boolean };
|
|
1177
|
+
const cands: Cand[] = [];
|
|
1178
|
+
const raisedWords = (n: number): string => (n === 0 ? "" : ` · raised ${plural(n, "time")} before, unanswered`);
|
|
1179
|
+
for (const x of o.rows) {
|
|
1180
|
+
const st = waitState(raisesAt(record, x.id, x.row.revision), o.day);
|
|
1181
|
+
if (st.kind !== "due") continue;
|
|
1182
|
+
const title = titleOfRow(x.row);
|
|
1183
|
+
cands.push({
|
|
1184
|
+
id: x.id,
|
|
1185
|
+
version: x.row.revision,
|
|
1186
|
+
kind: "memory",
|
|
1187
|
+
scope: x.row.origin_scope ?? null,
|
|
1188
|
+
text: `- Waiting on ${who}, ask when it fits: ${title}`,
|
|
1189
|
+
at: x.at,
|
|
1190
|
+
tail: `${x.settles === null ? "" : ` · settles when ${flatten(x.settles)}`}${raisedWords(st.raised)} [${x.id}]`,
|
|
1191
|
+
words: contentWords(`${title} ${x.settles ?? ""}`),
|
|
1192
|
+
here: x.here,
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
for (const h of o.handoffs) {
|
|
1196
|
+
const st = waitState(raisesAt(record, h.id, h.version), o.day);
|
|
1197
|
+
if (st.kind !== "due") continue;
|
|
1198
|
+
const title = titleOfRow({ title: null, body: h.body });
|
|
1199
|
+
cands.push({
|
|
1200
|
+
id: h.id,
|
|
1201
|
+
version: h.version,
|
|
1202
|
+
kind: "handoff",
|
|
1203
|
+
scope: h.scope,
|
|
1204
|
+
text: `- Waiting on ${who}, ask when it fits: ${title}`,
|
|
1205
|
+
at: cp.handoffs.writtenAt(h) ?? startOfLocalDay(h.writtenOn, cp.store.zone()),
|
|
1206
|
+
tail: ` · a handoff, below the others${raisedWords(st.raised)} [${h.id}]`,
|
|
1207
|
+
words: contentWords(leadOf(h.body, SHAPE.LEAD_LINES, SHAPE.LEAD_BYTES).lines.join(" ")),
|
|
1208
|
+
here: true,
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
if (cands.length === 0) return null;
|
|
1212
|
+
// This folder's week, as words: what an item is relevant to here.
|
|
1213
|
+
const ids = new Set(cands.map((c) => c.id));
|
|
1214
|
+
let recent: MemoryRow[] = [];
|
|
1215
|
+
try {
|
|
1216
|
+
recent = o.folders.flatMap((f) => cp.store.memoriesWrittenHereSince(f, o.now - SHAPE.OWNER_CONTEXT_MS, o.now, SHAPE.SINCE_READ));
|
|
1217
|
+
} catch {
|
|
1218
|
+
recent = [];
|
|
1219
|
+
}
|
|
1220
|
+
const week = contentWords([o.lead, ...recent.filter((r) => !ids.has(r.id) && !isNightRow(r)).map((r) => `${r.title ?? ""} ${r.body.split("\n")[0] ?? ""}`)].join(" "));
|
|
1221
|
+
const score = (c: Cand): number => [...c.words].filter((w) => week.has(w)).length;
|
|
1222
|
+
const ranked = cands.map((c) => ({ c, n: score(c) })).sort((a, b) => b.n - a.n || Number(b.c.here) - Number(a.c.here) || a.c.at - b.c.at || (a.c.id < b.c.id ? -1 : 1));
|
|
1223
|
+
const top = ranked[0]?.c;
|
|
1224
|
+
if (top === undefined) return null;
|
|
1225
|
+
const { words: _w, here: _h, ...owed } = top;
|
|
1226
|
+
return owed;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/** The meta key caching each folder's owed items for the turn lane, per lived day (round 3 of #796): `{ [folder]: { day, fp, at, items } }`. */
|
|
1230
|
+
export const OWNER_ITEMS_KEY = "wake.owner.items";
|
|
1231
|
+
|
|
1232
|
+
/** The cached list's shape, in its fingerprint: a list cached in an older shape is built again. */
|
|
1233
|
+
const OWNER_ITEMS_SHAPE = "subject-words";
|
|
1234
|
+
|
|
1235
|
+
/** One item waiting on the owner, as the turn lane matches it: its line's parts and its weighed words. */
|
|
1236
|
+
export interface OwedItem {
|
|
1237
|
+
readonly id: string;
|
|
1238
|
+
readonly version: number;
|
|
1239
|
+
readonly kind: "memory" | "handoff";
|
|
1240
|
+
readonly scope: string | null;
|
|
1241
|
+
readonly title: string;
|
|
1242
|
+
readonly needs: string | null;
|
|
1243
|
+
readonly at: number;
|
|
1244
|
+
readonly terms: TermWeights;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/** The owner's name and "owner", as index terms: a word every such item says, so it counts for nothing. */
|
|
1248
|
+
function ownerAside(cp: Counterpart): { who: string; aside: ReadonlySet<string> } {
|
|
1249
|
+
let owner: string | null = null;
|
|
1250
|
+
try {
|
|
1251
|
+
owner = cp.ownerDisplayName();
|
|
1252
|
+
} catch {
|
|
1253
|
+
owner = null;
|
|
1254
|
+
}
|
|
1255
|
+
const who = owner !== null && owner.trim().length > 0 ? owner.trim() : "the owner";
|
|
1256
|
+
return { who, aside: new Set(termsOf(`${who} owner`, SHAPE.WORD_MIN).keys()) };
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* ONE SUBJECT, ONE CHAIN (round 3 of #796: a memory raised on one day and the
|
|
1261
|
+
* handoff about it the next). A sunk handoff whose lead names an `asked`
|
|
1262
|
+
* memory among `mems`, or whose first sentence touches one's words as a turn
|
|
1263
|
+
* would (`touches`), is that memory's: not a candidate of its own, so the
|
|
1264
|
+
* memory's raise chain is the subject's. Pure but for the weighing.
|
|
1265
|
+
*/
|
|
1266
|
+
function handoffJoins(h: Handoff, first: TermWeights, mems: readonly { readonly id: string; readonly terms: TermWeights }[], aside: ReadonlySet<string>): boolean {
|
|
1267
|
+
const named = new Set(leadOf(h.body, SHAPE.LEAD_LINES, SHAPE.LEAD_BYTES).lines.join(" ").match(MEMORY_ID) ?? []);
|
|
1268
|
+
if (mems.some((m) => named.has(m.id))) return true;
|
|
1269
|
+
const words = new Set(Object.keys(first.w));
|
|
1270
|
+
return mems.some((m) => touches(sharedWeight(m.terms, words, aside)));
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/** The sunk handoffs that are no `asked` memory's subject (`handoffJoins`): the wake's candidates of their own. */
|
|
1274
|
+
function joinless(cp: Counterpart, hs: readonly Handoff[], mems: readonly { readonly id: string; readonly text: string }[]): Handoff[] {
|
|
1275
|
+
if (hs.length === 0 || mems.length === 0) return [...hs];
|
|
1276
|
+
const size = cp.store.countMemories({ archived: false });
|
|
1277
|
+
const { aside } = ownerAside(cp);
|
|
1278
|
+
const terms = weighMany(cp.store, [...mems.map((m) => m.text), ...hs.map((h) => firstRealSentence(h.body))], size);
|
|
1279
|
+
const weighed = mems.map((m, i) => ({ id: m.id, terms: terms[i] ?? NO_TERMS }));
|
|
1280
|
+
return hs.filter((h, i) => !handoffJoins(h, terms[mems.length + i] ?? NO_TERMS, weighed, aside));
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/**
|
|
1284
|
+
* THE ITEMS WAITING ON THE OWNER HERE, WEIGHED (SO1 step 4, the turn lane):
|
|
1285
|
+
* open memories marked `asked` that this folder's Still open would carry (its
|
|
1286
|
+
* own, a joined folder's, or personal; not dated, whose home is Coming up),
|
|
1287
|
+
* each by its title and what settles it; and this folder's handoffs WK3 sank,
|
|
1288
|
+
* each by its lead's first sentence and the titles of the memories its lead
|
|
1289
|
+
* names, unless it joins an `asked` memory's chain (`handoffJoins`). Reads only.
|
|
1290
|
+
*/
|
|
1291
|
+
export function owedItems(cp: Counterpart, scope: string, exportsFrom?: (scope: string) => boolean): OwedItem[] {
|
|
1292
|
+
const store = cp.store;
|
|
1293
|
+
const now: number = cp["nowFn"]();
|
|
1294
|
+
const reader = cp["threadReader"](scope, exportsFrom);
|
|
1295
|
+
const folders = new Set(reader.folders.map(projectFolder).filter((f) => f.length > 0));
|
|
1296
|
+
const rule = { craftTravels: cp.self.tunables.PROJECTS_TRAVEL, craftSince: craftSince(store) };
|
|
1297
|
+
const size = store.countMemories({ archived: false });
|
|
1298
|
+
const { aside } = ownerAside(cp);
|
|
1299
|
+
const asked = store.askedOpenStamps().map((r) => r.id);
|
|
1300
|
+
const found: (Omit<OwedItem, "terms"> & { readonly text: string })[] = [];
|
|
1301
|
+
for (const f of asked.length === 0 ? [] : store.openThreadTouches({ at: store.today(), ids: asked })) {
|
|
1302
|
+
if (!f.asked || f.dated) continue;
|
|
1303
|
+
const r = store.row(f.id);
|
|
1304
|
+
if (r === undefined || r.status !== "asked" || r.superseded_by !== null) continue;
|
|
1305
|
+
if (threadPlace({ about: r.about ?? null, kind: r.kind as Kind, originScope: r.origin_scope ?? null, journal: false }, folders, rule) === "out") continue;
|
|
1306
|
+
let needs: string | null = null;
|
|
1307
|
+
try {
|
|
1308
|
+
needs = settlesWhenOf(store.readProse(f.id).meta);
|
|
1309
|
+
} catch {
|
|
1310
|
+
needs = null;
|
|
1311
|
+
}
|
|
1312
|
+
const title = titleOfRow(r);
|
|
1313
|
+
found.push({ id: f.id, version: r.revision, kind: "memory", scope: r.origin_scope ?? null, title, needs, at: r.created_at ?? now, text: `${title} ${needs ?? ""}` });
|
|
1314
|
+
}
|
|
1315
|
+
const sunk = new Set<string>();
|
|
1316
|
+
const hs = handoffsTold(cp, cp.handoffs.readAll(scope), [...folders], now, null, sunk).slice(1).filter((h) => sunk.has(h.id));
|
|
1317
|
+
// A handoff by its lead's first sentence and the titles of the memories its lead names.
|
|
1318
|
+
const handText = (h: Handoff): string => {
|
|
1319
|
+
const named = leadOf(h.body, SHAPE.LEAD_LINES, SHAPE.LEAD_BYTES).lines.join(" ").match(MEMORY_ID) ?? [];
|
|
1320
|
+
return [firstRealSentence(h.body), ...named.flatMap((id) => {
|
|
1321
|
+
const r = store.row(id);
|
|
1322
|
+
return r === undefined ? [] : [titleOfRow(r)];
|
|
1323
|
+
})].join(" ");
|
|
1324
|
+
};
|
|
1325
|
+
// One document-frequency read for every item's words, and each handoff's first sentence.
|
|
1326
|
+
const weights = weighMany(store, [...found.map((x) => x.text), ...hs.map((h) => firstRealSentence(h.body)), ...hs.map(handText)], size);
|
|
1327
|
+
const items: OwedItem[] = found.map(({ text: _t, ...x }, i) => ({ ...x, terms: weights[i] ?? NO_TERMS }));
|
|
1328
|
+
const mems = [...items];
|
|
1329
|
+
hs.forEach((h, i) => {
|
|
1330
|
+
if (handoffJoins(h, weights[found.length + i] ?? NO_TERMS, mems, aside)) return;
|
|
1331
|
+
items.push({
|
|
1332
|
+
id: h.id,
|
|
1333
|
+
version: h.version,
|
|
1334
|
+
kind: "handoff",
|
|
1335
|
+
scope: h.scope,
|
|
1336
|
+
title: titleOfRow({ title: null, body: h.body }),
|
|
1337
|
+
needs: null,
|
|
1338
|
+
at: cp.handoffs.writtenAt(h) ?? startOfLocalDay(h.writtenOn, store.zone()),
|
|
1339
|
+
terms: weights[found.length + hs.length + i] ?? NO_TERMS,
|
|
1340
|
+
});
|
|
1341
|
+
});
|
|
1342
|
+
return items;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
type ItemsCache = Record<string, { readonly day: number; readonly fp: string; readonly at: number; readonly items: readonly OwedItem[] }>;
|
|
1346
|
+
|
|
1347
|
+
/**
|
|
1348
|
+
* `owedItems`, CACHED PER FOLDER PER LIVED DAY (round 3 of #796: the build
|
|
1349
|
+
* cost 17–23 ms a turn on a real store). Kept in meta under the folder (every
|
|
1350
|
+
* session there reads the same list, so asked per session it would only be
|
|
1351
|
+
* built more often), with a
|
|
1352
|
+
* fingerprint of what would change the list: the `asked` open items' ids and
|
|
1353
|
+
* revisions, this folder's handoffs' ids and versions, and WK3's lead record
|
|
1354
|
+
* (what sinks one). A write that changes any of those, or a new lived day,
|
|
1355
|
+
* builds it again. The cache never decides: only how often the list is read.
|
|
1356
|
+
*/
|
|
1357
|
+
function owedItemsCached(cp: Counterpart, scope: string, exportsFrom?: (scope: string) => boolean): OwedItem[] {
|
|
1358
|
+
const store = cp.store;
|
|
1359
|
+
const day = store.livedDay();
|
|
1360
|
+
const fp = hashText(JSON.stringify([OWNER_ITEMS_SHAPE, scope, store.askedOpenStamps(), cp.handoffs.readAll(scope).map((h) => [h.id, h.version]), store.getMeta(HANDOFF_LED_KEY) ?? ""]));
|
|
1361
|
+
let was: ItemsCache = {};
|
|
1362
|
+
try {
|
|
1363
|
+
const v = JSON.parse(store.getMeta(OWNER_ITEMS_KEY) ?? "{}") as unknown;
|
|
1364
|
+
if (v !== null && typeof v === "object" && !Array.isArray(v)) was = v as ItemsCache;
|
|
1365
|
+
} catch {
|
|
1366
|
+
was = {};
|
|
1367
|
+
}
|
|
1368
|
+
const hit = was[scope];
|
|
1369
|
+
if (hit !== undefined && hit.day === day && hit.fp === fp && Array.isArray(hit.items)) return [...hit.items];
|
|
1370
|
+
const items = owedItems(cp, scope, exportsFrom);
|
|
1371
|
+
if (!cp.observer) {
|
|
1372
|
+
try {
|
|
1373
|
+
const { [scope]: _old, ...rest } = was;
|
|
1374
|
+
const kept = Object.entries(rest)
|
|
1375
|
+
.sort((a, b) => (a[1].at ?? 0) - (b[1].at ?? 0))
|
|
1376
|
+
.slice(-(SHAPE.OWNER_ITEMS_KEPT - 1));
|
|
1377
|
+
store.setMeta(OWNER_ITEMS_KEY, JSON.stringify(Object.fromEntries([...kept, [scope, { day, fp, at: cp["nowFn"](), items }]])));
|
|
1378
|
+
} catch {
|
|
1379
|
+
/* uncached: the next turn builds it again */
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
return items;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
/**
|
|
1386
|
+
* THE RELEVANCE LANE (SO1 step 4, revised, point 2; coordinator 11-09, round 3
|
|
1387
|
+
* of #796): what waits on the owner comes up when the turn touches its
|
|
1388
|
+
* subject, in its own project, with its context. A turn with fewer than
|
|
1389
|
+
* `OWNER_TURN_MIN_WORDS` content words doesn't look. Touched: at least
|
|
1390
|
+
* `OWNER_TURN_SHARED` of the item's words in the turn, weighing together
|
|
1391
|
+
* `OWNER_TURN_WEIGHT` at recall's cue weight (`owner-waits.ts#touches`); the
|
|
1392
|
+
* owner's name counts for nothing. Due by the SAME backoff and record as the
|
|
1393
|
+
* wake's mention (`owner-waits.ts`), without the wake's weekly floor: 3, 7, 14
|
|
1394
|
+
* lived days, then parked, once per lived day store-wide. The heaviest match
|
|
1395
|
+
* first, then the oldest. One line, or null. The caller shows it and records
|
|
1396
|
+
* the raise. Never throws.
|
|
1397
|
+
*/
|
|
1398
|
+
export function owedForTurn(
|
|
1399
|
+
cp: Counterpart,
|
|
1400
|
+
o: { readonly text: string; readonly scope: string; readonly exportsFrom?: (scope: string) => boolean },
|
|
1401
|
+
): { line: string; item: { id: string; version: number; kind: "memory" | "handoff"; scope: string | null } } | null {
|
|
1402
|
+
try {
|
|
1403
|
+
if (contentWords(o.text).size < SHAPE.OWNER_TURN_MIN_WORDS) return null;
|
|
1404
|
+
const items = owedItemsCached(cp, o.scope, o.exportsFrom);
|
|
1405
|
+
if (items.length === 0) return null;
|
|
1406
|
+
const store = cp.store;
|
|
1407
|
+
const day = store.livedDay();
|
|
1408
|
+
const now: number = cp["nowFn"]();
|
|
1409
|
+
const record = raiseRecord(store);
|
|
1410
|
+
const { who, aside } = ownerAside(cp);
|
|
1411
|
+
const turn = new Set(termsOf(o.text).keys());
|
|
1412
|
+
const hits = items
|
|
1413
|
+
.map((i) => ({ i, s: sharedWeight(i.terms, turn, aside), st: waitState(raisesAt(record, i.id, i.version), day, SHAPE.OWNER_RAISE_STEPS, 0) }))
|
|
1414
|
+
.filter((x) => x.st.kind === "due" && touches(x.s))
|
|
1415
|
+
.sort((a, b) => b.s.sum - a.s.sum || a.i.at - b.i.at || (a.i.id < b.i.id ? -1 : 1));
|
|
1416
|
+
const top = hits[0];
|
|
1417
|
+
if (top === undefined) return null;
|
|
1418
|
+
const { i } = top;
|
|
1419
|
+
const needs = i.needs === null ? "" : ` · needs: ${flatten(i.needs)}`;
|
|
1420
|
+
const raised = top.st.raised === 0 ? "" : ` · raised ${plural(top.st.raised, "time")} before, unanswered`;
|
|
1421
|
+
const line = `Waiting on ${who}, ask when it fits: ${i.title}${needs} · waiting ${ageWords(i.at, now)}${i.kind === "handoff" ? " (a handoff)" : ""}${raised} [${i.id}]`;
|
|
1422
|
+
return { line, item: { id: i.id, version: i.version, kind: i.kind, scope: i.scope } };
|
|
1423
|
+
} catch {
|
|
1424
|
+
return null;
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
/**
|
|
1429
|
+
* THE HANDOFFS AS THE WAKE TELLS THEM (WK3, 2026-11-09; a counterpart's
|
|
1430
|
+
* feedback: a 47-hour-old handoff led three sessions with "ask him first", and
|
|
1431
|
+
* ten-day-old ones were still listed). `all` newest first, as
|
|
1432
|
+
* `Handoffs#readAll` gives them; `recall "handoffs"` still lists every one.
|
|
1433
|
+
*
|
|
1434
|
+
* - Not listed: one past `HANDOFF_LISTED_MS` that nothing written since
|
|
1435
|
+
* refers to by its id (a newer handoff, or a memory written in one of this
|
|
1436
|
+
* reader's folders). The newest always is: the folder's last word.
|
|
1437
|
+
* - Sinks below the rest, newest first among them, until it is revised: one
|
|
1438
|
+
* whose lead waits on the owner (`waitsOnOwner`) and that has led
|
|
1439
|
+
* `LEAD_SHOWN_SINK` wakes since its last revision, with no reply since: no
|
|
1440
|
+
* memory written here after it, by another session, whose title says the
|
|
1441
|
+
* lead again (`titleInLead`) or that names a memory still `asked`. A
|
|
1442
|
+
* handoff that doesn't wait on the owner never sinks. Alone, it still leads.
|
|
1443
|
+
*
|
|
1444
|
+
* Never throws: what can't be read keeps the order it came in.
|
|
1445
|
+
*/
|
|
1446
|
+
function handoffsTold(cp: Counterpart, all: readonly Handoff[], folders: readonly string[], now: number, reader: string | null, sunkOut?: Set<string>): Handoff[] {
|
|
1447
|
+
if (all.length <= 1) return [...all];
|
|
1448
|
+
const zone = cp.store.zone();
|
|
1449
|
+
const at = (h: Handoff): number => cp.handoffs.writtenAt(h) ?? startOfLocalDay(h.writtenOn, zone);
|
|
1450
|
+
const oldest = Math.min(...all.map(at));
|
|
1451
|
+
let rows: MemoryRow[] = [];
|
|
1452
|
+
try {
|
|
1453
|
+
rows = folders.flatMap((f) => cp.store.memoriesWrittenHereSince(f, oldest, now, SHAPE.SINCE_READ));
|
|
1454
|
+
} catch {
|
|
1455
|
+
rows = [];
|
|
1456
|
+
}
|
|
1457
|
+
const referred = (h: Handoff): boolean =>
|
|
1458
|
+
all.some((o) => o.id !== h.id && at(o) > at(h) && o.body.includes(h.id)) || rows.some((r) => (r.created_at ?? 0) > at(h) && (r.body.includes(h.id) || (r.meta ?? "").includes(h.id)));
|
|
1459
|
+
const listed = all.filter((h, i) => i === 0 || now - at(h) < SHAPE.HANDOFF_LISTED_MS || referred(h));
|
|
1460
|
+
const signal = (h: Handoff): boolean => {
|
|
1461
|
+
// The asked ids from the whole lead; the words from its first sentence only: a
|
|
1462
|
+
// five-line lead shares most titles' words by chance (review 2 of #792, real store).
|
|
1463
|
+
const lead = firstRealSentence(h.body);
|
|
1464
|
+
// Only an id still marked `asked`: a later row that merely cites a lead's other ids
|
|
1465
|
+
// (a night's, a recap) is no answer (review 2 of #792, real store).
|
|
1466
|
+
const asked = (leadOf(h.body, SHAPE.LEAD_LINES, SHAPE.LEAD_BYTES).lines.join(" ").match(MEMORY_ID) ?? []).filter((id) => {
|
|
1467
|
+
try {
|
|
1468
|
+
return cp.store.row(id)?.status === "asked";
|
|
1469
|
+
} catch {
|
|
1470
|
+
return false;
|
|
1471
|
+
}
|
|
1472
|
+
});
|
|
1473
|
+
return rows.some(
|
|
1474
|
+
(r) =>
|
|
1475
|
+
(r.created_at ?? 0) > at(h) &&
|
|
1476
|
+
(h.session === null || r.origin_session !== h.session) &&
|
|
1477
|
+
(titleInLead(flatten(r.title ?? ""), lead, SHAPE.SINCE_IN_LEAD) || asked.some((id) => r.body.includes(id) || (r.meta ?? "").includes(id))),
|
|
1478
|
+
);
|
|
1479
|
+
};
|
|
1480
|
+
let owner: string | null = null;
|
|
1481
|
+
try {
|
|
1482
|
+
owner = cp.ownerDisplayName();
|
|
1483
|
+
} catch {
|
|
1484
|
+
owner = null;
|
|
1485
|
+
}
|
|
1486
|
+
// SUNK (review 3 of #792): a lead that waits on the owner AND has led at least
|
|
1487
|
+
// `LEAD_SHOWN_SINK` wakes since its last revision (the record's version), with
|
|
1488
|
+
// no reply since. Nothing else sinks by count. It stays sunk until revised,
|
|
1489
|
+
// whatever else is left, so two stale leads never take turns.
|
|
1490
|
+
const led = ledRecord(cp.store);
|
|
1491
|
+
const ledEnough = (h: Handoff): boolean => {
|
|
1492
|
+
const r = led[h.id];
|
|
1493
|
+
return r !== undefined && r.version === h.version && r.sessions.length >= SHAPE.LEAD_SHOWN_SINK;
|
|
1494
|
+
};
|
|
1495
|
+
const sunk = new Set(listed.filter((h) => ledEnough(h) && !signal(h) && waitsOnOwner(cp.store, h, owner)).map((h) => h.id));
|
|
1496
|
+
// What SO1 step 4's weekly mention reads (coordinator 11-09): a sunk one is said there, or nowhere.
|
|
1497
|
+
for (const id of sunk) sunkOut?.add(id);
|
|
1498
|
+
// Sunk ones by when each last led, latest first: the one that sank first stays at
|
|
1499
|
+
// the bottom when every handoff has sunk (review 3 of #792: no tie flip-flop).
|
|
1500
|
+
const lastLed = (h: Handoff): number => led[h.id]?.last ?? 0;
|
|
1501
|
+
const down = listed.filter((h) => sunk.has(h.id)).sort((x, y) => lastLed(y) - lastLed(x));
|
|
1502
|
+
return [...listed.filter((h) => !sunk.has(h.id)), ...down];
|
|
1503
|
+
}
|
|
1504
|
+
|
|
909
1505
|
/** Up to `OLDER_SHOWN` of the older handoffs, one per seat, not the lead's, newest of each. */
|
|
910
1506
|
function pickOlder(hs: readonly Handoff[]): { h: Handoff; seat: string }[] {
|
|
911
1507
|
const first = hs[0];
|
|
@@ -977,6 +1573,8 @@ interface ElsewhereRow {
|
|
|
977
1573
|
readonly fact: number;
|
|
978
1574
|
readonly at: number;
|
|
979
1575
|
readonly live: boolean;
|
|
1576
|
+
/** When its earliest live session here started; 0 when none is live. */
|
|
1577
|
+
readonly since: number;
|
|
980
1578
|
}
|
|
981
1579
|
|
|
982
1580
|
/** One block for other folders: each one's NEWEST title, so an older line can't sit under its own correction; live ones first. */
|
|
@@ -1010,14 +1608,18 @@ function elsewhereFacts(
|
|
|
1010
1608
|
if (had !== undefined && had.at >= ch.writtenAt) continue;
|
|
1011
1609
|
best.set(key, { id: ch.id, title: `chapter "${flatten(t)}"`, at: ch.writtenAt, fact: ch.writtenAt });
|
|
1012
1610
|
}
|
|
1013
|
-
const live = new
|
|
1014
|
-
for (const s of sessions)
|
|
1611
|
+
const live = new Map<string, number>();
|
|
1612
|
+
for (const s of sessions) {
|
|
1613
|
+
if (!s.live || s.session === reader || !gate.named(s.scope)) continue;
|
|
1614
|
+
const key = gate.norm(s.scope);
|
|
1615
|
+
live.set(key, Math.min(live.get(key) ?? s.startedAt, s.startedAt));
|
|
1616
|
+
}
|
|
1015
1617
|
// Folders worked in with no title to say: counted past the list, and named at its door.
|
|
1016
1618
|
const counted = store.memoryCountsByScopeSince(sinceY).flatMap(({ scope }) => (gate.named(scope) ? [gate.norm(scope)] : []));
|
|
1017
1619
|
// A folder by its name; by its path only when another here or in the section has the same name (FS1).
|
|
1018
|
-
const among = [...best.keys(), ...live, ...counted, ...gate.ours];
|
|
1019
|
-
const list: ElsewhereRow[] = [...best.entries()].map(([key, m]) => ({ place: placeWords(key, among), id: m.id, title: m.title, fact: m.fact, at: m.at, live: live.has(key) }));
|
|
1020
|
-
for (const key of live) if (!best.has(key)) list.push({ place: placeWords(key, among), id: null, title: null, fact: now, at: 0, live: true });
|
|
1620
|
+
const among = [...best.keys(), ...live.keys(), ...counted, ...gate.ours];
|
|
1621
|
+
const list: ElsewhereRow[] = [...best.entries()].map(([key, m]) => ({ place: placeWords(key, among), id: m.id, title: m.title, fact: m.fact, at: m.at, live: live.has(key), since: live.get(key) ?? 0 }));
|
|
1622
|
+
for (const [key, started] of live) if (!best.has(key)) list.push({ place: placeWords(key, among), id: null, title: null, fact: now, at: 0, live: true, since: started });
|
|
1021
1623
|
list.sort((a, b) => Number(b.live) - Number(a.live) || b.at - a.at || (a.place < b.place ? -1 : 1));
|
|
1022
1624
|
const named = new Set(list.map((l) => l.place));
|
|
1023
1625
|
const quiet = new Set<string>();
|
|
@@ -1076,8 +1678,49 @@ function nightClosedLine(cp: Counterpart, day: number, folders: ReadonlySet<stri
|
|
|
1076
1678
|
return `Closed by the night (${String(mine.length)}): ${named.join("; ")}${more > 0 ? `; +${String(more)} more` : ""}. One not done? The reflect tool's phase "reopen", reopen: [its id], puts it back.`;
|
|
1077
1679
|
}
|
|
1078
1680
|
|
|
1681
|
+
/**
|
|
1682
|
+
* `Set down from my page last night: "Kiln logs wander: look, then fix the
|
|
1683
|
+
* note" (recall "set down")` (PG1, 2026-11-09): the set-downs of the newest
|
|
1684
|
+
* night (`counterpart-wake-news.ts#lastNightAt`, by its local date), told
|
|
1685
|
+
* until the next night runs, at most `SET_DOWN_SHOWN` by line, then "and N
|
|
1686
|
+
* more". The night runs at a day's first prompt, after that day's first wake,
|
|
1687
|
+
* so this reaches a later session that day and the next morning's first wake
|
|
1688
|
+
* — but told ONCE (review of #789): the first wake that tells a night's
|
|
1689
|
+
* set-downs records it (`SET_DOWN_TOLD_KEY`), and no later wake tells that
|
|
1690
|
+
* night's again. Only the quoted ones: named by the writer, or clearly gone; a
|
|
1691
|
+
* quiet one ("maybe reworded", the lines past a write's cap) is behind the
|
|
1692
|
+
* door only. A set-down whose line is on the page now (brought back) or in the
|
|
1693
|
+
* night's own words is not told (WK3). Null when there is none.
|
|
1694
|
+
*/
|
|
1695
|
+
function setDownWakeLine(cp: Counterpart, now: number, own: string | null): { line: string; ids: string[]; night: string } | null {
|
|
1696
|
+
const store = cp.store;
|
|
1697
|
+
const nightAt = lastNightAt(store, now);
|
|
1698
|
+
if (nightAt === null) return null;
|
|
1699
|
+
const night = localDate(nightAt, store.zone());
|
|
1700
|
+
if (store.getMeta(SET_DOWN_TOLD_KEY) === night) return null;
|
|
1701
|
+
const page = cp.self.page()?.body ?? null;
|
|
1702
|
+
const prepared = page === null ? null : preparePage(page);
|
|
1703
|
+
const ownPage = own === null ? null : preparePage(own);
|
|
1704
|
+
const rows = nightSetDowns(store, night).filter(
|
|
1705
|
+
(r) => r.quiet !== true && (prepared === null || !lineOnPage(r.line, prepared)) && (ownPage === null || !lineOnPage(r.line, ownPage)),
|
|
1706
|
+
);
|
|
1707
|
+
if (rows.length === 0) return null;
|
|
1708
|
+
const max = SHAPE.SET_DOWN_LINE_CHARS;
|
|
1709
|
+
const clip = (t: string): string => {
|
|
1710
|
+
const flat = flatten(t);
|
|
1711
|
+
return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat;
|
|
1712
|
+
};
|
|
1713
|
+
const named = rows.slice(0, SHAPE.SET_DOWN_SHOWN).map((r) => `"${clip(r.line)}"`);
|
|
1714
|
+
const more = rows.length - named.length;
|
|
1715
|
+
return {
|
|
1716
|
+
line: `Set down from my page last night: ${named.join("; ")}${more > 0 ? `, and ${String(more)} more` : ""} (recall "${SET_DOWN_HANDLE}")`,
|
|
1717
|
+
ids: rows.map((r) => r.id),
|
|
1718
|
+
night,
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1079
1722
|
/** "Last night", by title and door: the night's own words on what ran, no ids; and the night's own line, when it left one a reader here may read. */
|
|
1080
|
-
function nightWords(cp: Counterpart, at: string, here: WakeHere | undefined, scope: string): { line: string; own: string | null } | null {
|
|
1723
|
+
function nightWords(cp: Counterpart, at: string, here: WakeHere | undefined, scope: string): { line: string; own: string | null; reflection: string | null } | null {
|
|
1081
1724
|
const store = cp.store;
|
|
1082
1725
|
const readable = (s: string | null): boolean => {
|
|
1083
1726
|
if (s === null || s.trim().length === 0) return true;
|
|
@@ -1116,5 +1759,102 @@ function nightWords(cp: Counterpart, at: string, here: WakeHere | undefined, sco
|
|
|
1116
1759
|
}
|
|
1117
1760
|
}
|
|
1118
1761
|
const hasNight = reflectionId !== null || /dream "| a dream| a reflection/.test(line);
|
|
1119
|
-
return { line: hasNight ? `${line} Whole: recall "last night".` : line, own };
|
|
1762
|
+
return { line: hasNight ? `${line} Whole: recall "last night".` : line, own, reflection: reflectionId };
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/** `2026-11-07` or `11-07`; and `Nov 7`, `November 7th` (strings, so the root holds no number). */
|
|
1766
|
+
const NUMERIC_DAY = new RegExp("\\b(?:\\d\\d\\d\\d-)?(\\d\\d?)-(\\d\\d?)\\b", "g");
|
|
1767
|
+
const NAMED_DAY = new RegExp("\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?\\s+(\\d\\d?)(?:st|nd|rd|th)?\\b", "g");
|
|
1768
|
+
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
1769
|
+
|
|
1770
|
+
/** The days a sentence names, as `MM-DD`: `2026-11-07`, `11-07`, `Nov 7`, `November 7th`. Pure. */
|
|
1771
|
+
export function datesIn(text: string): Set<string> {
|
|
1772
|
+
const out = new Set<string>();
|
|
1773
|
+
const two = (n: number): string => (String(n).length === 1 ? `0${String(n)}` : String(n));
|
|
1774
|
+
for (const m of text.matchAll(NUMERIC_DAY)) {
|
|
1775
|
+
const mo = Number(m[1]);
|
|
1776
|
+
const d = Number(m[2]);
|
|
1777
|
+
if (mo >= 1 && mo <= MONTHS.length && d >= 1 && d <= SHAPE.MONTH_DAYS_MAX) out.add(`${two(mo)}-${two(d)}`);
|
|
1778
|
+
}
|
|
1779
|
+
for (const m of text.toLowerCase().matchAll(NAMED_DAY)) {
|
|
1780
|
+
const mo = MONTHS.indexOf(m[1] ?? "") + 1;
|
|
1781
|
+
const d = Number(m[2]);
|
|
1782
|
+
if (mo >= 1 && d >= 1 && d <= SHAPE.MONTH_DAYS_MAX) out.add(`${two(mo)}-${two(d)}`);
|
|
1783
|
+
}
|
|
1784
|
+
return out;
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/**
|
|
1788
|
+
* THE SAME MOMENT, WHATEVER THE WORDS (review of #792: the owner's 11-09 closing
|
|
1789
|
+
* line paraphrased a moment the page told as a clause, and the near-verbatim
|
|
1790
|
+
* check passed it). A sentence and a page sentence naming the same day
|
|
1791
|
+
* (`datesIn`) and sharing at least `MOMENT_SHARED_WORDS` content words (dates
|
|
1792
|
+
* and numbers aside) tell one moment. The line has no memory of its own to
|
|
1793
|
+
* match by identity (a reflection's `detail.line` is text), so this is the
|
|
1794
|
+
* rule. Pure.
|
|
1795
|
+
*/
|
|
1796
|
+
export function sameMoment(sentence: string, page: PreparedPage): boolean {
|
|
1797
|
+
const days = datesIn(sentence);
|
|
1798
|
+
if (days.size === 0) return false;
|
|
1799
|
+
const words = [...contentWords(sentence)].filter((w) => !/\d/.test(w));
|
|
1800
|
+
for (const p of page.sentences) {
|
|
1801
|
+
if (![...datesIn(p.text)].some((d) => days.has(d))) continue;
|
|
1802
|
+
if (words.filter((w) => p.words.has(w)).length >= SHAPE.MOMENT_SHARED_WORDS) return true;
|
|
1803
|
+
}
|
|
1804
|
+
return false;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
/** Where a line breaks into clauses, as set-down's clause rule reads them. */
|
|
1808
|
+
const CLAUSE_BREAK = /\s*(?:[;:(]|—|\s-\s)\s*/u;
|
|
1809
|
+
|
|
1810
|
+
/**
|
|
1811
|
+
* ONE TELLING OF A MOMENT PER WAKE (WK3, 2026-11-09; a counterpart's feedback:
|
|
1812
|
+
* a slip on the page came back as the wake's last line, on its own, two
|
|
1813
|
+
* mornings running, and read as penance, not memory). The night's own line is
|
|
1814
|
+
* the wake's closing line, so it carries something forward, never a sentence
|
|
1815
|
+
* the wake already told: each of its sentences on the page or in day's end's
|
|
1816
|
+
* words (word for word, or reworded past `SET_DOWN_LIMITS.NEAR_SHARE`:
|
|
1817
|
+
* `self/set-down.ts#lineOnPage`) is dropped, and with none left there is no
|
|
1818
|
+
* line (the night's titles and its door stand alone; the reflection's row has
|
|
1819
|
+
* no other line to fall back to). The same moment two mornings running — a
|
|
1820
|
+
* sentence of the line before this one's on the same footing — is at most
|
|
1821
|
+
* its first clause the second morning, or nothing when it has only one.
|
|
1822
|
+
* A read: what was told is not recorded (PG1's set-down latch is its own).
|
|
1823
|
+
*/
|
|
1824
|
+
function ownToldOnce(cp: Counterpart, night: { readonly own: string | null; readonly reflection: string | null }, told: readonly string[]): string | null {
|
|
1825
|
+
const own = night.own;
|
|
1826
|
+
if (own === null) return null;
|
|
1827
|
+
const already = told.filter((t) => t.trim().length > 0).map((t) => preparePage(t));
|
|
1828
|
+
const sentences = preparePage(own).sentences.map((x) => x.text);
|
|
1829
|
+
// One sentence of the line telling a told moment is the line telling it (review 2 of
|
|
1830
|
+
// #792): its undated rest is the same moment, and alone it would be a fragment.
|
|
1831
|
+
const kept = sentences.length === 0 ? [own] : sentences;
|
|
1832
|
+
if (kept.some((x) => already.some((p) => lineOnPage(x, p) || sameMoment(x, p)))) return null;
|
|
1833
|
+
const line = kept.join(" ");
|
|
1834
|
+
const before = previousOwn(cp, night.reflection);
|
|
1835
|
+
if (before === null) return line;
|
|
1836
|
+
const prior = preparePage(before);
|
|
1837
|
+
if (!kept.some((x) => lineOnPage(x, prior))) return line;
|
|
1838
|
+
const first = (kept[0] ?? "").trim();
|
|
1839
|
+
const clause = first.split(CLAUSE_BREAK)[0]?.trim() ?? "";
|
|
1840
|
+
if (clause.length === 0 || clause === first) return null;
|
|
1841
|
+
return `${clause.replace(/[,.;:!?]+$/u, "")}…`;
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
/** The own line of the reflection before `id` (the newest reflected one dated before it), or null. Reads only. */
|
|
1845
|
+
function previousOwn(cp: Counterpart, id: string | null): string | null {
|
|
1846
|
+
if (id === null) return null;
|
|
1847
|
+
const store = cp.store;
|
|
1848
|
+
const self = store.reflection(id);
|
|
1849
|
+
if (self === undefined) return null;
|
|
1850
|
+
for (const r of store.reflections({ limit: SHAPE.NEWS_NIGHTS_READ })) {
|
|
1851
|
+
if (r.id === id || r.state !== "reflected" || r.date === null || self.date === null || r.date >= self.date) continue;
|
|
1852
|
+
try {
|
|
1853
|
+
const l = (JSON.parse(store.reflection(r.id)?.detail ?? "{}") as { line?: unknown }).line;
|
|
1854
|
+
return typeof l === "string" && l.trim().length > 0 ? flatten(l) : null;
|
|
1855
|
+
} catch {
|
|
1856
|
+
return null;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
return null;
|
|
1120
1860
|
}
|