Skip to content

Commit 2fa787c

Browse files
authored
host: the palette's full-text search finds nothing after the index mark in a read-only window (and answers more: 0) (#3320)
Fixes #3319 Owner: Dev-1 Reviewer: Birfy ## What is missing In a read-only window — the second dsh over one home — ⌘K → **Messages (full text)** answered with the writer's index only. `searchHomeChat` caught each session up and then answered from `matchedRows`; in a read-only window `catchUp` returns at once (`if (!index.writable || readOnly()) return Promise.resolve()`), so a part whose log ran past `marks.through` contributed nothing: no row, no `stop` (the own-chat surface has one, #3195), and `more: 0`, which reads as "there is nothing else" while the message sat in the log. Reproduced on base `73e0972dd87216ed851cefa2fa8d6b705c37c4de` with the shape `core/test/chat-index-writers.test.js` already builds (a real runtime, a temporary home, real SQLite, a writer that indexed three lines and stopped): append `a fourth NEEDLE line` to the log, open the read-only window (`heldBy: process.ppid`), then - `searchHomeChat(['solo'], 'NEEDLE')` → `{"rows":[],"every":true,"more":0}` - the control, `'third'` → 1 row (the index and the query are fine; the index is behind) - through `/api/bot`, `chats.search` → `{"rows":[],"more":0}` ## Red first New case `a read-only window searches the log past its index mark (#3319)` in `core/test/chat-index-writers.test.js`, run at base `73e0972dd872` with only that test applied: ``` not ok 4 - a read-only window searches the log past its index mark (#3319) error: |- {"rows":[],"every":true,"more":0} 0 !== 1 # tests 12 # pass 11 # fail 1 ``` The case also asserts the row names its session and seq, that the index the writer left still holds its 3 rows, and that `chats.search` through the real `/api/bot` route answers the same. At the fixed tip: `# tests 12 / # pass 12 / # fail 0`. ## What changed - `core/src/host/chat-index.js`: `catchUp`'s row-building pass is factored out as `markedRows(sessionId, mark, events)` — same order, same `keepAnswers` rule, same `turn`/`turnNo` tracking — so a row matched outside the index cannot drift from the row the index holds; the writer inserts the same objects. - `unindexedRows()` reads each session whose `marks.through` is behind its log (`eventsBackwards` from `through`, bounded by `HISTORY_TIMEOUT_MS`) and matches the query in memory. Nothing is written; a session this window cannot resolve or read is answered from the index alone, with one warning, never an error for the palette. - `withLogRows()` merges the index answer with those rows the way the index answers: the rows holding every term when any exist, else the rows holding some; newest first, deduplicated by `(session, seq)`; `more` is the two totals minus what is shown, i.e. hits the cap left out, not "the index stopped early". - A writer window (which catches up first) and a read-only window whose index is caught up answer byte for byte as before: `searchHomeChat` returns `matchedRows`' own object unless the tail contributed a match. - `docs/subsystems/core-host.md`: one bullet beside the palette section; `changelog.d/3319-palette-readonly-search.fixed.md`; `patches/ds-bot/0001-core-fixes.patch` and `files/test/chat-index-writers.test.js` regenerated by `node scripts/ds-bot-patches.mjs generate`. ## Verification at the tip - `TZ=UTC npm run verify` → exit 0, run at `bc0fe9635b9aff8f14cbadeba8ae1472e94d00a8` (the tree the pushed head is rebuilt from): core **3446/3446**, plane 25, social 762, tree 157, timeline 178, workflow 544, project 151, scripts+policy 735, interop 37, live-e2e 34 — `# fail 0` in every suite. - `core/test/chat-index-writers.test.js` alone: 12/12 (11/12 at base, the new case the only red). - oxlint core: `Found 91 warnings and 0 errors.` (the count base carries). - `node scripts/ds-bot-patches.mjs check` → `10 patches apply cleanly in order`, `core/ equals ds-bot/ + patches/ds-bot/`; `canonical` → `patches/ds-bot/ is what generate writes (generate is a no-op)`. - `ARCH_DOCS_BASE=73e0972dd872 npm run arch-docs` (in `core/`) → `OK (6 changed file(s))`. - `node .github/scripts/changelog.mjs check` → `4 fragment(s) in changelog.d/ are well formed`. - `node .github/scripts/check-mojibake.mjs --check` → `0 occurrences of U+FFFD in 1789 text file(s)`. ## Not run - `dev/smoke.mjs` (bench): not run. - The CI `package` job's `build-client.mjs --check` is inside `verify`; its pack check, typecheck and actionlint are not part of `verify` and were not run here. ## Known limits - The tail is read for a session whose mark is behind its log; one whose agent this window cannot resolve is answered from the index alone, the way `stop` already behaves. - Nothing is written: a read-only window still never creates, repairs or adds to `chat-index.sqlite`, and the case asserts the 3 rows the writer left are unchanged. - No UI face: the palette's rows and copy are unchanged; the host answers rows it already had. ## Checkpoint <!-- flybot:checkpoint --> ```json { "pr": 3320, "claim": "Dev-1", "issue": 3319, "summary": "A read-only window's palette search answered only the writer's index, so a message already in the log past the mark was missing and more: 0 claimed there was nothing else. The index's catch-up pass is now markedRows(), shared by both paths, and searchHomeChat matches the events after each mark in memory and merges them with the index answer: every-term rows when any exist, else the some-term rows, newest first, deduplicated, with more still meaning hits the cap left out. Nothing is written, and a writer window or a caught-up window answers byte for byte as before.", "files": ["core/src/host/chat-index.js", "core/test/chat-index-writers.test.js", "docs/subsystems/core-host.md", "changelog.d/3319-palette-readonly-search.fixed.md", "patches/ds-bot/0001-core-fixes.patch", "patches/ds-bot/files/test/chat-index-writers.test.js"], "checks": { "ran": "TZ=UTC npm run verify", "result": "green", "at": "7ca6f0bf3e52a4e45cbe4fa091b5417b81578b52" }, "next": "review the read-only tail read, the merge ordering, and that the index is untouched at the pushed tip" } ``` <!-- /flybot:checkpoint -->
1 parent 73e0972 commit 2fa787c

