@wirecat/cli-core 0.616.0 → 0.618.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 (57) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/background/backfill.d.ts +21 -0
  3. package/dist/background/backfill.js +41 -0
  4. package/dist/background/report/messages.js +4 -1
  5. package/dist/background/report/view.js +4 -1
  6. package/dist/background/schedules.d.ts +17 -0
  7. package/dist/background/schedules.js +21 -8
  8. package/dist/cli/context.d.ts +5 -0
  9. package/dist/cli/index.d.ts +3 -2
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/messenger/serve-command.js +24 -2
  12. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  13. package/dist/cli/messenger/serve-outdated.js +100 -0
  14. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  15. package/dist/cli/schedule/schedule-command.js +13 -0
  16. package/dist/cli/store-recover.js +26 -2
  17. package/dist/domain/links.d.ts +17 -4
  18. package/dist/domain/links.js +20 -7
  19. package/dist/domain/models.d.ts +6 -0
  20. package/dist/domain/relations.d.ts +15 -0
  21. package/dist/domain/relations.js +23 -0
  22. package/dist/errors/reasons.js +7 -0
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +2 -2
  25. package/dist/meetings/mcp/index.d.ts +15 -15
  26. package/dist/services/link-scorers/chat-senders.js +39 -29
  27. package/dist/services/link-scorers/member-chats.js +4 -3
  28. package/dist/services/link-scorers/member-dialog.js +5 -7
  29. package/dist/services/link-scorers/scan.js +17 -8
  30. package/dist/services/link-scorers/shared.d.ts +6 -2
  31. package/dist/services/link-scorers/shared.js +6 -2
  32. package/dist/services/link-scorers/types.d.ts +2 -0
  33. package/dist/store/migrations.d.ts +1 -1
  34. package/dist/store/migrations.js +35 -12
  35. package/dist/store/recover.d.ts +34 -0
  36. package/dist/store/recover.js +188 -6
  37. package/dist/store/refill.d.ts +28 -0
  38. package/dist/store/refill.js +120 -0
  39. package/dist/store/sqlite/bot-tokens.d.ts +11 -0
  40. package/dist/store/sqlite/bot-tokens.js +57 -0
  41. package/dist/store/sqlite/chats.js +2 -0
  42. package/dist/store/sqlite/clients.d.ts +7 -3
  43. package/dist/store/sqlite/clients.js +11 -7
  44. package/dist/store/sqlite/email-index.js +9 -11
  45. package/dist/store/sqlite/knowledge.js +3 -1
  46. package/dist/store/sqlite/messages.d.ts +1 -1
  47. package/dist/store/sqlite/messages.js +3 -1
  48. package/dist/store/sqlite/note-index.js +9 -7
  49. package/dist/store/sqlite/notes.d.ts +1 -1
  50. package/dist/store/sqlite/notes.js +8 -6
  51. package/dist/store/sqlite/open-store.js +2 -0
  52. package/dist/store/sqlite/relation-list.js +2 -0
  53. package/dist/store/sqlite/relation-proposals.d.ts +12 -1
  54. package/dist/store/sqlite/relation-proposals.js +50 -11
  55. package/dist/store/sqlite/transaction.d.ts +13 -0
  56. package/dist/store/sqlite/transaction.js +25 -17
  57. package/package.json +1 -1
