Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/index.api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,8 @@ MailFields · interface · labels: string[];
MailFields · interface · thread: string;
MailFields · interface · read: boolean | null;
MailFields · interface · flagged: boolean | null;
MailFields · interface · mailType?: MailType;
MailFields · interface · reach?: MailTypeOf["reach"];
MailFields · interface · senderScore?: {
MailFields · interface · score: number;
MailFields · interface · signals: string[];
Expand Down
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@
"noExcessiveLinesPerFile": {
"level": "error",
"options": {
"maxLines": 1033
"maxLines": 1038
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions changes/feat-search-mail-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
### Added

- **Mail search filters by mail type and reach.** `type:` takes one of the [mail types](../docs/dev/GLOSSARY.md#mail-types)
and `reach:` takes `direct`, `group` or `broadcast`, in the query itself, so a page is never short:
`memo search mail 'type:order OR type:bill'`, `memo search mail 'invoice -type:promotion reach:direct'`. A search
that names either field first types the mail the store has not typed yet, 5,000 emails per write; on 100,000
untyped emails the first such search after an upgrade takes seconds, later ones the usual milliseconds. A store
opened read-only works the missing types out in memory for that search. tg and max refuse both as mail fields.
- **Email hits show their type and reach**: `email.mail_type` and `email.reach` in `--json`, and both on the hit's
line in mail's text output. In the API they are `MailFields.mailType` and `MailFields.reach` (experimental).
- **`SENDER_BOT_PREFIX` is exported from `@wirecat/cli-core/store`, and `MAIL_TYPES`, `MailType`, `REACHES` and
`Reach` from `@wirecat/cli-core/store/areas`** (experimental), so a CLI no longer copies them.
4 changes: 2 additions & 2 deletions docs/dev/GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ Verbs used but not in cli-base's vocabulary, by CLI (2026-10-12). Each needs a r
| organization | a company, team, family or community | entity | none |
| person | one human, across every messenger and mail (`person:<uid>`) | user, people | tg bot help: "user:<id> for a person", "the person's user id"; drive `people` |
| bot | a program that writes to the owner: a no-reply or alert address, a messenger's bot, a service's mail; an entity apart from people, with a name, identities and an optional organization, and no ties, tasks or merge review (`sender-bot:<id>`, the `sender_bots` table). Not an agent: `bot:<id>` and the `bots` table are agents that work here | automated person, sender (for a bot) | `people list kind:automated` still lists people a name or a bulk mailbox marks; memo's `{ bot }` author and `bot list` mean agents and a messenger's bot account |
| mail type | what one email is, apart from who sent it: one of the words in [Mail types](#mail-types), worked out per email from what the store keeps of it (`emails.mail_type`, key `mailType`). A sender's view is a summary of its mail, so a shop that sends receipts and sales counts under `order` and under `promotion` | category, kind (a person's `kind` is another thing), label | none |
| mail type | what one email is, apart from who sent it: one of the words in [Mail types](#mail-types), worked out per email from what the store keeps of it (`emails.mail_type`; key `mailType` in the API, `mail_type` in CLI JSON; search field `type:`). A sender's view is a summary of its mail, so a shop that sends receipts and sales counts under `order` and under `promotion` | category, kind (a person's `kind` is another thing), label | none |
| sorting rule | the owner's or the program's word on what mail is, by one of five scopes tried in this order: one mail, a List-Id or a subject pattern, an address, a registrable domain; then the header classifier. It sets a mail type, makes the sender a bot or a person for its whole history, or files the sender under an organization (`mail_sort_rules`, `store.mail.sorting`). An email it typed has `typeSignal` `rule:<id>`. Not a mail rule: `mail_rules` decide how one account's sync stores mail | filter, mail rule, label rule | none |
| reach | how a message reached the owner: `direct` (to the owner or a few people), `group` (a large group or a discussion list), `broadcast` (one sender to many readers who cannot answer in place). Worked out per email (`emails.reach`) and per sender (`people list`) | audience, scope | none |
| reach | how a message reached the owner: `direct` (to the owner or a few people), `group` (a large group or a discussion list), `broadcast` (one sender to many readers who cannot answer in place). Worked out per email (`emails.reach`, key `reach`, search field `reach:`) and per sender (`people list`) | audience, scope | none |
| contact | one person as one source knows them: a mail correspondent, a Telegram user, a Drive owner, a calendar attendee; an `identities` row | user | none found beyond the above |
| entity | the thing the owner means — a person, an event, a document; it carries no provider id ([WC-DATA-2](https://github.com/WireCatLabs/cli-base/blob/main/docs/standards/data-model.md)) | record, object | none |
| source record | one source's copy of an entity, keyed by account and `external_id`: a contact, a Zoom meeting, an email, a message | entity, item | none |
Expand Down
10 changes: 8 additions & 2 deletions docs/search/query-language.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ StandardSyntaxParser и PrecedenceQueryParser, default AND, default field `text`
`bcc:` (человек, как в `from:`), `subject:` (слова темы) и `mailbox:` (папка или ярлык по id или имени;
`label:` — то же самое), `is:unread`, `is:read` и `is:starred` (письмо не прочитано, прочитано, помечено
флагом — как их показал почтовый ящик при импорте; письмо, для которого импорт этого не узнал, не находит
ни `is:read`, ни `is:unread`). `is:starred` находит и сообщения, которые владелец отметил звёздочкой
ни `is:read`, ни `is:unread`), `type:` (тип письма, одно из слов [Mail types](../dev/GLOSSARY.md#mail-types):
`type:order OR type:bill`) и `reach:` (как письмо дошло: `direct`, `group`, `broadcast`). Тип хранится лениво: поиск
с `type:` или `reach:` сначала определяет и сохраняет тип писем, у которых его ещё нет, пачками по 5 000 (первый такой
поиск после обновления на 100 000 писем — секунды); хранилище, открытое только для чтения, определяет их в памяти на
время поиска. `is:starred` находит и сообщения, которые владелец отметил звёздочкой
(`messages star`), где у мессенджера есть звёзды. Профиль действует и для MCP-инструментов `search_*` (`source` у каждого).
Поле, которого у вида нет, в `search all` пропускает этот вид, и ответ называет причину в `skipped`. `bot search messages`
читает тот же язык в копиях ботов; строгий поиск общего архива выбирает bot accounts через `in:bots`.
Expand Down Expand Up @@ -454,6 +458,8 @@ enum или unsupported сочетание дают ошибку, а не пус
| `label` | kw | the same as mailbox:; mail only | `label:Projects` | term, phrase, wildcard |
| `list` | kw | the List-Id of a mailing list, lower case; a domain matches every list under it; mail only | `list:github.com` | term, phrase |
| `is` | enum | unread, read, starred | `is:unread` | term, phrase |
| `type` | enum | auto_reply, security, calendar, travel, event_ticket, order, shipping, bill, social_notification, discussion_list, newsletter, promotion, system_alert, account_notice, personal, other | `type:order OR type:bill` | term, phrase |
| `reach` | enum | direct, group, broadcast | `reach:direct` | term, phrase |
| `chat` | kw | account-scoped: an id or chat: reference as is; with * or ? a pattern over title, @username (up to 50); else a title | `chat:*fixture*` | term, phrase, wildcard |
| `date` | time | ISO/calendar timezone; today, yesterday, 30m/2h/7d ago | `date:[2026-01-01 TO 2026-02-01}` | term, phrase, range |
| `source` | enum | internal, file | `source:internal` | term, phrase |
Expand Down Expand Up @@ -907,7 +913,7 @@ Low-level `searchStore` и `MessagesService.search` без language сохран
фразы, `from:` `to:` `cc:` `subject:` `body:` (слово или фраза), `is:unread|read|starred` и `date:`
(на день шире с каждой стороны: сервер считает дни в своём поясе). Верхний OR — отдельный поиск на
ветку; вызов — одна ветка в одной папке, не больше 3, 100 новейших писем на вызов. Остальное
(`has:`, `list:`, `mailbox:`, отрицания, шаблоны, `from:me`) — только локально; запрос без того, что
(`has:`, `list:`, `mailbox:`, `type:`, `reach:`, отрицания, шаблоны, `from:me`) — только локально; запрос без того, что
сервер читает, его не спрашивает (`no_words`). IMAP ищет подстроку без форм слов, поэтому сервер
может не найти другую форму слова; строгий проход убирает лишние находки, но не возвращает
пропущенные. Gmail получает `X-GM-RAW` по All Mail, другие серверы — `UID SEARCH` по INBOX, Sent и
Expand Down
2 changes: 2 additions & 0 deletions src/cli/messenger/message-items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ export const messageItem = (message: ReadMessage, reader: AccountKey): MessageIt
thread: message.email.thread,
read: message.email.read,
flagged: message.email.flagged,
mail_type: message.email.mailType,
reach: message.email.reach,
sender_score: message.email.senderScore,
},
provider_metadata: message.providerMetadata,
Expand Down
2 changes: 2 additions & 0 deletions src/cli/messenger/search-answers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export const messageHitItem = (hit: FoundMessage, query = ""): MessageHitItem =>
thread: hit.email.thread,
read: hit.email.read,
flagged: hit.email.flagged,
mail_type: hit.email.mailType,
reach: hit.email.reach,
sender_score: hit.email.senderScore,
}
: undefined,
Expand Down
5 changes: 5 additions & 0 deletions src/domain/models.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { MailType, MailTypeOf } from "../mail/mail-types.js"
import type { Upload } from "./attachments.js"
import type { CounterObservation, CounterObservations } from "./counters.js"

Expand Down Expand Up @@ -477,6 +478,10 @@ export interface MailFields {
thread: string
read: boolean | null
flagged: boolean | null
/** What the email is, apart from its sender. @experimental */
mailType?: MailType
/** How it reached the owner. @experimental */
reach?: MailTypeOf["reach"]
/** How much the sender's mail looks like spam, a scam or a robot, and why; absent when the sender is not scored. */
senderScore?: { score: number; signals: string[]; demoted?: true }
}
Expand Down
4 changes: 4 additions & 0 deletions src/entities/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ export const message = v.strictObject({
thread: reference,
read: v.nullable(v.boolean()),
flagged: v.nullable(v.boolean()),
/** What the email is, apart from its sender: one of the mail types. @experimental */
mail_type: v.optional(text),
/** How it reached the owner: direct, group or broadcast. @experimental */
reach: v.optional(text),
/** How much the sender's mail looks like spam, a scam or a robot (memo's score), and why; absent when unscored. */
sender_score: v.optional(
v.strictObject({ score: v.number(), signals: v.array(text), demoted: v.optional(v.literal(true)) }),
Expand Down
2 changes: 1 addition & 1 deletion src/mail/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ const searchCommand = (mail: MailReads): Command => {
"after",
`
Fields: from: to: cc: bcc: subject: body: mailbox: (or label:) list: (a List-Id or its domain) is:unread|read|starred
has:attachment, filename:, content: (the text of attachments), size>, date: — \`${mail.app.command} personal search messages 'content:invoice'\`.
type: (order, bill, promotion… — what the email is) reach:direct|group|broadcast has:attachment, filename:, content: (the text of attachments), size>, date: — \`${mail.app.command} personal search messages 'content:invoice'\`.
chat: names a thread by its subject. Mail sent to many is in the mailbox bulk; NOT mailbox:bulk leaves it out.
Mail from senders with signs of fraud comes after the rest of the page; --plain-order keeps it in place.
--json: the list is items; each hit's reference is ref (msg:email/…), which messages show reads.${
Expand Down
1 change: 1 addition & 0 deletions src/mail/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export const hitText = (
mail.to.length ? `to ${names(mail.to)}` : "",
mail.cc.length ? `cc ${names(mail.cc)}` : "",
mail.labels.join(", "),
[mail.mailType, mail.reach].filter(Boolean).join(", "),
]
.filter(Boolean)
.join(" · ")
Expand Down
25 changes: 25 additions & 0 deletions src/search/lucene/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
} from "@wirecat/cli-base/query"
import * as v from "valibot"
import { tagOf } from "../../domain/tags.js"
import { MAIL_TYPES } from "../../mail/mail-types.js"
import { REACHES } from "../../store/sqlite/sender-signals.js"
import { MOST_WORDS_APART, QUERY_LIMITS, SEARCH_QUERY, searchError } from "./types.js"

export const FIELD_VERSION = 2
Expand Down Expand Up @@ -173,6 +175,29 @@ export const QUERY_FIELDS: readonly MessageField[] = [
support: "A1",
values: ["unread", "read", "starred"],
},
{
name: "type",
example: "type:order OR type:bill",
index: "emails.mail_type (emails_by_mail_type)",
aliases: [],
type: "enum",
operators: terms,
normalization:
"lowercase; what one email is, apart from its sender; mail not typed yet is typed before the search; mail only",
support: "A1",
values: MAIL_TYPES,
},
{
name: "reach",
example: "reach:direct",
index: "emails.reach",
aliases: [],
type: "enum",
operators: terms,
normalization: "lowercase; how one email reached the owner; mail only",
support: "A1",
values: REACHES,
},
{
name: "chat",
example: "chat:*fixture*",
Expand Down
55 changes: 55 additions & 0 deletions src/services/mail-search.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { join } from "node:path"
import { afterEach, describe, expect, it } from "vitest"
import { formatLocator } from "../domain/locator.js"
import type { AttachmentInput, EmailInput } from "../store/index.js"
import { openCache } from "../store/open.js"
import { type AccountKey, type MessageStore, openStore, type ScoredHit } from "../store/store.js"
import { storeOnlyDeps } from "./deps.js"
import { embeddingsService } from "./embeddings.js"
Expand Down Expand Up @@ -290,6 +291,60 @@ describe("search mail over the mail tables", () => {
expect(await found(store, "link:click?id=1")).toEqual(["<news@example.com>"])
})

it("filters by mail type and reach, typing the mail the store has not typed yet", async () => {
const path = join(mkdtempSync(join(tmpdir(), "mail-types-search-")), "store.db")
const typed = await openStore({ path })
live.push(typed)
const owner = await typed.accounts.saveAccount(MAIL, { name: null })
await typed.mail.saveThread({
accountId: owner,
externalId: "thread-9",
now: at(10),
emails: [
email("<order@example.com>", {
subject: "Thank you for your order #4411",
from: { address: "orders@shop.example.com", name: "Shop" },
}),
email("<bill@example.com>", {
subject: "Your bill is ready",
from: { address: "billing@phone.example.com", name: "Phone Co" },
}),
email("<team@example.com>", {
subject: "All hands",
to: Array.from({ length: 12 }, (_, i) => ({ address: `colleague${i}@example.com`, name: null })),
}),
],
})
const untyped = await openCache(path)
live.push({ close: async () => untyped.close() } as MessageStore)
const left = () => Number(untyped.prepare("SELECT count(*) AS n FROM emails WHERE mail_type IS NULL").get()?.n)
const sorted = async (text: string, on = typed) =>
(await searchStore(on, MAIL, { text, kind: "mail", limit: 10 })).items.map(({ id }) => id).sort()

expect(await sorted("roadmap")).toHaveLength(3)
expect(left()).toBe(3)

const readOnly = await openStore({ path, readOnly: true })
live.push(readOnly)
expect(await sorted("type:order OR type:BILL", readOnly)).toEqual(["<bill@example.com>", "<order@example.com>"])
expect(left()).toBe(3)

expect(await sorted("type:order OR type:BILL")).toEqual(["<bill@example.com>", "<order@example.com>"])
expect(left()).toBe(0)
expect(await sorted("reach:group")).toEqual(["<team@example.com>"])
expect(await sorted("roadmap -type:bill -reach:group")).toEqual(["<order@example.com>"])
expect(await sorted("bill type:bill")).toEqual(["<bill@example.com>"])
expect(await sorted("bill type:order")).toEqual([])

const [hit] = (await searchStore(typed, MAIL, { text: "type:order", kind: "mail", limit: 1 })).items
expect(hit?.email).toMatchObject({ mailType: "order", reach: "direct" })
await expect(search(typed, "type:receipt")).rejects.toThrow("type takes auto_reply")
await expect(search(typed, "reach:everyone")).rejects.toThrow("reach takes direct, group, broadcast")
await expect(
searchStore(typed, { provider: "tg", account: "1" }, { text: "type:order", limit: 5 }),
).rejects.toThrow("type: is a mail field")
})

it("refuses messenger-only fields", async () => {
const { store } = await seeded()
await expect(search(store, "kind:group")).rejects.toThrow("mail has no kind")
Expand Down
2 changes: 1 addition & 1 deletion src/services/messages-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import type { SearchFound, SearchQuery } from "./messages.js"
import { accountsOfKind, listedAccounts, MAIL } from "./search-kind.js"

const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"])
const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list"])
const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list", "type", "reach"])

import {
type Predicate,
Expand Down
3 changes: 3 additions & 0 deletions src/store/areas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
* Store area types and constants some CLIs use beyond the stable `@wirecat/cli-core/store`: experimental, so a
* minor release may change them.
*/

export { MAIL_TYPES, type MailType } from "../mail/mail-types.js"
export {
type AddedSource,
type AddedSourceContent,
Expand Down Expand Up @@ -51,6 +53,7 @@ export type {
SenderBot,
SenderBotDetails,
} from "./sqlite/sender-bots.js"
export { REACHES, type Reach } from "./sqlite/sender-signals.js"
export type { SubscriptionFilter } from "./sqlite/subscriptions.js"
export { PROJECT_TASK_FIELDS, TASK_SORTS, type TaskSort } from "./sqlite/task-board.js"
export { TASK_RELATION_KINDS, type TaskRelationKind } from "./sqlite/task-relations.js"
Expand Down
2 changes: 1 addition & 1 deletion src/store/public.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export {
TASK_TYPES,
WORK_TASK_TYPES,
} from "../domain/knowledge.js"
export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js"
export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js"
export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js"
export type {
TagConsolidationApplyOptions,
Expand Down
Loading
Loading