6 files changed

Lines changed: 322 additions & 52 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The command palette's **Messages (full text)** group now finds a message in a read-only window even when the other window that holds the folder has not indexed it yet: the host matches its own chat log past the index mark, without writing the index, so a message that already exists is no longer answered as missing with `more: 0` ([#3319](https://github.com/ThinkFlowLab/FlyBot/issues/3319)).

‎core/src/host/chat-index.js‎

Lines changed: 105 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,34 @@ export function install(rt) {
252252
return { at: t === null ? undefined : rt.clock(t) }
253253
}
254254

255+
// The rows one pass over a part's events adds, as the writer indexes them: an answer is kept
256+
// only while its turn keeps answers, and any other message with text is kept as said. It
257+
// returns the mark values the pass ends with too. `start` is the mark it continues from.
258+
function markedRows(sessionId, start, events) {
259+
let keep = start?.keep === 1
260+
let turn = start?.turn ?? -1
261+
let turnNo = start?.turnNo ?? -1
262+
let last = start?.through ?? -1
263+
const rows = []
264+
for (const event of events) {
265+
if (event.seq <= last) continue
266+
last = event.seq
267+
if (event.type === 'turn/start') {
268+
turn = event.seq
269+
if (Number.isFinite(event.data?.turn)) turnNo = event.data.turn
270+
}
271+
const entry = rt.historyEntry(event, false)
272+
if (entry === undefined) continue
273+
if (entry.answer) {
274+
if (keep) rows.push({ text: entry.text, session: sessionId, seq: event.seq, time: event.time ?? 0, who: 'you', turn: turnNo })
275+
continue
276+
}
277+
keep = entry.keepAnswers
278+
if (entry.text !== '') rows.push({ text: entry.text, session: sessionId, seq: event.seq, time: event.time ?? 0, who: entry.who, turn: turnNo })
279+
}
280+
return { rows, last, keep, turn, turnNo }
281+
}
282+
255283
// Adds what a part said since its mark. Reads of one part wait for each other within this
256284
// installation; two installations over one home meet again inside the transaction below.
257285
const catchingUp = new Map()
@@ -286,27 +314,9 @@ export function install(rt) {
286314
index.db.exec('COMMIT')
287315
return
288316
}
289-
let keep = mark ? mark.keep === 1 : false
290-
let turn = mark?.turn ?? -1
291-
let turnNo = mark?.turnNo ?? -1
292-
let last = mark?.through ?? -1
293-
for (const event of events) {
294-
if (event.seq <= last) continue
295-
last = event.seq
296-
if (event.type === 'turn/start') {
297-
turn = event.seq
298-
if (Number.isFinite(event.data?.turn)) turnNo = event.data.turn
299-
}
300-
const entry = rt.historyEntry(event, false)
301-
if (entry === undefined) continue
302-
if (entry.answer) {
303-
if (keep) index.insert.run(entry.text, part.sessionId, event.seq, event.time ?? 0, 'you', turnNo)
304-
continue
305-
}
306-
keep = entry.keepAnswers
307-
if (entry.text !== '') index.insert.run(entry.text, part.sessionId, event.seq, event.time ?? 0, entry.who, turnNo)
308-
}
309-
index.setMark.run(part.sessionId, last, keep ? 1 : 0, seal ? 1 : 0, turn, turnNo)
317+
const built = markedRows(part.sessionId, mark, events)
318+
for (const row of built.rows) index.insert.run(row.text, row.session, row.seq, row.time, row.who, row.turn)
319+
index.setMark.run(part.sessionId, built.last, built.keep ? 1 : 0, seal ? 1 : 0, built.turn, built.turnNo)
310320
index.db.exec('COMMIT')
311321
// The first commit is what makes `-wal`/`-shm`, so the modes are put right once it exists.
312322
if (!index.hardened) {
@@ -390,6 +400,75 @@ export function install(rt) {
390400
return { rows, every, more: total === undefined ? 0 : Math.max(0, total - rows.length) }
391401
}
392402

403+
// The rows a read-only window's log holds past the mark of each session: this window adds
404+
// nothing to the index, so the palette asks what the log holds rather than how far the
405+
// writer's index got. Nothing is written, and the row shape is the writer's own (#3319).
406+
async function unindexedRows(index, sessions, terms) {
407+
const every = []
408+
const some = []
409+
for (const sessionId of sessions) {
410+
const mark = index.mark.get(sessionId)
411+
const through = mark?.through ?? -1
412+
const agent = await rt.resolveAgent(sessionId).catch(() => undefined)
413+
if (agent === undefined || through >= Number(agent.session.seq) - 1) continue
414+
const events = []
415+
try {
416+
for await (const event of eventsBackwards(sessionId, AbortSignal.timeout(HISTORY_TIMEOUT_MS), Infinity)) {
417+
if (event.seq <= through) break
418+
events.push(event)
419+
}
420+
} catch (error) {
421+
rt.warn('ds-bot: reading %s past its index mark failed: %s', sessionId, error)
422+
continue
423+
}
424+
events.reverse()
425+
for (const row of markedRows(sessionId, mark, events).rows) {
426+
const lower = row.text.toLowerCase()
427+
const hits = terms.filter(term => lower.includes(term)).length
428+
if (hits === 0) continue
429+
some.push({ row, hits })
430+
if (hits === terms.length) every.push(row)
431+
}
432+
}
433+
const newest = (a, b) => (b.time - a.time) || (b.seq - a.seq)
434+
return {
435+
every: every.sort(newest),
436+
some: some.sort((a, b) => (b.hits - a.hits) || (b.row.time - a.row.time)).map(hit => hit.row),
437+
}
438+
}
439+
440+
// The index's answer and the rows read past its mark, as one answer: the rows holding every
441+
// term when any exist, else the ones holding some, and `more` from the two totals. The two
442+
// sources have no rank in common, so the answer is newest first, as the palette reads it;
443+
// without a tail the index's own order is untouched (#3319).
444+
function withLogRows(found, tail, limit) {
445+
const every = found.every || tail.every.length > 0
446+
const rows = []
447+
const seen = new Set()
448+
const add = list => {
449+
for (const row of list) {
450+
// A row both sources hold comes from one event, not two messages.
451+
const key = `${row.session}#${row.seq}`
452+
if (seen.has(key)) continue
453+
seen.add(key)
454+
rows.push(row)
455+
}
456+
}
457+
const indexTotal = found.rows.length + found.more
458+
let total
459+
if (every) {
460+
if (found.every) add(found.rows)
461+
add(tail.every)
462+
total = (found.every ? indexTotal : 0) + tail.every.length
463+
} else {
464+
add(found.rows)
465+
add(tail.some)
466+
total = indexTotal + tail.some.length
467+
}
468+
const shown = rows.sort((a, b) => (b.time - a.time) || (b.seq - a.seq)).slice(0, limit)
469+
return { rows: shown, every, more: Math.max(0, total - shown.length) }
470+
}
471+
393472
// The whole-text search behind the palette's "Messages (full text)" group (P-820): the
394473
// outline previews stop at 50/120 characters, so a hit past that budget is invisible to
395474
// the outline read. The sessions are the caller's to name — the channel lists the caller's
@@ -403,7 +482,11 @@ export function install(rt) {
403482
if (index === null) return { rows: [], more: 0 }
404483
const sessions = [...new Set(sessionIds)]
405484
for (const sessionId of sessions) await catchUp(index, { sessionId }).catch(error => rt.warn('ds-bot: indexing %s failed: %s', sessionId, error))
406-
return matchedRows(index, sessions, terms, limit, undefined)
485+
const found = matchedRows(index, sessions, terms, limit, undefined)
486+
if (!readOnly()) return found
487+
// A message newer than the mark was answered as missing, and `more: 0` called that whole.
488+
const tail = await unindexedRows(index, sessions, terms)
489+
return tail.some.length === 0 ? found : withLogRows(found, tail, limit)
407490
}
408491

409492
// The latest messages across all parts, oldest first; `more` is how many the cap left out (#1906).

‎core/test/chat-index-writers.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,53 @@ test('a read-only window reads the index and leaves it alone (#2711)', async (t)
303303
}
304304
})
305305

