@wirecat/cli-core 0.615.0 → 0.617.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 (96) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/dist/background/report/messages.d.ts +108 -0
  3. package/dist/background/report/messages.js +230 -0
  4. package/dist/background/report/render.d.ts +26 -4
  5. package/dist/background/report/render.js +56 -7
  6. package/dist/background/report/schema.d.ts +7 -1
  7. package/dist/background/report/schema.js +9 -3
  8. package/dist/background/report/stored-templates.d.ts +21 -19
  9. package/dist/background/report/stored-templates.js +20 -15
  10. package/dist/background/report/templates/morning-digest.email.en.liquid +3 -0
  11. package/dist/background/report/templates/morning-digest.email.ru.liquid +3 -0
  12. package/dist/background/report/templates/morning-digest.sample.json +8 -1
  13. package/dist/background/report/templates/morning-digest.telegram.en.liquid +3 -0
  14. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +3 -0
  15. package/dist/background/report/templates/morning-digest.text.en.liquid +3 -0
  16. package/dist/background/report/templates/morning-digest.text.ru.liquid +3 -0
  17. package/dist/background/report/templates/schedule-failed.email.en.liquid +12 -0
  18. package/dist/background/report/templates/schedule-failed.email.ru.liquid +12 -0
  19. package/dist/background/report/templates/schedule-failed.sample.json +10 -0
  20. package/dist/background/report/templates/schedule-failed.telegram.en.liquid +9 -0
  21. package/dist/background/report/templates/schedule-failed.telegram.ru.liquid +9 -0
  22. package/dist/background/report/templates/schedule-failed.text.en.liquid +9 -0
  23. package/dist/background/report/templates/schedule-failed.text.ru.liquid +9 -0
  24. package/dist/background/report/templates/weekly-gaps.email.en.liquid +19 -0
  25. package/dist/background/report/templates/weekly-gaps.email.ru.liquid +19 -0
  26. package/dist/background/report/templates/weekly-gaps.sample.json +33 -0
  27. package/dist/background/report/templates/weekly-gaps.telegram.en.liquid +15 -0
  28. package/dist/background/report/templates/weekly-gaps.telegram.ru.liquid +15 -0
  29. package/dist/background/report/templates/weekly-gaps.text.en.liquid +14 -0
  30. package/dist/background/report/templates/weekly-gaps.text.ru.liquid +14 -0
  31. package/dist/background/report/view.d.ts +5 -0
  32. package/dist/background/report/view.js +9 -1
  33. package/dist/background/schedules.d.ts +10 -1
  34. package/dist/background/schedules.js +127 -30
  35. package/dist/cli/help/sections.js +1 -0
  36. package/dist/cli/schedule/schedule-command.js +3 -2
  37. package/dist/cli/templates-command.js +43 -20
  38. package/dist/domain/links.d.ts +1 -1
  39. package/dist/domain/links.js +1 -1
  40. package/dist/domain/models.d.ts +6 -0
  41. package/dist/entities/fact.d.ts +4 -0
  42. package/dist/entities/fact.js +2 -1
  43. package/dist/entities/fields.d.ts +5 -0
  44. package/dist/entities/fields.js +3 -0
  45. package/dist/entities/index.d.ts +21 -1
  46. package/dist/entities/index.js +3 -1
  47. package/dist/entities/list-results.d.ts +4 -2
  48. package/dist/entities/list-results.js +4 -2
  49. package/dist/entities/memory.d.ts +4 -0
  50. package/dist/entities/memory.js +2 -1
  51. package/dist/entities/template.d.ts +11 -0
  52. package/dist/entities/template.js +12 -0
  53. package/dist/errors/reasons.js +6 -0
  54. package/dist/meetings/mcp/index.d.ts +15 -15
  55. package/dist/store/exports.d.ts +1 -0
  56. package/dist/store/exports.js +1 -0
  57. package/dist/store/index.d.ts +3 -2
  58. package/dist/store/index.js +1 -0
  59. package/dist/store/people.d.ts +7 -0
  60. package/dist/store/people.js +4 -0
  61. package/dist/store/source-review.d.ts +21 -0
  62. package/dist/store/sqlite/accounts.d.ts +3 -1
  63. package/dist/store/sqlite/accounts.js +10 -3
  64. package/dist/store/sqlite/added-sources.d.ts +16 -0
  65. package/dist/store/sqlite/added-sources.js +22 -0
  66. package/dist/store/sqlite/bot-tokens.d.ts +11 -0
  67. package/dist/store/sqlite/bot-tokens.js +57 -0
  68. package/dist/store/sqlite/chats.js +2 -0
  69. package/dist/store/sqlite/facts.js +3 -2
  70. package/dist/store/sqlite/imported-documents.js +3 -2
  71. package/dist/store/sqlite/knowledge.js +6 -4
  72. package/dist/store/sqlite/memories.js +5 -4
  73. package/dist/store/sqlite/mention-drain.js +9 -1
  74. package/dist/store/sqlite/merged-persons.d.ts +24 -0
  75. package/dist/store/sqlite/merged-persons.js +59 -0
  76. package/dist/store/sqlite/messages.d.ts +1 -1
  77. package/dist/store/sqlite/messages.js +3 -1
  78. package/dist/store/sqlite/notes.js +5 -4
  79. package/dist/store/sqlite/open-store.js +2 -0
  80. package/dist/store/sqlite/person-links.d.ts +10 -1
  81. package/dist/store/sqlite/person-links.js +14 -6
  82. package/dist/store/sqlite/person-merges.d.ts +39 -0
  83. package/dist/store/sqlite/person-merges.js +136 -0
  84. package/dist/store/sqlite/person-preparation.js +11 -8
  85. package/dist/store/sqlite/person-resolution.js +2 -1
  86. package/dist/store/sqlite/person-scope.js +2 -1
  87. package/dist/store/sqlite/relation-list.js +3 -2
  88. package/dist/store/sqlite/reported-relations.js +6 -3
  89. package/dist/store/sqlite/source-review.d.ts +20 -1
  90. package/dist/store/sqlite/source-review.js +74 -3
  91. package/dist/store/sqlite/task-board.d.ts +6 -1
  92. package/dist/store/sqlite/task-board.js +22 -4
  93. package/dist/store/sqlite/work-tasks.js +8 -9
  94. package/dist/store/types.d.ts +2 -0
  95. package/package.json +2 -2
  96. package/parity.json +19 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,107 @@ 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
