@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.
Files changed (141) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/calendar/prepare.d.ts +4 -2
  3. package/dist/calendar/prepare.js +8 -8
  4. package/dist/cli/index.d.ts +2 -2
  5. package/dist/cli/index.js +2 -1
  6. package/dist/cli/messenger/contacts-command.js +3 -2
  7. package/dist/cli/messenger/doctor-command.js +14 -7
  8. package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
  9. package/dist/cli/messenger/store-maintenance-command.js +31 -4
  10. package/dist/cli/program.js +11 -2
  11. package/dist/cli/steps.js +9 -1
  12. package/dist/cli/store-recover.d.ts +10 -2
  13. package/dist/cli/store-recover.js +18 -4
  14. package/dist/cli/store-settings.js +38 -4
  15. package/dist/crm/cli/index.js +3 -1
  16. package/dist/crm/index.d.ts +2 -2
  17. package/dist/crm/index.js +1 -1
  18. package/dist/crm/source.d.ts +35 -5
  19. package/dist/crm/sync.d.ts +15 -7
  20. package/dist/crm/sync.js +169 -11
  21. package/dist/domain/crm.d.ts +41 -2
  22. package/dist/domain/deals.d.ts +5 -2
  23. package/dist/domain/deals.js +5 -2
  24. package/dist/domain/record-types.d.ts +61 -0
  25. package/dist/domain/record-types.js +26 -0
  26. package/dist/domain/records.d.ts +3 -5
  27. package/dist/domain/records.js +10 -13
  28. package/dist/domain/relations.d.ts +125 -0
  29. package/dist/domain/relations.js +107 -0
  30. package/dist/entities/contact-activity.d.ts +4 -0
  31. package/dist/entities/contact-activity.js +1 -0
  32. package/dist/entities/contact-context.d.ts +20 -0
  33. package/dist/entities/contact-context.js +2 -0
  34. package/dist/entities/deal.d.ts +2 -2
  35. package/dist/entities/deal.js +2 -1
  36. package/dist/entities/index.d.ts +39 -13
  37. package/dist/entities/relationship.d.ts +8 -2
  38. package/dist/entities/relationship.js +8 -2
  39. package/dist/entities/task-results.d.ts +10 -10
  40. package/dist/errors/failures.d.ts +17 -1
  41. package/dist/errors/failures.js +57 -1
  42. package/dist/errors/reasons.js +28 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +1 -0
  45. package/dist/mail/cli/review.js +20 -6
  46. package/dist/mail/index.d.ts +1 -1
  47. package/dist/mail/marks.d.ts +10 -5
  48. package/dist/mail/marks.js +16 -8
  49. package/dist/mail/review.d.ts +5 -0
  50. package/dist/mcp/tool.js +2 -1
  51. package/dist/runs/recording.js +13 -4
  52. package/dist/services/deps.js +4 -6
  53. package/dist/services/index.d.ts +1 -1
  54. package/dist/services/link-scorers/chat-senders.d.ts +3 -2
  55. package/dist/services/link-scorers/chat-senders.js +7 -4
  56. package/dist/services/link-scorers/mail-thread.js +1 -0
  57. package/dist/services/link-scorers/member-chats.js +1 -0
  58. package/dist/services/link-scorers/member-dialog.d.ts +1 -1
  59. package/dist/services/link-scorers/member-dialog.js +4 -3
  60. package/dist/services/link-scorers/scan.d.ts +5 -2
  61. package/dist/services/link-scorers/scan.js +100 -54
  62. package/dist/services/link-scorers/shared.d.ts +2 -2
  63. package/dist/services/link-scorers/shared.js +8 -4
  64. package/dist/services/link-scorers/types.d.ts +3 -0
  65. package/dist/services/metadata.d.ts +1 -1
  66. package/dist/services/person-context.d.ts +24 -7
  67. package/dist/services/person-context.js +45 -11
  68. package/dist/services/person-preparation.js +4 -5
  69. package/dist/services/project-status/index.js +2 -1
  70. package/dist/services/stored-project-gathering.js +4 -3
  71. package/dist/store/damage.d.ts +3 -1
  72. package/dist/store/damage.js +19 -12
  73. package/dist/store/document-transfer/index.js +7 -0
  74. package/dist/store/exports.d.ts +1 -0
  75. package/dist/store/exports.js +1 -0
  76. package/dist/store/index.d.ts +7 -1
  77. package/dist/store/index.js +2 -0
  78. package/dist/store/marks.d.ts +57 -0
  79. package/dist/store/marks.js +121 -0
  80. package/dist/store/project-transfer/preview.js +12 -7
  81. package/dist/store/project-transfer/request.d.ts +4 -1
  82. package/dist/store/project-transfer/schema.d.ts +9 -2
  83. package/dist/store/project-transfer/schema.js +4 -0
  84. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  85. package/dist/store/recover.js +16 -1
  86. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  87. package/dist/store/sqlite/crm-settings.js +80 -0
  88. package/dist/store/sqlite/crm.d.ts +42 -2
  89. package/dist/store/sqlite/crm.js +397 -36
  90. package/dist/store/sqlite/deals.js +3 -2
  91. package/dist/store/sqlite/finance.d.ts +8 -1
  92. package/dist/store/sqlite/finance.js +10 -3
  93. package/dist/store/sqlite/involvement-queue.js +4 -3
  94. package/dist/store/sqlite/knowledge.d.ts +7 -3
  95. package/dist/store/sqlite/knowledge.js +43 -31
  96. package/dist/store/sqlite/link-kinds.d.ts +2 -3
  97. package/dist/store/sqlite/link-kinds.js +4 -2
  98. package/dist/store/sqlite/manifest.js +5 -0
  99. package/dist/store/sqlite/memories.d.ts +1 -1
  100. package/dist/store/sqlite/memories.js +33 -7
  101. package/dist/store/sqlite/migrations.generated.js +31 -0
  102. package/dist/store/sqlite/notes.d.ts +3 -2
  103. package/dist/store/sqlite/notes.js +23 -6
  104. package/dist/store/sqlite/open-store.js +4 -1
  105. package/dist/store/sqlite/organizations.d.ts +8 -0
  106. package/dist/store/sqlite/organizations.js +14 -0
  107. package/dist/store/sqlite/own-identities.d.ts +1 -1
  108. package/dist/store/sqlite/own-identities.js +7 -5
  109. package/dist/store/sqlite/person-links.d.ts +5 -2
  110. package/dist/store/sqlite/person-links.js +24 -18
  111. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  112. package/dist/store/sqlite/person-preparation.js +3 -2
  113. package/dist/store/sqlite/person-separation.d.ts +5 -0
  114. package/dist/store/sqlite/person-separation.js +26 -0
  115. package/dist/store/sqlite/project-transfer/records.js +14 -3
  116. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  117. package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
  118. package/dist/store/sqlite/record-projectors.d.ts +44 -0
  119. package/dist/store/sqlite/record-projectors.js +72 -0
  120. package/dist/store/sqlite/records.js +12 -70
  121. package/dist/store/sqlite/relation-list.d.ts +43 -0
  122. package/dist/store/sqlite/relation-list.js +133 -0
  123. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  124. package/dist/store/sqlite/relation-proposals.js +134 -10
  125. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  126. package/dist/store/sqlite/relation-reads.js +7 -0
  127. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  128. package/dist/store/sqlite/relation-roles.js +91 -0
  129. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  130. package/dist/store/sqlite/reported-relations.js +132 -0
  131. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  132. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  133. package/dist/store/sqlite/schema/links.d.ts +360 -0
  134. package/dist/store/sqlite/schema/links.js +32 -0
  135. package/dist/store/sqlite/schema.d.ts +2 -296
  136. package/dist/store/sqlite/schema.js +2 -24
  137. package/dist/store/sqlite/transaction.js +2 -5
  138. package/dist/store/store.d.ts +3 -0
  139. package/dist/store/store.js +5 -0
  140. package/dist/store/types.d.ts +5 -0
  141. package/package.json +5 -5
