counterparts 0.3.11 → 0.3.13
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 +326 -0
- package/docs/QUICKSTART.md +5 -0
- package/docs/README.md +2 -2
- package/docs/module-map.md +3 -3
- package/package.json +1 -1
- package/src/adapters/claude-code/CONTRACT.md +36 -10
- package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
- package/src/adapters/claude-code/NOTES.md +182 -0
- package/src/adapters/claude-code/bin/hook.ts +46 -12
- package/src/adapters/claude-code/bin/runner.ts +7 -1
- package/src/adapters/claude-code/doctor.ts +632 -18
- package/src/adapters/claude-code/hooks.ts +61 -16
- package/src/adapters/claude-code/index.ts +11 -0
- package/src/adapters/claude-code/night-run.ts +150 -14
- package/src/adapters/claude-code/transcript.ts +268 -1
- package/src/adapters/cli/CONTRACT.md +5 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
- package/src/adapters/cli/NOTES.md +111 -0
- package/src/adapters/cli/commands.ts +134 -92
- package/src/adapters/cli/dream-core.ts +57 -42
- package/src/adapters/cli/export.ts +320 -21
- package/src/adapters/cli/help.ts +2 -1
- package/src/adapters/cli/index.ts +1 -0
- package/src/adapters/cli/install.ts +39 -7
- package/src/adapters/cli/mechanisms.ts +7 -1
- package/src/adapters/cli/uninstall.ts +13 -5
- package/src/adapters/cli/wire.ts +189 -63
- package/src/adapters/config.ts +2 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
- package/src/adapters/dashboard/NOTES.md +79 -0
- package/src/adapters/dashboard/registries.ts +34 -2
- package/src/adapters/dashboard/web/README.md +19 -14
- package/src/adapters/dashboard/web/actions.ts +23 -1
- package/src/adapters/dashboard/web/flow.ts +14 -0
- package/src/adapters/dashboard/web/lanes.ts +10 -0
- package/src/adapters/dashboard/web/narrate.ts +88 -2
- package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
- package/src/adapters/dashboard/web/pages/health/sections/checks.js +2 -0
- package/src/adapters/dashboard/web/pages/health/sections/wake.js +3 -1
- package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
- package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
- package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
- package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
- package/src/adapters/dashboard/web/server.ts +0 -5
- package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
- package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
- package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
- package/src/adapters/dashboard/web/views/health.ts +21 -3
- package/src/adapters/dashboard/web/views/search.ts +4 -45
- package/src/adapters/dashboard/web/views.ts +2 -2
- package/src/adapters/fired.ts +430 -28
- package/src/adapters/host-wiring.ts +300 -0
- package/src/adapters/hosts.ts +11 -0
- package/src/adapters/lifecycle.ts +42 -2
- package/src/adapters/log/index.ts +9 -0
- package/src/adapters/mcp/CONTRACT.md +151 -11
- package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
- package/src/adapters/mcp/NOTES.md +313 -1
- package/src/adapters/mcp/bin/serve.ts +74 -1
- package/src/adapters/mcp/deliberate.ts +169 -651
- package/src/adapters/mcp/facts.ts +1094 -0
- package/src/adapters/mcp/index.ts +25 -7
- package/src/adapters/mcp/meaning.ts +1610 -0
- package/src/adapters/mcp/server.ts +835 -150
- package/src/adapters/mcp/stdio.ts +3 -1
- package/src/adapters/mcp/stood-down.ts +51 -0
- package/src/adapters/mcp/tools.ts +167 -41
- package/src/adapters/plugin-run.sh +133 -0
- package/src/adapters/plugin.ts +329 -0
- package/src/adapters/sessions.ts +18 -4
- package/src/core/associate/CONTRACT.md +2 -1
- package/src/core/associate/INTERFACE-GAPS.md +6 -1
- package/src/core/associate/NOTES.md +45 -0
- package/src/core/briefing.ts +12 -3
- package/src/core/contradictions.ts +184 -0
- package/src/core/counterpart.ts +797 -51
- package/src/core/dream/CONTRACT.md +36 -4
- package/src/core/dream/INTERFACE-GAPS.md +29 -6
- package/src/core/dream/NOTES.md +107 -0
- package/src/core/dream/feeling-weeks.ts +198 -0
- package/src/core/dream/index.ts +109 -18
- package/src/core/dream/reflect.ts +346 -87
- package/src/core/dream/tunables.ts +24 -4
- package/src/core/encode/INTERFACE-GAPS.md +3 -1
- package/src/core/encode/NOTES.md +7 -0
- package/src/core/encode/words.ts +45 -0
- package/src/core/fit/INTERFACE-GAPS.md +8 -2
- package/src/core/fit/NOTES.md +39 -1
- package/src/core/fit/index.ts +40 -0
- package/src/core/handoff/CONTRACT.md +37 -2
- package/src/core/handoff/INTERFACE-GAPS.md +10 -0
- package/src/core/handoff/NOTES.md +72 -0
- package/src/core/handoff/index.ts +214 -12
- package/src/core/handoff/last-here.ts +6 -4
- package/src/core/mint.ts +12 -2
- package/src/core/physics/CONTRACT.md +14 -2
- package/src/core/physics/NOTES.md +33 -1
- package/src/core/physics/index.ts +28 -5
- package/src/core/prospective/CONTRACT.md +45 -6
- package/src/core/prospective/INTERFACE-GAPS.md +4 -0
- package/src/core/prospective/NOTES.md +138 -0
- package/src/core/prospective/derive.ts +33 -5
- package/src/core/prospective/index.ts +90 -5
- package/src/core/prospective/windows.ts +72 -1
- package/src/core/recall/CONTRACT.md +31 -12
- package/src/core/recall/INTERFACE-GAPS.md +28 -4
- package/src/core/recall/NOTES.md +70 -1
- package/src/core/recall/feeling-ask.ts +10 -1
- package/src/core/recall/index.ts +3 -1
- package/src/core/recall/probe.ts +58 -0
- package/src/core/recall/session.ts +46 -2
- package/src/core/recall/time-ask.ts +487 -0
- package/src/core/remember/CONTRACT.md +4 -1
- package/src/core/remember/INTERFACE-GAPS.md +9 -1
- package/src/core/remember/NOTES.md +8 -0
- package/src/core/remember/proposals.ts +47 -5
- package/src/core/revision.ts +18 -1
- package/src/core/schemas/CONTRACT.md +21 -1
- package/src/core/schemas/INTERFACE-GAPS.md +20 -2
- package/src/core/schemas/NOTES.md +144 -0
- package/src/core/schemas/aliases.ts +55 -5
- package/src/core/schemas/index.ts +93 -1
- package/src/core/schemas/types.ts +2 -0
- package/src/core/self/CONTRACT.md +32 -5
- package/src/core/self/INTERFACE-GAPS.md +7 -2
- package/src/core/self/NOTES.md +102 -1
- package/src/core/self/behind.ts +43 -3
- package/src/core/self/briefing.ts +12 -2
- package/src/core/self/chapter-address.ts +254 -0
- package/src/core/self/episodes.ts +27 -0
- package/src/core/self/index.ts +83 -8
- package/src/core/self/page.ts +88 -0
- package/src/core/self/tunables.ts +5 -0
- package/src/core/self/work.ts +35 -2
- package/src/core/self/writer.ts +30 -0
- package/src/core/sleep/INTERFACE-GAPS.md +22 -3
- package/src/core/sleep/NOTES.md +20 -1
- package/src/core/sleep/consolidate.ts +59 -7
- package/src/core/sleep/index.ts +3 -0
- package/src/core/sleep/prune.ts +6 -2
- package/src/core/sleep/types.ts +7 -0
- package/src/core/store/CONTRACT.md +16 -0
- package/src/core/store/NOTES.md +66 -0
- package/src/core/store/feelings.ts +14 -1
- package/src/core/store/index.ts +483 -16
- package/src/core/store/operational.ts +95 -2
- package/src/core/store/owner-op-seam.ts +23 -0
- package/src/core/time.ts +152 -0
- package/tools/install-loop/run.sh +48 -12
- package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
|
@@ -0,0 +1,1094 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FACTS MODE — `recall` with `mode: "facts"` (Release B of deliberate recall,
|
|
3
|
+
* 2026-10-03; design `~/counterparts-notes/2026-10-03-deliberate-recall-
|
|
4
|
+
* design.md`, held lightly and revisited after a few days of use).
|
|
5
|
+
*
|
|
6
|
+
* A question asked on purpose gets EVERY memory it matches, by any of four
|
|
7
|
+
* ways, ranked by how strongly it matched:
|
|
8
|
+
*
|
|
9
|
+
* - **words** — every memory sharing a content word with the question (the
|
|
10
|
+
* token index, every hit: `store.search` with a limit of the word's own
|
|
11
|
+
* document count), each word weighted by its rarity (`cues.ts#
|
|
12
|
+
* informativeness`); the score is the share of the question's rarity a
|
|
13
|
+
* memory holds, shaded by how much of it (BM25 within the word);
|
|
14
|
+
* - **meaning** — the `FACTS_MEANING_CAP` nearest by the question's
|
|
15
|
+
* embedding, above the floor ambient recall uses for this embedder
|
|
16
|
+
* (`recall/tunables.ts#semanticTuning`, inline path);
|
|
17
|
+
* - **subjects** — every memory linked to an entity card the question names
|
|
18
|
+
* (`schemas#subjectsIn` → `store.memoriesNaming`, the v12 links), weighted
|
|
19
|
+
* by how rare the card is;
|
|
20
|
+
* - **time** — a window the question names (`recall/time-ask.ts`) FILTERS:
|
|
21
|
+
* only memories inside it, by when the thing happened (`occurred_on`) or,
|
|
22
|
+
* with no event date, when it was learned (and the line says which), plus a
|
|
23
|
+
* count of the matches outside it. A question that is only time ("what
|
|
24
|
+
* happened last week?") answers with everything in the window. An event
|
|
25
|
+
* anchor ("around the cut-over") is resolved by searching the phrase and
|
|
26
|
+
* taking the top match's date, shown in the header; "the last session" is
|
|
27
|
+
* the session the wake's "Last here" names (else the newest here), and its
|
|
28
|
+
* own rows lead.
|
|
29
|
+
*
|
|
30
|
+
* A memory matched several ways scores the sum, so it ranks higher; recency
|
|
31
|
+
* only breaks ties. Nothing here calls `Recall.build()` — this is its own
|
|
32
|
+
* path, with its own pool and its own ranking, and tuning ambient recall does
|
|
33
|
+
* not move it (nor the reverse).
|
|
34
|
+
*
|
|
35
|
+
* REBUILT HERE, not inherited from the ambient path: a chapter and its own
|
|
36
|
+
* copy are one result (the chapter); a near-duplicate of a result already
|
|
37
|
+
* kept is left out (`NEAR_DUPLICATE`, token overlap); the self page and the
|
|
38
|
+
* handoffs are never results; a chapter is labeled journal; a confidential
|
|
39
|
+
* memory is left out of a non-owner's list, silently (counted on the durable
|
|
40
|
+
* row only).
|
|
41
|
+
*
|
|
42
|
+
* FOLDING. Each result is the CURRENT version of a fact. Earlier versions are
|
|
43
|
+
* folded under it: in-place revisions (`versions` rows whose words differ)
|
|
44
|
+
* and memories it settled as `changed` (a contradiction pair) — an earlier
|
|
45
|
+
* one that matched brings its current one in as the result. Corrected
|
|
46
|
+
* versions are hidden and counted. An `open` pair says "disagrees with", an
|
|
47
|
+
* unsettled older one "may be out of date".
|
|
48
|
+
*
|
|
49
|
+
* FADED. A matched memory that has kept `deliberate.ts#FADED_RETAINED` of
|
|
50
|
+
* its strength or less (it was not used for a long while; `hasFaded`, the
|
|
51
|
+
* rule meaning mode uses too) is listed AFTER the main results, a title line
|
|
52
|
+
* each, labeled faded — never in the main slots. Journal chapters and schemas
|
|
53
|
+
* never fade here. Opening one by id credits it, which brings it back.
|
|
54
|
+
*
|
|
55
|
+
* THE ANSWER (what `renderFacts` writes; the server ships it as `answer`):
|
|
56
|
+
*
|
|
57
|
+
* 12 match · showing 10 · 2 more → page 2 · 3 faded, listed after
|
|
58
|
+
* time: last week → 09-21..09-27, stretched 2 days each side · 4 more match outside it
|
|
59
|
+
* about: Han
|
|
60
|
+
* may not be everything: meaning search hit its cap (100) · 3 weak matches not shown
|
|
61
|
+
*
|
|
62
|
+
* 1. Gym moved to 6am · mem_… · words, subject
|
|
63
|
+
* you said · done · happened 09-28
|
|
64
|
+
* learned 09-28 in ~/counterparts · session a1b2c3d4 · CURRENT
|
|
65
|
+
* earlier: "gym at 7" (learned 09-12), changed 09-28 · mem_…
|
|
66
|
+
* <the body whole when short, else a 300-character excerpt>
|
|
67
|
+
*
|
|
68
|
+
* faded (3):
|
|
69
|
+
* - Old gym schedule · 2026-06-02 · mem_… · faded
|
|
70
|
+
*
|
|
71
|
+
* The header counts DISTINCT facts (folded versions are not counted apart).
|
|
72
|
+
* "may not be everything" is said only when a cap cut or a weak tail was left
|
|
73
|
+
* out, with the reason. `page: N` pages in a stable order. Unknown fields say
|
|
74
|
+
* so ("speaker unknown"): most rows predate v12. The whole answer stays under
|
|
75
|
+
* `RECALL_RESULT_CHARS`.
|
|
76
|
+
*
|
|
77
|
+
* Pure: reads only, writes nothing — the console's `ask` runs it on a
|
|
78
|
+
* read-only store. NO MODEL CALL.
|
|
79
|
+
*/
|
|
80
|
+
import type { Counterpart } from "../../core/counterpart.js";
|
|
81
|
+
import { sessionsHere } from "../../core/coverage/index.js";
|
|
82
|
+
import { chaptersOf } from "../../core/handoff/last-here.js";
|
|
83
|
+
|
|
84
|
+
import {
|
|
85
|
+
OPEN_END,
|
|
86
|
+
OPEN_START,
|
|
87
|
+
informativeness,
|
|
88
|
+
localKey,
|
|
89
|
+
readTimeAsk,
|
|
90
|
+
semanticTuning,
|
|
91
|
+
} from "../../core/recall/index.js";
|
|
92
|
+
import type { DayWindow, FeelingWhose, SemanticSource, TimeAsk } from "../../core/recall/index.js";
|
|
93
|
+
import { STOPWORDS } from "../../core/recall/reference.js";
|
|
94
|
+
import { tokenize } from "../../core/store/index.js";
|
|
95
|
+
import type { ContradictionRow, RecallRow } from "../../core/store/index.js";
|
|
96
|
+
import { addDays, localDate, parseCalendarDate } from "../../core/time.js";
|
|
97
|
+
import { UNBOUND_SESSION } from "../../core/types.js";
|
|
98
|
+
import {
|
|
99
|
+
RECALL_EXCERPT_CHARS,
|
|
100
|
+
RECALL_MAX_IDS,
|
|
101
|
+
RECALL_RESULT_CHARS,
|
|
102
|
+
cutExcerpt,
|
|
103
|
+
hasFaded,
|
|
104
|
+
nightlyMade,
|
|
105
|
+
provenanceParts,
|
|
106
|
+
} from "./deliberate.js";
|
|
107
|
+
|
|
108
|
+
// ── the working defaults (held lightly; revisit after a few days of use) ────
|
|
109
|
+
|
|
110
|
+
/** Results on one page. The design's judgment call; tune at the revisit. */
|
|
111
|
+
export const FACTS_PAGE_SIZE = 10;
|
|
112
|
+
/** The meaning search's cap: the only one of the four ways that is capped. */
|
|
113
|
+
export const FACTS_MEANING_CAP = 100;
|
|
114
|
+
/** Faded title lines on one page (faded: `deliberate.ts#hasFaded`, shared with meaning mode). */
|
|
115
|
+
export const FACTS_FADED_LINES = 5;
|
|
116
|
+
/**
|
|
117
|
+
* WEAK: a match scoring below this share of the best match's score is left
|
|
118
|
+
* out, and counted ("3 weak matches not shown"). Not applied to a question
|
|
119
|
+
* that is only a time window, where every row in it matched the same way.
|
|
120
|
+
*/
|
|
121
|
+
export const FACTS_WEAK_FRACTION = 0.2;
|
|
122
|
+
/** Earlier versions shown under a result; the rest are counted. */
|
|
123
|
+
export const FACTS_EARLIER_SHOWN = 2;
|
|
124
|
+
/** Token overlap at or above which two results are near-duplicates (the gate's `NEAR_DUPLICATE`). */
|
|
125
|
+
export const FACTS_NEAR_DUPLICATE = 0.85;
|
|
126
|
+
/** How far an event anchor's window reaches each side of its date. */
|
|
127
|
+
export const FACTS_ANCHOR_DAYS = 2;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The journal label, once per answer that shows a chapter (owner ruling
|
|
131
|
+
* 2026-09-04, §I14: a chapter stays recallable and is never presented as a
|
|
132
|
+
* memory; `deliberate.ts#JOURNAL_GLOSS` says the same on the id path).
|
|
133
|
+
*/
|
|
134
|
+
export const FACTS_JOURNAL_GLOSS =
|
|
135
|
+
"[journal] = a chapter: the first-person account memories were made from, not a memory — outside decay, dedup and the prune, and not a claim about the world the way a memory is.";
|
|
136
|
+
|
|
137
|
+
/** Words that ask nothing of their own in a question (beyond `reference.ts#STOPWORDS`). */
|
|
138
|
+
const ASKS_NOTHING = new Set([
|
|
139
|
+
"remember", "remembered", "recall", "tell", "happened", "happen", "happens", "decide", "decided",
|
|
140
|
+
"anything", "something", "everything", "ever", "else", "did", "does", "do", "talk", "talked",
|
|
141
|
+
"discuss", "discussed", "mention", "mentioned", "about", "whats", "who", "whom", "whose",
|
|
142
|
+
]);
|
|
143
|
+
|
|
144
|
+
/** The words only a facts question's own wording carries, never its content. */
|
|
145
|
+
function contentTokens(text: string): string[] {
|
|
146
|
+
return [...new Set(tokenize(text))].filter((t) => !STOPWORDS.has(t) && !ASKS_NOTHING.has(t) && !/^\d{1,2}$/.test(t));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* What facts mode reads off the counterpart — a `Counterpart` is one; a tool
|
|
151
|
+
* holding only a store and a recall (`tools/recall-bench`) can pass those, and
|
|
152
|
+
* the subject way and "the last session" then answer nothing.
|
|
153
|
+
*/
|
|
154
|
+
export interface FactsSource {
|
|
155
|
+
readonly store: Counterpart["store"];
|
|
156
|
+
readonly recall: { readonly tunables: Counterpart["recall"]["tunables"] };
|
|
157
|
+
readonly schemas?: Pick<Counterpart["schemas"], "subjectsIn" | "aliasIndex">;
|
|
158
|
+
readonly spans?: Counterpart["spans"];
|
|
159
|
+
readonly chaptersHereFor?: Counterpart["chaptersHereFor"];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export interface FactsContext {
|
|
163
|
+
readonly counterpart: FactsSource;
|
|
164
|
+
readonly sessionId: string;
|
|
165
|
+
/** The owner's own session? Confidentiality turns on this and nothing else. */
|
|
166
|
+
readonly owner: boolean;
|
|
167
|
+
/** The asking session's directory, for "the last session"; none at the console. */
|
|
168
|
+
readonly scope?: string;
|
|
169
|
+
/** The question embedded in line; null when it could not be. */
|
|
170
|
+
readonly vector: readonly number[] | null;
|
|
171
|
+
readonly semantic: SemanticSource;
|
|
172
|
+
/** Not read by facts mode; here so one context object serves both modes. */
|
|
173
|
+
readonly asker?: FeelingWhose;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export type FactWay = "words" | "meaning" | "subject" | "time" | "session";
|
|
177
|
+
|
|
178
|
+
export interface EarlierVersion {
|
|
179
|
+
/** Its title, or the start of its words. */
|
|
180
|
+
readonly text: string;
|
|
181
|
+
readonly learned: string | null;
|
|
182
|
+
/** When it stopped being current, `YYYY-MM-DD` in the store's zone. */
|
|
183
|
+
readonly changed: string | null;
|
|
184
|
+
/** A separate memory (a `changed` pair) has an id to open; an in-place version has none. */
|
|
185
|
+
readonly id?: string;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export interface FactItem {
|
|
189
|
+
readonly id: string;
|
|
190
|
+
readonly title: string | null;
|
|
191
|
+
/** The title, or the start of the words when there is none. */
|
|
192
|
+
readonly line: string;
|
|
193
|
+
readonly kind: string;
|
|
194
|
+
readonly journal: boolean;
|
|
195
|
+
/** For a journal entry: which chapter the excerpt is from, of how many. */
|
|
196
|
+
readonly chapter?: { readonly n: number; readonly of: number };
|
|
197
|
+
/** The words: whole when short, else an excerpt. */
|
|
198
|
+
readonly body: string;
|
|
199
|
+
readonly bodyChars: number;
|
|
200
|
+
readonly whole: boolean;
|
|
201
|
+
readonly saidBy: string | null;
|
|
202
|
+
readonly status: string | null;
|
|
203
|
+
readonly occurredOn: string | null;
|
|
204
|
+
/** When it was learned, `YYYY-MM-DD` in the store's zone (a chapter: when first written). */
|
|
205
|
+
readonly learned: string | null;
|
|
206
|
+
/** A chapter's latest write, when later than `learned`. */
|
|
207
|
+
readonly lastWritten?: string | null;
|
|
208
|
+
readonly where: string | null;
|
|
209
|
+
readonly who: string | null;
|
|
210
|
+
/** True unless it is an earlier version shown on its own (its current one not shown). */
|
|
211
|
+
readonly current: boolean;
|
|
212
|
+
/** For an earlier version shown on its own: the current one's id ("a later version" when this asker may not be told it). */
|
|
213
|
+
readonly now?: string;
|
|
214
|
+
readonly earlier: readonly EarlierVersion[];
|
|
215
|
+
readonly earlierMore: number;
|
|
216
|
+
/** Corrected (wrong) versions of it, hidden. */
|
|
217
|
+
readonly corrected: number;
|
|
218
|
+
/** Pair labels besides earlier/corrected: disagrees with, unsettled. */
|
|
219
|
+
readonly standing: readonly string[];
|
|
220
|
+
readonly ways: readonly FactWay[];
|
|
221
|
+
/** Under a time window: whether its event date or (none recorded) its learned date put it there. */
|
|
222
|
+
readonly timeBy?: "event" | "learned";
|
|
223
|
+
readonly score: number;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export interface FadedLine {
|
|
227
|
+
readonly id: string;
|
|
228
|
+
readonly line: string;
|
|
229
|
+
readonly date: string | null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export interface FactsTime {
|
|
233
|
+
readonly cue: string;
|
|
234
|
+
readonly said: DayWindow | null;
|
|
235
|
+
readonly window: DayWindow | null;
|
|
236
|
+
readonly stretch: number;
|
|
237
|
+
/** An event or the last session, resolved — or `date: null` when it could not be. */
|
|
238
|
+
readonly anchor?: {
|
|
239
|
+
readonly kind: "event" | "session";
|
|
240
|
+
readonly phrase: string;
|
|
241
|
+
readonly date: string | null;
|
|
242
|
+
readonly id?: string;
|
|
243
|
+
readonly session?: string;
|
|
244
|
+
};
|
|
245
|
+
/** Matches that fell outside the window (the same ways, not weak). */
|
|
246
|
+
readonly outside: number;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export interface FactsResult {
|
|
250
|
+
readonly mode: "facts";
|
|
251
|
+
readonly reason: "answered" | "nothing-came";
|
|
252
|
+
readonly semantic: SemanticSource;
|
|
253
|
+
/** Distinct facts that matched (main list, folded versions not counted apart). */
|
|
254
|
+
readonly matched: number;
|
|
255
|
+
readonly page: number;
|
|
256
|
+
readonly pages: number;
|
|
257
|
+
/** The page's results, in order. */
|
|
258
|
+
readonly memories: readonly FactItem[];
|
|
259
|
+
readonly faded: readonly FadedLine[];
|
|
260
|
+
readonly fadedTotal: number;
|
|
261
|
+
readonly weak: number;
|
|
262
|
+
readonly duplicates: number;
|
|
263
|
+
readonly meaningCapped: boolean;
|
|
264
|
+
readonly time: FactsTime | null;
|
|
265
|
+
readonly subjects: readonly { readonly id: string; readonly name: string }[];
|
|
266
|
+
/** Every candidate any way reached, before the window, folding and the weak tail. */
|
|
267
|
+
readonly considered: number;
|
|
268
|
+
/** Live rows in the store. */
|
|
269
|
+
readonly storeSize: number;
|
|
270
|
+
/** What kept a matched row out, counted — for the durable row only, never the wire. */
|
|
271
|
+
readonly blockedBy: Readonly<Record<string, number>>;
|
|
272
|
+
/** Today in the store's zone — what the answer's short dates are relative to. */
|
|
273
|
+
readonly today: string;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
interface Candidate {
|
|
277
|
+
readonly id: string;
|
|
278
|
+
score: number;
|
|
279
|
+
readonly ways: Set<FactWay>;
|
|
280
|
+
timeBy?: "event" | "learned";
|
|
281
|
+
/** Earlier memories (changed pairs) folded into this one because they matched. */
|
|
282
|
+
readonly foldedEarlier: Set<string>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The row's learned moment and dates in the store's zone. */
|
|
286
|
+
function learnedOf(row: RecallRow, zone: string): string | null {
|
|
287
|
+
if (row.created_at !== null && row.created_at > 0) return localDate(row.created_at, zone);
|
|
288
|
+
return row.learned_on.length > 0 ? row.learned_on : null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function metaOf(row: RecallRow): Record<string, unknown> {
|
|
292
|
+
if (row.meta === null || row.meta.length === 0) return {};
|
|
293
|
+
try {
|
|
294
|
+
const m = JSON.parse(row.meta) as unknown;
|
|
295
|
+
return m !== null && typeof m === "object" ? (m as Record<string, unknown>) : {};
|
|
296
|
+
} catch {
|
|
297
|
+
return {};
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Never a result: the self page (delivered whole at the wake) and a handoff (a directory's pointer). */
|
|
302
|
+
function neverAResult(row: RecallRow): boolean {
|
|
303
|
+
if (row.type !== "schema") return false;
|
|
304
|
+
const role = metaOf(row)["role"];
|
|
305
|
+
return role === "page" || role === "handoff";
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function sessionOf(row: RecallRow): string | null {
|
|
309
|
+
if (row.origin_session !== null && row.origin_session.length > 0) return row.origin_session;
|
|
310
|
+
if (row.type === "episode") {
|
|
311
|
+
const s = metaOf(row)["sessionId"];
|
|
312
|
+
return typeof s === "string" ? s : null;
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Is the row inside the window — by its event date when it has one, else by
|
|
319
|
+
* when it was learned (a chapter: anywhere between its first and latest
|
|
320
|
+
* write)? A clock window also asks the learned moment's time of day.
|
|
321
|
+
*/
|
|
322
|
+
function inWindow(
|
|
323
|
+
row: RecallRow,
|
|
324
|
+
window: DayWindow,
|
|
325
|
+
clock: TimeAsk["clock"],
|
|
326
|
+
zone: string,
|
|
327
|
+
chapterDates?: (id: string) => readonly string[],
|
|
328
|
+
): "event" | "learned" | null {
|
|
329
|
+
// A chapter is also inside the window when one of its headings is dated
|
|
330
|
+
// there: an episode written up the next morning names the day it was about.
|
|
331
|
+
if (row.type === "episode" && chapterDates !== undefined && clock === null) {
|
|
332
|
+
if (chapterDates(row.id).some((d) => d >= window.from && d <= window.to)) return "learned";
|
|
333
|
+
}
|
|
334
|
+
if (row.occurred_on !== null) {
|
|
335
|
+
const c = parseCalendarDate(row.occurred_on);
|
|
336
|
+
if (c !== null) return c.first <= window.to && c.last >= window.from ? "event" : null;
|
|
337
|
+
}
|
|
338
|
+
const first = row.created_at;
|
|
339
|
+
if (first === null || first <= 0) {
|
|
340
|
+
const d = row.learned_on;
|
|
341
|
+
return d.length > 0 && d >= window.from && d <= window.to ? "learned" : null;
|
|
342
|
+
}
|
|
343
|
+
const last = row.type === "episode" && row.updated_at !== null ? Math.max(first, row.updated_at) : first;
|
|
344
|
+
if (clock !== null) {
|
|
345
|
+
return localKey(last, zone) >= clock.from && localKey(first, zone) <= clock.to ? "learned" : null;
|
|
346
|
+
}
|
|
347
|
+
return localDate(last, zone) >= window.from && localDate(first, zone) <= window.to ? "learned" : null;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** A date for a header or a line: `MM-DD` this year, else the whole date. */
|
|
351
|
+
export function shortDate(ymd: string | null, today: string): string {
|
|
352
|
+
if (ymd === null || ymd.length === 0) return "";
|
|
353
|
+
const c = parseCalendarDate(ymd);
|
|
354
|
+
if (c === null) return ymd;
|
|
355
|
+
const year = today.slice(0, 4);
|
|
356
|
+
const one = (d: string): string => (d.slice(0, 4) === year ? d.slice(5) : d);
|
|
357
|
+
if (c.precision === "day") return one(c.first);
|
|
358
|
+
if (c.precision === "range") return `${one(c.first)}..${one(c.last)}`;
|
|
359
|
+
return c.text;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function plainLine(text: string, max: number): string {
|
|
363
|
+
const flat = text
|
|
364
|
+
.replace(/^[ \t]*#{1,6}[ \t]+/gm, "")
|
|
365
|
+
.replace(/\s+/g, " ")
|
|
366
|
+
.trim();
|
|
367
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
|
|
371
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
372
|
+
let inter = 0;
|
|
373
|
+
for (const t of a) if (b.has(t)) inter += 1;
|
|
374
|
+
return inter / (a.size + b.size - inter);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* THE FACTS ANSWER to one question. Reads only; never throws on a row that
|
|
379
|
+
* will not read (that row is skipped).
|
|
380
|
+
*/
|
|
381
|
+
export function factsRecall(ctx: FactsContext, question: string, opts: { page?: number } = {}): FactsResult {
|
|
382
|
+
const store = ctx.counterpart.store;
|
|
383
|
+
const zone = store.zone();
|
|
384
|
+
const now = store.now();
|
|
385
|
+
const today = localDate(now, zone);
|
|
386
|
+
const day = store.livedDay();
|
|
387
|
+
const page = opts.page !== undefined && Number.isInteger(opts.page) && opts.page >= 1 ? opts.page : 1;
|
|
388
|
+
|
|
389
|
+
// ── the rows, once ──────────────────────────────────────────────────────
|
|
390
|
+
const denied = new Set(safe(() => store.deniedIds(), [] as string[]));
|
|
391
|
+
const rows = new Map<string, RecallRow>();
|
|
392
|
+
for (const r of safe(() => store.recallRows(), [] as RecallRow[])) {
|
|
393
|
+
if (denied.has(r.id)) continue;
|
|
394
|
+
rows.set(r.id, r);
|
|
395
|
+
}
|
|
396
|
+
const storeSize = rows.size;
|
|
397
|
+
const blockedBy: Record<string, number> = {};
|
|
398
|
+
const blocked = (why: string): void => {
|
|
399
|
+
blockedBy[why] = (blockedBy[why] ?? 0) + 1;
|
|
400
|
+
};
|
|
401
|
+
/** A row that may be a result for this asker. */
|
|
402
|
+
const visible = (id: string): RecallRow | undefined => {
|
|
403
|
+
const r = rows.get(id);
|
|
404
|
+
if (r === undefined || neverAResult(r)) return undefined;
|
|
405
|
+
if (!ctx.owner && r.confidential === 1) return undefined;
|
|
406
|
+
return r;
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
// ── time ────────────────────────────────────────────────────────────────
|
|
410
|
+
const time = safe(() => readTimeAsk(question, { now, zone }), null);
|
|
411
|
+
let rest = time?.rest ?? question;
|
|
412
|
+
let window: DayWindow | null = time?.window ?? null;
|
|
413
|
+
let anchor: FactsTime["anchor"];
|
|
414
|
+
let anchorSession: string | null = null;
|
|
415
|
+
let anchorStretch: Stretch | null = null;
|
|
416
|
+
|
|
417
|
+
const words = (text: string): { scores: Map<string, number>; idfTotal: number; tokens: string[] } => {
|
|
418
|
+
const tokens = contentTokens(text);
|
|
419
|
+
const df = safe(() => store.docFrequency(tokens), new Map<string, number>());
|
|
420
|
+
const scores = new Map<string, number>();
|
|
421
|
+
let idfTotal = 0;
|
|
422
|
+
for (const tok of tokens) {
|
|
423
|
+
const n = df.get(tok) ?? 0;
|
|
424
|
+
const idf = informativeness(n, storeSize);
|
|
425
|
+
if (n <= 0 || idf <= 0) continue;
|
|
426
|
+
idfTotal += idf;
|
|
427
|
+
const hits = safe(() => store.search(tok, n), []);
|
|
428
|
+
const top = hits[0]?.score ?? 0;
|
|
429
|
+
for (const h of hits) {
|
|
430
|
+
const shade = top > 0 ? 0.5 + 0.5 * (h.score / top) : 1;
|
|
431
|
+
scores.set(h.id, (scores.get(h.id) ?? 0) + idf * shade);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (idfTotal > 0) for (const [id, s] of scores) scores.set(id, s / idfTotal);
|
|
435
|
+
return { scores, idfTotal, tokens };
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
if (time?.anchor?.kind === "event") {
|
|
439
|
+
const phrase = time.anchor.phrase;
|
|
440
|
+
const found = words(phrase).scores;
|
|
441
|
+
let best: { id: string; score: number } | null = null;
|
|
442
|
+
for (const [id, score] of found) {
|
|
443
|
+
if (visible(id) === undefined) continue;
|
|
444
|
+
if (best === null || score > best.score || (score === best.score && id < best.id)) best = { id, score };
|
|
445
|
+
}
|
|
446
|
+
const row = best === null ? undefined : rows.get(best.id);
|
|
447
|
+
const date = row === undefined ? null : (parseCalendarDate(row.occurred_on ?? "")?.first ?? learnedOf(row, zone));
|
|
448
|
+
if (date !== null && best !== null) {
|
|
449
|
+
window = { from: addDays(date, -FACTS_ANCHOR_DAYS), to: addDays(date, FACTS_ANCHOR_DAYS) };
|
|
450
|
+
anchor = { kind: "event", phrase, date, id: best.id };
|
|
451
|
+
} else {
|
|
452
|
+
// Nothing names it: the phrase stays part of the question, and nothing is filtered by time.
|
|
453
|
+
anchor = { kind: "event", phrase, date: null };
|
|
454
|
+
rest = question;
|
|
455
|
+
}
|
|
456
|
+
} else if (time?.anchor?.kind === "session") {
|
|
457
|
+
const found = lastSession(ctx, rows, zone);
|
|
458
|
+
if (found !== null) {
|
|
459
|
+
window = { from: found.from, to: found.to };
|
|
460
|
+
anchorSession = found.session;
|
|
461
|
+
anchorStretch = found.stretch;
|
|
462
|
+
anchor = { kind: "session", phrase: time.cue, date: found.from === found.to ? found.from : `${found.from}..${found.to}`, session: found.session };
|
|
463
|
+
} else {
|
|
464
|
+
anchor = { kind: "session", phrase: time.cue, date: null };
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ── the four ways ───────────────────────────────────────────────────────
|
|
469
|
+
const w = words(rest);
|
|
470
|
+
const subjectIds = safe(() => ctx.counterpart.schemas?.subjectsIn(rest) ?? [], [] as string[]);
|
|
471
|
+
const subjects: { id: string; name: string }[] = [];
|
|
472
|
+
const subjectScore = new Map<string, number>();
|
|
473
|
+
const unit = Math.max(w.idfTotal, informativeness(1, storeSize), 1e-9);
|
|
474
|
+
for (const s of subjectIds) {
|
|
475
|
+
const members = safe(() => store.memoriesNaming(s), [] as string[]);
|
|
476
|
+
const name = safe(() => ctx.counterpart.schemas?.aliasIndex().termsFor(s)?.name ?? null, null) ?? s;
|
|
477
|
+
subjects.push({ id: s, name });
|
|
478
|
+
if (members.length === 0) continue;
|
|
479
|
+
const weight = Math.min(1, informativeness(members.length, storeSize) / unit);
|
|
480
|
+
for (const m of members) subjectScore.set(m, Math.max(subjectScore.get(m) ?? 0, Math.max(weight, 0.05)));
|
|
481
|
+
}
|
|
482
|
+
// A question that is only time asks for the window, and its meaning is
|
|
483
|
+
// "what happened": the embedding of that would rank noise.
|
|
484
|
+
const onlyTime = window !== null && w.tokens.length === 0 && subjectIds.length === 0;
|
|
485
|
+
const meaningScore = new Map<string, number>();
|
|
486
|
+
let meaningCapped = false;
|
|
487
|
+
if (ctx.vector !== null && ctx.vector.length > 0 && !onlyTime) {
|
|
488
|
+
const hits = safe(() => store.nearestTo(ctx.vector as number[], FACTS_MEANING_CAP), []);
|
|
489
|
+
const tuning = semanticTuning(ctx.counterpart.recall.tunables, safe(() => store.rankingIdentity(), null), "inline");
|
|
490
|
+
const floor = tuning.floor;
|
|
491
|
+
for (const h of hits) {
|
|
492
|
+
if (h.score < floor) continue;
|
|
493
|
+
meaningScore.set(h.id, floor >= 1 ? h.score : (h.score - floor) / (1 - floor));
|
|
494
|
+
}
|
|
495
|
+
const last = hits[hits.length - 1];
|
|
496
|
+
meaningCapped = hits.length >= FACTS_MEANING_CAP && last !== undefined && last.score >= floor;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const pool = new Map<string, Candidate>();
|
|
500
|
+
const add = (id: string, way: FactWay, score: number): void => {
|
|
501
|
+
let c = pool.get(id);
|
|
502
|
+
if (c === undefined) {
|
|
503
|
+
c = { id, score: 0, ways: new Set(), foldedEarlier: new Set() };
|
|
504
|
+
pool.set(id, c);
|
|
505
|
+
}
|
|
506
|
+
c.score += score;
|
|
507
|
+
c.ways.add(way);
|
|
508
|
+
};
|
|
509
|
+
for (const [id, s] of w.scores) add(id, "words", s);
|
|
510
|
+
for (const [id, s] of meaningScore) add(id, "meaning", s);
|
|
511
|
+
for (const [id, s] of subjectScore) add(id, "subject", s);
|
|
512
|
+
const datesHeld = new Map<string, readonly string[]>();
|
|
513
|
+
const chapterDates = (id: string): readonly string[] => {
|
|
514
|
+
const held = datesHeld.get(id);
|
|
515
|
+
if (held !== undefined) return held;
|
|
516
|
+
const dates = safe(
|
|
517
|
+
() => chaptersOf(store.readProse(id).body).map((ch) => ch.date).filter((d): d is string => d !== null),
|
|
518
|
+
[] as string[],
|
|
519
|
+
);
|
|
520
|
+
datesHeld.set(id, dates);
|
|
521
|
+
return dates;
|
|
522
|
+
};
|
|
523
|
+
if (onlyTime && window !== null) {
|
|
524
|
+
for (const [id, r] of rows) {
|
|
525
|
+
if (r.type === "schema") continue;
|
|
526
|
+
if (inWindow(r, window, time?.clock ?? null, zone, chapterDates) !== null) add(id, "time", 0.1);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
/** Is this row the anchor session's own — its words, not the nightly run's? */
|
|
530
|
+
const ofAnchorSession = (r: RecallRow): boolean => {
|
|
531
|
+
if (anchorSession === null || nightlyMade(r) !== null) return false;
|
|
532
|
+
const s = sessionOf(r);
|
|
533
|
+
if (s === anchorSession) return true;
|
|
534
|
+
// A note from before the server knew its session, placed by when it was
|
|
535
|
+
// written: in this directory, inside the session's stretch and no other's.
|
|
536
|
+
return s === UNBOUND_SESSION && anchorStretch !== null && placedIn(r, anchorStretch);
|
|
537
|
+
};
|
|
538
|
+
const considered = pool.size;
|
|
539
|
+
|
|
540
|
+
// ── visibility, the window, the session ────────────────────────────────
|
|
541
|
+
// Matches outside the window are held apart, not dropped: they are folded
|
|
542
|
+
// and weighed as the results are, so the count says "N more match outside
|
|
543
|
+
// it" in distinct facts, without the weak tail (review of #323).
|
|
544
|
+
const beyond = new Map<string, Candidate>();
|
|
545
|
+
for (const [id, c] of [...pool]) {
|
|
546
|
+
const r = rows.get(id);
|
|
547
|
+
if (r === undefined || neverAResult(r)) {
|
|
548
|
+
pool.delete(id);
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
if (!ctx.owner && r.confidential === 1) {
|
|
552
|
+
blocked("confidential-withheld");
|
|
553
|
+
pool.delete(id);
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (window !== null) {
|
|
557
|
+
const by = inWindow(r, window, time?.clock ?? null, zone, chapterDates);
|
|
558
|
+
if (by === null) {
|
|
559
|
+
beyond.set(id, c);
|
|
560
|
+
pool.delete(id);
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
c.timeBy = by;
|
|
564
|
+
c.ways.add("time");
|
|
565
|
+
}
|
|
566
|
+
if (ofAnchorSession(r)) {
|
|
567
|
+
c.score += 1;
|
|
568
|
+
c.ways.add("session");
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ── a chapter and its own copy are one result: the chapter ─────────────
|
|
573
|
+
const foldCopies = (into: Map<string, Candidate>): void => {
|
|
574
|
+
for (const [id, c] of [...into]) {
|
|
575
|
+
const r = rows.get(id) as RecallRow;
|
|
576
|
+
if (r.type !== "memory" || r.source !== "episode" || r.origin_ref === null || !r.origin_ref.startsWith("epi_")) continue;
|
|
577
|
+
const chapter = r.origin_ref;
|
|
578
|
+
if (visible(chapter) === undefined) continue;
|
|
579
|
+
const to = into.get(chapter) ?? { id: chapter, score: 0, ways: new Set<FactWay>(), foldedEarlier: new Set<string>(), ...(c.timeBy === undefined ? {} : { timeBy: c.timeBy }) };
|
|
580
|
+
to.score = Math.max(to.score, c.score);
|
|
581
|
+
for (const way of c.ways) to.ways.add(way);
|
|
582
|
+
into.set(chapter, to);
|
|
583
|
+
into.delete(id);
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
// ── current first: an earlier version that matched brings its current one ──
|
|
588
|
+
const pairs = safe(() => store.contradictions({ limit: 100_000 }), [] as ContradictionRow[]).filter(
|
|
589
|
+
(p) => p.via === null && p.state !== "withdrawn",
|
|
590
|
+
);
|
|
591
|
+
const nowOf = new Map<string, string>();
|
|
592
|
+
for (const p of pairs) {
|
|
593
|
+
if (p.state === "settled" && p.how === "changed" && p.over !== null && p.holds !== null) nowOf.set(p.over, p.holds);
|
|
594
|
+
}
|
|
595
|
+
const foldEarlier = (into: Map<string, Candidate>): void => {
|
|
596
|
+
for (const [id, c] of [...into]) {
|
|
597
|
+
let head = id;
|
|
598
|
+
for (let i = 0; i < 8; i += 1) {
|
|
599
|
+
const next = nowOf.get(head);
|
|
600
|
+
if (next === undefined || visible(next) === undefined) break;
|
|
601
|
+
head = next;
|
|
602
|
+
}
|
|
603
|
+
if (head === id) continue;
|
|
604
|
+
const to = into.get(head) ?? { id: head, score: 0, ways: new Set<FactWay>(), foldedEarlier: new Set<string>(), ...(c.timeBy === undefined ? {} : { timeBy: c.timeBy }) };
|
|
605
|
+
to.score = Math.max(to.score, c.score);
|
|
606
|
+
for (const way of c.ways) to.ways.add(way);
|
|
607
|
+
to.foldedEarlier.add(id);
|
|
608
|
+
into.set(head, to);
|
|
609
|
+
into.delete(id);
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
foldCopies(pool);
|
|
613
|
+
foldEarlier(pool);
|
|
614
|
+
foldCopies(beyond);
|
|
615
|
+
foldEarlier(beyond);
|
|
616
|
+
// A fact the window brought in (its chapter, its current version) is not also outside it.
|
|
617
|
+
for (const id of pool.keys()) beyond.delete(id);
|
|
618
|
+
|
|
619
|
+
// ── the weak tail ───────────────────────────────────────────────────────
|
|
620
|
+
let weak = 0;
|
|
621
|
+
const best = (m: ReadonlyMap<string, Candidate>): number => {
|
|
622
|
+
let b = 0;
|
|
623
|
+
for (const c of m.values()) if (c.score > b) b = c.score;
|
|
624
|
+
return b;
|
|
625
|
+
};
|
|
626
|
+
const top = best(pool);
|
|
627
|
+
if (!onlyTime && top > 0) {
|
|
628
|
+
for (const [id, c] of [...pool]) {
|
|
629
|
+
if (c.score < FACTS_WEAK_FRACTION * top) {
|
|
630
|
+
weak += 1;
|
|
631
|
+
pool.delete(id);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
// Outside the window, by the same bar — the best match anywhere sets it.
|
|
636
|
+
const topAll = Math.max(top, best(beyond));
|
|
637
|
+
let outside = 0;
|
|
638
|
+
for (const c of beyond.values()) if (onlyTime || topAll <= 0 || c.score >= FACTS_WEAK_FRACTION * topAll) outside += 1;
|
|
639
|
+
|
|
640
|
+
// ── faded, and the order ────────────────────────────────────────────────
|
|
641
|
+
const main: Candidate[] = [];
|
|
642
|
+
const faded: Candidate[] = [];
|
|
643
|
+
for (const c of pool.values()) {
|
|
644
|
+
const r = rows.get(c.id) as RecallRow;
|
|
645
|
+
let isFaded = false;
|
|
646
|
+
if (r.type === "memory") {
|
|
647
|
+
try {
|
|
648
|
+
const p = store.physicsOf(c.id);
|
|
649
|
+
isFaded = hasFaded(p, day);
|
|
650
|
+
} catch {
|
|
651
|
+
isFaded = false;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
(isFaded ? faded : main).push(c);
|
|
655
|
+
}
|
|
656
|
+
const moment = (id: string): number => {
|
|
657
|
+
const r = rows.get(id);
|
|
658
|
+
return r === undefined ? 0 : (r.type === "episode" ? (r.updated_at ?? r.created_at ?? 0) : (r.created_at ?? 0));
|
|
659
|
+
};
|
|
660
|
+
const order = (a: Candidate, b: Candidate): number =>
|
|
661
|
+
b.score - a.score || moment(b.id) - moment(a.id) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
662
|
+
main.sort(order);
|
|
663
|
+
faded.sort(order);
|
|
664
|
+
|
|
665
|
+
// ── near-duplicates, walked in order as far as this page needs ─────────
|
|
666
|
+
const bodies = new Map<string, { title: string | null; body: string }>();
|
|
667
|
+
const read = (id: string): { title: string | null; body: string } | null => {
|
|
668
|
+
const held = bodies.get(id);
|
|
669
|
+
if (held !== undefined) return held;
|
|
670
|
+
try {
|
|
671
|
+
const doc = store.readProse(id);
|
|
672
|
+
const got = { title: doc.title ?? null, body: doc.body };
|
|
673
|
+
bodies.set(id, got);
|
|
674
|
+
return got;
|
|
675
|
+
} catch {
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
const kept: Candidate[] = [];
|
|
680
|
+
const keptTokens: Set<string>[] = [];
|
|
681
|
+
let duplicates = 0;
|
|
682
|
+
let unreadable = 0;
|
|
683
|
+
const need = page * FACTS_PAGE_SIZE;
|
|
684
|
+
let walked = 0;
|
|
685
|
+
for (const c of main) {
|
|
686
|
+
if (kept.length >= need) break;
|
|
687
|
+
walked += 1;
|
|
688
|
+
const doc = read(c.id);
|
|
689
|
+
if (doc === null) {
|
|
690
|
+
unreadable += 1;
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const toks = new Set(tokenize(`${doc.title ?? ""}\n${doc.body}`));
|
|
694
|
+
if (keptTokens.some((k) => jaccard(k, toks) >= FACTS_NEAR_DUPLICATE)) {
|
|
695
|
+
duplicates += 1;
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
kept.push(c);
|
|
699
|
+
keptTokens.push(toks);
|
|
700
|
+
}
|
|
701
|
+
const matched = kept.length + (main.length - walked);
|
|
702
|
+
if (unreadable > 0) blocked("unreadable");
|
|
703
|
+
if (duplicates > 0) blockedBy["near-duplicate"] = duplicates;
|
|
704
|
+
if (weak > 0) blockedBy["weak"] = weak;
|
|
705
|
+
if (outside > 0) blockedBy["outside-window"] = outside;
|
|
706
|
+
|
|
707
|
+
const shown = kept.slice((page - 1) * FACTS_PAGE_SIZE, page * FACTS_PAGE_SIZE);
|
|
708
|
+
const pages = Math.max(1, Math.ceil(matched / FACTS_PAGE_SIZE), Math.ceil(faded.length / FACTS_FADED_LINES));
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* May this asker be told this id exists? A pair line names its other side
|
|
712
|
+
* (`disagrees with mem_…`, `now mem_…`): a confidential or removed memory is
|
|
713
|
+
* not named to a non-owner, as a list never shows it (review of #323).
|
|
714
|
+
*/
|
|
715
|
+
const canName = (id: string): boolean => {
|
|
716
|
+
if (denied.has(id)) return false;
|
|
717
|
+
if (ctx.owner) return true;
|
|
718
|
+
const r = rows.get(id) ?? safe(() => store.row(id), undefined);
|
|
719
|
+
return r !== undefined && r.confidential !== 1;
|
|
720
|
+
};
|
|
721
|
+
const memories = shown.map((c) => factItem(ctx, c, rows.get(c.id) as RecallRow, read(c.id) as { title: string | null; body: string }, pairs, w.tokens, today, zone, window, canName));
|
|
722
|
+
const fadedLines: FadedLine[] = faded.slice((page - 1) * FACTS_FADED_LINES, page * FACTS_FADED_LINES).map((c) => {
|
|
723
|
+
const r = rows.get(c.id) as RecallRow;
|
|
724
|
+
const title = r.title ?? read(c.id)?.body ?? c.id;
|
|
725
|
+
return { id: c.id, line: plainLine(title, 80), date: parseCalendarDate(r.occurred_on ?? "")?.text ?? learnedOf(r, zone) };
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
return {
|
|
729
|
+
mode: "facts",
|
|
730
|
+
reason: matched + faded.length === 0 ? "nothing-came" : "answered",
|
|
731
|
+
semantic: ctx.vector !== null && ctx.vector.length > 0 ? "in-line" : ctx.semantic,
|
|
732
|
+
matched,
|
|
733
|
+
page,
|
|
734
|
+
pages,
|
|
735
|
+
memories,
|
|
736
|
+
faded: fadedLines,
|
|
737
|
+
fadedTotal: faded.length,
|
|
738
|
+
weak,
|
|
739
|
+
duplicates,
|
|
740
|
+
meaningCapped,
|
|
741
|
+
time:
|
|
742
|
+
time === null
|
|
743
|
+
? null
|
|
744
|
+
: {
|
|
745
|
+
cue: time.cue,
|
|
746
|
+
said: anchor !== undefined ? window : time.said,
|
|
747
|
+
window,
|
|
748
|
+
stretch: anchor?.kind === "event" && anchor.date !== null ? FACTS_ANCHOR_DAYS : time.stretch,
|
|
749
|
+
...(anchor === undefined ? {} : { anchor }),
|
|
750
|
+
outside,
|
|
751
|
+
},
|
|
752
|
+
subjects,
|
|
753
|
+
considered,
|
|
754
|
+
storeSize,
|
|
755
|
+
blockedBy,
|
|
756
|
+
today,
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** One result, with its labeled lines' fields filled. */
|
|
761
|
+
function factItem(
|
|
762
|
+
ctx: FactsContext,
|
|
763
|
+
c: Candidate,
|
|
764
|
+
row: RecallRow,
|
|
765
|
+
doc: { title: string | null; body: string },
|
|
766
|
+
pairs: readonly ContradictionRow[],
|
|
767
|
+
tokens: readonly string[],
|
|
768
|
+
today: string,
|
|
769
|
+
zone: string,
|
|
770
|
+
window: DayWindow | null,
|
|
771
|
+
canName: (id: string) => boolean,
|
|
772
|
+
): FactItem {
|
|
773
|
+
const store = ctx.counterpart.store;
|
|
774
|
+
const journal = row.type === "episode";
|
|
775
|
+
let text = doc.body;
|
|
776
|
+
let chapter: FactItem["chapter"];
|
|
777
|
+
if (journal) {
|
|
778
|
+
// The chapter the question's words reach most, else the first — among
|
|
779
|
+
// the chapters dated inside the question's window, when it named one and
|
|
780
|
+
// any are.
|
|
781
|
+
const all = chaptersOf(doc.body);
|
|
782
|
+
if (all.length > 1) {
|
|
783
|
+
const dated = window === null ? [] : all.map((ch, i) => ({ ch, i })).filter(({ ch }) => ch.date !== null && ch.date >= window.from && ch.date <= window.to);
|
|
784
|
+
const among = dated.length > 0 ? dated : all.map((ch, i) => ({ ch, i }));
|
|
785
|
+
let best = among[0]?.i ?? 0;
|
|
786
|
+
let bestHits = -1;
|
|
787
|
+
for (const { ch, i } of among) {
|
|
788
|
+
const toks = new Set(tokenize(ch.text));
|
|
789
|
+
const hits = tokens.filter((t) => toks.has(t)).length;
|
|
790
|
+
if (hits > bestHits) {
|
|
791
|
+
best = i;
|
|
792
|
+
bestHits = hits;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
text = all[best]?.text ?? doc.body;
|
|
796
|
+
chapter = { n: best + 1, of: all.length };
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
const flat = text.replace(/^[ \t]*#{1,6}[ \t]+/gm, "").replace(/\s+/g, " ").trim();
|
|
800
|
+
const body = cutExcerpt(flat, RECALL_EXCERPT_CHARS);
|
|
801
|
+
const parts = provenanceParts(store, c.id, ctx.sessionId, ctx.counterpart.spans);
|
|
802
|
+
const learned = learnedOf(row, zone);
|
|
803
|
+
const lastWritten = journal && row.updated_at !== null ? localDate(row.updated_at, zone) : null;
|
|
804
|
+
|
|
805
|
+
// Earlier: in-place versions whose words differ, then `changed` pairs it holds.
|
|
806
|
+
const earlier: EarlierVersion[] = [];
|
|
807
|
+
const versions = safe(() => store.versions(c.id), []);
|
|
808
|
+
for (const v of [...versions].reverse()) {
|
|
809
|
+
if (v.body.length === 0 || v.body === doc.body || v.reason === "episode-chapter") continue;
|
|
810
|
+
earlier.push({
|
|
811
|
+
text: plainLine(v.title ?? v.body, 60),
|
|
812
|
+
learned: v.learned_on.length > 0 ? v.learned_on : null,
|
|
813
|
+
changed: v.archived_at > 0 ? localDate(v.archived_at, zone) : null,
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
let corrected = 0;
|
|
817
|
+
const standing: string[] = [];
|
|
818
|
+
let now: string | undefined;
|
|
819
|
+
for (const p of pairs) {
|
|
820
|
+
if (p.a !== c.id && p.b !== c.id) continue;
|
|
821
|
+
const other = p.a === c.id ? p.b : p.a;
|
|
822
|
+
if (p.state === "settled" && p.how === "changed" && p.holds === c.id && p.over !== null) {
|
|
823
|
+
const o = store.row(p.over);
|
|
824
|
+
if (o === undefined || !canName(p.over)) continue;
|
|
825
|
+
earlier.push({
|
|
826
|
+
text: plainLine(o.title ?? o.body, 60),
|
|
827
|
+
learned: o.learned_on.length > 0 ? o.learned_on : null,
|
|
828
|
+
changed: localDate(p.updated_at, zone),
|
|
829
|
+
id: p.over,
|
|
830
|
+
});
|
|
831
|
+
} else if (p.state === "settled" && p.how === "changed" && p.over === c.id && p.holds !== null) {
|
|
832
|
+
now = canName(p.holds) ? p.holds : "a later version";
|
|
833
|
+
} else if (p.state === "settled" && p.how === "corrected" && p.holds === c.id) {
|
|
834
|
+
corrected += 1;
|
|
835
|
+
} else if (p.state === "settled" && p.how === "open") {
|
|
836
|
+
if (canName(other)) standing.push(`disagrees with ${other}`);
|
|
837
|
+
} else if (p.state === "unsettled" && p.a === c.id) {
|
|
838
|
+
const b = store.row(p.b);
|
|
839
|
+
if (b !== undefined && b.archived === 0 && b.superseded_by === null && canName(p.b)) standing.push(`unsettled — may be out of date, see ${p.b}`);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
// Matched earlier memories first, then by when they changed, newest first.
|
|
843
|
+
earlier.sort((a, b) => {
|
|
844
|
+
const fa = a.id !== undefined && c.foldedEarlier.has(a.id) ? 0 : 1;
|
|
845
|
+
const fb = b.id !== undefined && c.foldedEarlier.has(b.id) ? 0 : 1;
|
|
846
|
+
return fa - fb || (b.changed ?? "").localeCompare(a.changed ?? "");
|
|
847
|
+
});
|
|
848
|
+
const title = row.title ?? doc.title;
|
|
849
|
+
return {
|
|
850
|
+
id: c.id,
|
|
851
|
+
title,
|
|
852
|
+
line: title !== null && title.trim().length > 0 ? plainLine(title, 100) : plainLine(text, 80),
|
|
853
|
+
kind: row.kind,
|
|
854
|
+
journal,
|
|
855
|
+
...(chapter === undefined ? {} : { chapter }),
|
|
856
|
+
body,
|
|
857
|
+
bodyChars: doc.body.length,
|
|
858
|
+
whole: body.length === flat.length && chapter === undefined,
|
|
859
|
+
saidBy: row.said_by,
|
|
860
|
+
status: row.status,
|
|
861
|
+
occurredOn: row.occurred_on,
|
|
862
|
+
learned,
|
|
863
|
+
...(lastWritten !== null && lastWritten !== learned ? { lastWritten } : {}),
|
|
864
|
+
where: parts?.where ?? null,
|
|
865
|
+
who: parts?.who ?? null,
|
|
866
|
+
current: now === undefined,
|
|
867
|
+
...(now === undefined ? {} : { now }),
|
|
868
|
+
earlier: earlier.slice(0, FACTS_EARLIER_SHOWN),
|
|
869
|
+
earlierMore: Math.max(0, earlier.length - FACTS_EARLIER_SHOWN),
|
|
870
|
+
corrected,
|
|
871
|
+
standing: standing.slice(0, 2),
|
|
872
|
+
ways: (["words", "meaning", "subject", "session", "time"] as const).filter((x) => c.ways.has(x)),
|
|
873
|
+
...(c.timeBy === undefined ? {} : { timeBy: c.timeBy }),
|
|
874
|
+
score: Math.round(c.score * 1000) / 1000,
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/** Where and when the anchor session was at work, and who else was here then. */
|
|
879
|
+
interface Stretch {
|
|
880
|
+
readonly scope: string;
|
|
881
|
+
readonly firstAt: number;
|
|
882
|
+
readonly lastAt: number;
|
|
883
|
+
readonly others: readonly { readonly firstAt: number; readonly lastAt: number }[];
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const normScope = (s: string): string => s.trim().replace(/\/+$/, "");
|
|
887
|
+
|
|
888
|
+
/**
|
|
889
|
+
* A note an unbound server wrote, read as the anchor session's when it can be
|
|
890
|
+
* no one else's (`deliberate.ts#provenanceParts`' rule): written in this
|
|
891
|
+
* directory, inside the session's stretch, and inside no other session's.
|
|
892
|
+
*/
|
|
893
|
+
function placedIn(r: RecallRow, s: Stretch): boolean {
|
|
894
|
+
const at = r.created_at;
|
|
895
|
+
if (at === null || r.origin_scope === null || normScope(r.origin_scope) !== normScope(s.scope)) return false;
|
|
896
|
+
if (at < s.firstAt || at > s.lastAt) return false;
|
|
897
|
+
return !s.others.some((o) => at >= o.firstAt && at <= o.lastAt);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* THE LAST SESSION a question means: in a directory, the session the wake's
|
|
902
|
+
* "Last here" names, else the newest other session at work here; without one
|
|
903
|
+
* (the console), the newest journal's session anywhere. Its window is the
|
|
904
|
+
* days it was at work. Null when there is none.
|
|
905
|
+
*/
|
|
906
|
+
function lastSession(
|
|
907
|
+
ctx: FactsContext,
|
|
908
|
+
rows: ReadonlyMap<string, RecallRow>,
|
|
909
|
+
zone: string,
|
|
910
|
+
): { session: string; from: string; to: string; stretch: Stretch | null } | null {
|
|
911
|
+
const scope = ctx.scope?.trim() ?? "";
|
|
912
|
+
if (scope.length > 0) {
|
|
913
|
+
const spans = ctx.counterpart.spans;
|
|
914
|
+
const here = spans === undefined ? [] : safe(() => sessionsHere(spans, scope), []);
|
|
915
|
+
const stretchOf = (session: string, firstAt: number, lastAt: number): Stretch => ({
|
|
916
|
+
scope,
|
|
917
|
+
firstAt,
|
|
918
|
+
lastAt,
|
|
919
|
+
others: here.filter((h) => h.session !== session),
|
|
920
|
+
});
|
|
921
|
+
try {
|
|
922
|
+
const named = ctx.counterpart.chaptersHereFor?.(scope, ctx.sessionId)[0];
|
|
923
|
+
if (named !== undefined) {
|
|
924
|
+
const session = named.chapter.session;
|
|
925
|
+
const own = here.find((h) => h.session === session);
|
|
926
|
+
return {
|
|
927
|
+
session,
|
|
928
|
+
from: localDate(named.firstAt, zone),
|
|
929
|
+
to: localDate(named.lastAt, zone),
|
|
930
|
+
stretch: stretchOf(session, own?.firstAt ?? named.firstAt, own?.lastAt ?? named.lastAt),
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
} catch {
|
|
934
|
+
/* fall through to the sessions here */
|
|
935
|
+
}
|
|
936
|
+
const s = here.filter((h) => h.session !== ctx.sessionId).sort((a, b) => b.lastAt - a.lastAt)[0];
|
|
937
|
+
if (s !== undefined) {
|
|
938
|
+
return { session: s.session, from: localDate(s.firstAt, zone), to: localDate(s.lastAt, zone), stretch: stretchOf(s.session, s.firstAt, s.lastAt) };
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
let best: RecallRow | null = null;
|
|
942
|
+
for (const r of rows.values()) {
|
|
943
|
+
if (r.type !== "episode") continue;
|
|
944
|
+
const s = sessionOf(r);
|
|
945
|
+
if (s === null || s === ctx.sessionId) continue;
|
|
946
|
+
if (best === null || (r.updated_at ?? 0) > (best.updated_at ?? 0)) best = r;
|
|
947
|
+
}
|
|
948
|
+
if (best === null) return null;
|
|
949
|
+
const session = sessionOf(best) as string;
|
|
950
|
+
const first = best.created_at ?? best.updated_at ?? 0;
|
|
951
|
+
const last = best.updated_at ?? first;
|
|
952
|
+
if (first <= 0) return null;
|
|
953
|
+
return { session, from: localDate(first, zone), to: localDate(last, zone), stretch: null };
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function safe<T>(fn: () => T, fallback: T): T {
|
|
957
|
+
try {
|
|
958
|
+
return fn();
|
|
959
|
+
} catch {
|
|
960
|
+
return fallback;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
// ── the answer, as labeled lines ───────────────────────────────────────────
|
|
965
|
+
|
|
966
|
+
const SAID: Readonly<Record<string, string>> = { owner: "you said", self: "I said", inferred: "inferred" };
|
|
967
|
+
|
|
968
|
+
/** Why words alone answered, in plain words. */
|
|
969
|
+
function channelWords(semantic: SemanticSource): string | null {
|
|
970
|
+
if (semantic === "in-line") return null;
|
|
971
|
+
if (semantic === "embedder-off") return "by words only — recall by meaning is off";
|
|
972
|
+
if (semantic === "embed-failed") return "by words only — the question could not be embedded";
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/** The labeled lines of one result. */
|
|
977
|
+
function itemLines(m: FactItem, i: number, today: string, excerptChars: number): string[] {
|
|
978
|
+
const out: string[] = [];
|
|
979
|
+
const mark = m.journal ? "[journal] " : "";
|
|
980
|
+
const ch = m.chapter === undefined ? "" : ` (chapter ${String(m.chapter.n)} of ${String(m.chapter.of)})`;
|
|
981
|
+
out.push(`${String(i)}. ${mark}${m.line} · ${m.id}${ch} · ${m.ways.join(", ")}`);
|
|
982
|
+
if (m.journal) {
|
|
983
|
+
out.push(` my journal · written ${shortDate(m.learned, today)}${m.lastWritten === undefined || m.lastWritten === null ? "" : `..${shortDate(m.lastWritten, today)}`}${m.where === null ? "" : ` in ${m.where}`}${m.who === null ? "" : ` · ${m.who}`}`);
|
|
984
|
+
} else {
|
|
985
|
+
const said = m.saidBy === null ? "speaker unknown" : (SAID[m.saidBy] ?? m.saidBy);
|
|
986
|
+
const status = m.status ?? "status unknown";
|
|
987
|
+
const occurred =
|
|
988
|
+
m.occurredOn === null
|
|
989
|
+
? "no event date"
|
|
990
|
+
: `${m.status === "planned" || m.status === "proposed" || m.status === "asked" ? "for" : "happened"} ${shortDate(m.occurredOn, today)}`;
|
|
991
|
+
out.push(` ${said} · ${status} · ${occurred}`);
|
|
992
|
+
const where = m.where === null ? "" : ` in ${m.where}`;
|
|
993
|
+
const who = m.who === null ? "" : ` · ${m.who}`;
|
|
994
|
+
const standing = m.current ? "CURRENT" : `earlier — now ${m.now ?? "?"}`;
|
|
995
|
+
const extra = m.standing.length === 0 ? "" : ` · ${m.standing.join(" · ")}`;
|
|
996
|
+
const by = m.timeBy === "learned" && m.occurredOn === null ? " (in the window by this date)" : "";
|
|
997
|
+
out.push(` learned ${m.learned === null ? "date unknown" : shortDate(m.learned, today)}${by}${where}${who} · ${standing}${extra}`);
|
|
998
|
+
}
|
|
999
|
+
for (const e of m.earlier) {
|
|
1000
|
+
const learned = e.learned === null ? "" : ` (learned ${shortDate(e.learned, today)})`;
|
|
1001
|
+
const changed = e.changed === null ? "" : `, changed ${shortDate(e.changed, today)}`;
|
|
1002
|
+
out.push(` earlier: "${e.text}"${learned}${changed}${e.id === undefined ? "" : ` · ${e.id}`}`);
|
|
1003
|
+
}
|
|
1004
|
+
if (m.earlierMore > 0) out.push(` +${String(m.earlierMore)} more earlier`);
|
|
1005
|
+
if (m.corrected > 0) out.push(` ${String(m.corrected)} corrected version${m.corrected === 1 ? "" : "s"} hidden`);
|
|
1006
|
+
const words = m.body.length <= excerptChars ? m.body : cutExcerpt(m.body, excerptChars);
|
|
1007
|
+
out.push(` ${words}`);
|
|
1008
|
+
return out;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/**
|
|
1012
|
+
* The answer a facts question returns, as labeled lines. Bounded by
|
|
1013
|
+
* `RECALL_RESULT_CHARS`: past it, excerpts are cut shorter until it fits.
|
|
1014
|
+
*/
|
|
1015
|
+
export function renderFacts(r: FactsResult): string {
|
|
1016
|
+
for (const excerpt of [RECALL_EXCERPT_CHARS, 150, 60, 0]) {
|
|
1017
|
+
const text = renderAt(r, r.today, excerpt);
|
|
1018
|
+
if (text.length <= RECALL_RESULT_CHARS || excerpt === 0) return text.length <= RECALL_RESULT_CHARS ? text : cutExcerpt(text, RECALL_RESULT_CHARS);
|
|
1019
|
+
}
|
|
1020
|
+
return "";
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function renderAt(r: FactsResult, today: string, excerpt: number): string {
|
|
1024
|
+
const lines: string[] = [];
|
|
1025
|
+
const first = (r.page - 1) * FACTS_PAGE_SIZE;
|
|
1026
|
+
const shown = r.memories.length;
|
|
1027
|
+
const after = Math.max(0, r.matched - first - shown);
|
|
1028
|
+
const head: string[] = [`${String(r.matched)} match`];
|
|
1029
|
+
if (r.page > 1) head.push(`page ${String(r.page)}`);
|
|
1030
|
+
if (shown > 0) head.push(r.page > 1 ? `showing ${String(first + 1)}–${String(first + shown)}` : `showing ${String(shown)}`);
|
|
1031
|
+
if (r.page < r.pages) head.push(`${after > 0 ? `${String(after)} more` : "more"} → page ${String(r.page + 1)}`);
|
|
1032
|
+
if (r.fadedTotal > 0) head.push(`${String(r.fadedTotal)} faded, listed after`);
|
|
1033
|
+
lines.push(head.join(" · "));
|
|
1034
|
+
if (r.time !== null) {
|
|
1035
|
+
const t = r.time;
|
|
1036
|
+
// An open end ("before 7/22", "after 7/22") reads as a cutoff, not as year 1 or 9999.
|
|
1037
|
+
const span = (w: DayWindow | null): string =>
|
|
1038
|
+
w === null
|
|
1039
|
+
? ""
|
|
1040
|
+
: w.from === OPEN_START
|
|
1041
|
+
? `through ${shortDate(w.to, today)}`
|
|
1042
|
+
: w.to === OPEN_END
|
|
1043
|
+
? `${shortDate(w.from, today)} onward`
|
|
1044
|
+
: w.from === w.to
|
|
1045
|
+
? shortDate(w.from, today)
|
|
1046
|
+
: `${shortDate(w.from, today)}..${shortDate(w.to, today)}`;
|
|
1047
|
+
const out = t.outside > 0 ? ` · ${String(t.outside)} more match outside it` : "";
|
|
1048
|
+
if (t.anchor !== undefined && t.anchor.date === null) {
|
|
1049
|
+
lines.push(
|
|
1050
|
+
t.anchor.kind === "event"
|
|
1051
|
+
? `time: ${t.cue} — no memory names "${t.anchor.phrase}", so nothing was filtered by time`
|
|
1052
|
+
: `time: ${t.cue} — no earlier session found, so nothing was filtered by time`,
|
|
1053
|
+
);
|
|
1054
|
+
} else if (t.anchor !== undefined) {
|
|
1055
|
+
const what = t.anchor.kind === "event" ? `${t.anchor.phrase} → ${shortDate(t.anchor.date, today)}${t.anchor.id === undefined ? "" : ` (${t.anchor.id})`}` : `${t.cue} → ${shortDate(t.anchor.date, today)}${t.anchor.session === undefined ? "" : ` (session ${t.anchor.session.slice(0, 8)}, its rows first)`}`;
|
|
1056
|
+
const stretch = t.anchor.kind === "event" ? `, window ${span(t.window)}` : "";
|
|
1057
|
+
lines.push(`time: ${what}${stretch}${out}`);
|
|
1058
|
+
} else {
|
|
1059
|
+
const stretch = t.stretch > 0 ? `, stretched ${String(t.stretch)} day${t.stretch === 1 ? "" : "s"} each side` : "";
|
|
1060
|
+
lines.push(`time: ${t.cue} → ${span(t.said)}${stretch}${out}`);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
if (r.subjects.length > 0) lines.push(`about: ${r.subjects.map((s) => s.name).join(", ")}`);
|
|
1064
|
+
const channel = channelWords(r.semantic);
|
|
1065
|
+
if (channel !== null) lines.push(channel);
|
|
1066
|
+
const notAll: string[] = [];
|
|
1067
|
+
if (r.meaningCapped) notAll.push(`meaning search hit its cap (${String(FACTS_MEANING_CAP)})`);
|
|
1068
|
+
if (r.weak > 0) notAll.push(`${String(r.weak)} weak match${r.weak === 1 ? "" : "es"} not shown`);
|
|
1069
|
+
if (notAll.length > 0) lines.push(`may not be everything: ${notAll.join(" · ")}`);
|
|
1070
|
+
if (r.duplicates > 0) {
|
|
1071
|
+
lines.push(`${String(r.duplicates)} near-duplicate${r.duplicates === 1 ? "" : "s"} of a result shown left out`);
|
|
1072
|
+
}
|
|
1073
|
+
if (r.matched === 0 && r.fadedTotal === 0) {
|
|
1074
|
+
lines.push("");
|
|
1075
|
+
lines.push("Nothing matched. Try the words the memory itself would use, a person or project it names, or a wider time.");
|
|
1076
|
+
return lines.join("\n");
|
|
1077
|
+
}
|
|
1078
|
+
r.memories.forEach((m, i) => {
|
|
1079
|
+
lines.push("");
|
|
1080
|
+
lines.push(...itemLines(m, first + i + 1, today, excerpt));
|
|
1081
|
+
});
|
|
1082
|
+
if (r.faded.length > 0) {
|
|
1083
|
+
lines.push("");
|
|
1084
|
+
lines.push(`faded (${String(r.fadedTotal)}): not used for a long while; opening one by id brings it back`);
|
|
1085
|
+
for (const f of r.faded) lines.push(`- ${f.line} · ${f.date === null ? "date unknown" : shortDate(f.date, today)} · ${f.id} · faded`);
|
|
1086
|
+
}
|
|
1087
|
+
lines.push("");
|
|
1088
|
+
const foot: string[] = [];
|
|
1089
|
+
if (r.memories.some((m) => !m.whole)) foot.push(`read any whole with ids: [...] (up to ${String(RECALL_MAX_IDS)})`);
|
|
1090
|
+
if (r.page < r.pages) foot.push(`page: ${String(r.page + 1)} for the next`);
|
|
1091
|
+
if (foot.length > 0) lines.push(`${foot.join(" · ")}.`);
|
|
1092
|
+
if (r.memories.some((m) => m.journal)) lines.push(FACTS_JOURNAL_GLOSS);
|
|
1093
|
+
return lines.join("\n").trimEnd();
|
|
1094
|
+
}
|