@taopao/memoir 0.0.0-stage → 0.1.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/assets/migrations-pg/0100_baseline.sql +1115 -0
  4. package/assets/migrations-pg/0101_functions.sql +93 -0
  5. package/assets/migrations-pg/0102_views.sql +2425 -0
  6. package/assets/migrations-pg/0103_constraints.sql +147 -0
  7. package/assets/migrations-pg/0104_protection.sql +33 -0
  8. package/assets/migrations-pg/0105_bocom_credit_card.sql +43 -0
  9. package/assets/migrations-pg/0106_psbc_debit_card.sql +87 -0
  10. package/assets/migrations-pg/0107_tailong_debit_card.sql +87 -0
  11. package/assets/migrations-pg/0108_ccb_debit_card.sql +87 -0
  12. package/assets/migrations-pg/0109_ccb_credit_card.sql +63 -0
  13. package/assets/migrations-pg/0110_icbc_debit_card.sql +87 -0
  14. package/assets/migrations-pg/0111_icbc_credit_card.sql +66 -0
  15. package/assets/migrations-pg/0112_boc_debit_card.sql +88 -0
  16. package/assets/migrations-pg/0113_jsb_debit_card.sql +88 -0
  17. package/assets/migrations-pg/0114_cmbc_debit_card.sql +88 -0
  18. package/assets/migrations-pg/0115_hzbank_debit_card.sql +88 -0
  19. package/assets/migrations-pg/0116_unified_bank_documents.sql +197 -0
  20. package/assets/migrations-pg/0117_agent_submissions.sql +50 -0
  21. package/assets/migrations-pg/0118_agent_reversions_analysis.sql +34 -0
  22. package/assets/migrations-pg/0119_agent_extension_registry.sql +72 -0
  23. package/assets/migrations-pg/0120_agent_record_sources.sql +22 -0
  24. package/assets/migrations-pg/0121_agent_extension_deprecation.sql +30 -0
  25. package/assets/migrations-pg/0122_agent_extension_controlled_revert.sql +107 -0
  26. package/assets/migrations-pg/0123_agent_extension_versions.sql +54 -0
  27. package/assets/migrations-pg/0124_agent_extension_retirement_groups.sql +26 -0
  28. package/assets/migrations-pg/0125_agent_candidate_reviews.sql +30 -0
  29. package/assets/migrations-pg/0126_agent_module_lifecycle.sql +93 -0
  30. package/assets/migrations-pg/0127_agent_tasks.sql +64 -0
  31. package/assets/migrations-pg/0128_agent_task_leases.sql +80 -0
  32. package/assets/migrations-pg/0129_agent_task_plans.sql +66 -0
  33. package/assets/migrations-pg/0130_agent_task_submissions.sql +72 -0
  34. package/assets/migrations-pg/0131_agent_task_completions.sql +93 -0
  35. package/assets/migrations-pg/0132_agent_task_changes.sql +113 -0
  36. package/assets/migrations-pg/0133_agent_imported_source_snapshots.sql +152 -0
  37. package/assets/migrations-pg/0134_agent_analysis_datasets.sql +6 -0
  38. package/assets/migrations-pg/0135_agent_maintenance_tasks.sql +139 -0
  39. package/assets/migrations-pg/0136_agent_task_structures.sql +66 -0
  40. package/assets/migrations-pg/0137_agent_personal_identity.sql +149 -0
  41. package/assets/migrations-pg/0138_agent_work_records.sql +24 -0
  42. package/assets/migrations-pg/0139_shared_files.sql +43 -0
  43. package/assets/migrations-pg/0140_shared_script_runs.sql +36 -0
  44. package/assets/migrations-pg/0141_payment_bank_links.sql +96 -0
  45. package/assets/migrations-pg/0142_consumption_order_types_and_places.sql +287 -0
  46. package/assets/migrations-pg/0143_skill_direct_write.sql +330 -0
  47. package/assets/migrations-pg/0144_skill_schema_archive.sql +73 -0
  48. package/assets/migrations-pg/0145_skill_ingest_wiki.sql +91 -0
  49. package/assets/migrations-pg/0146_skill_load.sql +17 -0
  50. package/assets/migrations-pg/0147_drop_agent_schema.sql +147 -0
  51. package/assets/migrations-pg/0148_ingest_lanes.sql +19 -0
  52. package/assets/migrations-pg/0149_account_ownership.sql +233 -0
  53. package/assets/migrations-pg/0150_bank_card_exact_link.sql +24 -0
  54. package/assets/migrations-pg/0151_account_ownership_enforce.sql +35 -0
  55. package/assets/migrations-pg/0152_account_ownership_views.sql +750 -0
  56. package/assets/migrations-pg/0153_web_frontend.sql +34 -0
  57. package/assets/migrations-pg/0154_audio_record_owners.sql +103 -0
  58. package/assets/migrations-pg/0155_ingest_knowledge_tables.sql +171 -0
  59. package/assets/migrations-pg/0156_batch_playbook_note.sql +17 -0
  60. package/assets/migrations-pg/0157_last_contact.sql +166 -0
  61. package/assets/migrations-pg/0158_refund_match_hash_join.sql +91 -0
  62. package/assets/migrations-pg/0159_fact_occurred_time.sql +88 -0
  63. package/assets/migrations-pg/0160_agent_notes.sql +118 -0
  64. package/assets/migrations-pg/0161_life_history.sql +314 -0
  65. package/assets/migrations-pg/0162_person_card.sql +427 -0
  66. package/assets/migrations-pg/0163_parking_drop_personal_defaults.sql +12 -0
  67. package/assets/native/darwin-arm64.node +0 -0
  68. package/assets/playbooks/audio.md +83 -0
  69. package/assets/playbooks/chat.md +37 -0
  70. package/assets/playbooks/common.md +66 -0
  71. package/assets/playbooks/intimate.md +19 -0
  72. package/assets/playbooks/journal.md +17 -0
  73. package/assets/playbooks/orders.md +15 -0
  74. package/assets/playbooks/payments.md +16 -0
  75. package/assets/playbooks/self.md +29 -0
  76. package/bin/install-codex-skill.mjs +77 -0
  77. package/bin/memoir.mjs +5 -0
  78. package/dist/cli.js +34062 -0
  79. package/package.json +40 -4
  80. package/release-manifest.json +432 -0
  81. package/skill/SKILL.md +120 -0
  82. package/skill/references//345/256/211/350/243/205/344/275/215/347/275/256.md +21 -0
  83. package/skill/references//346/225/260/346/215/256/345/217/243/345/276/204.md +36 -0
  84. package/skill/scripts/memoir.mjs +82 -0
