@audiofool/moondog 0.4.0-beta.2 → 0.4.0-beta.4
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.
- package/README.md +19 -8
- package/package.json +1 -1
- package/scripts/moondog.mjs +130 -106
- package/src/core/apple-library-source-status.mjs +64 -18
- package/src/core/apple-projection-domain-services.mjs +67 -52
- package/src/core/capability-catalog.mjs +18 -2
- package/src/core/import-source-history.mjs +28 -0
- package/src/core/library-draft.mjs +16 -0
- package/src/core/library-names.mjs +12 -0
- package/src/core/library-store.mjs +361 -23
- package/src/core/listener-avoids.mjs +31 -0
- package/src/core/listening-action.mjs +41 -0
- package/src/core/listening-moment.mjs +67 -0
- package/src/core/listening-now.mjs +69 -28
- package/src/core/listening-profile-domain-services.mjs +32 -18
- package/src/core/listening-scope.mjs +119 -0
- package/src/core/moondog-application.mjs +1045 -270
- package/src/core/play-follower.mjs +104 -0
- package/src/core/portable-playlist.mjs +125 -0
- package/src/core/profile-discovery-draft.mjs +35 -0
- package/src/core/track-title.mjs +70 -4
- package/src/i18n/import-history.mjs +647 -0
- package/src/i18n/messages/de.mjs +3 -3
- package/src/i18n/messages/en.mjs +3 -3
- package/src/i18n/messages/es.mjs +3 -3
- package/src/i18n/messages/fr.mjs +3 -3
- package/src/i18n/messages/it.mjs +3 -3
- package/src/i18n/messages/ja.mjs +3 -3
- package/src/i18n/messages/ko.mjs +3 -3
- package/src/i18n/messages/pt.mjs +3 -3
- package/src/i18n/messages/zh-Hant.mjs +3 -3
- package/src/i18n/messages/zh.mjs +3 -3
- package/src/i18n/screen/es.mjs +90 -26
- package/src/i18n/screen/ja.mjs +89 -25
- package/src/i18n/screen/pt.mjs +90 -26
- package/src/i18n/screen/zh.mjs +89 -25
- package/src/importers/apple-music-library/import-batch.mjs +64 -32
- package/src/importers/apple-music-library/normalize.mjs +36 -6
- package/src/importers/apple-music-library/save-time.mjs +17 -0
- package/src/importers/zip-reader.mjs +24 -2
- package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
- package/src/integrations/apple-music/catalog.mjs +84 -25
- package/src/integrations/apple-music/music-app-listening.mjs +107 -0
- package/src/integrations/apple-music/music-app.mjs +6 -2
- package/src/integrations/apple-music/song-id.mjs +13 -0
- package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
- package/src/integrations/listenbrainz/history-file.mjs +63 -35
- package/src/integrations/netease/ncm-cli-player.mjs +355 -68
- package/src/integrations/netease/queue-occurrence.mjs +138 -0
- package/src/integrations/playlist-links.mjs +93 -30
- package/src/integrations/public-playlists.mjs +21 -15
- package/src/integrations/spotify/account-data-history.mjs +9 -10
- package/src/integrations/spotify/account-data-profile.mjs +1 -0
- package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
- package/src/integrations/spotify/history-archive.mjs +8 -18
- package/src/integrations/spotify/library-snapshot.mjs +2 -1
- package/src/integrations/spotify/service.mjs +29 -11
- package/src/integrations/spotify/web-api-client.mjs +2 -2
- package/src/integrations/stable-audio/local-generator.mjs +13 -5
- package/src/integrations/youtube-music/takeout.mjs +12 -8
- package/src/memory/local-memory-store.mjs +479 -27
- package/src/memory/reflection-worker.mjs +19 -0
- package/src/profile/apple-library-import.mjs +56 -2
- package/src/profile/history-import.mjs +58 -27
- package/src/profile/listener-corrections.mjs +2 -4
- package/src/profile/listener-profile-build.mjs +133 -46
- package/src/profile/listener-profile-store.mjs +57 -4
- package/src/profile/listener-profile-verification.mjs +11 -5
- package/src/profile/listener-profile-worker.mjs +36 -10
- package/src/profile/listening-history-store.mjs +975 -354
- package/src/profile/listening-profile-projection.mjs +130 -160
- package/src/profile/local-file-import.mjs +172 -0
- package/src/profile/moondog-suggestions.mjs +40 -11
- package/src/profile/profile-exploration.mjs +36 -6
- package/src/profile/recorded-measures.mjs +5 -0
- package/src/profile/spotify-archive-taste.mjs +41 -65
- package/src/runtime/pi/agent-runtime.mjs +368 -221
- package/src/runtime/pi/custom-endpoints.mjs +30 -8
- package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
- package/src/runtime/pi/moondog-model.mjs +6 -0
- package/src/runtime/pi/playback-rules.mjs +100 -0
- package/src/runtime/pi/profile-build-runtime.mjs +85 -24
- package/src/surfaces/cli/brand-components.mjs +9 -6
- package/src/surfaces/cli/command-completions.mjs +8 -1
- package/src/surfaces/cli/format-output.mjs +207 -34
- package/src/surfaces/cli/history-import-view.mjs +130 -21
- package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
- package/src/surfaces/cli/listener-profile-command.mjs +67 -8
- package/src/surfaces/cli/listening-menu.mjs +3 -0
- package/src/surfaces/cli/profile-command.mjs +1 -0
- package/src/surfaces/cli/spotify-command.mjs +17 -25
- package/src/surfaces/cli/taste-period.mjs +22 -0
- package/src/surfaces/cli/taste-profile-model.mjs +52 -32
- package/src/surfaces/cli/tui.mjs +557 -170
- package/src/surfaces/html/tasteprint.mjs +181 -93
- package/src/surfaces/import-source-history.mjs +80 -0
|
@@ -2,8 +2,21 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { chmod, mkdir } from "node:fs/promises";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { restoreListeningMoment } from "../core/listening-moment.mjs";
|
|
5
6
|
|
|
6
7
|
export const MOONDOG_MEMORY_SCHEMA_VERSION = 3;
|
|
8
|
+
export const LISTENING_MOMENT_TTL_MS = 3 * 60 * 60 * 1_000;
|
|
9
|
+
|
|
10
|
+
export function unfinishedConversationReply(partial) {
|
|
11
|
+
const notice = "This turn did not finish. External actions may have occurred. Check their state before repeating them.";
|
|
12
|
+
return [partial, notice].filter(Boolean).join("\n\n");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function writerIsAlive(pid) {
|
|
16
|
+
try { process.kill(pid, 0); return true; }
|
|
17
|
+
catch (error) { return error.code !== "ESRCH"; }
|
|
18
|
+
}
|
|
19
|
+
|
|
7
20
|
export function resolveMoondogMemoryPath(environment = process.env) {
|
|
8
21
|
const configuredState = environment.MOONDOG_STATE_HOME?.trim();
|
|
9
22
|
if (configuredState) {
|
|
@@ -58,6 +71,7 @@ const reflectionTriggers = new Set([
|
|
|
58
71
|
const reflectionActions = new Set([
|
|
59
72
|
"candidate_memory",
|
|
60
73
|
"candidate_music_profile",
|
|
74
|
+
"candidate_skill",
|
|
61
75
|
"ignore",
|
|
62
76
|
]);
|
|
63
77
|
|
|
@@ -115,7 +129,39 @@ const schema = `
|
|
|
115
129
|
queued_json TEXT NOT NULL DEFAULT '[]'
|
|
116
130
|
) STRICT;
|
|
117
131
|
|
|
132
|
+
CREATE TABLE IF NOT EXISTS conversation_library_refs (
|
|
133
|
+
entry_id TEXT PRIMARY KEY NOT NULL REFERENCES conversation_entries(entry_id) ON DELETE CASCADE,
|
|
134
|
+
ref TEXT NOT NULL
|
|
135
|
+
) STRICT;
|
|
136
|
+
|
|
137
|
+
CREATE TABLE IF NOT EXISTS conversation_draft_tracks (
|
|
138
|
+
session_id TEXT PRIMARY KEY NOT NULL REFERENCES conversation_branches(session_id) ON DELETE CASCADE,
|
|
139
|
+
subject_id TEXT NOT NULL CHECK(length(subject_id) = 36),
|
|
140
|
+
title TEXT NOT NULL CHECK(length(title) BETWEEN 1 AND 512),
|
|
141
|
+
artist TEXT NOT NULL CHECK(length(artist) BETWEEN 1 AND 512)
|
|
142
|
+
) STRICT;
|
|
143
|
+
-- Older clients can still edit, send or rewind a draft. Such a write clears its optional selection.
|
|
144
|
+
CREATE TRIGGER IF NOT EXISTS clear_conversation_draft_track AFTER UPDATE OF draft ON conversation_branches
|
|
145
|
+
BEGIN DELETE FROM conversation_draft_tracks WHERE session_id = NEW.session_id; END;
|
|
146
|
+
|
|
147
|
+
CREATE TABLE IF NOT EXISTS conversation_draft_library (
|
|
148
|
+
session_id TEXT PRIMARY KEY NOT NULL REFERENCES conversation_branches(session_id) ON DELETE CASCADE,
|
|
149
|
+
ref TEXT NOT NULL CHECK(length(ref) BETWEEN 1 AND 2048),
|
|
150
|
+
label TEXT NOT NULL CHECK(length(label) BETWEEN 1 AND 1024)
|
|
151
|
+
) STRICT;
|
|
152
|
+
-- An older client can replace the queue while writing the same draft back. Keep its Library selection.
|
|
153
|
+
CREATE TRIGGER IF NOT EXISTS clear_conversation_draft_library AFTER UPDATE OF draft ON conversation_branches
|
|
154
|
+
WHEN OLD.draft <> NEW.draft OR OLD.queued_json = NEW.queued_json
|
|
155
|
+
BEGIN DELETE FROM conversation_draft_library WHERE session_id = NEW.session_id; END;
|
|
156
|
+
|
|
118
157
|
-- Additive tables keep the schema version, so older cores still open this database.
|
|
158
|
+
CREATE TABLE IF NOT EXISTS conversation_listening_moments (
|
|
159
|
+
entry_id TEXT PRIMARY KEY NOT NULL REFERENCES conversation_entries(entry_id) ON DELETE CASCADE,
|
|
160
|
+
expires_at TEXT NOT NULL,
|
|
161
|
+
snapshot_json TEXT NOT NULL
|
|
162
|
+
) STRICT;
|
|
163
|
+
CREATE INDEX IF NOT EXISTS conversation_listening_moments_expiry ON conversation_listening_moments(expires_at);
|
|
164
|
+
|
|
119
165
|
CREATE TABLE IF NOT EXISTS conversation_folders (
|
|
120
166
|
folder_id TEXT PRIMARY KEY NOT NULL,
|
|
121
167
|
name TEXT NOT NULL,
|
|
@@ -209,6 +255,41 @@ const schema = `
|
|
|
209
255
|
FOREIGN KEY (episode_id) REFERENCES episodes(episode_id)
|
|
210
256
|
) STRICT;
|
|
211
257
|
|
|
258
|
+
CREATE TABLE IF NOT EXISTS learned_skills (
|
|
259
|
+
name TEXT PRIMARY KEY NOT NULL,
|
|
260
|
+
description TEXT NOT NULL,
|
|
261
|
+
instructions TEXT NOT NULL,
|
|
262
|
+
status TEXT NOT NULL CHECK (status IN ('active', 'archived')),
|
|
263
|
+
origin TEXT NOT NULL,
|
|
264
|
+
revision INTEGER NOT NULL CHECK (revision >= 1),
|
|
265
|
+
created_at TEXT NOT NULL,
|
|
266
|
+
updated_at TEXT NOT NULL,
|
|
267
|
+
archived_at TEXT
|
|
268
|
+
) STRICT;
|
|
269
|
+
|
|
270
|
+
CREATE INDEX IF NOT EXISTS learned_skills_active
|
|
271
|
+
ON learned_skills(status, name);
|
|
272
|
+
|
|
273
|
+
CREATE TABLE IF NOT EXISTS learned_skill_revisions (
|
|
274
|
+
name TEXT NOT NULL,
|
|
275
|
+
revision INTEGER NOT NULL,
|
|
276
|
+
description TEXT NOT NULL,
|
|
277
|
+
instructions TEXT NOT NULL,
|
|
278
|
+
origin TEXT NOT NULL,
|
|
279
|
+
created_at TEXT NOT NULL,
|
|
280
|
+
PRIMARY KEY (name, revision),
|
|
281
|
+
FOREIGN KEY (name) REFERENCES learned_skills(name)
|
|
282
|
+
) STRICT;
|
|
283
|
+
|
|
284
|
+
CREATE TABLE IF NOT EXISTS learned_skill_episode_refs (
|
|
285
|
+
name TEXT NOT NULL,
|
|
286
|
+
episode_id TEXT NOT NULL,
|
|
287
|
+
created_at TEXT NOT NULL,
|
|
288
|
+
PRIMARY KEY (name, episode_id),
|
|
289
|
+
FOREIGN KEY (name) REFERENCES learned_skills(name),
|
|
290
|
+
FOREIGN KEY (episode_id) REFERENCES episodes(episode_id)
|
|
291
|
+
) STRICT;
|
|
292
|
+
|
|
212
293
|
CREATE TABLE IF NOT EXISTS reflection_runs (
|
|
213
294
|
run_id TEXT PRIMARY KEY NOT NULL,
|
|
214
295
|
trigger_kind TEXT NOT NULL CHECK (
|
|
@@ -265,6 +346,28 @@ function cleanText(value, maximum, label) {
|
|
|
265
346
|
return Array.from(cleaned).slice(0, maximum).join("");
|
|
266
347
|
}
|
|
267
348
|
|
|
349
|
+
function cleanSkillName(value) {
|
|
350
|
+
const name = cleanText(value, 64, "Learned skill name");
|
|
351
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+){0,5}$/u.test(name)) {
|
|
352
|
+
throw new TypeError("Learned skill name must be a short lowercase hyphenated identifier");
|
|
353
|
+
}
|
|
354
|
+
return name;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function cleanSkillInstructions(value) {
|
|
358
|
+
if (typeof value !== "string") throw new TypeError("Learned skill instructions must be text");
|
|
359
|
+
const cleaned = value
|
|
360
|
+
.replace(/\r\n?/gu, "\n")
|
|
361
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "")
|
|
362
|
+
.replace(/[\u202a-\u202e\u2066-\u2069]/gu, "")
|
|
363
|
+
.trim();
|
|
364
|
+
if (!cleaned) throw new TypeError("Learned skill instructions must not be empty");
|
|
365
|
+
if (Array.from(cleaned).length > 6_000 || cleaned.split("\n").length > 120) {
|
|
366
|
+
throw new TypeError("Learned skill instructions exceed their bounds");
|
|
367
|
+
}
|
|
368
|
+
return cleaned;
|
|
369
|
+
}
|
|
370
|
+
|
|
268
371
|
export function normalizeMemoryContent(value) {
|
|
269
372
|
return cleanText(value, 2_000, "Memory");
|
|
270
373
|
}
|
|
@@ -276,6 +379,25 @@ function cleanSessionId(value) {
|
|
|
276
379
|
return value;
|
|
277
380
|
}
|
|
278
381
|
|
|
382
|
+
function listeningMomentJson(moment) {
|
|
383
|
+
if (moment == null) return null;
|
|
384
|
+
const { situation = null, likes = [], avoids = [], queue_action: queue = null } = moment;
|
|
385
|
+
const quotes = (items) => Array.isArray(items) && items.every((text) => typeof text === "string" && text.trim());
|
|
386
|
+
if (typeof moment !== "object" || Array.isArray(moment) || (situation !== null && typeof situation !== "string") || !quotes(likes) || !quotes(avoids)) {
|
|
387
|
+
throw new TypeError("Listening moment is invalid");
|
|
388
|
+
}
|
|
389
|
+
let action = null;
|
|
390
|
+
if (queue !== null) {
|
|
391
|
+
const { service, action: verb, count } = queue;
|
|
392
|
+
if (!["spotify", "apple_music", "netease", "moondog"].includes(service) || !["queued", "started"].includes(verb) || !Number.isSafeInteger(count) || count < 1) {
|
|
393
|
+
throw new TypeError("Listening moment queue action is invalid");
|
|
394
|
+
}
|
|
395
|
+
action = { service, action: verb, count };
|
|
396
|
+
}
|
|
397
|
+
const context = situation?.trim() ? situation : null;
|
|
398
|
+
return context || likes.length || avoids.length || action ? JSON.stringify({ situation: context, likes, avoids, queue_action: action }) : null;
|
|
399
|
+
}
|
|
400
|
+
|
|
279
401
|
// A partial patch: a missing key keeps its value, and a null or empty title clears it.
|
|
280
402
|
// The in-memory conversations reuse this, so both paths accept the same input.
|
|
281
403
|
export function normalizeConversationLabel(patch) {
|
|
@@ -474,6 +596,37 @@ function normalizeReflectionProposal(value) {
|
|
|
474
596
|
value: cleanText(value.value, 1_000, "Music profile value"),
|
|
475
597
|
};
|
|
476
598
|
}
|
|
599
|
+
if (value.action === "candidate_skill") {
|
|
600
|
+
exactKeys(
|
|
601
|
+
value,
|
|
602
|
+
[
|
|
603
|
+
"action",
|
|
604
|
+
"assertion_mode",
|
|
605
|
+
"confidence",
|
|
606
|
+
"description",
|
|
607
|
+
"episode_ids",
|
|
608
|
+
"instructions",
|
|
609
|
+
"name",
|
|
610
|
+
"rationale",
|
|
611
|
+
"source_quote",
|
|
612
|
+
],
|
|
613
|
+
"Learned skill proposal",
|
|
614
|
+
);
|
|
615
|
+
if (!new Set(["explicit", "inferred"]).has(value.assertion_mode)) {
|
|
616
|
+
throw new TypeError("Learned skill proposal assertion mode is invalid");
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
action: value.action,
|
|
620
|
+
assertion_mode: value.assertion_mode,
|
|
621
|
+
confidence: cleanConfidence(value.confidence),
|
|
622
|
+
description: cleanText(value.description, 240, "Learned skill description"),
|
|
623
|
+
episode_ids: cleanEpisodeIds(value.episode_ids),
|
|
624
|
+
instructions: cleanSkillInstructions(value.instructions),
|
|
625
|
+
name: cleanSkillName(value.name),
|
|
626
|
+
rationale: cleanText(value.rationale, 500, "Learned skill proposal rationale"),
|
|
627
|
+
source_quote: cleanText(value.source_quote, 2_000, "Learned skill source quote"),
|
|
628
|
+
};
|
|
629
|
+
}
|
|
477
630
|
exactKeys(value, ["action", "episode_ids", "reason"], "Ignore proposal");
|
|
478
631
|
return {
|
|
479
632
|
action: value.action,
|
|
@@ -644,13 +797,10 @@ export class LocalMemoryStore {
|
|
|
644
797
|
|
|
645
798
|
// The reply another running Moondog process is writing in this conversation, if any.
|
|
646
799
|
#replyElsewhere(sessionId) {
|
|
647
|
-
const running = (pid) => {
|
|
648
|
-
try { process.kill(pid, 0); return true; } catch (error) { return error.code === "EPERM"; }
|
|
649
|
-
};
|
|
650
800
|
const row = this.#database.prepare(`SELECT e.entry_id, e.user_text, e.assistant_text, w.pid
|
|
651
801
|
FROM conversation_entries e JOIN conversation_writers w ON w.entry_id = e.entry_id
|
|
652
802
|
WHERE e.session_id = ? AND e.outcome = 'running' AND w.pid != ?`).all(sessionId, this.#processId)
|
|
653
|
-
.find((candidate) =>
|
|
803
|
+
.find((candidate) => writerIsAlive(candidate.pid));
|
|
654
804
|
return row ? { entry_id: row.entry_id, user_text: row.user_text, assistant_text: row.assistant_text } : null;
|
|
655
805
|
}
|
|
656
806
|
|
|
@@ -940,6 +1090,156 @@ export class LocalMemoryStore {
|
|
|
940
1090
|
};
|
|
941
1091
|
}
|
|
942
1092
|
|
|
1093
|
+
listLearnedSkills({ includeArchived = false, limit = 64 } = {}) {
|
|
1094
|
+
this.#assertOpen();
|
|
1095
|
+
const boundedLimit = Math.max(1, Math.min(Math.trunc(Number(limit)) || 64, 64));
|
|
1096
|
+
return this.#database.prepare(`
|
|
1097
|
+
SELECT name, description, origin, revision, created_at, updated_at
|
|
1098
|
+
FROM learned_skills
|
|
1099
|
+
WHERE status = 'active' OR ? = 1
|
|
1100
|
+
ORDER BY name ASC
|
|
1101
|
+
LIMIT ?
|
|
1102
|
+
`).all(includeArchived ? 1 : 0, boundedLimit).map((row) => ({ ...row }));
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
readLearnedSkill(name, { includeArchived = false } = {}) {
|
|
1106
|
+
this.#assertOpen();
|
|
1107
|
+
const cleanedName = cleanSkillName(name);
|
|
1108
|
+
const row = this.#database.prepare(`
|
|
1109
|
+
SELECT * FROM learned_skills
|
|
1110
|
+
WHERE name = ? AND (status = 'active' OR ? = 1)
|
|
1111
|
+
`).get(cleanedName, includeArchived ? 1 : 0);
|
|
1112
|
+
if (!row) throw new Error(`Learned skill not found: ${cleanedName}`);
|
|
1113
|
+
const evidence = this.#database.prepare(`
|
|
1114
|
+
SELECT episode_id FROM learned_skill_episode_refs
|
|
1115
|
+
WHERE name = ? ORDER BY episode_id ASC
|
|
1116
|
+
`).all(cleanedName).map((entry) => entry.episode_id);
|
|
1117
|
+
return {
|
|
1118
|
+
name: row.name,
|
|
1119
|
+
description: row.description,
|
|
1120
|
+
instructions: row.instructions,
|
|
1121
|
+
status: row.status,
|
|
1122
|
+
origin: row.origin,
|
|
1123
|
+
revision: row.revision,
|
|
1124
|
+
created_at: row.created_at,
|
|
1125
|
+
updated_at: row.updated_at,
|
|
1126
|
+
archived_at: row.archived_at,
|
|
1127
|
+
evidence_episode_ids: evidence,
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
readLearnedSkillRevision(name, revision) {
|
|
1132
|
+
this.#assertOpen();
|
|
1133
|
+
const cleanedName = cleanSkillName(name);
|
|
1134
|
+
if (!Number.isSafeInteger(revision) || revision < 1) {
|
|
1135
|
+
throw new TypeError("Learned skill revision is invalid");
|
|
1136
|
+
}
|
|
1137
|
+
const row = this.#database.prepare(`
|
|
1138
|
+
SELECT name, revision, description, instructions, origin, created_at
|
|
1139
|
+
FROM learned_skill_revisions WHERE name = ? AND revision = ?
|
|
1140
|
+
`).get(cleanedName, revision);
|
|
1141
|
+
if (!row) throw new Error(`Learned skill revision not found: ${cleanedName}@${revision}`);
|
|
1142
|
+
return { ...row };
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
archiveLearnedSkill(name) {
|
|
1146
|
+
this.#assertOpen();
|
|
1147
|
+
const cleanedName = cleanSkillName(name);
|
|
1148
|
+
const archivedAt = isoTimestamp(this.#clock);
|
|
1149
|
+
const result = this.#database.prepare(`
|
|
1150
|
+
UPDATE learned_skills
|
|
1151
|
+
SET status = 'archived', archived_at = ?, updated_at = ?
|
|
1152
|
+
WHERE name = ? AND status = 'active'
|
|
1153
|
+
`).run(archivedAt, archivedAt, cleanedName);
|
|
1154
|
+
if (result.changes !== 1) {
|
|
1155
|
+
const archived = this.#database.prepare(
|
|
1156
|
+
"SELECT status FROM learned_skills WHERE name = ?",
|
|
1157
|
+
).get(cleanedName);
|
|
1158
|
+
if (archived?.status !== "archived") throw new Error(`Learned skill not found: ${cleanedName}`);
|
|
1159
|
+
}
|
|
1160
|
+
return this.readLearnedSkill(cleanedName, { includeArchived: true });
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
restoreLearnedSkill(name) {
|
|
1164
|
+
this.#assertOpen();
|
|
1165
|
+
const cleanedName = cleanSkillName(name);
|
|
1166
|
+
const restoredAt = isoTimestamp(this.#clock);
|
|
1167
|
+
const result = this.#database.prepare(`
|
|
1168
|
+
UPDATE learned_skills
|
|
1169
|
+
SET status = 'active', archived_at = NULL, updated_at = ?
|
|
1170
|
+
WHERE name = ? AND status = 'archived'
|
|
1171
|
+
`).run(restoredAt, cleanedName);
|
|
1172
|
+
if (result.changes !== 1) {
|
|
1173
|
+
const current = this.#database.prepare(
|
|
1174
|
+
"SELECT status FROM learned_skills WHERE name = ?",
|
|
1175
|
+
).get(cleanedName);
|
|
1176
|
+
if (current?.status !== "active") throw new Error(`Learned skill not found: ${cleanedName}`);
|
|
1177
|
+
}
|
|
1178
|
+
return this.readLearnedSkill(cleanedName);
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
#applyReflectionSkillProposal(proposal, timestamp) {
|
|
1182
|
+
const timeBoundedEvidence = this.#database
|
|
1183
|
+
.prepare(`
|
|
1184
|
+
SELECT episode_id FROM episodes
|
|
1185
|
+
WHERE episode_id IN (${proposal.episode_ids.map(() => "?").join(", ")})
|
|
1186
|
+
AND expires_at IS NOT NULL LIMIT 1
|
|
1187
|
+
`)
|
|
1188
|
+
.get(...proposal.episode_ids);
|
|
1189
|
+
if (timeBoundedEvidence) return { blocked: true, reason: "expiry" };
|
|
1190
|
+
if (Array.from(proposal.source_quote).length < 4) {
|
|
1191
|
+
return { blocked: true, reason: "source_quote" };
|
|
1192
|
+
}
|
|
1193
|
+
const exactQuote = this.#database
|
|
1194
|
+
.prepare(`
|
|
1195
|
+
SELECT episode_id FROM episodes
|
|
1196
|
+
WHERE episode_id IN (${proposal.episode_ids.map(() => "?").join(", ")})
|
|
1197
|
+
AND instr(summary, ?) > 0 LIMIT 1
|
|
1198
|
+
`)
|
|
1199
|
+
.get(...proposal.episode_ids, proposal.source_quote);
|
|
1200
|
+
if (!exactQuote) return { blocked: true, reason: "source_quote" };
|
|
1201
|
+
|
|
1202
|
+
const existing = this.#database
|
|
1203
|
+
.prepare("SELECT * FROM learned_skills WHERE name = ?")
|
|
1204
|
+
.get(proposal.name);
|
|
1205
|
+
if (existing?.status === "archived") return { blocked: true, reason: "archived" };
|
|
1206
|
+
const created = !existing;
|
|
1207
|
+
const changed = created || existing.description !== proposal.description ||
|
|
1208
|
+
existing.instructions !== proposal.instructions;
|
|
1209
|
+
const revision = created ? 1 : changed ? existing.revision + 1 : existing.revision;
|
|
1210
|
+
if (created) {
|
|
1211
|
+
this.#database.prepare(`
|
|
1212
|
+
INSERT INTO learned_skills(
|
|
1213
|
+
name, description, instructions, status, origin, revision, created_at, updated_at
|
|
1214
|
+
) VALUES (?, ?, ?, 'active', 'memory_agent_explicit', 1, ?, ?)
|
|
1215
|
+
`).run(proposal.name, proposal.description, proposal.instructions, timestamp, timestamp);
|
|
1216
|
+
} else if (changed) {
|
|
1217
|
+
this.#database.prepare(`
|
|
1218
|
+
UPDATE learned_skills
|
|
1219
|
+
SET description = ?, instructions = ?, revision = ?, updated_at = ?
|
|
1220
|
+
WHERE name = ? AND status = 'active'
|
|
1221
|
+
`).run(proposal.description, proposal.instructions, revision, timestamp, proposal.name);
|
|
1222
|
+
}
|
|
1223
|
+
if (changed) {
|
|
1224
|
+
this.#database.prepare(`
|
|
1225
|
+
INSERT INTO learned_skill_revisions(
|
|
1226
|
+
name, revision, description, instructions, origin, created_at
|
|
1227
|
+
) VALUES (?, ?, ?, ?, 'memory_agent_explicit', ?)
|
|
1228
|
+
`).run(proposal.name, revision, proposal.description, proposal.instructions, timestamp);
|
|
1229
|
+
}
|
|
1230
|
+
const link = this.#database.prepare(`
|
|
1231
|
+
INSERT OR IGNORE INTO learned_skill_episode_refs(name, episode_id, created_at)
|
|
1232
|
+
VALUES (?, ?, ?)
|
|
1233
|
+
`);
|
|
1234
|
+
for (const episodeId of proposal.episode_ids) link.run(proposal.name, episodeId, timestamp);
|
|
1235
|
+
return {
|
|
1236
|
+
blocked: false,
|
|
1237
|
+
created,
|
|
1238
|
+
changed,
|
|
1239
|
+
skill: this.readLearnedSkill(proposal.name),
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
|
|
943
1243
|
startSession({ routeKey = "local:main" } = {}) {
|
|
944
1244
|
this.#assertOpen();
|
|
945
1245
|
const sessionId = randomUUID();
|
|
@@ -1005,7 +1305,7 @@ export class LocalMemoryStore {
|
|
|
1005
1305
|
l.title AS label_title,
|
|
1006
1306
|
COALESCE((SELECT user_text FROM conversation_entries WHERE session_id = s.session_id ORDER BY position LIMIT 1),
|
|
1007
1307
|
(SELECT content FROM turns WHERE session_id = s.session_id AND role = 'user' ORDER BY position LIMIT 1),
|
|
1008
|
-
b.draft, '') AS first_text,
|
|
1308
|
+
picked.title || ' · ' || picked.artist, NULLIF(b.draft, ''), json_extract(b.queued_json, '$[0]'), '') AS first_text,
|
|
1009
1309
|
l.title IS NOT NULL AS custom_title, l.pinned_at, l.folder_id,
|
|
1010
1310
|
b.parent_session_id,
|
|
1011
1311
|
CASE WHEN b.parent_session_id IS NOT NULL AND l.title IS NULL THEN
|
|
@@ -1018,10 +1318,11 @@ export class LocalMemoryStore {
|
|
|
1018
1318
|
AND (rs.started_at < s.started_at OR (rs.started_at = s.started_at AND rs.rowid <= s.rowid))) END AS lineage_number,
|
|
1019
1319
|
COALESCE(NULLIF(b.draft, ''), (SELECT user_text FROM conversation_entries WHERE session_id = s.session_id ORDER BY position DESC LIMIT 1), '') AS last_message
|
|
1020
1320
|
FROM sessions s LEFT JOIN conversation_branches b ON b.session_id = s.session_id
|
|
1321
|
+
LEFT JOIN conversation_draft_tracks picked ON picked.session_id = s.session_id
|
|
1021
1322
|
LEFT JOIN conversation_labels l ON l.session_id = s.session_id
|
|
1022
1323
|
WHERE s.route_key = ? AND (
|
|
1023
1324
|
EXISTS (SELECT 1 FROM conversation_entries WHERE session_id = s.session_id) OR
|
|
1024
|
-
EXISTS (SELECT 1 FROM turns WHERE session_id = s.session_id) OR b.draft != '')
|
|
1325
|
+
EXISTS (SELECT 1 FROM turns WHERE session_id = s.session_id) OR b.draft != '' OR json_array_length(b.queued_json) > 0)
|
|
1025
1326
|
ORDER BY l.pinned_at IS NULL, updated_at DESC, s.started_at DESC, s.rowid DESC LIMIT ?
|
|
1026
1327
|
`).all(route, bounded).map(row => {
|
|
1027
1328
|
// An unnamed conversation shows its first message, cut short.
|
|
@@ -1143,6 +1444,30 @@ export class LocalMemoryStore {
|
|
|
1143
1444
|
} catch (error) { this.#database.exec("ROLLBACK"); throw error; }
|
|
1144
1445
|
}
|
|
1145
1446
|
|
|
1447
|
+
#archiveSkillsWithoutRemainingEvidence(episodePredicate, values, timestamp) {
|
|
1448
|
+
const episodeSet = `SELECT episode_id FROM episodes WHERE ${episodePredicate}`;
|
|
1449
|
+
const affected = this.#database.prepare(`
|
|
1450
|
+
SELECT DISTINCT name FROM learned_skill_episode_refs
|
|
1451
|
+
WHERE episode_id IN (${episodeSet})
|
|
1452
|
+
`).all(...values);
|
|
1453
|
+
const remains = this.#database.prepare(`
|
|
1454
|
+
SELECT 1 FROM learned_skill_episode_refs
|
|
1455
|
+
WHERE name = ? AND episode_id NOT IN (${episodeSet})
|
|
1456
|
+
LIMIT 1
|
|
1457
|
+
`);
|
|
1458
|
+
for (const { name } of affected) {
|
|
1459
|
+
if (remains.get(name, ...values)) continue;
|
|
1460
|
+
this.#database.prepare(`
|
|
1461
|
+
UPDATE learned_skills
|
|
1462
|
+
SET status = 'archived', archived_at = ?, updated_at = ?
|
|
1463
|
+
WHERE name = ? AND status = 'active'
|
|
1464
|
+
`).run(timestamp, timestamp, name);
|
|
1465
|
+
}
|
|
1466
|
+
this.#database.prepare(`
|
|
1467
|
+
DELETE FROM learned_skill_episode_refs WHERE episode_id IN (${episodeSet})
|
|
1468
|
+
`).run(...values);
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1146
1471
|
// Removes one conversation and its transcript but keeps durable memories, so a
|
|
1147
1472
|
// preference stated in it still holds. Its branches stay, re-parented and re-rooted.
|
|
1148
1473
|
deleteConversation(sessionId, { routeKey = "local:main" } = {}) {
|
|
@@ -1164,6 +1489,11 @@ export class LocalMemoryStore {
|
|
|
1164
1489
|
if (heir) run("UPDATE conversation_branches SET root_session_id = ? WHERE root_session_id = ? AND session_id != ?", heir, id, id);
|
|
1165
1490
|
// Dialogue episodes hold the raw user text. With no session they would be recalled
|
|
1166
1491
|
// in every conversation, so they go; explicit memories and retractions stay.
|
|
1492
|
+
this.#archiveSkillsWithoutRemainingEvidence(
|
|
1493
|
+
"session_id = ? AND kind = 'dialogue'",
|
|
1494
|
+
[id],
|
|
1495
|
+
isoTimestamp(this.#clock),
|
|
1496
|
+
);
|
|
1167
1497
|
run(`DELETE FROM claim_episode_refs WHERE episode_id IN
|
|
1168
1498
|
(SELECT episode_id FROM episodes WHERE session_id = ? AND kind = 'dialogue')`, id);
|
|
1169
1499
|
run("DELETE FROM episodes WHERE session_id = ? AND kind = 'dialogue'", id);
|
|
@@ -1395,7 +1725,19 @@ export class LocalMemoryStore {
|
|
|
1395
1725
|
|
|
1396
1726
|
#ensureConversation(sessionId) {
|
|
1397
1727
|
const exists = this.#database.prepare("SELECT 1 FROM conversation_branches WHERE session_id = ?").get(sessionId);
|
|
1398
|
-
if (exists)
|
|
1728
|
+
if (exists) {
|
|
1729
|
+
// A process can exit after saving part of its answer. Preserve the last text and any
|
|
1730
|
+
// confirmed playback action. All callers hold a transaction while recovering the entry.
|
|
1731
|
+
const writers = this.#database.prepare(`SELECT e.entry_id, e.assistant_text, w.pid FROM conversation_writers w
|
|
1732
|
+
JOIN conversation_entries e USING (entry_id) WHERE w.session_id = ? AND w.pid != ? AND e.outcome = 'running'`).all(sessionId, this.#processId);
|
|
1733
|
+
for (const { entry_id, assistant_text, pid } of writers) {
|
|
1734
|
+
if (writerIsAlive(pid)) continue;
|
|
1735
|
+
this.#database.prepare("UPDATE conversation_entries SET outcome = 'interrupted', assistant_text = ? WHERE entry_id = ?")
|
|
1736
|
+
.run(unfinishedConversationReply(assistant_text), entry_id);
|
|
1737
|
+
this.#database.prepare("DELETE FROM conversation_writers WHERE entry_id = ?").run(entry_id);
|
|
1738
|
+
}
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1399
1741
|
this.#database.prepare(`INSERT INTO conversation_branches(session_id, root_session_id) VALUES (?, ?)`).run(sessionId, sessionId);
|
|
1400
1742
|
// Import only an old session's rendered text, never tool messages or plans.
|
|
1401
1743
|
const legacy = this.#database.prepare("SELECT * FROM turns WHERE session_id = ? ORDER BY position").all(sessionId);
|
|
@@ -1410,7 +1752,7 @@ export class LocalMemoryStore {
|
|
|
1410
1752
|
}
|
|
1411
1753
|
}
|
|
1412
1754
|
|
|
1413
|
-
beginConversationEntry(sessionId, user) {
|
|
1755
|
+
beginConversationEntry(sessionId, user, libraryRef = null, listenerText = user) {
|
|
1414
1756
|
this.#assertOpen();
|
|
1415
1757
|
if (typeof user !== 'string' || !user.trim() || user.length > 8_000) throw new TypeError("Conversation input is invalid");
|
|
1416
1758
|
const text = user;
|
|
@@ -1424,22 +1766,72 @@ export class LocalMemoryStore {
|
|
|
1424
1766
|
const entryId = randomUUID();
|
|
1425
1767
|
this.#database.prepare(`INSERT INTO conversation_entries(entry_id, session_id, position, user_text, outcome, created_at)
|
|
1426
1768
|
VALUES (?, ?, ?, ?, 'running', ?)`).run(entryId, sessionId, position, text, isoTimestamp(this.#clock));
|
|
1769
|
+
if (libraryRef) this.#database.prepare("INSERT INTO conversation_library_refs(entry_id, ref) VALUES (?, ?)").run(entryId, libraryRef);
|
|
1427
1770
|
this.#database.prepare("INSERT INTO conversation_writers(entry_id, session_id, pid) VALUES (?, ?, ?)").run(entryId, sessionId, this.#processId);
|
|
1428
|
-
|
|
1771
|
+
// Another client can be composing a new request while this one sends a queued turn.
|
|
1772
|
+
this.#database.prepare(`UPDATE conversation_branches SET draft = '' WHERE session_id = ? AND draft = ?
|
|
1773
|
+
AND NOT EXISTS (SELECT 1 FROM conversation_draft_library WHERE session_id = ? AND ref IS NOT ?)`)
|
|
1774
|
+
.run(sessionId, listenerText, sessionId, libraryRef ?? null);
|
|
1429
1775
|
this.#database.exec("COMMIT");
|
|
1430
1776
|
return entryId;
|
|
1431
1777
|
} catch (error) { this.#database.exec("ROLLBACK"); throw error; }
|
|
1432
1778
|
}
|
|
1433
1779
|
|
|
1434
|
-
|
|
1780
|
+
#saveListeningMoment(sessionId, entryId, status, snapshot, now) {
|
|
1781
|
+
// Anchor expiry to when the listener spoke, even if playback or the reply took a long time.
|
|
1782
|
+
const oldest = new Date(Date.parse(now) - LISTENING_MOMENT_TTL_MS).toISOString();
|
|
1783
|
+
this.#database.prepare(`INSERT INTO conversation_listening_moments(entry_id, expires_at, snapshot_json)
|
|
1784
|
+
SELECT entry_id, strftime('%Y-%m-%dT%H:%M:%fZ', created_at, ?), ? FROM conversation_entries
|
|
1785
|
+
WHERE session_id = ? AND entry_id = ? AND outcome = ? AND created_at > ?
|
|
1786
|
+
ON CONFLICT(entry_id) DO UPDATE SET snapshot_json = excluded.snapshot_json`)
|
|
1787
|
+
.run(`+${LISTENING_MOMENT_TTL_MS / 1000} seconds`, snapshot, sessionId, entryId, status, oldest);
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
recordListeningAction(sessionId, entryId, action) {
|
|
1791
|
+
this.#assertOpen();
|
|
1792
|
+
const snapshot = listeningMomentJson({ queue_action: action });
|
|
1793
|
+
if (snapshot) this.#saveListeningMoment(sessionId, entryId, "running", snapshot, isoTimestamp(this.#clock));
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
finishConversationEntry(sessionId, entryId, { text = '', status = 'failed', transient = false, listeningMoment, confirmedAction } = {}) {
|
|
1435
1797
|
this.#assertOpen();
|
|
1436
1798
|
if (!['completed', 'aborted', 'interrupted', 'failed'].includes(status) || typeof text !== 'string' || text.length > 40_000) {
|
|
1437
1799
|
throw new TypeError("Conversation outcome is invalid");
|
|
1438
1800
|
}
|
|
1439
|
-
|
|
1440
|
-
const
|
|
1441
|
-
|
|
1442
|
-
|
|
1801
|
+
const snapshot = listeningMomentJson(status === "completed" ? listeningMoment : confirmedAction && { queue_action: confirmedAction });
|
|
1802
|
+
const now = isoTimestamp(this.#clock);
|
|
1803
|
+
this.#database.exec("BEGIN IMMEDIATE");
|
|
1804
|
+
try {
|
|
1805
|
+
const update = this.#database.prepare(`UPDATE conversation_entries SET assistant_text = ?, outcome = ?, transient = ?
|
|
1806
|
+
WHERE session_id = ? AND entry_id = ? AND outcome = 'running'`).run(text, status, transient ? 1 : 0, sessionId, entryId);
|
|
1807
|
+
if (!update.changes) throw new Error("Conversation turn is no longer active");
|
|
1808
|
+
this.#database.prepare("DELETE FROM conversation_writers WHERE entry_id = ?").run(entryId);
|
|
1809
|
+
this.#database.prepare("DELETE FROM conversation_listening_moments WHERE expires_at <= ?").run(now);
|
|
1810
|
+
if (snapshot) this.#saveListeningMoment(sessionId, entryId, status, snapshot, now);
|
|
1811
|
+
else if (status === "completed") this.#database.prepare("DELETE FROM conversation_listening_moments WHERE entry_id = ?").run(entryId);
|
|
1812
|
+
this.#database.exec("COMMIT");
|
|
1813
|
+
} catch (error) { this.#database.exec("ROLLBACK"); throw error; }
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
readListeningMoment(sessionId, now = this.#clock()) {
|
|
1817
|
+
this.#assertOpen();
|
|
1818
|
+
const at = cleanTimestamp(now, "Listening moment time");
|
|
1819
|
+
if (!at) return null;
|
|
1820
|
+
// A completed entry with no snapshot is a clear, including a completion from an older core.
|
|
1821
|
+
const entries = this.#database.prepare(`SELECT e.outcome, m.expires_at, m.snapshot_json FROM conversation_entries e
|
|
1822
|
+
LEFT JOIN conversation_listening_moments m USING (entry_id)
|
|
1823
|
+
WHERE e.session_id = ? AND (e.outcome = 'completed' OR m.entry_id IS NOT NULL)
|
|
1824
|
+
ORDER BY e.position DESC`).iterate(cleanSessionId(sessionId));
|
|
1825
|
+
let expired = false;
|
|
1826
|
+
const moment = restoreListeningMoment(entries, row => {
|
|
1827
|
+
if (!row.snapshot_json) return null;
|
|
1828
|
+
if (row.expires_at > at) return JSON.parse(row.snapshot_json);
|
|
1829
|
+
expired = true;
|
|
1830
|
+
return null;
|
|
1831
|
+
});
|
|
1832
|
+
// A caller may check another time. Prune only what has expired on the store's own clock.
|
|
1833
|
+
if (expired) this.#database.prepare("DELETE FROM conversation_listening_moments WHERE expires_at <= ?").run(isoTimestamp(this.#clock));
|
|
1834
|
+
return moment;
|
|
1443
1835
|
}
|
|
1444
1836
|
|
|
1445
1837
|
// The reply so far, so another Moondog window or terminal can show it while it grows.
|
|
@@ -1456,24 +1848,44 @@ export class LocalMemoryStore {
|
|
|
1456
1848
|
try { this.#ensureConversation(sessionId); this.#database.exec("COMMIT"); }
|
|
1457
1849
|
catch (error) { this.#database.exec("ROLLBACK"); throw error; }
|
|
1458
1850
|
const bounded = Math.max(1, Math.min(Math.trunc(Number(limit)) || 200, 500));
|
|
1459
|
-
return this.#database.prepare(`SELECT entry_id, user_text, assistant_text, outcome, transient, created_at
|
|
1460
|
-
FROM conversation_entries
|
|
1461
|
-
|
|
1851
|
+
return this.#database.prepare(`SELECT entry_id, user_text, assistant_text, outcome, transient, created_at, ref
|
|
1852
|
+
FROM conversation_entries LEFT JOIN conversation_library_refs USING (entry_id)
|
|
1853
|
+
WHERE session_id = ? ORDER BY position DESC LIMIT ?`).all(sessionId, bounded).reverse()
|
|
1854
|
+
.map(({ ref, ...row }) => ({ ...row, ...(ref ? { library_ref: ref } : {}), transient: row.transient === 1 }));
|
|
1462
1855
|
}
|
|
1463
1856
|
|
|
1464
|
-
conversationPending(sessionId, pending) {
|
|
1857
|
+
conversationPending(sessionId, pending, { expectedDraft, expectedLibraryRef } = {}) {
|
|
1465
1858
|
this.#assertOpen();
|
|
1466
1859
|
if (pending !== undefined && (typeof pending?.draft !== 'string' || pending.draft.length > 8_000 ||
|
|
1467
|
-
!Array.isArray(pending.queued) || pending.queued.length > 30 ||
|
|
1468
|
-
|
|
1860
|
+
(pending.queued !== undefined && (!Array.isArray(pending.queued) || pending.queued.length > 30 ||
|
|
1861
|
+
pending.queued.some(text => typeof text !== 'string' || text.length > 8_000))))) throw new TypeError("Conversation draft is invalid");
|
|
1469
1862
|
this.#database.exec("BEGIN IMMEDIATE");
|
|
1470
1863
|
try {
|
|
1471
1864
|
this.#ensureConversation(sessionId);
|
|
1472
|
-
if (pending !== undefined)
|
|
1473
|
-
.
|
|
1474
|
-
|
|
1865
|
+
if (pending !== undefined) {
|
|
1866
|
+
const { changes } = this.#database.prepare(`UPDATE conversation_branches SET draft = ?, queued_json = COALESCE(?, queued_json)
|
|
1867
|
+
WHERE session_id = ? AND (? IS NULL OR draft = ?) AND
|
|
1868
|
+
(? = 0 OR (SELECT ref FROM conversation_draft_library WHERE session_id = ?) IS ?)`)
|
|
1869
|
+
.run(pending.draft, pending.queued === undefined ? null : JSON.stringify(pending.queued), sessionId, expectedDraft ?? null, expectedDraft ?? null,
|
|
1870
|
+
Number(expectedLibraryRef !== undefined), sessionId, expectedLibraryRef ?? null);
|
|
1871
|
+
if (changes && pending.profileSeed) {
|
|
1872
|
+
const { subjectId, label, artistCredit } = pending.profileSeed;
|
|
1873
|
+
this.#database.prepare("INSERT INTO conversation_draft_tracks(session_id, subject_id, title, artist) VALUES (?, ?, ?, ?)")
|
|
1874
|
+
.run(sessionId, subjectId, label, artistCredit);
|
|
1875
|
+
}
|
|
1876
|
+
if (changes && pending.libraryLocation) {
|
|
1877
|
+
this.#database.prepare(`INSERT INTO conversation_draft_library(session_id, ref, label) VALUES (?, ?, ?)
|
|
1878
|
+
ON CONFLICT(session_id) DO UPDATE SET ref = excluded.ref, label = excluded.label`)
|
|
1879
|
+
.run(sessionId, pending.libraryLocation.ref, pending.libraryLocation.label);
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
const row = this.#database.prepare(`SELECT b.draft, b.queued_json, t.subject_id, t.title, t.artist, l.ref, l.label
|
|
1883
|
+
FROM conversation_branches b LEFT JOIN conversation_draft_tracks t USING(session_id)
|
|
1884
|
+
LEFT JOIN conversation_draft_library l USING(session_id) WHERE b.session_id = ?`).get(sessionId);
|
|
1475
1885
|
this.#database.exec("COMMIT");
|
|
1476
|
-
return { draft: row.draft, queued: JSON.parse(row.queued_json)
|
|
1886
|
+
return { draft: row.draft, queued: JSON.parse(row.queued_json),
|
|
1887
|
+
...(row.ref ? { libraryLocation: { ref: row.ref, label: row.label } } : {}),
|
|
1888
|
+
...(row.subject_id ? { profileSeed: { subjectId: row.subject_id, entityType: "track", label: row.title, artistCredit: row.artist } } : {}) };
|
|
1477
1889
|
} catch (error) { this.#database.exec("ROLLBACK"); throw error; }
|
|
1478
1890
|
}
|
|
1479
1891
|
|
|
@@ -1499,6 +1911,11 @@ export class LocalMemoryStore {
|
|
|
1499
1911
|
if (first !== null) {
|
|
1500
1912
|
const replaced = "SELECT turn_id FROM turns WHERE session_id = ? AND role = 'user' AND position >= ?";
|
|
1501
1913
|
const dialogue = `SELECT episode_id FROM episodes WHERE kind = 'dialogue' AND source_kind = 'turn' AND source_id IN (${replaced})`;
|
|
1914
|
+
this.#archiveSkillsWithoutRemainingEvidence(
|
|
1915
|
+
`kind = 'dialogue' AND source_kind = 'turn' AND source_id IN (${replaced})`,
|
|
1916
|
+
[sessionId, first],
|
|
1917
|
+
isoTimestamp(this.#clock),
|
|
1918
|
+
);
|
|
1502
1919
|
this.#database.prepare(`DELETE FROM claim_episode_refs WHERE episode_id IN (${dialogue})`).run(sessionId, first);
|
|
1503
1920
|
this.#database.prepare(`DELETE FROM episodes WHERE episode_id IN (${dialogue})`).run(sessionId, first);
|
|
1504
1921
|
this.#database.prepare("DELETE FROM turns WHERE session_id = ? AND position >= ?").run(sessionId, first);
|
|
@@ -1526,7 +1943,9 @@ export class LocalMemoryStore {
|
|
|
1526
1943
|
this.#ensureConversation(sessionId);
|
|
1527
1944
|
const selected = this.#database.prepare("SELECT * FROM conversation_entries WHERE session_id = ? AND entry_id = ?").get(sessionId, entryId);
|
|
1528
1945
|
if (!selected) throw new Error("The selected turn is no longer available");
|
|
1529
|
-
if (selected.outcome === 'running'
|
|
1946
|
+
if (selected.outcome === 'running' && this.#database.prepare("SELECT 1 FROM conversation_writers WHERE entry_id = ?").get(entryId)) {
|
|
1947
|
+
throw new Error("Wait for the reply to finish before branching");
|
|
1948
|
+
}
|
|
1530
1949
|
const root = this.#database.prepare("SELECT root_session_id FROM conversation_branches WHERE session_id = ?").get(sessionId).root_session_id;
|
|
1531
1950
|
const createdAt = isoTimestamp(this.#clock);
|
|
1532
1951
|
const nextId = randomUUID();
|
|
@@ -1534,10 +1953,20 @@ export class LocalMemoryStore {
|
|
|
1534
1953
|
this.#database.prepare("INSERT INTO sessions(session_id, route_key, started_at, status) VALUES (?, ?, ?, 'active')").run(nextId, route, createdAt);
|
|
1535
1954
|
this.#database.prepare(`INSERT INTO conversation_branches(session_id, root_session_id, parent_session_id, source_entry_id)
|
|
1536
1955
|
VALUES (?, ?, ?, ?)`).run(nextId, root, sessionId, entryId);
|
|
1537
|
-
const prefix = this.#database.prepare(
|
|
1956
|
+
const prefix = this.#database.prepare(`SELECT e.*, r.ref FROM conversation_entries e LEFT JOIN conversation_library_refs r USING (entry_id)
|
|
1957
|
+
WHERE session_id = ? AND position <= ? ORDER BY position`).all(sessionId, selected.position);
|
|
1538
1958
|
const insert = this.#database.prepare(`INSERT INTO conversation_entries
|
|
1539
1959
|
(entry_id, session_id, position, user_text, assistant_text, outcome, transient, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
1540
|
-
|
|
1960
|
+
const keepRef = this.#database.prepare("INSERT INTO conversation_library_refs(entry_id, ref) VALUES (?, ?)");
|
|
1961
|
+
for (const row of prefix) {
|
|
1962
|
+
const id = randomUUID();
|
|
1963
|
+
// Older journals can have partial replies without a writer ID. Only snapshot their saved
|
|
1964
|
+
// text: an older client may still finish its own original, but cannot finish this copy.
|
|
1965
|
+
const partial = row.outcome === "running";
|
|
1966
|
+
insert.run(id, nextId, row.position, row.user_text, partial ? unfinishedConversationReply(row.assistant_text) : row.assistant_text,
|
|
1967
|
+
partial ? "interrupted" : row.outcome, row.transient, row.created_at);
|
|
1968
|
+
if (row.ref) keepRef.run(id, row.ref);
|
|
1969
|
+
}
|
|
1541
1970
|
this.#database.exec("COMMIT");
|
|
1542
1971
|
return { session_id: nextId, route_key: route, started_at: createdAt, parent_session_id: sessionId };
|
|
1543
1972
|
} catch (error) { this.#database.exec("ROLLBACK"); throw error; }
|
|
@@ -1778,6 +2207,10 @@ export class LocalMemoryStore {
|
|
|
1778
2207
|
lease_token: leaseToken,
|
|
1779
2208
|
episodes: episodes.map(reflectionEpisode),
|
|
1780
2209
|
active_memories: this.listMemories({ limit: 12 }),
|
|
2210
|
+
active_skills: this.listLearnedSkills({ limit: 24 }).map((skill) => ({
|
|
2211
|
+
name: skill.name,
|
|
2212
|
+
description: skill.description,
|
|
2213
|
+
})),
|
|
1781
2214
|
};
|
|
1782
2215
|
} catch (error) {
|
|
1783
2216
|
this.#database.exec("ROLLBACK");
|
|
@@ -1812,10 +2245,13 @@ export class LocalMemoryStore {
|
|
|
1812
2245
|
episodeIds,
|
|
1813
2246
|
);
|
|
1814
2247
|
const completedAt = isoTimestamp(this.#clock);
|
|
2248
|
+
const learnedSkills = [];
|
|
1815
2249
|
const counts = {
|
|
1816
2250
|
proposals: normalizedProposals.length,
|
|
1817
2251
|
promoted_memories: 0,
|
|
1818
2252
|
created_memories: 0,
|
|
2253
|
+
promoted_skills: 0,
|
|
2254
|
+
created_skills: 0,
|
|
1819
2255
|
candidate_episodes: 0,
|
|
1820
2256
|
ignored_episodes: 0,
|
|
1821
2257
|
};
|
|
@@ -1857,6 +2293,21 @@ export class LocalMemoryStore {
|
|
|
1857
2293
|
if (proposal.action === "ignore") {
|
|
1858
2294
|
nextState = "rejected";
|
|
1859
2295
|
counts.ignored_episodes += proposal.episode_ids.length;
|
|
2296
|
+
} else if (
|
|
2297
|
+
proposal.action === "candidate_skill" &&
|
|
2298
|
+
proposal.assertion_mode === "explicit" &&
|
|
2299
|
+
proposal.confidence >= 0.9
|
|
2300
|
+
) {
|
|
2301
|
+
const learned = this.#applyReflectionSkillProposal(proposal, completedAt);
|
|
2302
|
+
if (learned.blocked) {
|
|
2303
|
+
nextState = "candidate";
|
|
2304
|
+
counts.candidate_episodes += proposal.episode_ids.length;
|
|
2305
|
+
} else {
|
|
2306
|
+
nextState = "promoted";
|
|
2307
|
+
counts.promoted_skills += 1;
|
|
2308
|
+
if (learned.created) counts.created_skills += 1;
|
|
2309
|
+
learnedSkills.push(learned.skill);
|
|
2310
|
+
}
|
|
1860
2311
|
} else if (
|
|
1861
2312
|
proposal.action === "candidate_memory" &&
|
|
1862
2313
|
proposal.assertion_mode === "explicit" &&
|
|
@@ -1912,6 +2363,7 @@ export class LocalMemoryStore {
|
|
|
1912
2363
|
run_id: cleanedRunId,
|
|
1913
2364
|
counts,
|
|
1914
2365
|
proposals: normalizedProposals,
|
|
2366
|
+
learned_skills: learnedSkills,
|
|
1915
2367
|
};
|
|
1916
2368
|
} catch (error) {
|
|
1917
2369
|
this.#database.exec("ROLLBACK");
|