@@ -0,0 +1,57 @@
1
+ import { NORMALIZER_VERSION, normalize } from "../normalize.js";
2
+ import { write } from "./transaction.js";
3
+ import { purgeVectorsOf } from "./vectors.js";
4
+ // Only a digit may not come before: `bot<id>:<secret>` in an API URL is the shape pasted most often.
5
+ const BOT_TOKEN = /(?<!\d)(\d{6,12}):[A-Za-z0-9_-]{30,40}(?![A-Za-z0-9_-])/g;
6
+ const MAY_HOLD = "*[0-9][0-9][0-9][0-9][0-9][0-9]:*";
7
+ const MASKED_THROUGH = "bot_tokens_masked_through";
8
+ /** A messenger bot's token keeps the bot's id, which is public, and loses its secret half. */
9
+ export const withoutBotTokens = (text) => text.replace(BOT_TOKEN, "$1:<bot token hidden>");
10
+ export const withoutBotTokensIn = (message) => {
11
+ const { replyTo } = message;
12
+ return {
13
+ ...message,
14
+ text: withoutBotTokens(message.text),
15
+ ...(replyTo ? { replyTo: { ...replyTo, text: withoutBotTokens(replyTo.text) } } : {}),
16
+ };
17
+ };
18
+ /**
19
+ * Masks the tokens in messages this build did not write: those stored before it, and those an older build saves
20
+ * later. On every open, from the newest message checked last time; a store with nothing new costs two index probes.
21
+ * The scan reads outside a write, so the first one, over the whole archive, does not hold other writers back.
22
+ */
23
+ export const maskStoredBotTokens = (context) => {
24
+ const { database, now } = context;
25
+ const through = Number(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MASKED_THROUGH)?.value ?? 0);
26
+ const newest = Number(database.prepare("SELECT max(id) AS id FROM messages").get()?.id ?? 0);
27
+ if (newest <= through)
28
+ return 0;
29
+ const messages = database
30
+ .prepare("SELECT id, text, reply_to FROM messages WHERE id > ? AND id <= ? AND (text GLOB ? OR reply_to GLOB ?)")
31
+ .all(through, newest, MAY_HOLD, MAY_HOLD)
32
+ .filter((row) => masks(row.text) || masks(row.reply_to));
33
+ const revisions = database
34
+ .prepare("SELECT id, text FROM message_revisions WHERE message_id > ? AND message_id <= ? AND text GLOB ?")
35
+ .all(through, newest, MAY_HOLD)
36
+ .filter((row) => masks(row.text));
37
+ write(database, () => {
38
+ // Only the text read above: a message another process changed since then was written by a build that masks.
39
+ const message = database.prepare(`UPDATE messages SET text = ?, normalized_text = ?, normalizer_version = ?, reply_to = ?
40
+ WHERE id = ? AND text = ? AND reply_to IS ?`);
41
+ for (const row of messages) {
42
+ const text = withoutBotTokens(String(row.text));
43
+ const quote = row.reply_to == null ? null : withoutBotTokens(String(row.reply_to));
44
+ const { changes } = message.run(text, normalize(text), NORMALIZER_VERSION, quote, Number(row.id), row.text, row.reply_to);
45
+ if (Number(changes) > 0)
46
+ purgeVectorsOf(context, Number(row.id));
47
+ }
48
+ const revision = database.prepare("UPDATE message_revisions SET text = ? WHERE id = ? AND text = ?");
49
+ for (const row of revisions)
50
+ revision.run(withoutBotTokens(String(row.text)), Number(row.id), row.text);
51
+ database
52
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
53
+ .run(MASKED_THROUGH, String(newest), now());
54
+ });
55
+ return messages.length + revisions.length;
56
+ };
57
+ const masks = (value) => value != null && withoutBotTokens(String(value)) !== value;
@@ -150,6 +150,7 @@ export const upsertChat = (context, accountKey, chat) => {
150
150
  metadata: mergedMetadata(stored?.metadata ?? null, chat.providerMetadata),
151
151
  membershipState: chat.membershipState === "member" ? null : (chat.membershipState ?? null),
152
152
  ...stateOf(chat, now()),
153
+ ...(chat.searchable === false ? { searchable: 0 } : {}),
153
154
  createdAt: now(),
154
155
  updatedAt: now(),
155
156
  })
