@wirecat/cli-core 0.616.0 → 0.618.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 (57) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/background/backfill.d.ts +21 -0
  3. package/dist/background/backfill.js +41 -0
  4. package/dist/background/report/messages.js +4 -1
  5. package/dist/background/report/view.js +4 -1
  6. package/dist/background/schedules.d.ts +17 -0
  7. package/dist/background/schedules.js +21 -8
  8. package/dist/cli/context.d.ts +5 -0
  9. package/dist/cli/index.d.ts +3 -2
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/messenger/serve-command.js +24 -2
  12. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  13. package/dist/cli/messenger/serve-outdated.js +100 -0
  14. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  15. package/dist/cli/schedule/schedule-command.js +13 -0
  16. package/dist/cli/store-recover.js +26 -2
  17. package/dist/domain/links.d.ts +17 -4
  18. package/dist/domain/links.js +20 -7
  19. package/dist/domain/models.d.ts +6 -0
  20. package/dist/domain/relations.d.ts +15 -0
  21. package/dist/domain/relations.js +23 -0
  22. package/dist/errors/reasons.js +7 -0
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +2 -2
  25. package/dist/meetings/mcp/index.d.ts +15 -15
  26. package/dist/services/link-scorers/chat-senders.js +39 -29
  27. package/dist/services/link-scorers/member-chats.js +4 -3
  28. package/dist/services/link-scorers/member-dialog.js +5 -7
  29. package/dist/services/link-scorers/scan.js +17 -8
  30. package/dist/services/link-scorers/shared.d.ts +6 -2
  31. package/dist/services/link-scorers/shared.js +6 -2
  32. package/dist/services/link-scorers/types.d.ts +2 -0
  33. package/dist/store/migrations.d.ts +1 -1
  34. package/dist/store/migrations.js +35 -12
  35. package/dist/store/recover.d.ts +34 -0
  36. package/dist/store/recover.js +188 -6
  37. package/dist/store/refill.d.ts +28 -0
  38. package/dist/store/refill.js +120 -0
  39. package/dist/store/sqlite/bot-tokens.d.ts +11 -0
  40. package/dist/store/sqlite/bot-tokens.js +57 -0
  41. package/dist/store/sqlite/chats.js +2 -0
  42. package/dist/store/sqlite/clients.d.ts +7 -3
  43. package/dist/store/sqlite/clients.js +11 -7
  44. package/dist/store/sqlite/email-index.js +9 -11
  45. package/dist/store/sqlite/knowledge.js +3 -1
  46. package/dist/store/sqlite/messages.d.ts +1 -1
  47. package/dist/store/sqlite/messages.js +3 -1
  48. package/dist/store/sqlite/note-index.js +9 -7
  49. package/dist/store/sqlite/notes.d.ts +1 -1
  50. package/dist/store/sqlite/notes.js +8 -6
  51. package/dist/store/sqlite/open-store.js +2 -0
  52. package/dist/store/sqlite/relation-list.js +2 -0
  53. package/dist/store/sqlite/relation-proposals.d.ts +12 -1
  54. package/dist/store/sqlite/relation-proposals.js +50 -11
  55. package/dist/store/sqlite/transaction.d.ts +13 -0
  56. package/dist/store/sqlite/transaction.js +25 -17
  57. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,90 @@ 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.618.0 — 09.11.2026
