@wirecat/cli-core 0.579.0 → 0.581.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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,45 @@ shape of this file.
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.581.0 — 05.11.2026
11
+
12
+ ### Added
13
+
14
+ - **`review --holder` gives the findings key.** A host that mounts its findings command (`MailMount.findings`)
15
+ gets a `mail-findings.add` step with `key` before the acknowledge step, so an agent copies the key instead of
16
+ building it from the cursor. The text answer names it too.
17
+
18
+ ### Fixed
19
+
20
+ - **A run after `messages reset` can stage its findings.** The reset counts on the mark (`resets`), and the findings
21
+ key of a mark moved back is `<holder>:<through_id>-r<resets>`, such as `mail-triage:277352-r1`. The runs after a
22
+ reset reached the through id of a batch staged before it and were refused (`mail-findings.key-used`), so their
23
+ mark stayed. Keys of marks never moved back keep their shape, and the same review still gives the same key, so
24
+ a retry of one run stages nothing twice.
25
+
26
+ ## 0.580.0 — 05.11.2026
27
+
28
+ ### Added
29
+
30
+ - **`mailFindings.check` tries a whole mail findings batch without staging it.** It makes every check `stage`
31
+ makes, the trial write of each invoice, payment and order included, rolls everything back and answers
32
+ `{ valid, findings, batch, problems }`: one problem per finding that would be refused, with its id, kind, code,
33
+ message and details, and the batch's own problems (`mail-findings.key-used` when the key holds other input). Its
34
+ input is `readMailFindingsJson`, the decoded JSON before validation.
35
+ - **Mail findings name a party the store does not hold yet.** An invoice takes `counterparty_name`, a payment
36
+ `payer_name` and `payee_name`, an order `customer_name`, each with an optional `<party>_email` that sent or
37
+ received a cited email. The owner's accept finds the organization by that address, by its company domain or by
38
+ exact name, or makes a company of that name and joins the address to it; two matches are refused
39
+ (`finance.party`).
40
+
41
+ ### Fixed
42
+
43
+ - **An unknown finding field is named.** The refusal says the field, the finding's id and kind and what that kind
44
+ takes, also in `details` (`fields`, `allowed`, `finding`, `kind`, reason `finding.unknown-field`); it was only
45
+ "unknown mail finding field".
46
+ - **An order is not proposed twice.** Staging an `order` whose shop and number already wait in a proposed mail
47
+ findings batch is refused (`order.proposed`), as one already stored is (`order.duplicate`).
48
+
10
49
  ## 0.579.0 — 05.11.2026
11
50
 
12
51
  ### Added
@@ -2,5 +2,7 @@ import { type MailFindingsInput } from "../mail/findings.js";
2
2
  import { type FindingsInput, type MeetingFindingsInput } from "../meetings/index.js";
3
3
  export declare const parseMeetingFindingsJson: (text: string) => MeetingFindingsInput;
4
4
  export declare const parseEvidenceFindingsJson: (text: string) => FindingsInput;
5
+ /** A mail findings batch as `mail findings add --dry-run` reads it: snake_case JSON, for `mailFindings.check`. */
6
+ export declare const readMailFindingsJson: (text: string) => MailFindingsInput;
5
7
  /** A mail findings batch as `mail findings add` reads it: snake_case JSON, checked for shape before the store. */
6
8
  export declare const parseMailFindingsJson: (text: string) => MailFindingsInput;