306+
// #3319. The palette's whole-text search in a read-only window answered only what the writer
307+
// had indexed, so a line in the log past the mark was not found, and `more: 0` read as "there
308+
// is nothing else" while the line sat there. The window now matches its own log after the mark
309+
// in memory, without writing the index.
310+
test('a read-only window searches the log past its index mark (#3319)', async (t) => {
311+
const home = scratch(t)
312+
const writer = await start(t, home)
313+
assert.deepEqual(anchorsOf(await writer.rt.latestOwnChat('a', {})), ['0', '1', '2'])
314+
await writer.stop()
315+
316+
// The writer stopped before indexing the fourth line: the index mark ends at seq 2.
317+
HISTORY.solo.push(line(3, 'a fourth NEEDLE line'))
318+
try {
319+
const reader = await start(t, home, { heldBy: process.ppid })
320+
await reader.rt.load()
321+
assert.notEqual(reader.rt.readOnly(), undefined, 'this window must be read-only for the case to mean anything')
322+
323+
// The indexed part of the log is answered as before, from the index.
324+
const older = await reader.rt.searchHomeChat(['solo'], 'third', {})
325+
assert.equal(older.rows.length, 1, JSON.stringify(older))
326+
327+
// The line past the mark is in this window's log, so the query finds it.
328+
const found = await reader.rt.searchHomeChat(['solo'], 'NEEDLE', {})
329+
assert.equal(found.rows.length, 1, JSON.stringify(found))
330+
assert.equal(found.rows[0].session, 'solo')
331+
assert.equal(found.rows[0].seq, 3)
332+
assert.match(found.rows[0].text, /NEEDLE/)
333+
assert.equal(found.more, 0)
334+
335+
// The palette's own call: the channel action answers the same through /api/bot.
336+
assert.notEqual(reader.route, undefined, 'the channel registered its /api/bot route')
337+
const response = await reader.route.fetch(new Request('http://localhost/api/bot', {
338+
method: 'POST',
339+
body: JSON.stringify({ endpoint: 'chats.search', payload: { query: 'NEEDLE' } }),
340+
}))
341+
const result = await response.json()
342+
assert.equal(result.ok, true, JSON.stringify(result))
343+
assert.equal(result.value.rows.length, 1, JSON.stringify(result.value))
344+
assert.match(result.value.rows[0].text, /NEEDLE/)
345+
346+
// A read is a read: the index the writer left is still the writer's.
347+
assert.equal(rowsOf(home), 3)
348+
} finally {
349+
HISTORY.solo.pop()
350+
}
351+
})
352+
306353
test('a read-only window reads the index while the writer still holds the home (#2711)', async (t) => {
307354
const home = scratch(t)
308355
const writer = await start(t, home)

‎docs/subsystems/core-host.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,8 @@ has lines (#2790, `core/test/room-read-floor-clamp.test.js`).
474474
- The client's command palette searched each chat's `turnOutline` projection, whose prompt and response previews stop at 50/120 characters, so a hit past that budget — most of any long reply — found nothing. The index this file already keeps holds the whole text, so the search became a host read: `chat-index.js` lifts the term/any-term core of `searchOwnChat` into `matchedRows` (both reads share it; `searchOwnChat` answers byte for byte as before) and adds `rt.searchHomeChat(sessionIds, query, { limit })` — raw rows (`text, session, seq, time, who, turn`), best first, over the sessions the caller names. Each named session is caught up bare first, exactly as a Bot's parts are; no `endedAt` is known there, so nothing seals. Without an index there are no rows and the palette keeps its outline search.
475475
- Every indexed line carries the turn it belongs to by number: `lines.turn` (and `marks.turnNo`, what the next catch-up resumes from), tracked from the number a `turn/start` event carries, `INDEX_VERSION` 4 → 5 — a bump rides the same drop-and-rebuild path as #2711's. A line written before any turn, or after a `turn/start` that carried no number, keeps `-1`, which the client reads as no turn to jump to.
476476
- The channel endpoint is `chats.search` (`{ query }` → `{ rows: [{ chat, turn, text, part? }], more }`, `text` an `excerpt` around the first term the row holds, `part` the Session id of the part the hit was said in — set only for a Bot's own chat, and absent from a room's row, because a room's member part is not a chat the palette may open (#3114)): the sessions are taken from `view(actor)` — the same narrowing the `state` answer carries — but each Bot's parts map to their chat id only while `sessionOwnedBy` passes, and every member/owned room's parts map unconditionally. The view keeps an other-owner Bot so a shared room renders, and that Bot's own chat is not room content, so the ownership test is what stops a signed-in member from reading another member's Bot chats here, while a room's own parts stay searchable because the room is shared. `authorize` and this channel handler are installed as a pair (`authz.js` defines `rt.authorize`; `channel.js:326` calls it before its switch), and mounting the handler alone is fail-open — `channel.js:370` then skips every ownership test — so the two are never reused separately; a host whose `authzEnforced()` answers `false` is a supported single-user install, not a missing pair. `authz.js` allows the endpoint for any signed-in actor the way `schedules` is allowed (the handler scopes), and the channel's `READS` whitelist carries it, so a second read-only window answers it too.
477-
- Covered by `core/test/chat-index-writers.test.js` (a line whose match sits 300 characters past the preview budget, with its turn; the endpoint scoped to the signed-in member through the real `/api/bot` route; and a shared room where the other member's Bot own chat stays unreadable while the room's own Session is found, with `earlier` and `sessionOwnedBy` still refusing it) and `core/test/authz.test.js` (allowed for a signed-in actor, refused without one).
477+
- A read-only window answers the palette from its own log (#3319). `catchUp` adds nothing there, so a part whose log runs past `marks.through` answered nothing for a message the window held, and `more: 0` called that the whole chat. `searchHomeChat` now reads each such session's events after its mark (`eventsBackwards` from `through`, `HISTORY_TIMEOUT_MS`) and matches them in memory; the rows are built by `markedRows`, the same pass `catchUp` inserts, so the shape the palette reads cannot drift from the index's. Nothing is written, and `more` keeps its meaning — hits the cap left out — instead of naming the index. A window whose index is caught up, and a writer window (which catches up first), answer byte for byte as before.
478+
- Covered by `core/test/chat-index-writers.test.js` (a line whose match sits 300 characters past the preview budget, with its turn; the endpoint scoped to the signed-in member through the real `/api/bot` route; a shared room where the other member's Bot own chat stays unreadable while the room's own Session is found, with `earlier` and `sessionOwnedBy` still refusing it; and a read-only window finding a line past its mark while the index it reads stays the writer's) and `core/test/authz.test.js` (allowed for a signed-in actor, refused without one).
478479

479480
### Out-of-app delivery, first half (#355)
480481

0 commit comments

Comments
 (0)