@@ -0,0 +1,133 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { inverseOf, notOverriddenSql, RELATION_KINDS, rolesOf, STANDINGS, } from "../../domain/relations.js";
3
+ import { linkKind } from "./link-kinds.js";
4
+ import { linkOf } from "./notes.js";
5
+ import { proposalOperationsOver } from "./proposed-actions.js";
6
+ import { relationOf } from "./relation-proposals.js";
7
+ import { thingOf } from "./things.js";
8
+ const KINDS = RELATION_KINDS.map(linkKind).join(", ");
9
+ const typeOfRef = (column) => `substr(${column}, 1, instr(${column}, ':') - 1)`;
10
+ const idOfRef = (column) => `CAST(substr(${column}, instr(${column}, ':') + 1) AS INTEGER)`;
11
+ export const relationListOver = (context) => {
12
+ const { database, now } = context;
13
+ const operations = proposalOperationsOver(context);
14
+ const thing = (ref, what) => {
15
+ const found = thingOf(database, ref);
16
+ if (!found)
17
+ throw new CliError("not_found", `${what} ${ref} is not in the local store`);
18
+ return found;
19
+ };
20
+ return {
21
+ listRelations: async (filter = {}) => {
22
+ const limit = filter.limit ?? 50;
23
+ const page = filter.page ?? 1;
24
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500 || !Number.isInteger(page) || page < 1)
25
+ throw new CliError("validation_error", "limit takes 1–500 and page starts at 1");
26
+ if (filter.standing !== undefined && !STANDINGS.includes(filter.standing))
27
+ throw new CliError("validation_error", `standing is one of ${STANDINGS.join(", ")}`);
28
+ const at = now();
29
+ const where = [];
30
+ const params = [];
31
+ const add = (sql, ...values) => {
32
+ where.push(sql);
33
+ params.push(...values);
34
+ };
35
+ const end = (side, ref) => {
36
+ const found = thing(ref, `the ${side} end`);
37
+ add(`r.${side}_type = ? AND r.${side}_id = ?`, found.type, found.id);
38
+ };
39
+ if (filter.kind !== undefined)
40
+ add("r.kind = ?", filter.kind);
41
+ if (filter.role !== undefined)
42
+ add("ifnull(r.role, '') = ?", filter.role.trim());
43
+ if (filter.from !== undefined)
44
+ end("from", filter.from);
45
+ if (filter.to !== undefined)
46
+ end("to", filter.to);
47
+ const about = filter.about === undefined ? undefined : thing(filter.about, "the reference");
48
+ if (about)
49
+ add("((r.from_type = ? AND r.from_id = ?) OR (r.to_type = ? AND r.to_id = ?))", about.type, about.id, about.type, about.id);
50
+ if (filter.at !== undefined)
51
+ add("(r.starts_at IS NULL OR r.starts_at <= ?) AND (r.ends_at IS NULL OR ? < r.ends_at)", filter.at, filter.at);
52
+ if (filter.standing !== undefined)
53
+ add("r.standing = ?", filter.standing);
54
+ else if (!filter.includeEnded)
55
+ add("r.standing <> 'ended'");
56
+ if (filter.accounts !== undefined) {
57
+ const ids = filter.accounts.flatMap((key) => {
58
+ const row = database
59
+ .prepare("SELECT id FROM accounts WHERE provider = ? AND external_id = ?")
60
+ .get(key.provider, key.account);
61
+ return row ? [Number(row.id)] : [];
62
+ });
63
+ add(`(r.account_id IS NULL OR r.account_id IN (${ids.map(() => "?").join(", ") || "NULL"}))`, ...ids);
64
+ }
65
+ if (filter.deniedKinds?.length) {
66
+ const list = filter.deniedKinds.map(() => "?").join(", ");
67
+ add(`r.from_type NOT IN (${list}) AND r.to_type NOT IN (${list})`, ...filter.deniedKinds, ...filter.deniedKinds);
68
+ }
69
+ const rows = database
70
+ .prepare(`SELECT r.source, r.id FROM (
71
+ SELECT 'link' AS source, id, from_type, from_id, to_type, to_id, kind, role, account_id, starts_at, ends_at,
72
+ created_at,
73
+ CASE WHEN ends_at IS NOT NULL AND ends_at <= ? THEN 'ended' WHEN confirmed = 1 THEN 'confirmed'
74
+ WHEN deleted_at IS NOT NULL THEN 'ended' WHEN account_id IS NOT NULL THEN 'reported'
75
+ ELSE 'proposed' END AS standing
76
+ FROM links WHERE kind IN (${KINDS}) AND to_id IS NOT NULL AND ${notOverriddenSql("links")}
77
+ UNION ALL
78
+ SELECT 'proposal', id, target_type, target_id, ${typeOfRef("json_extract(payload, '$.to')")},
79
+ ${idOfRef("json_extract(payload, '$.to')")}, json_extract(payload, '$.kind'),
80
+ json_extract(payload, '$.role'), NULL, json_extract(payload, '$.startsAt'),
81
+ json_extract(payload, '$.endsAt'), created_at, 'proposed'
82
+ FROM proposed_actions WHERE kind = 'relationship' AND status = 'proposed'
83
+ ) r${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
84
+ ORDER BY r.standing = 'ended', r.created_at, r.source, r.id LIMIT ? OFFSET ?`)
85
+ .all(at, ...params, limit + 1, (page - 1) * limit);
86
+ const items = rows.slice(0, limit).map((row) => {
87
+ const item = row.source === "link" ? linkItem(Number(row.id), at) : proposalItem(String(row.id));
88
+ if (!about)
89
+ return item;
90
+ const from = thingOf(database, item.from);
91
+ const outgoing = from?.type === about.type && from.id === about.id;
92
+ return outgoing
93
+ ? { ...item, direction: "outgoing" }
94
+ : { ...item, direction: "incoming", inverse: inverseOf(item.kind) };
95
+ });
96
+ return { items, hasMore: rows.length > limit };
97
+ },
98
+ };
99
+ function custom(kind, from, to, role) {
100
+ const fromThing = thingOf(database, from);
101
+ const toThing = thingOf(database, to);
102
+ const roles = fromThing && toThing ? rolesOf(kind, fromThing.type, toThing.type) : undefined;
103
+ return role !== null && roles !== undefined && !roles.includes(role);
104
+ }
105
+ function linkItem(id, at) {
106
+ const relation = relationOf(linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(id)), at);
107
+ return { ...relation, source: "link", custom: custom(relation.kind, relation.from, relation.to, relation.role) };
108
+ }
109
+ function proposalItem(id) {
110
+ const action = operations.get(id);
111
+ const payload = action.payload;
112
+ const iso = (ms) => (ms === undefined ? null : new Date(ms).toISOString());
113
+ return {
114
+ id: action.id,
115
+ from: payload.from,
116
+ to: payload.to,
117
+ kind: payload.kind,
118
+ role: payload.role ?? null,
119
+ purpose: payload.purpose ?? null,
120
+ evidence: action.reason,
121
+ confirmed: false,
122
+ provenance: null,
123
+ confidenceCategory: "weak",
124
+ standing: "proposed",
125
+ position: payload.position ?? null,
126
+ startsAt: iso(payload.startsAt),
127
+ endsAt: iso(payload.endsAt),
128
+ createdAt: action.createdAt,
129
+ source: "proposal",
130
+ custom: custom(payload.kind, payload.from, payload.to, payload.role ?? null),
131
+ };
132
+ }
133
+ };
@@ -1,5 +1,5 @@
1
+ import { type RelationKind, type Standing } from "../../domain/relations.js";
1
2
  import { type Decider } from "../decisions.js";
