@wirecat/cli-core 0.633.0 → 0.635.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 (71) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/domain/display-names.d.ts +4 -2
  4. package/dist/domain/display-names.js +5 -2
  5. package/dist/domain/relation-role-labels.d.ts +10 -0
  6. package/dist/domain/relation-role-labels.js +40 -0
  7. package/dist/domain/relations.d.ts +7 -0
  8. package/dist/domain/relations.js +10 -0
  9. package/dist/errors/reasons.js +5 -0
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +2 -1
  12. package/dist/search/groups.d.ts +2 -0
  13. package/dist/search/groups.js +1 -0
  14. package/dist/services/account-groups.d.ts +30 -1
  15. package/dist/services/account-groups.js +27 -0
  16. package/dist/services/index.d.ts +2 -1
  17. package/dist/services/index.js +2 -1
  18. package/dist/services/project-activity.d.ts +45 -0
  19. package/dist/services/project-activity.js +76 -0
  20. package/dist/services/project-status/index.d.ts +11 -1
  21. package/dist/services/project-status/index.js +3 -3
  22. package/dist/store/accounts.d.ts +10 -1
  23. package/dist/store/accounts.js +3 -2
  24. package/dist/store/chats.d.ts +5 -0
  25. package/dist/store/chats.js +6 -0
  26. package/dist/store/exports.d.ts +2 -1
  27. package/dist/store/identity-links.d.ts +21 -0
  28. package/dist/store/identity-splits.d.ts +2 -0
  29. package/dist/store/index.d.ts +3 -3
  30. package/dist/store/keys.d.ts +1 -1
  31. package/dist/store/keys.js +1 -1
  32. package/dist/store/messages.d.ts +13 -0
  33. package/dist/store/messages.js +7 -0
  34. package/dist/store/people.d.ts +10 -4
  35. package/dist/store/sqlite/accounts.d.ts +12 -2
  36. package/dist/store/sqlite/accounts.js +42 -3
  37. package/dist/store/sqlite/address-organization.d.ts +18 -0
  38. package/dist/store/sqlite/address-organization.js +48 -0
  39. package/dist/store/sqlite/chat-activity-counts.d.ts +19 -0
  40. package/dist/store/sqlite/chat-activity-counts.js +26 -0
  41. package/dist/store/sqlite/chats.d.ts +3 -1
  42. package/dist/store/sqlite/chats.js +8 -0
  43. package/dist/store/sqlite/identity-link-rows.d.ts +5 -1
  44. package/dist/store/sqlite/identity-link-rows.js +9 -3
  45. package/dist/store/sqlite/identity-proposals.d.ts +5 -3
  46. package/dist/store/sqlite/identity-proposals.js +66 -7
  47. package/dist/store/sqlite/identity-split-proposals.js +3 -1
  48. package/dist/store/sqlite/mail-findings.js +10 -44
  49. package/dist/store/sqlite/manifest.js +1 -0
  50. package/dist/store/sqlite/migrations.generated.js +6 -0
  51. package/dist/store/sqlite/name-traces.d.ts +5 -2
  52. package/dist/store/sqlite/name-traces.js +8 -5
  53. package/dist/store/sqlite/open-store.js +2 -0
  54. package/dist/store/sqlite/people-list.js +7 -3
  55. package/dist/store/sqlite/person-doubts.d.ts +13 -0
  56. package/dist/store/sqlite/person-doubts.js +12 -8
  57. package/dist/store/sqlite/person-links.d.ts +7 -2
  58. package/dist/store/sqlite/person-links.js +26 -1
  59. package/dist/store/sqlite/person-match-scan.js +74 -4
  60. package/dist/store/sqlite/person-merges.js +3 -7
  61. package/dist/store/sqlite/relation-list.d.ts +3 -1
  62. package/dist/store/sqlite/relation-list.js +16 -9
  63. package/dist/store/sqlite/relation-roles.d.ts +4 -0
  64. package/dist/store/sqlite/relation-roles.js +19 -5
  65. package/dist/store/sqlite/reply-times.d.ts +2 -0
  66. package/dist/store/sqlite/reply-times.js +2 -1
  67. package/dist/store/sqlite/task-titles.d.ts +12 -1
  68. package/dist/store/sqlite/task-titles.js +42 -1
  69. package/dist/store/sqlite/tasks.js +6 -1
  70. package/dist/store/types.d.ts +4 -0
  71. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,92 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.635.0 — 10.11.2026
