@wirecat/cli-core 0.614.0 → 0.616.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 (106) hide show
  1. package/CHANGELOG.md +105 -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 +41 -5
  5. package/dist/background/report/render.js +115 -25
  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 +66 -0
  9. package/dist/background/report/stored-templates.js +85 -0
  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 +157 -0
  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 +13 -2
  34. package/dist/background/schedules.js +128 -30
  35. package/dist/cli/help/sections.js +1 -0
  36. package/dist/cli/index.d.ts +2 -1
  37. package/dist/cli/index.js +1 -1
  38. package/dist/cli/schedule/schedule-command.d.ts +2 -0
  39. package/dist/cli/schedule/schedule-command.js +21 -2
  40. package/dist/cli/shared-command-exports.d.ts +1 -0
  41. package/dist/cli/shared-command-exports.js +2 -0
  42. package/dist/cli/templates-command.d.ts +16 -0
  43. package/dist/cli/templates-command.js +266 -0
  44. package/dist/domain/links.d.ts +1 -1
  45. package/dist/domain/links.js +1 -1
  46. package/dist/entities/fact.d.ts +4 -0
  47. package/dist/entities/fact.js +2 -1
  48. package/dist/entities/fields.d.ts +5 -0
  49. package/dist/entities/fields.js +3 -0
  50. package/dist/entities/index.d.ts +21 -1
  51. package/dist/entities/index.js +3 -1
  52. package/dist/entities/list-results.d.ts +4 -2
  53. package/dist/entities/list-results.js +4 -2
  54. package/dist/entities/memory.d.ts +4 -0
  55. package/dist/entities/memory.js +2 -1
  56. package/dist/entities/template.d.ts +11 -0
  57. package/dist/entities/template.js +12 -0
  58. package/dist/errors/reasons.js +13 -0
  59. package/dist/meetings/mcp/index.d.ts +15 -15
  60. package/dist/services/metadata.d.ts +1 -1
  61. package/dist/store/exports.d.ts +2 -0
  62. package/dist/store/exports.js +2 -0
  63. package/dist/store/index.d.ts +4 -2
  64. package/dist/store/index.js +1 -0
  65. package/dist/store/people.d.ts +7 -0
  66. package/dist/store/people.js +4 -0
  67. package/dist/store/source-review.d.ts +21 -0
  68. package/dist/store/sqlite/accounts.d.ts +3 -1
  69. package/dist/store/sqlite/accounts.js +10 -3
  70. package/dist/store/sqlite/added-sources.d.ts +16 -0
  71. package/dist/store/sqlite/added-sources.js +22 -0
  72. package/dist/store/sqlite/facts.js +3 -2
  73. package/dist/store/sqlite/imported-documents.js +3 -2
  74. package/dist/store/sqlite/knowledge.js +6 -4
  75. package/dist/store/sqlite/manifest.js +1 -0
  76. package/dist/store/sqlite/memories.js +5 -4
  77. package/dist/store/sqlite/mention-drain.js +9 -1
  78. package/dist/store/sqlite/merged-persons.d.ts +24 -0
  79. package/dist/store/sqlite/merged-persons.js +59 -0
  80. package/dist/store/sqlite/migrations.generated.js +8 -0
  81. package/dist/store/sqlite/notes.js +5 -4
  82. package/dist/store/sqlite/person-links.d.ts +10 -1
  83. package/dist/store/sqlite/person-links.js +14 -6
  84. package/dist/store/sqlite/person-merges.d.ts +39 -0
  85. package/dist/store/sqlite/person-merges.js +136 -0
  86. package/dist/store/sqlite/person-preparation.js +11 -8
  87. package/dist/store/sqlite/person-resolution.js +2 -1
  88. package/dist/store/sqlite/person-scope.js +2 -1
  89. package/dist/store/sqlite/relation-list.js +3 -2
  90. package/dist/store/sqlite/reported-relations.js +6 -3
  91. package/dist/store/sqlite/schema/templates.d.ts +242 -0
  92. package/dist/store/sqlite/schema/templates.js +23 -0
  93. package/dist/store/sqlite/schema.d.ts +1 -0
  94. package/dist/store/sqlite/schema.js +1 -0
  95. package/dist/store/sqlite/source-review.d.ts +20 -1
  96. package/dist/store/sqlite/source-review.js +74 -3
  97. package/dist/store/sqlite/task-board.d.ts +6 -1
  98. package/dist/store/sqlite/task-board.js +22 -4
  99. package/dist/store/sqlite/templates.d.ts +38 -0
  100. package/dist/store/sqlite/templates.js +69 -0
  101. package/dist/store/sqlite/work-tasks.js +8 -9
  102. package/dist/store/store.d.ts +3 -0
  103. package/dist/store/store.js +5 -0
  104. package/dist/store/types.d.ts +2 -0
  105. package/package.json +4 -4
  106. package/parity.json +19 -0
