@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
@@ -3,6 +3,7 @@ import { checkEnds, isSymmetric } from "../../domain/relations.js";
3
3
  import { accountPk } from "./accounts.js";
4
4
  import { crmLinkMode } from "./crm-settings.js";
5
5
  import { linkKind } from "./link-kinds.js";
6
+ import { idsOf } from "./merged-persons.js";
6
7
  import { relationProposalsOver } from "./relation-proposals.js";
7
8
  import { checkStoredRole } from "./relation-roles.js";
8
9
  import { referenceOfThing, thingOf } from "./things.js";
@@ -108,14 +109,16 @@ export const syncReportedIn = (context, key, relationships, scope, { source = "i
108
109
  const thing = thingOf(database, ref);
109
110
  if (!thing)
110
111
  continue;
112
+ // What the source said about a person since merged into this one is withdrawn too, or it would show twice.
113
+ const ids = idsOf(database, thing.type, thing.id);
111
114
  // A partnership is stored once, either way round, so either end covers it.
112
115
  const match = end === "from"
113
- ? `((from_type = ? AND from_id = ?) OR (kind = ${linkKind("partner-of")} AND to_type = ? AND to_id = ?))`
114
- : `((to_type = ? AND to_id = ?) OR (kind = ${linkKind("partner-of")} AND from_type = ? AND from_id = ?))`;
116
+ ? `((from_type = ? AND from_id IN (SELECT value FROM json_each(?))) OR (kind = ${linkKind("partner-of")} AND to_type = ? AND to_id IN (SELECT value FROM json_each(?))))`
117
+ : `((to_type = ? AND to_id IN (SELECT value FROM json_each(?))) OR (kind = ${linkKind("partner-of")} AND from_type = ? AND from_id IN (SELECT value FROM json_each(?))))`;
115
118
  const rows = database
116
119
  .prepare(`SELECT id FROM links WHERE account_id = ? AND confirmed = 0 AND deleted_at IS NULL AND kind IN (${kinds}) ` +
117
120
  `AND ${match}${roles ? ` AND ifnull(role, '') IN (${roles})` : ""}`)
118
- .all(accountId, thing.type, thing.id, thing.type, thing.id, ...(scope.roles ?? []));
121
+ .all(accountId, thing.type, ids, thing.type, ids, ...(scope.roles ?? []));
119
122
  for (const row of rows)
120
123
  if (!seen.has(Number(row.id))) {
121
124
  seen.add(Number(row.id));
@@ -0,0 +1,242 @@
1
+ /** A template the owner saved over the shipped one, per key, channel and language. */
2
+ export declare const templates: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
3
+ name: "templates";
4
+ schema: undefined;
5
+ columns: {
6
+ key: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7
+ name: string;
8
+ tableName: "templates";
9
+ dataType: "string";
10
+ data: string;
11
+ driverParam: string;
12
+ notNull: true;
13
+ hasDefault: false;
14
+ isPrimaryKey: false;
15
+ isAutoincrement: false;
16
+ hasRuntimeDefault: false;
17
+ enumValues: [string, ...string[]];
18
+ baseColumn: never;
19
+ identity: undefined;
20
+ generated: undefined;
21
+ }, {}>;
22
+ channel: import("drizzle-orm/sqlite-core").SQLiteColumn<{
23
+ name: string;
24
+ tableName: "templates";
25
+ dataType: "string";
26
+ data: string;
27
+ driverParam: string;
28
+ notNull: true;
29
+ hasDefault: false;
30
+ isPrimaryKey: false;
31
+ isAutoincrement: false;
32
+ hasRuntimeDefault: false;
33
+ enumValues: [string, ...string[]];
34
+ baseColumn: never;
35
+ identity: undefined;
36
+ generated: undefined;
37
+ }, {}>;
38
+ language: import("drizzle-orm/sqlite-core").SQLiteColumn<{
39
+ name: string;
40
+ tableName: "templates";
41
+ dataType: "string";
42
+ data: string;
43
+ driverParam: string;
44
+ notNull: true;
45
+ hasDefault: false;
46
+ isPrimaryKey: false;
47
+ isAutoincrement: false;
48
+ hasRuntimeDefault: false;
49
+ enumValues: [string, ...string[]];
50
+ baseColumn: never;
51
+ identity: undefined;
52
+ generated: undefined;
53
+ }, {}>;
54
+ body: import("drizzle-orm/sqlite-core").SQLiteColumn<{
55
+ name: string;
56
+ tableName: "templates";
57
+ dataType: "string";
58
+ data: string;
59
+ driverParam: string;
60
+ notNull: true;
61
+ hasDefault: false;
62
+ isPrimaryKey: false;
63
+ isAutoincrement: false;
64
+ hasRuntimeDefault: false;
65
+ enumValues: [string, ...string[]];
66
+ baseColumn: never;
67
+ identity: undefined;
68
+ generated: undefined;
69
+ }, {}>;
70
+ updatedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
71
+ name: string;
72
+ tableName: "templates";
73
+ dataType: "number int53";
74
+ data: number;
75
+ driverParam: number;
76
+ notNull: true;
77
+ hasDefault: false;
78
+ isPrimaryKey: false;
79
+ isAutoincrement: false;
80
+ hasRuntimeDefault: false;
81
+ enumValues: undefined;
82
+ baseColumn: never;
83
+ identity: undefined;
84
+ generated: undefined;
85
+ }, {}>;
86
+ updatedBy: import("drizzle-orm/sqlite-core").SQLiteColumn<{
87
+ name: string;
88
+ tableName: "templates";
89
+ dataType: "string";
90
+ data: string;
91
+ driverParam: string;
92
+ notNull: true;
93
+ hasDefault: false;
94
+ isPrimaryKey: false;
95
+ isAutoincrement: false;
96
+ hasRuntimeDefault: false;
97
+ enumValues: [string, ...string[]];
98
+ baseColumn: never;
99
+ identity: undefined;
100
+ generated: undefined;
101
+ }, {}>;
102
+ };
103
+ dialect: 'sqlite';
104
+ isAlias: false;
105
+ }>;
106
+ /** Every body a save or a reset replaced. */
107
+ export declare const templatesHistory: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
108
+ name: "templates_history";
109
+ schema: undefined;
110
+ columns: {
111
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
112
+ name: string;
113
+ tableName: "templates_history";
114
+ dataType: "number int53";
115
+ data: number;
116
+ driverParam: number;
117
+ notNull: true;
118
+ hasDefault: true;
119
+ isPrimaryKey: true;
120
+ isAutoincrement: false;
121
+ hasRuntimeDefault: false;
122
+ enumValues: undefined;
123
+ baseColumn: never;
124
+ identity: undefined;
125
+ generated: undefined;
126
+ }, {}>;
127
+ key: import("drizzle-orm/sqlite-core").SQLiteColumn<{
128
+ name: string;
129
+ tableName: "templates_history";
130
+ dataType: "string";
131
+ data: string;
132
+ driverParam: string;
133
+ notNull: true;
134
+ hasDefault: false;
135
+ isPrimaryKey: false;
136
+ isAutoincrement: false;
137
+ hasRuntimeDefault: false;
138
+ enumValues: [string, ...string[]];
139
+ baseColumn: never;
140
+ identity: undefined;
141
+ generated: undefined;
142
+ }, {}>;
143
+ channel: import("drizzle-orm/sqlite-core").SQLiteColumn<{
144
+ name: string;
145
+ tableName: "templates_history";
146
+ dataType: "string";
147
+ data: string;
148
+ driverParam: string;
149
+ notNull: true;
150
+ hasDefault: false;
151
+ isPrimaryKey: false;
152
+ isAutoincrement: false;
153
+ hasRuntimeDefault: false;
154
+ enumValues: [string, ...string[]];
155
+ baseColumn: never;
156
+ identity: undefined;
157
+ generated: undefined;
158
+ }, {}>;
159
+ language: import("drizzle-orm/sqlite-core").SQLiteColumn<{
160
+ name: string;
161
+ tableName: "templates_history";
162
+ dataType: "string";
163
+ data: string;
164
+ driverParam: string;
165
+ notNull: true;
166
+ hasDefault: false;
167
+ isPrimaryKey: false;
168
+ isAutoincrement: false;
169
+ hasRuntimeDefault: false;
170
+ enumValues: [string, ...string[]];
171
+ baseColumn: never;
172
+ identity: undefined;
173
+ generated: undefined;
174
+ }, {}>;
175
+ body: import("drizzle-orm/sqlite-core").SQLiteColumn<{
176
+ name: string;
177
+ tableName: "templates_history";
178
+ dataType: "string";
179
+ data: string;
180
+ driverParam: string;
181
+ notNull: true;
182
+ hasDefault: false;
183
+ isPrimaryKey: false;
184
+ isAutoincrement: false;
185
+ hasRuntimeDefault: false;
186
+ enumValues: [string, ...string[]];
187
+ baseColumn: never;
188
+ identity: undefined;
189
+ generated: undefined;
190
+ }, {}>;
191
+ savedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
192
+ name: string;
193
+ tableName: "templates_history";
194
+ dataType: "number int53";
195
+ data: number;
196
+ driverParam: number;
197
+ notNull: true;
198
+ hasDefault: false;
199
+ isPrimaryKey: false;
200
+ isAutoincrement: false;
201
+ hasRuntimeDefault: false;
202
+ enumValues: undefined;
203
+ baseColumn: never;
204
+ identity: undefined;
205
+ generated: undefined;
206
+ }, {}>;
207
+ savedBy: import("drizzle-orm/sqlite-core").SQLiteColumn<{
208
+ name: string;
209
+ tableName: "templates_history";
210
+ dataType: "string";
211
+ data: string;
212
+ driverParam: string;
213
+ notNull: true;
214
+ hasDefault: false;
215
+ isPrimaryKey: false;
216
+ isAutoincrement: false;
217
+ hasRuntimeDefault: false;
218
+ enumValues: [string, ...string[]];
219
+ baseColumn: never;
220
+ identity: undefined;
221
+ generated: undefined;
222
+ }, {}>;
223
+ replacedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
224
+ name: string;
225
+ tableName: "templates_history";
226
+ dataType: "number int53";
227
+ data: number;
228
+ driverParam: number;
229
+ notNull: true;
230
+ hasDefault: false;
231
+ isPrimaryKey: false;
232
+ isAutoincrement: false;
233
+ hasRuntimeDefault: false;
234
+ enumValues: undefined;
235
+ baseColumn: never;
236
+ identity: undefined;
237
+ generated: undefined;
238
+ }, {}>;
239
+ };
240
+ dialect: 'sqlite';
241
+ isAlias: false;
242
+ }>;
@@ -0,0 +1,23 @@
1
+ import { index, integer, primaryKey, sqliteTable, text } from "../drizzle/core.js";
2
+ /** A template the owner saved over the shipped one, per key, channel and language. */
3
+ export const templates = sqliteTable("templates", {
4
+ key: text("key").notNull(),
5
+ channel: text("channel").notNull(),
6
+ language: text("language").notNull(),
7
+ body: text("body").notNull(),
8
+ updatedAt: integer("updated_at").notNull(),
9
+ updatedBy: text("updated_by").notNull(),
10
+ }, (table) => [primaryKey({ columns: [table.key, table.channel, table.language] })]);
11
+ /** Every body a save or a reset replaced. */
12
+ export const templatesHistory = sqliteTable("templates_history", {
13
+ id: integer("id").primaryKey(),
14
+ key: text("key").notNull(),
15
+ channel: text("channel").notNull(),
16
+ language: text("language").notNull(),
17
+ body: text("body").notNull(),
18
+ savedAt: integer("saved_at").notNull(),
19
+ savedBy: text("saved_by").notNull(),
20
+ replacedAt: integer("replaced_at").notNull(),
21
+ }, (table) => [
22
+ index("templates_history_by_key_channel_language_id").on(table.key, table.channel, table.language, table.id),
23
+ ]);
@@ -19487,6 +19487,7 @@ export declare const transactionSplits: import("drizzle-orm/sqlite-core").SQLite
19487
19487
  }>;
