@wirecat/cli-core 0.617.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 (50) hide show
  1. package/CHANGELOG.md +67 -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/relations.d.ts +15 -0
  20. package/dist/domain/relations.js +23 -0
  21. package/dist/errors/reasons.js +7 -0
  22. package/dist/index.d.ts +2 -2
  23. package/dist/index.js +2 -2
  24. package/dist/meetings/mcp/index.d.ts +15 -15
  25. package/dist/services/link-scorers/chat-senders.js +39 -29
  26. package/dist/services/link-scorers/member-chats.js +4 -3
  27. package/dist/services/link-scorers/member-dialog.js +5 -7
  28. package/dist/services/link-scorers/scan.js +17 -8
  29. package/dist/services/link-scorers/shared.d.ts +6 -2
  30. package/dist/services/link-scorers/shared.js +6 -2
  31. package/dist/services/link-scorers/types.d.ts +2 -0
  32. package/dist/store/migrations.d.ts +1 -1
  33. package/dist/store/migrations.js +35 -12
  34. package/dist/store/recover.d.ts +34 -0
  35. package/dist/store/recover.js +188 -6
  36. package/dist/store/refill.d.ts +28 -0
  37. package/dist/store/refill.js +120 -0
  38. package/dist/store/sqlite/clients.d.ts +7 -3
  39. package/dist/store/sqlite/clients.js +11 -7
  40. package/dist/store/sqlite/email-index.js +9 -11
  41. package/dist/store/sqlite/knowledge.js +3 -1
  42. package/dist/store/sqlite/note-index.js +9 -7
  43. package/dist/store/sqlite/notes.d.ts +1 -1
  44. package/dist/store/sqlite/notes.js +8 -6
  45. package/dist/store/sqlite/relation-list.js +2 -0
  46. package/dist/store/sqlite/relation-proposals.d.ts +12 -1
  47. package/dist/store/sqlite/relation-proposals.js +50 -11
  48. package/dist/store/sqlite/transaction.d.ts +13 -0
  49. package/dist/store/sqlite/transaction.js +25 -17
  50. package/package.json +1 -1
@@ -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 }];
@@ -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) " +
@@ -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
@@ -12,17 +12,18 @@ export const isBusy = (error) => sqliteCode(error) === SQLITE_BUSY;
12
12
  * Takes the write lock, waiting as long as the connection's `busy_timeout`. SQLite's own wait sleeps 1 ms, then up to
13
13
  * 100 ms between tries, so a process that commits and begins again at once is never seen free and the waiter fails
14
14
  * with "database is locked" after the full timeout. Trying every millisecond sees a gap of a fraction of a
15
- * millisecond between two writes; a writer that leaves none still starves it, hence `writeBatch`'s pause.
15
+ * millisecond between two writes; a writer that leaves none still starves it, hence the pause after a write that
16
+ * waited. Answers whether it had to wait.
16
17
  */
17
- const beginImmediate = (database) => {
18
+ export const beginImmediate = (database) => {
18
19
  const timeout = Number(database.prepare("PRAGMA busy_timeout").get()?.timeout ?? 0);
19
20
  const deadline = Date.now() + timeout;
20
21
  database.exec("PRAGMA busy_timeout = 0");
21
22
  try {
22
- for (;;) {
23
+ for (let waited = false;; waited = true) {
23
24
  try {
24
25
  database.exec("BEGIN IMMEDIATE");
25
- return;
26
+ return waited;
26
27
  }
27
28
  catch (error) {
28
29
  if (!isBusy(error) || Date.now() >= deadline)
@@ -35,6 +36,16 @@ const beginImmediate = (database) => {
35
36
  database.exec(`PRAGMA busy_timeout = ${timeout}`);
36
37
  }
37
38
  };
39
+ /**
40
+ * On some errors (a full disk, an I/O error) SQLite has already rolled the transaction back, and the ROLLBACK then
41
+ * fails with "no transaction is active". That failure must not take the place of the error that ended it.
42
+ */
43
+ export const rollBack = (database, sql = "ROLLBACK") => {
44
+ try {
45
+ database.exec(sql);
46
+ }
47
+ catch { }
48
+ };
38
49
  const connections = new WeakMap();
39
50
  const connectionOf = (database) => {
40
51
  let connection = connections.get(database);
@@ -57,13 +68,7 @@ export const write = (database, body, { beforeCommit } = {}) => transact(databas
57
68
  * the next `write`. The outermost pauses 2 ms after it commits: a loop that begins again at once leaves another
58
69
  * process's `write` a gap of microseconds, and it misses that gap until its 5 s wait runs out.
59
70
  */
60
- export const writeBatch = (database, body) => {
61
- const outer = connectionOf(database).depth === 0;
62
- const result = transact(database, body, false);
63
- if (outer)
64
- Atomics.wait(pause, 0, 0, BATCH_PAUSE_MS);
65
- return result;
66
- };
71
+ export const writeBatch = (database, body) => transact(database, body, false);
67
72
  const BATCH_PAUSE_MS = 2;
68
73
  const transact = (database, body, drain, beforeCommit) => {
69
74
  const connection = connectionOf(database);
@@ -71,9 +76,8 @@ const transact = (database, body, drain, beforeCommit) => {
71
76
  throw new Error("a store write cannot run inside a read");
72
77
  const outer = connection.depth === 0;
73
78
  const name = `w${connection.depth + 1}`;
74
- if (outer)
75
- beginImmediate(database);
76
- else
79
+ const waited = outer && beginImmediate(database);
80
+ if (!outer)
77
81
  database.exec(`SAVEPOINT ${name}`);
78
82
  connection.depth += 1;
79
83
  try {
@@ -85,10 +89,14 @@ const transact = (database, body, drain, beforeCommit) => {
85
89
  }
86
90
  beforeCommit?.();
87
91
  database.exec(outer ? "COMMIT" : `RELEASE ${name}`);
92
+ // A write that had to wait has others waiting behind it, and its caller's next write would begin before they see
93
+ // the lock free. Pausing only then costs an uncontended write nothing.
94
+ if (outer && (waited || !drain))
95
+ Atomics.wait(pause, 0, 0, BATCH_PAUSE_MS);
88
96
  return result;
89
97
  }
90
98
  catch (error) {
91
- database.exec(outer ? "ROLLBACK" : `ROLLBACK TO ${name}; RELEASE ${name}`);
99
+ rollBack(database, outer ? "ROLLBACK" : `ROLLBACK TO ${name}; RELEASE ${name}`);
92
100
  throw error;
93
101
  }
94
102
  finally {
@@ -146,7 +154,7 @@ export const rehearse = async ({ database, client }, body) => {
146
154
  else
147
155
  delete target[name];
148
156
  connection.depth -= 1;
149
- database.exec("ROLLBACK");
157
+ rollBack(database);
150
158
  }
151
159
  };
152
160
  /** Several queries that must see one state of the file. Never drains: that is the outer write's work, or nobody's. */
@@ -164,7 +172,7 @@ export const read = (database, body) => {
164
172
  return result;
165
173
  }
166
174
  catch (error) {
167
- database.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
175
+ rollBack(database, `ROLLBACK TO ${name}; RELEASE ${name}`);
168
176
  throw error;
169
177
  }
170
178
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.617.0",
3
+ "version": "0.618.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",