@segmentstream/ontology 0.167.0 → 0.168.1

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.
@@ -411,24 +411,28 @@ export declare const MigrationPlan: Schema.Struct<{
411
411
  readonly files?: {
412
412
  readonly keep: boolean;
413
413
  } | undefined;
414
+ readonly signature?: boolean | undefined;
414
415
  } | undefined;
415
416
  readonly slack?: {
416
417
  readonly connection: string;
417
418
  readonly files?: {
418
419
  readonly keep: boolean;
419
420
  } | undefined;
421
+ readonly signature?: boolean | undefined;
420
422
  } | undefined;
421
423
  readonly whatsapp?: {
422
424
  readonly connection: string;
423
425
  readonly files?: {
424
426
  readonly keep: boolean;
425
427
  } | undefined;
428
+ readonly signature?: boolean | undefined;
426
429
  } | undefined;
427
430
  readonly email?: {
428
431
  readonly connection: string;
429
432
  readonly files?: {
430
433
  readonly keep: boolean;
431
434
  } | undefined;
435
+ readonly signature?: boolean | undefined;
432
436
  } | undefined;
433
437
  readonly channels?: {
434
438
  readonly [x: string]: {
@@ -437,6 +441,7 @@ export declare const MigrationPlan: Schema.Struct<{
437
441
  readonly keep: boolean;
438
442
  } | undefined;
439
443
  readonly connection?: string | undefined;
444
+ readonly signature?: boolean | undefined;
440
445
  };
441
446
  } | undefined;
