@wirecat/cli-core 1.0.0-rc.0 → 1.0.0

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/THIRD_PARTY_NOTICES +4 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-rename.js +1 -1
  5. package/dist/cli/bot/api-input.d.ts +5 -0
  6. package/dist/cli/bot/api-input.js +6 -1
  7. package/dist/cli/bot/api.js +7 -1
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/service-api.js +3 -1
  10. package/dist/crm/manifest/map.d.ts +5 -2
  11. package/dist/crm/manifest/map.js +14 -2
  12. package/dist/domain/organization-sectors.d.ts +10 -0
  13. package/dist/domain/organization-sectors.generated.d.ts +11 -0
  14. package/dist/domain/organization-sectors.generated.js +14 -0
  15. package/dist/domain/organization-sectors.js +9 -0
  16. package/dist/domain/person-kinds.d.ts +1 -1
  17. package/dist/entities/index.d.ts +1 -0
  18. package/dist/entities/knowledge-lists.d.ts +1 -0
  19. package/dist/entities/knowledge-lists.js +2 -0
  20. package/dist/errors/reasons.js +12 -3
  21. package/dist/mail/score.d.ts +2 -0
  22. package/dist/mail/score.js +9 -2
  23. package/dist/services/metadata.d.ts +1 -1
  24. package/dist/services/search-all-rank.d.ts +44 -0
  25. package/dist/services/search-all-rank.js +112 -0
  26. package/dist/services/search-all-tracker.d.ts +58 -0
  27. package/dist/services/search-all-tracker.js +155 -0
  28. package/dist/services/search-all.d.ts +1 -8
  29. package/dist/services/search-all.js +18 -199
  30. package/dist/services/tracker-meaning.js +1 -1
  31. package/dist/store/areas.d.ts +1 -0
  32. package/dist/store/index.d.ts +1 -0
  33. package/dist/store/people.d.ts +22 -1
  34. package/dist/store/people.js +15 -1
  35. package/dist/store/sqlite/domain-organizations.d.ts +33 -0
  36. package/dist/store/sqlite/domain-organizations.js +230 -0
  37. package/dist/store/sqlite/knowledge.d.ts +2 -9
  38. package/dist/store/sqlite/manifest.js +2 -0
  39. package/dist/store/sqlite/migrations.generated.js +21 -0
  40. package/dist/store/sqlite/organizations.d.ts +12 -1
  41. package/dist/store/sqlite/organizations.js +9 -1
  42. package/dist/store/sqlite/people-list.d.ts +6 -1
  43. package/dist/store/sqlite/people-list.js +66 -14
  44. package/dist/store/sqlite/person-match-scan.js +11 -1
  45. package/dist/store/sqlite/schema/sender-bots.d.ts +288 -0
  46. package/dist/store/sqlite/schema/sender-bots.js +22 -0
  47. package/dist/store/sqlite/schema.d.ts +1 -0
  48. package/dist/store/sqlite/schema.js +2 -0
  49. package/dist/store/sqlite/sender-bots.d.ts +43 -0
  50. package/dist/store/sqlite/sender-bots.js +189 -0
  51. package/dist/store/sqlite/sender-signals.d.ts +5 -2
  52. package/dist/store/sqlite/sender-signals.js +6 -6
  53. package/dist/store/sqlite/tracker.d.ts +11 -9
  54. package/dist/store/sqlite/tracker.js +27 -12
  55. package/dist/store/sqlite/work-tasks.js +2 -0
  56. package/dist/tracker/cli/index.d.ts +1 -1
  57. package/dist/tracker/cli/index.js +83 -24
  58. package/dist/tracker/sync.js +43 -20
  59. package/dist/tracker/writes.d.ts +28 -0
  60. package/dist/tracker/writes.js +141 -19
  61. package/package.json +3 -3
@@ -266,6 +266,7 @@ export const bots = sqliteTable("bots", {
266
266
  index("bots_by_owner_person_id").on(table.ownerPersonId),
267
267
  check("bots_metadata_json", sql `"metadata" IS NULL OR json_valid("metadata")`),
268
268
  ]);