19488
19488
  export { decisionRequests } from "./schema/decision-requests.js";
19489
19489
  export { enrichments } from "./schema/enrichments.js";
19490
+ export { templates, templatesHistory } from "./schema/templates.js";
19490
19491
  /** What a source said about one of its records, as it said it: the layer under the entity an import makes. */
19491
19492
  export declare const records: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
19492
19493
  name: "records";
@@ -1934,6 +1934,7 @@ export const transactionSplits = sqliteTable("transaction_splits", {
1934
1934
  ]);
1935
1935
  export { decisionRequests } from "./schema/decision-requests.js";
1936
1936
  export { enrichments } from "./schema/enrichments.js";
1937
+ export { templates, templatesHistory } from "./schema/templates.js";
1937
1938
  /** What a source said about one of its records, as it said it: the layer under the entity an import makes. */
1938
1939
  export const records = sqliteTable("records", {
1939
1940
  id: integer("id").primaryKey(),
@@ -1,5 +1,5 @@
1
1
  import { type Decider } from "../decisions.js";
2
- import { type SourceCheck } from "../source-review.js";
2
+ import { type ChangedSource, type SourceCheck, type SourceReviewText } from "../source-review.js";
3
3
  import { type Author } from "./memories.js";
4
4
  import type { StoreContext } from "./open.js";
5
5
  import { type ProposedAction } from "./proposed-actions.js";
@@ -27,6 +27,11 @@ export declare const sourceReviewOver: (context: StoreContext) => {
27
27
  limit?: number;
28
28
  }) => SourceCheck;
29
29
  challenge: (reference: string, input: ChallengeInput) => ProposedAction;
30
+ changedSince: ({ since, limit }: {
31
+ since: number;
32
+ limit?: number;
33
+ }) => ChangedSource[];
34
+ texts: (id: string) => SourceReviewText[];
30
35
  decide: (id: string, decision: SourceReviewDecision) => ProposedAction;
31
36
  };
