luckytri 1.0.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 (235) hide show
  1. package/.github/SECURITY.md +71 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +250 -0
  4. package/README.md +250 -0
  5. package/bin/luckytri.js +107 -0
  6. package/docs/brand/banner.png +0 -0
  7. package/docs/brand/palette.png +0 -0
  8. package/docs/brand/portrait.png +0 -0
  9. package/docs/en/CHANGELOG.md +113 -0
  10. package/docs/en/architecture.md +152 -0
  11. package/docs/en/chat-style.md +62 -0
  12. package/docs/en/connect.md +63 -0
  13. package/docs/en/guide.md +216 -0
  14. package/docs/en/her-life.md +189 -0
  15. package/docs/en/npm-release.md +25 -0
  16. package/docs/en/plugins.md +82 -0
  17. package/docs/en/recovery.md +28 -0
  18. package/docs/en/time.md +71 -0
  19. package/docs/en/webui.md +73 -0
  20. package/docs/zh/CHANGELOG.md +113 -0
  21. package/docs/zh/architecture.md +152 -0
  22. package/docs/zh/chat-style.md +62 -0
  23. package/docs/zh/connect.md +63 -0
  24. package/docs/zh/guide.md +216 -0
  25. package/docs/zh/her-life.md +189 -0
  26. package/docs/zh/npm-release.md +33 -0
  27. package/docs/zh/plugins.md +82 -0
  28. package/docs/zh/recovery.md +28 -0
  29. package/docs/zh/time.md +71 -0
  30. package/docs/zh/webui.md +73 -0
  31. package/package.json +108 -0
  32. package/plugins/sdk/index.d.ts +155 -0
  33. package/plugins/sdk/testing.js +58 -0
  34. package/plugins/weather/index.js +82 -0
  35. package/plugins/weather/luckytri-plugin.json +29 -0
  36. package/public/app/assets/ChatsPage-C-FcRapR.js +3 -0
  37. package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
  38. package/public/app/assets/Empty-CpP5kQHH.js +2 -0
  39. package/public/app/assets/Empty-DmUB2-Bk.css +1 -0
  40. package/public/app/assets/Field-D4gY-INU.js +1 -0
  41. package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
  42. package/public/app/assets/HeartPage-CPy_thQd.js +1 -0
  43. package/public/app/assets/LifePage-BUi5euBF.css +1 -0
  44. package/public/app/assets/LifePage-CxWvwmSf.js +1 -0
  45. package/public/app/assets/MemoryPage-DC4rhQ68.js +1 -0
  46. package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
  47. package/public/app/assets/NaturePage-CTXHCE2D.css +1 -0
  48. package/public/app/assets/NaturePage-IvYw04Zq.js +3 -0
  49. package/public/app/assets/PeoplePage-BmUxkrOU.css +1 -0
  50. package/public/app/assets/PeoplePage-Cqefm9-q.js +1 -0
  51. package/public/app/assets/PluginsPage-DKSaKvXb.js +2 -0
  52. package/public/app/assets/PluginsPage-HyBe5D8w.css +1 -0
  53. package/public/app/assets/SystemPage-CAMPoYqM.css +1 -0
  54. package/public/app/assets/SystemPage-CJmtJkrK.js +1 -0
  55. package/public/app/assets/TimePage-BOms_n4I.css +1 -0
  56. package/public/app/assets/TimePage-Cw44inM4.js +3 -0
  57. package/public/app/assets/formatters-ZmW_xFHw.js +1 -0
  58. package/public/app/assets/index-BheRW-1t.js +4 -0
  59. package/public/app/assets/index-YDz1ree1.css +1 -0
  60. package/public/app/assets/knowledge-DG0e0uKw.js +1 -0
  61. package/public/app/assets/liquid-garden-IMoHBwzc.png +0 -0
  62. package/public/app/assets/luckytri-home-95QKeMtc.png +0 -0
  63. package/public/app/assets/media-BzPDBm7e.js +1 -0
  64. package/public/app/index.html +27 -0
  65. package/public/guide.en.html +1053 -0
  66. package/public/guide.html +893 -0
  67. package/public/plugin-kit/v1/bridge.js +30 -0
  68. package/public/plugin-kit/v1/kit.css +14 -0
  69. package/public/tutorial.en.md +214 -0
  70. package/public/tutorial.md +214 -0
  71. package/scripts/backup.js +311 -0
  72. package/scripts/browser.js +41 -0
  73. package/scripts/launch.js +94 -0
  74. package/scripts/plugin.js +150 -0
  75. package/scripts/proxy-config.js +167 -0
  76. package/scripts/recover.js +26 -0
  77. package/scripts/runtime.js +25 -0
  78. package/scripts/service.js +47 -0
  79. package/scripts/setup.js +50 -0
  80. package/scripts/start-server.js +41 -0
  81. package/scripts/stop.js +36 -0
  82. package/server/app.js +96 -0
  83. package/server/channels/adapters.js +27 -0
  84. package/server/channels/contract.js +57 -0
  85. package/server/channels/hub.js +165 -0
  86. package/server/channels/index.js +25 -0
  87. package/server/channels/onebot/adapter.js +288 -0
  88. package/server/channels/onebot/index.js +336 -0
  89. package/server/channels/onebot/token.js +3 -0
  90. package/server/channels/qqbot/adapter.js +253 -0
  91. package/server/channels/qqbot/api.js +199 -0
  92. package/server/channels/qqbot/credentials.js +11 -0
  93. package/server/channels/qqbot/gateway.js +274 -0
  94. package/server/channels/qqbot/index.js +389 -0
  95. package/server/channels/segments.js +40 -0
  96. package/server/channels/session-key.js +153 -0
  97. package/server/channels/state.js +42 -0
  98. package/server/core/api.js +564 -0
  99. package/server/core/capabilities.js +208 -0
  100. package/server/core/context-builder.js +288 -0
  101. package/server/core/context-compactor.js +454 -0
  102. package/server/core/conversation-cues.js +325 -0
  103. package/server/core/conversation-manager.js +87 -0
  104. package/server/core/events.js +60 -0
  105. package/server/core/feedback.js +8 -0
  106. package/server/core/group-style.js +72 -0
  107. package/server/core/image-preprocessor.js +208 -0
  108. package/server/core/initiative-context.js +66 -0
  109. package/server/core/input-budget.js +32 -0
  110. package/server/core/local-demo.js +98 -0
  111. package/server/core/message-manager.js +118 -0
  112. package/server/core/message-scheduler.js +78 -0
  113. package/server/core/model-json.js +190 -0
  114. package/server/core/model-manager.js +1213 -0
  115. package/server/core/model-presets.js +900 -0
  116. package/server/core/name-call.js +29 -0
  117. package/server/core/net-guard.js +49 -0
  118. package/server/core/network.js +157 -0
  119. package/server/core/orchestrator.js +569 -0
  120. package/server/core/perceivers.js +91 -0
  121. package/server/core/person-name.js +22 -0
  122. package/server/core/persona-manager.js +243 -0
  123. package/server/core/reply-delivery.js +393 -0
  124. package/server/core/reply-target-resolver.js +50 -0
  125. package/server/core/repository.js +293 -0
  126. package/server/core/response-generator.js +50 -0
  127. package/server/core/response-validator.js +508 -0
  128. package/server/core/retired-prompts.js +51 -0
  129. package/server/core/sessions.js +109 -0
  130. package/server/core/speaker-names.js +92 -0
  131. package/server/core/topic-tracker.js +65 -0
  132. package/server/core/turn-processor.js +630 -0
  133. package/server/core/turn.js +236 -0
  134. package/server/core/vision-manager.js +633 -0
  135. package/server/http.js +18 -0
  136. package/server/i18n/decisions.js +206 -0
  137. package/server/i18n/errors.js +497 -0
  138. package/server/i18n/index.js +144 -0
  139. package/server/i18n/labels.js +653 -0
  140. package/server/i18n/models.js +111 -0
  141. package/server/index.js +102 -0
  142. package/server/knowledge/api.js +342 -0
  143. package/server/knowledge/embedding-profile.js +114 -0
  144. package/server/knowledge/index.js +13 -0
  145. package/server/knowledge/manager.js +386 -0
  146. package/server/knowledge/retrieval.js +93 -0
  147. package/server/knowledge/schema.js +154 -0
  148. package/server/knowledge/vector-index.js +90 -0
  149. package/server/mind/affect.js +265 -0
  150. package/server/mind/anticipations.js +507 -0
  151. package/server/mind/api.js +703 -0
  152. package/server/mind/attention.js +200 -0
  153. package/server/mind/bonds.js +558 -0
  154. package/server/mind/budget.js +152 -0
  155. package/server/mind/clock.js +83 -0
  156. package/server/mind/context-selection.js +61 -0
  157. package/server/mind/continuity.js +562 -0
  158. package/server/mind/conversation-origin.js +175 -0
  159. package/server/mind/day-planner.js +324 -0
  160. package/server/mind/days.js +210 -0
  161. package/server/mind/evidence-read.js +45 -0
  162. package/server/mind/evidence.js +148 -0
  163. package/server/mind/faces.js +138 -0
  164. package/server/mind/guard.js +60 -0
  165. package/server/mind/index.js +445 -0
  166. package/server/mind/initiative.js +333 -0
  167. package/server/mind/life/activities.js +21 -0
  168. package/server/mind/life/context.js +309 -0
  169. package/server/mind/life/diary.js +786 -0
  170. package/server/mind/life/growth.js +252 -0
  171. package/server/mind/life/index.js +1049 -0
  172. package/server/mind/life/presence.js +305 -0
  173. package/server/mind/meetings.js +1069 -0
  174. package/server/mind/memory-policy.js +48 -0
  175. package/server/mind/memory.js +888 -0
  176. package/server/mind/nature.js +262 -0
  177. package/server/mind/novelty.js +19 -0
  178. package/server/mind/observations.js +84 -0
  179. package/server/mind/own-day.js +324 -0
  180. package/server/mind/own-voice.js +318 -0
  181. package/server/mind/periods.js +118 -0
  182. package/server/mind/reading.js +120 -0
  183. package/server/mind/salience.js +201 -0
  184. package/server/mind/schema.js +562 -0
  185. package/server/mind/self.js +484 -0
  186. package/server/mind/senses.js +53 -0
  187. package/server/mind/thoughts.js +274 -0
  188. package/server/mind/time/activity-clock.js +196 -0
  189. package/server/mind/time/agenda.js +242 -0
  190. package/server/mind/time/api.js +200 -0
  191. package/server/mind/time/attention.js +34 -0
  192. package/server/mind/time/availability.js +69 -0
  193. package/server/mind/time/commitment-review.js +198 -0
  194. package/server/mind/time/delivery-links.js +130 -0
  195. package/server/mind/time/executor.js +512 -0
  196. package/server/mind/time/experiences.js +128 -0
  197. package/server/mind/time/games.js +562 -0
  198. package/server/mind/time/index.js +739 -0
  199. package/server/mind/time/intent.js +166 -0
  200. package/server/mind/time/kinds.js +171 -0
  201. package/server/mind/time/model-material.js +77 -0
  202. package/server/mind/time/plugin-activity.js +207 -0
  203. package/server/mind/time/presentation.js +51 -0
  204. package/server/mind/time/schedule.js +83 -0
  205. package/server/mind/time/schema.js +84 -0
  206. package/server/mind/time/search.js +383 -0
  207. package/server/mind/time/sharing.js +472 -0
  208. package/server/mind/time/task-links.js +311 -0
  209. package/server/mind/time/tasks.js +587 -0
  210. package/server/mind/time/works.js +432 -0
  211. package/server/mind/traits.js +191 -0
  212. package/server/mind/util.js +110 -0
  213. package/server/mind/view.js +273 -0
  214. package/server/paths.js +102 -0
  215. package/server/plugins/api.js +204 -0
  216. package/server/plugins/host.js +967 -0
  217. package/server/plugins/install.js +295 -0
  218. package/server/plugins/manifest.js +201 -0
  219. package/server/plugins/permissions.js +42 -0
  220. package/server/plugins/runner/guard.mjs +36 -0
  221. package/server/plugins/runner/worker.mjs +250 -0
  222. package/server/plugins/schema.js +91 -0
  223. package/server/plugins/zip.js +112 -0
  224. package/server/startup-lock.js +118 -0
  225. package/server/storage/archive.js +241 -0
  226. package/server/storage/backup-cleanup-worker.js +8 -0
  227. package/server/storage/backup-cleanup.js +414 -0
  228. package/server/storage/backup-lock.js +76 -0
  229. package/server/storage/backup-scheduler.js +131 -0
  230. package/server/storage/store.js +199 -0
  231. package/server/studio/display-names.js +138 -0
  232. package/server/studio/management.js +102 -0
  233. package/server/studio/readiness.js +190 -0
  234. package/server/studio/settings.js +236 -0
  235. package/server/version.js +10 -0