11
+
12
+ ### Added
13
+
14
+ - **Links open a person and a project.** The v1 link grammar takes `person/<id>` and `project/<key>`
15
+ (`https://wirecat.dev/o#/v1/person/77`, `wirecat://open/v1/project/ACME%20site`), and `linkFor` builds them from a
16
+ report item's `person:<id>` and `project:<key>` refs; a project key is one encoded part. An item still opens where
17
+ it happened first: a person or a project ref gives its one link only when no other ref does
18
+ (`refsForLink(refs)`, exported). `test/fixtures/links-v1.json` has the new cases; the bounce page and WireCat
19
+ Desktop need them too before such a link opens there.
20
+ - **An agent schedule's run for a past day (`backfillSchedule`, `backfillScheduleRun`).** It runs the schedule's
21
+ agent as its timer does, with the same harness, flags, per-run cap and an input of the host's, and keeps the run in
22
+ `runs/` under the time it is given (`2026-11-05T07-30-00Z.md`, `.log`, `.jsonl`), with `"backfill": true` in its
23
+ `.report.json`; the report is rendered as of that time. It sends nothing, shows no notice, and leaves `last.json`,
24
+ `latest.md` and `latest.txt` as they are; its cost counts in today's `spend.json`. The count of runs a schedule keeps
25
+ (30) no longer removes a backfilled run, which is older than the runs around it. `readSchedule`, `scheduleFile`,
26
+ `spentToday` and `SCHEDULE_DEFAULTS` are exported from `@wirecat/cli-core/cli` for a host's own checks.
27
+ - **A person's engagement on a project.** `engagement` on a person's `member-of` a project: `none`, `low`,
28
+ `medium` or `high`, how much the owner deals with that person himself, not how active the person is; absent means
29
+ unknown. `relate` and `updateRelation` take it (`null` clears it), an agent's change is a `relationship_update`
30
+ proposal as for a role, and every relationship read carries it. It is refused on any other relationship
31
+ (`relationship.engagement-ends`). `byEngagement` and `engagementRank` order links high, medium, unknown, low,
32
+ none; `ENGAGEMENT_LEVELS` lists the levels.
33
+ - **A role note beside the role.** `roleNote`, up to 200 characters, says what the role means on this link in the
34
+ owner's words, while the role itself stays one of its list. `relate` and `updateRelation` take it; `null` clears it.
35
+
36
+ ### Fixed
37
+
38
+ - **`store recover run` no longer says nothing was lost when it cannot know.** Before the copy it compares
39
+ each plain index of the damaged file with its table: entries the table no longer holds are rows a stale page cut
40
+ off, reported per table in `lost` as `gone_at_least` with the index in `seen_in`. Rows lost from a table and its
41
+ indexes alike leave no trace, so the notes never say "no table lost a row": they give the lower bound, or say the
42
+ loss is unknown, with the last deep check that passed (`last_known_good`). On six stores the cli-testing integrity
43
+ harness broke, it says at least 50, 200, 50 and 265 messages are gone where 50, 241, 50 and 291 are, and "unknown"
44
+ on the two stores whose lost rows never reached the file.
45
+ - **`store recover run` keeps rows that `.recover` found on pages no table claims.** It dropped them with the rest of
46
+ its lost-and-found table; each one now goes back into the one data table whose columns its values fit (`placed`,
47
+ per table), and only the rest are dropped. 9 committed messages came back on one R1 store.
48
+ - **After `store recover run`, the next ordinary sync fetches again what the damage may have taken.** A messenger
49
+ sync jumps over every stretch the store marks as fetched, so a hole inside one stayed for good. The recovery now
50
+ forgets what was fetched from a day before the last deep check that passed (all of it when none is on record): each
51
+ chat's held stretches end at its last message sent before then, and each mail folder keeps as listed only the UIDs
52
+ up to its last email from before then. `refetch` in the answer says how many chats and mail folders per account,
53
+ and the notes say what cannot come back: what only the store held, and WhatsApp history the phone does not push
54
+ again. Nothing on any service is asked or changed by the recovery. On the T1-roles store the cli-testing harness
55
+ broke with a hole of 291 messages inside a chat, one ordinary sync brought all of them back; without this, 200
56
+ were still missing after 25 syncs.
57
+ - **A `serve` no longer runs on after the store or the installed package moved past it.** Every minute it
58
+ checks whether the store's format is one its build can no longer write, or whether a newer version of its own
59
+ package is installed on disk; then it logs one error, `serve.outdated`, and exits 3, which its unit
60
+ (`Restart=on-failure`) answers by starting the installed build. A wa serve had stored nothing for a day on 0.30.0
61
+ after 0.33.0 moved the store to format 57. `outdatedReason`, `watchOutdated` and `ownPackageRoot` from
62
+ `@wirecat/cli-core/cli`, for a CLI with a serve of its own.
63
+ - **Busy sync runs no longer fail with "database is locked".** Each writable open read the schema version under the
64
+ write lock, without the retry other writes use, so with several tools syncing at once it gave up after 5 s. A
65
+ current store is now checked without the lock, and a migration takes it with the retry. Listing mail pieces to
66
+ embed (`mail.chunksToEmbed`, and mail search) wrote its queue bookkeeping outside a transaction; it now reads
67
+ first and writes through the store's transaction only when there is work. A write that had to wait for the lock
68
+ leaves it free for 2 ms after it commits, so a waiter gets in between one process's back-to-back writes.
69
+ - **The real error of a failed write is shown.** When SQLite had already rolled a transaction back itself (an I/O
70
+ error, a full disk), the store's own rollback failed with "cannot rollback - no transaction is active", and that
71
+ message replaced the real one.
72
+ - **`relationships scan` reads each chat once, however many times it spreads.** Each of its up to 4 passes read every
73
+ chat found so far again (up to 2 000 messages each) and looked up every sender's person again, so a project with
74
+ confirmed links took about three times longer than one without: 4.9–5.8 s against 1.6–1.9 s on a synthetic store
75
+ of 2 600 chats. A scan now keeps what it read until it ends: 0.6–0.8 s on the same store, with the same proposals.
76
+
77
+ ## 0.617.0 — 08.11.2026
78
+
79
+ ### Security
80
+
81
+ - **Messenger bot tokens are masked in the store.** A Telegram bot token (`<bot id>:<secret>`, as BotFather sends
82
+ 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
83
+ hidden>`, before the search copy and the vectors are made, for every messenger. Messages already stored, and those
84
+ an older build saves later, are masked the next time a store is opened for writing, from the newest message checked
85
+ last time (`store_settings.bot_tokens_masked_through`): the text, the search copy, the quote and the edit history,
86
+ and the vectors of the conversation pieces they were in are dropped, to be made again. No store version.
87
+ - **`Chat.searchable: false`**: a messenger saves a chat whose messages hold credentials as not searchable. Search
88
+ over all chats, search by meaning and context evidence leave it out (as for any chat with `chats.searchable = 0`);
89
+ a read that names the chat still sees it. A later save without the
90
+ field keeps the mark, and nothing a messenger saves unhides a chat.
91
+
8
92
  ## 0.616.0 — 08.11.2026
9
93
 
10
94
  ### Added
@@ -0,0 +1,21 @@
1
+ import type { AppIdentity } from "../ports/app.js";
2
+ import { type StoredTemplates } from "./report/render.js";
3
+ import { type AgentCli, type LastRun } from "./schedules.js";
4
+ import type { ServerSystem } from "./system.js";
5
+ /**
6
+ * One past day's run of an agent schedule, as its timer would have made it at `at`: the same harness, flags, per-run
7
+ * cap and input, the report rendered as of `at` and kept in `runs/` under that time, with `"backfill": true` in its
8
+ * `.report.json`. It sends nothing, shows no notice, and leaves `last.json` and `latest.*` as they are; its cost counts
9
+ * in today's spend, as any run's does.
10
+ */
11
+ export declare const backfillSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { at, input, now, signal, killAfterMs, agentRuns, ownerLanguage, reportTemplates, }: {
12
+ at: Date;
13
+ /** What the agent reads on its stdin before its first turn: here, which day it writes and the window it reads. */
14
+ input?: string;
15
+ now?: () => Date;
16
+ signal?: AbortSignal;
17
+ killAfterMs?: number;
18
+ agentRuns?: readonly AgentCli[];
19
+ ownerLanguage?: (env: NodeJS.ProcessEnv) => Promise<string>;
20
+ reportTemplates?: (env: NodeJS.ProcessEnv) => StoredTemplates;
21
+ }) => Promise<LastRun>;
@@ -0,0 +1,41 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CliError } from "@wirecat/cli-base";
4
+ import { prepareReport } from "./report/render.js";
5
+ import { attemptSchedule, KILL_AFTER_MS, readSchedule, sharedLinks } from "./schedules.js";
6
+ /**
7
+ * One past day's run of an agent schedule, as its timer would have made it at `at`: the same harness, flags, per-run
8
+ * cap and input, the report rendered as of `at` and kept in `runs/` under that time, with `"backfill": true` in its
9
+ * `.report.json`. It sends nothing, shows no notice, and leaves `last.json` and `latest.*` as they are; its cost counts
10
+ * in today's spend, as any run's does.
11
+ */
12
+ export const backfillSchedule = async (app, system, env, file, { at, input, now = () => new Date(), signal, killAfterMs = KILL_AFTER_MS, agentRuns = [], ownerLanguage = async () => "ru", reportTemplates, }) => {
13
+ const schedule = readSchedule(file);
14
+ if (schedule.kind !== "agent")
15
+ throw new CliError("validation_error", `${schedule.name} runs a command, not an agent; only an agent's report is built for a past day`);
16
+ const folder = join(file, "..");
17
+ mkdirSync(join(folder, "runs"), { recursive: true, mode: 0o700 });
18
+ const last = (await attemptSchedule(app, system, env, schedule, folder, {
19
+ now,
20
+ signal,
21
+ killAfterMs,
22
+ agentRuns,
23
+ agentInput: input === undefined ? undefined : async () => input,
24
+ at,
25
+ }));
26
+ if (last.exitCode !== 0)
27
+ return last;
28
+ const runEnv = { ...env, ...schedule.environment };
29
+ const prepared = await prepareReport(readFileSync(last.output, "utf8"), {
30
+ language: await ownerLanguage(runEnv).catch(() => "ru"),
31
+ now: at.getTime(),
32
+ links: sharedLinks(runEnv),
33
+ env: runEnv,
34
+ ...(reportTemplates ? { templates: reportTemplates(runEnv) } : {}),
35
+ });
36
+ if (!prepared)
37
+ return last;
38
+ if (prepared.document)
39
+ writeFileSync(last.output.replace(/\.md$/, ".report.json"), `${JSON.stringify({ ...JSON.parse(prepared.document), backfill: true }, null, 2)}\n`, { mode: 0o600 });
40
+ return { ...last, report: prepared.run };
41
+ };
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { refsForLink } from "../../domain/links.js";
3
4
  import { jsonOfAnswer, REPORT_FORMAT, withoutLeaks } from "./schema.js";