32
37
  /** The knowledge store's part that watches what memories and facts cite. */
@@ -50,5 +55,19 @@ export interface SourceReviewStore {
50
55
  * reject dismisses the review. Both sign its sources again as they are now.
51
56
  */
52
57
  decideSourceReview(id: string, decision: SourceReviewDecision): Promise<ProposedAction>;
58
+ /**
59
+ * Each source of a `memory_source_review`, as it was cited and as it is now, with the quote the claim rested on.
60
+ * The review itself never holds source text; this reads it when the owner looks.
61
+ */
62
+ sourceReviewTexts(id: string): Promise<SourceReviewText[]>;
63
+ /**
64
+ * Cited sources a check found changed since `since` (ms) that differ from the version cited, newest first, at most
65
+ * `limit` (500): what `checkSources` reported once as `changedRefs`, still there after another run took it.
66
+ * Deleted sources, cited memories or facts, and what an open `evidence_findings` batch cites are left out.
67
+ */
68
+ changedSources(options: {
69
+ since: number;
70
+ limit?: number;
71
+ }): Promise<ChangedSource[]>;
53
72
  }
54
73
  export declare const sourceReviewStoreOver: (context: StoreContext) => SourceReviewStore;
@@ -1,7 +1,8 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { assertMayDecide, deciderAuthor } from "../decisions.js";
3
- import { SOURCE_REVIEW_KIND } from "../source-review.js";
4
- import { evidenceSignature, resignEvidence, sourceHolds, storedEvidenceMetadata, } from "./evidence-signature.js";
3
+ import { EVIDENCE_FINDINGS_KIND } from "../evidence-findings.js";
4
+ import { SOURCE_REVIEW_KIND, } from "../source-review.js";
5
+ import { evidenceSignature, resignEvidence, sourceHolds, sourceTextAt, storedEvidenceMetadata, } from "./evidence-signature.js";
5
6
  import { linkKind } from "./link-kinds.js";