269
+ export { senderBotMoves, senderBots } from "./schema/sender-bots.js";
269
270
  export const chats = sqliteTable("chats", {
270
271
  id: integer("id").primaryKey({ autoIncrement: true }),
271
272
  accountId: integer("account_id")
@@ -669,6 +670,7 @@ export const emails = sqliteTable("emails", {
669
670
  unique().on(table.accountId, table.externalId),
670
671
  index("emails_by_time").on(table.accountId, desc(table.sentAt)),
671
672
  index("emails_by_mail_rule_id").on(table.mailRuleId).where(sql `mail_rule_id IS NOT NULL`),
673
+ index("emails_by_list_id").on(sql `coalesce(json_extract(headers, '$."list-id"'), json_extract(metadata, '$.listId'))`),
672
674
  index("emails_by_email_thread_id").on(table.emailThreadId),
673
675
  index("emails_by_from_identity_id").on(table.fromIdentityId),
674
676
  check("emails_references_json", sql `"references" IS NULL OR json_valid("references")`),
@@ -0,0 +1,43 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { IdentityRef, PersonRecord } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export declare const SENDER_BOT_PREFIX = "sender-bot:";
5
+ export type BotAuthor = "rules" | "owner";
6
+ /** A sender bot as the people list reads it, keyed by the person row whose identities are the bot's. */
7
+ export interface HeldBot {
8
+ id: number;
9
+ author: BotAuthor;
10
+ name: string | null;
11
+ }
12
+ export interface SenderBot {
13
+ bot: string;
14
+ /** The person row whose identities are the bot's: its handle in `people list` and `people show`. */
15
+ person: string;
16
+ name: string | null;
17
+ author: BotAuthor;
18
+ reason: string | null;
19
+ }
20
+ export declare const senderBotsOf: (database: CacheDatabase) => Map<number, HeldBot>;
21
+ /** People holding an identity the owner last moved to a person, or kept as one: no rule makes them a bot. */
22
+ export declare const ownerPeopleOf: (database: CacheDatabase) => Set<number>;
23
+ export declare const refuseBotAssignee: (database: CacheDatabase, person: number) => void;
24
+ /** A rule's move of a whole person to a bot, or of a rule's bot back to a person; the caller holds the write lock. */
25
+ export declare const ruleMove: (database: CacheDatabase, person: number, to: "bot" | "person", reason: string, at: number) => void;
26
+ /**
27
+ * The owner's word that a person, or one of their identities, is a program, for its whole history: its messages stay
28
+ * where they are, and no rule moves it back. `bot` joins it to a bot already stored; one identity of a person with
29
+ * others gets a person row of its own first.
30
+ */
31
+ export declare const moveToBot: (context: StoreContext, subject: string | IdentityRef, options?: {
32
+ bot?: string;
33
+ name?: string;
34
+ reason?: string;
35
+ }) => SenderBot;
36
+ /**
37
+ * The owner's word that a bot, a person or one identity is a person, for its whole history; no rule makes it a bot
38
+ * again. `person` joins it to that person; one identity of a bot with others gets a person row of its own.
39
+ */
40
+ export declare const moveToPerson: (context: StoreContext, subject: string | IdentityRef, options?: {
41
+ person?: string;
42
+ reason?: string;
43
+ }) => PersonRecord;
@@ -0,0 +1,189 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { releaseDomainHolds } from "./domain-organizations.js";
3
+ import { currentPerson } from "./merged-persons.js";
4
+ import { isOwner, mergePerson, move, recordOf, renameAfterLeaving, required, unlinkIdentity } from "./person-links.js";
5
+ import { write } from "./transaction.js";
6
+ export const SENDER_BOT_PREFIX = "sender-bot:";
7
+ export const senderBotsOf = (database) => new Map(database
8
+ .prepare("SELECT id, person_id, author, name FROM sender_bots")
9
+ .all()
10
+ .map((row) => [
11
+ Number(row.person_id),
12
+ { id: Number(row.id), author: row.author, name: row.name == null ? null : String(row.name) },
13
+ ]));
14
+ /** People holding an identity the owner last moved to a person, or kept as one: no rule makes them a bot. */
15
+ export const ownerPeopleOf = (database) => new Set(database
16
+ .prepare("SELECT DISTINCT l.person_id AS person FROM sender_bot_moves m JOIN identity_links l ON l.identity_id = m.identity_id " +
17
+ "WHERE m.author = 'owner' AND m.to_bot_id IS NULL " +
18
+ "AND m.id = (SELECT max(id) FROM sender_bot_moves WHERE identity_id = m.identity_id)")
19
+ .all()
20
+ .map((row) => Number(row.person)));
21
+ export const refuseBotAssignee = (database, person) => {
22
+ if (database.prepare("SELECT 1 FROM sender_bots WHERE person_id = ?").get(person) !== undefined)
23
+ throw new CliError("validation_error", `person:${person} is a sender bot, which is no one's assignee`, {
24
+ reason: "sender-bot.assignee",
25
+ });
26
+ };
27
+ const identitiesOf = (database, person) => database
28
+ .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
29
+ .all(person)
30
+ .map((row) => Number(row.identity_id));
31
+ const logMoves = (database, identities, from, to, { author, reason, at }) => {
32
+ const row = database.prepare("INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, reason, " +
33
+ "created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
34
+ for (const identity of identities)
35
+ row.run(identity, from.person ?? null, from.bot ?? null, to.person ?? null, to.bot ?? null, author, reason, at);
36
+ };
37
+ const createBot = (database, person, { author, reason, at, name = null }) => Number(database
38
+ .prepare("INSERT INTO sender_bots (person_id, name, author, reason, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) " +
39
+ "RETURNING id")
40
+ .get(person, name, author, reason, at, at)?.id);
41
+ /** A rule's move of a whole person to a bot, or of a rule's bot back to a person; the caller holds the write lock. */
42
+ export const ruleMove = (database, person, to, reason, at) => {
43
+ const identities = identitiesOf(database, person);
44
+ const options = { author: "rules", reason, at };
45
+ if (to === "bot") {
46
+ const bot = createBot(database, person, options);
47
+ logMoves(database, identities, { person }, { bot }, options);
48
+ return;
49
+ }
50
+ const held = database.prepare("SELECT id FROM sender_bots WHERE person_id = ? AND author = 'rules'").get(person);
51
+ if (held === undefined)
52
+ return;
53
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(Number(held.id));
54
+ logMoves(database, identities, { bot: Number(held.id) }, { person }, options);
55
+ };
56
+ const botRow = (database, ref) => {
57
+ const id = ref.startsWith(SENDER_BOT_PREFIX) ? ref.slice(SENDER_BOT_PREFIX.length) : "";
58
+ const row = /^[1-9]\d*$/.test(id)
59
+ ? database.prepare("SELECT id, person_id FROM sender_bots WHERE id = ?").get(Number(id))
60
+ : undefined;
61
+ if (row === undefined)
62
+ throw new CliError("not_found", `no ${ref} in the store`, { reason: "sender-bot.not-found", reference: ref });
63
+ return { id: Number(row.id), person: Number(row.person_id) };
64
+ };
65
+ const botOfPerson = (database, person) => {
66
+ const row = database.prepare("SELECT id FROM sender_bots WHERE person_id = ?").get(person);
67
+ return row === undefined ? undefined : Number(row.id);
68
+ };
69
+ const personRow = (database, ref) => {
70
+ const uid = ref.startsWith("person:") ? ref.slice("person:".length) : "";
71
+ const found = /^[1-9]\d*$/.test(uid) ? database.prepare("SELECT id FROM persons WHERE id = ?").get(uid) : undefined;
72
+ if (found === undefined)
73
+ throw new CliError("not_found", `no ${ref} in the store`, { reference: ref });
74
+ return currentPerson(database, Number(found.id));
75
+ };
76
+ /** What a move names: a whole person or bot, or one identity and the person it sits on. */
77
+ const subjectOf = (context, subject) => {
78
+ const { database } = context;
79
+ if (typeof subject !== "string") {
80
+ const found = required(context, subject);
81
+ const alone = identitiesOf(database, found.personPk).length === 1;
82
+ return alone ? { person: found.personPk } : { person: found.personPk, identity: found.pk, ref: subject };
83
+ }
84
+ if (subject.startsWith(SENDER_BOT_PREFIX))
85
+ return { person: botRow(database, subject).person };
86
+ return { person: personRow(database, subject) };
87
+ };
88
+ const senderBotOf = (database, id) => {
89
+ const row = database.prepare("SELECT person_id, name, author, reason FROM sender_bots WHERE id = ?").get(id);
90
+ return {
91
+ bot: `${SENDER_BOT_PREFIX}${id}`,
92
+ person: `person:${Number(row?.person_id)}`,
93
+ name: row?.name == null ? null : String(row.name),
94
+ author: row?.author,
95
+ reason: row?.reason == null ? null : String(row.reason),
96
+ };
97
+ };
98
+ /**
99
+ * The owner's word that a person, or one of their identities, is a program, for its whole history: its messages stay
100
+ * where they are, and no rule moves it back. `bot` joins it to a bot already stored; one identity of a person with
101
+ * others gets a person row of its own first.
102
+ */
103
+ export const moveToBot = (context, subject, options = {}) => {
104
+ const { database } = context;
105
+ return write(database, () => {
106
+ const at = context.now();
107
+ const log = { author: "owner", reason: options.reason ?? null, at };
108
+ const chosen = subjectOf(context, subject);
109
+ if (isOwner(context, chosen.person))
110
+ throw new CliError("validation_error", "the owner's own person is never a bot", { reason: "sender-bot.owner" });
111
+ const target = options.bot === undefined ? undefined : botRow(database, options.bot);
112
+ const from = { person: chosen.person, bot: botOfPerson(database, chosen.person) };
113
+ const claim = (bot) => database
114
+ .prepare("UPDATE sender_bots SET author = 'owner', name = coalesce(?, name), updated_at = ? WHERE id = ?")
115
+ .run(options.name ?? null, at, bot);
116
+ if (target !== undefined && target.person !== chosen.person) {
117
+ const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
118
+ if (chosen.identity === undefined) {
119
+ mergePerson(context, chosen.person, target.person, { method: "bot", by: "owner" });
120
+ if (from.bot !== undefined)
121
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(from.bot);
122
+ }
123
+ else {
124
+ move(context, chosen.identity, chosen.person, target.person, { method: "bot", by: "owner" });
125
+ renameAfterLeaving(context, chosen.person, [chosen.identity]);
126
+ }
127
+ claim(target.id);
128
+ logMoves(database, moving, from, { bot: target.id }, log);
129
+ return senderBotOf(database, target.id);
130
+ }
131
+ if (chosen.identity !== undefined && chosen.ref !== undefined) {
132
+ const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid);
133
+ const bot = createBot(database, alone, { ...log, name: options.name ?? null });
134
+ logMoves(database, [chosen.identity], from, { bot }, log);
135
+ return senderBotOf(database, bot);
136
+ }
137
+ const held = from.bot ?? createBot(database, chosen.person, { ...log, name: options.name ?? null });
138
+ if (from.bot !== undefined)
139
+ claim(held);
140
+ logMoves(database, identitiesOf(database, chosen.person), from, { bot: held }, log);
141
+ return senderBotOf(database, held);
142
+ });
143
+ };
144
+ /**
145
+ * The owner's word that a bot, a person or one identity is a person, for its whole history; no rule makes it a bot
146
+ * again. `person` joins it to that person; one identity of a bot with others gets a person row of its own.
147
+ */
148
+ export const moveToPerson = (context, subject, options = {}) => {
149
+ const { database } = context;
150
+ return write(database, () => {
151
+ const at = context.now();
152
+ const log = { author: "owner", reason: options.reason ?? null, at };
153
+ const chosen = subjectOf(context, subject);
154
+ const bot = botOfPerson(database, chosen.person);
155
+ const from = { person: chosen.person, bot };
156
+ const target = options.person === undefined ? undefined : personRow(database, options.person);
157
+ if (target !== undefined && botOfPerson(database, target) !== undefined)
158
+ throw new CliError("validation_error", `${options.person} is a bot; name a person`, {
159
+ reason: "sender-bot.not-a-person",
160
+ reference: options.person,
161
+ });
162
+ if (target !== undefined && target !== chosen.person) {
163
+ const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
164
+ if (chosen.identity === undefined)
165
+ mergePerson(context, chosen.person, target, { method: "manual", by: "owner" });
166
+ else {
167
+ move(context, chosen.identity, chosen.person, target, { method: "manual", by: "owner" });
168
+ renameAfterLeaving(context, chosen.person, [chosen.identity]);
169
+ }
170
+ if (bot !== undefined && identitiesOf(database, chosen.person).length === 0)
171
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
172
+ releaseDomainHolds(database, moving);
173
+ logMoves(database, moving, from, { person: target }, log);
174
+ return recordOf(context, target);
175
+ }
176
+ if (chosen.identity !== undefined && chosen.ref !== undefined && bot !== undefined) {
177
+ const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid);
178
+ releaseDomainHolds(database, [chosen.identity]);
179
+ logMoves(database, [chosen.identity], from, { person: alone }, log);
180
+ return recordOf(context, alone);
181
+ }
182
+ if (bot !== undefined)
183
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
184
+ const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
185
+ releaseDomainHolds(database, moving);
186
+ logMoves(database, moving, from, { person: chosen.person }, log);
187
+ return recordOf(context, chosen.person);
188
+ });
189
+ };
@@ -35,8 +35,11 @@ export declare const senderSignalsOf: (mail: readonly SentMail[], { addresses, o
35
35
  signals: SenderSignal[];
36
36
  reach: Reach | null;
37
37
  };
38
+ /** `bob+news@x` and `bob@x` are one sender. */
39
+ /** The senders of each of these List-Ids, through `emails_by_list_id`. */
40
+ export declare const LIST_SENDERS: string;
38
41
  /**
39
- * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
40
- * reads every stored email's List-Id once to tell a discussion list from a newsletter.
42
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: the
43
+ * senders of their List-Ids tell a discussion list from a newsletter.
41
44
  */
42
45
  export declare const sentMailOf: (database: CacheDatabase, people: readonly number[]) => Map<number, SentMail[]>;
@@ -54,10 +54,13 @@ export const senderSignalsOf = (mail, { addresses, ownerWrote, chatted }) => {
54
54
  };
55
55
  const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
56
56
  /** `bob+news@x` and `bob@x` are one sender. */
57
+ /** The senders of each of these List-Ids, through `emails_by_list_id`. */
58
+ export const LIST_SENDERS = `SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
59
+ `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`;
57
60
  const senderKey = (address) => address.toLowerCase().replace(/\+[^@]*@/, "@");
58
61
  /**
59
- * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
60
- * reads every stored email's List-Id once to tell a discussion list from a newsletter.
62
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: the
63
+ * senders of their List-Ids tell a discussion list from a newsletter.
61
64
  */
62
65
  export const sentMailOf = (database, people) => {
63
66
  const found = new Map();
@@ -79,10 +82,7 @@ export const sentMailOf = (database, people) => {
79
82
  const lists = [...new Set(rows.flatMap((row) => (typeof row.list === "string" ? [row.list] : [])))];
80
83
  const senders = new Map();
81
84
  if (lists.length > 0)
82
- for (const row of database
83
- .prepare(`SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
84
- `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`)
85
- .all(JSON.stringify(lists))) {
85
+ for (const row of database.prepare(LIST_SENDERS).all(JSON.stringify(lists))) {
86
86
  const list = String(row.list);
87
87
  const held = senders.get(list) ?? new Set();
88
88
  held.add(senderKey(String(row.address)));
@@ -14,15 +14,15 @@ export interface TrackerItem<K extends TrackerKind = TrackerKind> {
14
14
  export interface TrackerFilter {
15
15
  /** A comment's issue, an issue's, a state's or a label's team. */
16
16
  parent?: string;
17
- /** Issues only. */
18
- assignee?: string | null;
19
- project?: string;
20
- state?: string;
17
+ /** Issues only; several ids match any of them, as a name every team's state has. */
18
+ assignee?: string | readonly string[] | null;
19
+ project?: string | readonly string[];
20
+ state?: string | readonly string[];
21
21
  /** Issues whose state is of one of these types. */
22
22
  stateTypes?: readonly StateType[];
23
- label?: string;
23
+ label?: string | readonly string[];
24
24
  /** Issues only; `null`, the issues in no sprint. */
25
- sprint?: string | null;
25
+ sprint?: string | readonly string[] | null;
26
26
  /** Archived rows too; absent, only the live ones. */
27
27
  archived?: boolean;
28
28
  limit?: number;
@@ -59,16 +59,18 @@ export interface TrackerStore {
59
59
  /**
60
60
  * Upserts records of one kind; a field a record leaves out keeps its stored value, and a record listed again after
61
61
  * the tracker stopped listing it comes back. A record the tracker calls `deleted` is marked deleted, and an issue
62
- * takes its comments with it. Answers how many changed: a row read again as it was stored is not counted.
62
+ * takes its comments with it. Answers how many changed: a row read again as it was stored is not counted. `state`
63
+ * is the account's sync state saved in the same transaction, as a sync's cursor after the page.
63
64
  */
64
- save<K extends TrackerKind>(key: AccountKey, kind: K, records: readonly TrackerRecords[K][], now: number): Promise<number>;
65
+ save<K extends TrackerKind>(key: AccountKey, kind: K, records: readonly TrackerRecords[K][], now: number, state?: Record<string, string>): Promise<number>;
65
66
  /**
66
67
  * After a complete list of the kind's ids: marks deleted every stored one the list lacks that has not been synced
67
68
  * since `before`, so a row saved while the list was read is never taken for a deleted one, and the comments of an
68
- * issue it marks. Answers how many of the kind.
69
+ * issue it marks. Answers how many of the kind. `state` is saved in the same transaction; a dry run writes nothing.
69
70
  */
70
71
  removeUnlisted(key: AccountKey, kind: TrackerKind, listed: readonly string[], before: number, now: number, options?: {
71
72
  dryRun?: boolean;
73
+ state?: Record<string, string>;
72
74
  }): Promise<number>;
73
75
  get<K extends TrackerKind>(key: AccountKey, kind: K, externalId: string): Promise<TrackerItem<K> | undefined>;
74
76
  /** An issue by its readable key (`ENG-12`), in any letter case. */
@@ -4,8 +4,9 @@ import { clauseIn, probeOf, tokensOf, wordMatches, } from "../../search/word-mat
4
4
  import { fold, normalize } from "../normalize.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { excerptOf } from "./crm-files.js";
7
+ import { writeState } from "./sync.js";
7
8
  import { dropTrackerChunks, isChunkedTrackerKind, nearestTrackerItems, refreshTrackerChunks, trackerChunksLeft, trackerChunksToEmbed, trackerChunkWriter, trackerEmbedded, } from "./tracker-chunks.js";
8
- import { write } from "./transaction.js";
9
+ import { read, write } from "./transaction.js";
9
10
  import { dropUnusedVectors } from "./vector-index.js";
10
11
  const MOST = 500;
11
12
  /** How many rows the index may offer one search; each is read and its words checked. */
@@ -88,7 +89,11 @@ const queryOf = (words, exact) => {
88
89
  };
89
90
  export const trackerStoreOver = (context) => {
90
91
  const { database } = context;
91
- const save = (key, kind, records, now) => write(database, () => {
92
+ const saveStates = (accountId, state = {}) => {
93
+ for (const [name, value] of Object.entries(state))
94
+ writeState(context, accountId, name, value);
95
+ };
96
+ const save = (key, kind, records, now, state) => write(database, () => {
92
97
  const accountId = accountPk(context, key);
93
98
  const stored = database.prepare("SELECT data, title, body, deleted_at FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
94
99
  const issueDeletedAt = database.prepare("SELECT deleted_at FROM tracker_items WHERE account_id = ? AND kind = 'issue' AND external_id = ?");
@@ -179,6 +184,7 @@ export const trackerStoreOver = (context) => {
179
184
  released.push(hash);
180
185
  }
181
186
  dropUnusedVectors(database, released);
187
+ saveStates(accountId, state);
182
188
  return changed;
183
189
  });
184
190
  /**
@@ -202,12 +208,13 @@ export const trackerStoreOver = (context) => {
202
208
  comments.run(accountId, String(row.external_id), Number(row.deleted_at));
203
209
  }
204
210
  };
205
- const removeUnlisted = (key, kind, listed, before, now, { dryRun = false } = {}) => {
206
- const accountId = findAccountPk(context, key);
207
- if (accountId === undefined)
211
+ const removeUnlisted = (key, kind, listed, before, now, { dryRun = false, state } = {}) => {
212
+ const found = findAccountPk(context, key);
213
+ if (found === undefined && (dryRun || !state))
208
214
  return 0;
209
215
  const keep = new Set(listed);
210
- return write(database, () => {
216
+ return (dryRun ? read : write)(database, () => {
217
+ const accountId = found ?? accountPk(context, key);
211
218
  const mark = database.prepare("UPDATE tracker_items SET deleted_at = ? WHERE id = ?");
212
219
  let removed = 0;
213
220
  const marked = [];
@@ -229,8 +236,10 @@ export const trackerStoreOver = (context) => {
229
236
  if (isChunkedTrackerKind(kind))
230
237
  dropTrackerChunks(database, marked);
231
238
  deleteComments(database, accountId, issues, now);
232
- if (!dryRun)
239
+ if (!dryRun) {
233
240
  restoreListed(accountId, kind, listed);
241
+ saveStates(accountId, state);
242
+ }
234
243
  return removed;
235
244
  });
236
245
  };
@@ -254,13 +263,19 @@ export const trackerStoreOver = (context) => {
254
263
  if (value === null)
255
264
  sql += ` AND json_extract(t.data, '$.${field}') IS NULL`;
256
265
  else {
257
- sql += ` AND json_extract(t.data, '$.${field}') = ?`;
258
- params.push(value);
266
+ const ids = typeof value === "string" ? [value] : value;
267
+ sql += ids.length ? ` AND json_extract(t.data, '$.${field}') IN (${ids.map(() => "?").join(", ")})` : " AND 0";
268
+ for (const id of ids)
269
+ params.push(id);
259
270
  }
260
271
  }
261
272
  if (filter.label !== undefined) {
262
- sql += " AND EXISTS (SELECT 1 FROM json_each(t.data, '$.labels') l WHERE l.value = ?)";
263
- params.push(filter.label);
273
+ const ids = typeof filter.label === "string" ? [filter.label] : filter.label;
274
+ sql += ids.length
275
+ ? ` AND EXISTS (SELECT 1 FROM json_each(t.data, '$.labels') l WHERE l.value IN (${ids.map(() => "?").join(", ")}))`
276
+ : " AND 0";
277
+ for (const id of ids)
278
+ params.push(id);
264
279
  }
265
280
  if (filter.stateTypes?.length) {
266
281
  sql +=
@@ -366,7 +381,7 @@ export const trackerStoreOver = (context) => {
366
381
  .slice(0, limit);
367
382
  };
368
383
  return {
369
- save: async (key, kind, records, now) => save(key, kind, records, now),
384
+ save: async (key, kind, records, now, state) => save(key, kind, records, now, state),
370
385
  removeUnlisted: async (key, kind, listed, before, now, options) => removeUnlisted(key, kind, listed, before, now, options),
371
386
  get: async (key, kind, externalId) => {
372
387
  const accountId = findAccountPk(context, key);
@@ -10,6 +10,7 @@ import { CORPORA, drainCorpus } from "./note-index.js";
10
10
  import { requiredThing } from "./notes.js";
11
11
  import { queryFilter } from "./query-filter.js";
12
12
  import { pageOfRows } from "./rows-page.js";
13
+ import { refuseBotAssignee } from "./sender-bots.js";
13
14
  import { stemmerCache } from "./stems.js";
14
15
  import { BOARD_SCOPE, boardOrder, dueGroups, mergedAssignees, projectTaskColumns, TASK_PEOPLE, withoutField, } from "./task-board.js";
15
16
  import { closeSuggestionOf, SUGGESTION_COLUMNS } from "./task-close.js";
@@ -441,6 +442,7 @@ export const workTaskOperationsOver = (context) => {
441
442
  write(database, () => {
442
443
  checkRevision(rowById(task), check.revision);
443
444
  const person = personOf(to);
445
+ refuseBotAssignee(database, person);
444
446
  const held = database
445
447
  .prepare("SELECT 1 FROM task_assignments WHERE task_id = ? AND assignee_type = 'person' " +
446
448
  "AND assignee_id IN (SELECT value FROM json_each(?)) AND role = ?")
@@ -5,7 +5,7 @@ import type { MessageStore } from "../../store/store.js";
5
5
  import type { AccountKey } from "../../store/types.js";
6
6
  import type { TrackerSource } from "../source.js";
7
7
  import type { TrackerWrite } from "../writer.js";
8
- import type { TrackerWrites } from "../writes.js";
8
+ import { type TrackerWrites } from "../writes.js";
9
9
  /** The selected profile's tracker account, opened for one command and closed before its answer is printed. */
10
10
  export interface TrackerRun {
11
11
  account: AccountKey;
@@ -8,12 +8,16 @@ import { honoursDryRun } from "../../cli/dry-run-guard.js";
8
8
  import { allowDeletionsOption, FETCH, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS } from "../../cli/effects.js";
9
9
  import { itemOf, listOf, renderAnswer } from "../../cli/envelope.js";
10
10
  import { listQuery, nativeTermLists, queryTerms, termField, typedQuery, withQuery } from "../../cli/list-query.js";
11
+ import { commandAt, lineOf, nextStep, rootOf } from "../../cli/steps.js";
11
12
  import { aheadOf } from "../../domain/moment.js";
12
13
  import { STATE_TYPES, TRACKER_KINDS, TRACKER_PRIORITY_LABELS, } from "../../domain/tracker.js";
14
+ import { chosenTextModel } from "../../embeddings/models.js";
13
15
  import { count, text } from "../../entities/fields.js";
16
+ import { searchTracker } from "../../services/search-all-tracker.js";
14
17
  import { embedTracker } from "../../services/tracker-meaning.js";
15
18
  import { syncTracker } from "../sync.js";
16
19
  import { trackerIssueTask } from "../tasks.js";
20
+ import { ambiguousTrackerReference, trackerMatches, unknownTrackerReference, } from "../writes.js";
17
21
  import { addTrackerWriteCommands } from "./writes.js";
18
22
  const MOST = 500;
19
23
  // The documents' own answer has a `skipped` list of files; a part that did not run says why in a string.
@@ -34,18 +38,26 @@ const listQueryOf = (kind) => ({
34
38
  backend: "native",
35
39
  fields: [ARCHIVED],
36
40
  });
37
- /** What `issues list` narrows by: each by the tracker's id, as `issues show` and the lists name them. */
41
+ /** What `issues list` narrows by: each by its name or the tracker's id, as `issues show` and the lists name them. */
38
42
  const ISSUES_QUERY = {
39
43
  entity: "tracker_issue",
40
44
  backend: "native",
41
45
  fields: [
42
- termField("team", "kw", "team:team-1", { relation: "the team's id, as teams list shows it" }),
43
- termField("project", "kw", "project:project-1", { relation: "the project's id, as projects list shows it" }),
44
- termField("assignee", "kw", "assignee:none", { relation: "the user's id, as users list shows it, or none" }),
45
- termField("state", "kw", "state:state-1", { relation: "the state's id, as states list shows it" }),
46
+ termField("team", "kw", "team:ENG", { relation: "the team's name, key or id, as teams list shows it" }),
47
+ termField("project", "kw", 'project:"Billing revamp"', {
48
+ relation: "the project's name or id, as projects list shows it",
49
+ }),
50
+ termField("assignee", "kw", "assignee:none", {
51
+ relation: "the user's name, e-mail or id, as users list shows it, or none",
52
+ }),
53
+ termField("state", "kw", 'state:"In Progress"', {
54
+ relation: "the state's name or id, as states list shows it; with team:, that team's",
55
+ }),
46
56
  termField("type", "enum", "type:started", { values: [...STATE_TYPES], relation: "repeat for any of several" }),
47
- termField("label", "kw", "label:label-1", { relation: "the label's id, as labels list shows it" }),
48
- termField("sprint", "kw", "sprint:sprint-1", { relation: "the sprint's id, as sprints list shows it, or none" }),
57
+ termField("label", "kw", "label:Bug", { relation: "the label's name or id, as labels list shows it" }),
58
+ termField("sprint", "kw", "sprint:12", {
59
+ relation: "the sprint's name, number or id, as sprints list shows it, or none",
60
+ }),
49
61
  ARCHIVED,
50
62
  ],
51
63
  };
@@ -153,7 +165,12 @@ const trackerNext = (report, opts) => report.state === "partial" && report.progr
153
165
  ? "a kind failed to sync; running sync again retries it"
154
166
  : "the sync stopped before its end; running it again goes on from there"),
155
167
  ]
156
- : [];
168
+ : report.embeddings?.left
169
+ ? [
170
+ resumeStep({ ...opts, embed: true }, `${report.embeddings.remaining ?? "some"} chunks of issues, projects and comments have no vectors yet, so ` +
171
+ "search all may miss them by meaning; running sync --embed again embeds the next ones"),
172
+ ]
173
+ : [];
157
174
  /** Why `--embed` failed after the sync saved its report: a model not downloaded. */
158
175
  const embeddingIssue = (error) => {
159
176
  const { code, reason } = errorOf(error);
@@ -412,24 +429,47 @@ const addTrackerCommandsDefinition = (program, options) => {
412
429
  outputFor(command).streams.diagnostic(line);
413
430
  });
414
431
  const issues = annotate(program.command("issues"), { effects: NO_EFFECTS }).description("the tracker's issues as last synced: state, team, project, assignee and labels");
415
- example(paging(withQuery(answerEntity(annotate(issues.command("list"), { effects: LOCAL_READ }), "tracker_issue", trackerView), ISSUES_QUERY).description("issues copied from the tracker, newest change first; run sync to bring them up to date")), "issues list type:started", "issues list assignee:none --json").action(async (words, opts, command) => {
432
+ example(paging(withQuery(answerEntity(annotate(issues.command("list"), { effects: LOCAL_READ }), "tracker_issue", trackerView), ISSUES_QUERY).description("issues copied from the tracker, newest change first; run sync to bring them up to date")), "issues list type:started", "issues list label:Bug assignee:none --json").action(async (words, opts, command) => {
416
433
  const lists = nativeTermLists(listQuery(typedQuery(words), ISSUES_QUERY, "issues list"), "issues list", ["type"]);
417
434
  if ([...lists.values()].flat().some((one) => one.operator !== "term" && one.operator !== "phrase"))
418
435
  throw new InvalidArgumentError("issues list takes field:value terms, each one whole value");
419
436
  const types = (lists.get("type") ?? []).map((one) => one.value.toLowerCase());
420
437
  const terms = new Map([...lists].filter(([field]) => field !== "type").map(([field, [one]]) => [field, one?.value]));
421
- const noneOr = (field) => (terms.get(field)?.toLowerCase() === "none" ? "none" : terms.get(field));
422
- const assignee = noneOr("assignee");
423
- const sprint = noneOr("sprint");
424
438
  await within(command, true, async (run) => {
439
+ const TEAMED = new Set(["state", "label", "sprint"]);
440
+ // A name every team's state or sprint has matches each of them; only the team itself must be one row.
441
+ const rowsOf = async (field, kind, team) => {
442
+ const given = terms.get(field);
443
+ if (given === undefined)
444
+ return undefined;
445
+ const scoped = team !== undefined && TEAMED.has(kind) ? " for that team" : "";
446
+ const found = await trackerMatches(run, kind, given, team);
447
+ if (found.length)
448
+ return found;
449
+ throw await unknownTrackerReference(run, kind, given, `${field}:`, {
450
+ ...(team === undefined ? {} : { team }),
451
+ scoped,
452
+ });
453
+ };
454
+ const idsOf = async (field, kind, team) => (await rowsOf(field, kind, team))?.map(({ record }) => record.externalId);
455
+ const teams = await rowsOf("team", "team");
456
+ if (teams && teams.length > 1)
457
+ throw ambiguousTrackerReference("team", terms.get("team"), teams.map(({ record }) => record), "team:");
458
+ const team = teams?.[0]?.record.externalId;
459
+ const noneOr = async (field, kind) => terms.get(field)?.toLowerCase() === "none" ? null : await idsOf(field, kind, team);
460
+ const project = await idsOf("project", "project");
461
+ const assignee = await noneOr("assignee", "user");
462
+ const state = await idsOf("state", "state", team);
463
+ const label = await idsOf("label", "label", team);
464
+ const sprint = await noneOr("sprint", "sprint");
425
465
  const filter = {
426
- ...(terms.has("team") ? { parent: terms.get("team") } : {}),
427
- ...(terms.has("project") ? { project: terms.get("project") } : {}),
428
- ...(assignee !== undefined ? { assignee: assignee === "none" ? null : assignee } : {}),
429
- ...(terms.has("state") ? { state: terms.get("state") } : {}),
466
+ ...(team !== undefined ? { parent: team } : {}),
467
+ ...(project ? { project } : {}),
468
+ ...(assignee !== undefined ? { assignee } : {}),
469
+ ...(state ? { state } : {}),
430
470
  ...(types.length ? { stateTypes: types } : {}),
431
- ...(terms.has("label") ? { label: terms.get("label") } : {}),
432
- ...(sprint !== undefined ? { sprint: sprint === "none" ? null : sprint } : {}),
471
+ ...(label ? { label } : {}),
472
+ ...(sprint !== undefined ? { sprint } : {}),
433
473
  ...(terms.has("archived") ? { archived: true } : {}),
434
474
  limit: opts.limit,
435
475
  offset: (opts.page - 1) * opts.limit,
@@ -458,22 +498,41 @@ const addTrackerCommandsDefinition = (program, options) => {
458
498
  });
459
499
  });
460
500
  example(paging(answerEntity(annotate(issues.command("search"), { effects: LOCAL_READ }), "tracker_hit", trackerView)
461
- .description("find issues, projects and comments in the copy by their words")
462
- .argument("<words...>", "every word must match, in any form; a word of four letters or more finds the words it begins")), 'issues search "invoice currency"').action(async (words, opts, command) => {
501
+ .description("find issues, projects and comments in the copy by their words, and by meaning once sync --embed built " +
502
+ "their vectors")
503
+ .argument("<words...>", 'every word must match, in any form and any order; a word of four letters or more finds the words it begins; "a phrase" in quote marks inside the query keeps its words together; a question finds what holds some of its words')), "issues search invoice currency", 'issues search "why do refunds round wrong?"').action(async (words, opts, command) => {
504
+ const { env } = environmentOf(command);
505
+ const download = commandAt(rootOf(command), "models download") !== undefined;
463
506
  await within(command, true, async (run) => {
464
- const found = await run.store.tracker.find({
465
- words,
507
+ const found = await searchTracker(run.store, {
508
+ text: words.join(" "),
466
509
  accounts: [run.account],
467
- kinds: ["issue", "project", "comment"],
468
510
  limit: opts.limit,
469
511
  offset: (opts.page - 1) * opts.limit,
512
+ now: now(),
513
+ ...(download ? { command: options.app.command } : {}),
514
+ ...(env ? { env } : {}),
470
515
  });
516
+ const noVectors = found.meaningReason === "tracker.no-vectors";
517
+ const why = found.meaningSkipped === undefined
518
+ ? undefined
519
+ : `found by words only: ${found.meaningSkipped}` +
520
+ (noVectors ? `; \`${lineOf(command, "sync --embed")}\` builds the vectors that find them by meaning` : "");
521
+ if (why)
522
+ outputFor(command).renderer.note(why);
523
+ const next = noVectors
524
+ ? [resumeStep({ embed: true }, "builds the vectors that find issues, projects and comments by meaning")]
525
+ : download && found.meaningReason === "model.not-downloaded"
526
+ ? [nextStep("models.download", { args: { model: chosenTextModel(env).id } })]
527
+ : [];
471
528
  return listOf("issues search", {
472
- items: found.items.map((hit) => viewOf(hit.item, { excerpt: hit.excerpt })),
529
+ items: found.items.map(({ hit, item }) => viewOf(item, { excerpt: hit.text, found_by: hit.foundBy })),
473
530
  limit: opts.limit,
474
531
  page: opts.page,
475
532
  has_more: found.hasMore,
476
533
  args: { words },
534
+ ...(why ? { missing: [{ field: "found_by", why }] } : {}),
535
+ ...(next.length ? { next } : {}),
477
536
  });
478
537
  });
479
538
  });