@wirecat/cli-core 0.604.0 → 0.606.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 +159 -0
- package/dist/calendar/prepare.d.ts +4 -2
- package/dist/calendar/prepare.js +8 -8
- package/dist/cli/index.d.ts +2 -2
- package/dist/cli/index.js +2 -1
- package/dist/cli/messenger/contacts-command.js +3 -2
- package/dist/cli/messenger/doctor-command.js +14 -7
- package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
- package/dist/cli/messenger/store-maintenance-command.js +31 -4
- package/dist/cli/program.js +11 -2
- package/dist/cli/steps.js +9 -1
- package/dist/cli/store-recover.d.ts +10 -2
- package/dist/cli/store-recover.js +18 -4
- package/dist/cli/store-settings.js +38 -4
- package/dist/crm/cli/index.js +3 -1
- package/dist/crm/index.d.ts +2 -2
- package/dist/crm/index.js +1 -1
- package/dist/crm/source.d.ts +35 -5
- package/dist/crm/sync.d.ts +15 -7
- package/dist/crm/sync.js +169 -11
- package/dist/domain/crm.d.ts +41 -2
- package/dist/domain/deals.d.ts +5 -2
- package/dist/domain/deals.js +5 -2
- package/dist/domain/record-types.d.ts +61 -0
- package/dist/domain/record-types.js +26 -0
- package/dist/domain/records.d.ts +3 -5
- package/dist/domain/records.js +10 -13
- package/dist/domain/relations.d.ts +125 -0
- package/dist/domain/relations.js +107 -0
- package/dist/entities/contact-activity.d.ts +4 -0
- package/dist/entities/contact-activity.js +1 -0
- package/dist/entities/contact-context.d.ts +20 -0
- package/dist/entities/contact-context.js +2 -0
- package/dist/entities/deal.d.ts +2 -2
- package/dist/entities/deal.js +2 -1
- package/dist/entities/index.d.ts +39 -13
- package/dist/entities/relationship.d.ts +8 -2
- package/dist/entities/relationship.js +8 -2
- package/dist/entities/task-results.d.ts +10 -10
- package/dist/errors/failures.d.ts +17 -1
- package/dist/errors/failures.js +57 -1
- package/dist/errors/reasons.js +28 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/mail/cli/review.js +20 -6
- package/dist/mail/index.d.ts +1 -1
- package/dist/mail/marks.d.ts +10 -5
- package/dist/mail/marks.js +16 -8
- package/dist/mail/review.d.ts +5 -0
- package/dist/mcp/tool.js +2 -1
- package/dist/runs/recording.js +13 -4
- package/dist/services/deps.js +4 -6
- package/dist/services/index.d.ts +1 -1
- package/dist/services/link-scorers/chat-senders.d.ts +3 -2
- package/dist/services/link-scorers/chat-senders.js +7 -4
- package/dist/services/link-scorers/mail-thread.js +1 -0
- package/dist/services/link-scorers/member-chats.js +1 -0
- package/dist/services/link-scorers/member-dialog.d.ts +1 -1
- package/dist/services/link-scorers/member-dialog.js +4 -3
- package/dist/services/link-scorers/scan.d.ts +5 -2
- package/dist/services/link-scorers/scan.js +100 -54
- package/dist/services/link-scorers/shared.d.ts +2 -2
- package/dist/services/link-scorers/shared.js +8 -4
- package/dist/services/link-scorers/types.d.ts +3 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/person-context.d.ts +24 -7
- package/dist/services/person-context.js +45 -11
- package/dist/services/person-preparation.js +4 -5
- package/dist/services/project-status/index.js +2 -1
- package/dist/services/stored-project-gathering.js +4 -3
- package/dist/store/damage.d.ts +3 -1
- package/dist/store/damage.js +19 -12
- package/dist/store/document-transfer/index.js +7 -0
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/index.d.ts +7 -1
- package/dist/store/index.js +2 -0
- package/dist/store/marks.d.ts +57 -0
- package/dist/store/marks.js +121 -0
- package/dist/store/project-transfer/preview.js +12 -7
- package/dist/store/project-transfer/request.d.ts +4 -1
- package/dist/store/project-transfer/schema.d.ts +9 -2
- package/dist/store/project-transfer/schema.js +4 -0
- package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
- package/dist/store/recover.js +16 -1
- package/dist/store/sqlite/crm-settings.d.ts +28 -0
- package/dist/store/sqlite/crm-settings.js +80 -0
- package/dist/store/sqlite/crm.d.ts +42 -2
- package/dist/store/sqlite/crm.js +397 -36
- package/dist/store/sqlite/deals.js +3 -2
- package/dist/store/sqlite/finance.d.ts +8 -1
- package/dist/store/sqlite/finance.js +10 -3
- package/dist/store/sqlite/involvement-queue.js +4 -3
- package/dist/store/sqlite/knowledge.d.ts +7 -3
- package/dist/store/sqlite/knowledge.js +43 -31
- package/dist/store/sqlite/link-kinds.d.ts +2 -3
- package/dist/store/sqlite/link-kinds.js +4 -2
- package/dist/store/sqlite/manifest.js +5 -0
- package/dist/store/sqlite/memories.d.ts +1 -1
- package/dist/store/sqlite/memories.js +33 -7
- package/dist/store/sqlite/migrations.generated.js +31 -0
- package/dist/store/sqlite/notes.d.ts +3 -2
- package/dist/store/sqlite/notes.js +23 -6
- package/dist/store/sqlite/open-store.js +4 -1
- package/dist/store/sqlite/organizations.d.ts +8 -0
- package/dist/store/sqlite/organizations.js +14 -0
- package/dist/store/sqlite/own-identities.d.ts +1 -1
- package/dist/store/sqlite/own-identities.js +7 -5
- package/dist/store/sqlite/person-links.d.ts +5 -2
- package/dist/store/sqlite/person-links.js +24 -18
- package/dist/store/sqlite/person-preparation.d.ts +1 -1
- package/dist/store/sqlite/person-preparation.js +3 -2
- package/dist/store/sqlite/person-separation.d.ts +5 -0
- package/dist/store/sqlite/person-separation.js +26 -0
- package/dist/store/sqlite/project-transfer/records.js +14 -3
- package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
- package/dist/store/sqlite/record-projectors.d.ts +44 -0
- package/dist/store/sqlite/record-projectors.js +72 -0
- package/dist/store/sqlite/records.js +12 -70
- package/dist/store/sqlite/relation-list.d.ts +43 -0
- package/dist/store/sqlite/relation-list.js +133 -0
- package/dist/store/sqlite/relation-proposals.d.ts +28 -6
- package/dist/store/sqlite/relation-proposals.js +134 -10
- package/dist/store/sqlite/relation-reads.d.ts +8 -0
- package/dist/store/sqlite/relation-reads.js +7 -0
- package/dist/store/sqlite/relation-roles.d.ts +26 -0
- package/dist/store/sqlite/relation-roles.js +91 -0
- package/dist/store/sqlite/reported-relations.d.ts +63 -0
- package/dist/store/sqlite/reported-relations.js +132 -0
- package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
- package/dist/store/sqlite/schema/link-revisions.js +11 -0
- package/dist/store/sqlite/schema/links.d.ts +360 -0
- package/dist/store/sqlite/schema/links.js +32 -0
- package/dist/store/sqlite/schema.d.ts +2 -296
- package/dist/store/sqlite/schema.js +2 -24
- package/dist/store/sqlite/transaction.js +2 -5
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/dist/store/types.d.ts +5 -0
- package/package.json +5 -5
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { usableLinkSql } from "../../domain/relations.js";
|
|
2
3
|
/** One SELECT per way of taking part: the subject's kind, the column that holds its id, and the query. */
|
|
3
4
|
const ARMS = [
|
|
4
5
|
[
|
|
@@ -79,8 +80,8 @@ const ARMS = [
|
|
|
79
80
|
const linkArm = (linkFrom, linkTo) => `
|
|
80
81
|
SELECT CASE WHEN l.to_type='person' THEN l.to_id ELSE il.person_id END AS person_id, CASE WHEN l.to_type='identity' THEN l.to_id END AS identity_id, l.from_type AS subject_type, l.from_id AS subject_id, coalesce(l.role,'linked') AS role, l.created_at AS occurred_at,
|
|
81
82
|
coalesce(c.scope,a.scope,p.scope,'personal') AS scope, coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id) AS account_id, p.id AS project_id
|
|
82
|
-
FROM (SELECT from_type,from_id,to_type,to_id,role,created_at,confirmed FROM links WHERE ${linkFrom}
|
|
83
|
-
UNION ALL SELECT to_type,to_id,from_type,from_id,role,created_at,confirmed FROM links WHERE from_type IN ('person','identity') AND to_id IS NOT NULL AND ${linkTo}) l
|
|
83
|
+
FROM (SELECT from_type,from_id,to_type,to_id,role,created_at,confirmed,account_id,deleted_at FROM links WHERE ${linkFrom}
|
|
84
|
+
UNION ALL SELECT to_type,to_id,from_type,from_id,role,created_at,confirmed,account_id,deleted_at FROM links WHERE from_type IN ('person','identity') AND to_id IS NOT NULL AND ${linkTo}) l
|
|
84
85
|
LEFT JOIN identity_links il ON l.to_type='identity' AND il.identity_id=l.to_id
|
|
85
86
|
LEFT JOIN messages m ON l.from_type='message' AND m.id=l.from_id
|
|
86
87
|
LEFT JOIN chats c ON c.id=CASE WHEN l.from_type='chat' THEN l.from_id ELSE m.chat_id END
|
|
@@ -90,7 +91,7 @@ const linkArm = (linkFrom, linkTo) => `
|
|
|
90
91
|
LEFT JOIN tasks t ON l.from_type='task' AND t.id=l.from_id
|
|
91
92
|
LEFT JOIN projects p ON p.id=CASE WHEN l.from_type='project' THEN l.from_id ELSE t.project_id END
|
|
92
93
|
LEFT JOIN accounts a ON a.id=coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id)
|
|
93
|
-
WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND l
|
|
94
|
+
WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND ${usableLinkSql("l")} AND (l.from_type<>'message' OR m.deleted_at IS NULL) AND (l.from_type<>'email' OR e.deleted_at IS NULL) AND (l.from_type<>'meeting' OR mt.deleted_at IS NULL) AND (l.from_type<>'task' OR t.deleted_at IS NULL) AND (l.from_type<>'document' OR d.deleted_at IS NULL)
|
|
94
95
|
`;
|
|
95
96
|
/**
|
|
96
97
|
* Every way of taking part, or only the ones about `subject`, each filtered by its own key so SQLite reads
|
|
@@ -8,6 +8,7 @@ import type { StoreContext } from "./open.js";
|
|
|
8
8
|
import { type OrganizationsStore } from "./organizations.js";
|
|
9
9
|
import type { ProposedAction } from "./proposed-actions.js";
|
|
10
10
|
import { type KnowledgeRelation, type LinkDecision, type RelateInput, type RelationUpdate, type Scored } from "./relation-proposals.js";
|
|
11
|
+
import { type RelationReads } from "./relation-reads.js";
|
|
11
12
|
import type { TagCreationOptions } from "./tag-creation.js";
|
|
12
13
|
import { type Label, type TagKind, type TagRow } from "./tags.js";
|
|
13
14
|
import { type ThingState } from "./things.js";
|
|
@@ -101,7 +102,7 @@ export interface Reminder {
|
|
|
101
102
|
receipt: string | null;
|
|
102
103
|
}
|
|
103
104
|
export type LabelledType = "note" | "document" | "person" | "organization" | "project" | "task" | "meeting" | "folder";
|
|
104
|
-
export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, OrganizationsStore {
|
|
105
|
+
export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, OrganizationsStore, RelationReads {
|
|
105
106
|
taskIds(key: AccountKey, options?: {
|
|
106
107
|
state?: "open" | "done" | "dismissed";
|
|
107
108
|
limit?: number;
|
|
@@ -214,6 +215,9 @@ export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, O
|
|
|
214
215
|
by: Exclude<Author, "owner">;
|
|
215
216
|
reason?: string;
|
|
216
217
|
}): Promise<ProposedAction>;
|
|
218
|
+
/** Ends it at `at` (UTC ms) without removing it; an agent's end is a `relationship_update` proposal. */
|
|
219
|
+
endRelation(key: KnowledgeScope, id: string, at: number, by: "owner"): Promise<KnowledgeRelation>;
|
|
220
|
+
endRelation(key: KnowledgeScope, id: string, at: number, by: Exclude<Author, "owner">): Promise<ProposedAction>;
|
|
217
221
|
/** Decides a `relationship_update` proposal; a confirmed one changes the relationship in the same transaction. */
|
|
218
222
|
decideRelationUpdate(id: string, decision: LinkDecision): Promise<{
|
|
219
223
|
proposal: ProposedAction;
|
|
@@ -228,8 +232,8 @@ export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, O
|
|
|
228
232
|
decideSuggestedLink(id: string, decision: LinkDecision): Promise<Link | null>;
|
|
229
233
|
relations(key: KnowledgeScope, reference?: string): Promise<KnowledgeRelation[]>;
|
|
230
234
|
/**
|
|
231
|
-
* Removing an unconfirmed relationship rejects it, so `by` must be allowed to decide it.
|
|
232
|
-
*
|
|
235
|
+
* Removing an unconfirmed relationship rejects it, so `by` must be allowed to decide it. Every removal leaves a
|
|
236
|
+
* rejected `relationship` proposal, so neither a scan nor a source's sync brings the pair back.
|
|
233
237
|
*/
|
|
234
238
|
removeRelation(key: KnowledgeScope, id: string, by: Decider): Promise<{
|
|
235
239
|
id: string;
|
|
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
2
2
|
import { walkQuery } from "@wirecat/cli-base/query";
|
|
3
3
|
import { parseLocator } from "../../domain/locator.js";
|
|
4
4
|
import { formatReference, parseReference } from "../../domain/references.js";
|
|
5
|
+
import { checkEnds, isSymmetric, notOverriddenSql } from "../../domain/relations.js";
|
|
5
6
|
import { normalizeTag } from "../../domain/tags.js";
|
|
6
7
|
import { normalizeVocabularyName } from "../../domain/vocabulary.js";
|
|
7
8
|
import { formatMeetingReference } from "../../meetings/index.js";
|
|
@@ -16,7 +17,8 @@ import { holdingText } from "./note-index.js";
|
|
|
16
17
|
import { insertLink, linkOf } from "./notes.js";
|
|
17
18
|
import { organizationOf, organizationsStoreOver } from "./organizations.js";
|
|
18
19
|
import { queryFilter } from "./query-filter.js";
|
|
19
|
-
import { relationOf, relationProposalsOver, } from "./relation-proposals.js";
|
|
20
|
+
import { relationOf as relationAt, relationProposalsOver, } from "./relation-proposals.js";
|
|
21
|
+
import { checkStoredRole, relationReadsOver } from "./relation-reads.js";
|
|
20
22
|
import { addTags as addThingTags, canonicalTagNamed, createTag, labelsOf, liveTagging, removeTags as removeThingTags, setMainTopic, } from "./tags.js";
|
|
21
23
|
import { INBOX_KEY_LENGTH, TASK_KEY_PREFIXES } from "./task-keys.js";
|
|
22
24
|
import { inboxKey, taskAccountOf, taskIdOf, taskRowOf } from "./tasks.js";
|
|
@@ -54,8 +56,9 @@ const oneOf = (value, allowed, what) => {
|
|
|
54
56
|
throw new CliError("validation_error", `${what} is one of ${allowed.join(", ")}`);
|
|
55
57
|
return value;
|
|
56
58
|
};
|
|
57
|
-
/** What a relationship may connect. */
|
|
59
|
+
/** What a relationship may connect; a deal or a lead only as the end its people hang from. */
|
|
58
60
|
const RELATED = ["person", "organization", "project", "task"];
|
|
61
|
+
const DEALS = ["deal", "lead"];
|
|
59
62
|
/** What a label without an account may sit on; a chat, contact or message is the messenger's tag. */
|
|
60
63
|
const LABELLED = {
|
|
61
64
|
note: "note",
|
|
@@ -221,6 +224,7 @@ export const knowledgeStoreOver = (context) => {
|
|
|
221
224
|
createdAt: iso(row.created_at),
|
|
222
225
|
});
|
|
223
226
|
const proposals = relationProposalsOver(context);
|
|
227
|
+
const relationOf = (link) => relationAt(link, now());
|
|
224
228
|
const RELATIONS = `SELECT * FROM links WHERE kind IN (${RELATION_KINDS.map(linkKind).join(",")}) AND to_id IS NOT NULL`;
|
|
225
229
|
const relation = (id) => {
|
|
226
230
|
const row = /^\d+$/.test(id) ? database.prepare(`${RELATIONS} AND id = ?`).get(Number(id)) : undefined;
|
|
@@ -228,26 +232,33 @@ export const knowledgeStoreOver = (context) => {
|
|
|
228
232
|
throw new CliError("not_found", "no relationship with that id");
|
|
229
233
|
return row;
|
|
230
234
|
};
|
|
231
|
-
/** The two ends
|
|
235
|
+
/** The two ends, checked by the registry, in stored order (a symmetric pair's lower id first), and their link. */
|
|
232
236
|
const pair = (key, input) => {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (
|
|
236
|
-
throw new CliError("validation_error", "a relationship needs distinct references
|
|
237
|
-
|
|
238
|
-
|
|
237
|
+
let from = related(key, input.from, true);
|
|
238
|
+
let to = related(key, input.to);
|
|
239
|
+
if (from.type === to.type && from.id === to.id)
|
|
240
|
+
throw new CliError("validation_error", "a relationship needs two distinct references");
|
|
241
|
+
checkEnds(input.kind, from.type, to.type);
|
|
242
|
+
if (input.role !== undefined)
|
|
243
|
+
checkStoredRole(database, input.kind, from.type, to.type, input.role.trim());
|
|
244
|
+
let ends = { from: input.from, to: input.to };
|
|
245
|
+
if (isSymmetric(input.kind) && to.id < from.id)
|
|
246
|
+
[from, to, ends] = [to, from, { from: input.to, to: input.from }];
|
|
247
|
+
const role = input.role === undefined ? null : input.role.trim();
|
|
239
248
|
const existing = database
|
|
240
|
-
.prepare(`${RELATIONS} AND from_type=? AND from_id=? AND to_type=? AND to_id=? AND kind
|
|
241
|
-
|
|
242
|
-
|
|
249
|
+
.prepare(`${RELATIONS} AND from_type=? AND from_id=? AND to_type=? AND to_id=? AND kind=? AND account_id IS NULL ` +
|
|
250
|
+
"AND (? IS NULL OR ifnull(role, '') = ?)")
|
|
251
|
+
.get(from.type, from.id, to.type, to.id, input.kind, role, role);
|
|
252
|
+
return { from, to, existing, ends };
|
|
243
253
|
};
|
|
244
254
|
/** A chat may only be the member: its reference names its own account, so it is never another account's. */
|
|
245
255
|
const related = (key, reference, member = false) => {
|
|
246
256
|
checked(key);
|
|
247
257
|
const thing = thingOf(database, reference);
|
|
248
258
|
const chat = member && (thing?.type === "chat" || thing?.type === "email_thread");
|
|
249
|
-
|
|
250
|
-
|
|
259
|
+
const end = thing && (RELATED.includes(thing.type) || chat || (member && DEALS.includes(thing.type)));
|
|
260
|
+
if (!thing || !end || stateOfThing(database, thing) !== "available")
|
|
261
|
+
throw new CliError("not_found", `reference needs a stored person:, organization:, project:${member ? ", task:, deal:, lead: or chat:" : " or task:"}`);
|
|
251
262
|
if (chat && key !== null) {
|
|
252
263
|
const parsed = parseReference(reference);
|
|
253
264
|
if (parsed.provider !== key.provider || parsed.account !== key.account)
|
|
@@ -292,6 +303,7 @@ export const knowledgeStoreOver = (context) => {
|
|
|
292
303
|
...vocabularyStoreOver(context),
|
|
293
304
|
...organizationsStoreOver(context),
|
|
294
305
|
...meetingProjectsStoreOver(context),
|
|
306
|
+
...relationReadsOver(context),
|
|
295
307
|
taskIds: async (key, options = {}) => {
|
|
296
308
|
const { limit, offset } = bounded(options.limit, options.offset);
|
|
297
309
|
if (options.state !== undefined && !["open", "done", "dismissed"].includes(options.state))
|
|
@@ -518,36 +530,26 @@ export const knowledgeStoreOver = (context) => {
|
|
|
518
530
|
throw new CliError("validation_error", "a relationship names who writes it: the owner or an agent", {
|
|
519
531
|
reason: "proposal.decider-required",
|
|
520
532
|
});
|
|
521
|
-
const { from, existing } = pair(key, input);
|
|
533
|
+
const { from, existing, ends } = pair(key, input);
|
|
522
534
|
if (input.by !== "owner") {
|
|
523
535
|
if (existing)
|
|
524
536
|
throw new CliError("validation_error", `relationship ${String(existing.id)} already links them`, {
|
|
525
537
|
reason: "relationship.exists",
|
|
526
538
|
});
|
|
527
|
-
return proposals.propose(from, { ...input, ...(input.evidence === undefined ? {} : { reason: input.evidence }), evidence: [] }, input.by);
|
|
539
|
+
return proposals.propose(from, { ...input, ...ends, ...(input.evidence === undefined ? {} : { reason: input.evidence }), evidence: [] }, input.by);
|
|
528
540
|
}
|
|
529
541
|
if (existing)
|
|
530
542
|
return relationOf(linkOf(database, existing));
|
|
531
543
|
const confirmed = input.confirmed !== false;
|
|
532
|
-
return relationOf(write(database, () => insertLink(context, {
|
|
533
|
-
from: input.from,
|
|
534
|
-
to: input.to,
|
|
535
|
-
kind: input.kind,
|
|
536
|
-
origin: confirmed ? "owner" : "suggested",
|
|
537
|
-
confirmed,
|
|
538
|
-
...(input.role === undefined ? {} : { role: input.role }),
|
|
539
|
-
...(input.purpose === undefined ? {} : { purpose: input.purpose }),
|
|
540
|
-
...(input.evidence === undefined ? {} : { evidence: input.evidence }),
|
|
541
|
-
...(input.provenance === undefined ? {} : { provenance: input.provenance }),
|
|
542
|
-
})));
|
|
544
|
+
return relationOf(write(database, () => insertLink(context, { ...input, ...ends, by: "owner", origin: confirmed ? "owner" : "suggested", confirmed })));
|
|
543
545
|
}),
|
|
544
546
|
proposeRelation: async (key, input, by) => {
|
|
545
|
-
const { from, existing } = pair(key, input);
|
|
547
|
+
const { from, existing, ends } = pair(key, input);
|
|
546
548
|
if (existing)
|
|
547
549
|
throw new CliError("validation_error", `relationship ${String(existing.id)} already links them`, {
|
|
548
550
|
reason: "relationship.exists",
|
|
549
551
|
});
|
|
550
|
-
return proposals.propose(from, input, by);
|
|
552
|
+
return proposals.propose(from, { ...input, ...ends }, by);
|
|
551
553
|
},
|
|
552
554
|
relationState: async (key, input) => proposals.state(() => pair(key, input), input),
|
|
553
555
|
updateRelation: (async (key, id, input) => {
|
|
@@ -557,6 +559,13 @@ export const knowledgeStoreOver = (context) => {
|
|
|
557
559
|
return relationOf(proposals.update(link, input));
|
|
558
560
|
return proposals.proposeUpdate(link, input, input.by);
|
|
559
561
|
}),
|
|
562
|
+
endRelation: (async (key, id, at, by) => {
|
|
563
|
+
checked(key);
|
|
564
|
+
const link = linkOf(database, relation(id));
|
|
565
|
+
if (by === "owner")
|
|
566
|
+
return relationOf(proposals.update(link, { endsAt: at }));
|
|
567
|
+
return proposals.proposeUpdate(link, { endsAt: at }, by);
|
|
568
|
+
}),
|
|
560
569
|
decideRelationUpdate: async (id, decision) => {
|
|
561
570
|
const { proposal, link } = proposals.decideUpdate(id, decision);
|
|
562
571
|
return { proposal, relation: link && relationOf(link) };
|
|
@@ -569,7 +578,9 @@ export const knowledgeStoreOver = (context) => {
|
|
|
569
578
|
if (reference !== undefined && !thing)
|
|
570
579
|
return [];
|
|
571
580
|
return database
|
|
572
|
-
.prepare(
|
|
581
|
+
.prepare(
|
|
582
|
+
// Live ones first: a long history of withdrawn links never pushes them past the cap.
|
|
583
|
+
`${RELATIONS} AND ${notOverriddenSql("links")} AND (? IS NULL OR (from_type=? AND from_id=?) OR (to_type=? AND to_id=?)) ORDER BY deleted_at IS NOT NULL, created_at, id LIMIT 500`)
|
|
573
584
|
.all(thing?.type ?? null, thing?.type ?? null, thing?.id ?? null, thing?.type ?? null, thing?.id ?? null)
|
|
574
585
|
.map((row) => relationOf(linkOf(database, row)));
|
|
575
586
|
},
|
|
@@ -579,8 +590,9 @@ export const knowledgeStoreOver = (context) => {
|
|
|
579
590
|
const link = linkOf(database, row);
|
|
580
591
|
assertMayDecide({ id: `link:${id}`, proposedBy: UNVERIFIED }, by, context.decisions);
|
|
581
592
|
write(database, () => {
|
|
582
|
-
if (
|
|
593
|
+
if (link.overrides === undefined)
|
|
583
594
|
proposals.rejected(link, by);
|
|
595
|
+
database.prepare("UPDATE links SET updated_at = ? WHERE id = ?").run(now(), Number(id));
|
|
584
596
|
database.prepare("DELETE FROM links WHERE id = ?").run(Number(id));
|
|
585
597
|
});
|
|
586
598
|
return { id, removed: true };
|
|
@@ -2,13 +2,12 @@
|
|
|
2
2
|
* Every kind a `links` row may have. The schema doc's description of `links` names exactly these
|
|
3
3
|
* (`schema.test.ts` checks it); a writer that needs a new kind adds it here first.
|
|
4
4
|
*/
|
|
5
|
-
export declare const LINK_KINDS: readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "assigned-to", "attached"];
|
|
5
|
+
export declare const LINK_KINDS: readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"];
|
|
6
6
|
export type LinkKind = (typeof LINK_KINDS)[number];
|
|
7
7
|
/** Where a caller may say a link came from. */
|
|
8
8
|
export declare const LINK_ORIGINS: readonly ["file", "owner", "suggested", "message"];
|
|
9
9
|
/** Where a stored link came from: an origin a caller gives, or `calendar`, which only the store writes. */
|
|
10
10
|
export declare const LINK_SOURCES: readonly ["file", "owner", "suggested", "message", "calendar"];
|
|
11
|
-
|
|
12
|
-
export declare const RELATION_KINDS: readonly ["member-of", "related-to"];
|
|
11
|
+
export { RELATION_KINDS } from "../../domain/relations.js";
|
|
13
12
|
/** A kind as an SQL literal, so a kind written into a query is checked against the list. */
|
|
14
13
|
export declare const linkKind: (kind: LinkKind) => string;
|
|
@@ -14,6 +14,9 @@ export const LINK_KINDS = [
|
|
|
14
14
|
"created-from",
|
|
15
15
|
"duplicate-of",
|
|
16
16
|
"related-to",
|
|
17
|
+
"reports-to",
|
|
18
|
+
"customer-of",
|
|
19
|
+
"partner-of",
|
|
17
20
|
"assigned-to",
|
|
18
21
|
"attached",
|
|
19
22
|
];
|
|
@@ -21,7 +24,6 @@ export const LINK_KINDS = [
|
|
|
21
24
|
export const LINK_ORIGINS = ["file", "owner", "suggested", "message"];
|
|
22
25
|
/** Where a stored link came from: an origin a caller gives, or `calendar`, which only the store writes. */
|
|
23
26
|
export const LINK_SOURCES = [...LINK_ORIGINS, "calendar"];
|
|
24
|
-
|
|
25
|
-
export const RELATION_KINDS = ["member-of", "related-to"];
|
|
27
|
+
export { RELATION_KINDS } from "../../domain/relations.js";
|
|
26
28
|
/** A kind as an SQL literal, so a kind written into a query is checked against the list. */
|
|
27
29
|
export const linkKind = (kind) => `'${kind}'`;
|
|
@@ -28,6 +28,8 @@ const V31_TABLES = [
|
|
|
28
28
|
"syncs",
|
|
29
29
|
"taggings",
|
|
30
30
|
];
|
|
31
|
+
/** Version 56 rewrites CRM links and folds duplicates, which an older build would write again. */
|
|
32
|
+
const V56_TABLES = ["links", "proposed_actions"];
|
|
31
33
|
/** One migration creates the whole schema; every later one is added as the next version. */
|
|
32
34
|
export const MANIFEST = [
|
|
33
35
|
{ name: "20261010184427_initial", version: 1, minCompatible: 1 },
|
|
@@ -113,6 +115,9 @@ export const MANIFEST = [
|
|
|
113
115
|
{ name: "20261106225547_version-54-crm-fields", version: 54, minCompatible: 34 },
|
|
114
116
|
{ name: "20261107032742_version-55-decision-requests", version: 55, minCompatible: 34 },
|
|
115
117
|
{ name: "20261107043407_version-55-decision-requests-index", version: 55, minCompatible: 34 },
|
|
118
|
+
{ name: "20261107162427_version-56-relationship-links", version: 56, minCompatible: 56, tables: V56_TABLES },
|
|
119
|
+
{ name: "20261107162448_version-56-relationship-links-history", version: 56, minCompatible: 56, tables: V56_TABLES },
|
|
120
|
+
{ name: "20261107163245_version-56-relationship-links-key", version: 56, minCompatible: 56, tables: V56_TABLES },
|
|
116
121
|
];
|
|
117
122
|
export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
|
|
118
123
|
const migrations = [];
|
|
@@ -54,7 +54,7 @@ export interface MemoryInput {
|
|
|
54
54
|
project?: string;
|
|
55
55
|
confidence?: number;
|
|
56
56
|
status?: "proposed" | "confirmed";
|
|
57
|
-
/** The memory this one replaces; it becomes `superseded
|
|
57
|
+
/** The memory this one replaces; it becomes `superseded` once this one is confirmed. */
|
|
58
58
|
supersedes?: string;
|
|
59
59
|
}
|
|
60
60
|
export interface MemoriesStore {
|
|
@@ -155,10 +155,26 @@ export const memoriesStoreOver = (context) => {
|
|
|
155
155
|
throw new CliError("not_found", `${reference} is a fact now: store.facts holds it`);
|
|
156
156
|
return row;
|
|
157
157
|
};
|
|
158
|
-
const decided = (reference, by) => {
|
|
158
|
+
const decided = (reference, by, ownerOnly = false) => {
|
|
159
159
|
const row = rowOf(reference);
|
|
160
|
-
assertMayDecide({ id: `memory:${row.id}`, proposedBy: proposerOf(database, row.author_type, row.author_id) }, by, context.decisions);
|
|
160
|
+
assertMayDecide({ id: `memory:${row.id}`, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly }, by, context.decisions);
|
|
161
161
|
};
|
|
162
|
+
const alreadySuperseded = (id) => new CliError("validation_error", `memory:${id} is already superseded; correct the one that replaced it`, {
|
|
163
|
+
reason: "memory.already-superseded",
|
|
164
|
+
});
|
|
165
|
+
const replaceable = (reference) => {
|
|
166
|
+
const row = rowOf(reference);
|
|
167
|
+
if (row.status === "superseded")
|
|
168
|
+
throw alreadySuperseded(row.id);
|
|
169
|
+
return row;
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* A correction retired the memory if it was ever confirmed. An older store let an agent's proposal retire it at
|
|
173
|
+
* once, so a memory superseded only by the one being confirmed is not refused.
|
|
174
|
+
*/
|
|
175
|
+
const retiredByAnother = (replaced, by) => database
|
|
176
|
+
.prepare("SELECT 1 FROM memories WHERE supersedes_id = ? AND id <> ? AND last_verified_at IS NOT NULL LIMIT 1")
|
|
177
|
+
.get(replaced, by) !== undefined;
|
|
162
178
|
const setStatus = (reference, status, verified) => {
|
|
163
179
|
const row = rowOf(reference);
|
|
164
180
|
const at = now();
|
|
@@ -193,7 +209,7 @@ export const memoriesStoreOver = (context) => {
|
|
|
193
209
|
const { actor, model } = authorActor(context, input.author);
|
|
194
210
|
const subject = input.subject === undefined ? undefined : requiredThing(database, input.subject, "the subject");
|
|
195
211
|
const project = input.project === undefined ? null : projectId(database, input.project);
|
|
196
|
-
const replaced = input.supersedes === undefined ? undefined : Number(
|
|
212
|
+
const replaced = input.supersedes === undefined ? undefined : Number(replaceable(input.supersedes).id);
|
|
197
213
|
const at = now();
|
|
198
214
|
const made = Number(database
|
|
199
215
|
.prepare("INSERT INTO memories (id, kind, body, subject_type, subject_id, author_type, author_id, model, confidence, status, " +
|
|
@@ -201,16 +217,26 @@ export const memoriesStoreOver = (context) => {
|
|
|
201
217
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
202
218
|
.get(nextId(database, "memories"), kind, body, subject?.type ?? null, subject?.id ?? null, actor.type, actor.id, model, input.confidence ?? null, status, status === "confirmed" ? at : null, replaced ?? null, scope, project, at, at)?.id);
|
|
203
219
|
linkEvidence(context, { type: "memory", id: made }, input.evidence, input.author === "owner" ? "owner" : "agent");
|
|
204
|
-
if (replaced !== undefined)
|
|
220
|
+
if (replaced !== undefined && status === "confirmed")
|
|
205
221
|
database.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?").run(at, replaced);
|
|
206
222
|
return made;
|
|
207
223
|
});
|
|
208
224
|
return memoryOf(rowOf(`memory:${id}`));
|
|
209
225
|
};
|
|
210
|
-
|
|
211
|
-
|
|
226
|
+
/** Applies a pending correction; only the owner retires a confirmed memory, whatever `agent_decisions` says. */
|
|
227
|
+
const confirmNow = (reference, by) => write(database, () => {
|
|
228
|
+
const row = rowOf(reference);
|
|
229
|
+
const replaced = row.status === "confirmed" || row.supersedes_id == null ? undefined : rowOf(`memory:${row.supersedes_id}`);
|
|
230
|
+
decided(reference, by, replaced?.status === "confirmed");
|
|
231
|
+
if (replaced !== undefined) {
|
|
232
|
+
if (retiredByAnother(Number(replaced.id), Number(row.id)))
|
|
233
|
+
throw alreadySuperseded(replaced.id);
|
|
234
|
+
database
|
|
235
|
+
.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?")
|
|
236
|
+
.run(now(), Number(replaced.id));
|
|
237
|
+
}
|
|
212
238
|
return setStatus(reference, "confirmed", true);
|
|
213
|
-
};
|
|
239
|
+
});
|
|
214
240
|
return {
|
|
215
241
|
addNow,
|
|
216
242
|
confirmNow,
|
|
@@ -1060,5 +1060,36 @@ export const GENERATED = [
|
|
|
1060
1060
|
"statements": [
|
|
1061
1061
|
"CREATE INDEX `decision_requests_by_channel_bot_profile_chat_id_message_id` ON `decision_requests` (`channel`,`bot_profile`,`chat_id`,`message_id`);"
|
|
1062
1062
|
]
|
|
1063
|
+
},
|
|
1064
|
+
{
|
|
1065
|
+
"name": "20261107162427_version-56-relationship-links",
|
|
1066
|
+
"statements": [
|
|
1067
|
+
"CREATE TABLE `link_revisions` (\n\t`id` integer PRIMARY KEY,\n\t`link_id` integer NOT NULL,\n\t`change` text NOT NULL,\n\t`before` text,\n\t`after` text,\n\t`author` text,\n\t`account_id` integer,\n\t`created_at` integer NOT NULL\n);",
|
|
1068
|
+
"ALTER TABLE `links` ADD `account_id` integer;",
|
|
1069
|
+
"ALTER TABLE `links` ADD `starts_at` integer;",
|
|
1070
|
+
"ALTER TABLE `links` ADD `ends_at` integer;",
|
|
1071
|
+
"ALTER TABLE `links` ADD `deleted_at` integer;",
|
|
1072
|
+
"CREATE INDEX `link_revisions_by_link_id_created_at` ON `link_revisions` (`link_id`,`created_at`);"
|
|
1073
|
+
]
|
|
1074
|
+
},
|
|
1075
|
+
{
|
|
1076
|
+
"name": "20261107162448_version-56-relationship-links-history",
|
|
1077
|
+
"statements": [
|
|
1078
|
+
"-- A CRM's deal and lead people were stored as the owner's (confirmed = 1): they are the CRM account's report.\nUPDATE links SET confirmed = 0, account_id = (SELECT d.account_id FROM deals d WHERE d.id = links.from_id)\n WHERE source = 'crm' AND kind = 'related-to' AND from_type = 'deal';",
|
|
1079
|
+
"UPDATE links SET confirmed = 0, account_id = (SELECT l.account_id FROM leads l WHERE l.id = links.from_id)\n WHERE source = 'crm' AND kind = 'related-to' AND from_type = 'lead';",
|
|
1080
|
+
"-- The unique key below needs one row per relationship. Of duplicates the owner's row stays, then a confirmed one,\n-- then the oldest; it takes the others' metadata where its own has none, and proposals naming a dropped row name it.\nWITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE links SET metadata = json_patch(\n (SELECT json_group_object(j.key, CASE WHEN j.type IN ('object', 'array') THEN json(j.value) ELSE j.value END)\n FROM link_fold f JOIN links d ON d.id = f.drop_id, json_each(d.metadata) j\n WHERE f.keep_id = links.id AND json_valid(d.metadata)),\n coalesce(links.metadata, '{}'))\n WHERE id IN (SELECT f.keep_id FROM link_fold f JOIN links d ON d.id = f.drop_id\n WHERE d.metadata IS NOT NULL AND json_valid(d.metadata));",
|
|
1081
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE proposed_actions SET payload = json_set(payload, '$.relationship',\n (SELECT CAST(f.keep_id AS TEXT) FROM link_fold f WHERE CAST(f.drop_id AS TEXT) = json_extract(payload, '$.relationship')))\n WHERE kind = 'relationship_update'\n AND json_extract(payload, '$.relationship') IN (SELECT CAST(drop_id AS TEXT) FROM link_fold);",
|
|
1082
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE proposed_actions SET result = json_set(result, '$.link',\n (SELECT CAST(f.keep_id AS TEXT) FROM link_fold f WHERE CAST(f.drop_id AS TEXT) = json_extract(result, '$.link')))\n WHERE json_valid(result) AND json_extract(result, '$.link') IN (SELECT CAST(drop_id AS TEXT) FROM link_fold);",
|
|
1083
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nDELETE FROM links WHERE id IN (SELECT drop_id FROM link_fold);",
|
|
1084
|
+
"CREATE TRIGGER link_revisions_ai AFTER INSERT ON links\n WHEN new.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND new.to_id IS NOT NULL BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (new.id, 'added', NULL,\n json_object('role', new.role, 'confirmed', new.confirmed, 'account_id', new.account_id, 'starts_at', new.starts_at,\n 'ends_at', new.ends_at, 'deleted_at', new.deleted_at),\n new.author, new.account_id, new.updated_at);\nEND;",
|
|
1085
|
+
"-- Only a change a reader sees: a sync that touches `updated_at` alone writes no revision.\nCREATE TRIGGER link_revisions_au AFTER UPDATE OF role, confirmed, account_id, starts_at, ends_at, deleted_at ON links\n WHEN new.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND new.to_id IS NOT NULL\n AND (old.role IS NOT new.role OR old.confirmed IS NOT new.confirmed OR old.account_id IS NOT new.account_id\n OR old.starts_at IS NOT new.starts_at OR old.ends_at IS NOT new.ends_at OR old.deleted_at IS NOT new.deleted_at) BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (new.id,\n CASE\n WHEN old.deleted_at IS NULL AND new.deleted_at IS NOT NULL THEN 'withdrawn'\n WHEN old.deleted_at IS NOT NULL AND new.deleted_at IS NULL THEN 'restored'\n WHEN old.confirmed = 0 AND new.confirmed = 1 THEN 'confirmed'\n WHEN old.ends_at IS NULL AND new.ends_at IS NOT NULL THEN 'ended'\n ELSE 'changed'\n END,\n json_object('role', old.role, 'confirmed', old.confirmed, 'account_id', old.account_id, 'starts_at', old.starts_at,\n 'ends_at', old.ends_at, 'deleted_at', old.deleted_at),\n json_object('role', new.role, 'confirmed', new.confirmed, 'account_id', new.account_id, 'starts_at', new.starts_at,\n 'ends_at', new.ends_at, 'deleted_at', new.deleted_at),\n new.author, new.account_id, new.updated_at);\nEND;",
|
|
1086
|
+
"CREATE TRIGGER link_revisions_ad AFTER DELETE ON links\n WHEN old.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND old.to_id IS NOT NULL BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (old.id,\n -- The store records the rejection, then sets updated_at, then deletes: an older rejection the fold re-pointed is not this one.\n CASE WHEN old.confirmed = 0 AND EXISTS (SELECT 1 FROM proposed_actions p WHERE p.kind = 'relationship'\n AND p.status = 'rejected' AND p.decided_at >= old.updated_at AND json_valid(p.result)\n AND json_extract(p.result, '$.link') = CAST(old.id AS TEXT))\n THEN 'rejected' ELSE 'removed' END,\n json_object('role', old.role, 'confirmed', old.confirmed, 'account_id', old.account_id, 'starts_at', old.starts_at,\n 'ends_at', old.ends_at, 'deleted_at', old.deleted_at),\n NULL, old.author, old.account_id, old.updated_at);\nEND;"
|
|
1087
|
+
]
|
|
1088
|
+
},
|
|
1089
|
+
{
|
|
1090
|
+
"name": "20261107163245_version-56-relationship-links-key",
|
|
1091
|
+
"statements": [
|
|
1092
|
+
"CREATE UNIQUE INDEX `links_relationship_key` ON `links` (`kind`,`from_type`,`from_id`,`to_type`,`to_id`,ifnull(\"anchor\", ''),ifnull(\"role\", ''),ifnull(\"account_id\", 0)) WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL;"
|
|
1093
|
+
]
|
|
1063
1094
|
}
|
|
1064
1095
|
];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RelationshipColumns } from "../../domain/relations.js";
|
|
1
2
|
import type { Section } from "../../readers/types.js";
|
|
2
3
|
import { type Decider } from "../decisions.js";
|
|
3
4
|
import type { CacheDatabase } from "../driver.js";
|
|
@@ -51,7 +52,7 @@ export interface Note {
|
|
|
51
52
|
updatedAt: string;
|
|
52
53
|
deletedAt: string | null;
|
|
53
54
|
}
|
|
54
|
-
export interface Link {
|
|
55
|
+
export interface Link extends RelationshipColumns {
|
|
55
56
|
id: string;
|
|
56
57
|
from: string;
|
|
57
58
|
/** `null` while the link names nobody the store knows, or more than one. */
|
|
@@ -78,7 +79,7 @@ export interface LinkListFilter {
|
|
|
78
79
|
origin?: Link["origin"];
|
|
79
80
|
confirmed?: boolean;
|
|
80
81
|
}
|
|
81
|
-
export interface LinkInput {
|
|
82
|
+
export interface LinkInput extends Pick<RelationshipColumns, "position" | "startsAt" | "endsAt"> {
|
|
82
83
|
from: string;
|
|
83
84
|
to?: string;
|
|
84
85
|
targetText?: string;
|
|
@@ -3,6 +3,7 @@ import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
|
|
|
3
3
|
import { googleDocumentLinks } from "../../domain/google-documents.js";
|
|
4
4
|
import { DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, } from "../../domain/providers.js";
|
|
5
5
|
import { parseReference } from "../../domain/references.js";
|
|
6
|
+
import { isRelationKind } from "../../domain/relations.js";
|
|
6
7
|
import { normalizeTag } from "../../domain/tags.js";
|
|
7
8
|
import { assertMayWithdraw } from "../decisions.js";
|
|
8
9
|
import { fold } from "../normalize.js";
|
|
@@ -80,7 +81,9 @@ export const noteRowOf = (database, reference) => {
|
|
|
80
81
|
};
|
|
81
82
|
const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
|
|
82
83
|
export const linkOf = (database, row) => {
|
|
83
|
-
const metadata = row.metadata == null
|
|
84
|
+
const metadata = row.metadata == null
|
|
85
|
+
? {}
|
|
86
|
+
: JSON.parse(String(row.metadata));
|
|
84
87
|
return {
|
|
85
88
|
id: String(row.id),
|
|
86
89
|
from: thingRef(database, row.from_type, row.from_id),
|
|
@@ -95,6 +98,12 @@ export const linkOf = (database, row) => {
|
|
|
95
98
|
provenance: metadata.provenance ?? null,
|
|
96
99
|
confirmed: Number(row.confirmed) === 1,
|
|
97
100
|
createdAt: iso(row.created_at),
|
|
101
|
+
...(row.account_id == null ? {} : { accountId: Number(row.account_id) }),
|
|
102
|
+
...(row.starts_at == null ? {} : { startsAt: Number(row.starts_at) }),
|
|
103
|
+
...(row.ends_at == null ? {} : { endsAt: Number(row.ends_at) }),
|
|
104
|
+
...(row.deleted_at == null ? {} : { deletedAt: Number(row.deleted_at) }),
|
|
105
|
+
...(typeof metadata.position === "string" ? { position: metadata.position } : {}),
|
|
106
|
+
...(typeof metadata.overrides === "number" ? { overrides: metadata.overrides } : {}),
|
|
98
107
|
};
|
|
99
108
|
};
|
|
100
109
|
/** The row a reference names, refused when the store holds none. */
|
|
@@ -183,19 +192,27 @@ export const insertLink = (context, input) => {
|
|
|
183
192
|
if (to === null && targetText === null)
|
|
184
193
|
throw new CliError("validation_error", "a link needs a target");
|
|
185
194
|
if (to !== null) {
|
|
195
|
+
// A relationship's key holds its role and its source account: the owner's link with another role is another one.
|
|
196
|
+
const relationship = isRelationKind(kind);
|
|
197
|
+
const role = relationship && input.role !== undefined ? input.role.trim() : null;
|
|
186
198
|
const existing = database
|
|
187
|
-
.prepare("SELECT * FROM links WHERE from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ? AND anchor IS ?"
|
|
188
|
-
|
|
199
|
+
.prepare("SELECT * FROM links WHERE from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ? AND anchor IS ?" +
|
|
200
|
+
(relationship ? " AND account_id IS NULL AND (? IS NULL OR ifnull(role, '') = ?)" : ""))
|
|
201
|
+
.get(from.type, from.id, to.type, to.id, kind, input.anchor ?? null, ...(relationship ? [role, role] : []));
|
|
189
202
|
if (existing)
|
|
190
203
|
return linkOf(database, existing);
|
|
191
204
|
}
|
|
192
205
|
const at = now();
|
|
193
206
|
const provenance = input.provenance === undefined ? undefined : textOf(input.provenance, "provenance", 2000);
|
|
207
|
+
const position = input.position === undefined ? undefined : textOf(input.position, "a position", 200);
|
|
208
|
+
if (input.startsAt !== undefined && input.endsAt !== undefined && input.endsAt <= input.startsAt)
|
|
209
|
+
throw new CliError("validation_error", "a relationship ends after it starts");
|
|
210
|
+
const metadata = provenance === undefined && position === undefined ? null : JSON.stringify({ provenance, position });
|
|
194
211
|
const row = database
|
|
195
212
|
.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, anchor, source, target_text, target_folded, role, evidence, " +
|
|
196
|
-
"metadata, confirmed, created_at, author, updated_at, purpose
|
|
197
|
-
"RETURNING id")
|
|
198
|
-
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, kind, input.anchor ?? null, origin, targetText, targetText === null ? null : targetKey(targetText), input.role === undefined ? null : textOf(input.role, "a role", 200), input.evidence === undefined ? null : textOf(input.evidence, "evidence", 2000),
|
|
213
|
+
"metadata, confirmed, created_at, author, updated_at, purpose, starts_at, ends_at) " +
|
|
214
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
215
|
+
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, kind, input.anchor ?? null, origin, targetText, targetText === null ? null : targetKey(targetText), input.role === undefined ? null : textOf(input.role, "a role", 200), input.evidence === undefined ? null : textOf(input.evidence, "evidence", 2000), metadata, input.confirmed === false ? 0 : 1, at, origin === "owner" ? "owner" : null, at, input.purpose === undefined ? null : purposeOf(input.purpose), input.startsAt ?? null, input.endsAt ?? null);
|
|
199
216
|
if (to === null && targetText !== null)
|
|
200
217
|
resolveKey(database, targetKey(targetText));
|
|
201
218
|
return linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(Number(row?.id)));
|
|
@@ -2,6 +2,7 @@ import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync }
|
|
|
2
2
|
import { dirname } from "node:path";
|
|
3
3
|
import { CliError } from "@wirecat/cli-base";
|
|
4
4
|
import { DEFAULT_DECISION_POLICY } from "../decisions.js";
|
|
5
|
+
import { refuseDamagedStore } from "../marks.js";
|
|
5
6
|
import { migrate } from "../migrations.js";
|
|
6
7
|
import { storeCapable } from "../open.js";
|
|
7
8
|
import { refuseOwnerStoreInTests, storePath } from "../path.js";
|
|
@@ -78,8 +79,10 @@ export const openStoreContext = async (options = {}) => {
|
|
|
78
79
|
if (!statSync(file, { throwIfNoEntry: false })?.isFile())
|
|
79
80
|
throw new CliError("not_found", "The store does not exist as a file; read-only opening does not create it");
|
|
80
81
|
}
|
|
81
|
-
else
|
|
82
|
+
else {
|
|
82
83
|
createWritable(file);
|
|
84
|
+
refuseDamagedStore(file, command);
|
|
85
|
+
}
|
|
83
86
|
const opened = readOnly ? await openReadable(file, options) : await openSqlite(file, { readOnly });
|
|
84
87
|
const database = opened.database;
|
|
85
88
|
try {
|
|
@@ -9,6 +9,14 @@ export interface OrganizationsStore {
|
|
|
9
9
|
updateOrganization(organization: string, input: {
|
|
10
10
|
name: string;
|
|
11
11
|
}): Promise<Organization>;
|
|
12
|
+
/**
|
|
13
|
+
* The owner says whether an organization is one of his own; a CRM sync never changes his word. `null` hands it back
|
|
14
|
+
* to the CRM's own-company flag.
|
|
15
|
+
*/
|
|
16
|
+
setOwnOrganization(organization: string, own: boolean | null): Promise<{
|
|
17
|
+
ref: string;
|
|
18
|
+
own: boolean;
|
|
19
|
+
}>;
|
|
12
20
|
}
|
|
13
21
|
export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
|
|
14
22
|
export {};
|
|
@@ -45,4 +45,18 @@ export const organizationsStoreOver = ({ database, now }) => ({
|
|
|
45
45
|
throw new CliError("not_found", `no organization ${organization}`);
|
|
46
46
|
return organizationOf(row);
|
|
47
47
|
}),
|
|
48
|
+
setOwnOrganization: async (organization, own) => write(database, () => {
|
|
49
|
+
const thing = thingOf(database, organization.includes(":") ? organization : `organization:${organization}`);
|
|
50
|
+
const set = own === null
|
|
51
|
+
? "json_remove(coalesce(metadata, '{}'), '$.own', '$.own_by')"
|
|
52
|
+
: `json_set(coalesce(metadata, '{}'), '$.own', json('${own}'), '$.own_by', 'owner')`;
|
|
53
|
+
const row = thing?.type === "organization" &&
|
|
54
|
+
database
|
|
55
|
+
.prepare(`UPDATE organizations SET metadata = ${set}, updated_at = ? WHERE id = ? AND deleted_at IS NULL RETURNING id, metadata`)
|
|
56
|
+
.get(now(), thing.id);
|
|
57
|
+
if (!row)
|
|
58
|
+
throw new CliError("not_found", `no organization ${organization}`);
|
|
59
|
+
const metadata = JSON.parse(String(row.metadata ?? "{}"));
|
|
60
|
+
return { ref: `organization:${row.id}`, own: metadata.own === true };
|
|
61
|
+
}),
|
|
48
62
|
});
|
|
@@ -3,7 +3,7 @@ import type { StoreContext } from "./open.js";
|
|
|
3
3
|
/**
|
|
4
4
|
* An account's own identity (same provider and id as the account) is the owner. Messengers save it like anyone
|
|
5
5
|
* else's, as a person of its own, so the owner's name counted as a contact's. Links it, and whoever was linked
|
|
6
|
-
* with it, to the owner; nothing to do once done.
|
|
6
|
+
* with it, to the owner, unless the owner separated that person from themselves; nothing to do once done.
|
|
7
7
|
*/
|
|
8
8
|
export declare const linkOwnIdentities: (context: StoreContext) => number;
|
|
9
9
|
/** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { ownerPerson } from "./actors.js";
|
|
3
3
|
import { mergePerson, personOf } from "./person-links.js";
|
|
4
|
+
import { separated } from "./person-separation.js";
|
|
4
5
|
import { write } from "./transaction.js";
|
|
5
6
|
/**
|
|
6
7
|
* An account's own identity (same provider and id as the account) is the owner. Messengers save it like anyone
|
|
7
8
|
* else's, as a person of its own, so the owner's name counted as a contact's. Links it, and whoever was linked
|
|
8
|
-
* with it, to the owner; nothing to do once done.
|
|
9
|
+
* with it, to the owner, unless the owner separated that person from themselves; nothing to do once done.
|
|
9
10
|
*/
|
|
10
11
|
export const linkOwnIdentities = (context) => {
|
|
11
12
|
const owner = ownerPerson(context.database).id;
|
|
@@ -15,11 +16,12 @@ export const linkOwnIdentities = (context) => {
|
|
|
15
16
|
.all(owner);
|
|
16
17
|
if (strays.length === 0)
|
|
17
18
|
return 0;
|
|
18
|
-
write(context.database, () => {
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
return write(context.database, () => {
|
|
20
|
+
const joining = strays.map(({ person }) => Number(person)).filter((person) => !separated(context, person, owner));
|
|
21
|
+
for (const person of joining)
|
|
22
|
+
mergePerson(context, person, owner, { method: "account", by: "rules" });
|
|
23
|
+
return joining.length;
|
|
21
24
|
});
|
|
22
|
-
return strays.length;
|
|
23
25
|
};
|
|
24
26
|
/** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
|
|
25
27
|
export const linkToOwner = (context, ref) => {
|