6
7
  import { authorActor } from "./memories.js";
7
8
  import { requiredThing } from "./notes.js";
@@ -95,6 +96,13 @@ export const sourceReviewOver = (context) => {
95
96
  for (const link of evidenceLinksOf(target))
96
97
  resignEvidence(database, Number(link.id), evidenceSignature(database, storedThing(link.to_type, link.to_id)), at, storedEvidenceMetadata(link.metadata));
97
98
  };
99
+ /** Every reference an open evidence findings batch cites, so a changed source already being read is not offered. */
100
+ const inExtraction = () => new Set(database
101
+ .prepare("SELECT DISTINCT json_extract(e.value, '$.reference') AS ref FROM proposed_actions p, " +
102
+ "json_each(p.payload, '$.findings') f, json_each(f.value, '$.evidence') e " +
103
+ "WHERE p.kind = ? AND p.status = 'proposed' AND json_valid(p.payload)")
104
+ .all(EVIDENCE_FINDINGS_KIND)
105
+ .flatMap((row) => (typeof row.ref === "string" ? [row.ref] : [])));
98
106
  const cursor = () => Number(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(CURSOR)?.value ?? 0);
99
107
  /**
100
108
  * The next evidence links after the cursor, at most `limit`, read from a window of `SCAN_FACTOR * limit` link ids
@@ -116,7 +124,8 @@ export const sourceReviewOver = (context) => {
116
124
  throw new CliError("validation_error", "a source check takes 1–10000 evidence links");
117
125
  return write(database, () => {
118
126
  const at = now();
119
- const counts = { checked: 0, baselined: 0, raised: 0, refreshed: 0, closed: 0 };
127
+ const counts = { checked: 0, baselined: 0, raised: 0, refreshed: 0, closed: 0, changedRefs: [] };
128
+ const changed = new Set();
120
129
  const raised = new Map();
121
130
  const retired = new Map();
122
131
  const { links, next } = nextLinks(limit);
@@ -134,6 +143,13 @@ export const sourceReviewOver = (context) => {
134
143
  if (verdict.outcome === "same")
135
144
  continue;
136
145
  resignEvidence(database, Number(link.id), signature, at, storedEvidenceMetadata(link.metadata));
146
+ if (verdict.outcome !== "baselined" &&
147
+ !signature.deleted &&
148
+ asReviewTarget(thing.type, thing.id) === undefined) {
149
+ const ref = referenceOfThing(database, thing);
150
+ if (ref !== undefined)
151
+ changed.add(ref);
152
+ }
137
153
  if (verdict.outcome === "baselined")
138
154
  counts.baselined++;
139
155
  else if (verdict.outcome === "refreshed")
@@ -153,6 +169,10 @@ export const sourceReviewOver = (context) => {
153
169
  database
154
170
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
155
171
  .run(CURSOR, String(next), at);
172
+ if (changed.size > 0) {
173
+ const read = inExtraction();
174
+ counts.changedRefs = [...changed].filter((ref) => !read.has(ref));
175
+ }
156
176
  return counts;
157
177
  });
158
178
  },
@@ -186,6 +206,55 @@ export const sourceReviewOver = (context) => {
186
206
  return operations.get(id);
187
207
  });
188
208
  },
209
+ changedSince: ({ since, limit = DEFAULT_LIMIT }) => {
210
+ if (!Number.isFinite(since))
211
+ throw new CliError("validation_error", "changed sources take a start time");
212
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10_000)
213
+ throw new CliError("validation_error", "changed sources take 1–10000 references");
214
+ const rows = database
215
+ .prepare("SELECT to_type, to_id, max(json_extract(metadata, '$.checked_at')) AS at FROM links " +
216
+ `WHERE kind = ${linkKind("evidence")} AND from_type IN ('memory', 'fact') AND to_id IS NOT NULL ` +
217
+ "AND to_type NOT IN ('memory', 'fact') AND json_valid(metadata) " +
218
+ "AND json_extract(metadata, '$.checked_at') >= ? AND json_extract(metadata, '$.gone') IS NULL " +
219
+ "AND json_extract(metadata, '$.rev') IS NOT json_extract(metadata, '$.cited_rev') " +
220
+ "GROUP BY to_type, to_id ORDER BY at DESC")
221
+ .all(since);
222
+ const read = inExtraction();
223
+ const changed = [];
224
+ for (const row of rows) {
225
+ if (changed.length === limit)
226
+ break;
227
+ const thing = storedThing(row.to_type, row.to_id);
228
+ if (evidenceSignature(database, thing).deleted)
229
+ continue;
230
+ const ref = referenceOfThing(database, thing);
231
+ if (ref !== undefined && !read.has(ref))
232
+ changed.push({ ref, checkedAt: iso(Number(row.at)) });
233
+ }
234
+ return changed;
235
+ },
236
+ texts: (id) => {
237
+ const proposal = operations.get(id);
238
+ if (proposal.kind !== SOURCE_REVIEW_KIND)
239
+ throw new CliError("validation_error", `${id} is a ${proposal.kind} proposal, not a source review`);
240
+ const link = database.prepare(`SELECT to_type, to_id, metadata FROM links WHERE id = ? AND kind = ${linkKind("evidence")}`);
241
+ return proposal.payload.sources.map((source) => {
242
+ const row = link.get(source.link);
243
+ const quote = row ? (storedEvidenceMetadata(row.metadata)?.quote ?? null) : null;
244
+ if (!row || row.to_id == null || source.ref === null)
245
+ return { link: source.link, ref: source.ref, quote, cited: null, now: null };
246
+ const thing = storedThing(row.to_type, row.to_id);
247
+ const signature = evidenceSignature(database, thing);
248
+ const at = (rev) => (rev === null ? null : (sourceTextAt(database, thing, rev) ?? null));
249
+ return {
250
+ link: source.link,
251
+ ref: source.ref,
252
+ quote,
253
+ cited: at(source.citedRev),
254
+ now: signature.deleted ? null : at(signature.rev),
255
+ };
256
+ });
257
+ },
189
258
  decide: (id, decision) => write(database, () => {
190
259
  const proposal = operations.get(id);
191
260
  if (proposal.kind !== SOURCE_REVIEW_KIND)
@@ -217,5 +286,7 @@ export const sourceReviewStoreOver = (context) => {
217
286
  checkSources: async (options) => sourceReview.checkSources(options),
218
287
  challenge: async (reference, input) => sourceReview.challenge(reference, input),
219
288
  decideSourceReview: async (id, decision) => sourceReview.decide(id, decision),
289
+ sourceReviewTexts: async (id) => sourceReview.texts(id),
290
+ changedSources: async (options) => sourceReview.changedSince(options),
220
291
  };
221
292
  };
@@ -1,4 +1,5 @@
1
1
  import { type FieldSpec, type QueryAst } from "@wirecat/cli-base/query";
2
+ import type { CacheDatabase } from "../driver.js";
2
3
  import type { ColumnMap } from "./query-filter.js";
3
4
  export declare const TASK_SORTS: readonly ["priority", "due", "created", "updated", "key", "state"];
4
5
  export type TaskSort = (typeof TASK_SORTS)[number];
@@ -16,10 +17,14 @@ export declare const dueGroups: (now: number, zone: string) => {
16
17
  };
17
18
  export type DueGroup = keyof ReturnType<typeof dueGroups>;
18
19
  /** `now` and `zone` place today; one value per answer, so the list and its counts agree. */