9
+
10
+ ### Added
11
+
12
+ - **The owner sets an account's scope, personal or work, and pins or clears a chat's.** `setAccountScope` and
13
+ `setChatScope` (from `/services`) take an account as `--source` names it (`bitrix24:acme.bitrix24.ru`, `tg:work`),
14
+ refuse a run locked to a group, and are for an owner-only command (`grantsAuthority`). An account's change moves
15
+ what search copied of its old scope: its conversation pieces and involvements, its other search pieces, and the word
16
+ indexes of its documents, mail and calendar events, which are built again on the next search. A chat with its own
17
+ scope keeps it; memories and facts keep the scope they were written with. A chat's change is recorded in its
18
+ history as the owner's. The store methods are `accounts.setScope` and `chats.setChatScope`.
19
+ - **A CLI chooses the scope its new accounts start as.** `accounts.saveAccount(key, { name, scope: "work" })` makes a
20
+ new account work; an account already stored keeps its scope, so a sync never undoes the owner's choice. A `scope`
21
+ in the `AccountKey` itself still overwrites the stored one on every save.
22
+ - **Each member of an account group carries its account's `scope`**, so a groups view shows and switches it in place.
23
+ - **The owner can answer a shared-mailbox proposal with "this is the company's mailbox".** `people.decideLink` with
24
+ `company` (`{}`, `{ organization }` or `{ name }`) gives the address to an organization: the one named, else the one
25
+ that holds the address or its company domain, else one of that name, else a new company named after the domain. The
26
+ proposal is turned down, so the two people are not joined and are not proposed again on that address. Only the
27
+ owner decides it; a proposal that is not about a shared mailbox is refused with `identity.not-shared`
28
+ ([ARCHITECTURE.md](docs/dev/ARCHITECTURE.md)).
29
+
30
+ - **`IdentityLinkRow.mailbox` names the shared address**, beside `shared`, so a review can show which mailbox it is.
31
+
32
+ - **`people.linkProposals({ order: "score" })` lists the highest score first**, proposals with no score last, each
33
+ newest first. Without `order` the list stays newest first.
34
+ - **A shared mailbox proposes the people who have it again, scored, and still never joins them.** A role address such
35
+ as `info@` or `office@`, and a company's address (one an organization holds, or two people of one source list have),
36
+ now opens a proposal for each pair of its people instead of being skipped; a no-reply address still proposes no one,
37
+ and the owner is still never proposed. The proposal's `score` says what else the two share: 0.1 for the mailbox
38
+ alone, more for one name, a phone or another address only they hold, a chat or a company's domain
39
+ ([ARCHITECTURE.md](docs/dev/ARCHITECTURE.md)). The first people scan after the upgrade reads every address once,
40
+ so mailboxes nobody touched since are proposed too. Proposals already stored stay as they are.
41
+
42
+ - **`IdentityLinkRow.shared`: `role`, `line` or `null`.** Says that the address behind an `identity_link` proposal is
43
+ a shared mailbox, so a review can show it as one; `null` on proposals made before this release.
44
+
45
+ ### Changed — may break callers
46
+
47
+ - **A person with no readable name of their own is shown by an account's name before its username.** `people.list`
48
+ gave such a person `displayName` `@Xorlov` although their Telegram account is named «Ярослав Орлов» (a person left
49
+ with no name after a split, for one). The first readable account name now comes first, then the username, phone and
50
+ email as before; `displayName(name, { name })` takes it. The shown name also drives the sort by name and the
51
+ automated and company checks, so such a person may move in the list or between kinds.
52
+ - **Taking identities off a person can name that person, and is refused when they sit on someone else.**
53
+ `people.unlinkIdentity(ref, { from })` and `people.proposeSplit({ identities, from })` take the uid of the person the
54
+ identities leave; `people.split(uid, …)` checks its `uid` the same way. An identity on another person is refused with
55
+ `validation_error`, reason `identity.held-elsewhere`, `param: "from"` and `reference: "person:<uid>"` of whoever holds
56
+ it, and the message names them, so nothing moves. Before, a script that meant to take a colleague's mailbox off the
57
+ owner's card took it off the colleague. `split`'s refusal for an identity of another person is now this one (it said
58
+ "is not an identity of person:<n>").
59
+ - **A doubt's unlink names the person it takes the identities from.** `people.doubts()` gives each `unlink` move a
60
+ `from` (`person:<uid>`), and its `fix` command ends in `--from person:<uid>`, which memo's `people unlink` needs.
61
+
62
+ ### Fixed
63
+
64
+ - **A task found in a message keeps the message's first line as its title after the message is deleted.** The line is
65
+ now stored as the title when the task is found, as store version 65 did for the tasks found before. A task found
66
+ before its message is saved still shows the line once the message arrives, and a title the finder or a person sets
67
+ replaces it as before.
68
+ - **Tasks found in messages before 0.630 keep their message's first line as their title (store version 65).** Since
69
+ 0.630 such a task showed the first line only while its message was in the store, and its title went back to
70
+ `question — msg:…` once the message was deleted. Store version 65 stores that line as the title of every live
71
+ found task still titled `<kind> — <source>`, once, on the next writable open, in batches. A title a person wrote, a
72
+ project task, and a task whose message is missing, deleted or empty keep their title.
73
+
74
+ ## 0.634.0 — 10.11.2026
75
+
76
+ ### Added
77
+
78
+ - **A role list for ties between people and organizations, and role labels in three languages.** `related-to` between
79
+ a person or an organization and another is offered the new `related` list: `colleague`, `adviser`, `investor`,
80
+ `mentor`, `family`, `friend`, plus the owner's own (`knowledge.addRole("related", …)`). It is offered, not enforced:
81
+ any other word is still stored and reads as `custom`. Buying and partnering stay the kinds `customer-of` and
82
+ `partner-of`. Each built-in role of every list carries `labels` (`en`, `ru`, `es`, exported as `ROLE_LABELS`), and
83
+ each row of `listRelations` says in `roleList` which list its role is offered from, so an app shows a picker with
84
+ "add a new role" instead of a text field.
85
+ - **`projectActivity` says how busy every project's linked chats were, in one call.** For each of the owner's
86
+ projects: how many chats are linked to it or its child projects (every confirmed link, any purpose, no chat
87
+ limit; `partial` when some child projects were too deep or too many to read), how many of them are muted now, the messages and the owner's own in a window by when they
88
+ were sent, the newest message, and the busiest chats; muted chats are left out of the counts. A page at a time,
89
+ busiest first, optionally only some accounts. The store read under it, `MessagesStore.chatActivityCounts`, reads
90
+ each chat's window once.
91
+ - **`PersonDoubt.moves`**: the fix of each doubt as data (`{ op: "unmerge", merge }` or
92
+ `{ op: "unlink", identities }`), one per `fix` command, so an app runs it without parsing a command line.
93
+
8
94
  ## 0.633.0 — 10.11.2026
9
95
 
10
96
  ### Added
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
- action?: undefined;
28
27
  name: string;
29
28
  installed: boolean;
30
29
  active: boolean;
31
30
  servicePath: string;
32
31
  timerPath: string;