2
- import type { RELATION_KINDS } from "./link-kinds.js";
3
3
  import type { Author } from "./memories.js";
4
4
  import { type Link } from "./notes.js";
5
5
  import type { StoreContext } from "./open.js";
@@ -10,7 +10,7 @@ export interface KnowledgeRelation {
10
10
  id: string;
11
11
  from: string;
12
12
  to: string;
13
- kind: (typeof RELATION_KINDS)[number];
13
+ kind: RelationKind;
14
14
  role: string | null;
15
15
  /** What a chat is for in the project, from the purposes memo's config lists; `null` means `work`. */
16
16
  purpose: string | null;
@@ -18,6 +18,13 @@ export interface KnowledgeRelation {
18
18
  confirmed: boolean;
19
19
  provenance: string | null;
20
20
  confidenceCategory: "owner-confirmed" | "weak";
21
+ /** Derived from the link: the owner's, a source's nobody confirmed, a suggestion, or one that ended. */
22
+ standing: Standing;
23
+ /** A job title beside the relationship, never its role. */
24
+ position: string | null;
25
+ /** When it held, as ISO times; `endsAt` exclusive; `null` when nobody said. */
26
+ startsAt: string | null;
27
+ endsAt: string | null;
21
28
  createdAt: string;
22
29
  }
23
30
  export interface RelateInput {
@@ -29,8 +36,12 @@ export interface RelateInput {
29
36
  evidence?: string;
30
37
  confirmed?: boolean;
31
38
  provenance?: string;
39
+ position?: string;
40
+ /** UTC ms; `endsAt` exclusive and after `startsAt`. */
41
+ startsAt?: number;
42
+ endsAt?: number;
32
43
  }
33
- export declare const relationOf: (link: Link) => KnowledgeRelation;
44
+ export declare const relationOf: (link: Link, now: number) => KnowledgeRelation;
34
45
  /** `relationship` proposals in `proposed_actions`: an agent's or a rule's, and the rejected ones a scan skips. */
35
46
  export declare const relationProposalsOver: (context: StoreContext) => {
36
47
  /**
@@ -40,8 +51,10 @@ export declare const relationProposalsOver: (context: StoreContext) => {
40
51
  state: (paired: () => {
41
52
  from: Thing;
42
53
  existing: Row | undefined;
43
- }, { to, kind }: {
44
- to: string;
54
+ ends: {
55
+ to: string;
56
+ };
57
+ }, { kind }: {
45
58
  kind: string;
46
59
  }) => {
47
60
  linked: boolean;
@@ -56,6 +69,9 @@ export declare const relationProposalsOver: (context: StoreContext) => {
56
69
  kind: string;
57
70
  role?: string;
58
71
  purpose?: string;
72
+ position?: string;
73
+ startsAt?: number;
74
+ endsAt?: number;
59
75
  evidence?: string[];
60
76
  reason?: string;
61
77
  } & Scored, by: Exclude<Author, "owner">) => ProposedAction;
@@ -88,11 +104,17 @@ export interface Scored {
88
104
  why: string;
89
105
  }[];
90
106
  }
91
- /** A relationship's role and purpose to set; `null` clears one. */
107
+ /** What to set on a relationship; `null` clears one. Times are UTC ms, `endsAt` exclusive. */
92
108
  export interface RelationUpdate {
93
109
  role?: string | null;
94
110
  purpose?: string | null;
111
+ position?: string | null;
112
+ startsAt?: number | null;
113
+ endsAt?: number | null;
95
114
  }
115
+ /** A relationship ends after it starts. */
116
+ export declare const spanOf: (startsAt: number | null | undefined, endsAt: number | null | undefined) => void;
117
+ export declare const positionOf: (position: string) => string;
96
118
  export interface LinkDecision {
97
119
  confirm: boolean;
98
120
  by: Decider;
@@ -1,11 +1,14 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { standingOf } from "../../domain/relations.js";
2
3
  import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
3
4
  import { actorOfOrigin, botNamed, ownerPerson } from "./actors.js";
4
5
  import { insertLink, linkOf, purposeOf } from "./notes.js";
5
6
  import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
7
+ import { checkStoredRole } from "./relation-roles.js";
6
8
  import { thingOf } from "./things.js";
7
9
  import { write } from "./transaction.js";
8
- export const relationOf = (link) => ({
10
+ const isoOf = (ms) => (ms === undefined ? null : new Date(ms).toISOString());
11
+ export const relationOf = (link, now) => ({
9
12
  id: link.id,
10
13
  from: link.from,
11
14
  to: String(link.to),
@@ -16,6 +19,10 @@ export const relationOf = (link) => ({
16
19
  confirmed: link.confirmed,
17
20
  provenance: link.provenance,
18
21
  confidenceCategory: link.confirmed ? "owner-confirmed" : "weak",
22
+ standing: standingOf(link, now),
23
+ position: link.position ?? null,
24
+ startsAt: isoOf(link.startsAt),
25
+ endsAt: isoOf(link.endsAt),
19
26
  createdAt: link.createdAt,
20
27
  });
21
28
  /** `relationship` proposals in `proposed_actions`: an agent's or a rule's, and the rejected ones a scan skips. */
@@ -39,14 +46,89 @@ export const relationProposalsOver = (context) => {
39
46
  "VALUES ('relationship', ?, ?, ?, ?, 'rejected', ?, ?, ?, ?, ?, ?, ?, ?)")
40
47
  .run(from?.type ?? null, from?.id ?? null, JSON.stringify({ from: link.from, to: link.to, kind: link.kind, ...(link.role ? { role: link.role } : {}) }), link.evidence, proposed.type, proposed.id, decided.type, decided.id, at, JSON.stringify({ reason: why.join(": "), link: link.id }), at, at);
41
48
  };
49
+ /** The role lists may have changed since a proposal was made: a role is checked when it is written. */
50
+ const checkedRole = (link, role) => {
51
+ if (typeof role !== "string")
52
+ return;
53
+ const [fromType, , toType] = fromTo(link);
54
+ checkStoredRole(database, link.kind, fromType, toType, role);
55
+ };
42
56
  const applyUpdate = (link, input) => {
43
57
  const changes = changesOf(input);
58
+ checkedRole(link, changes.role);
59
+ if ("role" in changes) {
60
+ const taken = database
61
+ .prepare("SELECT b.id FROM links a JOIN links b ON b.kind = a.kind AND b.from_type = a.from_type AND b.from_id = a.from_id " +
62
+ "AND b.to_type = a.to_type AND b.to_id = a.to_id AND b.anchor IS a.anchor AND b.account_id IS a.account_id " +
63
+ "AND ifnull(b.role, '') = ifnull(?, '') AND b.id <> a.id WHERE a.id = ?")
64
+ .get(changes.role ?? null, Number(link.id));
65
+ if (taken)
66
+ throw new CliError("validation_error", `relationship ${String(taken.id)} already holds that role`, {
67
+ reason: "relationship.exists",
68
+ });
69
+ }
70
+ const startsAt = "startsAt" in changes ? (changes.startsAt ?? undefined) : link.startsAt;
71
+ const endsAt = "endsAt" in changes ? (changes.endsAt ?? undefined) : link.endsAt;
72
+ spanOf(startsAt, endsAt);
44
73
  database
45
74
  .prepare("UPDATE links SET role = CASE WHEN ? THEN ? ELSE role END, purpose = CASE WHEN ? THEN ? ELSE purpose END, " +
46
- "updated_at = ? WHERE id = ?")
47
- .run(Number("role" in changes), changes.role ?? null, Number("purpose" in changes), changes.purpose ?? null, now(), Number(link.id));
75
+ "starts_at = CASE WHEN ? THEN ? ELSE starts_at END, ends_at = CASE WHEN ? THEN ? ELSE ends_at END, " +
76
+ "metadata = CASE WHEN ? THEN (CASE WHEN ? IS NULL THEN json_remove(coalesce(metadata, '{}'), '$.position') " +
77
+ "ELSE json_set(coalesce(metadata, '{}'), '$.position', ?) END) ELSE metadata END, updated_at = ? WHERE id = ?")
78
+ .run(Number("role" in changes), changes.role ?? null, Number("purpose" in changes), changes.purpose ?? null, Number("startsAt" in changes), changes.startsAt ?? null, Number("endsAt" in changes), changes.endsAt ?? null, Number("position" in changes), changes.position ?? null, changes.position ?? null, now(), Number(link.id));
48
79
  return linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(Number(link.id)));
49
80
  };
81
+ /**
82
+ * The owner's change. On a link a source reported, the source's row stays for its sync to diff, and one owner link
83
+ * overrides it (`metadata.overrides`): made by the first change, changed in place by every later one. Reads show the
84
+ * override instead of the source's row.
85
+ */
86
+ const ownerUpdate = (link, input) => {
87
+ if (link.accountId === undefined || link.confirmed)
88
+ return applyUpdate(link, input);
89
+ const held = database
90
+ .prepare("SELECT * FROM links WHERE kind = ? AND from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? " +
91
+ "AND account_id IS NULL AND json_extract(metadata, '$.overrides') = ?")
92
+ .get(...endsOf(link), Number(link.id));
93
+ if (held)
94
+ return applyUpdate(linkOf(database, held), input);
95
+ const changes = changesOf(input);
96
+ const pick = (key, kept) => key in changes ? changes[key] : kept;
97
+ const role = pick("role", link.role) ?? null;
98
+ const at = now();
99
+ const metadata = JSON.stringify({
100
+ overrides: Number(link.id),
101
+ ...(link.position ? { position: link.position } : {}),
102
+ });
103
+ // An owner link of that role on the pair already (from `relate`) becomes the override rather than a second one.
104
+ const same = database
105
+ .prepare("SELECT id FROM links WHERE kind = ? AND from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? " +
106
+ "AND account_id IS NULL AND anchor IS NULL AND ifnull(role, '') = ?")
107
+ .get(...endsOf(link), role ?? "");
108
+ const id = same
109
+ ? Number(same.id)
110
+ : Number(database
111
+ .prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, role, purpose, source, metadata, confirmed, " +
112
+ "starts_at, ends_at, created_at, author, updated_at) " +
113
+ "VALUES (?, ?, ?, ?, ?, ?, ?, 'owner', ?, 1, ?, ?, ?, 'owner', ?) RETURNING id")
114
+ .get(...fromTo(link), link.kind, role, link.purpose, metadata, link.startsAt ?? null, link.endsAt ?? null, at, at)?.id);
115
+ if (same)
116
+ database
117
+ .prepare("UPDATE links SET metadata = json_set(coalesce(metadata, '{}'), '$.overrides', ?) WHERE id = ?")
118
+ .run(Number(link.id), id);
119
+ const { role: _, ...rest } = changes;
120
+ const owned = linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(id));
121
+ return Object.keys(rest).length ? applyUpdate(owned, rest) : owned;
122
+ };
123
+ const fromTo = (link) => {
124
+ const from = thingOf(database, link.from);
125
+ const to = thingOf(database, String(link.to));
126
+ return [from.type, from.id, to.type, to.id];
127
+ };
128
+ const endsOf = (link) => {
129
+ const [fromType, fromId, toType, toId] = fromTo(link);
130
+ return [link.kind, fromType, fromId, toType, toId];
131
+ };
50
132
  /**
51
133
  * A scan's newer score on a pending proposal, in place under the same id. A rule's own row takes the new score,
52
134
  * signals, evidence and purpose; another proposer's row keeps its author, evidence and purpose and gains the signals.
@@ -76,7 +158,7 @@ export const relationProposalsOver = (context) => {
76
158
  * Where a pair stands before a scan proposes it: a link joins it, a `relationship` proposal for it was rejected,
77
159
  * or one is pending. A rejection is matched by the pair alone, whoever proposed it and with whatever scorer.
78
160
  */
79
- state: (paired, { to, kind }) => {
161
+ state: (paired, { kind }) => {
80
162
  let found;
81
163
  try {
82
164
  found = paired();
@@ -87,6 +169,7 @@ export const relationProposalsOver = (context) => {
87
169
  throw error;
88
170
  }
89
171
  const { from, existing } = found;
172
+ const { to } = found.ends;
90
173
  const rows = database
91
174
  .prepare("SELECT id, status FROM proposed_actions WHERE kind='relationship' AND status IN ('proposed','rejected') " +
92
175
  "AND target_type=? AND target_id=? AND json_extract(payload,'$.to')=? AND json_extract(payload,'$.kind')=? " +
@@ -102,6 +185,7 @@ export const relationProposalsOver = (context) => {
102
185
  },
103
186
  /** The same pending pair returns the proposal already held; a scored one updates its score in place. */
104
187
  propose: (from, input, by) => {
188
+ spanOf(input.startsAt, input.endsAt);
105
189
  const evidence = input.evidence ?? [];
106
190
  if (!Array.isArray(evidence) || evidence.length > 5 || evidence.some((ref) => typeof ref !== "string"))
107
191
  throw new CliError("validation_error", "a relationship proposal cites up to 5 references");
@@ -109,8 +193,9 @@ export const relationProposalsOver = (context) => {
109
193
  return write(database, () => {
110
194
  const held = database
111
195
  .prepare("SELECT id FROM proposed_actions WHERE kind='relationship' AND status='proposed' AND target_type=? AND target_id=? " +
112
- "AND json_extract(payload,'$.to')=? AND json_extract(payload,'$.kind')=? ORDER BY id LIMIT 1")
113
- .get(from.type, from.id, input.to, input.kind);
196
+ "AND json_extract(payload,'$.to')=? AND json_extract(payload,'$.kind')=? " +
197
+ "AND (? IS NULL OR json_extract(payload,'$.role') IS ?) ORDER BY id LIMIT 1")
198
+ .get(from.type, from.id, input.to, input.kind, input.role ?? null, input.role ?? null);
114
199
  if (held) {
115
200
  const action = operations.get(String(held.id));
116
201
  return scored ? rescored(action, input, scored, by) : action;
@@ -125,6 +210,9 @@ export const relationProposalsOver = (context) => {
125
210
  kind: input.kind,
126
211
  ...(input.role === undefined ? {} : { role: input.role }),
127
212
  ...(input.purpose === undefined ? {} : { purpose: purposeOf(input.purpose) }),
213
+ ...(input.position === undefined ? {} : { position: positionOf(input.position) }),
214
+ ...(input.startsAt === undefined ? {} : { startsAt: input.startsAt }),
215
+ ...(input.endsAt === undefined ? {} : { endsAt: input.endsAt }),
128
216
  evidence,
129
217
  ...scored,
130
218
  },
@@ -133,9 +221,10 @@ export const relationProposalsOver = (context) => {
133
221
  });
134
222
  },
135
223
  rejected: (link, by, reason) => rejected(link, by, reason),
136
- update: (link, input) => write(database, () => applyUpdate(link, input)),
224
+ update: (link, input) => write(database, () => ownerUpdate(link, input)),
137
225
  proposeUpdate: (link, input, by) => {
138
226
  const changes = changesOf(input);
227
+ checkedRole(link, changes.role);
139
228
  return write(database, () => {
140
229
  const from = thingOf(database, link.from);
141
230
  const held = database
@@ -155,7 +244,13 @@ export const relationProposalsOver = (context) => {
155
244
  to: link.to,
156
245
  kind: link.kind,
157
246
  changes,
158
- before: { role: link.role, purpose: link.purpose },
247
+ before: {
248
+ role: link.role,
249
+ purpose: link.purpose,
250
+ position: link.position ?? null,
251
+ startsAt: link.startsAt ?? null,
252
+ endsAt: link.endsAt ?? null,
253
+ },
159
254
  },
160
255
  ...(input.reason === undefined ? {} : { reason: input.reason }),
161
256
  });
@@ -174,7 +269,7 @@ export const relationProposalsOver = (context) => {
174
269
  const row = database.prepare("SELECT * FROM links WHERE id = ?").get(Number(payload.relationship));
175
270
  if (!row)
176
271
  throw new CliError("not_found", `relationship ${payload.relationship} is gone`);
177
- const link = applyUpdate(linkOf(database, row), payload.changes);
272
+ const link = ownerUpdate(linkOf(database, row), payload.changes);
178
273
  return {
179
274
  proposal: operations.approve(id, { relationship: link.id, ...(reason === undefined ? {} : { reason }) }, author),
180
275
  link,
@@ -195,12 +290,18 @@ export const relationProposalsOver = (context) => {
195
290
  return { proposal: operations.reject(id, author, reason === undefined ? undefined : { reason }), link: null };
196
291
  const payload = proposal.payload;
197
292
  const key = proposal.kind === "key_document";
293
+ const ends = key ? undefined : [thingOf(database, String(payload.from)), thingOf(database, String(payload.to))];
294
+ if (ends?.[0] && ends[1] && payload.role !== undefined)
295
+ checkStoredRole(database, payload.kind ?? "member-of", ends[0].type, ends[1].type, payload.role);
198
296
  const link = insertLink(context, {
199
297
  from: String(key ? payload.ref : payload.from),
200
298
  to: String(key ? payload.project : payload.to),
201
299
  kind: key ? "related-to" : (payload.kind ?? "member-of"),
202
300
  ...(key ? { role: "key" } : payload.role === undefined ? {} : { role: payload.role }),
203
301
  ...(key || payload.purpose === undefined ? {} : { purpose: payload.purpose }),
302
+ ...(key || payload.position === undefined ? {} : { position: payload.position }),
303
+ ...(key || payload.startsAt === undefined ? {} : { startsAt: payload.startsAt }),
304
+ ...(key || payload.endsAt === undefined ? {} : { endsAt: payload.endsAt }),
204
305
  ...(proposal.reason === null ? {} : { evidence: proposal.reason }),
205
306
  ...decidedOrigin(decision.by),
206
307
  });
@@ -220,6 +321,7 @@ export const relationProposalsOver = (context) => {
220
321
  const link = linkOf(database, row);
221
322
  if (!decision.confirm) {
222
323
  rejected(link, decision.by, decision.reason);
324
+ database.prepare("UPDATE links SET updated_at = ? WHERE id = ?").run(now(), Number(id));
223
325
  database.prepare("DELETE FROM links WHERE id = ?").run(Number(id));
224
326
  return null;
225
327
  }
@@ -245,6 +347,22 @@ const scoredOf = (input) => {
245
347
  throw new CliError("validation_error", "a signal names its scorer, a weight of 0–1 and why, up to 500 characters");
246
348
  return { score, signals: signals.map(({ scorer, weight, why }) => ({ scorer, weight, why })) };
247
349
  };
350
+ const timeOf = (value, what) => {
351
+ if (!Number.isSafeInteger(value) || value < 0)
352
+ throw new CliError("validation_error", `${what} is UTC milliseconds`);
353
+ return value;
354
+ };
355
+ /** A relationship ends after it starts. */
356
+ export const spanOf = (startsAt, endsAt) => {
357
+ if (startsAt != null && endsAt != null && endsAt <= startsAt)
358
+ throw new CliError("validation_error", "a relationship ends after it starts");
359
+ };
360
+ export const positionOf = (position) => {
361
+ const value = position.trim();
362
+ if (!value || value.length > 200)
363
+ throw new CliError("validation_error", "a position takes 1–200 characters");
364
+ return value;
365
+ };
248
366
  /** What a relationship update sets, checked; `null` clears a field and an absent one is left alone. */
249
367
  const changesOf = (input) => {
250
368
  const changes = {};
@@ -252,8 +370,14 @@ const changesOf = (input) => {
252
370
  changes.role = input.role === null ? null : roleOf(input.role);
253
371
  if (input.purpose !== undefined)
254
372
  changes.purpose = input.purpose === null ? null : purposeOf(input.purpose);
373
+ if (input.position !== undefined)
374
+ changes.position = input.position === null ? null : positionOf(input.position);
375
+ if (input.startsAt !== undefined)
376
+ changes.startsAt = input.startsAt === null ? null : timeOf(input.startsAt, "a start");
377
+ if (input.endsAt !== undefined)
378
+ changes.endsAt = input.endsAt === null ? null : timeOf(input.endsAt, "an end");
255
379
  if (!Object.keys(changes).length)
256
- throw new CliError("validation_error", "a relationship update sets a role, a purpose or both");
380
+ throw new CliError("validation_error", "a relationship update sets a role, a purpose, a position or its dates");
257
381
  return changes;
258
382
  };
259
383
  const roleOf = (role) => {
@@ -0,0 +1,8 @@
1
+ import type { StoreContext } from "./open.js";
2
+ import { type RelationList } from "./relation-list.js";
3
+ import { type RelationRoles } from "./relation-roles.js";
4
+ export { checkStoredRole } from "./relation-roles.js";
5
+ /** The knowledge store's relationship reads: the filtered list and the role lists. */
6
+ export interface RelationReads extends RelationList, RelationRoles {
7
+ }
8
+ export declare const relationReadsOver: (context: StoreContext) => RelationReads;
@@ -0,0 +1,7 @@
1
+ import { relationListOver } from "./relation-list.js";
2
+ import { relationRolesOver } from "./relation-roles.js";
3
+ export { checkStoredRole } from "./relation-roles.js";
4
+ export const relationReadsOver = (context) => ({
5
+ ...relationListOver(context),
6
+ ...relationRolesOver(context),
7
+ });
@@ -0,0 +1,26 @@
1
+ import { type RoleList } from "../../domain/relations.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export interface RelationRole {
5
+ id: string;
6
+ label: string | null;
7
+ builtIn: boolean;
8
+ }
9
+ export interface RelationRoles {
10
+ /** A list's roles: the built-in ones first, then the owner's, in the order he added them. */
11
+ roles(list: RoleList): Promise<RelationRole[]>;
12
+ /** Adds an owner role to a list; an id the list holds already is refused. */
13
+ addRole(list: RoleList, id: string, label?: string): Promise<RelationRole[]>;
14
+ /** Removes an owner role; a built-in one, or one a stored relationship still holds, is refused. */
15
+ removeRole(list: RoleList, id: string): Promise<RelationRole[]>;
16
+ }
17
+ /** The owner's roles for a list; a value this build cannot read is none. */
18
+ export declare const ownerRolesOf: (database: CacheDatabase, list: RoleList) => {
19
+ id: string;
20
+ label: string | null;
21
+ }[];
22
+ /** The owner's role ids a relationship of these ends may also take. */
23
+ export declare const extraRolesOf: (database: CacheDatabase, kind: string, from: string, to: string) => string[];
24
+ /** `checkRole` with the owner's own roles for the list the ends take. */
25
+ export declare const checkStoredRole: (database: CacheDatabase, kind: string, from: string, to: string, role: string) => string;
26
+ export declare const relationRolesOver: ({ database, now }: StoreContext) => RelationRoles;
@@ -0,0 +1,91 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { checkRole, ROLE_LISTS, roleListOf } from "../../domain/relations.js";
3
+ import { write } from "./transaction.js";
4
+ const settingOf = (list) => `relationships.roles.${list}`;
5
+ const isList = (list) => Object.hasOwn(ROLE_LISTS, list);
6
+ const listOf = (list) => {
7
+ if (!isList(list))
8
+ throw new CliError("validation_error", `a role list is one of ${Object.keys(ROLE_LISTS).join(", ")}`);
9
+ return list;
10
+ };
11
+ /** The owner's roles for a list; a value this build cannot read is none. */
12
+ export const ownerRolesOf = (database, list) => {
13
+ const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(settingOf(list));
14
+ try {
15
+ const value = row ? JSON.parse(String(row.value)) : [];
16
+ return Array.isArray(value)
17
+ ? value.flatMap((one) => typeof one?.id === "string" ? [{ id: one.id, label: typeof one.label === "string" ? one.label : null }] : [])
18
+ : [];
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ };
24
+ /** The owner's role ids a relationship of these ends may also take. */
25
+ export const extraRolesOf = (database, kind, from, to) => {
26
+ const list = roleListOf(kind, from, to);
27
+ return list ? ownerRolesOf(database, list).map(({ id }) => id) : [];
28
+ };
29
+ /** `checkRole` with the owner's own roles for the list the ends take. */
30
+ export const checkStoredRole = (database, kind, from, to, role) => checkRole(kind, from, to, role, extraRolesOf(database, kind, from, to));
31
+ /** The links whose role comes from this list: a person's on an organization or a project, a deal's or a lead's people. */
32
+ const usedBy = (database, list, role) => {
33
+ const links = list === "deal"
34
+ ? "kind = 'related-to' AND from_type IN ('deal', 'lead')"
35
+ : `kind = 'member-of' AND from_type = 'person' AND to_type = '${list}'`;
36
+ // A pending proposal would make the role a relationship's once approved: it counts as a use.
37
+ const proposals = list === "deal"
38
+ ? "target_type IN ('deal', 'lead') AND json_extract(payload, '$.kind') = 'related-to'"
39
+ : `target_type = 'person' AND json_extract(payload, '$.kind') = 'member-of' AND json_extract(payload, '$.to') LIKE '${list}:%'`;
40
+ return Number(database
41
+ .prepare(`SELECT (SELECT count(*) FROM links WHERE role = ? AND ${links}) + (SELECT count(*) FROM proposed_actions ` +
42
+ `WHERE status = 'proposed' AND ${proposals} AND ((kind = 'relationship' AND json_extract(payload, '$.role') = ?) ` +
43
+ "OR (kind = 'relationship_update' AND json_extract(payload, '$.changes.role') = ?))) AS n")
44
+ .get(role, role, role)?.n);
45
+ };
46
+ export const relationRolesOver = ({ database, now }) => {
47
+ const all = (list) => [
48
+ ...ROLE_LISTS[list].map((id) => ({ id, label: null, builtIn: true })),
49
+ ...ownerRolesOf(database, list).map((role) => ({ ...role, builtIn: false })),
50
+ ];
51
+ const save = (list, roles) => database
52
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
53
+ .run(settingOf(list), JSON.stringify(roles.map(({ id, label }) => (label ? { id, label } : { id }))), now());
54
+ return {
55
+ roles: async (list) => all(listOf(list)),
56
+ addRole: async (name, id, label) => write(database, () => {
57
+ const list = listOf(name);
58
+ const role = id.trim();
59
+ if (!/^[a-z][a-z0-9-]{0,39}$/.test(role))
60
+ throw new CliError("validation_error", "a role id is 1–40 lowercase letters, digits and -, from a letter");
61
+ const text = label?.trim() || null;
62
+ if (text !== null && text.length > 80)
63
+ throw new CliError("validation_error", "a role's label takes 1–80 characters");
64
+ if (all(list).some((one) => one.id === role))
65
+ throw new CliError("validation_error", `the ${list} roles hold ${role} already`, {
66
+ reason: "relationship.role-exists",
67
+ });
68
+ save(list, [...ownerRolesOf(database, list), { id: role, label: text }]);
69
+ return all(list);
70
+ }),
71
+ removeRole: async (name, given) => write(database, () => {
72
+ const list = listOf(name);
73
+ const id = given.trim();
74
+ if (ROLE_LISTS[list].includes(id))
75
+ throw new CliError("validation_error", `${id} is a built-in ${list} role and stays`, {
76
+ reason: "relationship.role-built-in",
77
+ });
78
+ const owned = ownerRolesOf(database, list);
79
+ if (!owned.some((one) => one.id === id))
80
+ throw new CliError("not_found", `the ${list} roles hold no ${id}`);
81
+ const held = usedBy(database, list, id);
82
+ if (held)
83
+ throw new CliError("validation_error", `${held} relationship(s) still hold the ${list} role ${id}`, {
84
+ reason: "relationship.role-in-use",
85
+ count: held,
86
+ });
87
+ save(list, owned.filter((one) => one.id !== id));
88
+ return all(list);
89
+ }),
90
+ };
91
+ };