19
- export declare const projectTaskColumns: (now: number, zone: string) => ColumnMap;
20
+ export declare const projectTaskColumns: (now: number, zone: string, database: CacheDatabase) => ColumnMap;
20
21
  /** Live tasks of the owner's projects; an account's inbox is listed by its account, never here. */
21
22
  export declare const BOARD_SCOPE = "t.deleted_at IS NULL AND t.project_id IN (SELECT id FROM projects WHERE deleted_at IS NULL AND length(key) <> 10)";
22
23
  /** The chosen order first, then priority, age and id, so a page boundary never splits a tie. */
23
24
  export declare const boardOrder: (sort: TaskSort, descending: boolean) => string;
24
25
  /** The query without its required terms on `name`: a picker counts the choices its own filter hides. */
25
26
  export declare const withoutField: (query: QueryAst | undefined, name: string) => QueryAst | undefined;
27
+ /** The people tasks name; a merged-away person is left out and its tasks count for the person it is now. */
28
+ export declare const TASK_PEOPLE: string;
29
+ /** Merged-away people a task is assigned to, with the person each is now, as JSON pairs for `TASK_PEOPLE`. */
30
+ export declare const mergedAssignees: (database: CacheDatabase) => string;
@@ -3,6 +3,7 @@ import { dayBoundary, OPERATORS_BY_TYPE, walkQuery, } from "@wirecat/cli-base/qu
3
3
  import { TASK_TYPES } from "../../domain/knowledge.js";