@@ -12,6 +12,14 @@ const keys = {
12
12
  due_date: "dueDate",
13
13
  unit_price: "unitPrice",
14
14
  supplier_name: "supplierName",
15
+ counterparty_name: "counterpartyName",
16
+ counterparty_email: "counterpartyEmail",
17
+ payer_name: "payerName",
18
+ payer_email: "payerEmail",
19
+ payee_name: "payeeName",
20
+ payee_email: "payeeEmail",
21
+ customer_name: "customerName",
22
+ customer_email: "customerEmail",
15
23
  order_date: "orderDate",
16
24
  fulfilled_date: "fulfilledDate",
17
25
  external_id: "externalId",
@@ -50,5 +58,7 @@ const parseFindingsJson = (text, label, validate) => {
50
58
  };
51
59
  export const parseMeetingFindingsJson = (text) => parseFindingsJson(text, "meeting findings", validateMeetingFindings);
52
60
  export const parseEvidenceFindingsJson = (text) => parseFindingsJson(text, "evidence findings", validateEvidenceFindings);
61
+ /** A mail findings batch as `mail findings add --dry-run` reads it: snake_case JSON, for `mailFindings.check`. */
62
+ export const readMailFindingsJson = (text) => parseFindingsJson(text, "mail findings", (input) => input);
53
63
  /** A mail findings batch as `mail findings add` reads it: snake_case JSON, checked for shape before the store. */
54
64
  export const parseMailFindingsJson = (text) => parseFindingsJson(text, "mail findings", validateMailFindings);
@@ -75,7 +75,7 @@ export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthori
75
75
  export { type CliEntry, type EntryContext, type EntryIo, openBrowser, startCli } from "./entry.js";
76
76
  export { type AnswerOutput, answerSchema, type Body, type ItemBody, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, type ListBody, type ListInput, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
77
77
  export { withAbort } from "./execution.js";
78
- export { parseEvidenceFindingsJson, parseMailFindingsJson, parseMeetingFindingsJson, } from "./findings-input.js";
78
+ export { parseEvidenceFindingsJson, parseMailFindingsJson, parseMeetingFindingsJson, readMailFindingsJson, } from "./findings-input.js";
79
79
  export { askSetupQuestions, asksAtStart, type FirstRun, type FirstRunIo, setupAtStart, systemLanguage, } from "./first-run.js";
80
80
  export { checkGuide, checkStep, type GuideOptions, type GuideReference, type GuideStep, loadScenarios, MEMO_SCENARIOS, type Scenario, shellProblems, } from "./guide.js";
81
81
  export { type CommandHelp, commandHelp, commandHelpMarkdown, commandHelpText, exampleReport, type NextChoice, nextUsually, } from "./help/command-help.js";
package/dist/cli/index.js CHANGED
@@ -66,7 +66,7 @@ export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthori
66
66
  export { openBrowser, startCli } from "./entry.js";
67
67
  export { answerSchema, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
68
68
  export { withAbort } from "./execution.js";
69
- export { parseEvidenceFindingsJson, parseMailFindingsJson, parseMeetingFindingsJson, } from "./findings-input.js";
69
+ export { parseEvidenceFindingsJson, parseMailFindingsJson, parseMeetingFindingsJson, readMailFindingsJson, } from "./findings-input.js";
70
70
  export { askSetupQuestions, asksAtStart, setupAtStart, systemLanguage, } from "./first-run.js";
71
71
  export { checkGuide, checkStep, loadScenarios, MEMO_SCENARIOS, shellProblems, } from "./guide.js";
72
72
  export { commandHelp, commandHelpMarkdown, commandHelpText, exampleReport, nextUsually, } from "./help/command-help.js";
@@ -5988,7 +5988,9 @@ export declare const ENTITIES: {
5988
5988
  }, undefined>, undefined>;
5989
5989
  readonly kind: v.LiteralSchema<"invoice", undefined>;
5990
5990
  readonly direction: v.PicklistSchema<readonly ["receivable", "payable"], undefined>;
5991
- readonly counterparty: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
5991
+ readonly counterparty: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
5992
+ readonly counterparty_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
5993
+ readonly counterparty_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
5992
5994
  readonly currency: v.StringSchema<undefined>;
5993
5995
  readonly lines: v.ArraySchema<v.StrictObjectSchema<{
5994
5996
  readonly description: v.StringSchema<undefined>;
@@ -6011,7 +6013,11 @@ export declare const ENTITIES: {
6011
6013
  readonly kind: v.LiteralSchema<"payment", undefined>;
6012
6014
  readonly direction: v.PicklistSchema<readonly ["in", "out"], undefined>;
6013
6015
  readonly payer: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
6016
+ readonly payer_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
6017
+ readonly payer_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
6014
6018
  readonly payee: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
6019
+ readonly payee_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
6020
+ readonly payee_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
6015
6021
  readonly amount: v.StringSchema<undefined>;
6016
6022
  readonly currency: v.StringSchema<undefined>;
6017
6023
  readonly date: v.StringSchema<undefined>;
@@ -6031,6 +6037,8 @@ export declare const ENTITIES: {
6031
6037
  readonly kind: v.LiteralSchema<"order", undefined>;
6032
6038
  readonly purpose: v.PicklistSchema<readonly ["personal", "business", "client", "other"], undefined>;
6033
6039
  readonly customer: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
6040
+ readonly customer_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
6041
+ readonly customer_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
6034
6042
  readonly supplier: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
6035
6043
  readonly supplier_name: v.StringSchema<undefined>;
6036
6044
  readonly number: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -93,7 +93,10 @@ export declare const mailFindings: v.StrictObjectSchema<{
93
93
  }, undefined>, undefined>;
94
94
  readonly kind: v.LiteralSchema<"invoice", undefined>;
95
95
  readonly direction: v.PicklistSchema<readonly ["receivable", "payable"], undefined>;
96
- readonly counterparty: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
96
+ readonly counterparty: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
97
+ /** A counterparty the store may not hold yet; the owner's accept finds its organization or makes one. */
98
+ readonly counterparty_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
99
+ readonly counterparty_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
97
100
  readonly currency: v.StringSchema<undefined>;
98
101
  readonly lines: v.ArraySchema<v.StrictObjectSchema<{
99
102
  readonly description: v.StringSchema<undefined>;
@@ -116,7 +119,11 @@ export declare const mailFindings: v.StrictObjectSchema<{
116
119
  readonly kind: v.LiteralSchema<"payment", undefined>;
117
120
  readonly direction: v.PicklistSchema<readonly ["in", "out"], undefined>;
118
121
  readonly payer: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
122
+ readonly payer_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
123
+ readonly payer_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
119
124
  readonly payee: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
125
+ readonly payee_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
126
+ readonly payee_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
120
127
  readonly amount: v.StringSchema<undefined>;
121
128
  readonly currency: v.StringSchema<undefined>;
122
129
  readonly date: v.StringSchema<undefined>;
@@ -136,6 +143,8 @@ export declare const mailFindings: v.StrictObjectSchema<{
136
143
  readonly kind: v.LiteralSchema<"order", undefined>;
137
144
  readonly purpose: v.PicklistSchema<readonly ["personal", "business", "client", "other"], undefined>;
138
145
  readonly customer: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
146
+ readonly customer_name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
147
+ readonly customer_email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
139
148
  readonly supplier: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>, undefined>;
140
149
  readonly supplier_name: v.StringSchema<undefined>;
141
150
  readonly number: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -55,7 +55,10 @@ const finding = v.variant("kind", [
55
55
  ...base,
56
56
  kind: v.literal("invoice"),
57
57
  direction: v.picklist(INVOICE_DIRECTIONS),
58
- counterparty: reference,
58
+ counterparty: v.optional(reference),
59
+ /** A counterparty the store may not hold yet; the owner's accept finds its organization or makes one. */
60
+ counterparty_name: v.optional(text),
61
+ counterparty_email: v.optional(text),
59
62
  currency: text,
60
63
  lines: v.array(v.strictObject({
61
64
  description: text,
@@ -75,7 +78,11 @@ const finding = v.variant("kind", [
75
78
  kind: v.literal("payment"),
76
79
  direction: v.picklist(MONEY_DIRECTIONS),
77
80
  payer: v.optional(reference),
81
+ payer_name: v.optional(text),
82
+ payer_email: v.optional(text),
78
83
  payee: v.optional(reference),
84
+ payee_name: v.optional(text),
85
+ payee_email: v.optional(text),
79
86
  amount: text,
80
87
  currency: text,
81
88
  date: text,
@@ -89,6 +96,8 @@ const finding = v.variant("kind", [
89
96
  kind: v.literal("order"),
90
97
  purpose: v.picklist(ORDER_PURPOSES),
91
98
  customer: v.optional(reference),
99
+ customer_name: v.optional(text),
100
+ customer_email: v.optional(text),
92
101
  supplier: v.optional(reference),
93
102
  supplier_name: text,
94
103
  number: v.optional(text),
@@ -62,6 +62,9 @@ const OTHERS = [
62
62
  validation("mail-findings.partial", "a cited email is not stored whole yet; cite it once it is"),
63
63
  validation("evidence-findings.dedicated-review", "review evidence findings through the dedicated findings command"),
64
64
  validation("mail-findings.dedicated-review", "review mail findings through the dedicated findings command"),
65
+ validation("mail-findings.invalid", "a checked mail findings batch would be refused; details.problems names why, finding by finding"),
66
+ validation("mail-findings.key-used", "the findings batch key was already used for different input"),
67
+ validation("finding.unknown-field", "a finding has a field its kind does not take"),
65
68
  validation("document.changed", "the document changed while it was read; nothing was saved"),
66
69
  ["document.not-imported", "not_found", "the document is not imported in this source account"],
67
70
  ["extraction.invalid-proposals", "invalid_response", "the model's memory proposals could not be used"],
@@ -200,6 +203,7 @@ const OTHERS = [
200
203
  validation("money.currency", "the currency is not one the store keeps money in"),
201
204
  validation("money.quantity", "the quantity is not a decimal above 0"),
202
205
  validation("order.duplicate", "the shop's order with this number is already stored; change its status instead"),
206
+ validation("order.proposed", "the shop's order with this number already waits for the owner in a findings batch"),
203
207
  validation("order.field", "a field of the order is not valid"),
204
208
  validation("order.source-url", "an order's source URL is not an http or https address"),
205
209
  ["order.not-found", "not_found", "no stored order of that shop has that number"],
@@ -15,6 +15,8 @@ export interface MailMount {
15
15
  acknowledge?: string;
16
16
  /** `null`: the host mounts no thread read, so a review offers none. */
17
17
  conversation?: string | null;
18
+ /** The host's command that stages a findings batch with `--key`; `review --holder` then gives that key as a step. */
19
+ findings?: string;
18
20
  /** In snake_case, as a step names it: memo's `source`, with `email:<account>`. */
19
21
  mailbox?: {
20
22
  option: string;
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { defineQuery } from "@wirecat/cli-base/query";
4
- import { defineSteps, stepOf } from "@wirecat/cli-base/standards";
4
+ import { defineSteps, MAX_NEXT_STEPS, stepOf, } from "@wirecat/cli-base/standards";
5
5
  import { Command } from "commander";
6
6
  import { environmentOf, outputFor } from "../../cli/context.js";
7
7
  import { LOCAL_READ } from "../../cli/effects.js";
@@ -36,7 +36,18 @@ export const MAIL_REVIEW_QUERY = defineQuery({
36
36
  /** The mail review's steps where a host mounted them; a host lists them beside its own so its step checks know them. */
37
37
  export const mailReviewSteps = (mount = {}) => {
38
38
  const mailbox = mount.mailbox ? [{ name: mount.mailbox.option, required: true }] : [];
39
+ const findings = mount.findings
40
+ ? [
41
+ {
42
+ id: "mail-findings.add",
43
+ command: mount.findings,
44
+ args: [{ name: "key", required: true }, ...mailbox],
45
+ why: "stage what these emails ask under this key, before acknowledging them",
46
+ },
47
+ ]
48
+ : [];
39
49
  return defineSteps([
50
+ ...findings,
40
51
  {
41
52
  id: "mail-messages.acknowledge",
42
53
  command: mount.acknowledge ?? "messages acknowledge",
@@ -197,7 +208,12 @@ const holderReview = async (command, mail, holder, query) => {
197
208
  const step = stepsFor(mail.mount, mailbox);
198
209
  const answer = reviewAnswer(found, mailbox, true, step);
199
210
  const skipped = Object.entries(read.skipped).filter(([, count]) => count > 0);
200
- answer.next = [...step("mail-messages.acknowledge", { holder, cursor: read.cursor }), ...(answer.next ?? [])];
211
+ const stage = read.findingsKey === undefined ? [] : step("mail-findings.add", { key: read.findingsKey });
212
+ answer.next = [
213
+ ...stage,
214
+ ...step("mail-messages.acknowledge", { holder, cursor: read.cursor }),
215
+ ...(answer.next ?? []),
216
+ ].slice(0, MAX_NEXT_STEPS);
201
217
  answer.missing = [
202
218
  ...(answer.missing ?? []),
203
219
  ...(read.held > 0 ? [{ field: "items", why: `${read.held} partial emails held until they are whole` }] : []),
@@ -217,7 +233,7 @@ const holderReview = async (command, mail, holder, query) => {
217
233
  const output = outputFor(command);
218
234
  renderAnswer(command, output, answer, () => {
219
235
  output.renderer.note(read.mark
220
- ? `${holder}: past ${read.mark.throughId}; acknowledge with --cursor ${read.cursor}${read.more ? "; more after these" : ""}`
236
+ ? `${holder}: past ${read.mark.throughId}; findings key ${read.findingsKey}; acknowledge with --cursor ${read.cursor}${read.more ? "; more after these" : ""}`
221
237
  : `${holder} has no mark yet: it starts from now — acknowledge with --cursor ${read.cursor}`);
222
238
  return emails.map((hit) => `${hitText(hit)}${markText(marks.get(hit.id), hit.excerptOnly)}\n`).join("");
223
239
  });
@@ -45,8 +45,15 @@ export interface MailNewContactFinding extends Cited {
45
45
  export interface MailInvoiceFinding extends Cited {
46
46
  kind: "invoice";
47
47
  direction: (typeof INVOICE_DIRECTIONS)[number];
48
- /** `person:` or `organization:`. */
49
- counterparty: string;
48
+ /** `person:` or `organization:`; or `counterpartyName`, never both. */
49
+ counterparty?: string;
50
+ /**
51
+ * A party the store may not hold yet: on the owner's accept, the organization its `counterpartyEmail` or that
52
+ * address's domain belongs to, else the one of exactly this name, else a new company of this name.
53
+ */
54
+ counterpartyName?: string;
55
+ /** The party's own address, which a cited email was sent from or to. */
56
+ counterpartyEmail?: string;
50
57
  currency: string;
51
58
  lines: {
52
59
  description: string;
@@ -66,8 +73,13 @@ export interface MailInvoiceFinding extends Cited {
66
73
  export interface MailPaymentFinding extends Cited {
67
74
  kind: "payment";
68
75
  direction: (typeof MONEY_DIRECTIONS)[number];
76
+ /** Each party a reference, or a name and an optional address as an invoice's `counterpartyName` is. */
69
77
  payer?: string;
78
+ payerName?: string;
79
+ payerEmail?: string;
70
80
  payee?: string;
81
+ payeeName?: string;
82
+ payeeEmail?: string;
71
83
  amount: string;
72
84
  currency: string;
73
85
  /** `YYYY-MM-DD`. */
@@ -88,6 +100,9 @@ export interface MailOrderFinding extends Cited {
88
100
  purpose: (typeof ORDER_PURPOSES)[number];
89
101
  /** Whom it is for; the owner when left out. */
90
102
  customer?: string;
103
+ /** A customer the store may not hold yet, as an invoice's `counterpartyName` is. */
104
+ customerName?: string;
105
+ customerEmail?: string;
91
106
  supplier?: string;
92
107
  supplierName: string;
93
108
  number?: string;
@@ -116,14 +131,30 @@ export interface MailOrderUpdateFinding extends Cited {
116
131
  export type MailFinding = MailTaskFinding | MailFactFinding | MailTaskUpdateFinding | MailMemoryFinding | MailLinkFinding | MailNewContactFinding | MailInvoiceFinding | MailPaymentFinding | MailOrderFinding | MailOrderUpdateFinding;
117
132
  export interface MailFindingsInput {
118
133
  schemaVersion: 1;
119
- /** `<holder>:<through_id>`: one batch per run of a holder over the mail it was given. */
134
+ /**
135
+ * `<holder>:<through_id>`, with `-r<resets>` after the owner moved the mark back: one batch per run of a holder over
136
+ * the mail it was given. `review --holder` gives it.
137
+ */
120
138
  key: string;
121
139
  extractor: string;
122
140
  findings: MailFinding[];
123
141
  }
142
+ export declare const validateMailFindings: (input: MailFindingsInput) => MailFindingsInput;
143
+ /** Why one finding, or the batch when `finding` is null, would be refused. */
144
+ export interface MailFindingProblem {
145
+ finding: string | null;
146
+ kind: string | null;
147
+ code: string;
148
+ message: string;
149
+ details?: Record<string, unknown>;
150
+ }
151
+ export declare const mailFindingProblem: (raw: unknown, error: unknown) => MailFindingProblem;
124
152
  /**
125
- * The shape of a mail findings batch: 1–30 findings, each citing 1–8 `msg:email/…` references with fingerprints.
126
- * What needs the store — the fingerprints, partial mail, the per-sender cap, the targets — the store checks.
153
+ * `validateMailFindings` finding by finding: the envelope still refuses the whole batch, but a bad finding no longer
154
+ * hides the next one, so `mail findings add --dry-run` names every problem at once.
127
155
  */
128
- export declare const validateMailFindings: (input: MailFindingsInput) => MailFindingsInput;
156
+ export declare const checkMailFindings: (input: MailFindingsInput) => {
157
+ batch: MailFindingsInput;
158
+ problems: MailFindingProblem[];
159
+ };
129
160
  export declare const mailFindingFingerprint: ({ id: _id, ...finding }: MailFinding) => string;
@@ -1,4 +1,4 @@
1
- import { CliError } from "@wirecat/cli-base";
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { EXTERNAL_ID_CHARS, externalIdOf, SOURCE_URL_CHARS, sourceUrlOf } from "../domain/external-links.js";
3
3
  import { INVOICE_DIRECTIONS, MONEY_DIRECTIONS } from "../domain/finance.js";
4
4
  import { MEMORY_KINDS, MEMORY_SCOPES } from "../domain/knowledge.js";
@@ -64,8 +64,21 @@ const one = (raw, ids) => {
64
64
  return validateFinding(raw, RULES, ids);
65
65
  if (raw.kind === "task") {
66
66
  const { externalId, sourceUrl, ...task } = raw;
67
+ let checked;
68
+ try {
69
+ checked = validateFinding(task, RULES, ids);
70
+ }
71
+ catch (error) {
72
+ if (!isCliError(error) || error.details.reason !== "finding.unknown-field")
73
+ throw error;
74
+ const allowed = [...error.details.allowed, "external_id", "source_url"];
75
+ throw new CliError("validation_error", error.message.replace(/; it takes .*$/, `; it takes ${allowed.join(", ")}`), {
76
+ ...error.details,
77
+ allowed,
78
+ });
79
+ }
67
80
  return {
68
- ...validateFinding(task, RULES, ids),
81
+ ...checked,
69
82
  ...optional("externalId", externalId, (value) => {
70
83
  const { provider, id } = externalIdOf(findingText(value, EXTERNAL_ID_CHARS + 40));
71
84
  return `${provider}:${id}`;
@@ -81,6 +94,22 @@ const one = (raw, ids) => {
81
94
  return invalid(`${what} is not a reference of the kind it takes: ${text}`);
82
95
  return text;
83
96
  };
97
+ /** A party as a `person:`/`organization:` reference, or as `<field>_name` with an optional `<field>_email`. */
98
+ const party = (field, what) => {
99
+ const [given, name, email] = [raw[field], raw[`${field}Name`], raw[`${field}Email`]];
100
+ if (given !== undefined && name !== undefined)
101
+ return invalid(`${what} is ${field} or ${field}_name, not both`);
102
+ if (email !== undefined && name === undefined)
103
+ return invalid(`${field}_email comes with ${field}_name`);
104
+ return {
105
+ ...optional(field, given, (value) => reference(value, PARTY, what)),
106
+ ...optional(`${field}Name`, name, (value) => word(value, 200)),
107
+ ...optional(`${field}Email`, email, (value) => {
108
+ const address = findingText(value, 320).toLowerCase();
109
+ return ADDRESS.test(address) ? address : invalid(`${field}_email is an email address`);
110
+ }),
111
+ };
112
+ };
84
113
  switch (raw.kind) {
85
114
  case "task_update": {
86
115
  findingFields(raw, ["id", "kind", "task", "change", "dueAt", "detail", "reason", "evidence"], RULES.singular);
@@ -155,6 +184,8 @@ const one = (raw, ids) => {
155
184
  "kind",
156
185
  "direction",
157
186
  "counterparty",
187
+ "counterpartyName",
188
+ "counterpartyEmail",
158
189
  "currency",
159
190
  "lines",
160
191
  "total",
@@ -171,7 +202,7 @@ const one = (raw, ids) => {
171
202
  if (!line || typeof line !== "object")
172
203
  return invalid("an invoice line is an object");
173
204
  const fields = line;
174
- findingFields(fields, ["description", "quantity", "unitPrice", "amount"], "invoice line");
205
+ findingFields(fields, ["description", "quantity", "unitPrice", "amount"], "invoice line", raw);
175
206
  return {
176
207
  description: word(fields.description, 500),
177
208
  ...optional("quantity", fields.quantity, (value) => word(value, 20)),
@@ -183,7 +214,9 @@ const one = (raw, ids) => {
183
214
  id,
184
215
  kind: "invoice",
185
216
  direction: oneOf(raw.direction, INVOICE_DIRECTIONS, "an invoice's direction"),
186
- counterparty: reference(raw.counterparty, PARTY, "an invoice's counterparty"),
217
+ ...(raw.counterparty === undefined && raw.counterpartyName === undefined
218
+ ? invalid("an invoice names its counterparty: counterparty person:N|organization:N, or counterparty_name")
219
+ : party("counterparty", "an invoice's counterparty")),
187
220
  currency: word(raw.currency, 3),
188
221
  lines,
189
222
  ...optional("total", raw.total, (value) => word(value, 30)),
@@ -201,7 +234,11 @@ const one = (raw, ids) => {
201
234
  "kind",
202
235
  "direction",
203
236
  "payer",
237
+ "payerName",
238
+ "payerEmail",
204
239
  "payee",
240
+ "payeeName",
241
+ "payeeEmail",
205
242
  "amount",
206
243
  "currency",
207
244
  "date",
@@ -219,7 +256,7 @@ const one = (raw, ids) => {
219
256
  if (!share || typeof share !== "object")
220
257
  return invalid("an allocation is an invoice and an amount");
221
258
  const fields = share;
222
- findingFields(fields, ["invoice", "amount"], "allocation");
259
+ findingFields(fields, ["invoice", "amount"], "allocation", raw);
223
260
  return {
224
261
  invoice: reference(fields.invoice, INVOICE, "an allocation's invoice"),
225
262
  amount: word(fields.amount, 30),
@@ -230,8 +267,8 @@ const one = (raw, ids) => {
230
267
  id,
231
268
  kind: "payment",
232
269
  direction: oneOf(raw.direction, MONEY_DIRECTIONS, "a payment's direction"),
233
- ...optional("payer", raw.payer, (value) => reference(value, PARTY, "a payment's payer")),
234
- ...optional("payee", raw.payee, (value) => reference(value, PARTY, "a payment's payee")),
270
+ ...party("payer", "a payment's payer"),
271
+ ...party("payee", "a payment's payee"),
235
272
  amount: word(raw.amount, 30),
236
273
  currency: word(raw.currency, 3),
237
274
  date: word(raw.date, 10),
@@ -248,6 +285,8 @@ const one = (raw, ids) => {
248
285
  "kind",
249
286
  "purpose",
250
287
  "customer",
288
+ "customerName",
289
+ "customerEmail",
251
290
  "supplier",
252
291
  "supplierName",
253
292
  "number",
@@ -267,7 +306,7 @@ const one = (raw, ids) => {
267
306
  id,
268
307
  kind: "order",
269
308
  purpose: oneOf(raw.purpose, ORDER_PURPOSES, "an order's purpose"),
270
- ...optional("customer", raw.customer, (value) => reference(value, PARTY, "an order's customer")),
309
+ ...party("customer", "an order's customer"),
271
310
  ...optional("supplier", raw.supplier, (value) => reference(value, PARTY, "an order's supplier")),
272
311
  supplierName: word(raw.supplierName, 200),
273
312
  ...optional("number", raw.number, (value) => word(value, 80)),
@@ -308,10 +347,48 @@ const one = (raw, ids) => {
308
347
  * The shape of a mail findings batch: 1–30 findings, each citing 1–8 `msg:email/…` references with fingerprints.
309
348
  * What needs the store — the fingerprints, partial mail, the per-sender cap, the targets — the store checks.
310
349
  */
350
+ const KEY = /^[a-z0-9][a-z0-9-]{0,39}:[1-9]\d*(-r[1-9]\d*)?$/;
351
+ const KEY_SHAPE = "a mail findings key is the one `review --holder` gave: <holder>:<through_id>, and -r<resets> after a reset, " +
352
+ "such as mail-triage:9123456 or mail-triage:9123456-r1";
311
353
  export const validateMailFindings = (input) => {
312
354
  const batch = validateBatch(input, RULES, MAIL_FINDINGS_PER_RUN, one);
313
- if (!/^[a-z0-9][a-z0-9-]{0,39}:[1-9]\d*$/.test(batch.key))
314
- return invalid("a mail findings key is <holder>:<through_id>, such as mail-triage:9123456");
355
+ if (!KEY.test(batch.key))
356
+ return invalid(KEY_SHAPE);
315
357
  return batch;
316
358
  };
359
+ export const mailFindingProblem = (raw, error) => {
360
+ if (!isCliError(error))
361
+ throw error;
362
+ const fields = raw && typeof raw === "object" ? raw : {};
363
+ const details = Object.fromEntries(Object.entries(error.details).filter(([key]) => key !== "finding" && key !== "kind"));
364
+ return {
365
+ finding: typeof fields.id === "string" ? fields.id : null,
366
+ kind: typeof fields.kind === "string" ? fields.kind : null,
367
+ code: error.code,
368
+ message: error.message,
369
+ ...(Object.keys(details).length ? { details } : {}),
370
+ };
371
+ };
372
+ /**
373
+ * `validateMailFindings` finding by finding: the envelope still refuses the whole batch, but a bad finding no longer
374
+ * hides the next one, so `mail findings add --dry-run` names every problem at once.
375
+ */
376
+ export const checkMailFindings = (input) => {
377
+ const problems = [];
378
+ const batch = validateBatch(input, RULES, MAIL_FINDINGS_PER_RUN, (finding, ids) => {
379
+ try {
380
+ return one(finding, ids);
381
+ }
382
+ catch (error) {
383
+ problems.push(mailFindingProblem(finding, error));
384
+ return undefined;
385
+ }
386
+ });
387
+ if (!KEY.test(batch.key))
388
+ problems.push({ finding: null, kind: null, code: "validation_error", message: KEY_SHAPE });
389
+ return {
390
+ batch: { ...batch, findings: batch.findings.filter((one) => one !== undefined) },
391
+ problems,
392
+ };
393
+ };
317
394
  export const mailFindingFingerprint = ({ id: _id, ...finding }) => findingHash(finding);
@@ -22,6 +22,8 @@ export interface MailMark {
22
22
  suspicious: number[];
23
23
  read: number;
24
24
  skipped: Record<SkipReason, number>;
25
+ /** How often the owner moved the mark back: a findings key names it, so a run after a reset never reuses one. */
26
+ resets: number;
25
27
  /** ms. */
26
28
  updatedAt: number;
27
29
  }
@@ -30,6 +32,12 @@ export declare const markOf: (store: MessageStore, mailbox: AccountKey, holder:
30
32
  export declare const marksOf: (store: MessageStore, mailbox: AccountKey) => Promise<MailMark[]>;
31
33
  /** The mark's state, as a cursor `acknowledge` takes back: the last id read, and when it was read. */
32
34
  export declare const cursorOf: (throughId: number, readAt: number) => string;
35
+ /**
36
+ * The findings key of one run: `<holder>:<through_id>`, and `-r<resets>` once the owner moved the mark back, so the
37
+ * runs after a reset never reach a key a batch staged before it holds. The same review gives the same key: a retry
38
+ * of one run stages nothing twice.
39
+ */
40
+ export declare const findingsKeyOf: (holder: string, throughId: number, resets: number) => string;
33
41
  /** A bulk email that is not surely a newsletter: the holder gets its subject and first lines only. */
34
42
  export interface BulkExcerpt {
35
43
  email: StoredHit;
@@ -45,6 +53,8 @@ export interface MarkRead {
45
53
  excerpts: BulkExcerpt[];
46
54
  /** What `acknowledge --cursor` takes once the holder is done with these. */
47
55
  cursor: string;
56
+ /** The key a findings batch over these emails takes; `undefined` while nothing is stored to read. */
57
+ findingsKey: string | undefined;
48
58
  /** More is stored after this batch: read again after acknowledging. */
49
59
  more: boolean;
50
60
  held: number;
@@ -39,6 +39,7 @@ const parsed = (holder, value, at) => {
39
39
  suspicious: Array.isArray(saved.suspicious) ? saved.suspicious.filter((id) => typeof id === "number") : [],
40
40
  read: saved.read ?? 0,
41
41
  skipped: { ...noneSkipped(), ...saved.skipped },
42
+ resets: typeof saved.resets === "number" ? saved.resets : 0,
42
43
  updatedAt: at,
43
44
  };
44
45
  }
@@ -80,6 +81,12 @@ const verdict = (email, now) => {
80
81
  };
81
82
  /** The mark's state, as a cursor `acknowledge` takes back: the last id read, and when it was read. */
82
83
  export const cursorOf = (throughId, readAt) => `${throughId}.${readAt}`;
84
+ /**
85
+ * The findings key of one run: `<holder>:<through_id>`, and `-r<resets>` once the owner moved the mark back, so the
86
+ * runs after a reset never reach a key a batch staged before it holds. The same review gives the same key: a retry
87
+ * of one run stages nothing twice.
88
+ */
89
+ export const findingsKeyOf = (holder, throughId, resets) => `${holder}:${throughId}${resets > 0 ? `-r${resets}` : ""}`;
83
90
  const parseCursor = (cursor) => {
84
91
  const match = /^(\d+)\.(\d+)$/.exec(cursor.trim());
85
92
  if (!match)
@@ -140,10 +147,14 @@ const examine = async (store, mailbox, holder, { now = Date.now(), limit = MARK_
140
147
  skipped: noneSkipped(),
141
148
  mark: saved,
142
149
  };
150
+ const keyed = (throughId) => ({
151
+ cursor: cursorOf(throughId, now),
152
+ findingsKey: throughId > 0 ? findingsKeyOf(holder, throughId, saved?.resets ?? 0) : undefined,
153
+ });
143
154
  if (!account)
144
- return { ...empty, cursor: cursorOf(0, now) };
155
+ return { ...empty, ...keyed(0) };
145
156
  if (!saved)
146
- return { ...empty, cursor: cursorOf(await store.mail.newestEmailId(account.id), now) };
157
+ return { ...empty, ...keyed(await store.mail.newestEmailId(account.id)) };
147
158
  const mark = after === undefined ? saved : { ...saved, throughId: after, held: [], suspicious: [] };
148
159
  const found = await store.mail.emailsAfter(account.id, mark.throughId, limit + 1, [...mark.held, ...mark.suspicious]);
149
160
  // Mail a running sync stored is read once that sync ended: it files bulk mail only at its end.
@@ -179,7 +190,7 @@ const examine = async (store, mailbox, holder, { now = Date.now(), limit = MARK_
179
190
  wanted: wanted.sort((a, b) => a - b),
180
191
  sorted: new Map([...sorted].filter(([, one]) => one.verdict === "excerpt")),
181
192
  oldestStoredAt,
182
- cursor: cursorOf(batch.at(-1)?.id ?? mark.throughId, now),
193
+ ...keyed(batch.at(-1)?.id ?? mark.throughId),
183
194
  more: newer.length > batch.length,
184
195
  held,
185
196
  skipped,
@@ -312,6 +323,7 @@ export const acknowledgeMark = async (store, mailbox, holder, cursor, now = Date
312
323
  suspicious: [...new Set(suspicious)].sort((a, b) => a - b).slice(-MOST_HELD),
313
324
  read,
314
325
  skipped,
326
+ resets: mark?.resets ?? 0,
315
327
  };
316
328
  await store.sync.setSyncState(mailbox, key, JSON.stringify(next));
317
329
  return { holder, ...next, updatedAt: now };
@@ -397,6 +409,7 @@ export const rewindMark = async (store, mailbox, holder, to, { now = Date.now(),
397
409
  suspicious: mark.suspicious.filter((id) => id <= through),
398
410
  read: mark.read,
399
411
  skipped: mark.skipped,
412
+ resets: mark.resets + 1,
400
413
  };
401
414
  if (!dry)
402
415
  await store.sync.setSyncState(mailbox, key, JSON.stringify(next));
@@ -65,7 +65,14 @@ export interface FindingsReceipt {
65
65
  }
66
66
  export declare const findingText: (value: unknown, limit: number) => string;
67
67
  export declare const findingHash: (value: unknown) => string;
68
- export declare const findingFields: (value: object, allowed: string[], noun: string) => void;
68
+ /**
69
+ * Refuses a field `allowed` does not list, naming it, the finding it is in and what that kind takes: an agent fixes
70
+ * the batch from the message alone. `of` is the finding a nested object (an invoice line) belongs to.
71
+ */
72
+ export declare const findingFields: (value: object, allowed: string[], noun: string, of?: {
73
+ id?: unknown;
74
+ kind?: unknown;
75
+ }) => void;
69
76
  /** What differs between findings kinds: their wording and what one cited reference must look like. */
70
77
  export interface FindingsRules {
71
78
  /** "meeting findings" */
@@ -12,9 +12,27 @@ export const findingText = (value, limit) => {
12
12
  return value.trim();
13
13
  };
14
14
  export const findingHash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
15
- export const findingFields = (value, allowed, noun) => {
16
- if (Object.keys(value).some((key) => !allowed.includes(key)))
17
- invalid(`unknown ${noun} field`);
15
+ const snakeCase = (key) => key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
16
+ /**
17
+ * Refuses a field `allowed` does not list, naming it, the finding it is in and what that kind takes: an agent fixes
18
+ * the batch from the message alone. `of` is the finding a nested object (an invoice line) belongs to.
19
+ */
20
+ export const findingFields = (value, allowed, noun, of = value) => {
21
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
22
+ if (!unknown.length)
23
+ return;
24
+ const fields = unknown.map(snakeCase);
25
+ const takes = allowed.map(snakeCase);
26
+ const id = typeof of.id === "string" ? of.id : null;
27
+ const kind = typeof of.kind === "string" ? of.kind : null;
28
+ const where = id || kind ? ` in ${[id, kind && `(${kind})`].filter(Boolean).join(" ")}` : "";
29
+ throw new CliError("validation_error", `unknown ${noun} field${fields.length > 1 ? "s" : ""} ${fields.join(", ")}${where}; it takes ${takes.join(", ")}`, {
30
+ reason: "finding.unknown-field",
31
+ fields,
32
+ allowed: takes,
33
+ ...(id ? { finding: id } : {}),
34
+ ...(kind ? { kind } : {}),
35
+ });
18
36
  };
19
37
  const SUBJECT = /^(person|organization|project):[1-9]\d*$|^task:[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
20
38
  /** A finding's cited evidence: 1–8 distinct references in `rules`' form, each with a 64-hex fingerprint. */
@@ -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":
@@ -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")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.579.0",
3
+ "version": "0.581.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",