@wirecat/cli-core 0.578.0 → 0.580.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.
@@ -38,6 +38,7 @@ export declare const meetingTools: ({
38
38
  max_read_bytes?: undefined;
39
39
  cursor?: undefined;
40
40
  } | {
41
+ limit?: undefined;
41
42
  event_id?: undefined;
42
43
  series_id?: undefined;
43
44
  page?: undefined;
@@ -53,11 +54,11 @@ export declare const meetingTools: ({
53
54
  format?: undefined;
54
55
  transcript_id?: undefined;
55
56
  query?: undefined;
56
- limit?: undefined;
57
57
  scan_limit?: undefined;
58
58
  max_read_bytes?: undefined;
59
59
  cursor?: undefined;
60
60
  } | {
61
+ limit?: undefined;
61
62
  event_id?: undefined;
62
63
  series_id?: undefined;
63
64
  page?: undefined;
@@ -75,11 +76,11 @@ export declare const meetingTools: ({
75
76
  format?: undefined;
76
77
  transcript_id?: undefined;
77
78
  query?: undefined;
78
- limit?: undefined;
79
79
  scan_limit?: undefined;
80
80
  max_read_bytes?: undefined;
81
81
  cursor?: undefined;
82
82
  } | {
83
+ limit?: undefined;
83
84
  event_id?: undefined;
84
85
  series_id?: undefined;
85
86
  page?: undefined;
@@ -101,7 +102,6 @@ export declare const meetingTools: ({
101
102
  minimum: number;
102
103
  };
103
104
  query?: undefined;
104
- limit?: undefined;
105
105
  scan_limit?: undefined;
106
106
  max_read_bytes?: undefined;
107
107
  cursor?: undefined;
@@ -188,6 +188,7 @@ export declare const meetingTools: ({
188
188
  max_read_bytes?: undefined;
189
189
  cursor?: undefined;
190
190
  } | {
191
+ limit?: undefined;
191
192
  event_id?: undefined;
192
193
  series_id?: undefined;
193
194
  page?: undefined;
@@ -203,11 +204,11 @@ export declare const meetingTools: ({
203
204
  format?: undefined;
204
205
  transcript_id?: undefined;
205
206
  query?: undefined;
206
- limit?: undefined;
207
207
  scan_limit?: undefined;
208
208
  max_read_bytes?: undefined;
209
209
  cursor?: undefined;
210
210
  } | {
211
+ limit?: undefined;
211
212
  event_id?: undefined;
212
213
  series_id?: undefined;
213
214
  page?: undefined;
@@ -225,11 +226,11 @@ export declare const meetingTools: ({
225
226
  format?: undefined;
226
227
  transcript_id?: undefined;
227
228
  query?: undefined;
228
- limit?: undefined;
229
229
  scan_limit?: undefined;
230
230
  max_read_bytes?: undefined;
231
231
  cursor?: undefined;
232
232
  } | {
233
+ limit?: undefined;
233
234
  event_id?: undefined;
234
235
  series_id?: undefined;
235
236
  page?: undefined;
@@ -251,7 +252,6 @@ export declare const meetingTools: ({
251
252
  minimum: number;
252
253
  };
253
254
  query?: undefined;
254
- limit?: undefined;
255
255
  scan_limit?: undefined;
256
256
  max_read_bytes?: undefined;
257
257
  cursor?: undefined;
@@ -338,6 +338,7 @@ export declare const meetingTools: ({
338
338
  max_read_bytes?: undefined;
339
339
  cursor?: undefined;
340
340
  } | {
341
+ limit?: undefined;
341
342
  event_id?: undefined;
342
343
  series_id?: undefined;
343
344
  page?: undefined;
@@ -353,11 +354,11 @@ export declare const meetingTools: ({
353
354
  format?: undefined;
354
355
  transcript_id?: undefined;
355
356
  query?: undefined;
356
- limit?: undefined;
357
357
  scan_limit?: undefined;
358
358
  max_read_bytes?: undefined;
359
359
  cursor?: undefined;
360
360
  } | {
361
+ limit?: undefined;
361
362
  event_id?: undefined;
362
363
  series_id?: undefined;
363
364
  page?: undefined;
@@ -375,11 +376,11 @@ export declare const meetingTools: ({
375
376
  format?: undefined;
376
377
  transcript_id?: undefined;
377
378
  query?: undefined;
378
- limit?: undefined;
379
379
  scan_limit?: undefined;
380
380
  max_read_bytes?: undefined;
381
381
  cursor?: undefined;
382
382
  } | {
383
+ limit?: undefined;
383
384
  event_id?: undefined;
384
385
  series_id?: undefined;
385
386
  page?: undefined;
@@ -401,7 +402,6 @@ export declare const meetingTools: ({
401
402
  minimum: number;
402
403
  };
403
404
  query?: undefined;
404
- limit?: undefined;
405
405
  scan_limit?: undefined;
406
406
  max_read_bytes?: undefined;
407
407
  cursor?: undefined;
@@ -488,6 +488,7 @@ export declare const meetingTools: ({
488
488
  max_read_bytes?: undefined;
489
489
  cursor?: undefined;
490
490
  } | {
491
+ limit?: undefined;
491
492
  event_id?: undefined;
492
493
  series_id?: undefined;
493
494
  page?: undefined;
@@ -503,11 +504,11 @@ export declare const meetingTools: ({
503
504
  format?: undefined;
504
505
  transcript_id?: undefined;
505
506
  query?: undefined;
506
- limit?: undefined;
507
507
  scan_limit?: undefined;
508
508
  max_read_bytes?: undefined;
509
509
  cursor?: undefined;
510
510
  } | {
511
+ limit?: undefined;
511
512
  event_id?: undefined;
512
513
  series_id?: undefined;
513
514
  page?: undefined;
@@ -525,11 +526,11 @@ export declare const meetingTools: ({
525
526
  format?: undefined;
526
527
  transcript_id?: undefined;
527
528
  query?: undefined;
528
- limit?: undefined;
529
529
  scan_limit?: undefined;
530
530
  max_read_bytes?: undefined;
531
531
  cursor?: undefined;
532
532
  } | {
533
+ limit?: undefined;
533
534
  event_id?: undefined;
534
535
  series_id?: undefined;
535
536
  page?: undefined;
@@ -551,7 +552,6 @@ export declare const meetingTools: ({
551
552
  minimum: number;
552
553
  };
553
554
  query?: undefined;
554
- limit?: undefined;
555
555
  scan_limit?: undefined;
556
556
  max_read_bytes?: undefined;
557
557
  cursor?: undefined;
@@ -638,6 +638,7 @@ export declare const meetingTools: ({
638
638
  max_read_bytes?: undefined;
639
639
  cursor?: undefined;
640
640
  } | {
641
+ limit?: undefined;
641
642
  event_id?: undefined;
642
643
  series_id?: undefined;
643
644
  page?: undefined;
@@ -653,11 +654,11 @@ export declare const meetingTools: ({
653
654
  format?: undefined;
654
655
  transcript_id?: undefined;
655
656
  query?: undefined;
656
- limit?: undefined;
657
657
  scan_limit?: undefined;
658
658
  max_read_bytes?: undefined;
659
659
  cursor?: undefined;
660
660
  } | {
661
+ limit?: undefined;
661
662
  event_id?: undefined;
662
663
  series_id?: undefined;
663
664
  page?: undefined;
@@ -675,11 +676,11 @@ export declare const meetingTools: ({
675
676
  format?: undefined;
676
677
  transcript_id?: undefined;
677
678
  query?: undefined;
678
- limit?: undefined;
679
679
  scan_limit?: undefined;
680
680
  max_read_bytes?: undefined;
681
681
  cursor?: undefined;
682
682
  } | {
683
+ limit?: undefined;
683
684
  event_id?: undefined;
684
685
  series_id?: undefined;
685
686
  page?: undefined;
@@ -701,7 +702,6 @@ export declare const meetingTools: ({
701
702
  minimum: number;
702
703
  };
703
704
  query?: undefined;
704
- limit?: undefined;
705
705
  scan_limit?: undefined;
706
706
  max_read_bytes?: undefined;
707
707
  cursor?: undefined;
@@ -188,7 +188,7 @@ export { type PackageUpgradeOutcome, type PackageUpgradePorts, type PackageUpgra
188
188
  export { type PersonMeetingContext, type PersonMeetingContextItem, type PersonMeetingContextOptions, type PersonMeetingReadStore, personMeetingContext, } from "./person-meeting-context.js";
189
189
  export { privatePeopleService } from "./private-people.js";
190
190
  export { approveAsTask, type ProposalTaskStore, proposalSource } from "./proposal-tasks.js";
191
- export { type Decided, type Decision, emptyProposalRegistry, FACT_SUMMARIES, type ProposalFilter, type ProposalKind, type ProposalRegistry, type ProposalRow, parseProposalIds, proposalRegistry, } from "./proposals/index.js";
191
+ export { type Decided, type Decision, emptyProposalRegistry, FACT_SUMMARIES, ORGANIZATION_ADD_KIND, type OrganizationProposal, type ProposalFilter, type ProposalKind, type ProposalRegistry, type ProposalRow, parseProposalIds, proposalRegistry, proposeOrganization, } from "./proposals/index.js";
192
192
  export type { RetentionQuery, RetentionService } from "./retention.js";
193
193
  export { retentionService } from "./retention.js";
194
194
  export { RESOURCES_SEARCHED, type SearchAllFound, type SearchAllItem, type SearchAllMessenger, type SearchAllRequest, type SearchedResource, searchAll, } from "./search-all.js";
@@ -146,7 +146,7 @@ export { upgradePackage, } from "./package-upgrade.js";
146
146
  export { personMeetingContext, } from "./person-meeting-context.js";
147
147
  export { privatePeopleService } from "./private-people.js";
148
148
  export { approveAsTask, proposalSource } from "./proposal-tasks.js";
149
- export { emptyProposalRegistry, FACT_SUMMARIES, parseProposalIds, proposalRegistry, } from "./proposals/index.js";
149
+ export { emptyProposalRegistry, FACT_SUMMARIES, ORGANIZATION_ADD_KIND, parseProposalIds, proposalRegistry, proposeOrganization, } from "./proposals/index.js";
150
150
  export { retentionService } from "./retention.js";
151
151
  export { RESOURCES_SEARCHED, searchAll, } from "./search-all.js";
152
152
  export { RESOURCES_SEARCHED_WITH_MEETINGS, searchAllIncludingMeetings, searchAllWithMeetings, } from "./search-all-meetings.js";
@@ -1,4 +1,5 @@
1
1
  export { parseProposalIds } from "./ids.js";
2
2
  export { FACT_SUMMARIES } from "./kinds/findings.js";
3
+ export { ORGANIZATION_ADD_KIND, type OrganizationProposal, proposeOrganization } from "./kinds/organization.js";
3
4
  export { emptyProposalRegistry, proposalRegistry } from "./registry.js";
4
5
  export type { Decided, Decision, ProposalFilter, ProposalKind, ProposalRegistry, ProposalRow } from "./types.js";
@@ -1,3 +1,4 @@
1
1
  export { parseProposalIds } from "./ids.js";
2
2
  export { FACT_SUMMARIES } from "./kinds/findings.js";
3
+ export { ORGANIZATION_ADD_KIND, proposeOrganization } from "./kinds/organization.js";
3
4
  export { emptyProposalRegistry, proposalRegistry } from "./registry.js";
@@ -17,7 +17,7 @@ const summaryOf = (finding) => {
17
17
  case "new_contact":
18
18
  return `${finding.name} <${finding.address}>`;
19
19
  case "invoice":
20
- return words("invoice", finding.number, finding.total, finding.currency, `· ${finding.reason}`);
20
+ return words("invoice", finding.number, finding.total, finding.currency, finding.counterpartyName, `· ${finding.reason}`);
21
21
  case "payment":
22
22
  return words("payment", finding.amount, finding.currency, finding.date, `· ${finding.reason}`);
23
23
  case "order":
@@ -0,0 +1,11 @@
1
+ import type { Author, MessageStore, Organization, ProposedAction } from "../../../store/index.js";
2
+ import type { ProposalKind } from "../types.js";
3
+ export declare const ORGANIZATION_ADD_KIND = "organization_add";
4
+ export interface OrganizationProposal {
5
+ name: string;
6
+ kind: Organization["kind"];
7
+ scope?: Organization["scope"];
8
+ }
9
+ /** An agent's new organization waits as a stored proposal; the organization exists only once it is confirmed. */
10
+ export declare const proposeOrganization: (store: Pick<MessageStore, "proposedActions">, input: OrganizationProposal, by: Author, reason?: string) => Promise<ProposedAction>;
11
+ export declare const organizationKind: (store: Pick<MessageStore, "proposedActions" | "knowledge">) => ProposalKind;
@@ -0,0 +1,53 @@
1
+ import { proposerOfAction } from "../../../store/index.js";
2
+ import { actionStatus, kept, pushed, storedStatus } from "./shared.js";
3
+ export const ORGANIZATION_ADD_KIND = "organization_add";
4
+ const rowOf = (action) => {
5
+ const { name, kind } = action.payload;
6
+ return {
7
+ id: action.id,
8
+ kind: "organization",
9
+ status: actionStatus(action.status),
10
+ project: null,
11
+ subject: `organization:new`,
12
+ object: null,
13
+ summary: `add ${kind} ${name}`,
14
+ proposedBy: proposerOfAction(action),
15
+ reason: action.reason,
16
+ evidence: [],
17
+ score: null,
18
+ signals: null,
19
+ parts: null,
20
+ createdAt: action.createdAt,
21
+ };
22
+ };
23
+ /** An agent's new organization waits as a stored proposal; the organization exists only once it is confirmed. */
24
+ export const proposeOrganization = (store, input, by, reason) => store.proposedActions.propose({
25
+ kind: ORGANIZATION_ADD_KIND,
26
+ by,
27
+ payload: input,
28
+ ...(reason === undefined ? {} : { reason }),
29
+ });
30
+ export const organizationKind = (store) => ({
31
+ kind: "organization",
32
+ stored: [ORGANIZATION_ADD_KIND],
33
+ list: async (filter) => {
34
+ const status = storedStatus(filter);
35
+ const actions = await store.proposedActions.list({
36
+ kinds: [ORGANIZATION_ADD_KIND],
37
+ ...(status === undefined ? {} : { status }),
38
+ ...pushed(filter),
39
+ });
40
+ return kept(actions.map(rowOf), filter);
41
+ },
42
+ get: async (id) => rowOf(await store.proposedActions.get(id)),
43
+ decide: async (id, { confirm, by, reason }) => {
44
+ if (!confirm) {
45
+ await store.proposedActions.reject(id, by, reason);
46
+ return { id, kind: "organization", status: "rejected", made: [] };
47
+ }
48
+ const { name, kind, scope } = (await store.proposedActions.get(id)).payload;
49
+ const made = await store.knowledge.addOrganization({ name, kind, ...(scope === undefined ? {} : { scope }) });
50
+ await store.proposedActions.approve(id, by, { organization: made.ref });
51
+ return { id, kind: "organization", status: "confirmed", made: [made.ref] };
52
+ },
53
+ });
@@ -9,6 +9,7 @@ import { mailFindingsKind } from "./kinds/mail-findings.js";
9
9
  import { meetingFindingsKind } from "./kinds/meeting-findings.js";
10
10
  import { memoryKind } from "./kinds/memory.js";
11
11
  import { orderKind } from "./kinds/orders.js";
12
+ import { organizationKind } from "./kinds/organization.js";
12
13
  import { relationshipKind } from "./kinds/relationship.js";
13
14
  import { relationshipUpdateKind } from "./kinds/relationship-update.js";
14
15
  import { taskCloseKind } from "./kinds/task-close.js";
@@ -134,6 +135,7 @@ export const proposalRegistry = (store) => {
134
135
  invoiceKind(store),
135
136
  paymentKind(store),
136
137
  orderKind(store),
138
+ organizationKind(store),
137
139
  memoryKind(store),
138
140
  findingsKind(store),
139
141
  mailFindingsKind(store),
@@ -16,7 +16,7 @@ export type { CacheDatabase, CacheStatement, OpenDatabase, SqlValue } from "./dr
16
16
  export { PRAGMAS } from "./driver.js";
17
17
  export { EVIDENCE_FINDINGS_KIND, type EvidenceFindingsBatch, type EvidenceFindingsDecider, type EvidenceFindingsReceipt, type EvidenceFindingsStore, validateEvidenceFindings, } from "./evidence-findings.js";
18
18
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
19
- export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsStore } from "./mail-findings.js";
19
+ export { MAIL_FINDINGS_KIND, type MailFindingsBatch, type MailFindingsCheck, type MailFindingsStore, } from "./mail-findings.js";
20
20
  export type { MeetingFindingsBatch, MeetingFindingsStore } from "./meeting-findings.js";
21
21
  export { MIGRATIONS, type Migration, migrate } from "./migrations.js";
22
22
  export { openCache } from "./open.js";
@@ -8,7 +8,7 @@ export { applyDocumentTransfer, previewDocumentTransfer } from "./document-trans
8
8
  export { PRAGMAS } from "./driver.js";
9
9
  export { EVIDENCE_FINDINGS_KIND, validateEvidenceFindings, } from "./evidence-findings.js";
10
10
  export { ORGANIZATIONS_QUERY, organization, PROJECTS_QUERY, project, REMINDERS_QUERY, reminder, } from "./knowledge-query.js";
11
- export { MAIL_FINDINGS_KIND } from "./mail-findings.js";
11
+ export { MAIL_FINDINGS_KIND, } from "./mail-findings.js";
12
12
  export { MIGRATIONS, migrate } from "./migrations.js";
13
13
  export { openCache } from "./open.js";
14
14
  export { storePath } from "./path.js";
@@ -1,4 +1,4 @@
1
- import type { MailFindingsInput } from "../mail/findings.js";
1
+ import type { MailFindingProblem, MailFindingsInput } from "../mail/findings.js";
2
2
  import type { FindingOutcome, FindingsReceipt } from "../meetings/index.js";
3
3
  import type { Decider } from "./decisions.js";
4
4
  import type { AccountKey } from "./types.js";
@@ -23,6 +23,14 @@ export interface MailFindingsBatch {
23
23
  previous: FindingOutcome[];
24
24
  receipt: FindingsReceipt | null;
25
25
  }
26
+ /** What `stage` would do with a batch, found without writing anything. */
27
+ export interface MailFindingsCheck {
28
+ valid: boolean;
29
+ findings: number;
30
+ /** The batch `stage` would give back: an earlier one under this key with this same input, else null. */
31
+ batch: string | null;
32
+ problems: MailFindingProblem[];
33
+ }
26
34
  /**
27
35
  * What an agent read in new mail — tasks, task updates, facts, memories, links, new contacts — cited and staged for
28
36
  * the owner, one batch per mailbox and run. Only the owner decides one: an agent's mail proposal never becomes the
@@ -33,6 +41,14 @@ export interface MailFindingsStore {
33
41
  bot: string;
34
42
  model?: string;
35
43
  }): Promise<MailFindingsBatch>;
44
+ /**
45
+ * Every check `stage` makes, the trial write of each invoice, payment and order included, rolled back: each
46
+ * finding's problem is listed, not only the first. Input is the decoded JSON, before `validateMailFindings`.
47
+ */
48
+ check(account: AccountKey, input: MailFindingsInput, agent: {
49
+ bot: string;
50
+ model?: string;
51
+ }): Promise<MailFindingsCheck>;
36
52
  get(id: string): Promise<MailFindingsBatch>;
37
53
  list(options?: {
38
54
  account?: AccountKey;
@@ -1,10 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { contextEvidenceFingerprint } from "../../context/evidence.js";
3
3
  import { parseLocator } from "../../domain/locator.js";
4
- import { MAIL_FINDINGS_PER_SENDER, mailFindingFingerprint, validateMailFindings, } from "../../mail/findings.js";
4
+ import { checkMailFindings, MAIL_FINDINGS_PER_SENDER, mailFindingFingerprint, mailFindingProblem, validateMailFindings, } from "../../mail/findings.js";
5
+ import { FREE_MAIL } from "../../mail/score.js";
5
6
  import { findingHash } from "../../meetings/index.js";
6
7
  import { assertMayDecide } from "../decisions.js";
7
8
  import { MAIL_FINDINGS_KIND } from "../mail-findings.js";
9
+ import { fold } from "../normalize.js";
8
10
  import { financeOperationsOver } from "./finance.js";
9
11
  import { findingsAgent, findingsCoreOver } from "./findings-core.js";
10
12
  import { authorActor, linkEvidence, memoriesStoreOver } from "./memories.js";
@@ -139,6 +141,52 @@ export const mailFindingsStoreOver = (context) => {
139
141
  }
140
142
  return read;
141
143
  };
144
+ const organizationsOf = (sql, ...params) => [
145
+ ...new Set(database
146
+ .prepare(sql)
147
+ .all(...params)
148
+ .map((row) => Number(row.id))),
149
+ ];
150
+ const BY_ADDRESS = "SELECT o.id FROM organizations o JOIN organization_identities oi ON oi.organization_id = o.id " +
151
+ "JOIN identities i ON i.id = oi.identity_id WHERE o.deleted_at IS NULL AND i.provider = 'email' AND ";
152
+ /**
153
+ * The organization a finding names but does not reference: the one its address belongs to, else the one its
154
+ * company domain belongs to, else the one of exactly this name; else a new company. Its address joins it, so the
155
+ * next mail from it finds it. Only the owner's accept runs this for real; staging runs it and rolls it back.
156
+ */
157
+ const organizationNamed = (name, email) => {
158
+ const domain = email?.split("@")[1];
159
+ let found = email === undefined ? [] : organizationsOf(`${BY_ADDRESS}lower(i.external_id) = ?`, email);
160
+ if (!found.length && domain && !FREE_MAIL.has(domain))
161
+ found = organizationsOf(`${BY_ADDRESS}substr(lower(i.external_id), -length(?)) = ?`, `@${domain}`, `@${domain}`);
162
+ if (!found.length)
163
+ found = database
164
+ .prepare("SELECT id, name FROM organizations WHERE deleted_at IS NULL")
165
+ .all()
166
+ .filter((row) => fold(String(row.name)).trim() === fold(name).trim())
167
+ .map((row) => Number(row.id));
168
+ if (found.length > 1)
169
+ return invalid(`${found.length} organizations match ${name} (${found.map((id) => `organization:${id}`).join(", ")}); ` +
170
+ "name the one meant as a reference", "finance.party");
171
+ const at = now();
172
+ const id = found[0] ??
173
+ Number(database
174
+ .prepare("INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'work', ?, ?) RETURNING id")
175
+ .get(name, at, at)?.id);
176
+ if (email !== undefined) {
177
+ database
178
+ .prepare("INSERT INTO identities (provider, external_id, created_at, updated_at) VALUES ('email', ?, ?, ?) " +
179
+ "ON CONFLICT (provider, external_id) DO NOTHING")
180
+ .run(email, at, at);
181
+ database
182
+ .prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
183
+ "SELECT id, ?, 'mail-finding', 'owner', ?, ? FROM identities WHERE provider = 'email' AND external_id = ? " +
184
+ "ON CONFLICT (identity_id, organization_id) DO NOTHING")
185
+ .run(id, at, at, email);
186
+ }
187
+ return `organization:${id}`;
188
+ };
189
+ const partyOf = (reference, name, email) => reference ?? (name === undefined ? undefined : organizationNamed(name, email));
142
190
  /** The invoice, payment or order an accepted finding records: the owner's own entry, citing the mail it came from. */
143
191
  const entry = (finding, evidence) => {
144
192
  const by = "owner";
@@ -148,7 +196,7 @@ export const mailFindingsStoreOver = (context) => {
148
196
  by,
149
197
  evidence,
150
198
  direction: finding.direction,
151
- counterparty: finding.counterparty,
199
+ counterparty: partyOf(finding.counterparty, finding.counterpartyName, finding.counterpartyEmail),
152
200
  currency: finding.currency,
153
201
  lines: finding.lines,
154
202
  ...(finding.total === undefined ? {} : { total: finding.total }),
@@ -158,22 +206,29 @@ export const mailFindingsStoreOver = (context) => {
158
206
  ...(finding.project === undefined ? {} : { project: finding.project }),
159
207
  });
160
208
  case "payment":
161
- return () => finance.addPayment({
162
- by,
163
- evidence,
164
- direction: finding.direction,
165
- amount: finding.amount,
166
- currency: finding.currency,
167
- date: finding.date,
168
- ...(finding.payer === undefined ? {} : { payer: finding.payer }),
169
- ...(finding.payee === undefined ? {} : { payee: finding.payee }),
170
- ...(finding.reference === undefined ? {} : { reference: finding.reference }),
171
- ...(finding.allocations === undefined ? {} : { allocations: finding.allocations }),
172
- ...(finding.project === undefined ? {} : { project: finding.project }),
173
- });
209
+ return () => {
210
+ const payer = partyOf(finding.payer, finding.payerName, finding.payerEmail);
211
+ const payee = partyOf(finding.payee, finding.payeeName, finding.payeeEmail);
212
+ return finance.addPayment({
213
+ by,
214
+ evidence,
215
+ direction: finding.direction,
216
+ amount: finding.amount,
217
+ currency: finding.currency,
218
+ date: finding.date,
219
+ ...(payer === undefined ? {} : { payer }),
220
+ ...(payee === undefined ? {} : { payee }),
221
+ ...(finding.reference === undefined ? {} : { reference: finding.reference }),
222
+ ...(finding.allocations === undefined ? {} : { allocations: finding.allocations }),
223
+ ...(finding.project === undefined ? {} : { project: finding.project }),
224
+ });
225
+ };
174
226
  case "order": {
175
- const { id: _id, kind: _kind, evidence: _cited, reason: _reason, ...fields } = finding;
176
- return () => orders.add({ ...fields, by, evidence });
227
+ const { id: _id, kind: _kind, evidence: _cited, reason: _reason, customer: given, customerName, customerEmail, ...fields } = finding;
228
+ return () => {
229
+ const customer = partyOf(given, customerName, customerEmail);
230
+ return orders.add({ ...fields, ...(customer === undefined ? {} : { customer }), by, evidence });
231
+ };
177
232
  }
178
233
  default:
179
234
  return undefined;
@@ -197,6 +252,26 @@ export const mailFindingsStoreOver = (context) => {
197
252
  .prepare("SELECT i.id, l.person_id FROM identities i LEFT JOIN identity_links l ON l.identity_id = i.id " +
198
253
  "WHERE i.provider = 'email' AND lower(i.external_id) = ?")
199
254
  .get(address.toLowerCase());
255
+ /** Whether `address` sent or received one of the emails `finding` cites. */
256
+ const inCitedMail = (address, finding, read) => {
257
+ const ids = finding.evidence.map(({ reference }) => Number(read.get(reference)?.id));
258
+ const marks = ids.map(() => "?").join(",");
259
+ return Boolean(database
260
+ .prepare(`SELECT 1 FROM emails WHERE id IN (${marks}) AND lower(from_address) = ? UNION ALL ` +
261
+ `SELECT 1 FROM email_recipients WHERE email_id IN (${marks}) AND lower(address) = ? LIMIT 1`)
262
+ .get(...ids, address, ...ids, address));
263
+ };
264
+ /** A proposed findings batch that already holds this shop's order with this number. */
265
+ const proposedOrder = (supplierName, number) => {
266
+ const shop = fold(supplierName).trim();
267
+ return database
268
+ .prepare("SELECT p.id, json_extract(f.value, '$.supplierName') AS shop FROM proposed_actions p, " +
269
+ "json_each(p.payload, '$.findings') f WHERE p.kind = ? AND p.status = 'proposed' " +
270
+ "AND json_extract(f.value, '$.kind') = 'order' AND trim(json_extract(f.value, '$.number')) = ?")
271
+ .all(MAIL_FINDINGS_KIND, number.trim())
272
+ .filter((row) => fold(String(row.shop)).trim() === shop)
273
+ .map((row) => String(row.id))[0];
274
+ };
200
275
  /** Whatever a finding names must be stored: a task to update, a subject, a link's ends, a contact's address. */
201
276
  const targets = (finding, read) => {
202
277
  const thing = (reference, what) => {
@@ -224,19 +299,27 @@ export const mailFindingsStoreOver = (context) => {
224
299
  case "invoice":
225
300
  case "payment":
226
301
  case "order":
302
+ for (const address of [
303
+ "counterpartyEmail" in finding ? finding.counterpartyEmail : undefined,
304
+ "payerEmail" in finding ? finding.payerEmail : undefined,
305
+ "payeeEmail" in finding ? finding.payeeEmail : undefined,
306
+ "customerEmail" in finding ? finding.customerEmail : undefined,
307
+ ])
308
+ if (address !== undefined && !inCitedMail(address, finding, read))
309
+ return invalid(`${address} neither sent nor received the mail finding ${finding.id} cites`);
310
+ if (finding.kind === "order" && finding.number !== undefined) {
311
+ const waiting = proposedOrder(finding.supplierName, finding.number);
312
+ if (waiting)
313
+ return invalid(`order ${finding.number} from ${finding.supplierName} already waits for the owner in findings batch ` +
314
+ `${waiting}; leave it out, or send an order_update once it is stored and its status changes`, "order.proposed");
315
+ }
227
316
  wouldWrite(entry(finding, finding.evidence.map((one) => one.reference)));
228
317
  return;
229
318
  case "order_update":
230
319
  orderOfShop(context, finding.supplierName, finding.number);
231
320
  return;
232
321
  case "new_contact": {
233
- const ids = finding.evidence.map(({ reference }) => Number(read.get(reference)?.id));
234
- const marks = ids.map(() => "?").join(",");
235
- const named = database
236
- .prepare(`SELECT 1 FROM emails WHERE id IN (${marks}) AND lower(from_address) = ? UNION ALL ` +
237
- `SELECT 1 FROM email_recipients WHERE email_id IN (${marks}) AND lower(address) = ? LIMIT 1`)
238
- .get(...ids, finding.address, ...ids, finding.address);
239
- if (!named)
322
+ if (!inCitedMail(finding.address, finding, read))
240
323
  return invalid(`${finding.address} neither sent nor received the mail finding ${finding.id} cites`);
241
324
  if (!identityOfAddress(finding.address))
242
325
  throw new CliError("not_found", `no stored contact ${finding.address}`);
@@ -317,23 +400,31 @@ export const mailFindingsStoreOver = (context) => {
317
400
  }
318
401
  }
319
402
  };
403
+ /** The batch this agent already staged under the input's key: the same input's, or a refusal for another's. */
404
+ /** `whole` is false for a checked batch that lost findings to their problems: no staged input can equal it. */
405
+ const heldBatch = (account, input, by, whole = true) => {
406
+ const { actor } = authorActor(context, by);
407
+ const held = database
408
+ .prepare("SELECT id FROM proposed_actions WHERE account_id = ? AND kind = ? AND proposed_by_type = ? AND proposed_by_id = ? AND json_extract(payload, '$.key') = ? ORDER BY id LIMIT 1")
409
+ .get(account, MAIL_FINDINGS_KIND, actor.type, actor.id, input.key);
410
+ if (!held)
411
+ return undefined;
412
+ const proposal = load(String(held.id));
413
+ if (!whole || proposal.payload.inputHash !== findingHash({ input, model: by.model ?? null }))
414
+ return invalid(`the findings batch key ${input.key} was already used for different input (batch ${proposal.id}); ` +
415
+ "check a batch with --dry-run before staging it", "mail-findings.key-used");
416
+ return proposal;
417
+ };
320
418
  return {
321
419
  stage: async (key, raw, rawAgent) => {
322
420
  const input = validateMailFindings(raw);
323
421
  const by = findingsAgent(rawAgent);
324
422
  return write(database, () => {
325
423
  const account = mailbox(key);
326
- const { actor } = authorActor(context, by);
327
424
  const inputHash = findingHash({ input, model: by.model ?? null });
328
- const held = database
329
- .prepare("SELECT id FROM proposed_actions WHERE account_id = ? AND kind = ? AND proposed_by_type = ? AND proposed_by_id = ? AND json_extract(payload, '$.key') = ? ORDER BY id LIMIT 1")
330
- .get(account, MAIL_FINDINGS_KIND, actor.type, actor.id, input.key);
331
- if (held) {
332
- const proposal = load(String(held.id));
333
- if (proposal.payload.inputHash !== inputHash)
334
- return invalid("the findings batch key was already used for different input");
335
- return view(proposal);
336
- }
425
+ const held = heldBatch(account, input, by);
426
+ if (held)
427
+ return view(held);
337
428
  const read = cite(input.findings, account);
338
429
  for (const finding of input.findings)
339
430
  targets(finding, read);
@@ -348,6 +439,45 @@ export const mailFindingsStoreOver = (context) => {
348
439
  }));
349
440
  });
350
441
  },
442
+ check: async (key, raw, rawAgent) => {
443
+ const { batch: input, problems } = checkMailFindings(raw);
444
+ const by = findingsAgent(rawAgent);
445
+ const batchProblem = (error) => problems.push(mailFindingProblem(null, error));
446
+ let batch = null;
447
+ // authorActor and the trial writes touch the store; everything here is rolled back.
448
+ wouldWrite(() => {
449
+ const account = mailbox(key);
450
+ try {
451
+ batch = heldBatch(account, input, by, problems.length === 0)?.id ?? null;
452
+ }
453
+ catch (error) {
454
+ batchProblem(error);
455
+ }
456
+ if (batch !== null)
457
+ return;
458
+ const valid = [];
459
+ for (const finding of input.findings) {
460
+ try {
461
+ targets(finding, cite([finding], account));
462
+ valid.push(finding);
463
+ }
464
+ catch (error) {
465
+ problems.push(mailFindingProblem(finding, error));
466
+ }
467
+ }
468
+ try {
469
+ if (valid.length === input.findings.length)
470
+ cite(valid, account);
471
+ const fingerprints = valid.map(mailFindingFingerprint);
472
+ if (new Set(fingerprints).size !== fingerprints.length)
473
+ invalid("the batch contains duplicate findings");
474
+ }
475
+ catch (error) {
476
+ batchProblem(error);
477
+ }
478
+ });
479
+ return { valid: problems.length === 0, findings: raw.findings?.length ?? 0, batch, problems };
480
+ },
351
481
  get: async (id) => view(load(id)),
352
482
  list: async ({ account, status, limit = 20, offset = 0 } = {}) => {
353
483
  if (status !== undefined && status !== "proposed" && status !== "reviewed")