4
4
  import { taskWordsOf } from "../../search/task-similarity.js";
5
5
  import { PRIORITY_LABELS, priorityBand, TASK_STATES } from "../../tasks/index.js";
6
+ import { currentPerson, idsOf, mergedAwaySql } from "./merged-persons.js";
6
7
  import { INBOX_KEY_LENGTH } from "./task-keys.js";
7
8
  export const TASK_SORTS = ["priority", "due", "created", "updated", "key", "state"];
8
9
  const field = (name, type, example, more = {}) => ({
@@ -71,7 +72,7 @@ const projectWhere = (node) => {
71
72
  params: [key],
72
73
  };
73
74
  };
74
- const assigneeWhere = (node) => {
75
+ const assigneeWhere = (database, node) => {
75
76
  const value = node.value.trim().toLowerCase();
76
77
  if (value === "any" || (node.operator === "wildcard" && value === "*"))
77
78
  return { sql: `EXISTS (${ASSIGNED})`, params: [] };
@@ -80,7 +81,10 @@ const assigneeWhere = (node) => {
80
81
  const id = /^(?:person:)?(\d+)$/.exec(value)?.[1];
81
82
  if (id === undefined)
82
83
  throw new CliError("validation_error", `assignee: takes any, none or "person:<id>", not "${node.value}"`);
83
- return { sql: `EXISTS (${ASSIGNED} AND a.assignee_id = ?)`, params: [Number(id)] };
84
+ return {
85
+ sql: `EXISTS (${ASSIGNED} AND a.assignee_id IN (SELECT value FROM json_each(?)))`,
86
+ params: [idsOf(database, "person", Number(id))],
87
+ };
84
88
  };
85
89
  const bound = (value, side, node) => {
86
90
  const word = value.trim().toLowerCase();
@@ -175,11 +179,11 @@ export const dueGroups = (now, zone) => {
175
179
  };
176
180
  };
177
181
  /** `now` and `zone` place today; one value per answer, so the list and its counts agree. */
178
- export const projectTaskColumns = (now, zone) => ({
182
+ export const projectTaskColumns = (now, zone, database) => ({
179
183
  state: { type: "enum", sql: "t.status" },
180
184
  kind: { type: "enum", sql: "t.type" },
181
185
  project: { where: projectWhere },
182
- assignee: { where: assigneeWhere },
186
+ assignee: { where: (node) => assigneeWhere(database, node) },
183
187
  priority: { where: priorityWhere },
184
188
  agent: { where: agentWhere },
185
189
  parent: { where: parentWhere },
@@ -243,3 +247,17 @@ export const withoutField = (query, name) => {
243
247
  const root = strip(query.root);
244
248
  return root === undefined ? undefined : { ...query, root };
245
249
  };
250
+ /** The people tasks name; a merged-away person is left out and its tasks count for the person it is now. */
251
+ export const TASK_PEOPLE = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)), " +
252
+ "counts AS (SELECT coalesce(m.now, a.assignee_id) AS person, count(DISTINCT t.id) AS n FROM task_assignments a " +
253
+ "JOIN tasks t ON t.id = a.task_id AND t.deleted_at IS NULL LEFT JOIN merged m ON m.id = a.assignee_id " +
254
+ "WHERE a.assignee_type = 'person' GROUP BY 1) " +
255
+ "SELECT p.id, p.name, p.owner, coalesce(c.n, 0) AS n FROM persons p LEFT JOIN counts c ON c.person = p.id " +
256
+ `WHERE NOT ${mergedAwaySql("p")} ` +
257
+ "ORDER BY p.owner DESC, n DESC, p.name IS NULL, p.name COLLATE NOCASE, p.id LIMIT ?";
258
+ /** Merged-away people a task is assigned to, with the person each is now, as JSON pairs for `TASK_PEOPLE`. */
259
+ export const mergedAssignees = (database) => JSON.stringify(database
260
+ .prepare("SELECT DISTINCT a.assignee_id AS id FROM task_assignments a JOIN persons p ON p.id = a.assignee_id " +
261
+ `WHERE a.assignee_type = 'person' AND ${mergedAwaySql("p")}`)
262
+ .all()
263
+ .map(({ id }) => [Number(id), currentPerson(database, Number(id))]));
@@ -0,0 +1,38 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** Which template: `report/morning-digest`, `telegram`, `ru`. */
4
+ export interface TemplateAddress {
5
+ key: string;
6
+ channel: string;
7
+ language: string;
8
+ }
9
+ export interface StoredTemplate extends TemplateAddress {
10
+ body: string;
11
+ updatedAt: number;
12
+ updatedBy: string;
13
+ }
14
+ /** A body a save or a reset replaced. */
15
+ export interface TemplateHistoryEntry extends TemplateAddress {
16
+ id: number;
17
+ body: string;
18
+ savedAt: number;
19
+ savedBy: string;
20
+ replacedAt: number;
21
+ }
22
+ /** The owner's templates over the shipped ones. Nothing here checks a body: the caller does, before `save`. */
23
+ export interface TemplateStore {
24
+ list(): StoredTemplate[];
25
+ get(address: TemplateAddress): StoredTemplate | undefined;
26
+ /** Stores `body`, and keeps the body it replaces in the history. */
27
+ save(address: TemplateAddress, body: string, by: string): StoredTemplate;
28
+ /** Deletes the stored body, kept in the history, so the shipped one applies; false when there was none. */
29
+ reset(address: TemplateAddress): boolean;
30
+ /** Newest first. */
31
+ history(address: TemplateAddress, limit?: number): TemplateHistoryEntry[];
32
+ }
33
+ export declare const templateStoreOver: ({ database, now }: StoreContext) => TemplateStore;
34
+ /**
35
+ * The stored bodies of one key and language, by channel, read without migrating the file: a store older than the
36
+ * table has none.
37
+ */
38
+ export declare const storedTemplateBodies: (database: CacheDatabase, key: string, language: string) => Record<string, string>;
@@ -0,0 +1,69 @@
1
+ import { write } from "./transaction.js";
2
+ const templateOf = (row) => ({
3
+ key: row.key,
4
+ channel: row.channel,
5
+ language: row.language,
6
+ body: row.body,
7
+ updatedAt: row.updated_at,
8
+ updatedBy: row.updated_by,
9
+ });
10
+ const WHERE = "key = ? AND channel = ? AND language = ?";
11
+ const at = ({ key, channel, language }) => [key, channel, language];
12
+ export const templateStoreOver = ({ database, now }) => {
13
+ const get = (address) => {
14
+ const row = database.prepare(`SELECT * FROM templates WHERE ${WHERE}`).get(...at(address));
15
+ return row && templateOf(row);
16
+ };
17
+ const keep = (old, replacedAt) => database
18
+ .prepare("INSERT INTO templates_history (key, channel, language, body, saved_at, saved_by, replaced_at) " +
19
+ "VALUES (?, ?, ?, ?, ?, ?, ?)")
20
+ .run(...at(old), old.body, old.updatedAt, old.updatedBy, replacedAt);
21
+ return {
22
+ list: () => database.prepare("SELECT * FROM templates ORDER BY key, channel, language").all().map(templateOf),
23
+ get,
24
+ save: (address, body, by) => write(database, () => {
25
+ const time = now();
26
+ const old = get(address);
27
+ if (old)
28
+ keep(old, time);
29
+ database
30
+ .prepare("INSERT INTO templates (key, channel, language, body, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?) " +
31
+ "ON CONFLICT (key, channel, language) DO UPDATE SET body = excluded.body, " +
32
+ "updated_at = excluded.updated_at, updated_by = excluded.updated_by")
33
+ .run(...at(address), body, time, by);
34
+ return { ...address, body, updatedAt: time, updatedBy: by };
35
+ }),
36
+ reset: (address) => write(database, () => {
37
+ const old = get(address);
38
+ if (!old)
39
+ return false;
40
+ keep(old, now());
41
+ database.prepare(`DELETE FROM templates WHERE ${WHERE}`).run(...at(address));
42
+ return true;
43
+ }),
44
+ history: (address, limit = 20) => database
45
+ .prepare(`SELECT * FROM templates_history WHERE ${WHERE} ORDER BY id DESC LIMIT ?`)
46
+ .all(...at(address), limit).map((row) => ({
47
+ id: row.id,
48
+ key: row.key,
49
+ channel: row.channel,
50
+ language: row.language,
51
+ body: row.body,
52
+ savedAt: row.saved_at,
53
+ savedBy: row.saved_by,
54
+ replacedAt: row.replaced_at,
55
+ })),
56
+ };
57
+ };
58
+ /**
59
+ * The stored bodies of one key and language, by channel, read without migrating the file: a store older than the
60
+ * table has none.
61
+ */
62
+ export const storedTemplateBodies = (database, key, language) => {
63
+ if (!database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'templates'").get())
64
+ return {};
65
+ const rows = database
66
+ .prepare("SELECT channel, body FROM templates WHERE key = ? AND language = ?")
67
+ .all(key, language);
68
+ return Object.fromEntries(rows.map((row) => [row.channel, row.body]));
69
+ };