@bitcobblers/wod-wiki-engine 0.60.2258 → 0.62.2260

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/dist/agent.cjs CHANGED
@@ -808,7 +808,7 @@ function isNotebookLandingNote(note) {
808
808
  function baseUserMemberships(note) {
809
809
  if (note.seedOrigin === "seed" || note.feedOrigin === "feed") return [];
810
810
  if (isNotebookLandingNote(note) || isPropertyDefinitionNoteId(note.id)) return [];
811
- const base = ["notebook/journal"];
811
+ const base = [];
812
812
  if (note.type === "playground" || note.sourceId === "playground") {
813
813
  base.push("notebook/playground");
814
814
  }
@@ -926,7 +926,6 @@ async function promoteNoteToNotebooks(storage, input) {
926
926
  for (const sess of sessions) {
927
927
  if (!wantedSessions.has(sess.id)) continue;
928
928
  const sessNotebooks = dedupeNotebooks([
929
- "notebook/journal",
930
929
  ...sess.notebookIds ?? [],
931
930
  ...requestedTargets
932
931
  ]);
@@ -969,12 +968,12 @@ async function setNoteNotebooks(storage, input) {
969
968
  if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
970
969
  throw new Error(`Read-only Feed Note '${input.noteId}' cannot change Notebook membership.`);
971
970
  }
972
- const userTargets = requested.filter(
973
- (id) => id !== "notebook/journal" && id !== "notebook/playground"
974
- );
971
+ const userTargets = requested.filter((id) => id !== "notebook/playground");
975
972
  for (const target of userTargets) {
976
- await assertWritableTargetNotebook(tx, target);
977
- await ensureUserNotebookLanding(tx, target, now);
973
+ if (target !== "notebook/journal") {
974
+ await assertWritableTargetNotebook(tx, target);
975
+ await ensureUserNotebookLanding(tx, target, now);
976
+ }
978
977
  }
979
978
  const finalMemberships = dedupeNotebooks([
980
979
  ...baseUserMemberships(note),
@@ -996,46 +995,949 @@ async function setNoteNotebooks(storage, input) {
996
995
  targetKind: "note",
997
996
  targetId: note.id,
998
997
  noteId: note.id,
999
- createdAt: now
1000
- });
998
+ createdAt: now
999
+ });
1000
+ }
1001
+ const primaryUserNb = finalMemberships.find(
1002
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
1003
+ );
1004
+ const { notebookId: _priorSingle, ...rest } = note;
1005
+ const updatedNote = {
1006
+ ...rest,
1007
+ notebookIds: finalMemberships,
1008
+ ...primaryUserNb ? { notebookId: primaryUserNb } : {}
1009
+ };
1010
+ await tx.readwrite("notes").put(updatedNote);
1011
+ return finalMemberships;
1012
+ });
1013
+ }
1014
+ async function removeNoteFromNotebook(storage, noteId, notebookIdOrSlug) {
1015
+ const target = wodWikiCore.toNotebookId(notebookIdOrSlug);
1016
+ const current = await getNoteNotebooks(storage, noteId);
1017
+ const remaining = current.filter((id) => id !== target);
1018
+ return setNoteNotebooks(storage, { noteId, notebookIds: remaining });
1019
+ }
1020
+ async function getNoteNotebooks(storage, noteId) {
1021
+ const note = await storage.readonly("notes").get(noteId);
1022
+ if (!note) return [];
1023
+ let linkNotebookIds = [];
1024
+ try {
1025
+ const links = await storage.readonly("notebook_links").getAllFromIndex("by-note", noteId);
1026
+ linkNotebookIds = links.filter((l) => l.targetKind === "note" && l.targetId === noteId).map((l) => l.notebookId);
1027
+ } catch {
1028
+ }
1029
+ const hasExplicitArray = Array.isArray(note.notebookIds);
1030
+ return dedupeNotebooks([
1031
+ ...baseUserMemberships(note),
1032
+ ...note.notebookIds ?? [],
1033
+ ...linkNotebookIds,
1034
+ ...hasExplicitArray ? [] : wodWikiWql.notebooksOfItem(note)
1035
+ ]);
1036
+ }
1037
+ function mintUuid() {
1038
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1039
+ return crypto.randomUUID();
1040
+ }
1041
+ const bytes = new Uint8Array(16);
1042
+ crypto.getRandomValues(bytes);
1043
+ bytes[6] = bytes[6] & 15 | 64;
1044
+ bytes[8] = bytes[8] & 63 | 128;
1045
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1046
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1047
+ }
1048
+ function utcCivilDateKey(epochMs) {
1049
+ const d = new Date(epochMs);
1050
+ const y = d.getFullYear();
1051
+ const m = String(d.getMonth() + 1).padStart(2, "0");
1052
+ const day = String(d.getDate()).padStart(2, "0");
1053
+ return `${y}-${m}-${day}`;
1054
+ }
1055
+ function parseRemoteNoteId(noteId) {
1056
+ if (!noteId.startsWith("remote:")) return { isRemote: false };
1057
+ const rest = noteId.slice("remote:".length);
1058
+ const sep = rest.indexOf(":");
1059
+ if (sep <= 0) return { isRemote: false };
1060
+ const feedId = rest.slice(0, sep);
1061
+ const uuid = rest.slice(sep + 1);
1062
+ if (!uuid) return { isRemote: false };
1063
+ return { isRemote: true, feedId, uuid };
1064
+ }
1065
+ function computeWodContentId(blockSource) {
1066
+ const sec = wodWikiCore.parseDocumentSections(blockSource, { registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS }).find(
1067
+ (s) => s.scriptBlock
1068
+ );
1069
+ if (sec?.scriptBlock?.contentId) return sec.scriptBlock.contentId;
1070
+ if (sec?.scriptBlock?.content) return wodWikiCore.blockContentId(sec.scriptBlock.content);
1071
+ return void 0;
1072
+ }
1073
+ function selectWorkoutBlock(sourceNote, ownershipKind, blockId, blockContentId6) {
1074
+ const sourceBlocks = Object.values(sourceNote.blocks ?? {});
1075
+ if (blockId) {
1076
+ const exact = sourceNote.blocks?.[blockId] ?? sourceBlocks.find((b) => b.id === blockId);
1077
+ if (exact) return exact;
1078
+ if (ownershipKind !== "user" && blockContentId6) {
1079
+ return sourceBlocks.find(
1080
+ (b) => b.kind === "wod" && computeWodContentId(sourceNote.rawContent.slice(b.from, b.to)) === blockContentId6
1081
+ );
1082
+ }
1083
+ return void 0;
1084
+ }
1085
+ return sourceBlocks.find((b) => b.kind === "wod");
1086
+ }
1087
+ function extractTitleFromMarkdown(rawContent, sourcePath) {
1088
+ const fm = readFrontmatterMeta(rawContent);
1089
+ if (typeof fm["title"] === "string" && fm["title"].trim()) return fm["title"].trim();
1090
+ const withoutFm = rawContent.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
1091
+ for (const line of withoutFm.split(/\r?\n/)) {
1092
+ const m = /^#\s+(.+)$/.exec(line);
1093
+ if (m?.[1]?.trim()) return m[1].trim();
1094
+ }
1095
+ if (sourcePath) {
1096
+ const stem = (sourcePath.split("/").at(-1) ?? "").replace(/\.md$/i, "");
1097
+ if (stem) return stem.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1098
+ }
1099
+ return "Workout";
1100
+ }
1101
+ function parseFrontmatterDateEpoch(rawContent) {
1102
+ const fm = readFrontmatterMeta(rawContent);
1103
+ const rawDate = typeof fm["date"] === "string" ? fm["date"].trim() : "";
1104
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(rawDate);
1105
+ if (!match) return void 0;
1106
+ const ts = Date.parse(`${rawDate}T12:00:00Z`);
1107
+ if (!Number.isFinite(ts)) return void 0;
1108
+ const d = new Date(ts);
1109
+ if (d.getUTCMonth() !== Number(match[2]) - 1 || d.getUTCDate() !== Number(match[3])) {
1110
+ return void 0;
1111
+ }
1112
+ return ts;
1113
+ }
1114
+ function deriveNotebookSourceMeta(sourcePath, notebookSlug) {
1115
+ if (sourcePath?.startsWith("markdown/notebooks/")) {
1116
+ const rel = sourcePath.slice("markdown/notebooks/".length).replace(/\.md$/i, "");
1117
+ const segs = rel.split("/");
1118
+ const slug = segs[0];
1119
+ if (slug) {
1120
+ const isLanding = segs.length === 2 && segs[1].toLowerCase() === "readme";
1121
+ return {
1122
+ sourceId: isLanding ? `notebook:${slug}` : `notebook:${rel}`,
1123
+ seedChunkId: `notebook.${slug}`,
1124
+ sourceNotebookId: wodWikiCore.toNotebookId(slug)
1125
+ };
1126
+ }
1127
+ }
1128
+ if (notebookSlug) {
1129
+ const clean = wodWikiCore.notebookSlugFromId(notebookSlug);
1130
+ return {
1131
+ sourceId: `notebook:${clean}`,
1132
+ seedChunkId: `notebook.${clean}`,
1133
+ sourceNotebookId: wodWikiCore.toNotebookId(clean)
1134
+ };
1135
+ }
1136
+ return {};
1137
+ }
1138
+ function isEnvelope(val) {
1139
+ return typeof val === "object" && val !== null && !("rawContent" in val) && !("content" in val) && ("row" in val || "note" in val || "canonicalNoteId" in val);
1140
+ }
1141
+ function isBareSeedRow(val) {
1142
+ return typeof val === "object" && val !== null && "content" in val && "path" in val && !("rawContent" in val);
1143
+ }
1144
+ function normalizeRemoteResolution(requestedNoteId, resolution, now) {
1145
+ const parsedRemote = parseRemoteNoteId(requestedNoteId);
1146
+ let notePart;
1147
+ let seedRow;
1148
+ let envelopeFeedId;
1149
+ let envelopeNbSlug;
1150
+ let envelopeCanonicalId;
1151
+ let recordMeta;
1152
+ if (isEnvelope(resolution)) {
1153
+ notePart = resolution.note;
1154
+ seedRow = resolution.row;
1155
+ envelopeFeedId = resolution.feedId;
1156
+ envelopeNbSlug = resolution.notebookSlug;
1157
+ envelopeCanonicalId = resolution.canonicalNoteId;
1158
+ recordMeta = resolution.record;
1159
+ } else if (isBareSeedRow(resolution)) {
1160
+ seedRow = resolution;
1161
+ } else {
1162
+ notePart = resolution;
1163
+ if ("seedRow" in resolution && resolution.seedRow) {
1164
+ seedRow = resolution.seedRow;
1165
+ }
1166
+ }
1167
+ const rawContent = notePart?.rawContent ?? seedRow?.content ?? "";
1168
+ if (!rawContent) {
1169
+ throw new Error(`Resolved remote workout '${requestedNoteId}' has no Markdown content.`);
1170
+ }
1171
+ const canonicalNoteId = envelopeCanonicalId ?? (notePart?.id && !notePart.id.startsWith("remote:") ? notePart.id : void 0) ?? seedRow?.uuid ?? recordMeta?.uuid ?? (parsedRemote.isRemote ? parsedRemote.uuid : requestedNoteId);
1172
+ const sourcePath = notePart?.sourcePath ?? seedRow?.path ?? recordMeta?.path;
1173
+ const pathDerived = deriveNotebookSourceMeta(sourcePath, envelopeNbSlug);
1174
+ const feedSourceId = notePart?.feedSourceId ?? envelopeFeedId ?? (parsedRemote.isRemote ? parsedRemote.feedId : void 0);
1175
+ const sourceNotebookId = notePart?.sourceNotebookId ?? notePart?.provenance?.sourceNotebookId ?? pathDerived.sourceNotebookId ?? (notePart ? wodWikiWql.notebookOfItem(notePart) : void 0);
1176
+ const sourceId = notePart?.sourceId ?? pathDerived.sourceId;
1177
+ const seedChunkId = notePart?.seedChunkId ?? pathDerived.seedChunkId;
1178
+ const seedVersion = notePart?.seedVersion ?? seedRow?.version ?? recordMeta?.version ?? 1;
1179
+ const seedCommit = notePart?.seedCommit ?? seedRow?.commit ?? recordMeta?.commit;
1180
+ const date = notePart?.date ?? recordMeta?.date ?? parseFrontmatterDateEpoch(rawContent);
1181
+ const title = notePart?.title?.trim() || recordMeta?.title?.trim() || seedRow?.blockIndex?.[0]?.noteTitle?.trim() || extractTitleFromMarkdown(rawContent, sourcePath);
1182
+ const rawBlocks = notePart?.blocks && Object.keys(notePart.blocks).length > 0 ? notePart.blocks : seedRow?.blocks && Object.keys(seedRow.blocks).length > 0 ? seedRow.blocks : void 0;
1183
+ let ordinal = 0;
1184
+ const blocks = rawBlocks ? Object.fromEntries(
1185
+ Object.entries(rawBlocks).map(([k, b]) => [
1186
+ k,
1187
+ { ...b, version: b.version || 1, sourceRevision: 1 }
1188
+ ])
1189
+ ) : wodWikiCore.reconcileNoteBlocks(rawContent, {
1190
+ sourceRevision: 1,
1191
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS,
1192
+ createId: () => `blk-${canonicalNoteId.slice(0, 8)}-${ordinal++}`
1193
+ });
1194
+ return {
1195
+ canonicalNoteId,
1196
+ title,
1197
+ rawContent,
1198
+ blocks,
1199
+ ...date !== void 0 ? { date } : {},
1200
+ createdAt: notePart?.createdAt ?? date ?? now,
1201
+ ...notePart?.tags?.length ? { tags: notePart.tags.filter((t) => t !== "preview:remote") } : {},
1202
+ type: notePart?.type ?? "note",
1203
+ ...sourceId ? { sourceId } : {},
1204
+ ...sourcePath ? { sourcePath } : {},
1205
+ seedOrigin: notePart?.seedOrigin ?? "seed",
1206
+ feedOrigin: notePart?.feedOrigin ?? "feed",
1207
+ ...feedSourceId ? { feedSourceId } : {},
1208
+ seedVersion,
1209
+ ...seedChunkId ? { seedChunkId } : {},
1210
+ ...seedCommit ? { seedCommit } : {},
1211
+ ...sourceNotebookId ? { sourceNotebookId } : {},
1212
+ upstreamStatus: notePart?.upstreamStatus ?? "live",
1213
+ ...seedRow ? { seedRow } : {}
1214
+ };
1215
+ }
1216
+ async function ensureNoteBlockRevisionsAndIndexInTx(tx, note, now, seedRow) {
1217
+ const revStore = tx.readwrite("block_revisions");
1218
+ const idxStore = tx.readwrite("block_index");
1219
+ const blockList = Object.values(note.blocks ?? {}).sort((a, b) => a.from - b.from);
1220
+ const isStatic = note.seedOrigin === "seed" || note.feedOrigin === "feed" || void 0;
1221
+ const resolvedNb = wodWikiWql.notebookOfItem(note);
1222
+ const missingRevs = [];
1223
+ const missingIdx = [];
1224
+ const existingIdxRows = await idxStore.getAllFromIndex("by-note", note.id);
1225
+ const existingIdxIds = new Set(existingIdxRows.map((r) => r.id));
1226
+ for (const [pos, b] of blockList.entries()) {
1227
+ const slice = note.rawContent.slice(b.from, b.to);
1228
+ const existingRev = await revStore.get([note.id, b.id, b.version]);
1229
+ if (!existingRev) {
1230
+ missingRevs.push({
1231
+ noteId: note.id,
1232
+ blockId: b.id,
1233
+ version: b.version,
1234
+ kind: b.kind,
1235
+ rawContent: slice,
1236
+ savedAt: now,
1237
+ ...b.dialect ? { dialect: b.dialect } : {},
1238
+ ...b.sport ? { sport: b.sport } : {}
1239
+ });
1240
+ }
1241
+ const rowId = `${note.id}:${b.id}`;
1242
+ if (!existingIdxIds.has(rowId)) {
1243
+ const cid = b.kind === "wod" ? computeWodContentId(slice) : void 0;
1244
+ missingIdx.push({
1245
+ id: rowId,
1246
+ noteId: note.id,
1247
+ blockId: b.id,
1248
+ blockVersion: b.version,
1249
+ sourceRevision: note.sourceRevision,
1250
+ from: b.from,
1251
+ to: b.to,
1252
+ position: pos,
1253
+ dataType: b.kind,
1254
+ ...cid ? { blockContentId: cid } : {},
1255
+ rawContent: slice,
1256
+ noteTitle: note.title,
1257
+ createdAt: note.date ?? note.createdAt ?? now,
1258
+ ...isStatic ? { isStatic: true } : {},
1259
+ ...note.sourceId ? { sourceId: note.sourceId } : {},
1260
+ ...note.sourcePath ? { sourcePath: note.sourcePath } : {},
1261
+ ...resolvedNb ? { notebookId: resolvedNb } : {}
1262
+ });
1263
+ }
1264
+ }
1265
+ if (missingRevs.length > 0) await revStore.putMany(missingRevs);
1266
+ if (missingIdx.length > 0) await idxStore.putMany(missingIdx);
1267
+ if (seedRow?.blockEfforts?.length) {
1268
+ try {
1269
+ const effortStore = tx.readwrite("block_efforts");
1270
+ const rows = seedRow.blockEfforts.map((eff) => ({
1271
+ ...eff,
1272
+ id: `${note.id}:${eff.blockId}:${eff.effortSlug}`,
1273
+ noteId: note.id,
1274
+ ...isStatic ? { isStatic: true } : {}
1275
+ }));
1276
+ if (rows.length > 0) await effortStore.putMany(rows);
1277
+ } catch {
1278
+ }
1279
+ }
1280
+ if (seedRow?.blockEquipment?.length) {
1281
+ try {
1282
+ const eqStore = tx.readwrite("block_equipment");
1283
+ const rows = seedRow.blockEquipment.map((eq) => ({
1284
+ ...eq,
1285
+ id: `${note.id}:${eq.blockId}:${eq.equipmentSlug}`,
1286
+ noteId: note.id,
1287
+ ...isStatic ? { isStatic: true } : {}
1288
+ }));
1289
+ if (rows.length > 0) await eqStore.putMany(rows);
1290
+ } catch {
1291
+ }
1292
+ }
1293
+ }
1294
+ async function getOrCreateJournalPageInTx(tx, journalDate, now) {
1295
+ let existingPages;
1296
+ try {
1297
+ existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
1298
+ } catch {
1299
+ existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
1300
+ }
1301
+ if (existingPages[0]) return existingPages[0];
1302
+ const page = {
1303
+ id: mintUuid(),
1304
+ date: journalDate,
1305
+ title: journalDate,
1306
+ createdAt: now
1307
+ };
1308
+ await tx.readwrite("page").put(page);
1309
+ return page;
1310
+ }
1311
+ function promoteExternalNoteInPlace(existing, ownership, now, requestedRetention = "session-pinned") {
1312
+ const nextRetention = existing.retention === "session-pinned" || requestedRetention === "session-pinned" ? "session-pinned" : "schedule-pinned";
1313
+ const nextUpstreamStatus = existing.upstreamStatus ?? "live";
1314
+ const nextProvenance = existing.provenance ?? buildNoteProvenance(existing, ownership.sourceNotebookId ?? wodWikiWql.notebookOfItem(existing), now);
1315
+ const changed = existing.retention !== nextRetention || existing.upstreamStatus !== nextUpstreamStatus || !existing.provenance;
1316
+ if (!changed) return { updated: existing, changed: false };
1317
+ return {
1318
+ updated: {
1319
+ ...existing,
1320
+ retention: nextRetention,
1321
+ upstreamStatus: nextUpstreamStatus,
1322
+ provenance: nextProvenance
1323
+ },
1324
+ changed: true
1325
+ };
1326
+ }
1327
+ async function ensurePinnedExternalWorkout(storage, input) {
1328
+ const now = input.now ?? Date.now();
1329
+ const parsedRemote = parseRemoteNoteId(input.noteId);
1330
+ const initialCandidateId = parsedRemote.isRemote ? parsedRemote.uuid : input.noteId;
1331
+ let preloaded = await storage.readonly("notes").get(initialCandidateId) ?? (input.noteId !== initialCandidateId ? await storage.readonly("notes").get(input.noteId) : void 0);
1332
+ let materialized;
1333
+ if (!preloaded) {
1334
+ const resolved = input.remotePayload ?? (input.resolveRemoteWorkout ? await input.resolveRemoteWorkout(input.noteId) : void 0);
1335
+ if (!resolved) {
1336
+ throw new Error(`Note not found: ${input.noteId}`);
1337
+ }
1338
+ materialized = normalizeRemoteResolution(input.noteId, resolved, now);
1339
+ preloaded = await storage.readonly("notes").get(materialized.canonicalNoteId);
1340
+ }
1341
+ return storage.transaction(
1342
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment"],
1343
+ "readwrite",
1344
+ async (tx) => {
1345
+ const targetId = materialized?.canonicalNoteId ?? preloaded?.id ?? initialCandidateId;
1346
+ const existing = await tx.readonly("notes").get(targetId);
1347
+ if (existing) {
1348
+ const ownership2 = wodWikiCore.resolveNoteOwnership(
1349
+ existing,
1350
+ wodWikiWql.notebookOriginOfItem(existing),
1351
+ wodWikiWql.notebookOfItem(existing)
1352
+ );
1353
+ if (ownership2.kind === "user") {
1354
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, existing, now);
1355
+ return {
1356
+ note: existing,
1357
+ created: false,
1358
+ promotedFromLocal: false,
1359
+ ownership: ownership2
1360
+ };
1361
+ }
1362
+ const { updated, changed } = promoteExternalNoteInPlace(
1363
+ existing,
1364
+ ownership2,
1365
+ now,
1366
+ input.retention ?? "session-pinned"
1367
+ );
1368
+ if (changed) {
1369
+ await tx.readwrite("notes").put(updated);
1370
+ }
1371
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, updated, now);
1372
+ const nextOwnership = wodWikiCore.resolveNoteOwnership(
1373
+ updated,
1374
+ wodWikiWql.notebookOriginOfItem(updated),
1375
+ wodWikiWql.notebookOfItem(updated)
1376
+ );
1377
+ return {
1378
+ note: updated,
1379
+ created: false,
1380
+ promotedFromLocal: changed,
1381
+ ownership: nextOwnership
1382
+ };
1383
+ }
1384
+ if (!materialized) {
1385
+ throw new Error(`Note not found: ${input.noteId}`);
1386
+ }
1387
+ const newNote = {
1388
+ id: materialized.canonicalNoteId,
1389
+ title: materialized.title,
1390
+ rawContent: materialized.rawContent,
1391
+ sourceRevision: 1,
1392
+ blocks: materialized.blocks,
1393
+ ...materialized.date !== void 0 ? { date: materialized.date } : {},
1394
+ createdAt: materialized.createdAt,
1395
+ type: materialized.type,
1396
+ ...materialized.sourceId ? { sourceId: materialized.sourceId } : {},
1397
+ ...materialized.tags?.length ? { tags: materialized.tags } : {},
1398
+ seedOrigin: materialized.seedOrigin,
1399
+ seedVersion: materialized.seedVersion,
1400
+ ...materialized.seedChunkId ? { seedChunkId: materialized.seedChunkId } : {},
1401
+ ...materialized.feedOrigin ? { feedOrigin: materialized.feedOrigin } : {},
1402
+ ...materialized.feedSourceId ? { feedSourceId: materialized.feedSourceId } : {},
1403
+ ...materialized.sourcePath ? { sourcePath: materialized.sourcePath } : {},
1404
+ ...materialized.seedCommit ? { seedCommit: materialized.seedCommit } : {},
1405
+ retention: input.retention ?? "session-pinned",
1406
+ upstreamStatus: materialized.upstreamStatus,
1407
+ provenance: {
1408
+ sourceNoteId: materialized.canonicalNoteId,
1409
+ sourceVersion: materialized.seedVersion,
1410
+ ...materialized.seedCommit ? { sourceCommit: materialized.seedCommit } : {},
1411
+ ...materialized.feedSourceId ? { feedSourceId: materialized.feedSourceId } : {},
1412
+ ...materialized.sourceNotebookId ? { sourceNotebookId: materialized.sourceNotebookId } : {},
1413
+ ...materialized.sourcePath ? { sourcePath: materialized.sourcePath } : {},
1414
+ clonedAt: now
1415
+ }
1416
+ };
1417
+ await tx.readwrite("notes").put(newNote);
1418
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, newNote, now, materialized.seedRow);
1419
+ const ownership = wodWikiCore.resolveNoteOwnership(
1420
+ newNote,
1421
+ wodWikiWql.notebookOriginOfItem(newNote),
1422
+ wodWikiWql.notebookOfItem(newNote)
1423
+ );
1424
+ return {
1425
+ note: newNote,
1426
+ created: true,
1427
+ promotedFromLocal: false,
1428
+ ownership
1429
+ };
1430
+ }
1431
+ );
1432
+ }
1433
+ async function prepareJournalSessionRun(storage, input) {
1434
+ const startedAt = input.startedAt ?? Date.now();
1435
+ const sessionId = input.sessionId ?? mintUuid();
1436
+ const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
1437
+ const pinned = await ensurePinnedExternalWorkout(storage, {
1438
+ noteId: input.noteId,
1439
+ remotePayload: input.remotePayload,
1440
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
1441
+ now: startedAt
1442
+ });
1443
+ return storage.transaction(
1444
+ ["notes", "block_revisions", "block_index", "sessions", "page", "notebook_links"],
1445
+ "readwrite",
1446
+ async (tx) => {
1447
+ const sourceNote = await tx.readonly("notes").get(pinned.note.id);
1448
+ if (!sourceNote) {
1449
+ throw new Error(`Note not found: ${input.noteId}`);
1450
+ }
1451
+ const existingSession = await tx.readonly("sessions").get(sessionId);
1452
+ if (existingSession) {
1453
+ throw new Error(`Session already exists: ${sessionId}`);
1454
+ }
1455
+ const nbOrigin = wodWikiWql.notebookOriginOfItem(sourceNote);
1456
+ const resolvedNb = wodWikiWql.notebookOfItem(sourceNote);
1457
+ const ownership = wodWikiCore.resolveNoteOwnership(sourceNote, nbOrigin, resolvedNb);
1458
+ const selectedSourceBlock = selectWorkoutBlock(
1459
+ sourceNote,
1460
+ ownership.kind,
1461
+ input.blockId,
1462
+ input.blockContentId
1463
+ );
1464
+ if (!selectedSourceBlock || selectedSourceBlock.kind !== "wod") {
1465
+ throw new Error(`Selected workout block is unavailable on Note '${input.noteId}'.`);
1466
+ }
1467
+ const targetPage = await getOrCreateJournalPageInTx(tx, journalDate, startedAt);
1468
+ let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
1469
+ if (!revision) {
1470
+ revision = {
1471
+ noteId: sourceNote.id,
1472
+ blockId: selectedSourceBlock.id,
1473
+ version: selectedSourceBlock.version,
1474
+ kind: selectedSourceBlock.kind,
1475
+ rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
1476
+ savedAt: startedAt,
1477
+ ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
1478
+ ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
1479
+ };
1480
+ await tx.readwrite("block_revisions").put(revision);
1481
+ }
1482
+ const cid = computeWodContentId(revision.rawContent);
1483
+ if (ownership.kind !== "user") {
1484
+ const session2 = {
1485
+ id: sessionId,
1486
+ noteId: sourceNote.id,
1487
+ noteSourceRevision: sourceNote.sourceRevision,
1488
+ blockId: selectedSourceBlock.id,
1489
+ blockVersion: revision.version,
1490
+ ...cid ? { blockContentId: cid } : {},
1491
+ origin: input.origin ?? "journal",
1492
+ pageId: targetPage.id,
1493
+ sessionDate: journalDate,
1494
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
1495
+ status: "in-progress",
1496
+ startTime: startedAt,
1497
+ endTime: startedAt,
1498
+ duration: 0,
1499
+ completed: false,
1500
+ createdAt: startedAt,
1501
+ notebookIds: ["notebook/journal"]
1502
+ };
1503
+ return {
1504
+ note: sourceNote,
1505
+ revision,
1506
+ session: session2,
1507
+ clonedFromReadOnly: false,
1508
+ pinnedExternalWorkout: true,
1509
+ upstreamNoteId: sourceNote.id
1510
+ };
1511
+ }
1512
+ const isPlayground = sourceNote.type === "playground" || sourceNote.sourceId === "playground" || sourceNote.notebookId === "notebook/playground";
1513
+ const currentNotebooks = [
1514
+ .../* @__PURE__ */ new Set([
1515
+ ...isPlayground ? ["notebook/playground"] : [],
1516
+ ...sourceNote.notebookIds ?? [],
1517
+ ...sourceNote.notebookId ? [sourceNote.notebookId] : []
1518
+ ])
1519
+ ];
1520
+ const updatedNote = sourceNote.notebookIds !== void 0 && JSON.stringify(sourceNote.notebookIds) === JSON.stringify(currentNotebooks) ? sourceNote : { ...sourceNote, notebookIds: currentNotebooks };
1521
+ if (updatedNote !== sourceNote) {
1522
+ await tx.readwrite("notes").put(updatedNote);
1523
+ }
1524
+ const effectiveOrigin = input.origin ?? (isPlayground ? "playground" : "journal");
1525
+ const sessionNotebooks = currentNotebooks.length > 0 ? [...currentNotebooks] : ["notebook/journal"];
1526
+ const session = {
1527
+ id: sessionId,
1528
+ noteId: sourceNote.id,
1529
+ noteSourceRevision: sourceNote.sourceRevision,
1530
+ blockId: selectedSourceBlock.id,
1531
+ blockVersion: revision.version,
1532
+ ...cid ? { blockContentId: cid } : {},
1533
+ origin: effectiveOrigin,
1534
+ pageId: targetPage.id,
1535
+ sessionDate: journalDate,
1536
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
1537
+ status: "in-progress",
1538
+ startTime: startedAt,
1539
+ endTime: startedAt,
1540
+ duration: 0,
1541
+ completed: false,
1542
+ createdAt: startedAt,
1543
+ notebookIds: sessionNotebooks
1544
+ };
1545
+ const links = currentNotebooks.map((nbId) => ({
1546
+ id: makeNotebookLinkId(nbId, "note", sourceNote.id),
1547
+ notebookId: nbId,
1548
+ targetKind: "note",
1549
+ targetId: sourceNote.id,
1550
+ noteId: sourceNote.id,
1551
+ createdAt: startedAt
1552
+ }));
1553
+ if (links.length > 0) {
1554
+ await tx.readwrite("notebook_links").putMany(links);
1555
+ }
1556
+ return {
1557
+ note: updatedNote,
1558
+ revision,
1559
+ session,
1560
+ clonedFromReadOnly: false,
1561
+ pinnedExternalWorkout: false
1562
+ };
1563
+ }
1564
+ );
1565
+ }
1566
+ async function resolveUpstreamProvenance(storage, note) {
1567
+ const isExternalPinned = Boolean(note.id) && (note.retention === "session-pinned" || note.upstreamStatus !== void 0 || note.seedOrigin === "seed" || note.feedOrigin === "feed");
1568
+ const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : isExternalPinned ? note.id : void 0);
1569
+ if (!sourceNoteId) return null;
1570
+ if (note.id && sourceNoteId === note.id) {
1571
+ const status = note.upstreamStatus ?? "live";
1572
+ const isLive = status === "live";
1573
+ return {
1574
+ exists: isLive,
1575
+ sourceNoteId,
1576
+ ...isLive ? { currentUpstreamVersion: note.seedVersion ?? note.sourceRevision } : {},
1577
+ sourceVersion: note.provenance?.sourceVersion ?? note.seedVersion ?? note.sourceRevision,
1578
+ sourceCommit: note.provenance?.sourceCommit ?? note.seedCommit,
1579
+ feedSourceId: note.provenance?.feedSourceId ?? note.feedSourceId,
1580
+ sourceNotebookId: note.provenance?.sourceNotebookId,
1581
+ sourcePath: note.provenance?.sourcePath ?? note.sourcePath,
1582
+ upstreamStatus: status
1583
+ };
1584
+ }
1585
+ const upstream = await storage.readonly("notes").get(sourceNoteId);
1586
+ if (upstream) {
1587
+ const upstreamGone = upstream.upstreamStatus === "unsubscribed" || upstream.upstreamStatus === "removed";
1588
+ return {
1589
+ exists: !upstreamGone,
1590
+ sourceNoteId,
1591
+ title: upstream.title,
1592
+ sourceVersion: note.provenance?.sourceVersion,
1593
+ currentUpstreamVersion: upstream.seedVersion ?? upstream.sourceRevision,
1594
+ sourceCommit: note.provenance?.sourceCommit ?? upstream.seedCommit,
1595
+ feedSourceId: note.provenance?.feedSourceId ?? upstream.feedSourceId,
1596
+ sourceNotebookId: note.provenance?.sourceNotebookId ?? wodWikiWql.notebookOfItem(upstream),
1597
+ sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath,
1598
+ upstreamStatus: upstream.upstreamStatus ?? "live"
1599
+ };
1600
+ }
1601
+ return {
1602
+ exists: false,
1603
+ sourceNoteId,
1604
+ sourceVersion: note.provenance?.sourceVersion,
1605
+ sourceCommit: note.provenance?.sourceCommit,
1606
+ feedSourceId: note.provenance?.feedSourceId,
1607
+ sourceNotebookId: note.provenance?.sourceNotebookId,
1608
+ sourcePath: note.provenance?.sourcePath,
1609
+ ...note.upstreamStatus ? { upstreamStatus: note.upstreamStatus } : {}
1610
+ };
1611
+ }
1612
+ function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
1613
+ return {
1614
+ sourceNoteId: sourceNote.id,
1615
+ sourceVersion: sourceNote.seedVersion ?? sourceNote.sourceRevision,
1616
+ ...sourceNote.seedCommit ? { sourceCommit: sourceNote.seedCommit } : {},
1617
+ ...sourceNote.feedSourceId ? { feedSourceId: sourceNote.feedSourceId } : {},
1618
+ ...sourceNotebookId ? { sourceNotebookId } : {},
1619
+ ...sourceNote.sourcePath ? { sourcePath: sourceNote.sourcePath } : {},
1620
+ clonedAt
1621
+ };
1622
+ }
1623
+
1624
+ // src/notebook/schedule.ts
1625
+ function mintUuid2() {
1626
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1627
+ return crypto.randomUUID();
1628
+ }
1629
+ const bytes = new Uint8Array(16);
1630
+ crypto.getRandomValues(bytes);
1631
+ bytes[6] = bytes[6] & 15 | 64;
1632
+ bytes[8] = bytes[8] & 63 | 128;
1633
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1634
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1635
+ }
1636
+ function localCivilDateKey(ms = Date.now(), timeZone) {
1637
+ const d = new Date(ms);
1638
+ const y = d.getFullYear();
1639
+ const m = String(d.getMonth() + 1).padStart(2, "0");
1640
+ const day = String(d.getDate()).padStart(2, "0");
1641
+ return `${y}-${m}-${day}`;
1642
+ }
1643
+ function normalizeCivilDate(input, nowMs = Date.now(), timeZone) {
1644
+ if (!input || input.trim().toLowerCase() === "today") {
1645
+ return localCivilDateKey(nowMs);
1646
+ }
1647
+ const trimmed = input.trim();
1648
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
1649
+ throw new Error(`Invalid civil date '${input}'; expected YYYY-MM-DD or 'today'.`);
1650
+ }
1651
+ return trimmed;
1652
+ }
1653
+ async function getOrCreatePageForDateInTx(tx, dateKey, now) {
1654
+ let existing;
1655
+ try {
1656
+ existing = await tx.readonly("page").getAllFromIndex("by-date", dateKey);
1657
+ } catch {
1658
+ existing = (await tx.readonly("page").getAll()).filter((p) => p.date === dateKey);
1659
+ }
1660
+ if (existing[0]) return existing[0];
1661
+ const created = {
1662
+ id: mintUuid2(),
1663
+ date: dateKey,
1664
+ title: dateKey,
1665
+ createdAt: now
1666
+ };
1667
+ await tx.readwrite("page").put(created);
1668
+ return created;
1669
+ }
1670
+ async function noteHasRecordedSessionsInTx(tx, noteId) {
1671
+ try {
1672
+ const count = await tx.readonly("sessions").countFromIndex("by-note", noteId);
1673
+ if (count > 0) return true;
1674
+ } catch {
1675
+ const all = await tx.readonly("sessions").getAll();
1676
+ return all.some((s) => s.noteId === noteId);
1677
+ }
1678
+ return false;
1679
+ }
1680
+ async function snapshotNoteRevisionIfHasSessionsInTx(tx, previous, now = Date.now()) {
1681
+ if (!previous) return void 0;
1682
+ const hasSessions = await noteHasRecordedSessionsInTx(tx, previous.id);
1683
+ if (!hasSessions) return void 0;
1684
+ const existingRev = await tx.readonly("note_revisions").get([previous.id, previous.sourceRevision]).catch(() => void 0);
1685
+ if (existingRev) return existingRev;
1686
+ const snapshot = {
1687
+ noteId: previous.id,
1688
+ version: previous.sourceRevision,
1689
+ title: previous.title,
1690
+ rawContent: previous.rawContent,
1691
+ ...previous.tags ? { tags: [...previous.tags] } : {},
1692
+ ...previous.type ? { type: previous.type } : {},
1693
+ ...previous.notebookIds ? { notebookIds: [...previous.notebookIds] } : {},
1694
+ blocks: structuredClone(previous.blocks),
1695
+ savedAt: now
1696
+ };
1697
+ await tx.readwrite("note_revisions").put(snapshot);
1698
+ return snapshot;
1699
+ }
1700
+ async function listNoteRevisions(storage, noteId) {
1701
+ try {
1702
+ const rows = await storage.readonly("note_revisions").getAllFromIndex("by-note", noteId);
1703
+ return rows.sort((a, b) => b.version - a.version);
1704
+ } catch {
1705
+ const all = await storage.readonly("note_revisions").getAll();
1706
+ return all.filter((r) => r.noteId === noteId).sort((a, b) => b.version - a.version);
1707
+ }
1708
+ }
1709
+ async function scheduleNoteOnDate(storage, input) {
1710
+ const now = input.now ?? Date.now();
1711
+ const dateKey = normalizeCivilDate(input.date, now);
1712
+ const pinned = await ensurePinnedExternalWorkout(storage, {
1713
+ noteId: input.noteId,
1714
+ remotePayload: input.remotePayload,
1715
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
1716
+ retention: "schedule-pinned",
1717
+ now
1718
+ });
1719
+ return storage.transaction(
1720
+ ["schedule_items", "page", "notes"],
1721
+ "readwrite",
1722
+ async (tx) => {
1723
+ const note = await tx.readonly("notes").get(pinned.note.id) ?? pinned.note;
1724
+ const page = await getOrCreatePageForDateInTx(tx, dateKey, now);
1725
+ let existingForDate;
1726
+ try {
1727
+ existingForDate = await tx.readonly("schedule_items").getAllFromIndex("by-date", dateKey);
1728
+ } catch {
1729
+ existingForDate = (await tx.readonly("schedule_items").getAll()).filter((s) => s.date === dateKey);
1730
+ }
1731
+ const nextPos = input.position ?? existingForDate.reduce((max, item2) => Math.max(max, item2.position), -1) + 1;
1732
+ const resolvedNb = input.sourceNotebookId ?? wodWikiWql.notebookOfItem(note) ?? pinned.ownership.sourceNotebookId;
1733
+ const item = {
1734
+ id: input.id ?? mintUuid2(),
1735
+ date: dateKey,
1736
+ noteId: note.id,
1737
+ pageId: page.id,
1738
+ ...resolvedNb ? { sourceNotebookId: wodWikiCore.toNotebookId(resolvedNb) } : {},
1739
+ ...note.title ? { fallbackTitle: note.title } : {},
1740
+ ...input.blockId ? { blockId: input.blockId } : {},
1741
+ position: nextPos,
1742
+ ...input.slot?.trim() ? { slot: input.slot.trim() } : {},
1743
+ status: input.status ?? "planned",
1744
+ ...input.notes !== void 0 && input.notes.trim() ? { notes: input.notes.trim() } : {},
1745
+ createdAt: now,
1746
+ updatedAt: now
1747
+ };
1748
+ await tx.readwrite("schedule_items").put(item);
1749
+ return item;
1001
1750
  }
1002
- const primaryUserNb = finalMemberships.find(
1003
- (id) => id !== "notebook/journal" && id !== "notebook/playground"
1004
- );
1005
- const { notebookId: _priorSingle, ...rest } = note;
1006
- const updatedNote = {
1007
- ...rest,
1008
- notebookIds: finalMemberships,
1009
- ...primaryUserNb ? { notebookId: primaryUserNb } : {}
1751
+ );
1752
+ }
1753
+ async function batchScheduleNotes(storage, entries) {
1754
+ const created = [];
1755
+ for (const entry of entries) {
1756
+ created.push(await scheduleNoteOnDate(storage, entry));
1757
+ }
1758
+ return created;
1759
+ }
1760
+ async function updateScheduleItem(storage, id, patch) {
1761
+ const now = patch.now ?? Date.now();
1762
+ return storage.transaction(["schedule_items", "page"], "readwrite", async (tx) => {
1763
+ const existing = await tx.readonly("schedule_items").get(id);
1764
+ if (!existing) throw new Error(`ScheduleItem not found: ${id}`);
1765
+ const nextDate = patch.date !== void 0 ? normalizeCivilDate(patch.date, now) : existing.date;
1766
+ let nextPageId = existing.pageId;
1767
+ let movedFromDate = existing.movedFromDate;
1768
+ let nextStatus = patch.status ?? existing.status;
1769
+ if (nextDate !== existing.date) {
1770
+ const page = await getOrCreatePageForDateInTx(tx, nextDate, now);
1771
+ nextPageId = page.id;
1772
+ if (patch.status === void 0 && existing.status === "planned") {
1773
+ movedFromDate = existing.date;
1774
+ } else if (patch.status === "moved") {
1775
+ movedFromDate = existing.date;
1776
+ }
1777
+ }
1778
+ const updated = {
1779
+ ...existing,
1780
+ date: nextDate,
1781
+ ...nextPageId ? { pageId: nextPageId } : {},
1782
+ position: patch.position ?? existing.position,
1783
+ status: nextStatus,
1784
+ ...movedFromDate ? { movedFromDate } : {},
1785
+ updatedAt: now
1010
1786
  };
1011
- await tx.readwrite("notes").put(updatedNote);
1012
- return finalMemberships;
1787
+ if (patch.slot === null) delete updated.slot;
1788
+ else if (patch.slot !== void 0) updated.slot = patch.slot.trim() || void 0;
1789
+ if (patch.notes === null) delete updated.notes;
1790
+ else if (patch.notes !== void 0) updated.notes = patch.notes.trim() || void 0;
1791
+ if (patch.blockId === null) delete updated.blockId;
1792
+ else if (patch.blockId !== void 0) updated.blockId = patch.blockId.trim() || void 0;
1793
+ await tx.readwrite("schedule_items").put(updated);
1794
+ return updated;
1013
1795
  });
1014
1796
  }
1015
- async function removeNoteFromNotebook(storage, noteId, notebookIdOrSlug) {
1016
- const target = wodWikiCore.toNotebookId(notebookIdOrSlug);
1017
- if (target === "notebook/journal") {
1018
- throw new Error("Notes cannot be removed from private notebook/journal.");
1797
+ async function removeScheduleItem(storage, id) {
1798
+ return storage.transaction(["schedule_items"], "readwrite", async (tx) => {
1799
+ const existing = await tx.readonly("schedule_items").get(id);
1800
+ if (!existing) return false;
1801
+ await tx.readwrite("schedule_items").delete(id);
1802
+ return true;
1803
+ });
1804
+ }
1805
+ async function listScheduleItemsByDateRange(storage, fromDate, toDate) {
1806
+ const fromKey = normalizeCivilDate(fromDate);
1807
+ const toKey = normalizeCivilDate(toDate);
1808
+ let rows;
1809
+ try {
1810
+ rows = await storage.readonly("schedule_items").getAll();
1811
+ } catch {
1812
+ rows = [];
1019
1813
  }
1020
- const current = await getNoteNotebooks(storage, noteId);
1021
- const remaining = current.filter((id) => id !== target);
1022
- return setNoteNotebooks(storage, { noteId, notebookIds: remaining });
1814
+ return rows.filter((item) => item.date >= fromKey && item.date <= toKey).sort((a, b) => a.date.localeCompare(b.date) || a.position - b.position || a.createdAt - b.createdAt);
1023
1815
  }
1024
- async function getNoteNotebooks(storage, noteId) {
1025
- const note = await storage.readonly("notes").get(noteId);
1026
- if (!note) return [];
1027
- let linkNotebookIds = [];
1816
+ async function listScheduleItemsForNote(storage, noteId) {
1817
+ let rows;
1028
1818
  try {
1029
- const links = await storage.readonly("notebook_links").getAllFromIndex("by-note", noteId);
1030
- linkNotebookIds = links.filter((l) => l.targetKind === "note" && l.targetId === noteId).map((l) => l.notebookId);
1819
+ rows = await storage.readonly("schedule_items").getAllFromIndex("by-note", noteId);
1031
1820
  } catch {
1821
+ rows = (await storage.readonly("schedule_items").getAll()).filter((item) => item.noteId === noteId);
1032
1822
  }
1033
- return dedupeNotebooks([
1034
- ...baseUserMemberships(note),
1035
- ...note.notebookIds ?? [],
1036
- ...linkNotebookIds,
1037
- ...wodWikiWql.notebooksOfItem(note)
1823
+ return rows.sort((a, b) => a.date.localeCompare(b.date) || a.position - b.position);
1824
+ }
1825
+ async function attributeSession(storage, input) {
1826
+ const now = input.now ?? Date.now();
1827
+ return storage.transaction(["sessions", "schedule_items", "page"], "readwrite", async (tx) => {
1828
+ const session = await tx.readonly("sessions").get(input.sessionId);
1829
+ if (!session) throw new Error(`Session not found: ${input.sessionId}`);
1830
+ let nextSessionDate = session.sessionDate;
1831
+ let nextPageId = session.pageId;
1832
+ let nextScheduleItemId = session.scheduleItemId;
1833
+ if (input.scheduleItemId === null) {
1834
+ if (session.scheduleItemId) {
1835
+ const prevItem = await tx.readonly("schedule_items").get(session.scheduleItemId);
1836
+ if (prevItem && prevItem.status === "completed") {
1837
+ await tx.readwrite("schedule_items").put({
1838
+ ...prevItem,
1839
+ status: "planned",
1840
+ updatedAt: now
1841
+ });
1842
+ }
1843
+ }
1844
+ nextScheduleItemId = void 0;
1845
+ } else if (input.scheduleItemId !== void 0) {
1846
+ const targetItem = await tx.readonly("schedule_items").get(input.scheduleItemId);
1847
+ if (!targetItem) throw new Error(`ScheduleItem not found: ${input.scheduleItemId}`);
1848
+ if (session.scheduleItemId && session.scheduleItemId !== targetItem.id) {
1849
+ const prevItem = await tx.readonly("schedule_items").get(session.scheduleItemId);
1850
+ if (prevItem && prevItem.status === "completed") {
1851
+ await tx.readwrite("schedule_items").put({
1852
+ ...prevItem,
1853
+ status: "planned",
1854
+ updatedAt: now
1855
+ });
1856
+ }
1857
+ }
1858
+ nextScheduleItemId = targetItem.id;
1859
+ if (input.sessionDate === void 0) {
1860
+ nextSessionDate = targetItem.date;
1861
+ }
1862
+ if (targetItem.status !== "completed") {
1863
+ await tx.readwrite("schedule_items").put({
1864
+ ...targetItem,
1865
+ status: "completed",
1866
+ updatedAt: now
1867
+ });
1868
+ }
1869
+ }
1870
+ if (input.sessionDate !== void 0) {
1871
+ nextSessionDate = normalizeCivilDate(input.sessionDate, now);
1872
+ }
1873
+ if (nextSessionDate) {
1874
+ const page = await getOrCreatePageForDateInTx(tx, nextSessionDate, now);
1875
+ nextPageId = page.id;
1876
+ }
1877
+ const updated = {
1878
+ ...session,
1879
+ ...nextPageId !== void 0 ? { pageId: nextPageId } : {},
1880
+ ...nextSessionDate !== void 0 ? { sessionDate: nextSessionDate } : {}
1881
+ };
1882
+ if (nextScheduleItemId !== void 0) updated.scheduleItemId = nextScheduleItemId;
1883
+ else delete updated.scheduleItemId;
1884
+ await tx.readwrite("sessions").put(updated);
1885
+ return updated;
1886
+ });
1887
+ }
1888
+ function resolveSessionCivilDate(session, pageDateById, sessionPageId) {
1889
+ if (session.sessionDate) return session.sessionDate;
1890
+ if (sessionPageId && pageDateById?.has(sessionPageId)) {
1891
+ return pageDateById.get(sessionPageId);
1892
+ }
1893
+ return localCivilDateKey(session.startTime || session.createdAt);
1894
+ }
1895
+ async function getJournalDayOverlay(storage, rawDate) {
1896
+ const dateKey = normalizeCivilDate(rawDate);
1897
+ const [pages, daySchedules, allSessions, allNotes] = await Promise.all([
1898
+ storage.readonly("page").getAll().catch(() => []),
1899
+ listScheduleItemsByDateRange(storage, dateKey, dateKey),
1900
+ storage.readonly("sessions").getAll().catch(() => []),
1901
+ storage.readonly("notes").getAll().catch(() => [])
1038
1902
  ]);
1903
+ const pageDateById = /* @__PURE__ */ new Map();
1904
+ let pageId = null;
1905
+ for (const p of pages) {
1906
+ if (p.date) {
1907
+ pageDateById.set(p.id, p.date);
1908
+ if (p.date === dateKey && !pageId) pageId = p.id;
1909
+ }
1910
+ }
1911
+ const notesById = new Map(allNotes.map((n) => [n.id, n]));
1912
+ const daySessions = allSessions.filter((s) => resolveSessionCivilDate(s, pageDateById, s.pageId) === dateKey).sort((a, b) => a.startTime - b.startTime);
1913
+ const pairedByScheduleId = /* @__PURE__ */ new Map();
1914
+ const pairedSessionIds = /* @__PURE__ */ new Set();
1915
+ for (const s of daySessions) {
1916
+ if (!s.scheduleItemId) continue;
1917
+ const match = daySchedules.find((item) => item.id === s.scheduleItemId);
1918
+ if (match) {
1919
+ const bucket = pairedByScheduleId.get(match.id) ?? [];
1920
+ bucket.push(s);
1921
+ pairedByScheduleId.set(match.id, bucket);
1922
+ pairedSessionIds.add(s.id);
1923
+ }
1924
+ }
1925
+ const planned = daySchedules.map((item) => ({
1926
+ item,
1927
+ note: notesById.get(item.noteId),
1928
+ pairedSessions: pairedByScheduleId.get(item.id) ?? []
1929
+ }));
1930
+ const adhocSessions = daySessions.filter((s) => !pairedSessionIds.has(s.id)).map((session) => ({
1931
+ session,
1932
+ note: notesById.get(session.noteId)
1933
+ }));
1934
+ return {
1935
+ date: dateKey,
1936
+ pageId,
1937
+ planned,
1938
+ adhocSessions,
1939
+ allSessions: daySessions
1940
+ };
1039
1941
  }
1040
1942
  var SEED_SCHEMA = 9;
1041
1943
  var SEED_REGISTERED_WIDGETS = wodWikiCore.KNOWN_SECTION_WIDGETS;
@@ -1058,11 +1960,15 @@ function seedSourceTier(sourceIdOrMetaKey, explicitTier) {
1058
1960
  function seedPrecedenceRank(sourceIdOrMetaKey, explicitTier) {
1059
1961
  return SEED_PRECEDENCE_RANK[seedSourceTier(sourceIdOrMetaKey, explicitTier)];
1060
1962
  }
1963
+ var FEED_INDEX_META_PREFIX = "feed:index:";
1061
1964
  var EFFORTS_CHUNK_ID = "efforts";
1062
1965
  var EQUIPMENT_CHUNK_ID = "equipment";
1063
1966
  function seedMetaKey(sourceId) {
1064
1967
  return `seed:${sourceId}`;
1065
1968
  }
1969
+ function emptySeedMeta(key) {
1970
+ return { key, schema: SEED_SCHEMA, seedVersion: 0, builtAt: "", importedAt: 0, chunks: {}, claim: null };
1971
+ }
1066
1972
  function notebookSlugForChunkId(chunkId) {
1067
1973
  const value = /^notebook\.(.+)$/.exec(chunkId)?.[1];
1068
1974
  return value && value !== "_root" ? value : void 0;
@@ -1233,22 +2139,58 @@ function buildQueryServiceStoresFromStorage(storage, options = {}) {
1233
2139
  relationStore: {
1234
2140
  getBatches: async (noteIds) => {
1235
2141
  const bundles = /* @__PURE__ */ new Map();
1236
- for (const noteId of noteIds) {
1237
- const links = await storage.readonly("page_notes").getAllFromIndex("by-note", noteId);
1238
- const tagLinks = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
1239
- const tags = await storage.readonly("tags").getMany(tagLinks.map((l) => l.tagId));
1240
- const pages = await storage.readonly("page").getMany([...new Set(links.map((l) => l.pageId))]);
1241
- bundles.set(noteId, {
1242
- tags: tags.flatMap((t) => t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : []),
1243
- links,
1244
- pages: pages.filter((p) => p !== void 0)
1245
- });
1246
- }
1247
- return bundles;
2142
+ const uniqueIds = [...new Set(noteIds)];
2143
+ if (uniqueIds.length === 0) return bundles;
2144
+ return storage.transaction(["page_notes", "note_tags", "tags", "page"], "readonly", async (tx) => {
2145
+ const [pageLinkGroups, tagLinkGroups] = await Promise.all([
2146
+ tx.readonly("page_notes").getAllFromIndexMany("by-note", uniqueIds),
2147
+ tx.readonly("note_tags").getAllFromIndexMany("by-note", uniqueIds)
2148
+ ]);
2149
+ const tagIds = /* @__PURE__ */ new Set();
2150
+ const pageIds = /* @__PURE__ */ new Set();
2151
+ for (const group of tagLinkGroups) for (const link of group) tagIds.add(link.tagId);
2152
+ for (const group of pageLinkGroups) for (const link of group) pageIds.add(link.pageId);
2153
+ const [tagRows, pageRows] = await Promise.all([
2154
+ tx.readonly("tags").getMany([...tagIds]),
2155
+ tx.readonly("page").getMany([...pageIds])
2156
+ ]);
2157
+ const tagById = new Map([...tagIds].map((id, i) => [id, tagRows[i]]));
2158
+ const pageById = new Map([...pageIds].map((id, i) => [id, pageRows[i]]));
2159
+ for (let i = 0; i < uniqueIds.length; i++) {
2160
+ const noteId = uniqueIds[i];
2161
+ const links = pageLinkGroups[i] ?? [];
2162
+ const tagLinks = tagLinkGroups[i] ?? [];
2163
+ bundles.set(noteId, {
2164
+ tags: tagLinks.flatMap((l) => {
2165
+ const t = tagById.get(l.tagId);
2166
+ return t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : [];
2167
+ }),
2168
+ links,
2169
+ pages: links.flatMap((l) => {
2170
+ const p = pageById.get(l.pageId);
2171
+ return p ? [p] : [];
2172
+ })
2173
+ });
2174
+ }
2175
+ return bundles;
2176
+ });
1248
2177
  }
1249
2178
  },
1250
2179
  feedCatalogStore
1251
2180
  };
2181
+ const scheduleStore = {
2182
+ getAll: async () => storage.readonly("schedule_items").getAll().catch(() => []),
2183
+ getForNote: async (noteId) => storage.readonly("schedule_items").getAllFromIndex("by-note", noteId).catch(() => []),
2184
+ getByDateRange: async (fromDate, toDate) => {
2185
+ try {
2186
+ return (await storage.readonly("schedule_items").getAll()).filter(
2187
+ (item) => item.date >= fromDate && item.date <= toDate
2188
+ );
2189
+ } catch {
2190
+ return [];
2191
+ }
2192
+ }
2193
+ };
1252
2194
  const sessionStore = {
1253
2195
  getAll: async () => {
1254
2196
  const rows = await storage.readonly("sessions").getAll();
@@ -1261,11 +2203,13 @@ function buildQueryServiceStoresFromStorage(storage, options = {}) {
1261
2203
  createdAt: s.createdAt,
1262
2204
  ...s.notebookIds ? { notebookIds: s.notebookIds } : {},
1263
2205
  ...s.blockContentId ? { blockContentId: s.blockContentId } : {},
1264
- ...s.completed !== void 0 ? { completed: s.completed } : {}
2206
+ ...s.completed !== void 0 ? { completed: s.completed } : {},
2207
+ ...s.sessionDate ? { sessionDate: s.sessionDate } : {},
2208
+ ...s.scheduleItemId ? { scheduleItemId: s.scheduleItemId } : {}
1265
2209
  }));
1266
2210
  }
1267
2211
  };
1268
- Object.assign(stores, { sessionStore });
2212
+ Object.assign(stores, { scheduleStore, sessionStore });
1269
2213
  if (options.datasetStore) {
1270
2214
  stores.datasetStore = options.datasetStore;
1271
2215
  }
@@ -1363,6 +2307,7 @@ async function upsertNoteInStorage(storage, input) {
1363
2307
  [
1364
2308
  "notes",
1365
2309
  "block_revisions",
2310
+ "note_revisions",
1366
2311
  "block_index",
1367
2312
  "block_efforts",
1368
2313
  "block_equipment",
@@ -1372,6 +2317,8 @@ async function upsertNoteInStorage(storage, input) {
1372
2317
  "note_tags",
1373
2318
  "page",
1374
2319
  "page_notes",
2320
+ "schedule_items",
2321
+ "sessions",
1375
2322
  "notebook_links"
1376
2323
  ],
1377
2324
  "readwrite",
@@ -1440,13 +2387,19 @@ async function upsertNoteInStorage(storage, input) {
1440
2387
  }
1441
2388
  const resolvedTitle = input.title ?? stampedIdentity?.title ?? extractHeadingTitleFromMarkdown(input.rawContent) ?? existing?.title ?? "Untitled Workout";
1442
2389
  const targetNotebookId = input.notebookId ? wodWikiCore.toNotebookId(input.notebookId) : existing?.notebookId;
1443
- const notebookIds = Array.from(
1444
- /* @__PURE__ */ new Set([
1445
- "notebook/journal",
1446
- ...existing?.notebookIds ?? [],
1447
- ...targetNotebookId ? [targetNotebookId] : []
1448
- ])
1449
- );
2390
+ const notebookIds = targetNotebookId ? Array.from(/* @__PURE__ */ new Set([...existing?.notebookIds ?? [], targetNotebookId])) : existing ? [...existing.notebookIds ?? []] : [];
2391
+ const nextTagLabels = extractedTags.map((t) => t.label);
2392
+ const nextNoteType = input.type ?? existing?.type ?? (input.journalDate ? "journal" : "note");
2393
+ if (existing) {
2394
+ const meaningfulChange = existing.rawContent !== input.rawContent || existing.title !== resolvedTitle || existing.type !== nextNoteType || !wodWikiStorage.rowsEqual(existing.blocks, blocks) || !wodWikiStorage.rowsEqual(existing.tags ?? [], nextTagLabels);
2395
+ if (meaningfulChange && await noteHasRecordedSessionsInTx(tx, noteId)) {
2396
+ await snapshotNoteRevisionIfHasSessionsInTx(tx, existing, now);
2397
+ if (sourceRevision <= existing.sourceRevision) {
2398
+ sourceRevision = existing.sourceRevision + 1;
2399
+ for (const block of Object.values(blocks)) block.sourceRevision = sourceRevision;
2400
+ }
2401
+ }
2402
+ }
1450
2403
  const dateMs = input.journalDate ? Date.parse(`${civilDateKey(input.journalDate, now)}T12:00:00Z`) : existing?.date ?? now;
1451
2404
  const note = {
1452
2405
  ...existing ?? {},
@@ -1455,12 +2408,12 @@ async function upsertNoteInStorage(storage, input) {
1455
2408
  rawContent: input.rawContent,
1456
2409
  sourceRevision,
1457
2410
  blocks,
1458
- type: input.type ?? existing?.type ?? (input.journalDate ? "journal" : "note"),
2411
+ type: nextNoteType,
1459
2412
  date: dateMs,
1460
2413
  createdAt: existing?.createdAt ?? now,
1461
2414
  notebookIds,
1462
2415
  ...targetNotebookId && targetNotebookId !== "notebook/journal" ? { notebookId: targetNotebookId } : {},
1463
- tags: extractedTags.map((t) => t.label),
2416
+ tags: nextTagLabels,
1464
2417
  seedOrigin: "user"
1465
2418
  };
1466
2419
  const storedEfforts = await tx.readonly("efforts").getAll();
@@ -1587,6 +2540,7 @@ async function upsertNoteInStorage(storage, input) {
1587
2540
  if (links.length > 0) {
1588
2541
  await tx.readwrite("notebook_links").putMany(links);
1589
2542
  }
2543
+ let scheduleItemId;
1590
2544
  if (input.journalDate) {
1591
2545
  const dateKey = civilDateKey(input.journalDate, now);
1592
2546
  let pages;
@@ -1619,6 +2573,33 @@ async function upsertNoteInStorage(storage, input) {
1619
2573
  createdAt: now
1620
2574
  });
1621
2575
  }
2576
+ try {
2577
+ const existingSchedules = await tx.readonly("schedule_items").getAllFromIndex("by-date", dateKey);
2578
+ const matchedSched = existingSchedules.find((s) => s.noteId === noteId);
2579
+ if (matchedSched) {
2580
+ scheduleItemId = matchedSched.id;
2581
+ } else {
2582
+ const maxSchedPos = existingSchedules.reduce(
2583
+ (m, s) => typeof s.position === "number" && s.position > m ? s.position : m,
2584
+ -1
2585
+ );
2586
+ const nextSchedId = mintAgentUuid();
2587
+ await tx.readwrite("schedule_items").put({
2588
+ id: nextSchedId,
2589
+ date: dateKey,
2590
+ noteId,
2591
+ pageId: targetPage.id,
2592
+ ...note.notebookId ? { sourceNotebookId: note.notebookId } : {},
2593
+ fallbackTitle: note.title,
2594
+ position: maxSchedPos + 1,
2595
+ status: "planned",
2596
+ createdAt: now,
2597
+ updatedAt: now
2598
+ });
2599
+ scheduleItemId = nextSchedId;
2600
+ }
2601
+ } catch {
2602
+ }
1622
2603
  }
1623
2604
  return {
1624
2605
  note,
@@ -1626,7 +2607,8 @@ async function upsertNoteInStorage(storage, input) {
1626
2607
  blockCount: nextRows.length,
1627
2608
  effortSlugs: [...allEffortSlugs],
1628
2609
  equipmentSlugs: [...allEquipSlugs],
1629
- tagLabels: extractedTags.map((t) => t.label)
2610
+ tagLabels: extractedTags.map((t) => t.label),
2611
+ ...scheduleItemId ? { scheduleItemId } : {}
1630
2612
  };
1631
2613
  }
1632
2614
  );
@@ -1641,6 +2623,7 @@ async function deleteNoteFromStorage(storage, noteId) {
1641
2623
  "block_efforts",
1642
2624
  "block_equipment",
1643
2625
  "page_notes",
2626
+ "schedule_items",
1644
2627
  "notebook_links",
1645
2628
  "meta"
1646
2629
  ],
@@ -1667,6 +2650,12 @@ async function deleteNoteFromStorage(storage, noteId) {
1667
2650
  for (const pn of await tx.readonly("page_notes").getAllFromIndex("by-note", noteId)) {
1668
2651
  await tx.readwrite("page_notes").delete(pn.id);
1669
2652
  }
2653
+ try {
2654
+ for (const sched of await tx.readonly("schedule_items").getAllFromIndex("by-note", noteId)) {
2655
+ await tx.readwrite("schedule_items").delete(sched.id);
2656
+ }
2657
+ } catch {
2658
+ }
1670
2659
  try {
1671
2660
  for (const nl of await tx.readonly("notebook_links").getAllFromIndex("by-note", noteId)) {
1672
2661
  await tx.readwrite("notebook_links").delete(nl.id);
@@ -2316,6 +3305,37 @@ var wodCatalogUpsertTool = defineAgentTool({
2316
3305
  });
2317
3306
  var CATALOG_AGENT_TOOLS = [wodCatalogLookupTool, wodCatalogUpsertTool];
2318
3307
  var FEED_SUBSCRIPTIONS_META_KEY = "feed:subscriptions";
3308
+ var FEED_REGISTRY_META_KEY = "feed:registry";
3309
+ async function noteHasSessions(tx, noteId) {
3310
+ const sessionStore = tx.readonly("sessions");
3311
+ try {
3312
+ if (typeof sessionStore.countFromIndex === "function") {
3313
+ return await sessionStore.countFromIndex("by-note", noteId) > 0;
3314
+ }
3315
+ const rows = await sessionStore.getAllFromIndex("by-note", noteId);
3316
+ return rows.length > 0;
3317
+ } catch {
3318
+ const all = await sessionStore.getAll();
3319
+ return all.some((s) => s.noteId === noteId);
3320
+ }
3321
+ }
3322
+ async function noteHasScheduleItems(tx, noteId) {
3323
+ try {
3324
+ const schedStore = tx.readonly("schedule_items");
3325
+ if (typeof schedStore.countFromIndex === "function") {
3326
+ return await schedStore.countFromIndex("by-note", noteId) > 0;
3327
+ }
3328
+ const rows = await schedStore.getAllFromIndex("by-note", noteId);
3329
+ return rows.length > 0;
3330
+ } catch {
3331
+ try {
3332
+ const all = await tx.readonly("schedule_items").getAll();
3333
+ return all.some((s) => s.noteId === noteId);
3334
+ } catch {
3335
+ return false;
3336
+ }
3337
+ }
3338
+ }
2319
3339
  async function removeSeedSourceContent(storage, meta) {
2320
3340
  return storage.transaction(
2321
3341
  [
@@ -2327,13 +3347,18 @@ async function removeSeedSourceContent(storage, meta) {
2327
3347
  "block_efforts",
2328
3348
  "block_equipment",
2329
3349
  "page_notes",
3350
+ "schedule_items",
2330
3351
  "efforts",
2331
3352
  "equipment",
2332
3353
  "property_overrides",
3354
+ "sessions",
2333
3355
  "meta"
2334
3356
  ],
2335
3357
  "readwrite",
2336
3358
  async (tx) => {
3359
+ const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
3360
+ const chunkKeys = Object.keys(meta.chunks);
3361
+ const isWholeFeedSweep = chunkKeys.length === 0 || Object.values(meta.chunks).length > 0;
2337
3362
  const targetIds = /* @__PURE__ */ new Set();
2338
3363
  const legacyChunks = [];
2339
3364
  for (const [chunkId, chunk] of Object.entries(meta.chunks)) {
@@ -2343,16 +3368,31 @@ async function removeSeedSourceContent(storage, meta) {
2343
3368
  legacyChunks.push(chunkId);
2344
3369
  }
2345
3370
  }
3371
+ const allNotes = legacyChunks.length || isWholeFeedSweep ? await tx.readwrite("notes").getAll() : [];
2346
3372
  if (legacyChunks.length) {
2347
- for (const note of await tx.readwrite("notes").getAll()) {
3373
+ for (const note of allNotes) {
2348
3374
  if (note.seedOrigin === "seed" && note.seedChunkId && legacyChunks.includes(note.seedChunkId)) {
2349
3375
  targetIds.add(note.id);
2350
3376
  }
2351
3377
  }
2352
3378
  }
3379
+ if (isWholeFeedSweep) {
3380
+ for (const note of allNotes) {
3381
+ const rNote = note;
3382
+ if (note.seedOrigin === "seed" && note.feedSourceId === removedSourceId && (chunkKeys.length === 0 || rNote.retention === "cached" || rNote.retention === "schedule-pinned" || rNote.retention === "session-pinned")) {
3383
+ targetIds.add(note.id);
3384
+ }
3385
+ }
3386
+ }
2353
3387
  const metaStore = tx.readwrite("meta");
2354
3388
  const otherCheckpoints = [];
3389
+ const indexKeysToDelete = [];
3390
+ const indexPrefix = `${FEED_INDEX_META_PREFIX}${removedSourceId}:`;
2355
3391
  for (const row of await metaStore.getAll()) {
3392
+ const key = row?.key;
3393
+ if (typeof key === "string" && key.startsWith(indexPrefix)) {
3394
+ indexKeysToDelete.push(key);
3395
+ }
2356
3396
  const other = row;
2357
3397
  if (!other || typeof other.key !== "string" || !other.key.startsWith("seed:") || other.key === meta.key) {
2358
3398
  continue;
@@ -2371,50 +3411,28 @@ async function removeSeedSourceContent(storage, meta) {
2371
3411
  }
2372
3412
  otherCheckpoints.sort((a, b) => b.rank - a.rank);
2373
3413
  const isClaimedByOther = (noteId) => otherCheckpoints.some((cp) => cp.noteIds.has(noteId));
2374
- const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
2375
3414
  const notes = tx.readwrite("notes");
2376
- const noteTags = tx.readwrite("note_tags");
2377
3415
  let deleted = 0;
3416
+ let preservedPinned = 0;
2378
3417
  const removedPaths = /* @__PURE__ */ new Set();
2379
3418
  const touchedTagIds = /* @__PURE__ */ new Set();
2380
3419
  for (const id of targetIds) {
2381
3420
  if (isClaimedByOther(id)) continue;
2382
3421
  const note = await notes.get(id);
2383
3422
  if (!note || note.seedOrigin !== "seed") continue;
2384
- if (note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
2385
- if (note.sourcePath) removedPaths.add(note.sourcePath);
2386
- await notes.delete(id);
2387
- const attachments = tx.readwrite("attachments");
2388
- for (const attachment of await attachments.getAllFromIndex("by-note", id)) {
2389
- await attachments.delete(attachment.id);
2390
- }
2391
- for (const link of await noteTags.getAllFromIndex("by-note", id)) {
2392
- touchedTagIds.add(link.tagId);
2393
- await noteTags.delete(link.id);
2394
- }
2395
- const blockIndex = tx.readwrite("block_index");
2396
- for (const row of await blockIndex.getAllFromIndex("by-note", id)) await blockIndex.delete(row.id);
2397
- const blockEfforts = tx.readwrite("block_efforts");
2398
- for (const row of await blockEfforts.getAllFromIndex("by-note", id)) await blockEfforts.delete(row.id);
2399
- const blockEquipment = tx.readwrite("block_equipment");
2400
- for (const row of await blockEquipment.getAllFromIndex("by-note", id)) await blockEquipment.delete(row.id);
2401
- const pageNotes = tx.readwrite("page_notes");
2402
- for (const link of await pageNotes.getAllFromIndex("by-note", id)) await pageNotes.delete(link.id);
2403
- deleted++;
2404
- }
2405
- if (touchedTagIds.size > 0) {
2406
- const tagsStore = tx.readwrite("tags");
2407
- for (const tagId of touchedTagIds) {
2408
- const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
2409
- if (remainingLinks > 0) continue;
2410
- const tag = await tagsStore.get(tagId);
2411
- if (!tag) continue;
2412
- if (tag.contributions && tag.contributions.length > 0) continue;
2413
- const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
2414
- if (refNote) continue;
2415
- await tagsStore.delete(tagId);
2416
- }
3423
+ const ownedByFeedStamp = note.feedSourceId === removedSourceId && (chunkKeys.length === 0 || note.retention === "cached" || note.retention === "schedule-pinned" || note.retention === "session-pinned");
3424
+ if (!ownedByFeedStamp && note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
3425
+ const outcome = await deleteOrPreserveFeedNote(
3426
+ tx,
3427
+ note,
3428
+ "unsubscribed",
3429
+ touchedTagIds,
3430
+ removedPaths
3431
+ );
3432
+ if (outcome === "pinned") preservedPinned++;
3433
+ else deleted++;
2417
3434
  }
3435
+ await pruneOrphanTags(tx, touchedTagIds);
2418
3436
  const defFamilies = [
2419
3437
  { storeName: "efforts", familyPathPrefix: "markdown/efforts/", parse: wodWikiLang.parseEffortFile },
2420
3438
  { storeName: "equipment", familyPathPrefix: "markdown/equipment/", parse: wodWikiLang.parseEquipmentFile }
@@ -2459,11 +3477,92 @@ async function removeSeedSourceContent(storage, meta) {
2459
3477
  }
2460
3478
  } catch {
2461
3479
  }
3480
+ for (const idxKey of indexKeysToDelete) {
3481
+ await metaStore.delete(idxKey);
3482
+ }
2462
3483
  await metaStore.delete(meta.key);
2463
- return deleted;
3484
+ return { deleted, preservedPinned };
2464
3485
  }
2465
3486
  );
2466
3487
  }
3488
+ async function pruneOrphanTags(tx, touchedTagIds) {
3489
+ if (touchedTagIds.size === 0) return;
3490
+ const notes = tx.readwrite("notes");
3491
+ const noteTags = tx.readwrite("note_tags");
3492
+ const tagsStore = tx.readwrite("tags");
3493
+ for (const tagId of touchedTagIds) {
3494
+ const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
3495
+ if (remainingLinks > 0) continue;
3496
+ const tag = await tagsStore.get(tagId);
3497
+ if (!tag) continue;
3498
+ if (tag.contributions && tag.contributions.length > 0) continue;
3499
+ const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
3500
+ if (refNote) continue;
3501
+ await tagsStore.delete(tagId);
3502
+ }
3503
+ }
3504
+ async function deleteOrPreserveFeedNote(tx, note, upstreamStatus, touchedTagIds, removedPaths) {
3505
+ const notes = tx.readwrite("notes");
3506
+ const hasSessions = await noteHasSessions(tx, note.id);
3507
+ const isSessionPinned = note.retention === "session-pinned" || hasSessions;
3508
+ const hasSchedules = !isSessionPinned && await noteHasScheduleItems(tx, note.id);
3509
+ const isSchedulePinned = note.retention === "schedule-pinned" || hasSchedules;
3510
+ if (isSessionPinned || isSchedulePinned) {
3511
+ await notes.put({
3512
+ ...note,
3513
+ retention: isSessionPinned ? "session-pinned" : "schedule-pinned",
3514
+ upstreamStatus
3515
+ });
3516
+ return "pinned";
3517
+ }
3518
+ if (note.sourcePath && removedPaths) removedPaths.add(note.sourcePath);
3519
+ await notes.delete(note.id);
3520
+ const attachments = tx.readwrite("attachments");
3521
+ for (const attachment of await attachments.getAllFromIndex("by-note", note.id)) {
3522
+ await attachments.delete(attachment.id);
3523
+ }
3524
+ const noteTags = tx.readwrite("note_tags");
3525
+ for (const link of await noteTags.getAllFromIndex("by-note", note.id)) {
3526
+ touchedTagIds.add(link.tagId);
3527
+ await noteTags.delete(link.id);
3528
+ }
3529
+ const blockIndex = tx.readwrite("block_index");
3530
+ for (const row of await blockIndex.getAllFromIndex("by-note", note.id)) await blockIndex.delete(row.id);
3531
+ const blockEfforts = tx.readwrite("block_efforts");
3532
+ for (const row of await blockEfforts.getAllFromIndex("by-note", note.id)) await blockEfforts.delete(row.id);
3533
+ const blockEquipment = tx.readwrite("block_equipment");
3534
+ for (const row of await blockEquipment.getAllFromIndex("by-note", note.id)) await blockEquipment.delete(row.id);
3535
+ const pageNotes = tx.readwrite("page_notes");
3536
+ for (const link of await pageNotes.getAllFromIndex("by-note", note.id)) await pageNotes.delete(link.id);
3537
+ return "deleted";
3538
+ }
3539
+ async function removeFeedSourceContentById(storage, sourceId) {
3540
+ const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
3541
+ return removeSeedSourceContent(storage, meta ?? emptySeedMeta(seedMetaKey(sourceId)));
3542
+ }
3543
+ async function readFeedRegistryHeadless(storage) {
3544
+ const row = await storage.readonly("meta").get(FEED_REGISTRY_META_KEY);
3545
+ return {
3546
+ key: FEED_REGISTRY_META_KEY,
3547
+ customFeeds: Array.isArray(row?.customFeeds) ? [...row.customFeeds] : [],
3548
+ hiddenFeedIds: Array.isArray(row?.hiddenFeedIds) ? [...row.hiddenFeedIds] : [],
3549
+ updatedAt: typeof row?.updatedAt === "number" ? row.updatedAt : 0,
3550
+ ...row?.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
3551
+ };
3552
+ }
3553
+ async function writeFeedRegistryHeadless(storage, next) {
3554
+ const record = {
3555
+ key: FEED_REGISTRY_META_KEY,
3556
+ customFeeds: next.customFeeds,
3557
+ hiddenFeedIds: next.hiddenFeedIds,
3558
+ updatedAt: next.updatedAt,
3559
+ ...next.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
3560
+ };
3561
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
3562
+ await tx.readwrite("meta").put(record);
3563
+ });
3564
+ return record;
3565
+ }
2467
3566
  async function readFeedSubscriptionsMap(storage) {
2468
3567
  const row = await storage.readonly("meta").get(FEED_SUBSCRIPTIONS_META_KEY);
2469
3568
  return { ...row?.entries ?? {} };
@@ -2473,7 +3572,11 @@ async function writeFeedSubscriptionEntry(storage, sourceId, entry) {
2473
3572
  const metaStore = tx.readwrite("meta");
2474
3573
  const existing = await metaStore.get(FEED_SUBSCRIPTIONS_META_KEY);
2475
3574
  const entries = { ...existing?.entries ?? {}, [sourceId]: entry };
2476
- await metaStore.put({ key: FEED_SUBSCRIPTIONS_META_KEY, entries });
3575
+ await metaStore.put({
3576
+ key: FEED_SUBSCRIPTIONS_META_KEY,
3577
+ entries,
3578
+ ...existing?.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
3579
+ });
2477
3580
  });
2478
3581
  }
2479
3582
  async function listFeedSubscriptionsHeadless(storage) {
@@ -2481,41 +3584,64 @@ async function listFeedSubscriptionsHeadless(storage) {
2481
3584
  }
2482
3585
  async function subscribeFeedSourceHeadless(storage, sourceId, options) {
2483
3586
  const notebookIds = options?.notebookIds && options.notebookIds.length > 0 ? options.notebookIds : null;
3587
+ const existingMap = await readFeedSubscriptionsMap(storage);
3588
+ const prev = existingMap[sourceId];
3589
+ const offlinePolicy = sourceId === "core" ? "offline-full" : options?.offlinePolicy ?? prev?.offlinePolicy ?? "index-only";
2484
3590
  await writeFeedSubscriptionEntry(storage, sourceId, {
3591
+ ...prev,
2485
3592
  subscribed: true,
2486
3593
  notebookIds,
3594
+ offlinePolicy,
3595
+ ...options?.autoSync !== void 0 ? { autoSync: options.autoSync } : {},
2487
3596
  hidden: false,
2488
3597
  ...options?.url ? { url: options.url } : {},
2489
3598
  ...options?.name ? { name: options.name } : {},
2490
3599
  updatedAt: Date.now()
2491
3600
  });
2492
- return { sourceId, subscribed: true, notebookIds };
3601
+ return { sourceId, subscribed: true, notebookIds, offlinePolicy };
2493
3602
  }
2494
3603
  async function unsubscribeFeedSourceHeadless(storage, sourceId) {
2495
3604
  if (sourceId === "core") {
2496
3605
  throw new Error("Core feed cannot be unsubscribed.");
2497
3606
  }
2498
- const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
2499
- const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
3607
+ const { deleted, preservedPinned } = await removeFeedSourceContentById(storage, sourceId);
3608
+ const existingMap = await readFeedSubscriptionsMap(storage);
3609
+ const prev = existingMap[sourceId];
2500
3610
  await writeFeedSubscriptionEntry(storage, sourceId, {
3611
+ ...prev,
2501
3612
  subscribed: false,
3613
+ autoSync: false,
2502
3614
  hidden: false,
2503
3615
  updatedAt: Date.now()
2504
3616
  });
2505
- return { sourceId, unsubscribed: true, deletedNotes };
3617
+ return { sourceId, unsubscribed: true, deletedNotes: deleted, deleted, preservedPinned };
2506
3618
  }
2507
3619
  async function deleteFeedSourceHeadless(storage, sourceId) {
2508
3620
  if (sourceId === "core") {
2509
3621
  throw new Error("Core feed cannot be deleted.");
2510
3622
  }
2511
- const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
2512
- const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
3623
+ const { deleted, preservedPinned } = await removeFeedSourceContentById(storage, sourceId);
3624
+ const existingMap = await readFeedSubscriptionsMap(storage);
3625
+ const prev = existingMap[sourceId];
2513
3626
  await writeFeedSubscriptionEntry(storage, sourceId, {
3627
+ ...prev,
2514
3628
  subscribed: false,
3629
+ autoSync: false,
2515
3630
  hidden: true,
2516
3631
  updatedAt: Date.now()
2517
3632
  });
2518
- return { sourceId, deleted: true, deletedNotes };
3633
+ const registry = await readFeedRegistryHeadless(storage);
3634
+ const isCustom = registry.customFeeds.some((f) => f.id === sourceId);
3635
+ await writeFeedRegistryHeadless(storage, {
3636
+ customFeeds: isCustom ? registry.customFeeds.filter((f) => f.id !== sourceId) : registry.customFeeds,
3637
+ hiddenFeedIds: isCustom || registry.hiddenFeedIds.includes(sourceId) ? registry.hiddenFeedIds : [...registry.hiddenFeedIds, sourceId],
3638
+ updatedAt: Date.now(),
3639
+ migratedFromLocalStorage: registry.migratedFromLocalStorage
3640
+ });
3641
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
3642
+ await tx.readwrite("meta").delete(`catalog:${sourceId}`);
3643
+ });
3644
+ return { sourceId, deleted: true, deletedNotes: deleted, preservedPinned };
2519
3645
  }
2520
3646
  function object(value) {
2521
3647
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -2529,42 +3655,149 @@ function nonnegative(value) {
2529
3655
  function finite(value) {
2530
3656
  return typeof value === "number" && Number.isFinite(value);
2531
3657
  }
3658
+ function isSafeRelativePath(value) {
3659
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split("/").includes("..");
3660
+ }
3661
+ function isSafeRawUrlOrPath(value) {
3662
+ if (typeof value !== "string" || !value.trim()) return false;
3663
+ if (/^https?:\/\//i.test(value)) {
3664
+ try {
3665
+ const parsed = new URL(value);
3666
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && !parsed.username && !parsed.password;
3667
+ } catch {
3668
+ return false;
3669
+ }
3670
+ }
3671
+ return isSafeRelativePath(value);
3672
+ }
2532
3673
  function assertSeedManifest(value) {
2533
- if (!object(value) || value.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; rebuild seed artifacts");
2534
- if (!nonnegative(value.version) || typeof value.builtAt !== "string" || !Number.isFinite(Date.parse(value.builtAt)) || !Array.isArray(value.chunks)) throw new Error("seed manifest failed shape validation");
2535
- for (const key of ["versionLabel", "commit", "name", "description"]) if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
2536
- if (value.repositoryUrl !== void 0 && (typeof value.repositoryUrl !== "string" || !/^https:\/\//.test(value.repositoryUrl) || new URL(value.repositoryUrl).username || new URL(value.repositoryUrl).password)) throw new Error("invalid seed repository URL");
3674
+ if (!object(value)) throw new Error("Incompatible seed schema; rebuild seed artifacts");
3675
+ const hasNotebooks = Array.isArray(value.notebooks);
3676
+ if (value.schema === void 0) {
3677
+ if (!hasNotebooks) throw new Error("Incompatible seed schema; rebuild seed artifacts");
3678
+ } else if (!positive(value.schema) || value.schema !== SEED_SCHEMA && !hasNotebooks) {
3679
+ throw new Error("Incompatible seed schema; rebuild seed artifacts");
3680
+ }
3681
+ const normalizedSchema = value.schema === void 0 ? SEED_SCHEMA : value.schema;
3682
+ const normalizedVersion = value.version === void 0 && hasNotebooks ? 1 : value.version;
3683
+ const normalizedBuiltAt = value.builtAt === void 0 && hasNotebooks ? (/* @__PURE__ */ new Date(0)).toISOString() : value.builtAt;
3684
+ const normalizedChunks = value.chunks === void 0 && hasNotebooks ? [] : value.chunks;
3685
+ if (!nonnegative(normalizedVersion) || typeof normalizedBuiltAt !== "string" || !Number.isFinite(Date.parse(normalizedBuiltAt)) || !Array.isArray(normalizedChunks)) {
3686
+ throw new Error("seed manifest failed shape validation");
3687
+ }
3688
+ for (const key of ["versionLabel", "commit", "name", "description"]) {
3689
+ if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
3690
+ }
3691
+ if (value.repositoryUrl !== void 0 && (typeof value.repositoryUrl !== "string" || !/^https:\/\//.test(value.repositoryUrl) || new URL(value.repositoryUrl).username || new URL(value.repositoryUrl).password)) {
3692
+ throw new Error("invalid seed repository URL");
3693
+ }
2537
3694
  if (value.dirty !== void 0 && typeof value.dirty !== "boolean") throw new Error("invalid seed manifest metadata");
3695
+ for (const key of ["indexBytes", "chunkBytes"]) {
3696
+ if (value[key] !== void 0 && !nonnegative(value[key])) throw new Error("invalid seed manifest metadata");
3697
+ }
2538
3698
  const ids = /* @__PURE__ */ new Set(), paths = /* @__PURE__ */ new Set();
2539
- for (const chunk of value.chunks) {
2540
- if (!object(chunk) || typeof chunk.id !== "string" || !chunk.id || typeof chunk.path !== "string" || !/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(chunk.path) || typeof chunk.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(chunk.sha256) || !nonnegative(chunk.bytes) || !nonnegative(chunk.count) || chunk.kind !== void 0 && chunk.kind !== "notes" || ids.has(chunk.id) || paths.has(chunk.path)) throw new Error("seed manifest failed shape validation");
3699
+ for (const chunk of normalizedChunks) {
3700
+ if (!object(chunk) || typeof chunk.id !== "string" || !chunk.id || typeof chunk.path !== "string" || !/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(chunk.path) || typeof chunk.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(chunk.sha256) || !nonnegative(chunk.bytes) || !nonnegative(chunk.count) || chunk.kind !== void 0 && chunk.kind !== "notes" || ids.has(chunk.id) || paths.has(chunk.path)) {
3701
+ throw new Error("seed manifest failed shape validation");
3702
+ }
2541
3703
  ids.add(chunk.id);
2542
3704
  paths.add(chunk.path);
2543
3705
  }
3706
+ let normalizedNotebooks;
2544
3707
  if (value.notebooks !== void 0) {
2545
3708
  if (!Array.isArray(value.notebooks)) throw new Error("seed manifest failed shape validation");
3709
+ normalizedNotebooks = [];
2546
3710
  for (const nb of value.notebooks) {
2547
- if (!object(nb) || typeof nb.notebookId !== "string" || !nb.notebookId || typeof nb.label !== "string" || !nonnegative(nb.count) || typeof nb.indexPath !== "string" || !nb.indexPath || !nonnegative(nb.version) || typeof nb.commit !== "string" || typeof nb.builtAt !== "string" || typeof nb.sha256 !== "string" || !nonnegative(nb.bytes)) {
3711
+ if (!object(nb) || typeof nb.notebookId !== "string" || !nb.notebookId || typeof nb.label !== "string" || !nonnegative(nb.count) || !isSafeRawUrlOrPath(nb.indexPath)) {
2548
3712
  throw new Error("seed manifest failed shape validation");
2549
3713
  }
2550
3714
  if ("records" in nb && Array.isArray(nb.records)) {
2551
3715
  throw new Error("seed manifest failed shape validation: manifest.notebooks must not contain inline records");
2552
3716
  }
3717
+ if (nb.version !== void 0 && !nonnegative(nb.version)) throw new Error("seed manifest failed shape validation");
3718
+ if (nb.commit !== void 0 && typeof nb.commit !== "string") throw new Error("seed manifest failed shape validation");
3719
+ if (nb.builtAt !== void 0 && typeof nb.builtAt !== "string") throw new Error("seed manifest failed shape validation");
3720
+ if (nb.sha256 !== void 0 && typeof nb.sha256 !== "string") throw new Error("seed manifest failed shape validation");
3721
+ if (nb.bytes !== void 0 && !nonnegative(nb.bytes)) throw new Error("seed manifest failed shape validation");
3722
+ if (nb.indexBytes !== void 0 && !nonnegative(nb.indexBytes)) throw new Error("seed manifest failed shape validation");
3723
+ if (nb.chunkBytes !== void 0 && !nonnegative(nb.chunkBytes)) throw new Error("seed manifest failed shape validation");
3724
+ normalizedNotebooks.push({
3725
+ ...nb,
3726
+ version: nb.version ?? normalizedVersion,
3727
+ commit: nb.commit ?? "",
3728
+ builtAt: nb.builtAt ?? normalizedBuiltAt,
3729
+ sha256: nb.sha256 ?? "",
3730
+ bytes: nb.bytes ?? nb.indexBytes ?? 0
3731
+ });
2553
3732
  }
2554
3733
  }
2555
- return value;
3734
+ return {
3735
+ ...value,
3736
+ schema: normalizedSchema,
3737
+ version: normalizedVersion,
3738
+ builtAt: normalizedBuiltAt,
3739
+ chunks: normalizedChunks,
3740
+ ...normalizedNotebooks !== void 0 ? { notebooks: normalizedNotebooks } : {}
3741
+ };
2556
3742
  }
2557
3743
  function assertNotebookIndex(value) {
2558
3744
  if (!object(value)) throw new Error("notebook index failed shape validation");
2559
- if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || !value.label || typeof value.indexPath !== "string" || !value.indexPath || !nonnegative(value.version) || typeof value.commit !== "string" || typeof value.builtAt !== "string" || typeof value.sha256 !== "string" || !nonnegative(value.bytes) || !nonnegative(value.count) || !Array.isArray(value.records)) {
3745
+ if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || !value.label || !isSafeRawUrlOrPath(value.indexPath) || !nonnegative(value.count) || !Array.isArray(value.records)) {
2560
3746
  throw new Error("notebook index failed shape validation: missing required index summary or records");
2561
3747
  }
3748
+ if (value.version !== void 0 && !nonnegative(value.version)) throw new Error("notebook index failed shape validation: missing required index summary or records");
3749
+ if (value.commit !== void 0 && typeof value.commit !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
3750
+ if (value.builtAt !== void 0 && typeof value.builtAt !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
3751
+ if (value.sha256 !== void 0 && typeof value.sha256 !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
3752
+ if (value.bytes !== void 0 && !nonnegative(value.bytes)) throw new Error("notebook index failed shape validation: missing required index summary or records");
3753
+ const normalizedRecords = [];
2562
3754
  for (const r of value.records) {
2563
- if (!object(r) || typeof r.uuid !== "string" || typeof r.path !== "string" || typeof r.recordPath !== "string" || typeof r.commit !== "string" || !nonnegative(r.version) || typeof r.sha256 !== "string") {
3755
+ if (!object(r) || typeof r.uuid !== "string" || !r.uuid || !isSafeRelativePath(r.path)) {
3756
+ throw new Error("notebook index failed shape validation: invalid record ref");
3757
+ }
3758
+ const hasRecordPath = r.recordPath !== void 0;
3759
+ const hasRawUrl = r.rawUrl !== void 0;
3760
+ const hasMdPath = /\.md$/i.test(r.path);
3761
+ if (hasRecordPath && !isSafeRelativePath(r.recordPath)) {
3762
+ throw new Error("notebook index failed shape validation: invalid record ref");
3763
+ }
3764
+ if (hasRawUrl && !isSafeRawUrlOrPath(r.rawUrl)) {
3765
+ throw new Error("notebook index failed shape validation: invalid record ref");
3766
+ }
3767
+ if (!hasRecordPath && !hasRawUrl && !hasMdPath) {
3768
+ throw new Error("notebook index failed shape validation: invalid record ref");
3769
+ }
3770
+ if (r.commit !== void 0 && typeof r.commit !== "string") {
3771
+ throw new Error("notebook index failed shape validation: invalid record ref");
3772
+ }
3773
+ if (r.version !== void 0 && !nonnegative(r.version)) {
3774
+ throw new Error("notebook index failed shape validation: invalid record ref");
3775
+ }
3776
+ if (r.sha256 !== void 0 && typeof r.sha256 !== "string") {
3777
+ throw new Error("notebook index failed shape validation: invalid record ref");
3778
+ }
3779
+ if (r.title !== void 0 && typeof r.title !== "string") {
3780
+ throw new Error("notebook index failed shape validation: invalid record ref");
3781
+ }
3782
+ if (r.date !== void 0 && !finite(r.date)) {
2564
3783
  throw new Error("notebook index failed shape validation: invalid record ref");
2565
3784
  }
3785
+ normalizedRecords.push({
3786
+ ...r,
3787
+ commit: r.commit ?? "",
3788
+ version: r.version ?? 1,
3789
+ sha256: r.sha256 ?? ""
3790
+ });
2566
3791
  }
2567
- return value;
3792
+ return {
3793
+ ...value,
3794
+ version: value.version ?? 1,
3795
+ commit: value.commit ?? "",
3796
+ builtAt: value.builtAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
3797
+ sha256: value.sha256 ?? "",
3798
+ bytes: value.bytes ?? 0,
3799
+ records: normalizedRecords
3800
+ };
2568
3801
  }
2569
3802
  function assertTelemetry(row, blockIndex) {
2570
3803
  if (row.telemetry === void 0) return;
@@ -3126,7 +4359,7 @@ async function ingestPortableFilesIntoStorage(storage, files, options = {}) {
3126
4359
  }
3127
4360
 
3128
4361
  // src/version.ts
3129
- var VERSION = "0.60.2258";
4362
+ var VERSION = "0.62.2260";
3130
4363
 
3131
4364
  // src/feed/qr.ts
3132
4365
  var APP_ORIGIN = "https://wod.wiki";
@@ -4508,13 +5741,16 @@ var wodFeedManageTool = defineAgentTool({
4508
5741
  const obj = row;
4509
5742
  if (typeof obj.key === "string" && obj.key.startsWith("seed:") && obj.key !== seedMetaKey("user")) {
4510
5743
  const sourceId = obj.key.slice("seed:".length);
5744
+ const sub = subscriptions[sourceId];
4511
5745
  installedFeeds.push({
4512
5746
  sourceId,
4513
5747
  seedVersion: obj.seedVersion,
4514
5748
  builtAt: obj.builtAt,
4515
5749
  importedAt: obj.importedAt,
4516
5750
  chunkCount: Object.keys(obj.chunks ?? {}).length,
4517
- subscribed: subscriptions[sourceId]?.subscribed ?? true
5751
+ subscribed: sub?.subscribed ?? true,
5752
+ offlinePolicy: sub?.offlinePolicy ?? (sourceId === "core" ? "offline-full" : "index-only"),
5753
+ autoSync: sub?.autoSync ?? sourceId === "core"
4518
5754
  });
4519
5755
  }
4520
5756
  }
@@ -4748,6 +5984,7 @@ var wodJournalDayTool = defineAgentTool({
4748
5984
  cliEquivalent: "wod journal [today|YYYY-MM-DD] --json",
4749
5985
  async execute(args, ctx) {
4750
5986
  const dateKey = civilDateKey(args.date);
5987
+ const overlay = await getJournalDayOverlay(ctx.storage, dateKey);
4751
5988
  const dayStart = Date.parse(`${dateKey}T00:00:00Z`);
4752
5989
  const dayEnd = Date.parse(`${dateKey}T23:59:59.999Z`);
4753
5990
  let pages;
@@ -4766,16 +6003,20 @@ var wodJournalDayTool = defineAgentTool({
4766
6003
  if (!placedNoteIds.includes(link.noteId)) placedNoteIds.push(link.noteId);
4767
6004
  }
4768
6005
  }
4769
- const [allNotes, allSessions] = await Promise.all([
4770
- ctx.storage.readonly("notes").getAll(),
4771
- ctx.storage.readonly("sessions").getAll()
4772
- ]);
6006
+ const allNotes = await ctx.storage.readonly("notes").getAll();
4773
6007
  const notesById = new Map(allNotes.map((n) => [n.id, n]));
4774
6008
  const dayNotes = [];
4775
6009
  const seenIds = /* @__PURE__ */ new Set();
6010
+ for (const { item, note } of overlay.planned) {
6011
+ const resolved = note ?? notesById.get(item.noteId);
6012
+ if (resolved && !seenIds.has(resolved.id)) {
6013
+ dayNotes.push(resolved);
6014
+ seenIds.add(resolved.id);
6015
+ }
6016
+ }
4776
6017
  for (const id of placedNoteIds) {
4777
6018
  const n = notesById.get(id);
4778
- if (n) {
6019
+ if (n && !seenIds.has(n.id)) {
4779
6020
  dayNotes.push(n);
4780
6021
  seenIds.add(n.id);
4781
6022
  }
@@ -4790,16 +6031,50 @@ var wodJournalDayTool = defineAgentTool({
4790
6031
  seenIds.add(n.id);
4791
6032
  }
4792
6033
  }
4793
- const daySessions = allSessions.filter((s) => {
4794
- if (page && s.pageId === page.id) return true;
4795
- if (seenIds.has(s.noteId) && s.startTime >= dayStart && s.startTime <= dayEnd) return true;
4796
- return s.startTime >= dayStart && s.startTime <= dayEnd;
4797
- }).sort((a, b) => a.startTime - b.startTime);
6034
+ const overlaySessionsById = /* @__PURE__ */ new Map();
6035
+ for (const p of overlay.planned) {
6036
+ for (const s of p.pairedSessions) overlaySessionsById.set(s.id, s);
6037
+ }
6038
+ for (const a of overlay.adhocSessions) {
6039
+ overlaySessionsById.set(a.session.id, a.session);
6040
+ }
6041
+ const daySessions = Array.from(overlaySessionsById.values()).sort(
6042
+ (a, b) => a.startTime - b.startTime
6043
+ );
6044
+ for (const s of daySessions) {
6045
+ if (seenIds.has(s.noteId)) continue;
6046
+ const n = notesById.get(s.noteId);
6047
+ if (n) {
6048
+ dayNotes.push(n);
6049
+ seenIds.add(n.id);
6050
+ }
6051
+ }
4798
6052
  const prefix = (ctx.baseUrl ?? "").replace(/\/+$/, "");
4799
6053
  return {
4800
6054
  date: dateKey,
4801
- url: `${prefix}/journal/${dateKey}`,
6055
+ url: `${prefix}/day/${dateKey}`,
4802
6056
  pageId: page?.id ?? null,
6057
+ plannedCount: overlay.planned.length,
6058
+ planned: overlay.planned.map(({ item, note, pairedSessions }) => ({
6059
+ scheduleItemId: item.id,
6060
+ noteId: item.noteId,
6061
+ noteTitle: note?.title ?? item.noteId,
6062
+ status: pairedSessions.length > 0 ? "completed" : item.status,
6063
+ ...item.slot ? { slot: item.slot } : {},
6064
+ ...item.notes ? { notes: item.notes } : {},
6065
+ pairedSessionIds: pairedSessions.map((s) => s.id)
6066
+ })),
6067
+ adhocSessionCount: overlay.adhocSessions.length,
6068
+ adhocSessions: overlay.adhocSessions.map(({ session: s, note }) => ({
6069
+ id: s.id,
6070
+ noteId: s.noteId,
6071
+ noteTitle: note?.title ?? s.noteId,
6072
+ status: s.status,
6073
+ completed: s.completed,
6074
+ duration: s.duration,
6075
+ startTime: s.startTime,
6076
+ ...s.noteSourceRevision ? { noteSourceRevision: s.noteSourceRevision } : {}
6077
+ })),
4803
6078
  noteCount: dayNotes.length,
4804
6079
  notes: dayNotes.map((n) => ({
4805
6080
  id: n.id,
@@ -4818,7 +6093,10 @@ var wodJournalDayTool = defineAgentTool({
4818
6093
  status: s.status,
4819
6094
  completed: s.completed,
4820
6095
  duration: s.duration,
4821
- startTime: s.startTime
6096
+ startTime: s.startTime,
6097
+ ...s.scheduleItemId ? { scheduleItemId: s.scheduleItemId } : {},
6098
+ ...s.sessionDate ? { sessionDate: s.sessionDate } : {},
6099
+ ...s.noteSourceRevision ? { noteSourceRevision: s.noteSourceRevision } : {}
4822
6100
  }))
4823
6101
  };
4824
6102
  }
@@ -4828,12 +6106,12 @@ var journalAddInputSchema = zod.z.strictObject({
4828
6106
  title: zod.z.string().optional().describe("Workout title (defaults to # H1 heading or date)."),
4829
6107
  content: zod.z.string().min(1).describe("Markdown workout note or bare Whiteboard Script to schedule onto the Journal day."),
4830
6108
  sport: zod.z.string().optional().describe("Optional sport fence tag when passing bare Whiteboard Script."),
4831
- notebookId: zod.z.string().optional().describe("Optional additional user Notebook to promote this Journal Note into.")
6109
+ notebookId: zod.z.string().optional().describe("Optional user Notebook ID to assign this Note into (omit to keep unfiled on Journal).")
4832
6110
  });
4833
6111
  var wodJournalAddTool = defineAgentTool({
4834
6112
  name: "wod_journal_add",
4835
6113
  title: "Add Workout to Journal Day",
4836
- description: "Create a new workout Note in `notebook/journal` and place it onto the specified calendar day (`YYYY-MM-DD` or `today`).",
6114
+ description: "Create a lightweight workout Note (unfiled unless `notebookId` is given) and schedule it onto the specified calendar day via a `ScheduleItem`.",
4837
6115
  tier: 1,
4838
6116
  domain: "journal",
4839
6117
  annotations: {
@@ -4864,13 +6142,15 @@ var wodJournalAddTool = defineAgentTool({
4864
6142
  "block_equipment",
4865
6143
  "page",
4866
6144
  "page_notes",
4867
- "notebook_links"
6145
+ "notebook_links",
6146
+ "schedule_items"
4868
6147
  ]);
4869
6148
  const prefix = (ctx.baseUrl ?? "").replace(/\/+$/, "");
4870
6149
  return {
4871
6150
  date: dateKey,
4872
6151
  noteId: saved.note.id,
4873
- journalUrl: `${prefix}/journal/${dateKey}`,
6152
+ ...saved.scheduleItemId ? { scheduleItemId: saved.scheduleItemId } : {},
6153
+ journalUrl: `${prefix}/day/${dateKey}`,
4874
6154
  note: {
4875
6155
  id: saved.note.id,
4876
6156
  title: saved.note.title,
@@ -4879,14 +6159,105 @@ var wodJournalAddTool = defineAgentTool({
4879
6159
  effortSlugs: saved.effortSlugs,
4880
6160
  url: noteDeepLink(saved.note, ctx.baseUrl)
4881
6161
  }
4882
- };
4883
- }
4884
- });
4885
- var JOURNAL_AGENT_TOOLS = [wodJournalDayTool, wodJournalAddTool];
4886
- function isLandingNote(note) {
4887
- return note.id.startsWith("notebook/") && note.notebookId === note.id;
6162
+ };
6163
+ }
6164
+ });
6165
+ var JOURNAL_AGENT_TOOLS = [wodJournalDayTool, wodJournalAddTool];
6166
+ var RESERVED_SLUGS = new Set(wodWikiCore.BUILTIN_NOTEBOOKS.map((b) => b.slug));
6167
+ async function deleteUserNotebook(storage, notebookIdOrSlug) {
6168
+ const nbId = wodWikiCore.toNotebookId(notebookIdOrSlug);
6169
+ const slug = wodWikiCore.notebookSlugFromId(nbId);
6170
+ if (RESERVED_SLUGS.has(slug)) {
6171
+ throw new Error(`Notebook '${nbId}' is always present and cannot be deleted.`);
6172
+ }
6173
+ return storage.transaction(
6174
+ [
6175
+ "notes",
6176
+ "notebook_links",
6177
+ "attachments",
6178
+ "note_tags",
6179
+ "block_index",
6180
+ "block_efforts",
6181
+ "block_equipment",
6182
+ "page_notes",
6183
+ "meta"
6184
+ ],
6185
+ "readwrite",
6186
+ async (tx) => {
6187
+ const allNotes = await tx.readonly("notes").getAll();
6188
+ const links = await tx.readonly("notebook_links").getAllFromIndex("by-notebook", nbId).catch(() => []);
6189
+ const linkedNoteIds = new Set(
6190
+ links.filter((l) => l.targetKind === "note").map((l) => l.noteId)
6191
+ );
6192
+ let touchedMembers = 0;
6193
+ const noteWriter = tx.readwrite("notes");
6194
+ for (const note of allNotes) {
6195
+ if (wodWikiCore.isNotebookLanding(note)) continue;
6196
+ const hasSingle = note.notebookId === nbId;
6197
+ const hasMulti = (note.notebookIds ?? []).includes(nbId);
6198
+ const hasLink = linkedNoteIds.has(note.id);
6199
+ if (!hasSingle && !hasMulti && !hasLink) continue;
6200
+ const baseIds = note.notebookIds !== void 0 ? note.notebookIds : note.notebookId ? [note.notebookId] : [];
6201
+ const remaining = baseIds.map((id) => wodWikiCore.toNotebookId(id)).filter((id) => id !== nbId);
6202
+ const primaryUser = remaining.find(
6203
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
6204
+ );
6205
+ const { notebookId: _droppedSingle, notebookIds: _droppedMulti, ...rest } = note;
6206
+ await noteWriter.put({
6207
+ ...rest,
6208
+ notebookIds: remaining,
6209
+ ...primaryUser ? { notebookId: primaryUser } : {}
6210
+ });
6211
+ touchedMembers++;
6212
+ }
6213
+ if (links.length > 0) {
6214
+ const linkWriter = tx.readwrite("notebook_links");
6215
+ for (const link of links) {
6216
+ await linkWriter.delete(link.id);
6217
+ }
6218
+ }
6219
+ const landing = allNotes.find((n) => n.id === nbId);
6220
+ if (landing) {
6221
+ await noteWriter.delete(nbId);
6222
+ try {
6223
+ for (const att of await tx.readonly("attachments").getAllFromIndex("by-note", nbId)) {
6224
+ await tx.readwrite("attachments").delete(att.id);
6225
+ }
6226
+ for (const link of await tx.readonly("note_tags").getAllFromIndex("by-note", nbId)) {
6227
+ await tx.readwrite("note_tags").delete(link.id);
6228
+ }
6229
+ for (const row of await tx.readonly("block_index").getAllFromIndex("by-note", nbId)) {
6230
+ await tx.readwrite("block_index").delete(row.id);
6231
+ }
6232
+ for (const row of await tx.readonly("block_efforts").getAllFromIndex("by-note", nbId)) {
6233
+ await tx.readwrite("block_efforts").delete(row.id);
6234
+ }
6235
+ for (const row of await tx.readonly("block_equipment").getAllFromIndex("by-note", nbId)) {
6236
+ await tx.readwrite("block_equipment").delete(row.id);
6237
+ }
6238
+ for (const pn of await tx.readonly("page_notes").getAllFromIndex("by-note", nbId)) {
6239
+ await tx.readwrite("page_notes").delete(pn.id);
6240
+ }
6241
+ for (const nl of await tx.readonly("notebook_links").getAllFromIndex("by-note", nbId)) {
6242
+ await tx.readwrite("notebook_links").delete(nl.id);
6243
+ }
6244
+ } catch {
6245
+ }
6246
+ if (landing.seedOrigin === "seed" || landing.seedChunkId !== void 0 || landing.sourcePath !== void 0) {
6247
+ await tx.readwrite("meta").put({ key: wodWikiStorage.userDeletedSeedKey(nbId), value: Date.now() });
6248
+ }
6249
+ }
6250
+ return {
6251
+ deleted: Boolean(landing || touchedMembers > 0 || links.length > 0),
6252
+ notebookId: nbId,
6253
+ slug
6254
+ };
6255
+ }
6256
+ );
4888
6257
  }
4889
- var RESERVED_SLUGS = new Set(wodWikiCore.BUILTIN_NOTEBOOKS.map((b) => b.slug));
6258
+
6259
+ // src/agent/tools/notebookTools.ts
6260
+ var RESERVED_SLUGS2 = new Set(wodWikiCore.BUILTIN_NOTEBOOKS.map((b) => b.slug));
4890
6261
  var notebookListInputSchema = zod.z.strictObject({
4891
6262
  origin: zod.z.enum(["all", "default", "user", "feed"]).optional().describe('Filter notebooks by origin (default "all").')
4892
6263
  });
@@ -4910,22 +6281,7 @@ var wodNotebookListTool = defineAgentTool({
4910
6281
  ctx.storage.readonly("notes").getAll(),
4911
6282
  ctx.storage.readonly("notebook_links").getAll().catch(() => [])
4912
6283
  ]);
4913
- const counts = /* @__PURE__ */ new Map();
4914
- const countedPairs = /* @__PURE__ */ new Set();
4915
- const bump = (nbId, noteId) => {
4916
- const key = `${nbId}\0${noteId}`;
4917
- if (countedPairs.has(key)) return;
4918
- countedPairs.add(key);
4919
- counts.set(nbId, (counts.get(nbId) ?? 0) + 1);
4920
- };
4921
- for (const link of allLinks) {
4922
- if (link.targetKind === "note") bump(wodWikiCore.toNotebookId(link.notebookId), link.noteId);
4923
- }
4924
- for (const n of allNotes) {
4925
- for (const nbId of wodWikiWql.notebooksOfItem(n)) {
4926
- bump(wodWikiCore.toNotebookId(nbId), n.id);
4927
- }
4928
- }
6284
+ const counts = wodWikiCore.countNotesByNotebook(allNotes, allLinks, wodWikiWql.notebooksOfItem);
4929
6285
  const byId = /* @__PURE__ */ new Map();
4930
6286
  for (const spec of wodWikiCore.BUILTIN_NOTEBOOKS) {
4931
6287
  byId.set(spec.notebookId, {
@@ -4941,7 +6297,7 @@ var wodNotebookListTool = defineAgentTool({
4941
6297
  });
4942
6298
  }
4943
6299
  for (const n of allNotes) {
4944
- if (!isLandingNote(n)) continue;
6300
+ if (!wodWikiCore.isNotebookLanding(n)) continue;
4945
6301
  const slug = wodWikiCore.notebookSlugFromId(n.id);
4946
6302
  const fm = readFrontmatterMeta(n.rawContent);
4947
6303
  const description = typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : "";
@@ -4957,7 +6313,7 @@ var wodNotebookListTool = defineAgentTool({
4957
6313
  origin: existing?.origin ?? (isFeed ? "feed" : "user"),
4958
6314
  writable: !wodWikiCore.isSystemReadOnlyNotebook(n.id) && !isFeed,
4959
6315
  public: n.public === true,
4960
- noteCount: counts.get(n.id) ?? 0
6316
+ noteCount: counts.get(wodWikiCore.toNotebookId(n.id)) ?? 0
4961
6317
  });
4962
6318
  }
4963
6319
  const filterOrigin = args.origin ?? "all";
@@ -5035,431 +6391,128 @@ icon: ${JSON.stringify(args.icon ?? "\u{1F4D3}")}
5035
6391
  const nbId = wodWikiCore.toNotebookId(args.notebookId);
5036
6392
  const slug = wodWikiCore.notebookSlugFromId(nbId);
5037
6393
  if (args.action === "update") {
5038
- if (RESERVED_SLUGS.has(slug)) {
6394
+ if (RESERVED_SLUGS2.has(slug)) {
5039
6395
  throw new Error(`Built-in Notebook '${nbId}' cannot be modified.`);
5040
6396
  }
5041
6397
  const existing = await ctx.storage.readonly("notes").get(nbId);
5042
6398
  if (!existing) throw new Error(`Notebook not found: ${nbId}`);
5043
- const fm = readFrontmatterMeta(existing.rawContent);
5044
- const nextName = args.name ?? existing.title ?? slug;
5045
- const nextDesc = args.description ?? (typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : "");
5046
- const nextIcon = args.icon ?? (typeof fm["icon"] === "string" ? fm["icon"].replace(/^"|"$/g, "") : "\u{1F4D3}");
5047
- const rawContent = `---
5048
- description: ${JSON.stringify(nextDesc)}
5049
- icon: ${JSON.stringify(nextIcon)}
5050
- ---
5051
-
5052
- # ${nextName}
5053
- `;
5054
- const saved = await upsertNoteInStorage(ctx.storage, {
5055
- noteId: nbId,
5056
- title: nextName,
5057
- rawContent
5058
- });
5059
- await ctx.storage.readwrite("notes").put({
5060
- ...saved.note,
5061
- notebookId: nbId,
5062
- ...existing.public !== void 0 ? { public: existing.public } : {}
5063
- });
5064
- await ctx.onMutated?.(["notes", "block_revisions"]);
5065
- return { action: "update", notebookId: nbId, slug, name: nextName };
5066
- }
5067
- if (args.action === "promote") {
5068
- if (!args.noteId) throw new Error('`noteId` is required when action="promote".');
5069
- const promoted = await promoteNoteToNotebooks(ctx.storage, {
5070
- noteId: args.noteId,
5071
- notebookIds: [nbId],
5072
- sessionIds: args.sessionIds,
5073
- shareSessionsPublicly: args.public
5074
- });
5075
- await ctx.onMutated?.(["notes", "sessions", "notebook_links"]);
5076
- return {
5077
- action: "promote",
5078
- noteId: args.noteId,
5079
- notebookIds: promoted.notebookIds,
5080
- promotedSessionIds: promoted.promotedSessionIds
5081
- };
5082
- }
5083
- if (args.action === "detach") {
5084
- if (!args.noteId) throw new Error('`noteId` is required when action="detach".');
5085
- const remaining = await removeNoteFromNotebook(ctx.storage, args.noteId, nbId);
5086
- await ctx.onMutated?.(["notes", "notebook_links"]);
5087
- return {
5088
- action: "detach",
5089
- noteId: args.noteId,
5090
- notebookIds: remaining
5091
- };
5092
- }
5093
- if (wodWikiCore.isNonPublishableNotebook(nbId)) {
5094
- throw new Error(`Notebook '${nbId}' is private/system and cannot be published.`);
5095
- }
5096
- const updated = await setNotebookPublic(ctx.storage, nbId, args.public ?? true);
5097
- await ctx.onMutated?.(["notes"]);
5098
- return {
5099
- action: "set-public",
5100
- notebookId: nbId,
5101
- public: updated.public === true
5102
- };
5103
- }
5104
- });
5105
- var notebookDeleteInputSchema = zod.z.strictObject({
5106
- notebookId: zod.z.string().min(1).describe("User Notebook ID or slug to delete (member Notes stay safe in notebook/journal)."),
5107
- confirmId: zod.z.string().optional().describe("For non-interactive MCP/CLI calls, repeat the exact notebookId or slug to confirm deletion.")
5108
- });
5109
- var wodNotebookDeleteTool = defineAgentTool({
5110
- name: "wod_notebook_delete",
5111
- title: "Delete User Notebook",
5112
- description: "Delete a user-created Notebook landing note and detach member links while keeping all member Notes safely in `notebook/journal` (Tier 2 destructive).",
5113
- tier: 2,
5114
- domain: "notebook",
5115
- annotations: {
5116
- title: "Delete User Notebook",
5117
- readOnlyHint: false,
5118
- destructiveHint: true,
5119
- idempotentHint: true,
5120
- openWorldHint: false
5121
- },
5122
- inputSchema: notebookDeleteInputSchema,
5123
- cliEquivalent: "wod notebook delete <slug> --yes <slug> --json",
5124
- async execute(args, ctx) {
5125
- const nbId = wodWikiCore.toNotebookId(args.notebookId);
5126
- const slug = wodWikiCore.notebookSlugFromId(nbId);
5127
- if (RESERVED_SLUGS.has(slug)) {
5128
- throw new Error(`Built-in Notebook '${nbId}' cannot be deleted.`);
5129
- }
5130
- const matchedConfirm = args.confirmId === nbId || args.confirmId === slug ? nbId : void 0;
5131
- await requireDestructiveConfirmation(
5132
- ctx,
5133
- {
5134
- action: "wod_notebook_delete",
5135
- targetId: nbId,
5136
- summary: `Delete user Notebook "${slug}" (${nbId}); member Notes remain in notebook/journal`
5137
- },
5138
- matchedConfirm
5139
- );
5140
- const allNotes = await ctx.storage.readonly("notes").getAll();
5141
- for (const note of allNotes) {
5142
- if (isLandingNote(note)) continue;
5143
- if (note.notebookId === nbId || (note.notebookIds ?? []).includes(nbId)) {
5144
- const remaining = (note.notebookIds ?? ["notebook/journal"]).map((id) => wodWikiCore.toNotebookId(id)).filter((id) => id !== nbId);
5145
- const primaryUser = remaining.find(
5146
- (id) => id !== "notebook/journal" && id !== "notebook/playground"
5147
- );
5148
- const { notebookId: _oldSingle, ...rest } = note;
5149
- await ctx.storage.readwrite("notes").put({
5150
- ...rest,
5151
- notebookIds: remaining.length > 0 ? remaining : ["notebook/journal"],
5152
- ...primaryUser ? { notebookId: primaryUser } : {}
5153
- });
5154
- }
5155
- }
5156
- try {
5157
- const links = await ctx.storage.readonly("notebook_links").getAllFromIndex("by-notebook", nbId);
5158
- for (const link of links) {
5159
- await ctx.storage.readwrite("notebook_links").delete(link.id);
5160
- }
5161
- } catch {
5162
- }
5163
- const deleted = await deleteNoteFromStorage(ctx.storage, nbId);
5164
- await ctx.onMutated?.(["notes", "notebook_links"]);
5165
- return { deleted, notebookId: nbId, slug };
5166
- }
5167
- });
5168
- var NOTEBOOK_AGENT_TOOLS = [
5169
- wodNotebookListTool,
5170
- wodNotebookSaveTool,
5171
- wodNotebookDeleteTool
5172
- ];
5173
- function mintUuid() {
5174
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
5175
- return crypto.randomUUID();
5176
- }
5177
- const bytes = new Uint8Array(16);
5178
- crypto.getRandomValues(bytes);
5179
- bytes[6] = bytes[6] & 15 | 64;
5180
- bytes[8] = bytes[8] & 63 | 128;
5181
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
5182
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
5183
- }
5184
- function utcCivilDateKey(epochMs) {
5185
- const d = new Date(epochMs);
5186
- const y = d.getFullYear();
5187
- const m = String(d.getMonth() + 1).padStart(2, "0");
5188
- const day = String(d.getDate()).padStart(2, "0");
5189
- return `${y}-${m}-${day}`;
5190
- }
5191
- function computeWodContentId(blockSource) {
5192
- const sec = wodWikiCore.parseDocumentSections(blockSource, { registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS }).find(
5193
- (s) => s.scriptBlock
5194
- );
5195
- if (sec?.scriptBlock?.contentId) return sec.scriptBlock.contentId;
5196
- if (sec?.scriptBlock?.content) return wodWikiCore.blockContentId(sec.scriptBlock.content);
5197
- return void 0;
5198
- }
5199
- async function prepareJournalSessionRun(storage, input) {
5200
- const startedAt = input.startedAt ?? Date.now();
5201
- const sessionId = input.sessionId ?? mintUuid();
5202
- const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
5203
- return storage.transaction(
5204
- ["notes", "block_revisions", "block_index", "sessions", "page", "page_notes", "notebook_links"],
5205
- "readwrite",
5206
- async (tx) => {
5207
- const sourceNote = await tx.readonly("notes").get(input.noteId);
5208
- if (!sourceNote) {
5209
- throw new Error(`Note not found: ${input.noteId}`);
5210
- }
5211
- const existingSession = await tx.readonly("sessions").get(sessionId);
5212
- if (existingSession) {
5213
- throw new Error(`Session already exists: ${sessionId}`);
5214
- }
5215
- const sourceBlocks = Object.values(sourceNote.blocks);
5216
- const selectedSourceBlock = input.blockId ? sourceNote.blocks[input.blockId] ?? sourceBlocks.find((b) => b.id === input.blockId) : sourceBlocks.find((b) => b.kind === "wod");
5217
- if (!selectedSourceBlock || selectedSourceBlock.kind !== "wod") {
5218
- throw new Error(`Selected workout block is unavailable on Note '${input.noteId}'.`);
5219
- }
5220
- const nbOrigin = wodWikiWql.notebookOriginOfItem(sourceNote);
5221
- const resolvedNb = wodWikiWql.notebookOfItem(sourceNote);
5222
- const editable = wodWikiCore.isNoteEditable(sourceNote, nbOrigin, resolvedNb);
5223
- if (!editable) {
5224
- const clonedNoteId = mintUuid();
5225
- let ordinal = 0;
5226
- const clonedBlocks = wodWikiCore.reconcileNoteBlocks(sourceNote.rawContent, {
5227
- sourceRevision: 1,
5228
- registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS,
5229
- createId: () => `blk-${clonedNoteId.slice(0, 8)}-${ordinal++}`
5230
- });
5231
- const clonedBlockList = Object.values(clonedBlocks);
5232
- const mappedBlock = clonedBlockList.find(
5233
- (b) => b.kind === "wod" && b.from === selectedSourceBlock.from && b.to === selectedSourceBlock.to
5234
- ) ?? clonedBlockList.find((b) => b.kind === "wod");
5235
- if (!mappedBlock) {
5236
- throw new Error("Cloned Journal Note contains no runnable workout block.");
5237
- }
5238
- const revisions = [];
5239
- const projections = [];
5240
- let pinnedRevision;
5241
- for (const [pos, b] of clonedBlockList.entries()) {
5242
- const slice = sourceNote.rawContent.slice(b.from, b.to);
5243
- const rev = {
5244
- noteId: clonedNoteId,
5245
- blockId: b.id,
5246
- version: 1,
5247
- kind: b.kind,
5248
- rawContent: slice,
5249
- savedAt: startedAt,
5250
- ...b.dialect ? { dialect: b.dialect } : {},
5251
- ...b.sport ? { sport: b.sport } : {}
5252
- };
5253
- revisions.push(rev);
5254
- if (b.id === mappedBlock.id) pinnedRevision = rev;
5255
- const cid3 = b.kind === "wod" ? computeWodContentId(slice) : void 0;
5256
- projections.push({
5257
- id: `${clonedNoteId}:${b.id}`,
5258
- noteId: clonedNoteId,
5259
- blockId: b.id,
5260
- blockVersion: 1,
5261
- sourceRevision: 1,
5262
- from: b.from,
5263
- to: b.to,
5264
- position: pos,
5265
- dataType: b.kind,
5266
- ...cid3 ? { blockContentId: cid3 } : {},
5267
- rawContent: slice,
5268
- noteTitle: sourceNote.title,
5269
- createdAt: startedAt,
5270
- isStatic: false,
5271
- notebookId: "notebook/journal"
5272
- });
5273
- }
5274
- const provenance = buildNoteProvenance(sourceNote, resolvedNb, startedAt);
5275
- const dateEpoch = Date.parse(`${journalDate}T12:00:00Z`);
5276
- const clonedNote = {
5277
- id: clonedNoteId,
5278
- title: sourceNote.title,
5279
- rawContent: sourceNote.rawContent,
5280
- sourceRevision: 1,
5281
- blocks: clonedBlocks,
5282
- ...Number.isFinite(dateEpoch) ? { date: dateEpoch } : {},
5283
- createdAt: startedAt,
5284
- type: "journal",
5285
- sourceId: sourceNote.id,
5286
- notebookIds: ["notebook/journal"],
5287
- provenance,
5288
- ...sourceNote.tags?.length ? { tags: [...sourceNote.tags] } : {},
5289
- seedOrigin: "user"
5290
- };
5291
- let existingPages;
5292
- try {
5293
- existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
5294
- } catch {
5295
- existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
5296
- }
5297
- let targetPage = existingPages[0];
5298
- if (!targetPage) {
5299
- targetPage = {
5300
- id: mintUuid(),
5301
- date: journalDate,
5302
- title: journalDate,
5303
- createdAt: startedAt
5304
- };
5305
- await tx.readwrite("page").put(targetPage);
5306
- }
5307
- const pageNote = {
5308
- id: mintUuid(),
5309
- pageId: targetPage.id,
5310
- noteId: clonedNoteId,
5311
- createdAt: startedAt
5312
- };
5313
- const cid2 = computeWodContentId(pinnedRevision.rawContent);
5314
- const session2 = {
5315
- id: sessionId,
5316
- noteId: clonedNoteId,
5317
- blockId: mappedBlock.id,
5318
- blockVersion: 1,
5319
- ...cid2 ? { blockContentId: cid2 } : {},
5320
- origin: input.origin ?? "journal",
5321
- pageId: targetPage.id,
5322
- status: "in-progress",
5323
- startTime: startedAt,
5324
- endTime: startedAt,
5325
- duration: 0,
5326
- completed: false,
5327
- createdAt: startedAt,
5328
- notebookIds: ["notebook/journal"]
5329
- };
5330
- const links2 = [
5331
- {
5332
- id: makeNotebookLinkId("notebook/journal", "note", clonedNoteId),
5333
- notebookId: "notebook/journal",
5334
- targetKind: "note",
5335
- targetId: clonedNoteId,
5336
- noteId: clonedNoteId,
5337
- createdAt: startedAt
5338
- }
5339
- ];
5340
- await tx.readwrite("notes").put(clonedNote);
5341
- if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
5342
- if (projections.length > 0) await tx.readwrite("block_index").putMany(projections);
5343
- await tx.readwrite("page_notes").put(pageNote);
5344
- await tx.readwrite("notebook_links").putMany(links2);
5345
- return {
5346
- note: clonedNote,
5347
- revision: pinnedRevision,
5348
- session: session2,
5349
- clonedFromReadOnly: true,
5350
- upstreamNoteId: sourceNote.id
5351
- };
5352
- }
5353
- const isPlayground = sourceNote.type === "playground" || sourceNote.sourceId === "playground" || sourceNote.notebookId === "notebook/playground";
5354
- const baseNotebooks = isPlayground ? ["notebook/journal", "notebook/playground"] : ["notebook/journal"];
5355
- const mergedNotebooks = [
5356
- .../* @__PURE__ */ new Set([
5357
- ...baseNotebooks,
5358
- ...sourceNote.notebookIds ?? [],
5359
- ...sourceNote.notebookId ? [sourceNote.notebookId] : []
5360
- ])
5361
- ];
5362
- const updatedNote = JSON.stringify(sourceNote.notebookIds) === JSON.stringify(mergedNotebooks) ? sourceNote : { ...sourceNote, notebookIds: mergedNotebooks };
5363
- if (updatedNote !== sourceNote) {
5364
- await tx.readwrite("notes").put(updatedNote);
5365
- }
5366
- let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
5367
- if (!revision) {
5368
- revision = {
5369
- noteId: sourceNote.id,
5370
- blockId: selectedSourceBlock.id,
5371
- version: selectedSourceBlock.version,
5372
- kind: selectedSourceBlock.kind,
5373
- rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
5374
- savedAt: startedAt,
5375
- ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
5376
- ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
5377
- };
5378
- await tx.readwrite("block_revisions").put(revision);
5379
- }
5380
- const cid = computeWodContentId(revision.rawContent);
5381
- const effectiveOrigin = input.origin ?? (isPlayground ? "playground" : "journal");
5382
- const session = {
5383
- id: sessionId,
5384
- noteId: sourceNote.id,
5385
- blockId: selectedSourceBlock.id,
5386
- blockVersion: revision.version,
5387
- ...cid ? { blockContentId: cid } : {},
5388
- origin: effectiveOrigin,
5389
- status: "in-progress",
5390
- startTime: startedAt,
5391
- endTime: startedAt,
5392
- duration: 0,
5393
- completed: false,
5394
- createdAt: startedAt,
5395
- notebookIds: [...baseNotebooks]
5396
- };
5397
- const links = mergedNotebooks.map((nbId) => ({
5398
- id: makeNotebookLinkId(nbId, "note", sourceNote.id),
6399
+ const fm = readFrontmatterMeta(existing.rawContent);
6400
+ const nextName = args.name ?? existing.title ?? slug;
6401
+ const nextDesc = args.description ?? (typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : "");
6402
+ const nextIcon = args.icon ?? (typeof fm["icon"] === "string" ? fm["icon"].replace(/^"|"$/g, "") : "\u{1F4D3}");
6403
+ const rawContent = `---
6404
+ description: ${JSON.stringify(nextDesc)}
6405
+ icon: ${JSON.stringify(nextIcon)}
6406
+ ---
6407
+
6408
+ # ${nextName}
6409
+ `;
6410
+ const saved = await upsertNoteInStorage(ctx.storage, {
6411
+ noteId: nbId,
6412
+ title: nextName,
6413
+ rawContent
6414
+ });
6415
+ await ctx.storage.readwrite("notes").put({
6416
+ ...saved.note,
5399
6417
  notebookId: nbId,
5400
- targetKind: "note",
5401
- targetId: sourceNote.id,
5402
- noteId: sourceNote.id,
5403
- createdAt: startedAt
5404
- }));
5405
- await tx.readwrite("notebook_links").putMany(links);
6418
+ ...existing.public !== void 0 ? { public: existing.public } : {}
6419
+ });
6420
+ await ctx.onMutated?.(["notes", "block_revisions"]);
6421
+ return { action: "update", notebookId: nbId, slug, name: nextName };
6422
+ }
6423
+ if (args.action === "promote") {
6424
+ if (!args.noteId) throw new Error('`noteId` is required when action="promote".');
6425
+ const promoted = await promoteNoteToNotebooks(ctx.storage, {
6426
+ noteId: args.noteId,
6427
+ notebookIds: [nbId],
6428
+ sessionIds: args.sessionIds,
6429
+ shareSessionsPublicly: args.public
6430
+ });
6431
+ await ctx.onMutated?.(["notes", "sessions", "notebook_links"]);
5406
6432
  return {
5407
- note: updatedNote,
5408
- revision,
5409
- session,
5410
- clonedFromReadOnly: false
6433
+ action: "promote",
6434
+ noteId: args.noteId,
6435
+ notebookIds: promoted.notebookIds,
6436
+ promotedSessionIds: promoted.promotedSessionIds
5411
6437
  };
5412
6438
  }
5413
- );
5414
- }
5415
- async function resolveUpstreamProvenance(storage, note) {
5416
- const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : void 0);
5417
- if (!sourceNoteId) return null;
5418
- const upstream = await storage.readonly("notes").get(sourceNoteId);
5419
- if (upstream) {
6439
+ if (args.action === "detach") {
6440
+ if (!args.noteId) throw new Error('`noteId` is required when action="detach".');
6441
+ const remaining = await removeNoteFromNotebook(ctx.storage, args.noteId, nbId);
6442
+ await ctx.onMutated?.(["notes", "notebook_links"]);
6443
+ return {
6444
+ action: "detach",
6445
+ noteId: args.noteId,
6446
+ notebookIds: remaining
6447
+ };
6448
+ }
6449
+ if (wodWikiCore.isNonPublishableNotebook(nbId)) {
6450
+ throw new Error(`Notebook '${nbId}' is private/system and cannot be published.`);
6451
+ }
6452
+ const updated = await setNotebookPublic(ctx.storage, nbId, args.public ?? true);
6453
+ await ctx.onMutated?.(["notes"]);
5420
6454
  return {
5421
- exists: true,
5422
- sourceNoteId,
5423
- title: upstream.title,
5424
- sourceVersion: note.provenance?.sourceVersion,
5425
- currentUpstreamVersion: upstream.seedVersion ?? upstream.sourceRevision,
5426
- sourceCommit: note.provenance?.sourceCommit ?? upstream.seedCommit,
5427
- feedSourceId: note.provenance?.feedSourceId ?? upstream.feedSourceId,
5428
- sourceNotebookId: note.provenance?.sourceNotebookId ?? wodWikiWql.notebookOfItem(upstream),
5429
- sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath
6455
+ action: "set-public",
6456
+ notebookId: nbId,
6457
+ public: updated.public === true
5430
6458
  };
5431
6459
  }
5432
- return {
5433
- exists: false,
5434
- sourceNoteId,
5435
- sourceVersion: note.provenance?.sourceVersion,
5436
- sourceCommit: note.provenance?.sourceCommit,
5437
- feedSourceId: note.provenance?.feedSourceId,
5438
- sourceNotebookId: note.provenance?.sourceNotebookId,
5439
- sourcePath: note.provenance?.sourcePath
5440
- };
5441
- }
5442
- function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
5443
- return {
5444
- sourceNoteId: sourceNote.id,
5445
- sourceVersion: sourceNote.seedVersion ?? sourceNote.sourceRevision,
5446
- ...sourceNote.seedCommit ? { sourceCommit: sourceNote.seedCommit } : {},
5447
- ...sourceNote.feedSourceId ? { feedSourceId: sourceNote.feedSourceId } : {},
5448
- ...sourceNotebookId ? { sourceNotebookId } : {},
5449
- ...sourceNote.sourcePath ? { sourcePath: sourceNote.sourcePath } : {},
5450
- clonedAt
5451
- };
5452
- }
5453
-
5454
- // src/agent/tools/noteTools.ts
5455
- function isLandingNote2(note) {
6460
+ });
6461
+ var notebookDeleteInputSchema = zod.z.strictObject({
6462
+ notebookId: zod.z.string().min(1).describe("User Notebook ID or slug to delete (member Notes stay safe in notebook/journal)."),
6463
+ confirmId: zod.z.string().optional().describe("For non-interactive MCP/CLI calls, repeat the exact notebookId or slug to confirm deletion.")
6464
+ });
6465
+ var wodNotebookDeleteTool = defineAgentTool({
6466
+ name: "wod_notebook_delete",
6467
+ title: "Delete User Notebook",
6468
+ description: "Delete a user-created Notebook landing note and detach member links while keeping all member Notes safely in `notebook/journal` (Tier 2 destructive).",
6469
+ tier: 2,
6470
+ domain: "notebook",
6471
+ annotations: {
6472
+ title: "Delete User Notebook",
6473
+ readOnlyHint: false,
6474
+ destructiveHint: true,
6475
+ idempotentHint: true,
6476
+ openWorldHint: false
6477
+ },
6478
+ inputSchema: notebookDeleteInputSchema,
6479
+ cliEquivalent: "wod notebook delete <slug> --yes <slug> --json",
6480
+ async execute(args, ctx) {
6481
+ const nbId = wodWikiCore.toNotebookId(args.notebookId);
6482
+ const slug = wodWikiCore.notebookSlugFromId(nbId);
6483
+ if (RESERVED_SLUGS2.has(slug)) {
6484
+ throw new Error(`Built-in Notebook '${nbId}' cannot be deleted.`);
6485
+ }
6486
+ const matchedConfirm = args.confirmId === nbId || args.confirmId === slug ? nbId : void 0;
6487
+ await requireDestructiveConfirmation(
6488
+ ctx,
6489
+ {
6490
+ action: "wod_notebook_delete",
6491
+ targetId: nbId,
6492
+ summary: `Delete user Notebook "${slug}" (${nbId}); member Notes remain in notebook/journal`
6493
+ },
6494
+ matchedConfirm
6495
+ );
6496
+ const result = await deleteUserNotebook(ctx.storage, nbId);
6497
+ await ctx.onMutated?.(["notes", "notebook_links"]);
6498
+ return result;
6499
+ }
6500
+ });
6501
+ var NOTEBOOK_AGENT_TOOLS = [
6502
+ wodNotebookListTool,
6503
+ wodNotebookSaveTool,
6504
+ wodNotebookDeleteTool
6505
+ ];
6506
+ function isLandingNote(note) {
5456
6507
  return note.id.startsWith("notebook/") && note.notebookId === note.id;
5457
6508
  }
5458
6509
  var noteListInputSchema = zod.z.strictObject({
5459
6510
  notebookId: zod.z.string().optional().describe('Filter by notebook ID or slug (e.g. "journal", "custom", "guides", "notebook/strength").'),
5460
6511
  search: zod.z.string().optional().describe("Case-insensitive substring filter over title and Markdown content."),
5461
6512
  tag: zod.z.string().optional().describe("Filter to Notes carrying this tag label."),
5462
- includeSeed: zod.z.boolean().optional().describe("Include read-only Seed/Feed notes (default true when notebookId is specified, false otherwise)."),
6513
+ origin: zod.z.enum(["all", "user", "feed", "seed"]).optional().describe('Filter by Note origin ("user", "feed", "seed", or "all"; defaults to "all").'),
6514
+ includeSeed: zod.z.boolean().optional().describe("Include read-only Seed/Feed notes (default true; pass false for user-authored notes only)."),
6515
+ orphanedOnly: zod.z.boolean().optional().describe("When true, return only user Notes not belonging to any Notebook (equivalent to `:note{!notebook:*}`)."),
5463
6516
  limit: zod.z.number().int().min(1).max(200).optional().describe("Max notes to return (default 50).")
5464
6517
  });
5465
6518
  var wodNoteListTool = defineAgentTool({
@@ -5479,32 +6532,50 @@ var wodNoteListTool = defineAgentTool({
5479
6532
  cliEquivalent: "wod note list --json",
5480
6533
  async execute(args, ctx) {
5481
6534
  const targetNb = args.notebookId ? wodWikiCore.toNotebookId(args.notebookId) : void 0;
5482
- const includeSeed = args.includeSeed ?? Boolean(targetNb);
6535
+ const includeSeed = args.includeSeed ?? true;
6536
+ const origin = args.origin ?? "all";
6537
+ const orphanedOnly = args.orphanedOnly === true;
5483
6538
  const searchLower = args.search?.trim().toLowerCase();
5484
6539
  const tagLower = args.tag?.trim().toLowerCase();
5485
6540
  const limit = args.limit ?? 50;
5486
- const { allNotes, linkedNoteIdsForNb } = await ctx.storage.transaction(
6541
+ const { allNotes, linkedNoteIdsForNb, noteIdsWithLinks } = await ctx.storage.transaction(
5487
6542
  ["notes", "notebook_links"],
5488
6543
  "readonly",
5489
6544
  async (tx) => {
5490
6545
  const notes = await tx.readonly("notes").getAll();
5491
6546
  let linkedIds;
5492
- if (targetNb) {
5493
- try {
6547
+ const withLinks = /* @__PURE__ */ new Set();
6548
+ try {
6549
+ if (targetNb) {
5494
6550
  const links = await tx.readonly("notebook_links").getAllFromIndex("by-notebook", targetNb);
5495
6551
  linkedIds = new Set(
5496
6552
  links.filter((l) => l.targetKind === "note").map((l) => l.noteId)
5497
6553
  );
5498
- } catch {
5499
- linkedIds = /* @__PURE__ */ new Set();
5500
6554
  }
6555
+ if (orphanedOnly) {
6556
+ const allLinks = await tx.readonly("notebook_links").getAll();
6557
+ for (const link of allLinks) {
6558
+ if (link.targetKind === "note") withLinks.add(link.noteId);
6559
+ }
6560
+ }
6561
+ } catch {
6562
+ linkedIds = /* @__PURE__ */ new Set();
5501
6563
  }
5502
- return { allNotes: notes, linkedNoteIdsForNb: linkedIds };
6564
+ return { allNotes: notes, linkedNoteIdsForNb: linkedIds, noteIdsWithLinks: withLinks };
5503
6565
  }
5504
6566
  );
5505
6567
  const filtered = allNotes.filter((n) => {
5506
- if (isLandingNote2(n)) return false;
5507
- if (!includeSeed && (n.seedOrigin === "seed" || n.feedOrigin === "feed")) return false;
6568
+ if (isLandingNote(n)) return false;
6569
+ const isSeedOrFeed = n.seedOrigin === "seed" || n.feedOrigin === "feed";
6570
+ if (origin === "user" && isSeedOrFeed) return false;
6571
+ if (origin === "feed" && n.feedOrigin !== "feed") return false;
6572
+ if (origin === "seed" && n.seedOrigin !== "seed") return false;
6573
+ if (!includeSeed && isSeedOrFeed) return false;
6574
+ if (orphanedOnly) {
6575
+ if (isSeedOrFeed) return false;
6576
+ if (noteIdsWithLinks.has(n.id)) return false;
6577
+ if (wodWikiWql.notebooksOfItem(n).length > 0) return false;
6578
+ }
5508
6579
  if (targetNb) {
5509
6580
  const inNb = linkedNoteIdsForNb?.has(n.id) || n.notebookId === targetNb || (n.notebookIds ?? []).includes(targetNb) || wodWikiWql.notebooksOfItem(n).includes(targetNb);
5510
6581
  if (!inNb) return false;
@@ -5564,13 +6635,15 @@ var wodNoteGetTool = defineAgentTool({
5564
6635
  const nbOrigin = wodWikiWql.notebookOriginOfItem(note);
5565
6636
  const resolvedNb = wodWikiWql.notebookOfItem(note);
5566
6637
  const editable = wodWikiCore.isNoteEditable(note, nbOrigin, resolvedNb);
5567
- const [notebooks, provenance, visibility, sessions] = await Promise.all([
6638
+ const [notebooks, provenance, visibility, sessions, scheduleItems, revisions] = await Promise.all([
5568
6639
  getNoteNotebooks(ctx.storage, note.id),
5569
6640
  resolveUpstreamProvenance(ctx.storage, note),
5570
6641
  getNotePublicationSummary(ctx.storage, note.id),
5571
6642
  ctx.storage.readonly("sessions").getAllFromIndex("by-note", note.id).catch(
5572
6643
  async () => (await ctx.storage.readonly("sessions").getAll()).filter((s) => s.noteId === note.id)
5573
- )
6644
+ ),
6645
+ listScheduleItemsForNote(ctx.storage, note.id).catch(() => []),
6646
+ listNoteRevisions(ctx.storage, note.id).catch(() => [])
5574
6647
  ]);
5575
6648
  const sections = wodWikiCore.parseDocumentSections(note.rawContent, {
5576
6649
  registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS
@@ -5597,6 +6670,9 @@ var wodNoteGetTool = defineAgentTool({
5597
6670
  createdAt: note.createdAt,
5598
6671
  tags: note.tags ?? [],
5599
6672
  notebooks: notebooks.map((id) => ({ id, slug: wodWikiCore.notebookSlugFromId(id) })),
6673
+ scheduleCount: scheduleItems.length,
6674
+ scheduleItems,
6675
+ revisionCount: revisions.length,
5600
6676
  blocks,
5601
6677
  sessionCount: sessions.length,
5602
6678
  recentSessions: sessions.sort((a, b) => b.startTime - a.startTime).slice(0, 10).map((s) => ({
@@ -5620,7 +6696,7 @@ var noteUpsertInputSchema = zod.z.strictObject({
5620
6696
  content: zod.z.string().min(1).describe("Full Markdown document or Whiteboard Script body."),
5621
6697
  sport: zod.z.string().optional().describe("Optional sport fence tag when passing bare Whiteboard Script."),
5622
6698
  expectedSourceRevision: zod.z.number().int().min(0).optional().describe("Optimistic concurrency guard: pass the current sourceRevision from wod_note_get when updating."),
5623
- notebookId: zod.z.string().optional().describe("Optional user Notebook ID/slug to link this Note into (always stays anchored in notebook/journal)."),
6699
+ notebookId: zod.z.string().optional().describe("Optional user Notebook ID/slug to assign this Note into (omit for unfiled/existing memberships)."),
5624
6700
  journalDate: zod.z.string().optional().describe('Optional YYYY-MM-DD or "today" to place the Note on that Journal calendar day.')
5625
6701
  });
5626
6702
  var wodNoteUpsertTool = defineAgentTool({
@@ -5797,6 +6873,204 @@ var NOTE_AGENT_TOOLS = [
5797
6873
  wodNoteCloneTool,
5798
6874
  wodNoteDeleteTool
5799
6875
  ];
6876
+ var scheduleListInputSchema = zod.z.strictObject({
6877
+ from: zod.z.string().optional().describe('Start date in YYYY-MM-DD format (inclusive, or "today").'),
6878
+ to: zod.z.string().optional().describe('End date in YYYY-MM-DD format (inclusive, or "today").'),
6879
+ noteId: zod.z.string().optional().describe("Optional Note ID to list scheduled dates for one workout.")
6880
+ });
6881
+ var wodScheduleListTool = defineAgentTool({
6882
+ name: "wod_schedule_list",
6883
+ title: "List Scheduled Workouts",
6884
+ description: "List M:N ScheduleItem instances by date range (`from`/`to`) or for a specific Note ID.",
6885
+ tier: 0,
6886
+ domain: "journal",
6887
+ annotations: {
6888
+ title: "List Scheduled Workouts",
6889
+ readOnlyHint: true,
6890
+ destructiveHint: false,
6891
+ idempotentHint: true,
6892
+ openWorldHint: false
6893
+ },
6894
+ inputSchema: scheduleListInputSchema,
6895
+ cliEquivalent: "wod schedule list --json",
6896
+ async execute(args, ctx) {
6897
+ let items;
6898
+ if (args.noteId) {
6899
+ items = await listScheduleItemsForNote(ctx.storage, args.noteId);
6900
+ if (args.from) {
6901
+ const fromKey = civilDateKey(args.from);
6902
+ items = items.filter((i) => i.date >= fromKey);
6903
+ }
6904
+ if (args.to) {
6905
+ const toKey = civilDateKey(args.to);
6906
+ items = items.filter((i) => i.date <= toKey);
6907
+ }
6908
+ } else if (args.from || args.to) {
6909
+ const fromKey = civilDateKey(args.from ?? args.to);
6910
+ const toKey = civilDateKey(args.to ?? args.from);
6911
+ items = await listScheduleItemsByDateRange(ctx.storage, fromKey, toKey);
6912
+ } else {
6913
+ items = (await ctx.storage.readonly("schedule_items").getAll()).sort(
6914
+ (a, b) => a.date.localeCompare(b.date) || (a.position ?? 0) - (b.position ?? 0)
6915
+ );
6916
+ }
6917
+ const noteIds = [...new Set(items.map((i) => i.noteId))];
6918
+ const notes = await ctx.storage.readonly("notes").getMany(noteIds);
6919
+ const titleById = /* @__PURE__ */ new Map();
6920
+ notes.forEach((n, idx) => {
6921
+ if (n) titleById.set(noteIds[idx], n.title);
6922
+ });
6923
+ return {
6924
+ totalCount: items.length,
6925
+ items: items.map((item) => ({
6926
+ ...item,
6927
+ noteTitle: titleById.get(item.noteId) ?? item.noteId
6928
+ }))
6929
+ };
6930
+ }
6931
+ });
6932
+ var scheduleAddInputSchema = zod.z.strictObject({
6933
+ noteId: zod.z.string().min(1).describe("Canonical Note ID to schedule onto a calendar day."),
6934
+ date: zod.z.string().optional().describe('Calendar date YYYY-MM-DD or "today" (defaults to "today").'),
6935
+ slot: zod.z.string().optional().describe('Optional slot badge such as "AM", "PM", or "Warmup".'),
6936
+ position: zod.z.number().int().optional().describe("Optional ordering index within the day."),
6937
+ notes: zod.z.string().optional().describe("Optional scaling or session intent notes for this scheduled instance.")
6938
+ });
6939
+ var wodScheduleAddTool = defineAgentTool({
6940
+ name: "wod_schedule_add",
6941
+ title: "Schedule Workout onto Day",
6942
+ description: "Link an existing Note onto a Journal calendar date via a ScheduleItem (M:N link-first scheduling without cloning user Notes or forcing notebook/journal).",
6943
+ tier: 1,
6944
+ domain: "journal",
6945
+ annotations: {
6946
+ title: "Schedule Workout",
6947
+ readOnlyHint: false,
6948
+ destructiveHint: false,
6949
+ idempotentHint: false,
6950
+ openWorldHint: false
6951
+ },
6952
+ inputSchema: scheduleAddInputSchema,
6953
+ cliEquivalent: "wod schedule add <noteId> --date YYYY-MM-DD --json",
6954
+ async execute(args, ctx) {
6955
+ const dateKey = civilDateKey(args.date);
6956
+ const item = await scheduleNoteOnDate(ctx.storage, {
6957
+ noteId: args.noteId,
6958
+ date: dateKey,
6959
+ ...args.slot !== void 0 ? { slot: args.slot } : {},
6960
+ ...args.position !== void 0 ? { position: args.position } : {},
6961
+ ...args.notes !== void 0 ? { notes: args.notes } : {}
6962
+ });
6963
+ await ctx.onMutated?.(["schedule_items", "notes"]);
6964
+ return { item };
6965
+ }
6966
+ });
6967
+ var scheduleBatchInputSchema = zod.z.strictObject({
6968
+ items: zod.z.array(
6969
+ zod.z.strictObject({
6970
+ noteId: zod.z.string().min(1),
6971
+ date: zod.z.string().describe('Calendar date YYYY-MM-DD or "today".'),
6972
+ slot: zod.z.string().optional(),
6973
+ position: zod.z.number().int().optional(),
6974
+ notes: zod.z.string().optional()
6975
+ })
6976
+ ).min(1).describe("List of Note + date pairs to schedule atomically.")
6977
+ });
6978
+ var wodScheduleBatchTool = defineAgentTool({
6979
+ name: "wod_schedule_batch",
6980
+ title: "Batch Schedule Workouts",
6981
+ description: "Schedule one or more existing Notes across target calendar dates atomically via ScheduleItem links.",
6982
+ tier: 1,
6983
+ domain: "journal",
6984
+ annotations: {
6985
+ title: "Batch Schedule Workouts",
6986
+ readOnlyHint: false,
6987
+ destructiveHint: false,
6988
+ idempotentHint: false,
6989
+ openWorldHint: false
6990
+ },
6991
+ inputSchema: scheduleBatchInputSchema,
6992
+ cliEquivalent: "wod schedule batch --json",
6993
+ async execute(args, ctx) {
6994
+ const created = await batchScheduleNotes(
6995
+ ctx.storage,
6996
+ args.items.map((item) => ({
6997
+ noteId: item.noteId,
6998
+ date: civilDateKey(item.date),
6999
+ ...item.slot !== void 0 ? { slot: item.slot } : {},
7000
+ ...item.position !== void 0 ? { position: item.position } : {},
7001
+ ...item.notes !== void 0 ? { notes: item.notes } : {}
7002
+ }))
7003
+ );
7004
+ await ctx.onMutated?.(["schedule_items", "notes"]);
7005
+ return { scheduledCount: created.length, items: created };
7006
+ }
7007
+ });
7008
+ var scheduleUpdateInputSchema = zod.z.strictObject({
7009
+ scheduleItemId: zod.z.string().min(1).describe("ScheduleItem ID to update."),
7010
+ date: zod.z.string().optional().describe('New calendar date YYYY-MM-DD or "today".'),
7011
+ status: zod.z.enum(["planned", "completed", "moved", "skipped"]).optional().describe("Updated schedule status."),
7012
+ slot: zod.z.string().optional().describe("Updated slot label."),
7013
+ position: zod.z.number().int().optional().describe("Updated intra-day ordering index."),
7014
+ notes: zod.z.string().optional().describe("Updated intent or scaling notes.")
7015
+ });
7016
+ var wodScheduleUpdateTool = defineAgentTool({
7017
+ name: "wod_schedule_update",
7018
+ title: "Update Scheduled Workout",
7019
+ description: "Reschedule, reorder, or update status (`planned`, `completed`, `moved`, `skipped`) on a ScheduleItem.",
7020
+ tier: 1,
7021
+ domain: "journal",
7022
+ annotations: {
7023
+ title: "Update Scheduled Workout",
7024
+ readOnlyHint: false,
7025
+ destructiveHint: false,
7026
+ idempotentHint: true,
7027
+ openWorldHint: false
7028
+ },
7029
+ inputSchema: scheduleUpdateInputSchema,
7030
+ cliEquivalent: "wod schedule update <scheduleItemId> --json",
7031
+ async execute(args, ctx) {
7032
+ const updated = await updateScheduleItem(ctx.storage, args.scheduleItemId, {
7033
+ ...args.date !== void 0 ? { date: civilDateKey(args.date) } : {},
7034
+ ...args.status !== void 0 ? { status: args.status } : {},
7035
+ ...args.slot !== void 0 ? { slot: args.slot } : {},
7036
+ ...args.position !== void 0 ? { position: args.position } : {},
7037
+ ...args.notes !== void 0 ? { notes: args.notes } : {}
7038
+ });
7039
+ await ctx.onMutated?.(["schedule_items"]);
7040
+ return { item: updated };
7041
+ }
7042
+ });
7043
+ var scheduleRemoveInputSchema = zod.z.strictObject({
7044
+ scheduleItemId: zod.z.string().min(1).describe("ScheduleItem ID to remove from the calendar.")
7045
+ });
7046
+ var wodScheduleRemoveTool = defineAgentTool({
7047
+ name: "wod_schedule_remove",
7048
+ title: "Unschedule Workout Instance",
7049
+ description: "Remove a single ScheduleItem from a calendar day while leaving the canonical Note and recorded Sessions intact.",
7050
+ tier: 1,
7051
+ domain: "journal",
7052
+ annotations: {
7053
+ title: "Unschedule Workout",
7054
+ readOnlyHint: false,
7055
+ destructiveHint: false,
7056
+ idempotentHint: true,
7057
+ openWorldHint: false
7058
+ },
7059
+ inputSchema: scheduleRemoveInputSchema,
7060
+ cliEquivalent: "wod schedule remove <scheduleItemId> --json",
7061
+ async execute(args, ctx) {
7062
+ await removeScheduleItem(ctx.storage, args.scheduleItemId);
7063
+ await ctx.onMutated?.(["schedule_items"]);
7064
+ return { removed: true, scheduleItemId: args.scheduleItemId };
7065
+ }
7066
+ });
7067
+ var SCHEDULE_AGENT_TOOLS = [
7068
+ wodScheduleListTool,
7069
+ wodScheduleAddTool,
7070
+ wodScheduleBatchTool,
7071
+ wodScheduleUpdateTool,
7072
+ wodScheduleRemoveTool
7073
+ ];
5800
7074
  function statementToNode(stmt, idMap) {
5801
7075
  const meta = stmt.meta;
5802
7076
  const metrics = stmt.metrics.toArray().map((m) => ({
@@ -5973,12 +7247,13 @@ function applyCollectibleOverrides(body, overrides) {
5973
7247
  return updated;
5974
7248
  }
5975
7249
  var sessionRunHeadlessInputSchema = zod.z.strictObject({
5976
- noteId: zod.z.string().optional().describe("Existing Note ID to execute (read-only Seed/Feed Notes are automatically cloned to notebook/journal)."),
7250
+ noteId: zod.z.string().optional().describe("Existing Note ID to execute (read-only Seed/Feed Notes pin one immutable copy on first run)."),
5977
7251
  blockId: zod.z.string().optional().describe("Optional workout block ID on `noteId` (defaults to first wod block)."),
5978
7252
  source: zod.z.string().optional().describe("Inline Whiteboard Script or Markdown to persist & run when `noteId` is not supplied."),
5979
7253
  title: zod.z.string().optional().describe("Optional Note title when running inline `source`."),
5980
7254
  sport: zod.z.string().optional().describe("Optional sport dialect override."),
5981
- journalDate: zod.z.string().optional().describe('Optional YYYY-MM-DD or "today" Journal calendar date.'),
7255
+ journalDate: zod.z.string().optional().describe('Optional YYYY-MM-DD or "today" attributed Session calendar date.'),
7256
+ scheduleItemId: zod.z.string().optional().describe("Optional ScheduleItem ID that triggered this workout run."),
5982
7257
  collectibles: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number()])).optional().describe('Optional values for collectible `?` metrics (e.g. `{ "lb": 185, "reps": 12 }`).'),
5983
7258
  stepAdvanceMs: zod.z.number().int().min(100).max(36e5).optional().describe("Simulated clock advance per step in milliseconds (default 10000)."),
5984
7259
  maxSteps: zod.z.number().int().min(1).max(5e3).optional().describe("Safety cap on execution steps (default 500)."),
@@ -6019,6 +7294,7 @@ var wodSessionRunHeadlessTool = defineAgentTool({
6019
7294
  noteId: targetNoteId,
6020
7295
  blockId: args.blockId,
6021
7296
  journalDate: args.journalDate,
7297
+ ...args.scheduleItemId ? { scheduleItemId: args.scheduleItemId } : {},
6022
7298
  startedAt
6023
7299
  });
6024
7300
  const sec = wodWikiCore.parseDocumentSections(intake.revision.rawContent, {
@@ -6098,18 +7374,45 @@ var wodSessionRunHeadlessTool = defineAgentTool({
6098
7374
  const allEvents = [...eventRows, ...summaryRows];
6099
7375
  const finalizedSession = {
6100
7376
  ...intake.session,
7377
+ sessionDate: intake.session.sessionDate ?? localCivilDateKey(startedAt),
6101
7378
  status: completed ? "completed" : "in-progress",
6102
7379
  endTime,
6103
7380
  duration: Math.max(0, endTime - startedAt),
6104
7381
  completed,
6105
7382
  ...args.public !== void 0 ? { public: args.public } : {}
6106
7383
  };
6107
- await ctx.storage.transaction(["sessions", "events"], "readwrite", async (tx) => {
6108
- await tx.readwrite("sessions").put(finalizedSession);
6109
- if (allEvents.length > 0) {
6110
- await tx.readwrite("events").putMany(allEvents);
7384
+ await ctx.storage.transaction(
7385
+ ["sessions", "events", "notebook_links", "schedule_items"],
7386
+ "readwrite",
7387
+ async (tx) => {
7388
+ await tx.readwrite("sessions").put(finalizedSession);
7389
+ const nbIds = finalizedSession.notebookIds ?? [];
7390
+ const links = nbIds.map((nbId) => ({
7391
+ id: makeNotebookLinkId(wodWikiCore.toNotebookId(nbId), "session", finalizedSession.id),
7392
+ notebookId: wodWikiCore.toNotebookId(nbId),
7393
+ targetKind: "session",
7394
+ targetId: finalizedSession.id,
7395
+ noteId: finalizedSession.noteId,
7396
+ createdAt: finalizedSession.createdAt
7397
+ }));
7398
+ if (links.length > 0) {
7399
+ await tx.readwrite("notebook_links").putMany(links);
7400
+ }
7401
+ if (finalizedSession.scheduleItemId) {
7402
+ try {
7403
+ const schedStore = tx.readwrite("schedule_items");
7404
+ const item = await schedStore.get(finalizedSession.scheduleItemId);
7405
+ if (item && item.status !== "completed") {
7406
+ await schedStore.put({ ...item, status: "completed", updatedAt: endTime });
7407
+ }
7408
+ } catch {
7409
+ }
7410
+ }
7411
+ if (allEvents.length > 0) {
7412
+ await tx.readwrite("events").putMany(allEvents);
7413
+ }
6111
7414
  }
6112
- });
7415
+ );
6113
7416
  if (args.public !== void 0) {
6114
7417
  await setSessionPublic(ctx.storage, finalizedSession.id, args.public);
6115
7418
  }
@@ -6120,6 +7423,7 @@ var wodSessionRunHeadlessTool = defineAgentTool({
6120
7423
  blockId: finalizedSession.blockId,
6121
7424
  blockVersion: finalizedSession.blockVersion,
6122
7425
  clonedFromReadOnly: intake.clonedFromReadOnly,
7426
+ pinnedExternalWorkout: intake.pinnedExternalWorkout,
6123
7427
  ...intake.upstreamNoteId ? { upstreamNoteId: intake.upstreamNoteId } : {},
6124
7428
  completed,
6125
7429
  stepsExecuted: steps,
@@ -6270,10 +7574,41 @@ var wodSessionDeleteTool = defineAgentTool({
6270
7574
  return { deleted, sessionId: args.sessionId };
6271
7575
  }
6272
7576
  });
7577
+ var sessionAttributeInputSchema = zod.z.strictObject({
7578
+ sessionId: zod.z.string().min(1).describe("Session ID to attribute to a calendar date or ScheduleItem."),
7579
+ sessionDate: zod.z.string().optional().describe("Attributed Journal date (YYYY-MM-DD)."),
7580
+ scheduleItemId: zod.z.string().nullable().optional().describe("ScheduleItem ID to link this Session with, or null to unlink into an ad-hoc Session.")
7581
+ });
7582
+ var wodSessionAttributeTool = defineAgentTool({
7583
+ name: "wod_session_attribute",
7584
+ title: "Attribute Session to Day or Plan",
7585
+ description: "Associate a recorded workout Session with a specific Journal civil date and/or pair or unlink it with a planned ScheduleItem.",
7586
+ tier: 1,
7587
+ domain: "session",
7588
+ annotations: {
7589
+ title: "Attribute Session",
7590
+ readOnlyHint: false,
7591
+ destructiveHint: false,
7592
+ idempotentHint: true,
7593
+ openWorldHint: false
7594
+ },
7595
+ inputSchema: sessionAttributeInputSchema,
7596
+ cliEquivalent: "wod session attribute <sessionId> --json",
7597
+ async execute(args, ctx) {
7598
+ const updated = await attributeSession(ctx.storage, {
7599
+ sessionId: args.sessionId,
7600
+ ...args.sessionDate !== void 0 ? { sessionDate: args.sessionDate } : {},
7601
+ ...args.scheduleItemId !== void 0 ? { scheduleItemId: args.scheduleItemId } : {}
7602
+ });
7603
+ await ctx.onMutated?.(["sessions", "schedule_items"]);
7604
+ return { session: updated };
7605
+ }
7606
+ });
6273
7607
  var SESSION_AGENT_TOOLS = [
6274
7608
  wodSessionRunHeadlessTool,
6275
7609
  wodSessionListTool,
6276
7610
  wodSessionGetTool,
7611
+ wodSessionAttributeTool,
6277
7612
  wodSessionDeleteTool
6278
7613
  ];
6279
7614
  var validateWqlInputSchema = zod.z.strictObject({
@@ -6425,6 +7760,7 @@ var DOMAIN_AGENT_TOOLS = [
6425
7760
  ...WQL_AGENT_TOOLS,
6426
7761
  ...NOTE_AGENT_TOOLS,
6427
7762
  ...JOURNAL_AGENT_TOOLS,
7763
+ ...SCHEDULE_AGENT_TOOLS,
6428
7764
  ...NOTEBOOK_AGENT_TOOLS,
6429
7765
  ...SESSION_AGENT_TOOLS,
6430
7766
  ...CATALOG_AGENT_TOOLS,
@@ -6800,6 +8136,12 @@ exports.wodNotebookSaveTool = wodNotebookSaveTool;
6800
8136
  exports.wodParseScriptTool = wodParseScriptTool;
6801
8137
  exports.wodQueryWqlTool = wodQueryWqlTool;
6802
8138
  exports.wodResetStorageTool = wodResetStorageTool;
8139
+ exports.wodScheduleAddTool = wodScheduleAddTool;
8140
+ exports.wodScheduleBatchTool = wodScheduleBatchTool;
8141
+ exports.wodScheduleListTool = wodScheduleListTool;
8142
+ exports.wodScheduleRemoveTool = wodScheduleRemoveTool;
8143
+ exports.wodScheduleUpdateTool = wodScheduleUpdateTool;
8144
+ exports.wodSessionAttributeTool = wodSessionAttributeTool;
6803
8145
  exports.wodSessionDeleteTool = wodSessionDeleteTool;
6804
8146
  exports.wodSessionGetTool = wodSessionGetTool;
6805
8147
  exports.wodSessionListTool = wodSessionListTool;