32
+ action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -1,13 +1,15 @@
1
1
  /** What a person can be shown as when their name has nothing to read. */
2
2
  export interface NameFallbacks {
3
+ /** A name one of the person's accounts carries: a real name beats a handle. */
4
+ name?: string | null;
3
5
  username?: string | null;
4
6
  phone?: string | null;
5
7
  email?: string | null;
6
8
  }
7
9
  /**
8
10
  * A name as it is shown: no wrapping quotes, no repeated or edge spaces. One with no letter or digit (`!`, `!$`), or a
9
- * placeholder such as `null` or «Без имени», gives way to the username, then the phone, then the email; the stored name
10
- * stays as it came.
11
+ * placeholder such as `null` or «Без имени», gives way to an account's name, then the username, the phone, the email;
12
+ * the stored name stays as it came.
11
13
  */
12
14
  export declare const displayName: (name: string | null | undefined, fallbacks?: NameFallbacks) => string | null;
13
15
  /**
@@ -26,14 +26,17 @@ const given = (value) => {
26
26
  };
27
27
  /**
28
28
  * A name as it is shown: no wrapping quotes, no repeated or edge spaces. One with no letter or digit (`!`, `!$`), or a
29
- * placeholder such as `null` or «Без имени», gives way to the username, then the phone, then the email; the stored name
30
- * stays as it came.
29
+ * placeholder such as `null` or «Без имени», gives way to an account's name, then the username, the phone, the email;
30
+ * the stored name stays as it came.
31
31
  */