4
5
  import { momentFor } from "./view.js";
5
6
  const WHAT_LIMIT = 160;
@@ -188,7 +189,9 @@ const LINK_WORDS = {
188
189
  };
189
190
  const wordsOf = (language) => LINK_WORDS[language] ?? LINK_WORDS.en;
190
191
  const linkOfRefs = (refs, linkOf, label) => {
191
- const url = refs.map(linkOf).find((one) => one !== null);
192
+ const url = refsForLink(refs)
193
+ .map(linkOf)
194
+ .find((one) => one !== null);
192
195
  return url ? [{ kind: "open", url, label }] : [];
193
196
  };
194
197
  export const GAPS_CAP = 15;
@@ -1,3 +1,4 @@
1
+ import { refsForLink } from "../../domain/links.js";
1
2
  const LINK_WORDS = {
2
3
  ru: { open: "открыть", fix: "исправить" },
3
4
  en: { open: "open", fix: "fix" },
@@ -126,7 +127,9 @@ export const reportView = (report, { language, now, timeZone, linkOf = () => nul
126
127
  const moment = (iso) => (iso === null ? null : momentFor(iso, now, language, timeZone));
127
128
  const words = LINK_WORDS[language] ?? LINK_WORDS.en;
128
129
  const linksOf = (refs, label) => {
129
- const url = refs.map(linkOf).find((one) => one !== null);
130
+ const url = refsForLink(refs)
131
+ .map(linkOf)
132
+ .find((one) => one !== null);
130
133
  return url ? [{ kind: "open", url, label }] : [];
131
134
  };
132
135
  const itemOf = (item) => {
@@ -161,10 +161,14 @@ export declare const launchdTimer: (app: AppIdentity, system: ServerSystem, env:
161
161
  */
162
162
  export declare const windowsTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv) => Timer;
163
163
  export declare const timerFor: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv) => Timer;
164
+ /** The shared `links` settings; a config file that cannot be read keeps the default rather than stop a digest. */
165
+ export declare const sharedLinks: (env: NodeJS.ProcessEnv) => import("../domain/links.js").LinkConfig;
164
166
  /** A desktop notification; a machine without one loses only the notice, never the run. */
165
167
  export declare const notify: (system: ServerSystem, env: NodeJS.ProcessEnv, title: string, body: string) => Promise<boolean>;
166
168
  /** Finds a program on PATH, as the timer will not have the shell's PATH to find it by. */
167
169
  export declare const findProgram: (name: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => string | undefined;
170
+ /** How long a stopped child has to save and answer after SIGTERM before it is killed. */
171
+ export declare const KILL_AFTER_MS = 10000;
168
172
  /**
169
173
  * The reason tg and max give when a profile that has logged in here cannot read its sign-in: the keyring is
170
174
  * locked or out of reach, which a later try fixes and a new login does not.
@@ -199,3 +203,16 @@ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env:
199
203
  */
200
204
  skipRepeatedInput?: boolean;
201
205
  }) => Promise<LastRun>;
206
+ /** One run of the schedule's command or agent: its output in `runs/`, its result in `last.json`. */
207
+ export declare const attemptSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, schedule: Schedule, folder: string, { now, signal, killAfterMs, agentRuns, agentInput, skipRepeatedInput, at, }: {
208
+ now: () => Date;
209
+ signal: AbortSignal | undefined;
210
+ killAfterMs: number;
211
+ agentRuns: readonly AgentCli[];
212
+ agentInput: AgentInput | undefined;
213
+ skipRepeatedInput?: boolean;
214
+ /** A backfill's run time: the files are named for it, and `last.json` is left as it is. */
215
+ at?: Date;
216
+ }) => Promise<LastRun | {
217
+ repeated: LastRun;
218
+ }>;
@@ -349,7 +349,7 @@ export const timerFor = (app, system, env) => {
349
349
  throw new CliError("validation_error", `${app.command} schedule knows Linux, macOS and Windows, not ${system.platform}`);
350
350
  };
351
351
  /** The shared `links` settings; a config file that cannot be read keeps the default rather than stop a digest. */
352
- const sharedLinks = (env) => {
352
+ export const sharedLinks = (env) => {
353
353
  try {
354
354
  return linkConfigOf(readSharedSection(sharedConfigPath(storePath(env), env), "links"));
355
355
  }
@@ -432,7 +432,7 @@ export const findProgram = (name, env, platform) => {
432
432
  };
433
433
  const KEEP_RUNS = 30;
434
434
  /** How long a stopped child has to save and answer after SIGTERM before it is killed. */
435
- const KILL_AFTER_MS = 10_000;
435
+ export const KILL_AFTER_MS = 10_000;
436
436
  /**
437
437
  * The reason tg and max give when a profile that has logged in here cannot read its sign-in: the keyring is
438
438
  * locked or out of reach, which a later try fixes and a new login does not.
@@ -523,7 +523,9 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
523
523
  else if (agent && exitCode === 0)
524
524
  rmSync(latestText, { force: true });
525
525
  const stampOf = (file) => file.split(".")[0] ?? file;
526
- const kept = new Set([...new Set(readdirSync(runs).map(stampOf))].sort().slice(-KEEP_RUNS));
526
+ const stamps = [...new Set(readdirSync(runs).map(stampOf))].sort();
527
+ const old = new Set(stamps.filter((stamp) => backfilled(runs, stamp)));
528
+ const kept = new Set([...stamps.filter((stamp) => !old.has(stamp)).slice(-KEEP_RUNS), ...old]);
527
529
  for (const file of readdirSync(runs))
528
530
  if (!kept.has(stampOf(file)))
529
531
  rmSync(join(runs, file), { force: true });
@@ -650,9 +652,9 @@ const inputOf = async (agentInput, system, env, schedule, log) => {
650
652
  }
651
653
  };
652
654
  /** One run of the schedule's command or agent: its output in `runs/`, its result in `last.json`. */
653
- const attemptSchedule = async (app, system, env, schedule, folder, { now, signal, killAfterMs, agentRuns, agentInput, skipRepeatedInput = false, }) => {
655
+ export const attemptSchedule = async (app, system, env, schedule, folder, { now, signal, killAfterMs, agentRuns, agentInput, skipRepeatedInput = false, at, }) => {
654
656
  const runs = join(folder, "runs");
655
- const stamp = now()
657
+ const stamp = (at ?? now())
656
658
  .toISOString()
657
659
  .replaceAll(":", "-")
658
660
  .replace(/\.\d+Z$/, "Z");
@@ -736,13 +738,24 @@ const attemptSchedule = async (app, system, env, schedule, folder, { now, signal
736
738
  durationMs: ended.getTime() - began,
737
739
  ...(costUsd === undefined ? {} : { costUsd }),
738
740
  });
739
- return recordRun(join(folder, "last.json"), {
740
- at: ended.toISOString(),
741
+ const run = {
742
+ at: (at ?? ended).toISOString(),
741
743
  exitCode,
742
744
  output,
743
745
  traceId: trace.traceId,
744
746
  ...(costUsd === undefined ? {} : { costUsd }),
745
747
  ...(inputHash === undefined ? {} : { inputHash }),
746
748
  ...(exitCode === 0 ? {} : failureOf(readFileSync(errors, "utf8"), exitCode)),
747
- });
749
+ };
750
+ return at ? run : recordRun(join(folder, "last.json"), run);
751
+ };
752
+ /** A backfilled run is older than the runs it joins, so the count that keeps the newest runs would remove it first. */
753
+ const backfilled = (runs, stamp) => {
754
+ const document = join(runs, `${stamp}.report.json`);
755
+ try {
756
+ return (existsSync(document) && JSON.parse(readFileSync(document, "utf8")).backfill === true);
757
+ }
758
+ catch {
759
+ return false;
760
+ }
748
761
  };
@@ -70,6 +70,11 @@ export interface BaseEnvironment {
70
70
  handled?: (event: MessageEvent) => void;
71
71
  /** A test's hook into `serve`: how long it waits after connecting before its catch-up pass. */
72
72
  startSyncDelayMs?: number;
73
+ /** A test's hook into `serve`: how often it checks for a newer store or install, and the package it checks. */
74
+ outdated?: {
75
+ everyMs?: number;
76
+ packageRoot?: string;
77
+ };
73
78
  /** Set by an MCP server on a command it runs for an agent (`runCommandForAgent`). */
74
79
  agent?: AgentRun;
75
80
  /** Set by `run()`: the words it was given, which a run keeps as `record_input` says (`maskArgv`). */
@@ -1,5 +1,5 @@
1
1
  export { AI_ENTRIES, AI_SETTING_KEYS, type AISettings, resolveAISettings } from "../analysis/settings.js";
2
- export { AGENT_INPUT_MAX_CHARS, type AgentCli, type AgentInput } from "../background/schedules.js";
2
+ export { AGENT_INPUT_MAX_CHARS, type AgentCli, type AgentInput, readSchedule, SCHEDULE_DEFAULTS, scheduleFile, spentToday, } from "../background/schedules.js";
3
3
  export { parseDuration } from "../domain/duration.js";
4
4
  export { openOf, PROFILE_PLACEHOLDER, type ProfilesFor, type RefOpen, type RefSummary, refLabel, } from "../domain/ref-summaries.js";
5
5
  export { botTemplate } from "../entities/list-results.js";
@@ -112,6 +112,7 @@ export { allAnswer, allHitItem, coverageGaps, type HitItem, type MessageHitItem,
112
112
  export { SEARCHES_QUERY } from "./messenger/searches-command.js";
113
113
  export { servingProfiles } from "./messenger/serve-command.js";
114
114
  export { DAY_MS, FIRST_FETCH_MS, type MemberFetches, memberFetches } from "./messenger/serve-members.js";
115
+ export { OUTDATED_CHECK_MS, outdatedReason, ownPackageRoot, watchOutdated } from "./messenger/serve-outdated.js";
115
116
  export { STEMS_EVERY_MS, STEMS_SLICE_MS, type StemFills, stemFills } from "./messenger/serve-stems.js";
116
117
  export type { Running, ServerOptions, ServerProcess, ServerSystem } from "./messenger/server-command.js";
117
118
  export { storeSummary } from "./messenger/store-maintenance-command.js";
@@ -128,7 +129,7 @@ export { type ProjectTextHints, projectAnswerParts, projectCutoffTime, projectEv
128
129
  export { type ProjectStatusHints, type ProjectStatusItem, projectStatusAnswer, projectStatusRow, projectStatusSchema, projectStatusText, } from "./project-status.js";
129
130
  export { STATUS_ROWS, STATUS_SIGNAL_ROWS } from "./project-status-rows.js";
130
131
  export { fieldsOf, projectFields } from "./result-fields.js";
131
- export { SCHEDULE_SETTINGS, type ScheduleHost, type ScheduleLimits, scheduleLimitsOf, } from "./schedule/schedule-command.js";
132
+ export { backfillScheduleRun, SCHEDULE_SETTINGS, type ScheduleHost, type ScheduleLimits, scheduleLimitsOf, } from "./schedule/schedule-command.js";
132
133
  export { type DeclaredSetting, type SettingRow, settingRows, withSettingDefaults } from "./setting-defaults.js";
133
134
  export { type Config, type Configuration, count, first, flag, fromFile, type GlobalFlags, NONE_NAMED, namedProfile, type ProfileKind, plain, type ResolveOptions, type Settings, type SettingsExtension, type SettingsExtensionContext, type Source, settingsFor, } from "./settings.js";
134
135
  export { type PermissionAnswer, readSetupAnswers, type SetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { AI_ENTRIES, AI_SETTING_KEYS, resolveAISettings } from "../analysis/settings.js";
2
- export { AGENT_INPUT_MAX_CHARS } from "../background/schedules.js";
2
+ export { AGENT_INPUT_MAX_CHARS, readSchedule, SCHEDULE_DEFAULTS, scheduleFile, spentToday, } from "../background/schedules.js";
3
3
  export { parseDuration } from "../domain/duration.js";
4
4
  export { openOf, PROFILE_PLACEHOLDER, refLabel, } from "../domain/ref-summaries.js";
5
5
  export { botTemplate } from "../entities/list-results.js";
@@ -103,6 +103,7 @@ export { allAnswer, allHitItem, coverageGaps, messageHitItem, noteHitItem, shown
103
103
  export { SEARCHES_QUERY } from "./messenger/searches-command.js";
104
104
  export { servingProfiles } from "./messenger/serve-command.js";
105
105
  export { DAY_MS, FIRST_FETCH_MS, memberFetches } from "./messenger/serve-members.js";
106
+ export { OUTDATED_CHECK_MS, outdatedReason, ownPackageRoot, watchOutdated } from "./messenger/serve-outdated.js";
106
107
  export { STEMS_EVERY_MS, STEMS_SLICE_MS, stemFills } from "./messenger/serve-stems.js";
107
108
  export { storeSummary } from "./messenger/store-maintenance-command.js";
108
109
  export { stored } from "./messenger/stored.js";
@@ -118,7 +119,7 @@ export { projectAnswerParts, projectCutoffTime, projectEvidenceText, projectWind
118
119
  export { projectStatusAnswer, projectStatusRow, projectStatusSchema, projectStatusText, } from "./project-status.js";
119
120
  export { STATUS_ROWS, STATUS_SIGNAL_ROWS } from "./project-status-rows.js";
120
121
  export { fieldsOf, projectFields } from "./result-fields.js";
121
- export { SCHEDULE_SETTINGS, scheduleLimitsOf, } from "./schedule/schedule-command.js";
122
+ export { backfillScheduleRun, SCHEDULE_SETTINGS, scheduleLimitsOf, } from "./schedule/schedule-command.js";
122
123
  export { settingRows, withSettingDefaults } from "./setting-defaults.js";
123
124
  export { count, first, flag, fromFile, NONE_NAMED, namedProfile, plain, settingsFor, } from "./settings.js";
124
125
  export { readSetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
@@ -17,6 +17,7 @@ import { onlineDeps } from "../../services/deps.js";
17
17
  import { servicesFor } from "../../services/index.js";
18
18
  import { patiently } from "../../services/patience.js";
19
19
  import { applyTaskRulesOnArrival, openRequestTask } from "../../services/task-rules.js";
20
+ import { storePath } from "../../store/path.js";
20
21
  import { environmentOf } from "../context.js";
21
22
  import { REMOTE_WRITE } from "../effects.js";
22
23
  import { itemOf, renderAnswer } from "../envelope.js";
@@ -25,6 +26,7 @@ import { messengerContext } from "./context.js";
25
26
  import { START_SYNC_PER_CHAT, startSync } from "./serve-catch-up.js";
26
27
  import { memberFetches } from "./serve-members.js";
27
28
  import { noticeFor, recordDiagnostics } from "./serve-notice.js";
29
+ import { outdatedReason, ownPackageRoot, watchOutdated } from "./serve-outdated.js";
28
30
  import { serveRelay } from "./serve-relay.js";
29
31
  import { stemFills } from "./serve-stems.js";
30
32
  import { listenUntilStopped } from "./watch-command.js";
@@ -80,7 +82,7 @@ export const serveCommand = (messenger) => {
80
82
  const counts = {};
81
83
  const rules = replying(context, messenger, Date.parse(startedAt));
82
84
  const tasks = tasking(context, warn);
83
- const { handled, startSyncDelayMs } = environmentOf(this);
85
+ const { handled, startSyncDelayMs, outdated: outdatedHook } = environmentOf(this);
84
86
  const count = (event) => {
85
87
  counts[event.event] = (counts[event.event] ?? 0) + 1;
86
88
  if (event.event === "message") {
@@ -152,9 +154,25 @@ export const serveCommand = (messenger) => {
152
154
  withStore: (work) => context.withStore((store) => work(store), { name: "serve stems" }),
153
155
  warn,
154
156
  });
157
+ const listening = new AbortController();
158
+ let outdated;
159
+ const packageRoot = outdatedHook?.packageRoot ?? ownPackageRoot(version);
160
+ const watch = watchOutdated({
161
+ check: () => outdatedReason({
162
+ command: messenger.app.command,
163
+ running: version,
164
+ storePath: storePath(context.env),
165
+ packageRoot,
166
+ }),
167
+ onOutdated: (reason) => {
168
+ outdated = reason;
169
+ listening.abort();
170
+ },
171
+ ...(outdatedHook?.everyMs === undefined ? {} : { everyMs: outdatedHook.everyMs }),
172
+ });
155
173
  try {
156
174
  await listenUntilStopped(this, context, relay?.messenger ?? messenger, count, {
157
- stop: new AbortController(),
175
+ stop: listening,
158
176
  catchUp: true,
159
177
  onReady,
160
178
  connected: (open) => {
@@ -168,6 +186,7 @@ export const serveCommand = (messenger) => {
168
186
  });
169
187
  }
170
188
  finally {
189
+ watch.stop();
171
190
  await relaying;
172
191
  await relay?.close();
173
192
  rules.stop();
@@ -178,6 +197,9 @@ export const serveCommand = (messenger) => {
178
197
  await tasks.settled();
179
198
  releaseLock(path);
180
199
  }
200
+ // Not 0: the unit restarts only a serve that failed, and the restart is what loads the installed build.
201
+ if (outdated !== undefined)
202
+ throw new CliError("configuration_error", outdated, { reason: "serve.outdated" });
181
203
  // `kept` and the reply counts are keyed by event names and rule ids, never camelCased.
182
204
  renderAnswer(this, context, itemOf({
183
205
  profile: context.profile,
@@ -0,0 +1,22 @@
1
+ export declare const OUTDATED_CHECK_MS = 60000;
2
+ /** The folder of the package this process was started from, when its `package.json` still names `running`. */
3
+ export declare const ownPackageRoot: (running: string, script?: string | undefined) => string | undefined;
4
+ /**
5
+ * Why this serve should stop so its unit starts the installed build (BUG-643): the store moved past what this build
6
+ * may write, or a newer version was installed over it. A store that cannot be read now is not a reason.
7
+ */
8
+ export declare const outdatedReason: ({ command, running, storePath, packageRoot, speaks, }: {
9
+ command: string;
10
+ running: string;
11
+ storePath: string;
12
+ packageRoot?: string | undefined;
13
+ speaks?: number;
14
+ }) => Promise<string | undefined>;
15
+ /** Runs `check` every `everyMs` and calls `onOutdated` once with its first reason. */
16
+ export declare const watchOutdated: ({ check, onOutdated, everyMs, }: {
17
+ check: () => Promise<string | undefined>;
18
+ onOutdated: (reason: string) => void;
19
+ everyMs?: number;
20
+ }) => {
21
+ stop: () => void;
22
+ };
@@ -0,0 +1,100 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileSchemaOf, SPEAKS, writableBy } from "../../store/compatibility.js";
4
+ import { openSqlite } from "../../store/store.js";
5
+ export const OUTDATED_CHECK_MS = 60_000;
6
+ /** The folder of the package this process was started from, when its `package.json` still names `running`. */
7
+ export const ownPackageRoot = (running, script = process.argv[1]) => {
8
+ let dir;
9
+ try {
10
+ dir = dirname(realpathSync(script ?? ""));
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ for (let up = 0; up < 8; up++) {
16
+ const manifest = join(dir, "package.json");
17
+ if (existsSync(manifest))
18
+ return installedVersion(dir) === running ? dir : undefined;
19
+ const parent = dirname(dir);
20
+ if (parent === dir)
21
+ return undefined;
22
+ dir = parent;
23
+ }
24
+ return undefined;
25
+ };
26
+ const installedVersion = (root) => {
27
+ try {
28
+ const { version } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
29
+ return typeof version === "string" ? version : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ };
35
+ const newer = (one, other) => {
36
+ const parts = (version) => version.split(/[.+-]/, 3).map(Number);
37
+ const [a, b] = [parts(one), parts(other)];
38
+ for (let i = 0; i < 3; i++)
39
+ if ((a[i] ?? 0) !== (b[i] ?? 0))
40
+ return (a[i] ?? 0) > (b[i] ?? 0);
41
+ return false;
42
+ };
43
+ /**
44
+ * Why this serve should stop so its unit starts the installed build (BUG-643): the store moved past what this build
45
+ * may write, or a newer version was installed over it. A store that cannot be read now is not a reason.
46
+ */
47
+ export const outdatedReason = async ({ command, running, storePath, packageRoot, speaks = SPEAKS, }) => {
48
+ const installed = packageRoot === undefined ? undefined : installedVersion(packageRoot);
49
+ if (installed !== undefined && newer(installed, running))
50
+ return `${command} ${installed} is installed and this serve runs ${running}: stopping so it starts again on ${installed}`;
51
+ if (!existsSync(storePath))
52
+ return undefined;
53
+ let schema;
54
+ try {
55
+ const { database } = await openSqlite(storePath, { readOnly: true });
56
+ try {
57
+ schema = fileSchemaOf(database);
58
+ }
59
+ finally {
60
+ database.close();
61
+ }
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ if (writableBy(schema, speaks))
67
+ return undefined;
68
+ return (`the store is at format ${schema.version} and needs at least ${schema.minCompatible}; this serve (${command} ` +
69
+ `${running}) speaks ${speaks} and can no longer write it: stopping — \`${command} upgrade\` if it does not start ` +
70
+ "again on a newer version");
71
+ };
72
+ /** Runs `check` every `everyMs` and calls `onOutdated` once with its first reason. */
73
+ export const watchOutdated = ({ check, onOutdated, everyMs = OUTDATED_CHECK_MS, }) => {
74
+ let busy = false;
75
+ let done = false;
76
+ const timer = setInterval(() => {
77
+ if (busy || done)
78
+ return;
79
+ busy = true;
80
+ check()
81
+ .then((reason) => {
82
+ if (reason === undefined || done)
83
+ return;
84
+ done = true;
85
+ clearInterval(timer);
86
+ onOutdated(reason);
87
+ })
88
+ .catch(() => { })
89
+ .finally(() => {
90
+ busy = false;
91
+ });
92
+ }, everyMs);
93
+ timer.unref();
94
+ return {
95
+ stop: () => {
96
+ done = true;
97
+ clearInterval(timer);
98
+ },
99
+ };
100
+ };
@@ -46,6 +46,15 @@ export declare const scheduleLimitsOf: (config: {
46
46
  }) => ScheduleLimits;
47
47
  /** The language a report is rendered in: the store's `owner_languages`, first one; Russian when it cannot be read. */
48
48
  export declare const ownerLanguageOf: (env: NodeJS.ProcessEnv) => Promise<string>;
49
+ /**
50
+ * One past day's run of the agent schedule in `file`, as `backfillSchedule` makes it, with the owner's language and
51
+ * templates as `schedule run` renders them; a stop of the command stops the agent.
52
+ */
53
+ export declare const backfillScheduleRun: (command: Command, app: AppIdentity, env: NodeJS.ProcessEnv, file: string, { at, input, agentRuns }: {
54
+ at: Date;
55
+ input?: string;
56
+ agentRuns?: readonly AgentCli[];
57
+ }) => Promise<import("../../background/schedules.js").LastRun>;
49
58
  /**
50
59
  * Runs the CLI's own commands, or an agent, later or on a timer — through systemd (Linux), launchd
51
60
  * (macOS) or Task Scheduler (Windows). Every timer runs `schedule exec <file>`; the schedule file holds
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
3
3
  import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
4
  import { annotate } from "@wirecat/cli-base/commands";
5
5
  import { Argument, Command, Option } from "commander";
6
+ import { backfillSchedule } from "../../background/backfill.js";
6
7
  import { parseRoute, ROUTE_HELP, routeText } from "../../background/deliver.js";
7
8
  import { REPORT_CHANNELS } from "../../background/report/render.js";
8
9
  import { keyOfKind } from "../../background/report/stored-templates.js";
@@ -186,6 +187,18 @@ const reportTemplatesOf = (env) => async (kind, language) => {
186
187
  database.close();
187
188
  }
188
189
  };
190
+ /**
191
+ * One past day's run of the agent schedule in `file`, as `backfillSchedule` makes it, with the owner's language and
192
+ * templates as `schedule run` renders them; a stop of the command stops the agent.
193
+ */
194
+ export const backfillScheduleRun = (command, app, env, file, { at, input, agentRuns = [] }) => untilChildEnds(command, (signal) => backfillSchedule(app, environmentOf(command).system ?? thisMachine(), env, file, {
195
+ at,
196
+ agentRuns,
197
+ ownerLanguage: ownerLanguageOf,
198
+ reportTemplates: reportTemplatesOf,
199
+ ...(input === undefined ? {} : { input }),
200
+ ...(signal ? { signal } : {}),
201
+ }));
189
202
  /**
190
203
  * Runs the CLI's own commands, or an agent, later or on a timer — through systemd (Linux), launchd
191
204
  * (macOS) or Task Scheduler (Windows). Every timer runs `schedule exec <file>`; the schedule file holds
@@ -111,13 +111,37 @@ export const storeRecoveryRun = async (env, { command, version, note, timers: sc
111
111
  next: [...mail, ...lostMail, "systemctl --user start <the timers stopped before>"],
112
112
  };
113
113
  };
114
+ const refetchNotes = ({ since, chats, mail }) => {
115
+ const from = since === null ? "from the start" : `from ${since} on`;
116
+ const marked = [
117
+ ...chats.map(({ provider, account, chats }) => `${chats} chats of ${provider} ${account}`),
118
+ ...mail.map(({ account, folders }) => `${folders} mail folders of ${account}`),
119
+ ];
120
+ return [
121
+ marked.length > 0
122
+ ? `marked as not fetched ${from}, so the next sync or serve fetches it again: ${marked.join(", ")}`
123
+ : `nothing held ${from} was marked as fetched, so there is nothing to fetch again`,
124
+ ...chats
125
+ .filter(({ provider }) => provider === "whatsapp")
126
+ .map(({ account }) => `whatsapp ${account}: WhatsApp cannot be asked for its chats, so only what the phone pushes while serve runs comes back`),
127
+ "notes, memories, tags and whatever else only this store held cannot be fetched again",
128
+ ];
129
+ };
114
130
  /** The lines a person reads under the answer; the JSON carries the same in its fields. */
115
131
  export const recoveryNotes = (answer) => {
116
132
  if ("keptAt" in answer) {
117
- const lost = answer.lost.map(({ table, before, read, kept }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}`);
133
+ const lost = answer.lost.map(({ table, before, read, kept, goneAtLeast, seenIn }) => `${table}: ${kept} kept of ${before ?? "an uncountable number"}${read > kept ? `, ${read - kept} read but unusable` : ""}` +
134
+ (goneAtLeast > 0 ? `; at least ${goneAtLeast} rows are gone (the index ${seenIn} lists them)` : ""));
135
+ const since = answer.lastKnownGood
136
+ ? `since the last deep check that passed (${answer.lastKnownGood})`
137
+ : "since the store was made (no deep check that passed is on record)";
118
138
  return [
119
139
  `recovered in ${answer.seconds.total} s; the damaged file is kept at ${answer.keptAt}`,
120
- ...(lost.length ? lost : ["no table lost a row"]),
140
+ ...lost,
141
+ ...Object.entries(answer.placed).map(([table, rows]) => `${table}: ${rows} rows found on pages no table claimed were put back`),
142
+ ...refetchNotes(answer.refetch),
143
+ `${lost.some((line) => line.includes("are gone")) ? "more rows may be gone" : "how many rows were lost is unknown"}: ` +
144
+ `damage can take rows written ${since} without leaving a trace; a sync fetches again what the servers still hold`,
121
145
  ...answer.dangling.map(({ table, parent, rows }) => `${rows} rows of ${table} point at ${parent} rows the store does not hold`),
122
146
  ...answer.invalidJson.map(({ table, column, rows, required }) => `${table}.${column}: ${rows} values were not valid JSON — ${required ? "those rows were dropped" : "set to empty"}`),
123
147
  ...answer.next.map((line) => `next: ${line}`),