@@ -0,0 +1,287 @@
1
+ -- 仅 PostgreSQL:按业务订单类型(外卖、团购、电商包裹、停车)与消费地点(城市/商圈/门店)进行领域建模与视图穿透。
2
+ SELECT pg_advisory_xact_lock(hashtext('relation-vault:write'));
3
+
4
+ -- 1. 消费地点与场所主表
5
+ CREATE TABLE spending_places (
6
+ id text PRIMARY KEY,
7
+ city text NOT NULL,
8
+ district text,
9
+ area_landmark text,
10
+ place_name text NOT NULL,
11
+ place_type text NOT NULL CHECK(place_type IN ('mall', 'restaurant', 'supermarket', 'hospital', 'parking', 'transit', 'residence', 'other')),
12
+ address text,
13
+ created_at text NOT NULL,
14
+ created_by text NOT NULL,
15
+ updated_at text NOT NULL,
16
+ updated_by text NOT NULL
17
+ );
18
+
19
+ -- 2. 商户规则库与场景映射表
20
+ CREATE TABLE merchant_profiles (
21
+ id text PRIMARY KEY,
22
+ pattern text NOT NULL,
23
+ canonical_name text NOT NULL,
24
+ default_place_id text REFERENCES spending_places(id),
25
+ default_scene text NOT NULL CHECK(default_scene IN ('dating', 'dining_out', 'home_daily', 'car_transit', 'medical', 'shopping', 'other')),
26
+ created_at text NOT NULL,
27
+ created_by text NOT NULL,
28
+ updated_at text NOT NULL,
29
+ updated_by text NOT NULL
30
+ );
31
+
32
+ -- 3. 消费地点归属关联表
33
+ CREATE TABLE spending_location_links (
34
+ id text PRIMARY KEY,
35
+ target_type text NOT NULL CHECK(target_type IN ('order', 'payment')),
36
+ target_platform text NOT NULL,
37
+ target_key text NOT NULL,
38
+ place_id text NOT NULL REFERENCES spending_places(id),
39
+ scene text NOT NULL CHECK(scene IN ('dating', 'dining_out', 'home_daily', 'car_transit', 'medical', 'shopping', 'other')),
40
+ detected_from text NOT NULL CHECK(detected_from IN ('shop_name', 'counterparty', 'item_desc', 'address', 'manual')),
41
+ evidence_text text NOT NULL,
42
+ confidence text NOT NULL CHECK(confidence IN ('high', 'medium', 'low', 'manual')),
43
+ created_at text NOT NULL,
44
+ created_by text NOT NULL,
45
+ updated_at text NOT NULL,
46
+ updated_by text NOT NULL,
47
+ UNIQUE(target_type, target_platform, target_key)
48
+ );
49
+
50
+ -- 4. 专属订单类型子表:即时外卖订单
51
+ CREATE TABLE ext_takeout_orders (
52
+ order_platform text NOT NULL,
53
+ order_no text NOT NULL,
54
+ shop_name text NOT NULL,
55
+ shop_branch text,
56
+ delivery_address text NOT NULL,
57
+ recipient_name text,
58
+ delivery_fee_cents bigint NOT NULL DEFAULT 0,
59
+ packing_fee_cents bigint NOT NULL DEFAULT 0,
60
+ created_at text NOT NULL,
61
+ created_by text NOT NULL,
62
+ updated_at text NOT NULL,
63
+ updated_by text NOT NULL,
64
+ PRIMARY KEY (order_platform, order_no),
65
+ FOREIGN KEY (order_platform, order_no) REFERENCES orders(platform, order_no)
66
+ );
67
+
68
+ -- 5. 专属订单类型子表:到店团购券订单
69
+ CREATE TABLE ext_voucher_orders (
70
+ order_platform text NOT NULL,
71
+ order_no text NOT NULL,
72
+ package_title text NOT NULL,
73
+ merchant_name text NOT NULL,
74
+ applicable_mall text,
75
+ voucher_status text NOT NULL CHECK(voucher_status IN ('unused', 'redeemed', 'refunded', 'expired')),
76
+ redeemed_at text,
77
+ created_at text NOT NULL,
78
+ created_by text NOT NULL,
79
+ updated_at text NOT NULL,
80
+ updated_by text NOT NULL,
81
+ PRIMARY KEY (order_platform, order_no),
82
+ FOREIGN KEY (order_platform, order_no) REFERENCES orders(platform, order_no)
83
+ );
84
+
85
+ -- 6. 专属订单类型子表:电商实物快递包裹
86
+ CREATE TABLE ext_parcel_orders (
87
+ order_platform text NOT NULL,
88
+ order_no text NOT NULL,
89
+ carrier text,
90
+ tracking_number text,
91
+ shipping_address text NOT NULL,
92
+ goods_name text NOT NULL,
93
+ goods_spec text,
94
+ shipping_status text,
95
+ created_at text NOT NULL,
96
+ created_by text NOT NULL,
97
+ updated_at text NOT NULL,
98
+ updated_by text NOT NULL,
99
+ PRIMARY KEY (order_platform, order_no),
100
+ FOREIGN KEY (order_platform, order_no) REFERENCES orders(platform, order_no)
101
+ );
102
+
103
+ -- 7. 专属订单类型子表:车辆停放与路桥出行订单
104
+ CREATE TABLE ext_parking_orders (
105
+ id text PRIMARY KEY,
106
+ payment_platform text NOT NULL,
107
+ payment_txn_id text NOT NULL,
108
+ license_plate text NOT NULL DEFAULT '浙AG50033',
109
+ parking_lot_name text NOT NULL,
110
+ city text NOT NULL DEFAULT '徐州市',
111
+ entry_time text,
112
+ duration_minutes integer,
113
+ parking_fee_cents bigint NOT NULL,
114
+ created_at text NOT NULL,
115
+ created_by text NOT NULL,
116
+ updated_at text NOT NULL,
117
+ updated_by text NOT NULL,
118
+ FOREIGN KEY (payment_platform, payment_txn_id) REFERENCES payments(platform, txn_id)
119
+ );
120
+
121
+ -- 8. 审计与保护机制设置
122
+ DO $$ DECLARE tbl text; g record; BEGIN
123
+ FOREACH tbl IN ARRAY ARRAY['spending_places','merchant_profiles','spending_location_links','ext_takeout_orders','ext_voucher_orders','ext_parcel_orders','ext_parking_orders'] LOOP
124
+ EXECUTE format('CREATE TRIGGER trg_%1$s_guard BEFORE INSERT OR UPDATE OR DELETE ON %1$I FOR EACH ROW EXECUTE FUNCTION vault_guard(''session'')', tbl);
125
+ EXECUTE format('CREATE TRIGGER trg_%1$s_truncate BEFORE TRUNCATE ON %1$I FOR EACH STATEMENT EXECUTE FUNCTION vault_guard(''session'')', tbl);
126
+ IF tbl IN ('ext_takeout_orders','ext_voucher_orders','ext_parcel_orders') THEN
127
+ EXECUTE format('CREATE TRIGGER trg_%1$s_audit AFTER INSERT OR UPDATE OR DELETE ON %1$I FOR EACH ROW EXECUTE FUNCTION vault_audit(''order_platform'',''order_no'')', tbl);
128
+ ELSE
129
+ EXECUTE format('CREATE TRIGGER trg_%1$s_audit AFTER INSERT OR UPDATE OR DELETE ON %1$I FOR EACH ROW EXECUTE FUNCTION vault_audit(''id'')', tbl);
130
+ END IF;
131
+ EXECUTE format('CREATE TRIGGER trg_%1$s_version AFTER INSERT OR UPDATE OR DELETE ON %1$I FOR EACH STATEMENT EXECUTE FUNCTION vault_touch()', tbl);
132
+ EXECUTE format('REVOKE ALL ON %I FROM PUBLIC', tbl);
133
+ FOR g IN SELECT DISTINCT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_schema = 'public' AND table_name = 'payment_order_links' AND grantee <> current_user AND privilege_type IN ('SELECT', 'INSERT', 'UPDATE') LOOP
134
+ EXECUTE format('GRANT %s ON %I TO %s', g.privilege_type, tbl, CASE WHEN g.grantee = 'PUBLIC' THEN 'PUBLIC' ELSE quote_ident(g.grantee) END);
135
+ END LOOP;
136
+ END LOOP;
137
+ END $$;
138
+
139
+ -- 9. 视图:跨平台订单与全链路穿透大表
140
+ CREATE OR REPLACE VIEW v_cross_platform_orders AS
141
+ WITH order_item_agg AS (
142
+ SELECT
143
+ platform,
144
+ order_no,
145
+ string_agg(product_name, ' + ' ORDER BY line_no) AS products_summary,
146
+ count(*) AS item_count
147
+ FROM order_items
148
+ GROUP BY platform, order_no
149
+ ),
150
+ linked_chains AS (
151
+ SELECT
152
+ ol.order_platform,
153
+ ol.order_no,
154
+ p.platform AS payment_platform,
155
+ p.txn_id AS payment_txn_id,
156
+ p.pay_method AS payment_method,
157
+ b.bank_name AS bank_card_name,
158
+ b.card_last_four,
159
+ b.amount_cents AS bank_paid_cents
160
+ FROM payment_order_links ol
161
+ JOIN payments p
162
+ ON p.platform = ol.payment_platform AND p.txn_id = ol.payment_txn_id
163
+ LEFT JOIN payment_bank_links bl
164
+ ON bl.payment_platform = p.platform AND bl.payment_txn_id = p.txn_id AND bl.state = 'confirmed'
165
+ LEFT JOIN _v_finance_bank_entries b
166
+ ON b.transaction_key = COALESCE(bl.debit_transaction_key, bl.credit_transaction_key)
167
+ WHERE ol.deleted_at IS NULL
168
+ )
169
+ SELECT
170
+ o.platform AS order_platform,
171
+ CASE o.platform
172
+ WHEN 'taobao' THEN '淘宝/天猫'
173
+ WHEN 'jd' THEN '京东商城'
174
+ WHEN 'meituan' THEN '美团外卖'
175
+ WHEN 'pdd' THEN '拼多多'
176
+ WHEN 'douyin' THEN '抖音电商'
177
+ WHEN 'taobao_takeout' THEN '淘宝闪购'
178
+ ELSE o.platform
179
+ END AS order_platform_name,
180
+ o.order_no,
181
+ coalesce(o.paid_at, o.ordered_at) AS ordered_at,
182
+ o.status AS order_status,
183
+ o.shop_name,
184
+ coalesce(ia.products_summary, o.shop_name, '商品') AS products_summary,
185
+ o.total_paid_cents AS order_paid_cents,
186
+ round(o.total_paid_cents / 100.0, 2) AS order_paid_yuan,
187
+ lc.payment_platform,
188
+ lc.payment_method,
189
+ lc.bank_card_name,
190
+ lc.card_last_four,
191
+ lc.bank_paid_cents,
192
+ CASE
193
+ WHEN o.status IN ('交易关闭', '已退款', '已取消') THEN 'closed'
194
+ WHEN lc.bank_paid_cents IS NOT NULL THEN 'three_tier'
195
+ WHEN lc.payment_platform IS NOT NULL THEN 'two_tier'
196
+ WHEN o.platform = 'pdd' AND o.status = '待收货' THEN 'pending_settle'
197
+ ELSE 'unlinked'
198
+ END AS chain_state
199
+ FROM orders o
200
+ LEFT JOIN order_item_agg ia
201
+ ON ia.platform = o.platform AND ia.order_no = o.order_no
202
+ LEFT JOIN linked_chains lc
203
+ ON lc.order_platform = o.platform AND lc.order_no = o.order_no;
204
+
205
+ -- 10. 视图:按订单业务大类与地点分类呈现
206
+ CREATE OR REPLACE VIEW v_typed_orders_explorer AS
207
+ SELECT
208
+ o.platform,
209
+ o.order_no,
210
+ coalesce(o.paid_at, o.ordered_at) AS occurred_at,
211
+ round(o.total_paid_cents / 100.0, 2) AS amount_yuan,
212
+ o.status AS order_status,
213
+ CASE
214
+ WHEN t.order_no IS NOT NULL THEN '即时外卖'
215
+ WHEN v.order_no IS NOT NULL THEN '到店团购'
216
+ WHEN p.order_no IS NOT NULL THEN '电商快递'
217
+ WHEN o.shop_name = '火车票' THEN '城际高铁'
218
+ ELSE '其他消费'
219
+ END AS order_category,
220
+ CASE
221
+ WHEN t.order_no IS NOT NULL THEN concat_ws(' · 送至:', t.shop_branch, t.delivery_address)
222
+ WHEN v.order_no IS NOT NULL THEN concat_ws(' · ', v.applicable_mall, v.merchant_name)
223
+ WHEN p.order_no IS NOT NULL THEN concat_ws(' · 收件:', p.carrier, p.shipping_address)
224
+ WHEN o.shop_name = '火车票' THEN '京沪高铁沿线车站'
225
+ ELSE o.shop_name
226
+ END AS consumption_place,
227
+ CASE
228
+ WHEN t.order_no IS NOT NULL THEN t.shop_name
229
+ WHEN v.order_no IS NOT NULL THEN v.package_title
230
+ WHEN p.order_no IS NOT NULL THEN concat_ws(' ', p.goods_name, p.goods_spec)
231
+ WHEN o.shop_name = '火车票' THEN '12306 车票'
232
+ ELSE o.shop_name
233
+ END AS order_detail
234
+ FROM orders o
235
+ LEFT JOIN ext_takeout_orders t ON t.order_platform = o.platform AND t.order_no = o.order_no
236
+ LEFT JOIN ext_voucher_orders v ON v.order_platform = o.platform AND v.order_no = o.order_no
237
+ LEFT JOIN ext_parcel_orders p ON p.order_platform = o.platform AND p.order_no = o.order_no;
238
+
239
+ -- 11. 视图:按消费空间(城市与商圈)汇总
240
+ CREATE OR REPLACE VIEW v_spending_by_location AS
241
+ SELECT
242
+ p.city,
243
+ coalesce(p.district, '主城区') AS district,
244
+ coalesce(p.area_landmark, '其他商户') AS area_landmark,
245
+ count(DISTINCT s.source_key) AS order_count,
246
+ round(sum(s.amount_cents) / 100.0, 2) AS total_amount_yuan
247
+ FROM spending_location_links l
248
+ JOIN spending_places p ON p.id = l.place_id
249
+ JOIN v_spending s ON (
250
+ (l.target_type = 'order' AND s.source_type IN ('order', 'order_item') AND s.platform = l.target_platform AND s.order_no = l.target_key)
251
+ OR
252
+ (l.target_type = 'payment' AND s.source_type = 'payment' AND s.platform = l.target_platform AND s.source_key = (l.target_platform || ':' || l.target_key))
253
+ )
254
+ GROUP BY p.city, p.district, p.area_landmark
255
+ ORDER BY total_amount_yuan DESC;
256
+
257
+ -- 12. 视图:按生活场景汇总
258
+ CREATE OR REPLACE VIEW v_spending_by_scene AS
259
+ SELECT
260
+ CASE l.scene
261
+ WHEN 'dating' THEN '🌹 浪漫约会与心意礼物'
262
+ WHEN 'home_daily' THEN '🏠 居家日常与生活百货'
263
+ WHEN 'dining_out' THEN '🍽️ 外出堂食与便民快餐'
264
+ WHEN 'car_transit' THEN '🚗 车辆保养与通勤路费'
265
+ WHEN 'medical' THEN '💊 医疗健康与药房就医'
266
+ WHEN 'shopping' THEN '🛍️ 商场购物与服饰专柜'
267
+ ELSE '📦 其他日常消费'
268
+ END AS scene_name,
269
+ count(DISTINCT s.source_key) AS count,
270
+ round(sum(s.amount_cents) / 100.0, 2) AS total_amount_yuan
271
+ FROM spending_location_links l
272
+ JOIN v_spending s ON (
273
+ (l.target_type = 'order' AND s.source_type IN ('order', 'order_item') AND s.platform = l.target_platform AND s.order_no = l.target_key)
274
+ OR
275
+ (l.target_type = 'payment' AND s.source_type = 'payment' AND s.platform = l.target_platform AND s.source_key = (l.target_platform || ':' || l.target_key))
276
+ )
277
+ GROUP BY l.scene
278
+ ORDER BY total_amount_yuan DESC;
279
+
280
+ -- 视图读取权限授权
281
+ DO $$ DECLARE vw text; g record; BEGIN
282
+ FOREACH vw IN ARRAY ARRAY['v_cross_platform_orders','v_typed_orders_explorer','v_spending_by_location','v_spending_by_scene'] LOOP
283
+ FOR g IN SELECT DISTINCT grantee FROM information_schema.role_table_grants WHERE table_schema = 'public' AND table_name = 'v_spending' AND privilege_type = 'SELECT' AND grantee <> current_user LOOP
284
+ EXECUTE format('GRANT SELECT ON %I TO %s', vw, CASE WHEN g.grantee = 'PUBLIC' THEN 'PUBLIC' ELSE quote_ident(g.grantee) END);
285
+ END LOOP;
286
+ END LOOP;
287
+ END $$;
@@ -0,0 +1,330 @@
1
+ -- 仅 PostgreSQL:Agent 主导精简 Skill 的直接写入基础(方案见 docs/proposals/Agent主导精简Skill重构方案.md)。
2
+ --
3
+ -- 业务背景:Skill 让 Agent 直接写 SQL 记录数据、按需建表,不再经过逐类型 JSON 契约。为此需要:
4
+ -- 1. 标准列(id、时间、操作者)有默认值,Agent 写 INSERT 只填业务字段;
5
+ -- 2. 记忆类表有 provenance 来源标记(用户亲口 / Agent 推断 / 导入),代替候选审核;
6
+ -- 3. 批次登记表 vault_batches 与结构变更日志 schema_changes,支撑整批撤回与"数据库为结构权威";
7
+ -- 4. 新表/新视图的注册函数,让 Agent 新建的对象自动具备与核心表一致的写会话保护、逐行审计与授权;
8
+ -- 5. 核心表与常用视图的中文注释,Agent 通过 context 读注释理解结构。
9
+ -- 只追加默认值、可空列、新表与注释,不改写、不删除任何已有数据。
10
+ SELECT pg_advisory_xact_lock(hashtext('relation-vault:write'));
11
+
12
+ -- 1. 默认值函数:时间统一为上海时间文本(与 nowBeijing 同格式),操作者取当前写会话。
13
+ CREATE OR REPLACE FUNCTION public.vault_now_text() RETURNS text LANGUAGE sql VOLATILE AS $$
14
+ SELECT to_char(clock_timestamp() AT TIME ZONE 'Asia/Shanghai', 'YYYY-MM-DD HH24:MI:SS')
15
+ $$;
16
+ COMMENT ON FUNCTION public.vault_now_text() IS '当前上海时间,格式 YYYY-MM-DD HH24:MI:SS,用作 created_at/updated_at 默认值';
17
+
18
+ CREATE OR REPLACE FUNCTION public.vault_current_actor() RETURNS text LANGUAGE sql STABLE AS $$
19
+ SELECT coalesce(nullif(current_setting('vault.actor', true), ''), 'unknown')
20
+ $$;
21
+ COMMENT ON FUNCTION public.vault_current_actor() IS '当前写会话操作者,用作 created_by/updated_by 默认值';
22
+
23
+ -- 2. 为 public 下已有表的标准列补默认值;已有默认值的列不动。
24
+ -- UPDATE 时可写 updated_at = DEFAULT, updated_by = DEFAULT 刷新。
25
+ DO $$ DECLARE r record; BEGIN
26
+ FOR r IN
27
+ SELECT c.table_name, c.column_name
28
+ FROM information_schema.columns c
29
+ JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name
30
+ WHERE c.table_schema = 'public' AND t.table_type = 'BASE TABLE'
31
+ AND c.column_default IS NULL AND c.data_type = 'text'
32
+ AND c.column_name IN ('created_at', 'updated_at', 'created_by', 'updated_by')
33
+ LOOP
34
+ EXECUTE format('ALTER TABLE public.%I ALTER COLUMN %I SET DEFAULT %s', r.table_name, r.column_name,
35
+ CASE WHEN r.column_name LIKE '%\_at' THEN 'public.vault_now_text()' ELSE 'public.vault_current_actor()' END);
36
+ END LOOP;
37
+ -- 单列 text 主键 id 没有默认值时补随机 UUID 文本;persons.id 的小写/连字符检查对 UUID 同样成立。
38
+ FOR r IN
39
+ SELECT c.relname
40
+ FROM pg_class c
41
+ JOIN pg_namespace n ON n.oid = c.relnamespace
42
+ JOIN pg_index i ON i.indrelid = c.oid AND i.indisprimary AND i.indnatts = 1
43
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = i.indkey[0]
44
+ WHERE n.nspname = 'public' AND c.relkind = 'r'
45
+ AND a.attname = 'id' AND a.atttypid = 'text'::regtype AND NOT a.atthasdef
46
+ LOOP
47
+ EXECUTE format('ALTER TABLE public.%I ALTER COLUMN id SET DEFAULT gen_random_uuid()::text', r.relname);
48
+ END LOOP;
49
+ END $$;
50
+
51
+ -- 3. 记忆类表增加来源标记。旧行保持 NULL(来源未登记),不回填猜测值。
52
+ DO $$ DECLARE tbl text; BEGIN
53
+ FOREACH tbl IN ARRAY ARRAY[
54
+ 'persons','person_aliases','profile_facts','preferences','events','important_dates','wishes',
55
+ 'gift_ideas','promises','todos','health_events','relations','intimacy_events',
56
+ 'menstrual_cycles','menstrual_daily_logs','journal_entries'
57
+ ] LOOP
58
+ EXECUTE format('ALTER TABLE public.%I ADD COLUMN IF NOT EXISTS provenance text CHECK (provenance IS NULL OR provenance IN (''user'', ''inferred'', ''import''))', tbl);
59
+ EXECUTE format('COMMENT ON COLUMN public.%I.provenance IS %L', tbl,
60
+ '来源标记:user=用户亲口说的,inferred=Agent 从聊天/录音等推断,import=导入程序写入;NULL=历史数据未登记');
61
+ END LOOP;
62
+ END $$;
63
+
64
+ -- 4. 随笔 origin 增加 skill(经 Skill 记录的用户原话);只替换该 CHECK,其余约束不变。
65
+ DO $$ DECLARE con text; BEGIN
66
+ SELECT k.conname INTO con
67
+ FROM pg_constraint k
68
+ WHERE k.conrelid = 'public.journal_entries'::regclass AND k.contype = 'c'
69
+ AND pg_get_constraintdef(k.oid) LIKE '%origin%ai_dictation%';
70
+ IF con IS NOT NULL THEN
71
+ EXECUTE format('ALTER TABLE public.journal_entries DROP CONSTRAINT %I', con);
72
+ END IF;
73
+ ALTER TABLE public.journal_entries ADD CONSTRAINT journal_entries_origin_check
74
+ CHECK (origin IN ('h5', 'cli', 'legacy_md', 'ai_dictation', 'skill'));
75
+ END $$;
76
+
77
+ -- 5. 批次登记:每次 remember / undo 一行,id 同时写入 audit_log.change_set,撤回按它整批定位。
78
+ CREATE TABLE public.vault_batches (
79
+ id text PRIMARY KEY,
80
+ kind text NOT NULL CHECK (kind IN ('remember', 'undo')),
81
+ actor text NOT NULL DEFAULT public.vault_current_actor(),
82
+ agent text,
83
+ reason text,
84
+ journal_id text,
85
+ idempotency_key text UNIQUE,
86
+ request_hash text,
87
+ result_json text CHECK (result_json IS NULL OR vault_json_valid(result_json)),
88
+ undoes text REFERENCES public.vault_batches(id),
89
+ undone_by text REFERENCES public.vault_batches(id),
90
+ created_at text NOT NULL DEFAULT public.vault_now_text()
91
+ );
92
+ COMMENT ON TABLE public.vault_batches IS 'Skill 写入批次:每次记一下(remember)或撤回(undo)一行;id 即审计日志 change_set';
93
+ COMMENT ON COLUMN public.vault_batches.kind IS 'remember=记录写入,undo=撤回某个批次';
94
+ COMMENT ON COLUMN public.vault_batches.agent IS '调用的 Agent 名称(如 codex、antigravity、workbuddy),可空';
95
+ COMMENT ON COLUMN public.vault_batches.journal_id IS '本批保存的用户原话随笔 ID';
96
+ COMMENT ON COLUMN public.vault_batches.idempotency_key IS '可选幂等键:同键同内容重放返回原结果';
97
+ COMMENT ON COLUMN public.vault_batches.request_hash IS '规范请求的 SHA-256,用于判断同键内容是否一致';
98
+ COMMENT ON COLUMN public.vault_batches.result_json IS '首次执行的返回结果';
99
+ COMMENT ON COLUMN public.vault_batches.undoes IS 'undo 批次撤回的目标批次';
100
+ COMMENT ON COLUMN public.vault_batches.undone_by IS '本批已被哪个 undo 批次撤回';
101
+
102
+ -- 6. 结构变更日志:Agent 通过 Skill 做的建表、加字段、建视图都记一行,供撤回与"同步数据库结构到代码"。
103
+ CREATE TABLE public.schema_changes (
104
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
105
+ batch_id text NOT NULL REFERENCES public.vault_batches(id),
106
+ kind text NOT NULL CHECK (kind IN ('create_table', 'add_column', 'create_view', 'replace_view', 'create_index')),
107
+ object_name text NOT NULL,
108
+ column_name text,
109
+ statement text NOT NULL,
110
+ previous_definition text,
111
+ created_at text NOT NULL DEFAULT public.vault_now_text(),
112
+ created_by text NOT NULL DEFAULT public.vault_current_actor()
113
+ );
114
+ COMMENT ON TABLE public.schema_changes IS 'Agent 经 Skill 做的结构变更日志(数据库是结构权威,同步代码时按此对照)';
115
+ COMMENT ON COLUMN public.schema_changes.kind IS 'create_table/add_column/create_view/replace_view/create_index';
116
+ COMMENT ON COLUMN public.schema_changes.object_name IS '对象名(public 下)';
117
+ COMMENT ON COLUMN public.schema_changes.column_name IS 'add_column 时的列名';
118
+ COMMENT ON COLUMN public.schema_changes.statement IS 'Agent 提交的原始语句';
119
+ COMMENT ON COLUMN public.schema_changes.previous_definition IS 'replace_view 时被替换前的视图定义,撤回时恢复';
120
+
121
+ -- 表的自增/序列列授权:能读 persons 的角色可读序列(逐表逻辑导出要读取每个序列的状态),
122
+ -- 能写 persons 的角色可取号(网页或应用角色向新表插入时需要)。不在迁移里写死角色名。
123
+ CREATE OR REPLACE FUNCTION public.vault_grant_skill_sequences(rel regclass) RETURNS void LANGUAGE plpgsql AS $$
124
+ DECLARE g record; s record;
125
+ BEGIN
126
+ FOR s IN SELECT pg_get_serial_sequence(rel::text, a.attname) AS seq
127
+ FROM pg_attribute a WHERE a.attrelid = rel AND a.attnum > 0 AND NOT a.attisdropped
128
+ LOOP
129
+ CONTINUE WHEN s.seq IS NULL;
130
+ FOR g IN SELECT DISTINCT r.rolname, a.privilege_type
131
+ FROM pg_class c CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a
132
+ JOIN pg_roles r ON r.oid = a.grantee
133
+ WHERE c.oid = 'public.persons'::regclass AND a.grantee <> c.relowner AND a.privilege_type IN ('SELECT', 'INSERT')
134
+ LOOP
135
+ EXECUTE format('GRANT %s ON SEQUENCE %s TO %I',
136
+ CASE g.privilege_type WHEN 'SELECT' THEN 'SELECT' ELSE 'USAGE' END, s.seq, g.rolname);
137
+ END LOOP;
138
+ END LOOP;
139
+ END $$;
140
+ COMMENT ON FUNCTION public.vault_grant_skill_sequences(regclass) IS '按 persons 授权给表的序列:只读角色 SELECT,可写角色 USAGE';
141
+
142
+ DO $$ DECLARE tbl text; g record; BEGIN
143
+ FOREACH tbl IN ARRAY ARRAY['vault_batches', 'schema_changes'] LOOP
144
+ EXECUTE format('CREATE TRIGGER trg_%1$s_guard BEFORE INSERT OR UPDATE OR DELETE ON public.%1$I FOR EACH ROW EXECUTE FUNCTION public.vault_guard(''session'')', tbl);
145
+ EXECUTE format('CREATE TRIGGER trg_%1$s_truncate BEFORE TRUNCATE ON public.%1$I FOR EACH STATEMENT EXECUTE FUNCTION public.vault_guard(''session'')', tbl);
146
+ EXECUTE format('CREATE TRIGGER trg_%1$s_audit AFTER INSERT OR UPDATE OR DELETE ON public.%1$I FOR EACH ROW EXECUTE FUNCTION public.vault_audit(''id'')', tbl);
147
+ EXECUTE format('CREATE TRIGGER trg_%1$s_version AFTER INSERT OR UPDATE OR DELETE ON public.%1$I FOR EACH STATEMENT EXECUTE FUNCTION public.vault_touch()', tbl);
148
+ EXECUTE format('REVOKE ALL ON public.%I FROM PUBLIC', tbl);
149
+ FOR g IN SELECT DISTINCT r.rolname, a.privilege_type
150
+ FROM pg_class c CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a
151
+ JOIN pg_roles r ON r.oid = a.grantee
152
+ WHERE c.oid = 'public.persons'::regclass AND a.grantee <> c.relowner AND a.privilege_type IN ('SELECT', 'INSERT', 'UPDATE')
153
+ LOOP
154
+ EXECUTE format('GRANT %s ON public.%I TO %I', g.privilege_type, tbl, g.rolname);
155
+ END LOOP;
156
+ PERFORM public.vault_grant_skill_sequences(format('public.%I', tbl)::regclass);
157
+ END LOOP;
158
+ END $$;
159
+
160
+ -- 7. Agent 新建表的注册:与核心表一致的写会话保护、TRUNCATE 拒绝、逐行审计(按真实主键)、版本号与授权。
161
+ -- 授权照抄 persons(只读角色 SELECT、应用角色可写),不在迁移里写死角色名。
162
+ CREATE OR REPLACE FUNCTION public.vault_register_skill_table(tbl text) RETURNS void LANGUAGE plpgsql AS $$
163
+ DECLARE rel regclass := format('public.%I', tbl)::regclass; keys text; g record;
164
+ BEGIN
165
+ SELECT string_agg(quote_literal(a.attname), ',' ORDER BY k.ord) INTO keys
166
+ FROM pg_index i
167
+ CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
168
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
169
+ WHERE i.indrelid = rel AND i.indisprimary;
170
+ IF keys IS NULL THEN RAISE EXCEPTION '新表 % 必须定义主键(撤回与审计按主键定位行)', tbl; END IF;
171
+ EXECUTE format('CREATE TRIGGER %I BEFORE INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION public.vault_guard(''session'')', left('trg_' || tbl, 57) || '_guard', rel);
172
+ EXECUTE format('CREATE TRIGGER %I BEFORE TRUNCATE ON %s FOR EACH STATEMENT EXECUTE FUNCTION public.vault_guard(''session'')', left('trg_' || tbl, 57) || '_trunc', rel);
173
+ EXECUTE format('CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION public.vault_audit(%s)', left('trg_' || tbl, 57) || '_audit', rel, keys);
174
+ EXECUTE format('CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH STATEMENT EXECUTE FUNCTION public.vault_touch()', left('trg_' || tbl, 57) || '_ver', rel);
175
+ EXECUTE format('REVOKE ALL ON %s FROM PUBLIC', rel);
176
+ FOR g IN SELECT DISTINCT r.rolname, a.privilege_type
177
+ FROM pg_class c CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a
178
+ JOIN pg_roles r ON r.oid = a.grantee
179
+ WHERE c.oid = 'public.persons'::regclass AND a.grantee <> c.relowner
180
+ AND a.privilege_type IN ('SELECT', 'INSERT', 'UPDATE', 'DELETE')
181
+ LOOP
182
+ EXECUTE format('GRANT %s ON %s TO %I', g.privilege_type, rel, g.rolname);
183
+ END LOOP;
184
+ PERFORM public.vault_grant_skill_sequences(rel);
185
+ END $$;
186
+ COMMENT ON FUNCTION public.vault_register_skill_table(text) IS 'Agent 新建表后调用:挂写会话保护、审计、版本触发器并按 persons 授权';
187
+
188
+ -- 新视图只读:按 persons 的 SELECT 授权给只读与应用角色。
189
+ CREATE OR REPLACE FUNCTION public.vault_register_skill_view(view_name text) RETURNS void LANGUAGE plpgsql AS $$
190
+ DECLARE rel regclass := format('public.%I', view_name)::regclass; g record;
191
+ BEGIN
192
+ FOR g IN SELECT DISTINCT r.rolname
193
+ FROM pg_class c CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a
194
+ JOIN pg_roles r ON r.oid = a.grantee
195
+ WHERE c.oid = 'public.persons'::regclass AND a.grantee <> c.relowner AND a.privilege_type = 'SELECT'
196
+ LOOP
197
+ EXECUTE format('GRANT SELECT ON %s TO %I', rel, g.rolname);
198
+ END LOOP;
199
+ END $$;
200
+ COMMENT ON FUNCTION public.vault_register_skill_view(text) IS 'Agent 新建或替换视图后调用:按 persons 授予 SELECT';
201
+
202
+ -- 8. 核心表与常用视图中文注释:Agent 通过 context 读取。已有注释不覆盖。
203
+ DO $$ DECLARE item record; BEGIN
204
+ FOR item IN SELECT * FROM (VALUES
205
+ ('persons', '人物档案:本人(is_self=1)、伴侣、家人、朋友等;软删除看 deleted_at'),
206
+ ('person_aliases', '人物别名/昵称;主键(person_id, alias),for_transcript=1 用于录音转写识别'),
207
+ ('profile_facts', '人物属性事实(某人·属性·值),如鞋码、血型、住址;valid_from/valid_to 保存历史值,值变化时给旧行填结束日期再插新行'),
208
+ ('preferences', '人物喜好与忌口;同一人+domain+item 只有一行有效记录(ux_preferences),重复提及用 upsert 更新'),
209
+ ('events', '事件与共同经历(见面、旅行、约会、冲突、里程碑等);参与人在 event_participants'),
210
+ ('event_participants', '事件参与人;主键(event_id, person_id, role)'),
211
+ ('event_links', '事件关联的订单、支付、聊天等来源'),
212
+ ('important_dates', '重要日期:生日、纪念日、忌日等,支持公历/农历和每年重复'),
213
+ ('wishes', '心愿清单:某人想要/想做的事,wish_state 记录进展'),
214
+ ('gift_ideas', '礼物想法与送礼记录'),
215
+ ('promises', '承诺:谁对谁承诺了什么、期限与兑现状态'),
216
+ ('promise_checks', '承诺的检查与兑现记录'),
217
+ ('todos', '待办事项'),
218
+ ('health_events', '健康事件:症状、疾病、用药、体检、检测结果等'),
219
+ ('relations', '人物之间的关系(伴侣、家人、朋友、同事等)'),
220
+ ('families', '家庭/家族分组'),
221
+ ('family_members', '家庭成员'),
222
+ ('identities', '外部身份到人物的映射:微信号、手机号、收件人、交易对方等'),
223
+ ('labels', '通用标签:分类、隐藏、敏感等级、话题、情绪等,target_type+target_key 指向被标记对象'),
224
+ ('journal_entries', '随笔与用户原话:Skill 每次"记一下"先存原话于此(origin=skill)'),
225
+ ('evidence_links', '证据链:业务记录(subject_table+subject_id)对应的来源(随笔、消息、订单等)'),
226
+ ('intimacy_events', '亲密记录'),
227
+ ('menstrual_cycles', '经期周期记录'),
228
+ ('menstrual_daily_logs', '经期每日记录'),
229
+ ('private_profiles', '人物私密档案(证件等扩展信息)'),
230
+ ('wechat_sessions', '微信会话(导入)'),
231
+ ('wechat_messages', '微信聊天消息原文(导入,只允许导入程序修改)'),
232
+ ('audio_records', '录音文件记录(导入)'),
233
+ ('audio_sentences', '录音转写逐句文本(导入)'),
234
+ ('audio_summaries', '录音纪要摘要(导入)'),
235
+ ('orders', '电商/外卖等平台订单(导入);主键(platform, order_no),金额为整数分'),
236
+ ('order_items', '订单商品行(导入);主键(platform, order_no, line_no)'),
237
+ ('payments', '支付宝/微信等支付账单(导入);主键(platform, txn_id),金额为整数分'),
238
+ ('payment_order_links', '支付与订单的匹配关系(导入后规则生成)'),
239
+ ('train_tickets', '火车票记录(导入)'),
240
+ ('beneficiaries', '消费受益人分配:某笔订单/支付是为谁花的'),
241
+ ('bank_cards', '银行卡与信用卡档案'),
242
+ ('bank_document_records', '银行账单统一明细(各银行导入后归一)'),
243
+ ('import_batches', '导入批次'),
244
+ ('import_files', '导入原件登记(只增)'),
245
+ ('import_changes', '导入变更明细(只增)'),
246
+ ('search_docs', '全文检索索引:聊天、随笔、录音、订单、Wiki 等的检索文本'),
247
+ ('wiki_pages', 'Wiki 页面当前版本(Markdown 正文)'),
248
+ ('wiki_revisions', 'Wiki 页面历史版本(只增)'),
249
+ ('audit_log', '逐行审计日志(只增):change_set=批次 ID,before_json/after_json 为前后值'),
250
+ ('settings', '系统设置键值'),
251
+ ('spending_places', '消费地点与场所'),
252
+ ('merchant_profiles', '商户识别规则与默认消费场景'),
253
+ ('ext_takeout_orders', '外卖订单细分'),
254
+ ('ext_voucher_orders', '团购/到店券订单细分'),
255
+ ('ext_parcel_orders', '电商包裹订单细分'),
256
+ ('ext_parking_orders', '停车与路桥订单细分')
257
+ ) AS t(name, note)
258
+ LOOP
259
+ IF to_regclass('public.' || item.name) IS NOT NULL
260
+ AND obj_description(('public.' || item.name)::regclass, 'pg_class') IS NULL THEN
261
+ EXECUTE format('COMMENT ON TABLE public.%I IS %L', item.name, item.note);
262
+ END IF;
263
+ END LOOP;
264
+
265
+ FOR item IN SELECT * FROM (VALUES
266
+ ('v_spending', '去重后的消费明细(订单商品行分摊 + 无可信订单关联的支付);已排除隐藏、火车票、退款、转账、非正金额;金额整数分'),
267
+ ('v_me_spending_monthly', '按月、平台、分类汇总的本人消费;amount_cents 只含已确认部分,待确认金额在 pending_candidate_cents'),
268
+ ('v_payments', '支付账单视图(含方向、退款、转账标记)'),
269
+ ('v_persons_current', '当前有效人物(排除软删除)'),
270
+ ('v_her_preferences', '默认伴侣的喜好清单'),
271
+ ('v_her_profile', '默认伴侣的档案汇总'),
272
+ ('v_her_wishes_open', '默认伴侣未完成的心愿'),
273
+ ('v_messages', '微信消息统一视图'),
274
+ ('v_utterances', '聊天与录音的统一发言视图'),
275
+ ('v_timeline', '全部人物的时间线(事件、日期、记录等)'),
276
+ ('v_us_timeline', '我和默认伴侣的共同时间线'),
277
+ ('v_us_interaction_daily', '我和默认伴侣的每日互动统计'),
278
+ ('v_us_meetups', '我和默认伴侣的见面记录'),
279
+ ('v_meet_days', '见面日期'),
280
+ ('v_upcoming_dates', '即将到来的重要日期(生日、纪念日等)'),
281
+ ('v_money_flow', '人物之间的资金往来'),
282
+ ('v_us_money_flow', '我和默认伴侣之间的资金往来'),
283
+ ('v_us_spending_by_beneficiary', '按受益人统计的消费'),
284
+ ('v_us_spending_unassigned', '尚未分配受益人的消费'),
285
+ ('v_us_gifts', '我和默认伴侣之间的礼物'),
286
+ ('v_us_conflicts', '我和默认伴侣的冲突记录'),
287
+ ('v_promises', '全部承诺'),
288
+ ('v_me_promises', '本人相关承诺'),
289
+ ('v_cycles', '经期周期视图'),
290
+ ('v_intimacy', '亲密记录视图'),
291
+ ('v_cross_platform_orders', '跨平台订单全链路(订单-支付-银行卡)'),
292
+ ('v_typed_orders_explorer', '按业务类型(外卖/团购/包裹/停车)浏览订单'),
293
+ ('v_spending_by_location', '按消费地点汇总'),
294
+ ('v_spending_by_scene', '按消费场景汇总'),
295
+ ('q_spending_monthly', '具名查询:每月消费'),
296
+ ('q_upcoming_dates', '具名查询:近期重要日期'),
297
+ ('q_wishes_open', '具名查询:未完成心愿数'),
298
+ ('q_promises_open', '具名查询:未兑现承诺数'),
299
+ ('q_days_together', '具名查询:在一起天数'),
300
+ ('q_meet_days_total', '具名查询:见面总天数'),
301
+ ('q_meetups_total', '具名查询:见面总次数'),
302
+ ('q_last_meet_on', '具名查询:最近一次见面日期'),
303
+ ('q_next_meetup_on', '具名查询:下一次见面日期'),
304
+ ('q_first_meet_on', '具名查询:第一次见面日期'),
305
+ ('q_gifts_given_total', '具名查询:送礼总数'),
306
+ ('q_conflicts_total', '具名查询:冲突总数'),
307
+ ('q_money_received_total', '具名查询:收到的钱总额'),
308
+ ('q_money_sent_total', '具名查询:转出的钱总额'),
309
+ ('q_spend_on_her_total', '具名查询:为伴侣花费总额'),
310
+ ('q_spend_on_her_yearly', '具名查询:每年为伴侣花费'),
311
+ ('q_interaction_daily', '具名查询:每日互动')
312
+ ) AS t(name, note)
313
+ LOOP
314
+ IF to_regclass('public.' || item.name) IS NOT NULL
315
+ AND obj_description(('public.' || item.name)::regclass, 'pg_class') IS NULL THEN
316
+ EXECUTE format('COMMENT ON VIEW public.%I IS %L', item.name, item.note);
317
+ END IF;
318
+ END LOOP;
319
+
320
+ -- 各银行原始流水表名称形如 <银行>_bank_transactions / <银行>_credit_card_transactions,统一给出说明。
321
+ FOR item IN SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
322
+ WHERE n.nspname = 'public' AND c.relkind = 'r'
323
+ AND (c.relname LIKE '%\_bank\_transactions' OR c.relname LIKE '%\_credit\_card\_transactions'
324
+ OR c.relname LIKE '%\_bank\_statements' OR c.relname LIKE '%credit\_card\_statements')
325
+ AND obj_description(c.oid, 'pg_class') IS NULL
326
+ LOOP
327
+ EXECUTE format('COMMENT ON TABLE public.%I IS %L', item.name,
328
+ '银行原始导入(' || item.name || ');统一口径请优先用 bank_document_records 或 v_spending');
329
+ END LOOP;
330
+ END $$;