@@ -157,6 +158,7 @@ export const upsertChat = (context, accountKey, chat) => {
157
158
  target: [chats.accountId, chats.externalId],
158
159
  set: {
159
160
  kind: sql `excluded.kind`,
161
+ ...(chat.searchable === false ? { searchable: 0 } : {}),
160
162
  ...(chat.parentChatId === undefined ? {} : { parentChatId: sql `excluded.parent_chat_id` }),
161
163
  scope: sql `coalesce(excluded.scope, ${chats.scope})`,
162
164
  ...(chat.title === undefined ? {} : { title: sql `excluded.title`, titleFolded: sql `excluded.title_folded` }),
@@ -10,12 +10,15 @@ export interface StoreClient {
10
10
  }
11
11
  /** Readable from any schema: `store_settings` is in the initial migration. */
12
12
  export declare const storeClients: (database: CacheDatabase) => StoreClient[];
13
- /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
14
- export declare const recordClient: (database: CacheDatabase, { command, version, speaks }: {
13
+ type Client = {
15
14
  command: string;
16
15
  version: string;
17
16
  speaks: number;
18
- }, now: number) => void;
17
+ };
18
+ /** Whether `recordClient` would write nothing: the CLI's version, cli-core and schema are unchanged within a day. */
19
+ export declare const clientRecorded: (database: CacheDatabase, { command, version, speaks }: Client, now: number) => boolean;
20
+ /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
21
+ export declare const recordClient: (database: CacheDatabase, { command, version, speaks }: Client, now: number) => void;
19
22
  /** The sentence an upgrade that raised the store's minimum prints: who can no longer open it, and what to run. */
20
23
  export declare const lockedOutNotice: (clients: readonly StoreClient[], { command, schema, minCompatible }: {
21
24
  command?: string;
@@ -24,3 +27,4 @@ export declare const lockedOutNotice: (clients: readonly StoreClient[], { comman
24
27
  }) => string | undefined;
25
28
  /** Added to a refusal: this tool's own command, and the CLI that moved the store, so the owner knows what to run. */
26
29
  export declare const refusalAdvice: (clients: readonly StoreClient[], command: string | undefined, schema: number) => string;
30
+ export {};
@@ -38,18 +38,22 @@ export const storeClients = (database) => {
38
38
  return [];
39
39
  }
40
40
  };
41
- /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
42
- export const recordClient = (database, { command, version, speaks }, now) => {
41
+ /** Whether `recordClient` would write nothing: the CLI's version, cli-core and schema are unchanged within a day. */
42
+ export const clientRecorded = (database, { command, version, speaks }, now) => {
43
43
  if (!hasSettings(database))
44
- return;
45
- const stored = storeClients(database);
46
- const same = stored.find((one) => one.command === command);
47
- if (same &&
44
+ return true;
45
+ const same = storeClients(database).find((one) => one.command === command);
46
+ return (same !== undefined &&
48
47
  same.version === version &&
49
48
  same.core === coreVersion &&
50
49
  same.speaks === speaks &&
51
- now - same.seenAt < 86_400_000)
50
+ now - same.seenAt < 86_400_000);
51
+ };
52
+ /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
53
+ export const recordClient = (database, { command, version, speaks }, now) => {
54
+ if (clientRecorded(database, { command, version, speaks }, now))
52
55
  return;
56
+ const stored = storeClients(database);
53
57
  const entry = { command, version, core: coreVersion, speaks, seenAt: now };
54
58
  database
55
59
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
@@ -116,11 +116,13 @@ export const drainEmailIndex = (database, stemmerFor) => {
116
116
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
117
117
  .run(MAIL_CUT, CUT, Date.now());
118
118
  });
119
- database
120
- .prepare(`INSERT OR IGNORE INTO email_index_pending (indexable_type, id)
121
- SELECT DISTINCT 'email_thread', e.email_thread_id FROM email_index_pending q JOIN emails e ON e.id = q.id
122
- WHERE q.indexable_type = 'email' AND e.email_thread_id IS NOT NULL`)
123
- .run();
119
+ const unqueued = `FROM email_index_pending q JOIN emails e ON e.id = q.id
120
+ WHERE q.indexable_type = 'email' AND e.email_thread_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM email_index_pending t
121
+ WHERE t.indexable_type = 'email_thread' AND t.id = e.email_thread_id)`;
122
+ if (database.prepare(`SELECT 1 ${unqueued} LIMIT 1`).get())
123
+ write(database, () => database
124
+ .prepare(`INSERT OR IGNORE INTO email_index_pending (indexable_type, id) SELECT DISTINCT 'email_thread', e.email_thread_id ${unqueued}`)
125
+ .run());
124
126
  // Attachments saved before their text was cut into pieces get them here, once.
125
127
  const unchunked = database
126
128
  .prepare(`SELECT DISTINCT e.id, e.account_id FROM attachments a JOIN emails e ON a.attachable_type = 'email' AND e.id = a.attachable_id
@@ -139,8 +141,8 @@ export const drainEmailIndex = (database, stemmerFor) => {
139
141
  const next = database.prepare("SELECT id FROM email_index_pending WHERE indexable_type = 'email_thread' ORDER BY id LIMIT 50");
140
142
  const done = database.prepare("DELETE FROM email_index_pending WHERE indexable_type = 'email_thread' AND id = ?");
141
143
  let threads = 0;
142
- for (;;) {
143
- const count = write(database, () => {
144
+ while (next.all().length > 0)
145
+ threads += write(database, () => {
144
146
  const ids = next.all().map(({ id }) => Number(id));
145
147
  for (const id of ids) {
146
148
  chunkThread(database, id, Date.now());
@@ -148,9 +150,5 @@ export const drainEmailIndex = (database, stemmerFor) => {
148
150
  }
149
151
  return ids.length;
150
152
  });
151
- if (count === 0)
152
- break;
153
- threads += count;
154
- }
155
153
  return emails + threads;
156
154
  };
@@ -3,7 +3,7 @@ import { walkQuery } from "@wirecat/cli-base/query";
3
3
  import { parseLocator } from "../../domain/locator.js";
4
4
  import { isBusinessType } from "../../domain/record-types.js";
5
5
  import { formatReference, parseReference } from "../../domain/references.js";
6
- import { checkEnds, isSymmetric, notOverriddenSql } from "../../domain/relations.js";
6
+ import { checkEnds, checkEngagement, isSymmetric, notOverriddenSql } from "../../domain/relations.js";
7
7
  import { normalizeTag } from "../../domain/tags.js";
8
8
  import { normalizeVocabularyName } from "../../domain/vocabulary.js";
9
9
  import { formatMeetingReference } from "../../meetings/index.js";
@@ -231,6 +231,8 @@ export const knowledgeStoreOver = (context) => {
231
231
  checkEnds(input.kind, from.type, to.type);
232
232
  if (input.role !== undefined)
233
233
  checkStoredRole(database, input.kind, from.type, to.type, input.role.trim());
234
+ if (input.engagement !== undefined)
235
+ checkEngagement(input.kind, from.type, to.type, input.engagement);
234
236
  let ends = { from: input.from, to: input.to };
235
237
  if (isSymmetric(input.kind) && to.id < from.id)
236
238
  [from, to, ends] = [to, from, { from: input.to, to: input.from }];
@@ -1,7 +1,7 @@
1
1
  import type { Delivery, Id, Message, PersonReaction, PollVote, Provider, Reactions, Reactor } from "../../domain/models.js";
2
2
  import type { AccountKey, DeletionScope } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
- export declare const upsertMessage: (context: StoreContext, key: AccountKey, accountKey: number, chatKey: number, message: Message, via: string, seenAt?: number) => boolean;
4
+ export declare const upsertMessage: (context: StoreContext, key: AccountKey, accountKey: number, chatKey: number, received: Message, via: string, seenAt?: number) => boolean;
5
5
  /**
6
6
  * One more unread for a message from someone else that the store first saw now, sent after the messenger's count was
7
7
  * taken. A chat the messenger never gave a count for is left alone: the store would count its whole history.
@@ -1,5 +1,6 @@
1
1
  import { validCounter } from "../../domain/counters.js";
2
2
  import { NORMALIZER_VERSION, normalize } from "../normalize.js";
3
+ import { withoutBotTokensIn } from "./bot-tokens.js";
3
4
  import { findChatPk } from "./chats.js";
4
5
  import { applyCounterObservations } from "./counters.js";
5
6
  import { and, eq, isNull, sql } from "./drizzle/core.js";
@@ -113,8 +114,9 @@ const fieldsOf = (message, sender) => ({
113
114
  normalizedText: normalize(message.text),
114
115
  normalizerVersion: NORMALIZER_VERSION,
115
116
  });
116
- export const upsertMessage = (context, key, accountKey, chatKey, message, via, seenAt) => {
117
+ export const upsertMessage = (context, key, accountKey, chatKey, received, via, seenAt) => {
117
118
  const { orm, now } = context;
119
+ const message = withoutBotTokensIn(received);
118
120
  const statements = statementsOf(orm);
119
121
  const sender = message.senderId === null || message.senderIsChat
120
122
  ? null
@@ -273,15 +273,17 @@ export const drainCorpus = (database, corpus, stemmerFor, { batch = 200, until =
273
273
  if (isQueryOnly(database))
274
274
  return 0;
275
275
  // Pieces written before they carried their account get it, once: purge and vector search filter by it.
276
- if (corpus.type === "email" || corpus.type === "document")
277
- database
276
+ if ((corpus.type === "email" || corpus.type === "document") &&
277
+ database.prepare("SELECT 1 FROM chunks WHERE chunkable_type = ? AND account_id IS NULL LIMIT 1").get(corpus.type))
278
+ write(database, () => database
278
279
  .prepare(`UPDATE chunks SET account_id = (SELECT account_id FROM ${corpus.table} WHERE id = chunks.chunkable_id)
279
- WHERE chunkable_type = ? AND account_id IS NULL`)
280
- .run(corpus.type);
280
+ WHERE chunkable_type = ? AND account_id IS NULL`)
281
+ .run(corpus.type));
281
282
  // The first schema seeded no row for mail; a data row, so no migration.
282
- database
283
- .prepare("INSERT OR IGNORE INTO search_index_state (name, watermark, filled_through, terms_through, normalizer_version) VALUES (?, 0, 0, 0, 1)")
284
- .run(corpus.index);
283
+ if (!database.prepare("SELECT 1 FROM search_index_state WHERE name = ?").get(corpus.index))
284
+ write(database, () => database
285
+ .prepare("INSERT OR IGNORE INTO search_index_state (name, watermark, filled_through, terms_through, normalizer_version) VALUES (?, 0, 0, 0, 1)")
286
+ .run(corpus.index));
285
287
  const state = corpusIndexState(database, corpus);
286
288
  if (state.wanted === null)
287
289
  return 0;
@@ -80,7 +80,7 @@ export interface LinkListFilter {
80
80
  origin?: Link["origin"];
81
81
  confirmed?: boolean;
82
82
  }
83
- export interface LinkInput extends Pick<RelationshipColumns, "position" | "startsAt" | "endsAt"> {
83
+ export interface LinkInput extends Omit<RelationshipColumns, "accountId" | "deletedAt" | "overrides"> {
84
84
  from: string;
85
85
  to?: string;
86
86
  targetText?: string;
@@ -3,7 +3,7 @@ import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
3
3
  import { googleDocumentLinks } from "../../domain/google-documents.js";
4
4
  import { ADDED_PROVIDER, DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, notAdded, } from "../../domain/providers.js";
5
5
  import { parseReference } from "../../domain/references.js";
6
- import { isRelationKind } from "../../domain/relations.js";
6
+ import { isEngagement, isRelationKind } from "../../domain/relations.js";
7
7
  import { normalizeTag } from "../../domain/tags.js";
8
8
  import { assertMayWithdraw } from "../decisions.js";
9
9
  import { fold } from "../normalize.js";
@@ -73,9 +73,7 @@ export const noteRowOf = (database, reference) => {
73
73
  };
74
74
  export const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
75
75
  export const linkOf = (database, row) => {
76
- const metadata = row.metadata == null
77
- ? {}
78
- : JSON.parse(String(row.metadata));
76
+ const metadata = row.metadata == null ? {} : JSON.parse(String(row.metadata));
79
77
  return {
80
78
  id: String(row.id),
81
79
  from: thingRef(database, row.from_type, row.from_id),
@@ -87,7 +85,7 @@ export const linkOf = (database, row) => {
87
85
  role: row.role == null ? null : String(row.role),
88
86
  purpose: row.purpose == null ? null : String(row.purpose),
89
87
  evidence: row.evidence == null ? null : String(row.evidence),
90
- provenance: metadata.provenance ?? null,
88
+ provenance: typeof metadata.provenance === "string" ? metadata.provenance : null,
91
89
  confirmed: Number(row.confirmed) === 1,
92
90
  createdAt: iso(row.created_at),
93
91
  ...(row.account_id == null ? {} : { accountId: Number(row.account_id) }),
@@ -95,6 +93,8 @@ export const linkOf = (database, row) => {
95
93
  ...(row.ends_at == null ? {} : { endsAt: Number(row.ends_at) }),
96
94
  ...(row.deleted_at == null ? {} : { deletedAt: Number(row.deleted_at) }),
97
95
  ...(typeof metadata.position === "string" ? { position: metadata.position } : {}),
96
+ ...(typeof metadata.roleNote === "string" ? { roleNote: metadata.roleNote } : {}),
97
+ ...(isEngagement(metadata.engagement) ? { engagement: metadata.engagement } : {}),
98
98
  ...(typeof metadata.overrides === "number" ? { overrides: metadata.overrides } : {}),
99
99
  };
100
100
  };
@@ -199,7 +199,9 @@ export const insertLink = (context, input) => {
199
199
  const position = input.position === undefined ? undefined : textOf(input.position, "a position", 200);
200
200
  if (input.startsAt !== undefined && input.endsAt !== undefined && input.endsAt <= input.startsAt)
201
201
  throw new CliError("validation_error", "a relationship ends after it starts");
202
- const metadata = provenance === undefined && position === undefined ? null : JSON.stringify({ provenance, position });
202
+ const roleNote = input.roleNote === undefined ? undefined : textOf(input.roleNote, "a role note", 200);
203
+ const fields = { provenance, position, roleNote, engagement: input.engagement };
204
+ const metadata = Object.values(fields).every((value) => value === undefined) ? null : JSON.stringify(fields);
203
205
  const row = database
204
206
  .prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, anchor, source, target_text, target_folded, role, evidence, " +
205
207
  "metadata, confirmed, created_at, author, updated_at, purpose, starts_at, ends_at) " +
@@ -8,6 +8,7 @@ import { storeCapable } from "../open.js";
8
8
  import { refuseOwnerStoreInTests, storePath } from "../path.js";
9
9
  import { sharedConfigPath } from "../shared-config.js";
10
10
  import { backfillNormalized, pendingNormalization } from "./backfill.js";
11
+ import { maskStoredBotTokens } from "./bot-tokens.js";
11
12
  import { fillFiles } from "./files.js";
12
13
  import { fillFolded } from "./folded.js";
13
14
  import { fillJoinKeys } from "./join-keys.js";
@@ -102,6 +103,7 @@ export const openStoreContext = async (options = {}) => {
102
103
  moveSuggestedLinks(database, now);
103
104
  movePaymentFacts({ ...opened, now, decisions });
104
105
  purgeTestAccounts({ ...opened, now, decisions }, warn);
106
+ maskStoredBotTokens({ ...opened, now, decisions });
105
107
  const pending = pendingNormalization(database);
106
108
  if (pending > 0 && pending <= BACKFILL_ON_OPEN)
107
109
  backfillNormalized(database);
@@ -124,6 +124,8 @@ export const relationListOver = (context) => {
124
124
  confidenceCategory: "weak",
125
125
  standing: "proposed",
126
126
  position: payload.position ?? null,
127
+ roleNote: payload.roleNote ?? null,
128
+ engagement: payload.engagement ?? null,
127
129
  startsAt: iso(payload.startsAt),
128
130
  endsAt: iso(payload.endsAt),
129
131
  createdAt: action.createdAt,
@@ -1,4 +1,4 @@
1
- import { type RelationKind, type Standing } from "../../domain/relations.js";
1
+ import { type Engagement, type RelationKind, type Standing } from "../../domain/relations.js";
2
2
  import { type Decider } from "../decisions.js";
3
3
  import type { Author } from "./memories.js";
4
4
  import { type Link } from "./notes.js";
@@ -22,6 +22,10 @@ export interface KnowledgeRelation {
22
22
  standing: Standing;
23
23
  /** A job title beside the relationship, never its role. */
24
24
  position: string | null;
25
+ /** What the role means here, in the owner's words. */
26
+ roleNote: string | null;
27
+ /** How much the owner deals with a person on a project himself; `null` is unknown. */
28
+ engagement: Engagement | null;
25
29
  /** When it held, as ISO times; `endsAt` exclusive; `null` when nobody said. */
26
30
  startsAt: string | null;
27
31
  endsAt: string | null;
@@ -37,6 +41,8 @@ export interface RelateInput {
37
41
  confirmed?: boolean;
38
42
  provenance?: string;
39
43
  position?: string;
44
+ roleNote?: string;
45
+ engagement?: Engagement;
40
46
  /** UTC ms; `endsAt` exclusive and after `startsAt`. */
41
47
  startsAt?: number;
42
48
  endsAt?: number;
@@ -70,6 +76,8 @@ export declare const relationProposalsOver: (context: StoreContext) => {
70
76
  role?: string;
71
77
  purpose?: string;
72
78
  position?: string;
79
+ roleNote?: string;
80
+ engagement?: Engagement;
73
81
  startsAt?: number;
74
82
  endsAt?: number;
75
83
  evidence?: string[];
@@ -109,11 +117,14 @@ export interface RelationUpdate {
109
117
  role?: string | null;
110
118
  purpose?: string | null;
111
119
  position?: string | null;
120
+ roleNote?: string | null;
121
+ engagement?: Engagement | null;
112
122
  startsAt?: number | null;
113
123
  endsAt?: number | null;
114
124
  }
115
125
  /** A relationship ends after it starts. */
116
126
  export declare const spanOf: (startsAt: number | null | undefined, endsAt: number | null | undefined) => void;
127
+ export declare const roleNoteOf: (note: string) => string;
117
128
  export declare const positionOf: (position: string) => string;
118
129
  export interface LinkDecision {
119
130
  confirm: boolean;
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { standingOf } from "../../domain/relations.js";
2
+ import { checkEngagement, standingOf, } from "../../domain/relations.js";
3
3
  import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
4
4
  import { actorOfOrigin, botNamed, ownerPerson } from "./actors.js";
5
5
  import { insertLink, linkOf, purposeOf } from "./notes.js";
@@ -21,6 +21,8 @@ export const relationOf = (link, now) => ({
21
21
  confidenceCategory: link.confirmed ? "owner-confirmed" : "weak",
22
22
  standing: standingOf(link, now),
23
23
  position: link.position ?? null,
24
+ roleNote: link.roleNote ?? null,
25
+ engagement: link.engagement ?? null,
24
26
  startsAt: isoOf(link.startsAt),
25
27
  endsAt: isoOf(link.endsAt),
26
28
  createdAt: link.createdAt,
@@ -47,15 +49,30 @@ export const relationProposalsOver = (context) => {
47
49
  .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);
48
50
  };
49
51
  /** 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;
52
+ const checkedRole = (link, { role, engagement }) => {
53
53
  const [fromType, , toType] = fromTo(link);
54
- checkStoredRole(database, link.kind, fromType, toType, role);
54
+ if (typeof role === "string")
55
+ checkStoredRole(database, link.kind, fromType, toType, role);
56
+ if (typeof engagement === "string")
57
+ checkEngagement(link.kind, fromType, toType, engagement);
58
+ };
59
+ /** The link's metadata with the changed fields set or, when `null`, removed; `undefined` when none changed. */
60
+ const metadataOf = (link, changes) => {
61
+ const fields = METADATA_FIELDS.filter((field) => field in changes);
62
+ if (!fields.length)
63
+ return;
64
+ const row = database.prepare("SELECT metadata FROM links WHERE id = ?").get(Number(link.id));
65
+ const metadata = row?.metadata == null ? {} : JSON.parse(String(row.metadata));
66
+ for (const field of fields)
67
+ if (changes[field] == null)
68
+ delete metadata[field];
69
+ else
70
+ metadata[field] = changes[field];
71
+ return JSON.stringify(metadata);
55
72
  };
56
73
  const applyUpdate = (link, input) => {
57
74
  const changes = changesOf(input);
58
- checkedRole(link, changes.role);
75
+ checkedRole(link, changes);
59
76
  if ("role" in changes) {
60
77
  const taken = database
61
78
  .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 " +
@@ -70,12 +87,12 @@ export const relationProposalsOver = (context) => {
70
87
  const startsAt = "startsAt" in changes ? (changes.startsAt ?? undefined) : link.startsAt;
71
88
  const endsAt = "endsAt" in changes ? (changes.endsAt ?? undefined) : link.endsAt;
72
89
  spanOf(startsAt, endsAt);
90
+ const metadata = metadataOf(link, changes);
73
91
  database
74
92
  .prepare("UPDATE links SET role = CASE WHEN ? THEN ? ELSE role END, purpose = CASE WHEN ? THEN ? ELSE purpose END, " +
75
93
  "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));
94
+ "metadata = CASE WHEN ? THEN ? ELSE metadata END, updated_at = ? WHERE id = ?")
95
+ .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(metadata !== undefined), metadata ?? null, now(), Number(link.id));
79
96
  return linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(Number(link.id)));
80
97
  };
81
98
  /**
@@ -99,6 +116,8 @@ export const relationProposalsOver = (context) => {
99
116
  const metadata = JSON.stringify({
100
117
  overrides: Number(link.id),
101
118
  ...(link.position ? { position: link.position } : {}),
119
+ ...(link.roleNote ? { roleNote: link.roleNote } : {}),
120
+ ...(link.engagement ? { engagement: link.engagement } : {}),
102
121
  });
103
122
  // An owner link of that role on the pair already (from `relate`) becomes the override rather than a second one.
104
123
  const same = database
@@ -211,6 +230,8 @@ export const relationProposalsOver = (context) => {
211
230
  ...(input.role === undefined ? {} : { role: input.role }),
212
231
  ...(input.purpose === undefined ? {} : { purpose: purposeOf(input.purpose) }),
213
232
  ...(input.position === undefined ? {} : { position: positionOf(input.position) }),
233
+ ...(input.roleNote === undefined ? {} : { roleNote: roleNoteOf(input.roleNote) }),
234
+ ...(input.engagement === undefined ? {} : { engagement: input.engagement }),
214
235
  ...(input.startsAt === undefined ? {} : { startsAt: input.startsAt }),
215
236
  ...(input.endsAt === undefined ? {} : { endsAt: input.endsAt }),
216
237
  evidence,
@@ -224,7 +245,7 @@ export const relationProposalsOver = (context) => {
224
245
  update: (link, input) => write(database, () => ownerUpdate(link, input)),
225
246
  proposeUpdate: (link, input, by) => {
226
247
  const changes = changesOf(input);
227
- checkedRole(link, changes.role);
248
+ checkedRole(link, changes);
228
249
  return write(database, () => {
229
250
  const from = thingOf(database, link.from);
230
251
  const held = database
@@ -248,6 +269,8 @@ export const relationProposalsOver = (context) => {
248
269
  role: link.role,
249
270
  purpose: link.purpose,
250
271
  position: link.position ?? null,
272
+ roleNote: link.roleNote ?? null,
273
+ engagement: link.engagement ?? null,
251
274
  startsAt: link.startsAt ?? null,
252
275
  endsAt: link.endsAt ?? null,
253
276
  },
@@ -293,6 +316,8 @@ export const relationProposalsOver = (context) => {
293
316
  const ends = key ? undefined : [thingOf(database, String(payload.from)), thingOf(database, String(payload.to))];
294
317
  if (ends?.[0] && ends[1] && payload.role !== undefined)
295
318
  checkStoredRole(database, payload.kind ?? "member-of", ends[0].type, ends[1].type, payload.role);
319
+ if (ends?.[0] && ends[1] && payload.engagement !== undefined)
320
+ checkEngagement(payload.kind ?? "member-of", ends[0].type, ends[1].type, payload.engagement);
296
321
  const link = insertLink(context, {
297
322
  from: String(key ? payload.ref : payload.from),
298
323
  to: String(key ? payload.project : payload.to),
@@ -300,6 +325,8 @@ export const relationProposalsOver = (context) => {
300
325
  ...(key ? { role: "key" } : payload.role === undefined ? {} : { role: payload.role }),
301
326
  ...(key || payload.purpose === undefined ? {} : { purpose: payload.purpose }),
302
327
  ...(key || payload.position === undefined ? {} : { position: payload.position }),
328
+ ...(key || payload.roleNote === undefined ? {} : { roleNote: payload.roleNote }),
329
+ ...(key || payload.engagement === undefined ? {} : { engagement: payload.engagement }),
303
330
  ...(key || payload.startsAt === undefined ? {} : { startsAt: payload.startsAt }),
304
331
  ...(key || payload.endsAt === undefined ? {} : { endsAt: payload.endsAt }),
305
332
  ...(proposal.reason === null ? {} : { evidence: proposal.reason }),
@@ -357,6 +384,14 @@ export const spanOf = (startsAt, endsAt) => {
357
384
  if (startsAt != null && endsAt != null && endsAt <= startsAt)
358
385
  throw new CliError("validation_error", "a relationship ends after it starts");
359
386
  };
387
+ /** The relationship fields kept in `links.metadata`. */
388
+ const METADATA_FIELDS = ["position", "roleNote", "engagement"];
389
+ export const roleNoteOf = (note) => {
390
+ const value = note.trim();
391
+ if (!value || value.length > 200)
392
+ throw new CliError("validation_error", "a role note takes 1–200 characters");
393
+ return value;
394
+ };
360
395
  export const positionOf = (position) => {
361
396
  const value = position.trim();
362
397
  if (!value || value.length > 200)
@@ -372,12 +407,16 @@ const changesOf = (input) => {
372
407
  changes.purpose = input.purpose === null ? null : purposeOf(input.purpose);
373
408
  if (input.position !== undefined)
374
409
  changes.position = input.position === null ? null : positionOf(input.position);
410
+ if (input.roleNote !== undefined)
411
+ changes.roleNote = input.roleNote === null ? null : roleNoteOf(input.roleNote);
412
+ if (input.engagement !== undefined)
413
+ changes.engagement = input.engagement;
375
414
  if (input.startsAt !== undefined)
376
415
  changes.startsAt = input.startsAt === null ? null : timeOf(input.startsAt, "a start");
377
416
  if (input.endsAt !== undefined)
378
417
  changes.endsAt = input.endsAt === null ? null : timeOf(input.endsAt, "an end");
379
418
  if (!Object.keys(changes).length)
380
- throw new CliError("validation_error", "a relationship update sets a role, a purpose, a position or its dates");
419
+ throw new CliError("validation_error", "a relationship update sets a role, a role note, an engagement level, a purpose, a position or its dates");
381
420
  return changes;
382
421
  };
383
422
  const roleOf = (role) => {
@@ -1,5 +1,18 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
2
  export declare const isBusy: (error: unknown) => boolean;
3
+ /**
4
+ * Takes the write lock, waiting as long as the connection's `busy_timeout`. SQLite's own wait sleeps 1 ms, then up to
5
+ * 100 ms between tries, so a process that commits and begins again at once is never seen free and the waiter fails
6
+ * with "database is locked" after the full timeout. Trying every millisecond sees a gap of a fraction of a
7
+ * millisecond between two writes; a writer that leaves none still starves it, hence the pause after a write that
8
+ * waited. Answers whether it had to wait.
9
+ */
10
+ export declare const beginImmediate: (database: CacheDatabase) => boolean;
11
+ /**
12
+ * On some errors (a full disk, an I/O error) SQLite has already rolled the transaction back, and the ROLLBACK then
13
+ * fails with "no transaction is active". That failure must not take the place of the error that ended it.
14
+ */
15
+ export declare const rollBack: (database: CacheDatabase, sql?: string) => void;
3
16
  /**
4
17
  * One write transaction. The outermost takes the write lock at once (`BEGIN IMMEDIATE`): a deferred one that
5
18
  * reads first fails with SQLITE_BUSY when another process writes in between, and tg, max, memo and zm share