package/CHANGELOG.md CHANGED
@@ -5,10 +5,109 @@ 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.616.0 — 08.11.2026
9
+
10
+ ### Added
11
+
12
+ - **The weekly gaps message (`report/weekly-gaps`).** A morning digest may keep what it found on its own, which the
13
+ agenda did not show, in `internal.gaps` (`{ what, refs | ref, section }`); the digest never shows it. Once a week a
14
+ delivered digest run also sends those gaps along the same routes as one message: on Monday, or on the first digest
15
+ of a week whose Monday run did not send them, and never before a schedule's first Monday. It reads the run files
16
+ of the last 7 days, says a gap that several runs found once (the same ref, or the same words but for case and
17
+ punctuation) with how many digests found it, the most frequent first, and sends nothing for a week without gaps.
18
+ No agent runs for it. When it went, how many gaps and the deliveries are in the schedule's `weekly-gaps.json`.
19
+ - **A failed scheduled run sends a rendered notice (`notice/schedule-failed`).** In place of the one English line,
20
+ every route of a schedule that notifies on failures gets which schedule failed, since when and how many runs in a
21
+ row, the cause in the owner's language (keyring locked, sign-in needed, service unreachable, service error,
22
+ settings, stopped, crashed: from the error code, never its message) and one "fix" link to the tool's sync screen
23
+ (`sync/<tool>`). A notice whose templates fail sends the old line. The desktop notice is unchanged.
24
+ - Default templates for both, for Telegram, email and text in Russian and English, with the digest's escaping and
25
+ platform rules; `templates edit | preview` now take both keys, checked against their own synthetic samples.
26
+ - **A source check names what changed, and a source review's text can be read.** `knowledge.checkSources` also
27
+ answers `changedRefs`: the sources found changed in that run, whether they raised a review or still said the
28
+ quoted words, that no open `evidence_findings` batch cites, leaving out deleted sources and cited memories or facts.
29
+ An agent reads those again for new facts. `knowledge.sourceReviewTexts(id)` gives each source of a
30
+ `memory_source_review` with its quote, its text as cited (notes, documents and messages keep history) and its text
31
+ now, so a reader compares them while the review itself holds no source text. The shared `memory` and `fact`
32
+ entities take an optional `source_review: { id, cause } | null`, the marker reads already carry.
33
+ `knowledge.changedSources({ since })` reads the cited sources a check found changed since then and that differ
34
+ from the version cited, with the same exclusions, so a change the timer's check already took still reaches an
35
+ agent.
36
+ - **`store.notes.addedSource(ref)` reads an added source back with what it is and what was kept**: `kind`, the `url`
37
+ as given, `fileName`, `mime`, `size`, `kept` and the `copy` path, beside its document; `undefined` for any other
38
+ document or a removed source. The `AddedSourceDetails` type is exported.
39
+ - **`people.merges(uid)`, `people.undoMerge(to, from, by)` and `people.split(uid, identities, by)`.** `merges` lists
40
+ the people merged into a person, each with the identities from it that are still there, the method, who and when,
41
+ under an id `merge:<to>-<from>` (`parseMergeId` reads it back). `undoMerge` moves those identities back to the old
42
+ person, whose uid stays the same, and leaves any the owner split or unlinked off since; a chain of merges undoes
43
+ newest first. `split` moves the chosen identities to one new person. Both are the owner's only
44
+ (`identity.owner-only`; pass `"owner"` only from a path that established the owner ran it), and an automatic match
45
+ by the same address does not join those people again. `undoMerge` refuses with `identity.stale` when one of the
46
+ identities was merged on into another person since.
47
+ - **The digest says how many open tasks have no due date.** A report may give `tasks.undated` (a whole number; absent
48
+ is 0), and the section with the task group links gets one line after them, "без срока: 91 · открыть" or "no due
49
+ date: 91 · open", in every channel's Russian and English template, linking `tasks/undated`. The line is left out
50
+ when the count is 0. The v1 link grammar takes `tasks/undated` beside `overdue`, `today`, `tomorrow` and
51
+ `new/<since>`; the bounce page and WireCat Desktop need it too before such a link opens there.
52
+
53
+ ### Changed — may break callers
54
+
55
+ - **`templates` takes the language as `--locale <code>`, not `--language <code>`, and its words come from the shared
56
+ vocabulary.** `--language` is the query language in every other command (`<lucene|legacy>`); the template's
57
+ language keeps its field name, `language`. `--file <file>` names the file as the vocabulary does, `templates list
58
+ [query...]` narrows by `key`, `channel`, `language` and `source` (`templates list channel:telegram source:stored`)
59
+ and answers the `template` entity, every command has a short summary, and `<tool> commands` lists the group under
60
+ Automate, not Other. The shared commands' lint now covers the group, so `cli-dev lint` passes on a tool that mounts
61
+ it with cli-base 0.89.0 (`preview`, `--locale`, `--undo`, `--channel <channel>`).
62
+ - **`people.personByUid` of a person merged into someone else answers with that person.** Its `uid` is the
63
+ current person's, not the one asked for, and `mergedInto` is set; `personSeenInAccounts` follows the same merge.
64
+ A caller that compares the answer's `uid` with the one it passed reads `mergedInto` instead.
65
+ - **`unlinkIdentity` records its move with method `unlink`, whatever method the caller passes,** so a separation is
66
+ never listed as a merge.
67
+
68
+ ### Fixed
69
+
70
+ - **One notification per digest while WireCat Desktop runs.** Desktop announces a new morning digest itself, so a
71
+ finished run showed two system notices. A schedule's run now leaves its own success notice out when
72
+ `<state>/schedules/desktop.json` names a live pid and lists the schedule in `announces` (Desktop writes it while it
73
+ runs, wirecat-desktop#214). A marker whose pid is gone counts for nothing; failure notices and deliveries do not
74
+ change.
75
+ - **A mail-gated agent no longer runs again on the input its last run ended on.** One refusal the agent could not
76
+ get past (a findings key already taken) turned into a paid run every 5 minutes until the day's cost cap. The
77
+ timer (`schedule exec`) now keeps the SHA-256 of a `--on-new-mail` agent's input in `last.json` (`inputHash`);
78
+ when the next input is the same and that run exited 0, its mark did not move, so the run is left out with
79
+ `skipped.reason` `mail.same-input` (`SKIP_REASONS.mailSameInput`). New mail changes the input and runs normally;
80
+ `schedule run` by hand always runs. `runSchedule(…, { skipRepeatedInput: true })` turns it on for another timer.
81
+ - **A person shows once after a merge.** The person a merge emptied stayed in `taskPeople`, so memo's `people list`
82
+ and `search people` showed the same person two or three times. It is skipped now and its tasks count for the person
83
+ it was merged into. Rows that name the old uid keep it, so undoing loses nothing, and the filters by a person read
84
+ them with the current person: memories, facts, notes, documents' `person:`, relationships, the task board's
85
+ `assignee:` and preparation, and assigning the old uid to a task the current person holds is a no-op.
86
+ A source's sync that reports a relationship on the current person withdraws what it reported on the old one, so
87
+ the relationship shows once.
88
+
89
+ - **`account remove` is in the messenger parity manifest** (`parity.json`), with `--keep-data`, `--delete-data`
90
+ and `--dry-run`, so tg, max and wa can adopt it without failing `parity:check`.
91
+
8
92
  ## 0.614.0 — 08.11.2026
9
93
 
10
94
  ### Added
11
95
 
96
+ - **The owner's own message templates, in the shared store (store version 59).** `templatesCommand(app, { env,
97
+ output, diagnostic })` gives a tool `templates list | show | edit | preview | reset <key> --channel
98
+ telegram|email|text [--language <code>]`. Keys: `report/morning-digest`; `report/weekly-gaps` and
99
+ `notice/schedule-failed` are listed, but nothing renders them yet, so they cannot be edited. `edit` opens
100
+ `$VISUAL`/`$EDITOR` on the template that applies, or takes `--file`; a save is checked first against a synthetic
101
+ report and the tool's last real `<run>.report.json`: it must render, the channel's rules may remove nothing (a tag
102
+ outside the list, an `href` that is not a link of the report, a `style` with `url(`), and a Telegram text must fit
103
+ 4 096 characters once the size fit dropped what it could. A failed check saves nothing and says why, and keeps an
104
+ editor draft for `--file`. Every save and reset keeps the replaced body in `templates_history`; `edit --undo` puts
105
+ back the last one. `reset` deletes the row, so the shipped template applies again. `edit` and `reset` change what
106
+ later runs send (`grantsAuthority`), and an agent is refused (`template.owner-only`). A scheduled report renders
107
+ with the stored templates of the owner's language; a stored body that fails, or a store that cannot be read,
108
+ falls back to the shipped template for that channel and records `report.template-failed`. The email template is
109
+ stored and previewed, but mail still sends the plain-text rendering. `store.templates` and
110
+ `storedTemplateBodies(database, key, language)` from `@wirecat/cli-core/store`.
12
111
  - **`account remove`, built once for every tool.** `<tool> <profile> account remove --keep-data|--delete-data` signs
13
112
  the profile out with the tool's own `signOut` hook, then forgets it here: its keyring entries, its
14
113
  `state/accounts/<profile>.json`, the tool's own state files and its sections in the config file; other profiles stay.
@@ -25,6 +124,12 @@ shape of this file.
25
124
  outside its cli-core folders names them with the `ownFolders` hook; each must be absolute and inside the home folder
26
125
  (`account-remove.folder-outside`).
27
126
 
127
+ ### Fixed
128
+
129
+ - **cli-core accepts any `@wirecat/cli-base` 0.x from 0.80.7 (`>=0.80.7 <1.0.0`).** Its peer range stopped at
130
+ `<0.86.0`, so a CLI could not take cli-base 0.86.0 or 0.87.0 beside it. The range is pinned again at 1.0. Nothing
131
+ else changes for a caller.
132
+
28
133
  ## 0.612.0 — 08.11.2026
29
134
 
30
135
  ### Changed — may break callers
@@ -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,7 +1,10 @@
1
1
  import { type LinkConfig } from "../../domain/links.js";
2
+ import type { GapsView, MessageKind, NoticeView } from "./messages.js";
2
3
  import { type ReportView } from "./view.js";
3
4
  export declare const REPORT_CHANNELS: readonly ["telegram", "email", "text"];
4
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;
5
8
  export declare const REPORT_REASONS: {
6
9
  readonly invalid: "delivery.report-invalid";
7
10
  readonly templateFailed: "report.template-failed";
@@ -11,12 +14,13 @@ export declare const REPORT_REASONS: {
11
14
  export declare const defaultTemplate: (kind: string, channel: ReportChannel, language: string) => string;
12
15
  /**
13
16
  * What a template's HTML may keep, enforced after it rendered: the channel's tags and attributes only, a `style`
14
- * with no `url(`, and an `href` only to a URL of the view model. Anything else goes, its text kept; `changed` counts
15
- * what went.
17
+ * with no `url(`, and an `href` only to a URL of the view model. Anything else goes, its text kept; `removed` names
18
+ * what went, once per occurrence, and `changed` counts it.
16
19
  */
17
20
  export declare const sanitizeHtml: (channel: Exclude<ReportChannel, "text">, html: string, urls: ReadonlySet<string>) => {
18
21
  html: string;
19
22
  changed: number;
23
+ removed: string[];
20
24
  };
21
25
  export interface Rendering {
22
26
  text: string;
@@ -29,9 +33,20 @@ export interface Rendering {
29
33
  * One channel's text of a report. A failing `template` (a stored override, later) falls back to the shipped one for
30
34
  * this channel only. Telegram is rendered again with an item fewer, from the largest section, until it fits.
31
35
  */
32
- export declare const renderReport: (view: ReportView, channel: ReportChannel, { template }?: {
36
+ export declare const renderReport: (view: MessageView, channel: ReportChannel, { template }?: {
33
37
  template?: string;
34
38
  }) => Promise<Rendering>;
39
+ /**
40
+ * Why `source` may not be saved for this view, empty when it may, and what it renders: it must render, the platform
41
+ * rules may take nothing out, and a Telegram text must fit once the size fit dropped what it could. Unlike
42
+ * `renderReport` it never falls back to the shipped template.
43
+ */
44
+ export declare const checkTemplate: (view: MessageView, channel: ReportChannel, source: string) => Promise<{
45
+ problems: string[];
46
+ text: string;
47
+ }>;
48
+ /** The owner's stored templates of one report kind and language, by channel; a missing channel uses the shipped one. */
49
+ export type StoredTemplates = (kind: MessageKind, language: string) => Promise<Partial<Record<ReportChannel, string>>>;
35
50
  /** What `last.json` keeps of a report run, beside the deliveries. */
36
51
  export interface ReportRun {
37
52
  language: string;
@@ -59,12 +74,33 @@ export interface PreparedReport {
59
74
  * A run's answer rendered for every route, or `undefined` when it is not a report. An invalid report becomes one
60
75
  * line in the owner's language and is never shown raw.
61
76
  */
62
- export declare const prepareReport: (answer: string, { language, now, timeZone, templates, links, env, }: {
77
+ export declare const prepareReport: (answer: string, { language, now, timeZone, templates: storedTemplates, links, env, }: {
63
78
  language: string;
64
79
  now: number;
65
80
  timeZone?: string;
66
- templates?: Partial<Record<ReportChannel, string>>;
81
+ /** A lookup that fails delivers with the shipped templates and records `report.template-failed`. */
82
+ templates?: StoredTemplates;
67
83
  links?: LinkConfig;
68
84
  /** Read for `WIRECAT_LINKS=off`. */
69
85
  env?: NodeJS.ProcessEnv;
70
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>;