442
447
  readonly attribution?: {
@@ -783,24 +788,28 @@ export declare const MigrationPlan: Schema.Struct<{
783
788
  readonly files?: {
784
789
  readonly keep: boolean;
785
790
  } | undefined;
791
+ readonly signature?: boolean | undefined;
786
792
  } | undefined;
787
793
  readonly slack?: {
788
794
  readonly connection: string;
789
795
  readonly files?: {
790
796
  readonly keep: boolean;
791
797
  } | undefined;
798
+ readonly signature?: boolean | undefined;
792
799
  } | undefined;
793
800
  readonly whatsapp?: {
794
801
  readonly connection: string;
795
802
  readonly files?: {
796
803
  readonly keep: boolean;
797
804
  } | undefined;
805
+ readonly signature?: boolean | undefined;
798
806
  } | undefined;
799
807
  readonly email?: {
800
808
  readonly connection: string;
801
809
  readonly files?: {
802
810
  readonly keep: boolean;
803
811
  } | undefined;
812
+ readonly signature?: boolean | undefined;
804
813
  } | undefined;
805
814
  readonly channels?: {
806
815
  readonly [x: string]: {
@@ -809,6 +818,7 @@ export declare const MigrationPlan: Schema.Struct<{
809
818
  readonly keep: boolean;
810
819
  } | undefined;
811
820
  readonly connection?: string | undefined;
821
+ readonly signature?: boolean | undefined;
812
822
  };
813
823
  } | undefined;
814
824
  readonly attribution?: {
@@ -1155,24 +1165,28 @@ export declare const MigrationPlan: Schema.Struct<{
1155
1165
  readonly files?: {
1156
1166
  readonly keep: boolean;
1157
1167
  } | undefined;
1168
+ readonly signature?: boolean | undefined;
1158
1169
  } | undefined;
1159
1170
  readonly slack?: {
1160
1171
  readonly connection: string;
1161
1172
  readonly files?: {
1162
1173
  readonly keep: boolean;
1163
1174
  } | undefined;
1175
+ readonly signature?: boolean | undefined;
1164
1176
  } | undefined;
1165
1177
  readonly whatsapp?: {
1166
1178
  readonly connection: string;
1167
1179
  readonly files?: {
1168
1180
  readonly keep: boolean;
1169
1181
  } | undefined;
1182
+ readonly signature?: boolean | undefined;
1170
1183
  } | undefined;
1171
1184
  readonly email?: {
1172
1185
  readonly connection: string;
1173
1186
  readonly files?: {
1174
1187
  readonly keep: boolean;
1175
1188
  } | undefined;
1189
+ readonly signature?: boolean | undefined;
1176
1190
  } | undefined;
1177
1191
  readonly channels?: {
1178
1192
  readonly [x: string]: {
@@ -1181,6 +1195,7 @@ export declare const MigrationPlan: Schema.Struct<{
1181
1195
  readonly keep: boolean;
1182
1196
  } | undefined;
1183
1197
  readonly connection?: string | undefined;
1198
+ readonly signature?: boolean | undefined;
1184
1199
  };
1185
1200
  } | undefined;
1186
1201
  readonly attribution?: {
@@ -1527,24 +1542,28 @@ export declare const MigrationPlan: Schema.Struct<{
1527
1542
  readonly files?: {
1528
1543
  readonly keep: boolean;
1529
1544
  } | undefined;
1545
+ readonly signature?: boolean | undefined;
1530
1546
  } | undefined;
1531
1547
  readonly slack?: {
1532
1548
  readonly connection: string;
1533
1549
  readonly files?: {
1534
1550
  readonly keep: boolean;
1535
1551
  } | undefined;
1552
+ readonly signature?: boolean | undefined;
1536
1553
  } | undefined;
1537
1554
  readonly whatsapp?: {
1538
1555
  readonly connection: string;
1539
1556
  readonly files?: {
1540
1557
  readonly keep: boolean;
1541
1558
  } | undefined;
1559
+ readonly signature?: boolean | undefined;
1542
1560
  } | undefined;
1543
1561
  readonly email?: {
1544
1562
  readonly connection: string;
1545
1563
  readonly files?: {
1546
1564
  readonly keep: boolean;
1547
1565
  } | undefined;
1566
+ readonly signature?: boolean | undefined;
1548
1567
  } | undefined;
1549
1568
  readonly channels?: {
1550
1569
  readonly [x: string]: {
@@ -1553,6 +1572,7 @@ export declare const MigrationPlan: Schema.Struct<{
1553
1572
  readonly keep: boolean;
1554
1573
  } | undefined;
1555
1574
  readonly connection?: string | undefined;
1575
+ readonly signature?: boolean | undefined;
1556
1576
  };
1557
1577
  } | undefined;
1558
1578
  readonly attribution?: {
@@ -2009,24 +2029,28 @@ export declare const MigrationPlan: Schema.Struct<{
2009
2029
  readonly files: Schema.optionalKey<Schema.Struct<{
2010
2030
  readonly keep: Schema.Boolean;
2011
2031
  }>>;
2032
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2012
2033
  }>>;
2013
2034
  readonly slack: Schema.optionalKey<Schema.Struct<{
2014
2035
  readonly connection: Schema.String;
2015
2036
  readonly files: Schema.optionalKey<Schema.Struct<{
2016
2037
  readonly keep: Schema.Boolean;
2017
2038
  }>>;
2039
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2018
2040
  }>>;
2019
2041
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
2020
2042
  readonly connection: Schema.String;
2021
2043
  readonly files: Schema.optionalKey<Schema.Struct<{
2022
2044
  readonly keep: Schema.Boolean;
2023
2045
  }>>;
2046
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2024
2047
  }>>;
2025
2048
  readonly email: Schema.optionalKey<Schema.Struct<{
2026
2049
  readonly connection: Schema.String;
2027
2050
  readonly files: Schema.optionalKey<Schema.Struct<{
2028
2051
  readonly keep: Schema.Boolean;
2029
2052
  }>>;
2053
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2030
2054
  }>>;
2031
2055
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
2032
2056
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
@@ -2034,6 +2058,7 @@ export declare const MigrationPlan: Schema.Struct<{
2034
2058
  readonly files: Schema.optionalKey<Schema.Struct<{
2035
2059
  readonly keep: Schema.Boolean;
2036
2060
  }>>;
2061
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2037
2062
  }>>>;
2038
2063
  readonly attribution: Schema.optionalKey<Schema.Struct<{
2039
2064
  readonly template: Schema.optionalKey<Schema.String>;
@@ -2379,24 +2404,28 @@ export declare const MigrationPlan: Schema.Struct<{
2379
2404
  readonly files: Schema.optionalKey<Schema.Struct<{
2380
2405
  readonly keep: Schema.Boolean;
2381
2406
  }>>;
2407
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2382
2408
  }>>;
2383
2409
  readonly slack: Schema.optionalKey<Schema.Struct<{
2384
2410
  readonly connection: Schema.String;
2385
2411
  readonly files: Schema.optionalKey<Schema.Struct<{
2386
2412
  readonly keep: Schema.Boolean;
2387
2413
  }>>;
2414
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2388
2415
  }>>;
2389
2416
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
2390
2417
  readonly connection: Schema.String;
2391
2418
  readonly files: Schema.optionalKey<Schema.Struct<{
2392
2419
  readonly keep: Schema.Boolean;
2393
2420
  }>>;
2421
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2394
2422
  }>>;
2395
2423
  readonly email: Schema.optionalKey<Schema.Struct<{
2396
2424
  readonly connection: Schema.String;
2397
2425
  readonly files: Schema.optionalKey<Schema.Struct<{
2398
2426
  readonly keep: Schema.Boolean;
2399
2427
  }>>;
2428
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2400
2429
  }>>;
2401
2430
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
2402
2431
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
@@ -2404,6 +2433,7 @@ export declare const MigrationPlan: Schema.Struct<{
2404
2433
  readonly files: Schema.optionalKey<Schema.Struct<{
2405
2434
  readonly keep: Schema.Boolean;
2406
2435
  }>>;
2436
+ readonly signature: Schema.optionalKey<Schema.Boolean>;
2407
2437
  }>>>;
2408
2438
  readonly attribution: Schema.optionalKey<Schema.Struct<{
2409
2439
  readonly template: Schema.optionalKey<Schema.String>;
@@ -2653,24 +2683,28 @@ export declare const MigrationPlan: Schema.Struct<{
2653
2683
  readonly files?: {
2654
2684
  readonly keep: boolean;
2655
2685
  } | undefined;
2686
+ readonly signature?: boolean | undefined;
2656
2687
  } | undefined;
2657
2688
  readonly slack?: {
2658
2689
  readonly connection: string;
2659
2690
  readonly files?: {
2660
2691
  readonly keep: boolean;
2661
2692
  } | undefined;
2693
+ readonly signature?: boolean | undefined;
2662
2694
  } | undefined;
2663
2695
  readonly whatsapp?: {
2664
2696
  readonly connection: string;
2665
2697
  readonly files?: {
2666
2698
  readonly keep: boolean;
2667
2699
  } | undefined;
2700
+ readonly signature?: boolean | undefined;
2668
2701
  } | undefined;
2669
2702
  readonly email?: {
2670
2703
  readonly connection: string;
2671
2704
  readonly files?: {
2672
2705
  readonly keep: boolean;
2673
2706
  } | undefined;
2707
+ readonly signature?: boolean | undefined;
2674
2708
  } | undefined;
2675
2709
  readonly channels?: {
2676
2710
  readonly [x: string]: {
@@ -2679,6 +2713,7 @@ export declare const MigrationPlan: Schema.Struct<{
2679
2713
  readonly keep: boolean;
2680
2714
  } | undefined;
2681
2715
  readonly connection?: string | undefined;
2716
+ readonly signature?: boolean | undefined;
2682
2717
  };
2683
2718
  } | undefined;
2684
2719
  readonly attribution?: {
@@ -3025,24 +3060,28 @@ export declare const MigrationPlan: Schema.Struct<{
3025
3060
  readonly files?: {
3026
3061
  readonly keep: boolean;
3027
3062
  } | undefined;
3063
+ readonly signature?: boolean | undefined;
3028
3064
  } | undefined;
3029
3065
  readonly slack?: {
3030
3066
  readonly connection: string;
3031
3067
  readonly files?: {
3032
3068
  readonly keep: boolean;
3033
3069
  } | undefined;
3070
+ readonly signature?: boolean | undefined;
3034
3071
  } | undefined;
3035
3072
  readonly whatsapp?: {
3036
3073
  readonly connection: string;
3037
3074
  readonly files?: {
3038
3075
  readonly keep: boolean;
3039
3076
  } | undefined;
3077
+ readonly signature?: boolean | undefined;
3040
3078
  } | undefined;
3041
3079
  readonly email?: {
3042
3080
  readonly connection: string;
3043
3081
  readonly files?: {
3044
3082
  readonly keep: boolean;
3045
3083
  } | undefined;
3084
+ readonly signature?: boolean | undefined;
3046
3085
  } | undefined;
3047
3086
  readonly channels?: {
3048
3087
  readonly [x: string]: {
@@ -3051,6 +3090,7 @@ export declare const MigrationPlan: Schema.Struct<{
3051
3090
  readonly keep: boolean;
3052
3091
  } | undefined;
3053
3092
  readonly connection?: string | undefined;
3093
+ readonly signature?: boolean | undefined;
3054
3094
  };
3055
3095
  } | undefined;
3056
3096
  readonly attribution?: {
@@ -52,6 +52,7 @@ export function preparePreviewDatabase({ sql, }) {
52
52
  "_ontology_replication_scans",
53
53
  "_ontology_replication_baselines",
54
54
  "_ontology_replication_receipts",
55
+ "_ontology_replication_erasures",
55
56
  "_ontology_replication_targets",
56
57
  ];
57
58
  if (present.has("_ontology_replication")) {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Records whose replicated history the warehouse must lose: one row per deleted record of an
3
+ * entity that erases its history on delete. A row is the audit of its erasure as well, holding no
4
+ * content: which record, when it was deleted, when its history left the warehouse, by which
5
+ * warehouse job, how many rows that job removed, and when a later pass found nothing left.
6
+ *
7
+ * `due_at` batches the work by day: a deletion is erased from the next day's first pass, a failed
8
+ * attempt is retried an hour later, and an erased record is checked again once Pub/Sub can no
9
+ * longer deliver an event captured before the deletion.
10
+ */
11
+ export declare const REPLICATION_ERASURES_DDL: string[];
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Records whose replicated history the warehouse must lose: one row per deleted record of an
3
+ * entity that erases its history on delete. A row is the audit of its erasure as well, holding no
4
+ * content: which record, when it was deleted, when its history left the warehouse, by which
5
+ * warehouse job, how many rows that job removed, and when a later pass found nothing left.
6
+ *
7
+ * `due_at` batches the work by day: a deletion is erased from the next day's first pass, a failed
8
+ * attempt is retried an hour later, and an erased record is checked again once Pub/Sub can no
9
+ * longer deliver an event captured before the deletion.
10
+ */
11
+ export const REPLICATION_ERASURES_DDL = [
12
+ `CREATE TABLE IF NOT EXISTS _ontology_replication_erasures (
13
+ entity_id text NOT NULL, record_id uuid NOT NULL,
14
+ requested_at timestamptz NOT NULL DEFAULT now(),
15
+ due_at timestamptz NOT NULL DEFAULT date_trunc('day', now()) + interval '1 day',
16
+ attempts integer NOT NULL DEFAULT 0, failure text,
17
+ erased_at timestamptz, erased_job text, erased_rows bigint NOT NULL DEFAULT 0,
18
+ confirmed_at timestamptz,
19
+ PRIMARY KEY (entity_id, record_id)
20
+ )`,
21
+ `CREATE INDEX IF NOT EXISTS _ontology_replication_erasures_due
22
+ ON _ontology_replication_erasures (due_at, entity_id, record_id) WHERE confirmed_at IS NULL`,
23
+ ];
@@ -0,0 +1,56 @@
1
+ import { Effect } from "effect";
2
+ import type { SqlClient } from "effect/unstable/sql";
3
+ export { REPLICATION_ERASURES_DDL } from "./erasure-schema.js";
4
+ /** The most records one warehouse statement erases. */
5
+ export declare const REPLICATION_ERASURE_BATCH = 1000;
6
+ /**
7
+ * How long after its copies were scrubbed an event published before can still reach the warehouse:
8
+ * Pub/Sub keeps an undelivered message seven days. An erased record is confirmed by a pass after.
9
+ */
10
+ export declare const REPLICATION_ERASURE_CONFIRM_AFTER = "8 days";
11
+ export interface ReplicationErasureBatch {
12
+ readonly entityId: string;
13
+ readonly recordIds: readonly string[];
14
+ }
15
+ export interface ReplicationErasureScrub {
16
+ /** Staging objects of settled copy segments that held the records' events. */
17
+ readonly objectUris: readonly string[];
18
+ /** Copy segments that hold the records' events but have not settled yet: scrubbed later. */
19
+ readonly unsettled: number;
20
+ }
21
+ /**
22
+ * The next records due for erasure, of one entity. A source an SDK without erasure installed has
23
+ * none.
24
+ */
25
+ export declare const dueReplicationErasures: (sql: SqlClient.SqlClient, limit?: number) => Effect.Effect<{
26
+ entityId: string;
27
+ recordIds: string[];
28
+ } | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
29
+ /**
30
+ * Removes the records' content from every replication copy the source keeps: the events their
31
+ * history captured, delivery payloads kept for dropped history, baseline scan events and settled
32
+ * copy segments. Each copy keeps the event's identity and revision as a deletion, so a copy sent
33
+ * again can never show the record. Relationship events carry only ids and stay. A segment still
34
+ * being loaded keeps its events until it settles; the next pass scrubs it.
35
+ */
36
+ export declare const scrubReplicationErasures: (sql: SqlClient.SqlClient, batch: ReplicationErasureBatch) => Effect.Effect<{
37
+ objectUris: string[];
38
+ unsettled: number;
39
+ }, import("effect/unstable/sql/SqlError").SqlError, never>;
40
+ /**
41
+ * Records a warehouse erasure of the batch. The first erases the records. Their copies were scrubbed
42
+ * before it, so any event published since carries no content; one published earlier stays in
43
+ * Pub/Sub at most until the confirmation delay after that first erasure. A pass after that delay
44
+ * that removed nothing and found no unsettled copy confirms the records. Otherwise they are checked
45
+ * again the next day, or within the hour while a copy segment that holds them has not settled: it
46
+ * may still load their content, and its staging object is deleted once it has.
47
+ */
48
+ export declare const recordReplicationErasure: (sql: SqlClient.SqlClient, batch: ReplicationErasureBatch, outcome: {
49
+ readonly jobId: string;
50
+ readonly rows: number;
51
+ readonly unsettled: number;
52
+ }) => import("effect/unstable/sql/Statement").Statement<{
53
+ record_id: string;
54
+ }>;
55
+ /** A failed attempt is retried an hour later; its reason is a code, never content. */
56
+ export declare const recordReplicationErasureFailure: (sql: SqlClient.SqlClient, batch: ReplicationErasureBatch, failure: string) => Effect.Effect<number, import("effect/unstable/sql/SqlError").SqlError, never>;
@@ -0,0 +1,127 @@
1
+ import { Effect } from "effect";
2
+ import { historyTableName, quoteIdentifier as qi } from "../migrate/storage.js";
3
+ import { activeReplicationTarget } from "./store.js";
4
+ export { REPLICATION_ERASURES_DDL } from "./erasure-schema.js";
5
+ /** The most records one warehouse statement erases. */
6
+ export const REPLICATION_ERASURE_BATCH = 1000;
7
+ /**
8
+ * How long after its copies were scrubbed an event published before can still reach the warehouse:
9
+ * Pub/Sub keeps an undelivered message seven days. An erased record is confirmed by a pass after.
10
+ */
11
+ export const REPLICATION_ERASURE_CONFIRM_AFTER = "8 days";
12
+ /** What scrubbing a replicated event leaves: its identity and revision, no content, a deletion. */
13
+ const SCRUBBED = `'{"payload":"{}","deleted":true}'::jsonb`;
14
+ const present = (sql) => sql
15
+ .unsafe("SELECT to_regclass('_ontology_replication_erasures') IS NOT NULL AS present")
16
+ .pipe(Effect.map((rows) => rows[0]?.present === true));
17
+ /**
18
+ * The next records due for erasure, of one entity. A source an SDK without erasure installed has
19
+ * none.
20
+ */
21
+ export const dueReplicationErasures = (sql, limit = REPLICATION_ERASURE_BATCH) => Effect.gen(function* () {
22
+ if (!(yield* present(sql))) {
23
+ return undefined;
24
+ }
25
+ const [first] = yield* sql.unsafe(`SELECT entity_id FROM _ontology_replication_erasures
26
+ WHERE confirmed_at IS NULL AND due_at <= now() ORDER BY due_at LIMIT 1`);
27
+ if (!first) {
28
+ return undefined;
29
+ }
30
+ const rows = yield* sql.unsafe(`SELECT record_id::text FROM _ontology_replication_erasures
31
+ WHERE confirmed_at IS NULL AND due_at <= now() AND entity_id = $1
32
+ ORDER BY record_id LIMIT $2::int`, [first.entity_id, limit]);
33
+ return {
34
+ entityId: first.entity_id,
35
+ recordIds: rows.map((row) => row.record_id),
36
+ };
37
+ });
38
+ /**
39
+ * Removes the records' content from every replication copy the source keeps: the events their
40
+ * history captured, delivery payloads kept for dropped history, baseline scan events and settled
41
+ * copy segments. Each copy keeps the event's identity and revision as a deletion, so a copy sent
42
+ * again can never show the record. Relationship events carry only ids and stay. A segment still
43
+ * being loaded keeps its events until it settles; the next pass scrubs it.
44
+ */
45
+ export const scrubReplicationErasures = (sql, batch) => sql.withTransaction(Effect.gen(function* () {
46
+ const target = yield* activeReplicationTarget(sql);
47
+ const active = target?.manifest.entities.find((item) => item.id === batch.entityId)?.name;
48
+ // An entity removed from the ontology keeps its records and history under its last name,
49
+ // which the latest replication target that declared it records.
50
+ const [retained] = active
51
+ ? []
52
+ : yield* sql.unsafe(`SELECT e->>'name' AS name FROM _ontology_replication_targets t
53
+ CROSS JOIN LATERAL jsonb_array_elements(t.manifest->'entities') e
54
+ WHERE e->>'id' = $1 ORDER BY t.created_at DESC LIMIT 1`, [batch.entityId]);
55
+ const name = active ?? retained?.name;
56
+ const history = name ? historyTableName(name) : undefined;
57
+ const ids = JSON.stringify(batch.recordIds);
58
+ let events = [];
59
+ if (history) {
60
+ const [exists] = yield* sql.unsafe("SELECT to_regclass($1) IS NOT NULL AS present", [qi(history)]);
61
+ if (exists?.present) {
62
+ const scrubbed = yield* sql.unsafe(`UPDATE ${qi(history)} SET replication = replication || ${SCRUBBED}
63
+ WHERE record_id IN (SELECT value::uuid FROM jsonb_array_elements_text($1::jsonb))
64
+ AND replication IS NOT NULL AND replication->>'record_kind' = 'entity'
65
+ RETURNING id::text`, [ids]);
66
+ events = scrubbed.map((row) => row.id);
67
+ }
68
+ }
69
+ const delivered = yield* sql.unsafe(`UPDATE _ontology_replication_delivery d SET payload = d.payload || ${SCRUBBED}
70
+ WHERE d.payload IS NOT NULL AND d.payload->>'entity_id' = $1
71
+ AND d.payload->>'record_kind' = 'entity'
72
+ AND d.payload->>'record_key' IN (SELECT value FROM jsonb_array_elements_text($2::jsonb))
73
+ RETURNING d.event_id::text AS id`, [batch.entityId, ids]);
74
+ const baselines = yield* sql.unsafe(`UPDATE _ontology_replication_baselines SET event = event || ${SCRUBBED}
75
+ WHERE event->>'entity_id' = $1 AND event->>'record_kind' = 'entity'
76
+ AND event->>'record_key' IN (SELECT value FROM jsonb_array_elements_text($2::jsonb))
77
+ RETURNING id::text`, [batch.entityId, ids]);
78
+ events = [...events, ...delivered.map((row) => row.id), ...baselines.map((row) => row.id)];
79
+ if (!events.length) {
80
+ return { objectUris: [], unsettled: 0 };
81
+ }
82
+ const matches = `e->>'entity_id' = $1 AND e->>'record_kind' = 'entity'
83
+ AND e->>'record_key' IN (SELECT value FROM jsonb_array_elements_text($2::jsonb))`;
84
+ const settled = yield* sql.unsafe(`UPDATE _ontology_replication_segments s SET events = (
85
+ SELECT jsonb_agg(CASE WHEN ${matches} THEN e || ${SCRUBBED} ELSE e END ORDER BY n)
86
+ FROM jsonb_array_elements(s.events) WITH ORDINALITY AS item(e, n))
87
+ WHERE s.state <> 'pending' AND s.event_ids ?| ARRAY(SELECT jsonb_array_elements_text($3::jsonb))
88
+ RETURNING s.object_uri`, [batch.entityId, ids, JSON.stringify(events)]);
89
+ const [pending] = yield* sql.unsafe(`SELECT count(*)::int AS count FROM _ontology_replication_segments s
90
+ WHERE s.state = 'pending' AND s.event_ids ?| ARRAY(SELECT jsonb_array_elements_text($1::jsonb))`, [JSON.stringify(events)]);
91
+ return {
92
+ objectUris: settled.map((row) => row.object_uri),
93
+ unsettled: pending?.count ?? 0,
94
+ };
95
+ }));
96
+ /**
97
+ * Records a warehouse erasure of the batch. The first erases the records. Their copies were scrubbed
98
+ * before it, so any event published since carries no content; one published earlier stays in
99
+ * Pub/Sub at most until the confirmation delay after that first erasure. A pass after that delay
100
+ * that removed nothing and found no unsettled copy confirms the records. Otherwise they are checked
101
+ * again the next day, or within the hour while a copy segment that holds them has not settled: it
102
+ * may still load their content, and its staging object is deleted once it has.
103
+ */
104
+ export const recordReplicationErasure = (sql, batch, outcome) => sql.unsafe(`UPDATE _ontology_replication_erasures SET attempts = attempts + 1, failure = NULL,
105
+ erased_at = COALESCE(erased_at, now()), erased_job = $3, erased_rows = erased_rows + $4::bigint,
106
+ confirmed_at = CASE WHEN erased_at IS NOT NULL AND $4::bigint = 0 AND $5::int = 0
107
+ AND now() >= erased_at + interval '${REPLICATION_ERASURE_CONFIRM_AFTER}' THEN now() END,
108
+ due_at = CASE WHEN $5::int > 0 THEN now() + interval '1 hour'
109
+ WHEN erased_at IS NULL THEN now() + interval '${REPLICATION_ERASURE_CONFIRM_AFTER}'
110
+ ELSE now() + interval '1 day' END
111
+ WHERE entity_id = $1 AND confirmed_at IS NULL
112
+ AND record_id IN (SELECT value::uuid FROM jsonb_array_elements_text($2::jsonb))
113
+ RETURNING record_id::text`, [
114
+ batch.entityId,
115
+ JSON.stringify(batch.recordIds),
116
+ outcome.jobId,
117
+ outcome.rows,
118
+ outcome.unsettled,
119
+ ]);
120
+ /** A failed attempt is retried an hour later; its reason is a code, never content. */
121
+ export const recordReplicationErasureFailure = (sql, batch, failure) => sql
122
+ .unsafe(`UPDATE _ontology_replication_erasures SET attempts = attempts + 1, failure = $3,
123
+ due_at = now() + interval '1 hour'
124
+ WHERE entity_id = $1 AND confirmed_at IS NULL
125
+ AND record_id IN (SELECT value::uuid FROM jsonb_array_elements_text($2::jsonb))
126
+ RETURNING attempts`, [batch.entityId, JSON.stringify(batch.recordIds), failure])
127
+ .pipe(Effect.map((rows) => Math.max(0, ...rows.map((row) => row.attempts))));
@@ -3,6 +3,7 @@ import { columnName, historyTableName, quoteIdentifier as qi, quoteLiteral as ql
3
3
  import { replicatesRecords } from "../replicated-entities.js";
4
4
  import { replicatedFields, REPLICATION_RECORD_BYTES } from "./model.js";
5
5
  import { SHADOW_REPLICATION_DDL, SHADOW_CONTROL_JOBS_DDL, SHADOW_SOURCE_REPLACEMENTS_DDL, } from "./shadow-schema.js";
6
+ import { REPLICATION_ERASURES_DDL } from "./erasure-schema.js";
6
7
  export const REPLICATION_SCHEMA_VERSION = 6;
7
8
  /** Targets of sources not migrated since fills were introduced have no `fills` column. */
8
9
  export const REPLICATION_TARGET_FILLS = `COALESCE(to_jsonb(_ontology_replication_targets) -> 'fills',
@@ -111,6 +112,7 @@ export const REPLICATION_DDL = [
111
112
  ...SHADOW_REPLICATION_DDL,
112
113
  SHADOW_CONTROL_JOBS_DDL,
113
114
  SHADOW_SOURCE_REPLACEMENTS_DDL,
115
+ ...REPLICATION_ERASURES_DDL,
114
116
  `CREATE OR REPLACE FUNCTION _ontology_replication_guard() RETURNS trigger LANGUAGE plpgsql AS $$
115
117
  BEGIN
116
118
  IF (SELECT enabled FROM _ontology_replication WHERE id) AND
@@ -1,5 +1,5 @@
1
1
  import { validateTelegramPreviews } from "../../telegram.js";
2
- import { chatRetentionDaysOf, inboxAttributionOf, takeoverChannelsOf } from "../../manifest.js";
2
+ import { chatRetentionDaysOf, inboxAttributionOf, signsMail, takeoverChannelsOf, } from "../../manifest.js";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { Cause, Effect } from "effect";
5
5
  import { chatOperationId, chatPreviewDigest, } from "../../chat.js";
@@ -775,6 +775,7 @@ chats) {
775
775
  ? { chatId: place.chatId }
776
776
  : {}),
777
777
  transport,
778
+ ...(signsMail(ontology.manifest, target.provider) ? { signature: true } : {}),
778
779
  });
779
780
  if (outcome.cause !== undefined) {
780
781
  yield* report("provider", outcome.cause);
@@ -1,8 +1,10 @@
1
1
  import { Effect } from "effect";
2
2
  import { AGENT_DRAFT_FILES_LIMIT } from "../../../agent-draft.js";
3
- import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, } from "../../../email.js";
3
+ import { base64Url, EMAIL_FILES_BYTES, EMAIL_MESSAGE_LIMIT, emailReplyMessage, GmailError, gmailExplanation, GmailMaybeSent, renderEmailHtml, replyAllRecipients, sendGmailMessage, withEmailSignature, } from "../../../email.js";
4
+ import { mailboxSignature } from "../../../gmail-send.js";
4
5
  import { ActionRejected } from "../../../errors.js";
5
6
  import { EMAIL_PATTERN } from "../../../property.js";
7
+ import { describeChatError } from "../diagnostics.js";
6
8
  import { channelRequest, definiteTransportFailure, filesWithBytes, record, transportFailure, } from "./provider.js";
7
9
  /** A Gmail id, of a thread or a message. */
8
10
  const GMAIL_ID = /^[A-Za-z0-9_-]{1,512}$/;
@@ -88,6 +90,21 @@ function threadHeaders(received) {
88
90
  references: last.get("references") ?? null,
89
91
  };
90
92
  }
93
+ /**
94
+ * The mailbox's own signature, read through the connection and kept a while per mailbox, as the
95
+ * agent's replies read it; `undefined` when it has none or Gmail refused the read, which is logged
96
+ * and sends the reply unsigned rather than not at all.
97
+ */
98
+ function signatureOf(input) {
99
+ return Effect.tryPromise({
100
+ try: () => mailboxSignature({
101
+ mailbox: input.connection,
102
+ request: (call) => Effect.runPromise(input.transport.request({ connection: input.connection, ...call })),
103
+ }),
104
+ // The original failure, Gmail's explanation or the connection's, with its causes and stack.
105
+ catch: (cause) => cause,
106
+ }).pipe(Effect.catch((cause) => Effect.logWarning("ontology.chat.email_signature_unavailable").pipe(Effect.annotateLogs({ error: describeChatError(cause, (text) => text) }), Effect.as(undefined))));
107
+ }
91
108
  /**
92
109
  * One reply in the person's email thread, from the mailbox the ontology's `chat.email` names, to
93
110
  * its `recipients`, `To` and `Cc`, or else to the destination alone. It reads the thread's subject
@@ -146,6 +163,10 @@ export function sendEmail(input) {
146
163
  const key = input.operationId !== undefined && input.operationId !== input.destination.id
147
164
  ? `post-${input.operationId}`
148
165
  : `review-${input.destination.id}`;
166
+ // With the channel's `signature`, the HTML ends with the mailbox's own signature.
167
+ const html = input.signature === true
168
+ ? withEmailSignature(input.finalText, yield* signatureOf(input))
169
+ : input.finalText;
149
170
  const to = input.recipients?.to ?? [input.destination.external_id];
150
171
  const cc = input.recipients?.cc ?? [];
151
172
  const files = input.files ?? [];
@@ -156,7 +177,7 @@ export function sendEmail(input) {
156
177
  inReplyTo: answered.inReplyTo,
157
178
  references: answered.references,
158
179
  text: input.plainText,
159
- html: input.finalText,
180
+ html,
160
181
  autoSubmitted: true,
161
182
  ...(/^[A-Za-z0-9_-]{1,128}$/.test(key) ? { replyKey: key } : {}),
162
183
  ...(files.length === 0 ? {} : { attachments: filesWithBytes(files) }),
@@ -165,7 +186,7 @@ export function sendEmail(input) {
165
186
  threadId,
166
187
  to,
167
188
  cc,
168
- html: input.finalText,
189
+ html,
169
190
  text: input.plainText,
170
191
  ...(files.length === 0 ? {} : { files: files.map((file) => file.filename) }),
171
192
  };
@@ -126,6 +126,8 @@ export interface ChatSend {
126
126
  * the thread; without them the provider reads the thread itself. Others ignore them.
127
127
  */
128
128
  readonly thread?: ThreadHeaders;
129
+ /** Whether a reply to mail ends with the mailbox's own signature; others ignore it. */
130
+ readonly signature?: boolean;
129
131
  }
130
132
  /**
131
133
  * A channel the platform posts exact chat messages to. Each provider names its own ids, renders
@@ -6,7 +6,7 @@ import { effectiveScope } from "../../permissions.js";
6
6
  import { describeChatError } from "./diagnostics.js";
7
7
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
8
8
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
9
- import { chatRetentionDaysOf } from "../../manifest.js";
9
+ import { chatRetentionDaysOf, signsMail } from "../../manifest.js";
10
10
  import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
11
11
  import { storeDeliveryArchive } from "./store-delivery.js";
12
12
  import { readDraftFiles, refuseChatFiles } from "./draft-files.js";
@@ -468,6 +468,7 @@ export function reviewSender(input) {
468
468
  ...(sendFiles.length === 0 ? {} : { files: sendFiles }),
469
469
  ...(recipients === undefined ? {} : { recipients }),
470
470
  ...(input.agent === undefined ? {} : { agent: input.agent }),
471
+ ...(signsMail(input.ontology.manifest, providerName) ? { signature: true } : {}),
471
472
  ...(input.previews === undefined ? {} : { previews: input.previews }),
472
473
  transport: input.connections({
473
474
  identityToken: input.identityToken,