32
32
  export const displayName = (name, fallbacks = {}) => {
33
33
  const unwrapped = typeof name === "string" ? unquoted(name) : "";
34
34
  const cleaned = PLACEHOLDERS.has(unwrapped.toLowerCase()) ? "" : unwrapped;
35
35
  if (READABLE.test(cleaned))
36
36
  return cleaned;
37
+ const borrowed = fallbacks.name === undefined || fallbacks.name === null ? null : displayName(fallbacks.name);
38
+ if (borrowed !== null && READABLE.test(borrowed) && !borrowed.startsWith("@"))
39
+ return borrowed;
37
40
  const username = given(fallbacks.username);
38
41
  return ((username === undefined ? undefined : username.startsWith("@") ? username : `@${username}`) ??
39
42
  given(fallbacks.phone) ??
@@ -0,0 +1,10 @@
1
+ import type { ROLE_LISTS, RoleList } from "./relations.js";
2
+ export interface RoleLabels {
3
+ en: string;
4
+ ru: string;
5
+ es: string;
6
+ }
7
+ /** Keyed by list: a deal's `owner` is the one responsible for it, an organization's is the one who owns it. */
8
+ export declare const ROLE_LABELS: {
9
+ [L in RoleList]: Record<(typeof ROLE_LISTS)[L][number], RoleLabels>;
10
+ };
@@ -0,0 +1,40 @@
1
+ const label = (en, ru, es) => ({ en, ru, es });
2
+ /** Keyed by list: a deal's `owner` is the one responsible for it, an organization's is the one who owns it. */
3
+ export const ROLE_LABELS = {
4
+ organization: {
5
+ employee: label("Employee", "Сотрудник", "Empleado"),
6
+ contractor: label("Contractor", "Подрядчик", "Contratista"),
7
+ founder: label("Founder", "Основатель", "Fundador"),
8
+ owner: label("Owner", "Владелец", "Propietario"),
9
+ manager: label("Manager", "Руководитель", "Directivo"),
10
+ adviser: label("Adviser", "Советник", "Asesor"),
11
+ contact: label("Contact", "Контакт", "Contacto"),
12
+ },
13
+ project: {
14
+ owner: label("Owner", "Владелец", "Propietario"),
15
+ manager: label("Manager", "Руководитель", "Directivo"),
16
+ contributor: label("Contributor", "Участник", "Colaborador"),
17
+ "client-contact": label("Client contact", "Контакт клиента", "Contacto del cliente"),
18
+ approver: label("Approver", "Согласующий", "Aprobador"),
19
+ },
20
+ deal: {
21
+ owner: label("Responsible", "Ответственный", "Responsable"),
22
+ contact: label("Contact", "Контакт", "Contacto"),
23
+ "decision-maker": label("Decision-maker", "Принимает решение", "Responsable de decidir"),
24
+ influencer: label("Influencer", "Влияет на решение", "Influye en la decisión"),
25
+ },
26
+ contract: {
27
+ customer: label("Customer", "Заказчик", "Cliente"),
28
+ supplier: label("Supplier", "Поставщик", "Proveedor"),
29
+ signatory: label("Signatory", "Подписант", "Firmante"),
30
+ guarantor: label("Guarantor", "Поручитель", "Garante"),
31
+ },
32
+ related: {
33
+ colleague: label("Colleague", "Коллега", "Colega"),
34
+ adviser: label("Adviser", "Советник", "Asesor"),
35
+ investor: label("Investor", "Инвестор", "Inversor"),
36
+ mentor: label("Mentor", "Наставник", "Mentor"),
37
+ family: label("Family", "Семья", "Familia"),
38
+ friend: label("Friend", "Друг", "Amigo"),
39
+ },
40
+ };
@@ -3,6 +3,12 @@ export declare const ORGANIZATION_ROLES: readonly ["employee", "contractor", "fo
3
3
  export declare const PROJECT_ROLES: readonly ["owner", "manager", "contributor", "client-contact", "approver"];
4
4
  /** A contract party's part; a party the list cannot name has none, never a catch-all `other`. */
5
5
  export declare const CONTRACT_ROLES: readonly ["customer", "supplier", "signatory", "guarantor"];
6
+ /**
7
+ * What a person or an organization is to another on `related-to`, offered so the same tie reads the same way. Unlike
8
+ * the other lists it is not enforced: roles written before it, and words a source reports, stay. Buying and partnering
9
+ * are the kinds `customer-of` and `partner-of`, so they are not roles here.
10
+ */
11
+ export declare const RELATED_ROLES: readonly ["colleague", "adviser", "investor", "mentor", "family", "friend"];
6
12
  /** How much the owner deals with a person on a project himself, not how active the person is; absent is unknown. */
7
13
  export declare const ENGAGEMENT_LEVELS: readonly ["none", "low", "medium", "high"];
8
14
  export type Engagement = (typeof ENGAGEMENT_LEVELS)[number];
@@ -85,6 +91,7 @@ export declare const ROLE_LISTS: {
85
91
  readonly project: readonly ["owner", "manager", "contributor", "client-contact", "approver"];
86
92
  readonly deal: readonly ["owner", "contact", "decision-maker", "influencer"];
87
93
  readonly contract: readonly ["customer", "supplier", "signatory", "guarantor"];
94
+ readonly related: readonly ["colleague", "adviser", "investor", "mentor", "family", "friend"];
88
95
  };
89
96
  export type RoleList = keyof typeof ROLE_LISTS;
90
97
  /** Which list a relationship's role comes from, or `undefined` where a role is free text. */
@@ -13,6 +13,12 @@ export const ORGANIZATION_ROLES = [
13
13
  export const PROJECT_ROLES = ["owner", "manager", "contributor", "client-contact", "approver"];
14
14
  /** A contract party's part; a party the list cannot name has none, never a catch-all `other`. */
15
15
  export const CONTRACT_ROLES = ["customer", "supplier", "signatory", "guarantor"];
16
+ /**
17
+ * What a person or an organization is to another on `related-to`, offered so the same tie reads the same way. Unlike
18
+ * the other lists it is not enforced: roles written before it, and words a source reports, stay. Buying and partnering
19
+ * are the kinds `customer-of` and `partner-of`, so they are not roles here.
20
+ */
21
+ export const RELATED_ROLES = ["colleague", "adviser", "investor", "mentor", "family", "friend"];
16
22
  /** How much the owner deals with a person on a project himself, not how active the person is; absent is unknown. */
17
23
  export const ENGAGEMENT_LEVELS = ["none", "low", "medium", "high"];
18
24
  export const isEngagement = (value) => typeof value === "string" && ENGAGEMENT_LEVELS.includes(value);
@@ -74,6 +80,7 @@ export const checkEnds = (kind, from, to) => {
74
80
  throw new CliError("validation_error", `${kind} joins ${spec.from.join(", ")} to ${spec.to.join(", ")}, not ${from} to ${to}`);
75
81
  return spec;
76
82
  };
83
+ const isParty = (type) => type === "person" || type === "organization";
77
84
  /**
78
85
  * The roles a relationship takes, or `undefined` for free text. A member's list is the organization's or the
79
86
  * project's only when the member is a person: a chat's or a sub-project's role was never one of them.
@@ -90,9 +97,12 @@ export const ROLE_LISTS = {
90
97
  project: PROJECT_ROLES,
91
98
  deal: DEAL_ROLES,
92
99
  contract: CONTRACT_ROLES,
100
+ related: RELATED_ROLES,
93
101
  };
94
102
  /** Which list a relationship's role comes from, or `undefined` where a role is free text. */
95
103
  export const roleListOf = (kind, from, to) => {
104
+ if (kind === "related-to" && isParty(from) && isParty(to))
105
+ return "related";
96
106
  const roles = rolesOf(kind, from, to);
97
107
  return Object.keys(ROLE_LISTS).find((list) => ROLE_LISTS[list] === roles);
98
108
  };
@@ -392,6 +392,7 @@ const OTHERS = [
392
392
  "the people a merge or a proposed link names changed since; undo the later merge, or propose the link again",
393
393
  ],
394
394
  ["identity.no-merge", "not_found", "nothing of that person is merged into the other; people show lists the merges"],
395
+ validation("identity.held-elsewhere", "the identity sits on another person than the one named; name that person to take it off them"),
395
396
  validation("identity.several-persons", "the identities that leave a person are all of that one person"),
396
397
  validation("identity.nothing-left", "a split leaves at least one identity with the person"),
397
398
  [
@@ -405,6 +406,10 @@ const OTHERS = [
405
406
  "the owner rejected linking these people on this evidence; only a new signal or identity proposes them again",
406
407
  ],
407
408
  validation("identity.same", "the two identities are one person already"),
409
+ validation("identity.not-shared", "only a match on a shared mailbox can say the mailbox is a company's"),
410
+ ["organization.not-found", "not_found", "no stored organization has that id"],
411
+ validation("organization.unnamed", "a free mailbox names no company; name the organization or the company"),
412
+ validation("organization.ambiguous", "more than one organization matches; name the one meant as a reference"),
408
413
  validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
409
414
  validation("identity.common-name", "more than six people have the name, so it proposes no one"),
410
415
  validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
package/dist/index.d.ts CHANGED
@@ -24,7 +24,8 @@ export { rankingOptions } from "./domain/rankings-options.js";
24
24
  export { type EnvelopeOptions, type EnvelopeRecord, type EnvelopeSource, envelopeOfJsonl, envelopeOfText, type IngestError, RECORD_ENTITY_TYPES, RECORD_OPERATIONS, RECORDS_ENVELOPE_SCHEMA, RECORDS_SCHEMA_VERSION, type RecordEntityType, type RecordOperation, type RecordRelation, type RecordsEnvelope, } from "./domain/records.js";
25
25
  export { type ColumnShape, envelopeOfCsv, recordColumns, recordTemplate, TABLE_RECORD_TYPES, type TableColumn, type TableEnvelope, TableError, type TablePlace, } from "./domain/records-table.js";
26
26
  export { canonicalReference, formatReference, looksLikeReference, parseReference, REF_KINDS, type Reference, type RefKindName, type RefKindSpec, } from "./domain/references.js";
27
- export { byEngagement, CONTRACT_ROLES, ENGAGEMENT_LEVELS, type Engagement, engagementRank, inverseOf, isUsable, ORGANIZATION_ROLES, PROJECT_ROLES, RELATION_KINDS, RELATIONS, type RelationKind, ROLE_LISTS, type RoleList, rolesOf, STANDINGS, type Standing, standingOf, usableLink, } from "./domain/relations.js";
27
+ export { ROLE_LABELS, type RoleLabels } from "./domain/relation-role-labels.js";
28
+ export { byEngagement, CONTRACT_ROLES, ENGAGEMENT_LEVELS, type Engagement, engagementRank, inverseOf, isUsable, ORGANIZATION_ROLES, PROJECT_ROLES, RELATED_ROLES, RELATION_KINDS, RELATIONS, type RelationKind, ROLE_LISTS, type RoleList, rolesOf, STANDINGS, type Standing, standingOf, usableLink, } from "./domain/relations.js";
28
29
  export { normalizeTag, TAG_TYPES, type TagType } from "./domain/tags.js";
29
30
  export { envelopeOfVcard, isVcard, type VcardIssue, type VcardOptions } from "./domain/vcard.js";
30
31
  export { type AppErrors, DETAILS as CORE_DETAILS, failureContext, REASONS as CORE_REASONS } from "./errors/reasons.js";
package/dist/index.js CHANGED
@@ -19,7 +19,8 @@ export { rankingOptions } from "./domain/rankings-options.js";
19
19
  export { envelopeOfJsonl, envelopeOfText, RECORD_ENTITY_TYPES, RECORD_OPERATIONS, RECORDS_ENVELOPE_SCHEMA, RECORDS_SCHEMA_VERSION, } from "./domain/records.js";
20
20
  export { envelopeOfCsv, recordColumns, recordTemplate, TABLE_RECORD_TYPES, TableError, } from "./domain/records-table.js";
21
21
  export { canonicalReference, formatReference, looksLikeReference, parseReference, REF_KINDS, } from "./domain/references.js";
22
- export { byEngagement, CONTRACT_ROLES, ENGAGEMENT_LEVELS, engagementRank, inverseOf, isUsable, ORGANIZATION_ROLES, PROJECT_ROLES, RELATION_KINDS, RELATIONS, ROLE_LISTS, rolesOf, STANDINGS, standingOf, usableLink, } from "./domain/relations.js";
22
+ export { ROLE_LABELS } from "./domain/relation-role-labels.js";
23
+ export { byEngagement, CONTRACT_ROLES, ENGAGEMENT_LEVELS, engagementRank, inverseOf, isUsable, ORGANIZATION_ROLES, PROJECT_ROLES, RELATED_ROLES, RELATION_KINDS, RELATIONS, ROLE_LISTS, rolesOf, STANDINGS, standingOf, usableLink, } from "./domain/relations.js";
23
24
  export { normalizeTag, TAG_TYPES } from "./domain/tags.js";
24
25
  export { envelopeOfVcard, isVcard } from "./domain/vcard.js";
25
26
  export { DETAILS as CORE_DETAILS, failureContext, REASONS as CORE_REASONS } from "./errors/reasons.js";
@@ -9,6 +9,8 @@ export declare const NOT_GROUP_NAMES: ReadonlySet<string>;
9
9
  /** `setting`: a saved group lists it; `all`: the default group, which holds every account. */
10
10
  export type GroupReason = "setting" | "all";
11
11
  export interface GroupMember extends AccountKey {
12
+ /** The account's scope as the store holds it, so a group view shows and switches it in place. */
13
+ scope?: "personal" | "work";
12
14
  /** Every saved entry that names it; its `provider:account` in `all`. */
13
15
  entries: string[];
14
16
  reason: GroupReason;
@@ -66,6 +66,7 @@ export const groupMembership = (context) => {
66
66
  holding.set(keyOf(one), [...(holding.get(keyOf(one)) ?? []), name]);
67
67
  for (const [name, members] of [...Object.entries(groups), [ALL, every]])
68
68
  for (const one of members) {
69
+ one.scope = context.held.find(sameAs(one))?.scope ?? "personal";
69
70
  one.profiles = recorded.filter(({ key }) => sameAs(key)(one)).map(({ app, profile }) => `${app} ${profile}`);
70
71
  one.also_in = (holding.get(keyOf(one)) ?? []).filter((other) => other !== name);
71
72
  }
@@ -1,6 +1,7 @@
1
+ import type { Id } from "../domain/models.js";
1
2
  import type { AppIdentity } from "../ports/app.js";
2
3
  import { type GroupMembership } from "../search/groups.js";
3
- import type { AccountKey, MessageStore } from "../store/store.js";
4
+ import type { AccountKey, MessageStore, StoredAccount } from "../store/store.js";
4
5
  /** The store, the account running and its app: what every group edit resolves members against. */
5
6
  export interface GroupStore {
6
7
  store: MessageStore;
@@ -20,9 +21,37 @@ export interface GroupMemberMove extends Omit<GroupMemberChange, "group"> {
20
21
  from: string;
21
22
  to: string;
22
23
  }
24
+ type Scope = StoredAccount["scope"];
25
+ export interface AccountScopeChange {
26
+ /** One account, as `--source` names it: `bitrix24:acme.bitrix24.ru`, `tg:work`. */
27
+ member: string;
28
+ scope: Scope;
29
+ }
30
+ export interface ChatScopeChange {
31
+ member: string;
32
+ /** The chat's id in that account. */
33
+ chat: Id;
34
+ /** `null` takes the chat's own scope off, so it follows its account again. */
35
+ scope: Scope | null;
36
+ }
37
+ export interface ChatScope extends AccountKey {
38
+ chat: Id;
39
+ /** The chat's own scope; `null` when it follows its account. */
40
+ own: Scope | null;
41
+ /** What every reader applies: its own, or else its account's. */
42
+ scope: Scope;
43
+ }
23
44
  /** Every group with its members, why each is in, its profiles and other groups, the duplicates and the suggestions. */
24
45
  export declare const listAccountGroups: (at: GroupStore) => Promise<GroupMembership>;
25
46
  export declare const addGroupMember: (at: GroupStore, change: GroupMemberChange) => Promise<GroupMembership>;
26
47
  export declare const removeGroupMember: (at: GroupStore, change: GroupMemberChange) => Promise<GroupMembership>;
27
48
  /** Out of one group and into another in one write: what a drag between groups does. */
28
49
  export declare const moveGroupMember: (at: GroupStore, move: GroupMemberMove) => Promise<GroupMembership>;
50
+ /**
51
+ * The owner's choice of which side of his life an account is on, as the store now holds it. Moving an account to work
52
+ * lets work views and meeting preparation read it, so a command over this is the owner's alone (`grantsAuthority`).
53
+ */
54
+ export declare const setAccountScope: (at: GroupStore, change: AccountScopeChange) => Promise<StoredAccount>;
55
+ /** The owner pins one chat to a scope, or with `null` lets it follow its account; the owner's alone, as above. */
56
+ export declare const setChatScope: (at: GroupStore, change: ChatScopeChange) => Promise<ChatScope>;
57
+ export {};
@@ -2,6 +2,12 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { accountsOfList, groupName, sameAs, sourceOf } from "../search/account-list.js";
3
3
  import { ALL, hasGroup, NOT_GROUP_NAMES } from "../search/groups.js";
4
4
  import { groupLockOf, listContextOf } from "./search-kind.js";
5
+ const SCOPES = ["personal", "work"];
6
+ const scopeOf = (scope) => {
7
+ if (!SCOPES.includes(scope))
8
+ throw new CliError("validation_error", `${scope} is not a scope — personal or work`, { reason: "input.invalid" });
9
+ return scope;
10
+ };
5
11
  const fail = (code, message) => {
6
12
  throw new CliError(code, message);
7
13
  };
@@ -87,3 +93,24 @@ export const moveGroupMember = async (at, move) => {
87
93
  });
88
94
  return listAccountGroups(at);
89
95
  };
96
+ /**
97
+ * The owner's choice of which side of his life an account is on, as the store now holds it. Moving an account to work
98
+ * lets work views and meeting preparation read it, so a command over this is the owner's alone (`grantsAuthority`).
99
+ */
100
+ export const setAccountScope = async (at, change) => {
101
+ unlocked(at);
102
+ const scope = scopeOf(change.scope);
103
+ const { provider, account } = accountOf(await contextOf(at), change.member);
104
+ return at.store.accounts.setScope({ provider, account }, scope);
105
+ };
106
+ /** The owner pins one chat to a scope, or with `null` lets it follow its account; the owner's alone, as above. */
107
+ export const setChatScope = async (at, change) => {
108
+ unlocked(at);
109
+ const scope = change.scope === null ? null : scopeOf(change.scope);
110
+ const { provider, account } = accountOf(await contextOf(at), change.member);
111
+ const key = { provider, account };
112
+ if (!(await at.store.chats.setChatScope(key, change.chat, scope)))
113
+ fail("not_found", `no chat ${change.chat} stored in ${sourceOf(key)}`);
114
+ const effective = (await at.store.chats.chatScopes(key, [change.chat])).get(change.chat) ?? "personal";
115
+ return { ...key, chat: change.chat, own: scope, scope: effective };
116
+ };
@@ -15,6 +15,7 @@ export type { MoveMediaArchiveOptions } from "./media-archive-move.js";
15
15
  export { moveMediaArchive } from "./media-archive-move.js";
16
16
  export { type DownloadedModel, downloadImageModel, downloadTextModel, type ModelDownloadOptions, } from "./model-downloads.js";
17
17
  export { MONEY_DONE, MONEY_REQUEST, MONEY_WORDS, moneyClassesOf, PROMISE } from "./money-words.js";
18
+ export { type ProjectActivities, type ProjectActivity, type ProjectActivityChat, type ProjectActivityInput, projectActivity, } from "./project-activity.js";
18
19
  export type { ProjectChatFetcher, ProjectChatFetchProgress, ProjectChatFetchRequest, ProjectEvidenceContext, ProjectEvidenceItem, ProjectEvidencePerson, ProjectGathering, ProjectGatheringPorts, ProjectGatheringStop, ProjectIndexCatchUp, } from "./project-gathering.js";
19
20
  export { gatherProjectEvidence } from "./project-gathering.js";
20
21
  export type { ProjectNeighbour, ProjectNeighbourReader } from "./project-gathering-around.js";
@@ -173,7 +174,7 @@ export { QUERY_LIMITS, QUERY_VERSION } from "../search/lucene/types.js";
173
174
  export { questionLookup } from "../search/question-plan.js";
174
175
  export { type SearchTotal, TOTAL_CAP } from "../search/total.js";
175
176
  export { TASK_KINDS, TASK_ORIGINS, type TaskKind, type TaskOrigin } from "../tasks/index.js";
176
- export { addGroupMember, type GroupMemberChange, type GroupMemberMove, type GroupStore, listAccountGroups, moveGroupMember, removeGroupMember, } from "./account-groups.js";
177
+ export { type AccountScopeChange, addGroupMember, type ChatScope, type ChatScopeChange, type GroupMemberChange, type GroupMemberMove, type GroupStore, listAccountGroups, moveGroupMember, removeGroupMember, setAccountScope, setChatScope, } from "./account-groups.js";
177
178
  export type { AdminFound, AdminQuery, AdminSelection, AdminStatisticsService } from "./admin-statistics.js";
178
179
  export { adminStatisticsService } from "./admin-statistics.js";
179
180
  export { GAP_BOUNDS, type GapPlan, type GapRepair, gapsService, type RepairOptions } from "./archive-gaps.js";
@@ -11,6 +11,7 @@ export { archiveMedia, checkMediaArchive } from "./media-archive.js";
11
11
  export { moveMediaArchive } from "./media-archive-move.js";
12
12
  export { downloadImageModel, downloadTextModel, } from "./model-downloads.js";
13
13
  export { MONEY_DONE, MONEY_REQUEST, MONEY_WORDS, moneyClassesOf, PROMISE } from "./money-words.js";
14
+ export { projectActivity, } from "./project-activity.js";
14
15
  export { gatherProjectEvidence } from "./project-gathering.js";
15
16
  export { documentPassage, storedMessageNeighbours, storedNeighbours } from "./project-gathering-around.js";
16
17
  export { findEvidenceMentions } from "./project-gathering-mentions.js";
@@ -132,7 +133,7 @@ export { QUERY_LIMITS, QUERY_VERSION } from "../search/lucene/types.js";
132
133
  export { questionLookup } from "../search/question-plan.js";
133
134
  export { TOTAL_CAP } from "../search/total.js";
134
135
  export { TASK_KINDS, TASK_ORIGINS } from "../tasks/index.js";
135
- export { addGroupMember, listAccountGroups, moveGroupMember, removeGroupMember, } from "./account-groups.js";
136
+ export { addGroupMember, listAccountGroups, moveGroupMember, removeGroupMember, setAccountScope, setChatScope, } from "./account-groups.js";
136
137
  export { adminStatisticsService } from "./admin-statistics.js";
137
138
  export { GAP_BOUNDS, gapsService } from "./archive-gaps.js";
138
139
  export { countersService } from "./counters.js";
@@ -0,0 +1,45 @@
1
+ import type { AccountKey, MessageStore } from "../store/store.js";
2
+ export interface ProjectActivityInput {
3
+ since: number;
4
+ /** Exclusive; now when left out. */
5
+ until?: number;
6
+ /** Only chats of these accounts count, as under a group lock; every account when left out. */
7
+ accounts?: AccountKey[];
8
+ limit: number;
9
+ offset: number;
10
+ /** The busiest chats named per project. */
11
+ top?: number;
12
+ }
13
+ export interface ProjectActivityChat {
14
+ ref: string;
15
+ title: string | null;
16
+ messages: number;
17
+ }
18
+ export interface ProjectActivity {
19
+ ref: string;
20
+ key: string | null;
21
+ name: string;
22
+ /** Chats linked to the project or its child projects, confirmed, in the accounts read. */
23
+ chats: number;
24
+ /** Of them, muted now: their messages are not counted. */
25
+ muted: number;
26
+ messages: number;
27
+ /** Of `messages`, the owner's. */
28
+ sent: number;
29
+ /** The newest message of an unmuted linked chat, in or before the window. */
30
+ lastAt: string | null;
31
+ top: ProjectActivityChat[];
32
+ /** Some child projects were past the depth or count `projects status` reads, so their chats are not counted. */
33
+ partial: boolean;
34
+ }
35
+ export interface ProjectActivities {
36
+ items: ProjectActivity[];
37
+ total: number;
38
+ hasMore: boolean;
39
+ }
40
+ /**
41
+ * Every project's linked chats and how busy they were, in one pass: every confirmed link of the project and its
42
+ * children, any purpose and with no chat limit (`projects status` caps both), counted by when each message was sent. A
43
+ * muted chat is named in `muted` and left out of the counts, as everywhere the owner's activity is counted.
44
+ */
45
+ export declare const projectActivity: (store: MessageStore, input: ProjectActivityInput) => Promise<ProjectActivities>;
@@ -0,0 +1,76 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { formatReference } from "../domain/references.js";
3
+ import { childrenOf, inAccounts, projectsCatalog } from "./project-status/index.js";
4
+ import { linkedChatsOf } from "./stored-project-gathering.js";
5
+ const TOP = 3;
6
+ /**
7
+ * Every project's linked chats and how busy they were, in one pass: every confirmed link of the project and its
8
+ * children, any purpose and with no chat limit (`projects status` caps both), counted by when each message was sent. A
9
+ * muted chat is named in `muted` and left out of the counts, as everywhere the owner's activity is counted.
10
+ */
11
+ export const projectActivity = async (store, input) => {
12
+ const until = input.until ?? Date.now();
13
+ if (!(input.since < until))
14
+ throw new CliError("validation_error", "the window must start before it ends");
15
+ const whole = (n) => n === undefined || (Number.isInteger(n) && n >= 0);
16
+ if (!(input.limit >= 1 && whole(input.limit) && whole(input.offset) && whole(input.top)))
17
+ throw new CliError("validation_error", "limit must be at least 1; offset and top whole numbers from 0");
18
+ const catalog = await projectsCatalog(store);
19
+ const linked = [];
20
+ for (const [ref, entry] of catalog) {
21
+ const root = { ref, key: entry.key ?? null, name: entry.name };
22
+ const { children, cut } = await childrenOf(store, root, catalog);
23
+ const chats = new Map();
24
+ for (const project of [root, ...children])
25
+ for (const link of await linkedChatsOf(store, project.ref)) {
26
+ if (!inAccounts(input.accounts, link.provider, link.account))
27
+ continue;
28
+ chats.set(refOf(link), link);
29
+ }
30
+ linked.push({
31
+ project: ref,
32
+ key: root.key,
33
+ name: root.name,
34
+ chats: [...chats.values()],
35
+ partial: cut.some((one) => one.reason !== "cycle"),
36
+ });
37
+ }
38
+ const unique = new Map(linked.flatMap(({ chats }) => chats.map((chat) => [refOf(chat), chat])));
39
+ const asked = [...unique.values()];
40
+ const counts = await store.messages.chatActivityCounts(asked.map((chat) => ({ account: { provider: chat.provider, account: chat.account }, chatId: chat.chat })), { since: input.since, until, now: Date.now() });
41
+ const countOf = new Map(asked.map((chat, index) => [refOf(chat), counts[index]]));
42
+ const all = linked.map(({ project, key, name, chats, partial }) => {
43
+ const known = chats.flatMap((chat) => {
44
+ const count = countOf.get(refOf(chat));
45
+ return count ? [{ ref: refOf(chat), ...count }] : [];
46
+ });
47
+ const counted = known.filter((chat) => !chat.muted);
48
+ const last = counted.map((chat) => chat.lastAt).filter((at) => at !== null);
49
+ return {
50
+ ref: project,
51
+ key,
52
+ name,
53
+ chats: chats.length,
54
+ muted: known.length - counted.length,
55
+ messages: counted.reduce((sum, chat) => sum + chat.messages, 0),
56
+ sent: counted.reduce((sum, chat) => sum + chat.sent, 0),
57
+ lastAt: last.sort().at(-1) ?? null,
58
+ top: counted
59
+ .filter((chat) => chat.messages > 0)
60
+ .sort((a, b) => b.messages - a.messages || a.ref.localeCompare(b.ref, undefined, { numeric: true }))
61
+ .slice(0, input.top ?? TOP)
62
+ .map(({ ref, title, messages }) => ({ ref, title, messages })),
63
+ partial,
64
+ };
65
+ });
66
+ all.sort((a, b) => b.messages - a.messages ||
67
+ (b.lastAt ?? "").localeCompare(a.lastAt ?? "") ||
68
+ b.chats - a.chats ||
69
+ a.ref.localeCompare(b.ref, undefined, { numeric: true }));
70
+ return {
71
+ items: all.slice(input.offset, input.offset + input.limit),
72
+ total: all.length,
73
+ hasMore: input.offset + input.limit < all.length,
74
+ };
75
+ };
76
+ const refOf = (chat) => formatReference({ type: "chat", provider: chat.provider, account: chat.account, chat: chat.chat });
@@ -3,7 +3,7 @@ import type { AccountKey, MessageStore } from "../../store/store.js";
3
3
  import { type PurposeConfig } from "../project-purposes.js";
4
4
  import { type ChatCount, type ChatCounter } from "../stored-project-gathering.js";
5
5
  import { STATUS_SIGNALS } from "./signals/index.js";
6
- import type { StatusAttention, StatusChat, StatusItem, StatusProject, StatusSignal } from "./types.js";
6
+ import type { StatusAttention, StatusChat, StatusChild, StatusItem, StatusProject, StatusSignal } from "./types.js";
7
7
  export type * from "./types.js";
8
8
  export { STATUS_SIGNALS };
9
9
  /** Messages read per chat; the newest of the window. */
@@ -78,6 +78,16 @@ export interface ProjectStatus {
78
78
  version: number;
79
79
  }[];
80
80
  }
81
+ export declare const projectsCatalog: (store: MessageStore) => Promise<Map<string, import("../../store/index.js").VocabularyEntry>>;
82
+ /** Confirmed `member-of` links from another project; depth two, eight at most, a project seen twice skipped. */
83
+ export declare const childrenOf: (store: MessageStore, root: StatusProject, catalog: Awaited<ReturnType<typeof projectsCatalog>>) => Promise<{
84
+ children: StatusChild[];
85
+ cut: {
86
+ ref: string;
87
+ reason: "depth" | "cycle" | "limit";
88
+ }[];
89
+ }>;
90
+ export declare const inAccounts: (accounts: AccountKey[] | undefined, provider: string, account: string) => boolean;
81
91
  /**
82
92
  * Where a project stands, from the store alone: its linked chats and its children's, each read once, then every
83
93
  * signal on its own. A signal that fails is named in `failed` and the others still answer. No model call.
@@ -14,9 +14,9 @@ export const STATUS_WINDOW = 300;
14
14
  export const STATUS_CHATS = 16;
15
15
  const CHILD_DEPTH = 2;
16
16
  const CHILDREN = 8;
17
- const projectsCatalog = async (store) => new Map((await store.knowledge.vocabulary({ kind: "project" })).entries.map((entry) => [`project:${entry.id}`, entry]));
17
+ export const projectsCatalog = async (store) => new Map((await store.knowledge.vocabulary({ kind: "project" })).entries.map((entry) => [`project:${entry.id}`, entry]));
18
18
  /** Confirmed `member-of` links from another project; depth two, eight at most, a project seen twice skipped. */
19
- const childrenOf = async (store, root, catalog) => {
19
+ export const childrenOf = async (store, root, catalog) => {
20
20
  const children = [];
21
21
  const cut = [];
22
22
  const seen = new Set([root.ref]);
@@ -52,7 +52,7 @@ const childrenOf = async (store, root, catalog) => {
52
52
  }
53
53
  return { children, cut };
54
54
  };
55
- const inAccounts = (accounts, provider, account) => accounts === undefined || accounts.some((one) => one.provider === provider && one.account === account);
55
+ export const inAccounts = (accounts, provider, account) => accounts === undefined || accounts.some((one) => one.provider === provider && one.account === account);
56
56
  const failure = (error) => (error instanceof Error ? error.message : String(error));
57
57
  const owed = (item) => {
58
58
  const data = item.data;