@@ -0,0 +1,432 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { evidence, hasCredential, parse, text } from "../util.js";
3
+ import { activityPresentation, gameText } from "./presentation.js";
4
+
5
+ const decode = (row) =>
6
+ row
7
+ ? {
8
+ ...activityPresentation(row),
9
+ sources: parse(row.sources, []),
10
+ bible: parse(row.bible, {}),
11
+ }
12
+ : null;
13
+ export class Works {
14
+ constructor(time) {
15
+ this.time = time;
16
+ this.db = time.db;
17
+ this.migrate();
18
+ this.linkLegacy();
19
+ }
20
+ linkLegacy() {
21
+ for (const row of this.db
22
+ .prepare(
23
+ "SELECT w.id,c.plan_id FROM mind_time_works w JOIN mind_creations c ON c.id=w.legacy_creation WHERE w.task_id IS NULL",
24
+ )
25
+ .all()) {
26
+ const task = this.db
27
+ .prepare(
28
+ "SELECT id FROM mind_time_tasks WHERE anticipation_id=? OR id=? ORDER BY created LIMIT 1",
29
+ )
30
+ .get(row.plan_id, row.plan_id);
31
+ if (!task) continue;
32
+ this.db
33
+ .prepare("UPDATE mind_time_works SET task_id=? WHERE id=?")
34
+ .run(task.id, row.id);
35
+ this.db
36
+ .prepare(
37
+ "UPDATE mind_time_tasks SET work_id=COALESCE(work_id,?) WHERE id=?",
38
+ )
39
+ .run(row.id, task.id);
40
+ }
41
+ }
42
+ migrate() {
43
+ for (const row of this.db
44
+ .prepare(
45
+ "SELECT * FROM mind_creations WHERE id NOT IN (SELECT legacy_creation FROM mind_time_works WHERE legacy_creation IS NOT NULL)",
46
+ )
47
+ .all()) {
48
+ const id = randomUUID();
49
+ this.db.exec("SAVEPOINT migrate_work");
50
+ try {
51
+ this.db
52
+ .prepare(
53
+ "INSERT INTO mind_time_works(id,created,updated,title,state,version,session_id,discretion,legacy_creation) VALUES (?,?,?,?,'complete',1,?,?,?)",
54
+ )
55
+ .run(
56
+ id,
57
+ row.created,
58
+ row.created,
59
+ row.title,
60
+ row.session_id,
61
+ row.discretion,
62
+ row.id,
63
+ );
64
+ this.db
65
+ .prepare(
66
+ "INSERT INTO mind_time_versions(id,work_id,version,created,title,content,sources,run_id) VALUES (?,?,1,?,?,?,?,?)",
67
+ )
68
+ .run(
69
+ randomUUID(),
70
+ id,
71
+ row.created,
72
+ row.title,
73
+ row.content,
74
+ row.sources,
75
+ row.run_id,
76
+ );
77
+ this.db.exec("RELEASE migrate_work");
78
+ } catch (error) {
79
+ this.db.exec("ROLLBACK TO migrate_work; RELEASE migrate_work");
80
+ throw error;
81
+ }
82
+ }
83
+ }
84
+ project(id) {
85
+ return decode(
86
+ this.db.prepare("SELECT * FROM mind_time_projects WHERE id=?").get(id),
87
+ );
88
+ }
89
+ projects({ limit = 30, offset = 0, q = "" } = {}) {
90
+ return this.db
91
+ .prepare(
92
+ "SELECT * FROM mind_time_projects WHERE title LIKE ? ORDER BY updated DESC LIMIT ? OFFSET ?",
93
+ )
94
+ .all(
95
+ "%" + text(q, 80) + "%",
96
+ Math.max(1, Math.min(100, Number(limit))),
97
+ Math.max(0, Number(offset)),
98
+ )
99
+ .map(decode);
100
+ }
101
+ ensureProject(task, now) {
102
+ if (task.project_id) return this.project(task.project_id);
103
+ const id = randomUUID();
104
+ this.db
105
+ .prepare(
106
+ "INSERT INTO mind_time_projects(id,created,updated,kind,title,why,session_id,discretion,sources,serial) VALUES (?,?,?,?,?,?,?,?,?,?)",
107
+ )
108
+ .run(
109
+ id,
110
+ now,
111
+ now,
112
+ task.activity,
113
+ task.title,
114
+ task.why,
115
+ task.session_id,
116
+ task.discretion,
117
+ JSON.stringify(task.sources),
118
+ /连载|续写|长篇|系列/.test(task.title) ? 1 : 0,
119
+ );
120
+ this.db
121
+ .prepare("UPDATE mind_time_tasks SET project_id=? WHERE id=?")
122
+ .run(id, task.id);
123
+ task.project_id = id;
124
+ return this.project(id);
125
+ }
126
+ list({ q = "", project = "", limit = 30, offset = 0 } = {}) {
127
+ return this.db
128
+ .prepare(
129
+ `SELECT w.*,COALESCE(p.kind,(SELECT kind FROM mind_creations WHERE id=w.legacy_creation)) kind,p.title project_title,v.summary,v.sources,length(v.content) characters FROM mind_time_works w LEFT JOIN mind_time_projects p ON p.id=w.project_id JOIN mind_time_versions v ON v.work_id=w.id AND v.version=w.version WHERE (w.title LIKE ? OR p.title LIKE ?) ${project ? "AND w.project_id=?" : ""} ORDER BY w.updated DESC LIMIT ? OFFSET ?`,
130
+ )
131
+ .all(
132
+ "%" + text(q, 80) + "%",
133
+ "%" + text(q, 80) + "%",
134
+ ...(project ? [project] : []),
135
+ Math.max(1, Math.min(100, Number(limit))),
136
+ Math.max(0, Number(offset)),
137
+ )
138
+ .map((row) =>
139
+ row.kind === "game"
140
+ ? {
141
+ ...row,
142
+ title: gameText(row.title),
143
+ summary: gameText(row.summary),
144
+ }
145
+ : row,
146
+ );
147
+ }
148
+ get(id, version) {
149
+ const work = this.db
150
+ .prepare("SELECT * FROM mind_time_works WHERE id=?")
151
+ .get(id);
152
+ if (!work) return null;
153
+ const v = this.db
154
+ .prepare("SELECT * FROM mind_time_versions WHERE work_id=? AND version=?")
155
+ .get(id, Number(version) || work.version);
156
+ const saved = v
157
+ ? this.db
158
+ .prepare(
159
+ "SELECT reason FROM mind_time_events WHERE kind='draft' AND json_extract(data,'$.workId')=? AND json_extract(data,'$.version')=? ORDER BY id DESC LIMIT 1",
160
+ )
161
+ .get(id, v.version)
162
+ : null;
163
+ return v
164
+ ? {
165
+ ...work,
166
+ ...v,
167
+ id: work.id,
168
+ versionId: v.id,
169
+ state: saved
170
+ ? saved.reason === "保存完成稿"
171
+ ? "complete"
172
+ : "draft"
173
+ : work.state,
174
+ sources: parse(v.sources, []),
175
+ provenance: parse(v.provenance, {}),
176
+ versions: this.db
177
+ .prepare(
178
+ "SELECT version,created,title,length(content) characters FROM mind_time_versions WHERE work_id=? ORDER BY version DESC",
179
+ )
180
+ .all(id),
181
+ }
182
+ : null;
183
+ }
184
+ context(task) {
185
+ const project = this.project(task.project_id);
186
+ if (!project) return {};
187
+ const work = task.checkpoint.workId
188
+ ? this.get(task.checkpoint.workId)
189
+ : null;
190
+ const chapters = this.list({ project: project.id, limit: 3 }).sort(
191
+ (a, b) => a.ordinal - b.ordinal,
192
+ );
193
+ return {
194
+ project: {
195
+ id: project.id,
196
+ title: project.title,
197
+ why: project.why,
198
+ bible: project.bible,
199
+ summary: project.summary,
200
+ serial: !!project.serial,
201
+ },
202
+ previous: chapters
203
+ .filter((w) => w.id !== work?.id)
204
+ .map((w) => ({
205
+ ordinal: w.ordinal,
206
+ title: w.title,
207
+ summary: w.summary,
208
+ ending: this.get(w.id)?.content.slice(-900),
209
+ })),
210
+ draft: work
211
+ ? {
212
+ title: work.title,
213
+ version: work.version,
214
+ summary: work.summary,
215
+ ending: work.content.slice(-1800),
216
+ }
217
+ : null,
218
+ };
219
+ }
220
+ save(task, result, { sources, runId, now, provenance = {} }) {
221
+ if (!this.time.valid(task)) throw Error("任务租约已经改变");
222
+ const title = text(result.title, 80),
223
+ segment = text(result.content, 1800);
224
+ if (!title || !segment || hasCredential(title + segment))
225
+ throw Error("作品正文格式无效");
226
+ const project = this.ensureProject(task, now),
227
+ existing = task.checkpoint.workId
228
+ ? this.get(task.checkpoint.workId)
229
+ : null;
230
+ const id = existing?.id || randomUUID(),
231
+ version = (existing?.version || 0) + 1;
232
+ const content =
233
+ task.checkpoint.intent === "revise"
234
+ ? segment
235
+ : (existing ? existing.content + "\n\n" : "") + segment;
236
+ if (content.length > 100000) throw Error("单篇过长,请接续新篇章");
237
+ const complete = result.done === true,
238
+ state = complete ? "complete" : "draft";
239
+ if (!existing) {
240
+ const ordinal = this.db
241
+ .prepare(
242
+ "SELECT COALESCE(MAX(ordinal),0)+1 n FROM mind_time_works WHERE project_id=?",
243
+ )
244
+ .get(project.id).n;
245
+ this.db
246
+ .prepare(
247
+ "INSERT INTO mind_time_works(id,created,updated,task_id,project_id,ordinal,title,state,version,session_id,discretion) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
248
+ )
249
+ .run(
250
+ id,
251
+ now,
252
+ now,
253
+ task.id,
254
+ project.id,
255
+ ordinal,
256
+ title,
257
+ state,
258
+ version,
259
+ task.session_id,
260
+ task.discretion,
261
+ );
262
+ } else
263
+ this.db
264
+ .prepare(
265
+ "UPDATE mind_time_works SET updated=?,title=?,state=?,version=? WHERE id=?",
266
+ )
267
+ .run(now, title, state, version, id);
268
+ const summary = text(result.summary || segment, 500),
269
+ checkpoint = {
270
+ ...task.checkpoint,
271
+ workId: id,
272
+ version,
273
+ summary,
274
+ next: text(result.next, 240) || "接着上一段往下写",
275
+ segments: (task.checkpoint.segments || 0) + 1,
276
+ };
277
+ this.db
278
+ .prepare(
279
+ "INSERT INTO mind_time_versions(id,work_id,version,created,title,content,summary,sources,run_id,provenance) VALUES (?,?,?,?,?,?,?,?,?,?)",
280
+ )
281
+ .run(
282
+ randomUUID(),
283
+ id,
284
+ version,
285
+ now,
286
+ title,
287
+ content,
288
+ summary,
289
+ JSON.stringify(evidence(sources)),
290
+ runId,
291
+ JSON.stringify(provenance),
292
+ );
293
+ // Only supplied continuity fields change; omitted fields never erase established settings.
294
+ const bible = { ...project.bible };
295
+ for (const key of ["characters", "world", "threads"])
296
+ if (result.bible?.[key] !== undefined)
297
+ bible[key] = text(
298
+ typeof result.bible[key] === "string"
299
+ ? result.bible[key]
300
+ : JSON.stringify(result.bible[key]),
301
+ 2000,
302
+ );
303
+ this.db
304
+ .prepare(
305
+ "UPDATE mind_time_projects SET updated=?,summary=?,bible=?,revision=revision+1 WHERE id=?",
306
+ )
307
+ .run(now, summary, JSON.stringify(bible), project.id);
308
+ this.db
309
+ .prepare("UPDATE mind_time_tasks SET checkpoint=?,work_id=? WHERE id=?")
310
+ .run(JSON.stringify(checkpoint), id, task.id);
311
+ this.time.event(
312
+ task.id,
313
+ "draft",
314
+ complete ? "保存完成稿" : "保存一个完整小段",
315
+ { workId: id, version, characters: content.length },
316
+ now,
317
+ );
318
+ return this.get(id);
319
+ }
320
+ settle(task, workId, complete, now) {
321
+ if (!this.time.valid(task)) throw Error("任务租约已经改变");
322
+ const work = this.get(workId);
323
+ if (!work || work.task_id !== task.id) throw Error("活动草稿已不可用");
324
+ if (complete) {
325
+ this.db
326
+ .prepare(
327
+ "UPDATE mind_time_works SET state='complete',updated=? WHERE id=?",
328
+ )
329
+ .run(now, workId);
330
+ this.time.event(
331
+ task.id,
332
+ "draft",
333
+ "保存完成稿",
334
+ { workId, version: work.version, characters: work.content.length },
335
+ now,
336
+ );
337
+ }
338
+ return this.get(workId);
339
+ }
340
+ suggest(
341
+ projectId,
342
+ { action = "continue", idea = "", why = "管理台提出的建议" } = {},
343
+ now = this.time.now(),
344
+ ) {
345
+ const project = this.project(projectId);
346
+ if (!project) throw Error("项目不存在");
347
+ if (
348
+ !["continue", "revise", "pause", "finish", "direction"].includes(action)
349
+ )
350
+ throw Error("建议类型无效");
351
+ const pending = this.db
352
+ .prepare(
353
+ "SELECT id FROM mind_time_tasks WHERE project_id=? AND state NOT IN ('done','abandoned') LIMIT 1",
354
+ )
355
+ .get(projectId);
356
+ if (pending) return { duplicate: pending.id };
357
+ const result = this.time.tasks.add(
358
+ {
359
+ kind: "suggestion",
360
+ activeOnly: true,
361
+ activity: project.kind,
362
+ title: `${action === "revise" ? "修改" : "接续"}《${project.title}》${text(idea, 120)}`,
363
+ why: text(why, 240),
364
+ sources: project.sources,
365
+ session: project.session_id,
366
+ discretion: project.discretion,
367
+ projectId,
368
+ },
369
+ now,
370
+ );
371
+ if (result.id) {
372
+ const latest = this.list({ project: projectId, limit: 1 })[0];
373
+ this.db.prepare("UPDATE mind_time_tasks SET checkpoint=? WHERE id=?").run(
374
+ JSON.stringify({
375
+ suggestion: {
376
+ action,
377
+ idea: text(idea, 500),
378
+ origin: "admin",
379
+ accepted: null,
380
+ },
381
+ ...(action === "revise" && latest
382
+ ? { workId: latest.id, intent: "revise" }
383
+ : {}),
384
+ }),
385
+ result.id,
386
+ );
387
+ this.time.event(
388
+ result.id,
389
+ "suggestion",
390
+ "外部建议,等待她决定是否采纳",
391
+ { action },
392
+ now,
393
+ );
394
+ }
395
+ return result;
396
+ }
397
+ fragments({ session, now = this.time.now(), cue = [] } = {}) {
398
+ const words = (Array.isArray(cue) ? cue : [cue])
399
+ .map((v) => (typeof v === "string" ? v : JSON.stringify(v)))
400
+ .join(" ");
401
+ return this.list({ limit: 30 })
402
+ .filter(
403
+ (w) =>
404
+ w.created <= now &&
405
+ this.time.visible(
406
+ { ...w, sources: parse(w.sources, []) },
407
+ session,
408
+ now,
409
+ ),
410
+ )
411
+ .map((w) => ({
412
+ ...w,
413
+ score: [...new Set(words.match(/[\p{L}\p{N}]{2,}/gu) || [])].filter(
414
+ (term) =>
415
+ (w.title + " " + w.project_title + " " + w.summary).includes(term),
416
+ ).length,
417
+ }))
418
+ .sort((a, b) => b.score - a.score || b.updated - a.updated)
419
+ .slice(0, 2)
420
+ .map((w) => ({
421
+ id: w.id,
422
+ title: w.title,
423
+ state: w.state,
424
+ kind: w.kind,
425
+ version: w.version,
426
+ ordinal: w.ordinal,
427
+ summary: text(w.summary, 180),
428
+ fragment: text(this.get(w.id).content, 240),
429
+ characters: w.characters,
430
+ }));
431
+ }
432
+ }
@@ -0,0 +1,191 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { evidenceRoots, externalEvidence } from "./evidence.js";
3
+ import { lifeDayStart } from "./nature.js";
4
+ import { evidence, hasCredential, similar, text } from "./util.js";
5
+
6
+ export const LIVED_TRAITS = [
7
+ "warmth",
8
+ "sarcasm",
9
+ "humor",
10
+ "activity",
11
+ "initiative",
12
+ ];
13
+ const TRAIT_HALF_LIFE = 180;
14
+ const DAILY_SHIFT_CAP = 4;
15
+ export function personaNeedsRephrase(content, mind) {
16
+ const value = String(content || "");
17
+ return (
18
+ value.length > 100 ||
19
+ /今天|昨天|明天|今晚|这几天|刚才|比如|下次|打完/.test(value) ||
20
+ !mind.meetings.sayable(value, "")
21
+ );
22
+ }
23
+
24
+ // Nature is the starting point. These small, cited changes are what she has
25
+ // actually learned about how she wants to show up; they belong to one self.
26
+ export class Traits {
27
+ constructor(mind) {
28
+ this.mind = mind;
29
+ this.db = mind.db;
30
+ }
31
+ current(nature = this.mind.nature.current(), before = Date.now()) {
32
+ const values = Object.fromEntries(
33
+ LIVED_TRAITS.map((key) => [key, Number(nature[key])]),
34
+ );
35
+ const rows = this.db
36
+ .prepare(
37
+ "SELECT trait,delta,created FROM mind_trait_changes WHERE nature_version=? AND created<=? ORDER BY created,rowid",
38
+ )
39
+ .all(nature.version, before);
40
+ const lived = this.mind.days.lived(before);
41
+ for (const row of rows) {
42
+ if (!LIVED_TRAITS.includes(row.trait)) continue;
43
+ values[row.trait] +=
44
+ row.delta * 0.5 ** (lived.since(row.created) / TRAIT_HALF_LIFE);
45
+ }
46
+ for (const trait of LIVED_TRAITS)
47
+ values[trait] = Math.max(0, Math.min(100, Math.round(values[trait])));
48
+ return values;
49
+ }
50
+ effective(nature = this.mind.nature.current(), before = Date.now()) {
51
+ const persona = this.persona(nature, before);
52
+ return {
53
+ ...nature,
54
+ ...this.current(nature, before),
55
+ ...(persona ? { livedPersona: persona.content } : {}),
56
+ };
57
+ }
58
+ persona(nature = this.mind.nature.current(), before = Date.now()) {
59
+ return (
60
+ this.db
61
+ .prepare(
62
+ "SELECT * FROM mind_persona_growth WHERE nature_version=? AND created<=? ORDER BY created DESC,rowid DESC LIMIT 1",
63
+ )
64
+ .get(nature.version, before) || null
65
+ );
66
+ }
67
+ personaHistory(limit = 15) {
68
+ return this.db
69
+ .prepare(
70
+ "SELECT * FROM mind_persona_growth ORDER BY created DESC,rowid DESC LIMIT ?",
71
+ )
72
+ .all(limit)
73
+ .map((row) => ({ ...row, sources: JSON.parse(row.sources) }));
74
+ }
75
+ proposePersona(
76
+ input,
77
+ { valid, origin = "solitude", time = Date.now() } = {},
78
+ ) {
79
+ const content = text(input?.content, 240);
80
+ if (
81
+ content.length < 12 ||
82
+ hasCredential(content) ||
83
+ personaNeedsRephrase(content, this.mind)
84
+ )
85
+ return { rejected: "不适合长期自述或含私下内容" };
86
+ const sources = evidence(input?.sources).filter(
87
+ (s) => !valid || valid.has(s),
88
+ );
89
+ if (!sources.length) return { rejected: "缺少亲历来源" };
90
+ const nature = this.mind.nature.current(time);
91
+ const previous = this.persona(nature, time);
92
+ const correcting =
93
+ previous && personaNeedsRephrase(previous.content, this.mind);
94
+ const grounded = externalEvidence(this.db, sources, time);
95
+ if (!correcting && !grounded.length)
96
+ return { rejected: "自述需要模型之外的新经历" };
97
+ if (previous && similar(content, previous.content, 0.85))
98
+ return { rejected: "没有实质变化" };
99
+ const spent = new Set(
100
+ this.db
101
+ .prepare(
102
+ "SELECT sources FROM mind_persona_growth WHERE nature_version=? AND created<=?",
103
+ )
104
+ .all(nature.version, time)
105
+ .flatMap((row) =>
106
+ evidenceRoots(this.db, JSON.parse(row.sources), time),
107
+ ),
108
+ );
109
+ if (
110
+ previous &&
111
+ !personaNeedsRephrase(previous.content, this.mind) &&
112
+ !grounded.some((root) => !spent.has(root))
113
+ )
114
+ return { rejected: "没有新的亲历来源" };
115
+ const id = randomUUID();
116
+ this.db
117
+ .prepare(
118
+ "INSERT INTO mind_persona_growth(id,created,content,sources,origin,nature_version) VALUES (?,?,?,?,?,?)",
119
+ )
120
+ .run(id, time, content, JSON.stringify(sources), origin, nature.version);
121
+ return { id };
122
+ }
123
+ history(limit = 30) {
124
+ return this.db
125
+ .prepare(
126
+ "SELECT id,created,trait,value,delta,reason,sources,origin,nature_version FROM mind_trait_changes ORDER BY created DESC,rowid DESC LIMIT ?",
127
+ )
128
+ .all(limit)
129
+ .map((row) => ({ ...row, sources: JSON.parse(row.sources) }));
130
+ }
131
+ propose(input, { valid, origin = "solitude", time = Date.now() } = {}) {
132
+ const trait = String(input?.trait || "");
133
+ if (!LIVED_TRAITS.includes(trait)) return { rejected: "未知性格维度" };
134
+ const direction = Number(input?.direction);
135
+ if (!Number.isFinite(direction) || direction === 0)
136
+ return { rejected: "没有方向" };
137
+ const reason = text(input?.why, 180);
138
+ if (!reason || hasCredential(reason)) return { rejected: "缺少可用的理由" };
139
+ const sources = evidence(input?.sources).filter(
140
+ (s) => !valid || valid.has(s),
141
+ );
142
+ if (!sources.length) return { rejected: "缺少亲历来源" };
143
+ const nature = this.mind.nature.current(time);
144
+ const grounded = externalEvidence(this.db, sources, time);
145
+ if (!grounded.length) return { rejected: "性格变化需要模型之外的经历" };
146
+ const spent = new Set(
147
+ this.db
148
+ .prepare(
149
+ "SELECT sources FROM mind_trait_changes WHERE trait=? AND nature_version=?",
150
+ )
151
+ .all(trait, nature.version)
152
+ .flatMap((row) =>
153
+ evidenceRoots(this.db, JSON.parse(row.sources), time),
154
+ ),
155
+ );
156
+ if (!grounded.some((source) => !spent.has(source)))
157
+ return { rejected: "这段经历已经改变过它" };
158
+ const previous = this.current(nature, time)[trait];
159
+ const start = lifeDayStart(nature, time, this.mind.timeZone());
160
+ const used = this.db
161
+ .prepare(
162
+ "SELECT COALESCE(SUM(ABS(delta)),0) n FROM mind_trait_changes WHERE trait=? AND nature_version=? AND created>=? AND created<=?",
163
+ )
164
+ .get(trait, nature.version, start, time).n;
165
+ const allowance = Math.max(0, DAILY_SHIFT_CAP - used);
166
+ if (!allowance) return { rejected: "今天这项性格已经改变过,留些时间检验" };
167
+ // A single reflection may nudge a tendency, never replace her overnight.
168
+ const delta =
169
+ Math.sign(direction) *
170
+ Math.min(allowance, Math.max(1, Math.round(Math.abs(direction))));
171
+ const value = Math.max(0, Math.min(100, previous + delta));
172
+ if (value === previous) return { rejected: "已到边界" };
173
+ const id = randomUUID();
174
+ this.db
175
+ .prepare(
176
+ "INSERT INTO mind_trait_changes(id,created,trait,value,delta,reason,sources,origin,nature_version) VALUES (?,?,?,?,?,?,?,?,?)",
177
+ )
178
+ .run(
179
+ id,
180
+ time,
181
+ trait,
182
+ value,
183
+ value - previous,
184
+ reason,
185
+ JSON.stringify(sources),
186
+ origin,
187
+ nature.version,
188
+ );
189
+ return { id, value };
190
+ }
191
+ }