+ ## Unreleased
9
+
10
+ ## 0.617.0 — 08.11.2026
11
+
12
+ ### Security
13
+
14
+ - **Messenger bot tokens are masked in the store.** A Telegram bot token (`<bot id>:<secret>`, as BotFather sends
15
+ it) in a message's text or caption, in the quote of a reply, or in an edit is saved as `<bot id>:<bot token
16
+ hidden>`, before the search copy and the vectors are made, for every messenger. Messages already stored, and those
17
+ an older build saves later, are masked the next time a store is opened for writing, from the newest message checked
18
+ last time (`store_settings.bot_tokens_masked_through`): the text, the search copy, the quote and the edit history,
19
+ and the vectors of the conversation pieces they were in are dropped, to be made again. No store version.
20
+ - **`Chat.searchable: false`**: a messenger saves a chat whose messages hold credentials as not searchable. Search
21
+ over all chats, search by meaning and context evidence leave it out (as for any chat with `chats.searchable = 0`);
22
+ a read that names the chat still sees it. A later save without the
23
+ field keeps the mark, and nothing a messenger saves unhides a chat.
24
+
25
+ ## 0.616.0 — 08.11.2026
26
+
27
+ ### Added
28
+
29
+ - **The weekly gaps message (`report/weekly-gaps`).** A morning digest may keep what it found on its own, which the
30
+ agenda did not show, in `internal.gaps` (`{ what, refs | ref, section }`); the digest never shows it. Once a week a
31
+ delivered digest run also sends those gaps along the same routes as one message: on Monday, or on the first digest
32
+ of a week whose Monday run did not send them, and never before a schedule's first Monday. It reads the run files
33
+ of the last 7 days, says a gap that several runs found once (the same ref, or the same words but for case and
34
+ punctuation) with how many digests found it, the most frequent first, and sends nothing for a week without gaps.
35
+ No agent runs for it. When it went, how many gaps and the deliveries are in the schedule's `weekly-gaps.json`.
36
+ - **A failed scheduled run sends a rendered notice (`notice/schedule-failed`).** In place of the one English line,
37
+ every route of a schedule that notifies on failures gets which schedule failed, since when and how many runs in a
38
+ row, the cause in the owner's language (keyring locked, sign-in needed, service unreachable, service error,
39
+ settings, stopped, crashed: from the error code, never its message) and one "fix" link to the tool's sync screen
40
+ (`sync/<tool>`). A notice whose templates fail sends the old line. The desktop notice is unchanged.
41
+ - Default templates for both, for Telegram, email and text in Russian and English, with the digest's escaping and
42
+ platform rules; `templates edit | preview` now take both keys, checked against their own synthetic samples.
43
+ - **A source check names what changed, and a source review's text can be read.** `knowledge.checkSources` also
44
+ answers `changedRefs`: the sources found changed in that run, whether they raised a review or still said the
45
+ quoted words, that no open `evidence_findings` batch cites, leaving out deleted sources and cited memories or facts.
46
+ An agent reads those again for new facts. `knowledge.sourceReviewTexts(id)` gives each source of a
47
+ `memory_source_review` with its quote, its text as cited (notes, documents and messages keep history) and its text
48
+ now, so a reader compares them while the review itself holds no source text. The shared `memory` and `fact`
49
+ entities take an optional `source_review: { id, cause } | null`, the marker reads already carry.
50
+ `knowledge.changedSources({ since })` reads the cited sources a check found changed since then and that differ
51
+ from the version cited, with the same exclusions, so a change the timer's check already took still reaches an
52
+ agent.
53
+ - **`store.notes.addedSource(ref)` reads an added source back with what it is and what was kept**: `kind`, the `url`
54
+ as given, `fileName`, `mime`, `size`, `kept` and the `copy` path, beside its document; `undefined` for any other
55
+ document or a removed source. The `AddedSourceDetails` type is exported.
56
+ - **`people.merges(uid)`, `people.undoMerge(to, from, by)` and `people.split(uid, identities, by)`.** `merges` lists
57
+ the people merged into a person, each with the identities from it that are still there, the method, who and when,
58
+ under an id `merge:<to>-<from>` (`parseMergeId` reads it back). `undoMerge` moves those identities back to the old
59
+ person, whose uid stays the same, and leaves any the owner split or unlinked off since; a chain of merges undoes
60
+ newest first. `split` moves the chosen identities to one new person. Both are the owner's only
61
+ (`identity.owner-only`; pass `"owner"` only from a path that established the owner ran it), and an automatic match
62
+ by the same address does not join those people again. `undoMerge` refuses with `identity.stale` when one of the
63
+ identities was merged on into another person since.
64
+ - **The digest says how many open tasks have no due date.** A report may give `tasks.undated` (a whole number; absent
65
+ is 0), and the section with the task group links gets one line after them, "без срока: 91 · открыть" or "no due
66
+ date: 91 · open", in every channel's Russian and English template, linking `tasks/undated`. The line is left out
67
+ when the count is 0. The v1 link grammar takes `tasks/undated` beside `overdue`, `today`, `tomorrow` and
68
+ `new/<since>`; the bounce page and WireCat Desktop need it too before such a link opens there.
69
+
70
+ ### Changed — may break callers
71
+
72
+ - **`templates` takes the language as `--locale <code>`, not `--language <code>`, and its words come from the shared
73
+ vocabulary.** `--language` is the query language in every other command (`<lucene|legacy>`); the template's
74
+ language keeps its field name, `language`. `--file <file>` names the file as the vocabulary does, `templates list
75
+ [query...]` narrows by `key`, `channel`, `language` and `source` (`templates list channel:telegram source:stored`)
76
+ and answers the `template` entity, every command has a short summary, and `<tool> commands` lists the group under
77
+ Automate, not Other. The shared commands' lint now covers the group, so `cli-dev lint` passes on a tool that mounts
78
+ it with cli-base 0.89.0 (`preview`, `--locale`, `--undo`, `--channel <channel>`).
79
+ - **`people.personByUid` of a person merged into someone else answers with that person.** Its `uid` is the
80
+ current person's, not the one asked for, and `mergedInto` is set; `personSeenInAccounts` follows the same merge.
81
+ A caller that compares the answer's `uid` with the one it passed reads `mergedInto` instead.
82
+ - **`unlinkIdentity` records its move with method `unlink`, whatever method the caller passes,** so a separation is
83
+ never listed as a merge.
84
+
85
+ ### Fixed
86
+
87
+ - **One notification per digest while WireCat Desktop runs.** Desktop announces a new morning digest itself, so a
88
+ finished run showed two system notices. A schedule's run now leaves its own success notice out when
89
+ `<state>/schedules/desktop.json` names a live pid and lists the schedule in `announces` (Desktop writes it while it
90
+ runs, wirecat-desktop#214). A marker whose pid is gone counts for nothing; failure notices and deliveries do not
91
+ change.
92
+ - **A mail-gated agent no longer runs again on the input its last run ended on.** One refusal the agent could not
93
+ get past (a findings key already taken) turned into a paid run every 5 minutes until the day's cost cap. The
94
+ timer (`schedule exec`) now keeps the SHA-256 of a `--on-new-mail` agent's input in `last.json` (`inputHash`);
95
+ when the next input is the same and that run exited 0, its mark did not move, so the run is left out with
96
+ `skipped.reason` `mail.same-input` (`SKIP_REASONS.mailSameInput`). New mail changes the input and runs normally;
97
+ `schedule run` by hand always runs. `runSchedule(…, { skipRepeatedInput: true })` turns it on for another timer.
98
+ - **A person shows once after a merge.** The person a merge emptied stayed in `taskPeople`, so memo's `people list`
99
+ and `search people` showed the same person two or three times. It is skipped now and its tasks count for the person
100
+ it was merged into. Rows that name the old uid keep it, so undoing loses nothing, and the filters by a person read
101
+ them with the current person: memories, facts, notes, documents' `person:`, relationships, the task board's
102
+ `assignee:` and preparation, and assigning the old uid to a task the current person holds is a no-op.
103
+ A source's sync that reports a relationship on the current person withdraws what it reported on the old one, so
104
+ the relationship shows once.
105
+
106
+ - **`account remove` is in the messenger parity manifest** (`parity.json`), with `--keep-data`, `--delete-data`
107
+ and `--dry-run`, so tg, max and wa can adopt it without failing `parity:check`.
108
+
8
109
  ## 0.614.0 — 08.11.2026
9
110
 
10
111
  ### Added
@@ -0,0 +1,108 @@
1
+ import { type ReportKind } from "./schema.js";
2
+ import { type LinkOf, type Moment, type ViewLink } from "./view.js";
3
+ /** Every message WireCat renders for the owner: the digest, the weekly gaps, and a failed schedule's notice. */
4
+ export type MessageKind = ReportKind | "weekly-gaps" | "schedule-failed";
5
+ /** What one digest run found that its agenda had not shown, as the agent wrote it in `internal.gaps`. */
6
+ export interface Gap {
7
+ what: string;
8
+ /** The agenda section it belonged in (`owed`, `mail`…), or null. */
9
+ section: string | null;
10
+ refs: string[];
11
+ }
12
+ /** A `wirecat.report/1` document of kind `weekly-gaps`: the gaps of a week of digests, each said once. */
13
+ export interface WeeklyGaps {
14
+ kind: "weekly-gaps";
15
+ from: string;
16
+ to: string;
17
+ /** The digests the week had. */
18
+ runs: number;
19
+ gaps: (Gap & {
20
+ seen: number;
21
+ first: string;
22
+ last: string;
23
+ })[];
24
+ }
25
+ /**
26
+ * The gaps a digest's answer kept in `internal.gaps`, or none. `internal` is the agent's note to itself, so a gap
27
+ * that is not `{ what, refs | ref, section }` is left out rather than failing anything; `what` loses its leaks.
28
+ */
29
+ export declare const gapsOfAnswer: (answer: string) => Gap[] | undefined;
30
+ /**
31
+ * The gaps of the digest runs in `runs` from the last `days` days, oldest run first. One gap that several runs
32
+ * found is said once: two gaps are the same when they share a ref, or their words differ only in case and
33
+ * punctuation. The newest wording is kept; the ones seen most often come first.
34
+ */
35
+ export declare const weeklyGapsOf: (runs: string, now: number, days?: number) => WeeklyGaps;
36
+ /** A weekly-gaps document as JSON, checked: the shipped sample, or one a test wrote. */
37
+ export declare const parseWeeklyGaps: (json: string) => WeeklyGaps;
38
+ /** The document as `<run>.report.json`-style JSON, refs kept for Desktop. */
39
+ export declare const weeklyGapsDocument: (gaps: WeeklyGaps) => Record<string, unknown>;
40
+ /** Why a scheduled run failed, as a word a template turns into the owner's language. */
41
+ export declare const FAILURE_CAUSES: readonly ["locked", "sign-in", "network", "provider", "setup", "stopped", "crashed"];
42
+ export type FailureCause = (typeof FAILURE_CAUSES)[number];
43
+ /** The cause of a failed run from its error code, else its exit code: killed (137, 143) is stopped. */
44
+ export declare const causeOf: (errorCode: string | undefined, exitCode: number) => FailureCause;
45
+ /** A scheduled run that failed: the notice `notice/schedule-failed` renders. */
46
+ export interface ScheduleFailure {
47
+ kind: "schedule-failed";
48
+ /** The CLI the schedule belongs to: `memo`, `tg`. */
49
+ tool: string;
50
+ schedule: string;
51
+ at: string;
52
+ /** The first failure of the ones in a row. */
53
+ since: string;
54
+ failures: number;
55
+ cause: FailureCause;
56
+ /** The one "fix" link: the tool's sync screen. */
57
+ refs: string[];
58
+ }
59
+ export declare const parseScheduleFailure: (json: string) => ScheduleFailure;
60
+ export declare const GAPS_CAP = 15;
61
+ export interface ViewGap {
62
+ what: string;
63
+ section: string | null;
64
+ /** In how many of the week's digests it came up; `plural` picks the word's form (`Intl.PluralRules`). */
65
+ seen: number;
66
+ plural: string;
67
+ first: Moment;
68
+ last: Moment;
69
+ links: ViewLink[];
70
+ }
71
+ /** What a `report/weekly-gaps` template gets. */
72
+ export interface GapsView {
73
+ kind: "weekly-gaps";
74
+ language: string;
75
+ from: Moment;
76
+ to: Moment;
77
+ runs: number;
78
+ plural: string;
79
+ items: ViewGap[];
80
+ /** Gaps past the cap, or dropped to fit Telegram. */
81
+ more: number;
82
+ links: ViewLink[];
83
+ }
84
+ export declare const gapsView: (gaps: WeeklyGaps, { language, now, timeZone, linkOf, }: {
85
+ language: string;
86
+ now: number;
87
+ timeZone?: string;
88
+ linkOf?: LinkOf;
89
+ }) => GapsView;
90
+ /** What a `notice/schedule-failed` template gets. */
91
+ export interface NoticeView {
92
+ kind: "schedule-failed";
93
+ language: string;
94
+ tool: string;
95
+ schedule: string;
96
+ at: Moment;
97
+ since: Moment;
98
+ failures: number;
99
+ plural: string;
100
+ cause: FailureCause;
101
+ links: ViewLink[];
102
+ }
103
+ export declare const noticeView: (failure: ScheduleFailure, { language, now, timeZone, linkOf, }: {
104
+ language: string;
105
+ now: number;
106
+ timeZone?: string;
107
+ linkOf?: LinkOf;
108
+ }) => NoticeView;
@@ -0,0 +1,230 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { jsonOfAnswer, REPORT_FORMAT, withoutLeaks } from "./schema.js";
4
+ import { momentFor } from "./view.js";
5
+ const WHAT_LIMIT = 160;
6
+ const SECTION = /^[a-z][a-z-]{0,23}$/;
7
+ const DAY_MS = 86_400_000;
8
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ const cut = (text, limit) => (text.length <= limit ? text : `${text.slice(0, limit - 1).trimEnd()}…`);
10
+ const stringsOf = (value) => Array.isArray(value) ? value.filter((one) => typeof one === "string") : [];
11
+ /**
12
+ * The gaps a digest's answer kept in `internal.gaps`, or none. `internal` is the agent's note to itself, so a gap
13
+ * that is not `{ what, refs | ref, section }` is left out rather than failing anything; `what` loses its leaks.
14
+ */
15
+ export const gapsOfAnswer = (answer) => {
16
+ const json = jsonOfAnswer(answer);
17
+ if (json === undefined)
18
+ return undefined;
19
+ let document;
20
+ try {
21
+ document = JSON.parse(json);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ if (!isObject(document) || document.format !== REPORT_FORMAT || document.kind !== "morning-digest")
27
+ return undefined;
28
+ const gaps = isObject(document.internal) ? document.internal.gaps : undefined;
29
+ return (Array.isArray(gaps) ? gaps : []).flatMap((gap) => {
30
+ if (!isObject(gap) || typeof gap.what !== "string")
31
+ return [];
32
+ const what = withoutLeaks(gap.what.trim()).text;
33
+ if (!what)
34
+ return [];
35
+ return [
36
+ {
37
+ what: cut(what, WHAT_LIMIT),
38
+ section: typeof gap.section === "string" && SECTION.test(gap.section) ? gap.section : null,
39
+ refs: [...new Set([...stringsOf(gap.refs), ...(typeof gap.ref === "string" ? [gap.ref] : [])])],
40
+ },
41
+ ];
42
+ });
43
+ };
44
+ /** A run file's time from its name, `2026-11-08T08-30-00Z.md`; NaN for any other file. */
45
+ const runTime = (file) => {
46
+ const [, day, hour, minute, second] = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})Z\.md$/.exec(file) ?? [];
47
+ return day ? Date.parse(`${day}T${hour}:${minute}:${second}Z`) : Number.NaN;
48
+ };
49
+ const sameText = (text) => text
50
+ .toLowerCase()
51
+ .replace(/[\p{P}\p{S}\s]+/gu, " ")
52
+ .trim();
53
+ /**
54
+ * The gaps of the digest runs in `runs` from the last `days` days, oldest run first. One gap that several runs
55
+ * found is said once: two gaps are the same when they share a ref, or their words differ only in case and
56
+ * punctuation. The newest wording is kept; the ones seen most often come first.
57
+ */
58
+ export const weeklyGapsOf = (runs, now, days = 7) => {
59
+ const from = now - days * DAY_MS;
60
+ const files = existsSync(runs)
61
+ ? readdirSync(runs)
62
+ .map((file) => ({ file, at: runTime(file) }))
63
+ .filter(({ at }) => at > from && at <= now)
64
+ .sort((a, b) => a.at - b.at)
65
+ : [];
66
+ const groups = [];
67
+ let digests = 0;
68
+ for (const { file, at } of files) {
69
+ const gaps = gapsOfAnswer(readFileSync(join(runs, file), "utf8"));
70
+ if (gaps === undefined)
71
+ continue;
72
+ digests++;
73
+ for (const gap of gaps) {
74
+ const text = sameText(gap.what);
75
+ const group = groups.find((one) => one.texts.has(text) || gap.refs.some((ref) => one.refs.has(ref)));
76
+ if (!group) {
77
+ groups.push({ gap, texts: new Set([text]), refs: new Set(gap.refs), seen: new Set([at]), first: at, last: at });
78
+ continue;
79
+ }
80
+ group.texts.add(text);
81
+ for (const ref of gap.refs)
82
+ group.refs.add(ref);
83
+ group.seen.add(at);
84
+ group.last = at;
85
+ group.gap = { what: gap.what, section: gap.section ?? group.gap.section, refs: [...group.refs] };
86
+ }
87
+ }
88
+ return {
89
+ kind: "weekly-gaps",
90
+ from: new Date(from).toISOString(),
91
+ to: new Date(now).toISOString(),
92
+ runs: digests,
93
+ gaps: groups
94
+ .sort((a, b) => b.seen.size - a.seen.size || b.last - a.last)
95
+ .map(({ gap, refs, seen, first, last }) => ({
96
+ ...gap,
97
+ refs: [...refs],
98
+ seen: seen.size,
99
+ first: new Date(first).toISOString(),
100
+ last: new Date(last).toISOString(),
101
+ })),
102
+ };
103
+ };
104
+ class Invalid extends Error {
105
+ }
106
+ const moment = (value, at) => {
107
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value)))
108
+ throw new Invalid(at);
109
+ return value;
110
+ };
111
+ const count = (value, at) => {
112
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0)
113
+ throw new Invalid(at);
114
+ return value;
115
+ };
116
+ /** A weekly-gaps document as JSON, checked: the shipped sample, or one a test wrote. */
117
+ export const parseWeeklyGaps = (json) => {
118
+ const document = JSON.parse(json);
119
+ if (!isObject(document) || document.format !== REPORT_FORMAT || document.kind !== "weekly-gaps")
120
+ throw new Invalid("kind");
121
+ if (!Array.isArray(document.gaps))
122
+ throw new Invalid("gaps");
123
+ return {
124
+ kind: "weekly-gaps",
125
+ from: moment(document.from, "from"),
126
+ to: moment(document.to, "to"),
127
+ runs: count(document.runs, "runs"),
128
+ gaps: document.gaps.map((gap, g) => {
129
+ if (!isObject(gap) || typeof gap.what !== "string")
130
+ throw new Invalid(`gaps[${g}].what`);
131
+ return {
132
+ what: cut(withoutLeaks(gap.what).text, WHAT_LIMIT),
133
+ section: typeof gap.section === "string" && SECTION.test(gap.section) ? gap.section : null,
134
+ refs: stringsOf(gap.refs),
135
+ seen: count(gap.seen, `gaps[${g}].seen`),
136
+ first: moment(gap.first, `gaps[${g}].first`),
137
+ last: moment(gap.last, `gaps[${g}].last`),
138
+ };
139
+ }),
140
+ };
141
+ };
142
+ /** The document as `<run>.report.json`-style JSON, refs kept for Desktop. */
143
+ export const weeklyGapsDocument = (gaps) => ({ format: REPORT_FORMAT, ...gaps });
144
+ /** Why a scheduled run failed, as a word a template turns into the owner's language. */
145
+ export const FAILURE_CAUSES = ["locked", "sign-in", "network", "provider", "setup", "stopped", "crashed"];
146
+ const CAUSE_OF_CODE = {
147
+ authentication_error: "sign-in",
148
+ network_error: "network",
149
+ provider_unavailable: "network",
150
+ timeout: "network",
151
+ rate_limited: "network",
152
+ provider_error: "provider",
153
+ invalid_response: "provider",
154
+ outcome_unknown: "provider",
155
+ configuration_error: "setup",
156
+ permission_error: "setup",
157
+ not_found: "setup",
158
+ validation_error: "setup",
159
+ conflict: "setup",
160
+ confirmation_required: "setup",
161
+ cancelled: "stopped",
162
+ };
163
+ /** The cause of a failed run from its error code, else its exit code: killed (137, 143) is stopped. */
164
+ export const causeOf = (errorCode, exitCode) => (errorCode === undefined ? undefined : CAUSE_OF_CODE[errorCode]) ??
165
+ (exitCode === 137 || exitCode === 143 ? "stopped" : "crashed");
166
+ export const parseScheduleFailure = (json) => {
167
+ const document = JSON.parse(json);
168
+ if (!isObject(document) || document.kind !== "schedule-failed")
169
+ throw new Invalid("kind");
170
+ if (typeof document.tool !== "string" || typeof document.schedule !== "string")
171
+ throw new Invalid("schedule");
172
+ if (!FAILURE_CAUSES.includes(document.cause))
173
+ throw new Invalid("cause");
174
+ return {
175
+ kind: "schedule-failed",
176
+ tool: document.tool,
177
+ schedule: document.schedule,
178
+ at: moment(document.at, "at"),
179
+ since: moment(document.since, "since"),
180
+ failures: count(document.failures, "failures"),
181
+ cause: document.cause,
182
+ refs: stringsOf(document.refs),
183
+ };
184
+ };
185
+ const LINK_WORDS = {
186
+ ru: { open: "открыть", fix: "исправить" },
187
+ en: { open: "open", fix: "fix" },
188
+ };
189
+ const wordsOf = (language) => LINK_WORDS[language] ?? LINK_WORDS.en;
190
+ const linkOfRefs = (refs, linkOf, label) => {
191
+ const url = refs.map(linkOf).find((one) => one !== null);
192
+ return url ? [{ kind: "open", url, label }] : [];
193
+ };
194
+ export const GAPS_CAP = 15;
195
+ export const gapsView = (gaps, { language, now, timeZone, linkOf = () => null, }) => {
196
+ const plural = new Intl.PluralRules(language);
197
+ const at = (iso) => momentFor(iso, now, language, timeZone);
198
+ const label = wordsOf(language).open;
199
+ return {
200
+ kind: "weekly-gaps",
201
+ language,
202
+ from: at(gaps.from),
203
+ to: at(gaps.to),
204
+ runs: gaps.runs,
205
+ plural: plural.select(gaps.runs),
206
+ items: gaps.gaps.slice(0, GAPS_CAP).map((gap) => ({
207
+ what: gap.what,
208
+ section: gap.section,
209
+ seen: gap.seen,
210
+ plural: plural.select(gap.seen),
211
+ first: at(gap.first),
212
+ last: at(gap.last),
213
+ links: linkOfRefs(gap.refs, linkOf, label),
214
+ })),
215
+ more: Math.max(gaps.gaps.length - GAPS_CAP, 0),
216
+ links: [],
217
+ };
218
+ };
219
+ export const noticeView = (failure, { language, now, timeZone, linkOf = () => null, }) => ({
220
+ kind: "schedule-failed",
221
+ language,
222
+ tool: failure.tool,
223
+ schedule: failure.schedule,
224
+ at: momentFor(failure.at, now, language, timeZone),
225
+ since: momentFor(failure.since, now, language, timeZone),
226
+ failures: failure.failures,
227
+ plural: new Intl.PluralRules(language).select(failure.failures),
228
+ cause: failure.cause,
229
+ links: linkOfRefs(failure.refs, linkOf, wordsOf(language).fix),
230
+ });
@@ -1,8 +1,10 @@
1
1
  import { type LinkConfig } from "../../domain/links.js";
2
- import { type ReportKind } from "./schema.js";
2
+ import type { GapsView, MessageKind, NoticeView } from "./messages.js";
3
3
  import { type ReportView } from "./view.js";
4
4
  export declare const REPORT_CHANNELS: readonly ["telegram", "email", "text"];
5
5
  export type ReportChannel = (typeof REPORT_CHANNELS)[number];
6
+ /** What a template renders: the digest's view, the weekly gaps' or a failed schedule's notice. */
7
+ export type MessageView = ReportView | GapsView | NoticeView;
6
8
  export declare const REPORT_REASONS: {
7
9
  readonly invalid: "delivery.report-invalid";
8
10
  readonly templateFailed: "report.template-failed";
@@ -31,7 +33,7 @@ export interface Rendering {
31
33
  * One channel's text of a report. A failing `template` (a stored override, later) falls back to the shipped one for
32
34
  * this channel only. Telegram is rendered again with an item fewer, from the largest section, until it fits.
33
35
  */
34
- export declare const renderReport: (view: ReportView, channel: ReportChannel, { template }?: {
36
+ export declare const renderReport: (view: MessageView, channel: ReportChannel, { template }?: {
35
37
  template?: string;
36
38
  }) => Promise<Rendering>;
37
39
  /**
@@ -39,12 +41,12 @@ export declare const renderReport: (view: ReportView, channel: ReportChannel, {
39
41
  * rules may take nothing out, and a Telegram text must fit once the size fit dropped what it could. Unlike
40
42
  * `renderReport` it never falls back to the shipped template.
41
43
  */
42
- export declare const checkTemplate: (view: ReportView, channel: ReportChannel, source: string) => Promise<{
44
+ export declare const checkTemplate: (view: MessageView, channel: ReportChannel, source: string) => Promise<{
43
45
  problems: string[];
44
46
  text: string;
45
47
  }>;
46
48
  /** The owner's stored templates of one report kind and language, by channel; a missing channel uses the shipped one. */
47
- export type StoredTemplates = (kind: ReportKind, language: string) => Promise<Partial<Record<ReportChannel, string>>>;
49
+ export type StoredTemplates = (kind: MessageKind, language: string) => Promise<Partial<Record<ReportChannel, string>>>;
48
50
  /** What `last.json` keeps of a report run, beside the deliveries. */
49
51
  export interface ReportRun {
50
52
  language: string;
@@ -82,3 +84,23 @@ export declare const prepareReport: (answer: string, { language, now, timeZone,
82
84
  /** Read for `WIRECAT_LINKS=off`. */
83
85
  env?: NodeJS.ProcessEnv;
84
86
  }) => Promise<PreparedReport | undefined>;
87
+ /** A message other than the digest, rendered for every channel: what `deliver` sends as a rendered parcel. */
88
+ export interface PreparedMessage {
89
+ telegram: string;
90
+ email: string;
91
+ text: string;
92
+ /** The text's first line. */
93
+ subject: string;
94
+ invalid: false;
95
+ language: string;
96
+ /** `report.template-failed`, `report.template-tags`: as a report run records them. */
97
+ reasons: string[];
98
+ }
99
+ /**
100
+ * Renders `kind` in the owner's language, or in English when cli-core ships no template in it, over the owner's
101
+ * stored templates; a lookup or a template that fails falls back to the shipped one, as a report's does.
102
+ */
103
+ export declare const prepareMessage: (kind: MessageKind, viewOf: (language: string) => MessageView, { language, templates: storedTemplates }: {
104
+ language: string;
105
+ templates?: StoredTemplates;
106
+ }) => Promise<PreparedMessage>;
@@ -40,12 +40,23 @@ const ALLOWED = {
40
40
  span: ["style"],
41
41
  },
42
42
  };
43
- const linkUrls = (view) => new Set([
44
- ...view.links,
45
- ...view.sections.flatMap((section) => section.items.flatMap((item) => item.links)),
46
- ...view.sections.flatMap((section) => section.groups.flatMap((group) => (group.link ? [group.link] : []))),
47
- ...view.health.items.flatMap((item) => item.links),
48
- ].map((link) => link.url));
43
+ /** Every link URL anywhere in the view: the only places a template's `href` may point. */
44
+ const linkUrls = (view) => {
45
+ const urls = new Set();
46
+ const walk = (value) => {
47
+ if (Array.isArray(value))
48
+ value.forEach(walk);
49
+ else if (value && typeof value === "object") {
50
+ const { kind, url, label } = value;
51
+ if ((kind === "open" || kind === "web") && typeof url === "string" && typeof label === "string")
52
+ urls.add(url);
53
+ else
54
+ Object.values(value).forEach(walk);
55
+ }
56
+ };
57
+ walk(view);
58
+ return urls;
59
+ };
49
60
  /**
50
61
  * What a template's HTML may keep, enforced after it rendered: the channel's tags and attributes only, a `style`
51
62
  * with no `url(`, and an `href` only to a URL of the view model. Anything else goes, its text kept; `removed` names
@@ -129,8 +140,15 @@ const renderWithFallback = async (view, channel, template) => {
129
140
  return { ...(await shipped()), templateFailed: true };
130
141
  }
131
142
  };
132
- /** The view with one item fewer: the last of the largest section, counted in that section's `more`. */
143
+ /**
144
+ * The view with one item fewer: the digest's last item of its largest section, the last gap; counted in `more`.
145
+ * A notice has nothing to drop.
146
+ */
133
147
  const dropOne = (view) => {
148
+ if (view.kind === "schedule-failed")
149
+ return undefined;
150
+ if (view.kind === "weekly-gaps")
151
+ return view.items.length === 0 ? undefined : { ...view, items: view.items.slice(0, -1), more: view.more + 1 };
134
152
  const lists = [...view.sections.map((section) => section.items.length), view.health.items.length];
135
153
  const largest = lists.reduce((most, one) => Math.max(most, one), 0);
136
154
  if (largest === 0)
@@ -260,3 +278,34 @@ const templateOf = (templates, channel) => {
260
278
  const template = templates[channel];
261
279
  return template === undefined ? {} : { template };
262
280
  };
281
+ /**
282
+ * Renders `kind` in the owner's language, or in English when cli-core ships no template in it, over the owner's
283
+ * stored templates; a lookup or a template that fails falls back to the shipped one, as a report's does.
284
+ */
285
+ export const prepareMessage = async (kind, viewOf, { language, templates: storedTemplates }) => {
286
+ const shipped = existsSync(templateFile(kind, "telegram", language)) ? language : DEFAULT_LANGUAGE;
287
+ let lookupFailed = false;
288
+ const templates = storedTemplates
289
+ ? await storedTemplates(kind, shipped).catch(() => {
290
+ lookupFailed = true;
291
+ return {};
292
+ })
293
+ : {};
294
+ const view = viewOf(shipped);
295
+ const telegram = await renderReport(view, "telegram", templateOf(templates, "telegram"));
296
+ const email = await renderReport(view, "email", templateOf(templates, "email"));
297
+ const text = await renderReport(view, "text", templateOf(templates, "text"));
298
+ const renderings = [telegram, email, text];
299
+ return {
300
+ telegram: telegram.text,
301
+ email: email.text,
302
+ text: text.text,
303
+ subject: text.text.split("\n")[0] ?? "",
304
+ invalid: false,
305
+ language: shipped,
306
+ reasons: [
307
+ ...(lookupFailed || renderings.some((one) => one.templateFailed) ? [REPORT_REASONS.templateFailed] : []),
308
+ ...(renderings.some((one) => one.templateTags > 0) ? [REPORT_REASONS.templateTags] : []),
309
+ ],
310
+ };
311
+ };
@@ -61,13 +61,17 @@ export interface ReportScope {
61
61
  meetings: number;
62
62
  };
63
63
  }
64
- /** The open task groups, each opened by a `tasks/<filter>` link; `new` counts what was created since `newSince`. */
64
+ /**
65
+ * The open task groups, each opened by a `tasks/<filter>` link; `new` counts what was created since `newSince`,
66
+ * `undated` the open tasks with no due date (0 when the report leaves it out).
67
+ */
65
68
  export interface TaskCounts {
66
69
  overdue: number;
67
70
  today: number;
68
71
  tomorrow: number;
69
72
  new: number;
70
73
  newSince: string | null;
74
+ undated: number;
71
75
  }
72
76
  /** A `wirecat.report/1` document as the renderers read it: checked, cut to its limits, with no `links` or `internal`. */
73
77
  export interface Report {
@@ -89,6 +93,8 @@ export declare const withoutLeaks: (text: string) => {
89
93
  * with refs (Desktop builds its own links from them) and without `links` or `internal`.
90
94
  */
91
95
  export declare const reportDocument: (report: Report) => Record<string, unknown>;
96
+ /** The JSON text of a run's answer: the bare object, or the only fenced `json` block; undefined for anything else. */
97
+ export declare const jsonOfAnswer: (answer: string) => string | undefined;
92
98
  export type ParsedReport = {
93
99
  report: Report;
94
100
  leaks: number;
@@ -132,6 +132,7 @@ const tasksOf = (value) => {
132
132
  tomorrow: wholeOr0(value.tomorrow, "tasks.tomorrow"),
133
133
  new: wholeOr0(value.new, "tasks.new"),
134
134
  newSince: momentOf(value.new_since, "tasks.new_since"),
135
+ undated: wholeOr0(value.undated, "tasks.undated"),
135
136
  };
136
137
  };
137
138
  const cut = (text, limit) => (text.length <= limit ? text : `${text.slice(0, limit - 1).trimEnd()}…`);
@@ -254,17 +255,22 @@ export const reportDocument = (report) => ({
254
255
  tomorrow: report.tasks.tomorrow,
255
256
  new: report.tasks.new,
256
257
  new_since: report.tasks.newSince,
258
+ undated: report.tasks.undated,
257
259
  },
258
260
  });
261
+ /** The JSON text of a run's answer: the bare object, or the only fenced `json` block; undefined for anything else. */
262
+ export const jsonOfAnswer = (answer) => {
263
+ const text = answer.trim();
264
+ const fenced = /^```json[ \t]*\n([\s\S]*?)\n```$/.exec(text)?.[1];
265
+ return fenced ?? (text.startsWith("{") ? text : undefined);
266
+ };
259
267
  /**
260
268
  * A run's answer as a report: one JSON object, bare or as the only fenced `json` block. Text that is neither is not a
261
269
  * report (`undefined`) and keeps the Markdown path; a JSON answer that fails the check is `invalid`, with the path
262
270
  * of the first field that failed, and is never shown.
263
271
  */
264
272
  export const parseReport = (answer) => {
265
- const text = answer.trim();
266
- const fenced = /^```json[ \t]*\n([\s\S]*?)\n```$/.exec(text)?.[1];
267
- const json = fenced ?? (text.startsWith("{") ? text : undefined);
273
+ const json = jsonOfAnswer(answer);
268
274
  if (json === undefined)
269
275
  return undefined;
270
276
  let document;