@bitcobblers/wod-wiki-engine 0.61.2259 → 0.62.2261

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/index.cjs CHANGED
@@ -941,13 +941,13 @@ function csvToTelemetryBundle(csv) {
941
941
  }
942
942
 
943
943
  // src/version.ts
944
- var VERSION = "0.61.2259";
945
- var GIT_SHA = "e65814e";
946
- var BUILD_TIME = "2026-11-21T02:31:54.391Z";
944
+ var VERSION = "0.62.2261";
945
+ var GIT_SHA = "e0e9bb0";
946
+ var BUILD_TIME = "2026-11-23T01:20:07.186Z";
947
947
  var SEMVER = {
948
- version: "0.61.2259",
949
- gitSha: "e65814e",
950
- buildTime: "2026-11-21T02:31:54.391Z"
948
+ version: "0.62.2261",
949
+ gitSha: "e0e9bb0",
950
+ buildTime: "2026-11-23T01:20:07.186Z"
951
951
  };
952
952
  var SEED_SCHEMA = 9;
953
953
  var SEED_REGISTERED_WIDGETS = wodWikiCore.KNOWN_SECTION_WIDGETS;
@@ -971,6 +971,10 @@ function seedPrecedenceRank(sourceIdOrMetaKey, explicitTier) {
971
971
  return SEED_PRECEDENCE_RANK[seedSourceTier(sourceIdOrMetaKey, explicitTier)];
972
972
  }
973
973
  var SEED_BROADCAST_CHANNEL = "wodwiki.seed";
974
+ var FEED_INDEX_META_PREFIX = "feed:index:";
975
+ function feedIndexMetaKey(feedId, notebookId) {
976
+ return `${FEED_INDEX_META_PREFIX}${feedId}:${notebookId}`;
977
+ }
974
978
  var EFFORTS_CHUNK_ID = "efforts";
975
979
  var EQUIPMENT_CHUNK_ID = "equipment";
976
980
  var CANVAS_CHUNK_ID = "canvas";
@@ -1019,42 +1023,149 @@ function nonnegative(value) {
1019
1023
  function finite(value) {
1020
1024
  return typeof value === "number" && Number.isFinite(value);
1021
1025
  }
1026
+ function isSafeRelativePath(value) {
1027
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split("/").includes("..");
1028
+ }
1029
+ function isSafeRawUrlOrPath(value) {
1030
+ if (typeof value !== "string" || !value.trim()) return false;
1031
+ if (/^https?:\/\//i.test(value)) {
1032
+ try {
1033
+ const parsed = new URL(value);
1034
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && !parsed.username && !parsed.password;
1035
+ } catch {
1036
+ return false;
1037
+ }
1038
+ }
1039
+ return isSafeRelativePath(value);
1040
+ }
1022
1041
  function assertSeedManifest(value) {
1023
- if (!object(value) || value.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; rebuild seed artifacts");
1024
- 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");
1025
- for (const key of ["versionLabel", "commit", "name", "description"]) if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
1026
- 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");
1042
+ if (!object(value)) throw new Error("Incompatible seed schema; rebuild seed artifacts");
1043
+ const hasNotebooks = Array.isArray(value.notebooks);
1044
+ if (value.schema === void 0) {
1045
+ if (!hasNotebooks) throw new Error("Incompatible seed schema; rebuild seed artifacts");
1046
+ } else if (!positive(value.schema) || value.schema !== SEED_SCHEMA && !hasNotebooks) {
1047
+ throw new Error("Incompatible seed schema; rebuild seed artifacts");
1048
+ }
1049
+ const normalizedSchema = value.schema === void 0 ? SEED_SCHEMA : value.schema;
1050
+ const normalizedVersion = value.version === void 0 && hasNotebooks ? 1 : value.version;
1051
+ const normalizedBuiltAt = value.builtAt === void 0 && hasNotebooks ? (/* @__PURE__ */ new Date(0)).toISOString() : value.builtAt;
1052
+ const normalizedChunks = value.chunks === void 0 && hasNotebooks ? [] : value.chunks;
1053
+ if (!nonnegative(normalizedVersion) || typeof normalizedBuiltAt !== "string" || !Number.isFinite(Date.parse(normalizedBuiltAt)) || !Array.isArray(normalizedChunks)) {
1054
+ throw new Error("seed manifest failed shape validation");
1055
+ }
1056
+ for (const key of ["versionLabel", "commit", "name", "description"]) {
1057
+ if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
1058
+ }
1059
+ if (value.repositoryUrl !== void 0 && (typeof value.repositoryUrl !== "string" || !/^https:\/\//.test(value.repositoryUrl) || new URL(value.repositoryUrl).username || new URL(value.repositoryUrl).password)) {
1060
+ throw new Error("invalid seed repository URL");
1061
+ }
1027
1062
  if (value.dirty !== void 0 && typeof value.dirty !== "boolean") throw new Error("invalid seed manifest metadata");
1063
+ for (const key of ["indexBytes", "chunkBytes"]) {
1064
+ if (value[key] !== void 0 && !nonnegative(value[key])) throw new Error("invalid seed manifest metadata");
1065
+ }
1028
1066
  const ids = /* @__PURE__ */ new Set(), paths = /* @__PURE__ */ new Set();
1029
- for (const chunk of value.chunks) {
1030
- 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");
1067
+ for (const chunk of normalizedChunks) {
1068
+ 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)) {
1069
+ throw new Error("seed manifest failed shape validation");
1070
+ }
1031
1071
  ids.add(chunk.id);
1032
1072
  paths.add(chunk.path);
1033
1073
  }
1074
+ let normalizedNotebooks;
1034
1075
  if (value.notebooks !== void 0) {
1035
1076
  if (!Array.isArray(value.notebooks)) throw new Error("seed manifest failed shape validation");
1077
+ normalizedNotebooks = [];
1036
1078
  for (const nb of value.notebooks) {
1037
- 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)) {
1079
+ if (!object(nb) || typeof nb.notebookId !== "string" || !nb.notebookId || typeof nb.label !== "string" || !nonnegative(nb.count) || !isSafeRawUrlOrPath(nb.indexPath)) {
1038
1080
  throw new Error("seed manifest failed shape validation");
1039
1081
  }
1040
1082
  if ("records" in nb && Array.isArray(nb.records)) {
1041
1083
  throw new Error("seed manifest failed shape validation: manifest.notebooks must not contain inline records");
1042
1084
  }
1085
+ if (nb.version !== void 0 && !nonnegative(nb.version)) throw new Error("seed manifest failed shape validation");
1086
+ if (nb.commit !== void 0 && typeof nb.commit !== "string") throw new Error("seed manifest failed shape validation");
1087
+ if (nb.builtAt !== void 0 && typeof nb.builtAt !== "string") throw new Error("seed manifest failed shape validation");
1088
+ if (nb.sha256 !== void 0 && typeof nb.sha256 !== "string") throw new Error("seed manifest failed shape validation");
1089
+ if (nb.bytes !== void 0 && !nonnegative(nb.bytes)) throw new Error("seed manifest failed shape validation");
1090
+ if (nb.indexBytes !== void 0 && !nonnegative(nb.indexBytes)) throw new Error("seed manifest failed shape validation");
1091
+ if (nb.chunkBytes !== void 0 && !nonnegative(nb.chunkBytes)) throw new Error("seed manifest failed shape validation");
1092
+ normalizedNotebooks.push({
1093
+ ...nb,
1094
+ version: nb.version ?? normalizedVersion,
1095
+ commit: nb.commit ?? "",
1096
+ builtAt: nb.builtAt ?? normalizedBuiltAt,
1097
+ sha256: nb.sha256 ?? "",
1098
+ bytes: nb.bytes ?? nb.indexBytes ?? 0
1099
+ });
1043
1100
  }
1044
1101
  }
1045
- return value;
1102
+ return {
1103
+ ...value,
1104
+ schema: normalizedSchema,
1105
+ version: normalizedVersion,
1106
+ builtAt: normalizedBuiltAt,
1107
+ chunks: normalizedChunks,
1108
+ ...normalizedNotebooks !== void 0 ? { notebooks: normalizedNotebooks } : {}
1109
+ };
1046
1110
  }
1047
1111
  function assertNotebookIndex(value) {
1048
1112
  if (!object(value)) throw new Error("notebook index failed shape validation");
1049
- 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)) {
1113
+ if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || !value.label || !isSafeRawUrlOrPath(value.indexPath) || !nonnegative(value.count) || !Array.isArray(value.records)) {
1050
1114
  throw new Error("notebook index failed shape validation: missing required index summary or records");
1051
1115
  }
1116
+ if (value.version !== void 0 && !nonnegative(value.version)) throw new Error("notebook index failed shape validation: missing required index summary or records");
1117
+ if (value.commit !== void 0 && typeof value.commit !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
1118
+ if (value.builtAt !== void 0 && typeof value.builtAt !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
1119
+ if (value.sha256 !== void 0 && typeof value.sha256 !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
1120
+ if (value.bytes !== void 0 && !nonnegative(value.bytes)) throw new Error("notebook index failed shape validation: missing required index summary or records");
1121
+ const normalizedRecords = [];
1052
1122
  for (const r of value.records) {
1053
- 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") {
1123
+ if (!object(r) || typeof r.uuid !== "string" || !r.uuid || !isSafeRelativePath(r.path)) {
1124
+ throw new Error("notebook index failed shape validation: invalid record ref");
1125
+ }
1126
+ const hasRecordPath = r.recordPath !== void 0;
1127
+ const hasRawUrl = r.rawUrl !== void 0;
1128
+ const hasMdPath = /\.md$/i.test(r.path);
1129
+ if (hasRecordPath && !isSafeRelativePath(r.recordPath)) {
1054
1130
  throw new Error("notebook index failed shape validation: invalid record ref");
1055
1131
  }
1132
+ if (hasRawUrl && !isSafeRawUrlOrPath(r.rawUrl)) {
1133
+ throw new Error("notebook index failed shape validation: invalid record ref");
1134
+ }
1135
+ if (!hasRecordPath && !hasRawUrl && !hasMdPath) {
1136
+ throw new Error("notebook index failed shape validation: invalid record ref");
1137
+ }
1138
+ if (r.commit !== void 0 && typeof r.commit !== "string") {
1139
+ throw new Error("notebook index failed shape validation: invalid record ref");
1140
+ }
1141
+ if (r.version !== void 0 && !nonnegative(r.version)) {
1142
+ throw new Error("notebook index failed shape validation: invalid record ref");
1143
+ }
1144
+ if (r.sha256 !== void 0 && typeof r.sha256 !== "string") {
1145
+ throw new Error("notebook index failed shape validation: invalid record ref");
1146
+ }
1147
+ if (r.title !== void 0 && typeof r.title !== "string") {
1148
+ throw new Error("notebook index failed shape validation: invalid record ref");
1149
+ }
1150
+ if (r.date !== void 0 && !finite(r.date)) {
1151
+ throw new Error("notebook index failed shape validation: invalid record ref");
1152
+ }
1153
+ normalizedRecords.push({
1154
+ ...r,
1155
+ commit: r.commit ?? "",
1156
+ version: r.version ?? 1,
1157
+ sha256: r.sha256 ?? ""
1158
+ });
1056
1159
  }
1057
- return value;
1160
+ return {
1161
+ ...value,
1162
+ version: value.version ?? 1,
1163
+ commit: value.commit ?? "",
1164
+ builtAt: value.builtAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
1165
+ sha256: value.sha256 ?? "",
1166
+ bytes: value.bytes ?? 0,
1167
+ records: normalizedRecords
1168
+ };
1058
1169
  }
1059
1170
  function assertTelemetry(row, blockIndex) {
1060
1171
  if (row.telemetry === void 0) return;
@@ -1682,31 +1793,38 @@ async function prepareSeedChunkWrite(write) {
1682
1793
  return { write, ids, pagesBySlug, linkIds, tagIds };
1683
1794
  }
1684
1795
  async function applySeedChunks(storage, writes) {
1685
- const empty = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1796
+ const empty = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, preservedPinned: 0, addedNotes: 0, updatedNotes: 0 };
1686
1797
  if (!writes.length) return empty;
1687
1798
  const prepared = await Promise.all(writes.map(prepareSeedChunkWrite));
1688
- return storage.transaction(SEED_TX_STORES, "readwrite", async (tx) => {
1689
- const total = { ...empty };
1690
- for (const item of prepared) {
1691
- const part = await applyPreparedSeedChunkInTx(tx, item);
1692
- total.totalNotes += part.totalNotes;
1693
- total.totalEfforts += part.totalEfforts;
1694
- total.totalEquipment += part.totalEquipment;
1695
- total.totalBlocks += part.totalBlocks;
1696
- total.skippedUserOwned += part.skippedUserOwned;
1697
- total.deleted += part.deleted;
1698
- total.addedNotes += part.addedNotes;
1699
- total.updatedNotes += part.updatedNotes;
1700
- }
1701
- return total;
1702
- });
1799
+ const total = { ...empty };
1800
+ for (let i = 0; i < prepared.length; i++) {
1801
+ const item = prepared[i];
1802
+ const part = await storage.transaction(
1803
+ SEED_TX_STORES,
1804
+ "readwrite",
1805
+ (tx) => applyPreparedSeedChunkInTx(tx, item)
1806
+ );
1807
+ total.totalNotes += part.totalNotes;
1808
+ total.totalEfforts += part.totalEfforts;
1809
+ total.totalEquipment += part.totalEquipment;
1810
+ total.totalBlocks += part.totalBlocks;
1811
+ total.skippedUserOwned += part.skippedUserOwned;
1812
+ total.deleted += part.deleted;
1813
+ total.preservedPinned = (total.preservedPinned ?? 0) + (part.preservedPinned ?? 0);
1814
+ total.addedNotes += part.addedNotes;
1815
+ total.updatedNotes += part.updatedNotes;
1816
+ if (i + 1 < prepared.length) {
1817
+ await new Promise((resolve) => setTimeout(resolve, 0));
1818
+ }
1819
+ }
1820
+ return total;
1703
1821
  }
1704
1822
  async function applySeedChunk(storage, write) {
1705
1823
  return applySeedChunks(storage, [write]);
1706
1824
  }
1707
1825
  async function applyPreparedSeedChunkInTx(tx, prepared) {
1708
1826
  const { write, ids, pagesBySlug, linkIds, tagIds } = prepared;
1709
- const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1827
+ const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, preservedPinned: 0, addedNotes: 0, updatedNotes: 0 };
1710
1828
  const metaStore = tx.readwrite("meta");
1711
1829
  const userDeleted = /* @__PURE__ */ new Set();
1712
1830
  for (const row of await metaStore.getAll()) {
@@ -1715,7 +1833,9 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1715
1833
  }
1716
1834
  const actualMeta = await metaStore.get(write.meta.key);
1717
1835
  if (!equal(actualMeta, write.expectedMeta)) throw new Error("Seed checkpoint changed during import");
1718
- if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; recreate artifacts");
1836
+ if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA && !Array.isArray(write.manifest.notebooks)) {
1837
+ throw new Error("Incompatible seed schema; recreate artifacts");
1838
+ }
1719
1839
  const noteStore = tx.readwrite("notes");
1720
1840
  const priorIds = write.chunkId ? write.expectedMeta?.chunks[write.chunkId]?.noteIds ?? [] : [];
1721
1841
  const declared = new Set((write.chunkId ? write.meta.chunks[write.chunkId]?.noteIds : void 0) ?? ids);
@@ -1779,6 +1899,23 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1779
1899
  const changedTags = [], changedNotes = [], revisions = [], pages = [], pageNotes = [], noteTags = [];
1780
1900
  const blocks = [], blockEfforts = [], blockEquipment = [];
1781
1901
  const sessionStore = tx.readwrite("sessions"), eventStore = tx.readwrite("events");
1902
+ const pinnedNoteIds = /* @__PURE__ */ new Set();
1903
+ if (ownedIds.length > 0) {
1904
+ let existingSessionsByNote;
1905
+ try {
1906
+ existingSessionsByNote = await sessionStore.getAllFromIndexMany("by-note", ownedIds);
1907
+ } catch {
1908
+ const allSessions = await sessionStore.getAll();
1909
+ existingSessionsByNote = ownedIds.map((nid) => allSessions.filter((s) => s.noteId === nid));
1910
+ }
1911
+ for (let i = 0; i < ownedIds.length; i++) {
1912
+ const nid = ownedIds[i];
1913
+ const existing = existingById.get(nid);
1914
+ if (existing?.retention === "session-pinned" || (existingSessionsByNote[i]?.length ?? 0) > 0) {
1915
+ pinnedNoteIds.add(nid);
1916
+ }
1917
+ }
1918
+ }
1782
1919
  const telemetrySessionIds = write.rows.flatMap((row) => row.telemetry?.sessions.map((session) => session.id) ?? []);
1783
1920
  const storedTelemetrySessions = await sessionStore.getMany(telemetrySessionIds);
1784
1921
  const existingTelemetrySessions = new Map(telemetrySessionIds.map((sessionId, i) => [sessionId, storedTelemetrySessions[i]]));
@@ -1818,7 +1955,29 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1818
1955
  date = ts;
1819
1956
  }
1820
1957
  const seedCommit = row.commit ?? write.manifest.commit;
1821
- const note = { ...existing, id, title, rawContent: row.content, sourceRevision, blocks: map, createdAt: write.manifest.version, ...date === void 0 ? {} : { date }, type: write.chunkId === DASHBOARDS_CHUNK_ID ? "dashboard" : "note", sourceId, seedOrigin: "seed", seedVersion: write.manifest.version, seedChunkId: write.chunkId ?? void 0, feedOrigin: "feed", feedSourceId, sourcePath: row.path, ...seedCommit ? { seedCommit } : {} };
1958
+ const existingRetention = existing;
1959
+ const resolvedPin = pinnedNoteIds.has(id) || existingRetention?.retention === "session-pinned" ? "session-pinned" : existingRetention?.retention === "schedule-pinned" ? "schedule-pinned" : void 0;
1960
+ const note = {
1961
+ ...existing,
1962
+ id,
1963
+ title,
1964
+ rawContent: row.content,
1965
+ sourceRevision,
1966
+ blocks: map,
1967
+ createdAt: write.manifest.version,
1968
+ ...date === void 0 ? {} : { date },
1969
+ type: write.chunkId === DASHBOARDS_CHUNK_ID ? "dashboard" : "note",
1970
+ sourceId,
1971
+ seedOrigin: "seed",
1972
+ seedVersion: write.manifest.version,
1973
+ seedChunkId: write.chunkId ?? void 0,
1974
+ feedOrigin: "feed",
1975
+ feedSourceId,
1976
+ sourcePath: row.path,
1977
+ ...seedCommit ? { seedCommit } : {},
1978
+ ...resolvedPin ? { retention: resolvedPin } : existingRetention?.retention ? { retention: existingRetention.retention } : {},
1979
+ ...resolvedPin || existingRetention?.upstreamStatus ? { upstreamStatus: "live" } : {}
1980
+ };
1822
1981
  if (date === void 0) delete note.date;
1823
1982
  if (!equal(note, existing)) changedNotes.push(note);
1824
1983
  const byRange = new Map(Object.values(map).map((b) => [`${b.from}:${b.to}`, b]));
@@ -1910,12 +2069,30 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1910
2069
  result.totalNotes++;
1911
2070
  result.totalBlocks += Object.keys(map).length;
1912
2071
  }
2072
+ const preservedGoneIds = new Set(
2073
+ goneIds.filter(
2074
+ (id) => owned.has(id) && (pinnedNoteIds.has(id) || existingById.get(id)?.retention === "schedule-pinned")
2075
+ )
2076
+ );
1913
2077
  const wantedBlocks = new Set(blocks.map((b) => b.id)), wantedEfforts = new Set(blockEfforts.map((b) => b.id)), wantedEquipment = new Set(blockEquipment.map((b) => b.id));
1914
- for (const rows of currentIndexes) for (const row of rows) if (row.isStatic === true && !wantedBlocks.has(row.id)) await indexStore.delete(row.id);
1915
- for (const rows of currentEfforts) for (const row of rows) if (row.isStatic === true && !wantedEfforts.has(row.id)) await effortLinks.delete(row.id);
1916
- for (const rows of currentEquipment) for (const row of rows) if (row.isStatic === true && !wantedEquipment.has(row.id)) await equipmentLinks.delete(row.id);
2078
+ for (const rows of currentIndexes) for (const row of rows) if (row.isStatic === true && !wantedBlocks.has(row.id) && !preservedGoneIds.has(row.noteId)) await indexStore.delete(row.id);
2079
+ for (const rows of currentEfforts) for (const row of rows) if (row.isStatic === true && !wantedEfforts.has(row.id) && !preservedGoneIds.has(row.noteId)) await effortLinks.delete(row.id);
2080
+ for (const rows of currentEquipment) for (const row of rows) if (row.isStatic === true && !wantedEquipment.has(row.id) && !preservedGoneIds.has(row.noteId)) await equipmentLinks.delete(row.id);
1917
2081
  for (const id of goneIds) {
1918
- if (!owned.has(id) || !existingById.get(id)) continue;
2082
+ if (!owned.has(id)) continue;
2083
+ const existing = existingById.get(id);
2084
+ if (!existing) continue;
2085
+ const preservedRetention = pinnedNoteIds.has(id) || existing.retention === "session-pinned" ? "session-pinned" : existing.retention === "schedule-pinned" ? "schedule-pinned" : void 0;
2086
+ if (preservedRetention) {
2087
+ const preserved = {
2088
+ ...existing,
2089
+ retention: preservedRetention,
2090
+ upstreamStatus: "removed"
2091
+ };
2092
+ if (!equal(preserved, existing)) changedNotes.push(preserved);
2093
+ result.preservedPinned = (result.preservedPinned ?? 0) + 1;
2094
+ continue;
2095
+ }
1919
2096
  const n = slot.get(id);
1920
2097
  await noteStore.delete(id);
1921
2098
  for (const link of currentTags[n]) await tagLinks.delete(link.id);
@@ -2234,22 +2411,58 @@ function buildQueryServiceStoresFromStorage(storage, options = {}) {
2234
2411
  relationStore: {
2235
2412
  getBatches: async (noteIds) => {
2236
2413
  const bundles = /* @__PURE__ */ new Map();
2237
- for (const noteId of noteIds) {
2238
- const links = await storage.readonly("page_notes").getAllFromIndex("by-note", noteId);
2239
- const tagLinks = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
2240
- const tags = await storage.readonly("tags").getMany(tagLinks.map((l) => l.tagId));
2241
- const pages = await storage.readonly("page").getMany([...new Set(links.map((l) => l.pageId))]);
2242
- bundles.set(noteId, {
2243
- tags: tags.flatMap((t) => t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : []),
2244
- links,
2245
- pages: pages.filter((p) => p !== void 0)
2246
- });
2247
- }
2248
- return bundles;
2414
+ const uniqueIds = [...new Set(noteIds)];
2415
+ if (uniqueIds.length === 0) return bundles;
2416
+ return storage.transaction(["page_notes", "note_tags", "tags", "page"], "readonly", async (tx) => {
2417
+ const [pageLinkGroups, tagLinkGroups] = await Promise.all([
2418
+ tx.readonly("page_notes").getAllFromIndexMany("by-note", uniqueIds),
2419
+ tx.readonly("note_tags").getAllFromIndexMany("by-note", uniqueIds)
2420
+ ]);
2421
+ const tagIds = /* @__PURE__ */ new Set();
2422
+ const pageIds = /* @__PURE__ */ new Set();
2423
+ for (const group of tagLinkGroups) for (const link of group) tagIds.add(link.tagId);
2424
+ for (const group of pageLinkGroups) for (const link of group) pageIds.add(link.pageId);
2425
+ const [tagRows, pageRows] = await Promise.all([
2426
+ tx.readonly("tags").getMany([...tagIds]),
2427
+ tx.readonly("page").getMany([...pageIds])
2428
+ ]);
2429
+ const tagById = new Map([...tagIds].map((id, i) => [id, tagRows[i]]));
2430
+ const pageById = new Map([...pageIds].map((id, i) => [id, pageRows[i]]));
2431
+ for (let i = 0; i < uniqueIds.length; i++) {
2432
+ const noteId = uniqueIds[i];
2433
+ const links = pageLinkGroups[i] ?? [];
2434
+ const tagLinks = tagLinkGroups[i] ?? [];
2435
+ bundles.set(noteId, {
2436
+ tags: tagLinks.flatMap((l) => {
2437
+ const t = tagById.get(l.tagId);
2438
+ return t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : [];
2439
+ }),
2440
+ links,
2441
+ pages: links.flatMap((l) => {
2442
+ const p = pageById.get(l.pageId);
2443
+ return p ? [p] : [];
2444
+ })
2445
+ });
2446
+ }
2447
+ return bundles;
2448
+ });
2249
2449
  }
2250
2450
  },
2251
2451
  feedCatalogStore
2252
2452
  };
2453
+ const scheduleStore = {
2454
+ getAll: async () => storage.readonly("schedule_items").getAll().catch(() => []),
2455
+ getForNote: async (noteId) => storage.readonly("schedule_items").getAllFromIndex("by-note", noteId).catch(() => []),
2456
+ getByDateRange: async (fromDate, toDate) => {
2457
+ try {
2458
+ return (await storage.readonly("schedule_items").getAll()).filter(
2459
+ (item) => item.date >= fromDate && item.date <= toDate
2460
+ );
2461
+ } catch {
2462
+ return [];
2463
+ }
2464
+ }
2465
+ };
2253
2466
  const sessionStore = {
2254
2467
  getAll: async () => {
2255
2468
  const rows = await storage.readonly("sessions").getAll();
@@ -2262,11 +2475,13 @@ function buildQueryServiceStoresFromStorage(storage, options = {}) {
2262
2475
  createdAt: s.createdAt,
2263
2476
  ...s.notebookIds ? { notebookIds: s.notebookIds } : {},
2264
2477
  ...s.blockContentId ? { blockContentId: s.blockContentId } : {},
2265
- ...s.completed !== void 0 ? { completed: s.completed } : {}
2478
+ ...s.completed !== void 0 ? { completed: s.completed } : {},
2479
+ ...s.sessionDate ? { sessionDate: s.sessionDate } : {},
2480
+ ...s.scheduleItemId ? { scheduleItemId: s.scheduleItemId } : {}
2266
2481
  }));
2267
2482
  }
2268
2483
  };
2269
- Object.assign(stores, { sessionStore });
2484
+ Object.assign(stores, { scheduleStore, sessionStore });
2270
2485
  if (options.datasetStore) {
2271
2486
  stores.datasetStore = options.datasetStore;
2272
2487
  }
@@ -3032,6 +3247,9 @@ var HttpFeedTree = class {
3032
3247
  const text = decodeUtf8(await this.read(path));
3033
3248
  return JSON.parse(text);
3034
3249
  }
3250
+ async readText(path) {
3251
+ return decodeUtf8(await this.read(path));
3252
+ }
3035
3253
  async stat(path) {
3036
3254
  try {
3037
3255
  const bytes = await this.read(path);
@@ -3866,7 +4084,7 @@ function isNotebookLandingNote(note) {
3866
4084
  function baseUserMemberships(note) {
3867
4085
  if (note.seedOrigin === "seed" || note.feedOrigin === "feed") return [];
3868
4086
  if (isNotebookLandingNote(note) || isPropertyDefinitionNoteId(note.id)) return [];
3869
- const base = ["notebook/journal"];
4087
+ const base = [];
3870
4088
  if (note.type === "playground" || note.sourceId === "playground") {
3871
4089
  base.push("notebook/playground");
3872
4090
  }
@@ -3984,7 +4202,6 @@ async function promoteNoteToNotebooks(storage, input) {
3984
4202
  for (const sess of sessions) {
3985
4203
  if (!wantedSessions.has(sess.id)) continue;
3986
4204
  const sessNotebooks = dedupeNotebooks([
3987
- "notebook/journal",
3988
4205
  ...sess.notebookIds ?? [],
3989
4206
  ...requestedTargets
3990
4207
  ]);
@@ -4027,12 +4244,12 @@ async function setNoteNotebooks(storage, input) {
4027
4244
  if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
4028
4245
  throw new Error(`Read-only Feed Note '${input.noteId}' cannot change Notebook membership.`);
4029
4246
  }
4030
- const userTargets = requested.filter(
4031
- (id) => id !== "notebook/journal" && id !== "notebook/playground"
4032
- );
4247
+ const userTargets = requested.filter((id) => id !== "notebook/playground");
4033
4248
  for (const target of userTargets) {
4034
- await assertWritableTargetNotebook(tx, target);
4035
- await ensureUserNotebookLanding(tx, target, now);
4249
+ if (target !== "notebook/journal") {
4250
+ await assertWritableTargetNotebook(tx, target);
4251
+ await ensureUserNotebookLanding(tx, target, now);
4252
+ }
4036
4253
  }
4037
4254
  const finalMemberships = dedupeNotebooks([
4038
4255
  ...baseUserMemberships(note),
@@ -4072,9 +4289,6 @@ async function setNoteNotebooks(storage, input) {
4072
4289
  }
4073
4290
  async function removeNoteFromNotebook(storage, noteId, notebookIdOrSlug) {
4074
4291
  const target = wodWikiCore.toNotebookId(notebookIdOrSlug);
4075
- if (target === "notebook/journal") {
4076
- throw new Error("Notes cannot be removed from private notebook/journal.");
4077
- }
4078
4292
  const current = await getNoteNotebooks(storage, noteId);
4079
4293
  const remaining = current.filter((id) => id !== target);
4080
4294
  return setNoteNotebooks(storage, { noteId, notebookIds: remaining });
@@ -4088,11 +4302,12 @@ async function getNoteNotebooks(storage, noteId) {
4088
4302
  linkNotebookIds = links.filter((l) => l.targetKind === "note" && l.targetId === noteId).map((l) => l.notebookId);
4089
4303
  } catch {
4090
4304
  }
4305
+ const hasExplicitArray = Array.isArray(note.notebookIds);
4091
4306
  return dedupeNotebooks([
4092
4307
  ...baseUserMemberships(note),
4093
4308
  ...note.notebookIds ?? [],
4094
4309
  ...linkNotebookIds,
4095
- ...wodWikiWql.notebooksOfItem(note)
4310
+ ...hasExplicitArray ? [] : wodWikiWql.notebooksOfItem(note)
4096
4311
  ]);
4097
4312
  }
4098
4313
 
@@ -4210,17 +4425,184 @@ async function setSessionPublic(storage, sessionId, isPublic) {
4210
4425
  return updated;
4211
4426
  });
4212
4427
  }
4428
+ var cachedDefaultReferenceIndex = null;
4429
+ function defaultLazyReferenceIndex() {
4430
+ if (!cachedDefaultReferenceIndex) {
4431
+ cachedDefaultReferenceIndex = wodWikiLang.createReferenceIndex({
4432
+ efforts: [...wodWikiLang.bundledEfforts],
4433
+ equipment: []
4434
+ });
4435
+ }
4436
+ return cachedDefaultReferenceIndex;
4437
+ }
4438
+ function titleFromMarkdown(path, markdown) {
4439
+ const fm = readFrontmatterMeta(markdown);
4440
+ const fmTitle = typeof fm["title"] === "string" ? fm["title"].trim().replace(/^["']|["']$/g, "") : "";
4441
+ if (fmTitle) return fmTitle;
4442
+ const heading = markdown.match(/^#\s+(.+)$/m)?.[1]?.trim();
4443
+ if (heading) return heading;
4444
+ return (path.split("/").at(-1) ?? path).replace(/\.md$/i, "").replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
4445
+ }
4446
+ function notebookSlugFromFeedPath(path) {
4447
+ const match = /^markdown\/notebooks\/([^/]+)\//.exec(path);
4448
+ return match?.[1] && match[1] !== "_root" ? match[1] : void 0;
4449
+ }
4450
+ async function compileSeedRowFromMarkdown(input) {
4451
+ const path = input.path.replace(/^\/+/, "");
4452
+ if (!path || path.split("/").includes("..")) {
4453
+ throw new Error(`Invalid seed markdown path: '${input.path}'`);
4454
+ }
4455
+ const content = input.markdown;
4456
+ const uuid = input.uuid || await seedNoteId(path);
4457
+ const fm = readFrontmatterMeta(content);
4458
+ const title = input.title?.trim() || titleFromMarkdown(path, content);
4459
+ const rawDate = typeof fm["date"] === "string" ? fm["date"] : void 0;
4460
+ const parsedDate = parseFrontmatterDateMs(rawDate);
4461
+ const createdAt = input.date ?? parsedDate ?? input.createdAt ?? 0;
4462
+ let ordinal = 0;
4463
+ const blocks = wodWikiCore.reconcileNoteBlocks(content, {
4464
+ sourceRevision: 1,
4465
+ registeredWidgets: SEED_REGISTERED_WIDGETS,
4466
+ createId: () => `seed:${path}:${ordinal++}`
4467
+ });
4468
+ const sections = wodWikiCore.parseDocumentSections(content, { registeredWidgets: SEED_REGISTERED_WIDGETS });
4469
+ const blockIndex = Object.values(blocks).map((block, position) => {
4470
+ const section = sections.find((s) => s.from === block.from && s.to === block.to);
4471
+ const fingerprint = block.kind === "wod" ? wodWikiCore.blockContentId(section?.scriptBlock?.content ?? content.slice(block.from, block.to)) : void 0;
4472
+ return {
4473
+ id: `${uuid}:${block.id}`,
4474
+ noteId: uuid,
4475
+ blockId: block.id,
4476
+ blockVersion: 1,
4477
+ sourceRevision: 1,
4478
+ from: block.from,
4479
+ to: block.to,
4480
+ position,
4481
+ dataType: block.kind,
4482
+ ...fingerprint ? { blockContentId: fingerprint } : {},
4483
+ rawContent: content.slice(block.from, block.to),
4484
+ noteTitle: title,
4485
+ createdAt,
4486
+ isStatic: true,
4487
+ ...input.sourceId ? { sourceId: input.sourceId } : {},
4488
+ sourcePath: path,
4489
+ ...input.routeId ? { routeId: input.routeId } : {}
4490
+ };
4491
+ });
4492
+ const referenceIndex = input.referenceIndex ?? defaultLazyReferenceIndex();
4493
+ const blockEfforts = [];
4494
+ const blockEquipment = [];
4495
+ for (const proj of blockIndex) {
4496
+ if (proj.dataType !== "wod" || !proj.rawContent) continue;
4497
+ const sec = wodWikiCore.parseDocumentSections(proj.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find(
4498
+ (s) => s.scriptBlock
4499
+ );
4500
+ const parsed = wodWikiLang.parseScript(sec?.scriptBlock?.content ?? proj.rawContent, { references: referenceIndex });
4501
+ const refs = wodWikiLang.extractStatementRefs(parsed.statements);
4502
+ const seenEfforts = /* @__PURE__ */ new Set();
4503
+ for (const rawSlug of refs.efforts) {
4504
+ const canonical = referenceIndex.resolveEffort(rawSlug)?.slug;
4505
+ if (!canonical || seenEfforts.has(canonical)) continue;
4506
+ seenEfforts.add(canonical);
4507
+ blockEfforts.push({
4508
+ id: `${proj.id}:${canonical}`,
4509
+ noteId: uuid,
4510
+ blockId: proj.blockId,
4511
+ ...proj.blockContentId ? { blockContentId: proj.blockContentId } : {},
4512
+ effortSlug: canonical,
4513
+ isStatic: true,
4514
+ sourcePath: path,
4515
+ createdAt
4516
+ });
4517
+ }
4518
+ const seenEquipment = /* @__PURE__ */ new Set();
4519
+ for (const rawSlug of refs.equipment) {
4520
+ const canonical = referenceIndex.resolveEquipment(rawSlug)?.slug;
4521
+ if (!canonical || seenEquipment.has(canonical)) continue;
4522
+ seenEquipment.add(canonical);
4523
+ blockEquipment.push({
4524
+ id: `${proj.id}:${canonical}`,
4525
+ noteId: uuid,
4526
+ blockId: proj.blockId,
4527
+ ...proj.blockContentId ? { blockContentId: proj.blockContentId } : {},
4528
+ equipmentSlug: canonical,
4529
+ isStatic: true,
4530
+ sourcePath: path,
4531
+ createdAt
4532
+ });
4533
+ }
4534
+ }
4535
+ return assertSeedRow({
4536
+ path,
4537
+ content,
4538
+ blocks,
4539
+ blockIndex,
4540
+ blockEfforts,
4541
+ blockEquipment,
4542
+ uuid,
4543
+ commit: input.commit ?? "",
4544
+ version: input.version ?? 1
4545
+ });
4546
+ }
4547
+ async function readTextFromReaderOrUrl(reader, target, fetchImpl) {
4548
+ if (/^https?:\/\//i.test(target)) {
4549
+ const parsed = new URL(target);
4550
+ if (parsed.username || parsed.password) {
4551
+ throw new FeedTreeError("permission", "Disallowed credentials in feed URL");
4552
+ }
4553
+ const doFetch = fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
4554
+ const res = await doFetch(parsed.toString());
4555
+ if (res.status === 404) {
4556
+ throw new FeedTreeError("not-found", `HTTP 404 for ${parsed.toString()}`);
4557
+ }
4558
+ if (!res.ok) {
4559
+ throw new FeedTreeError("permission", `HTTP ${res.status} fetching ${parsed.toString()}`);
4560
+ }
4561
+ return await res.text();
4562
+ }
4563
+ return decodeUtf8(await reader.read(target));
4564
+ }
4213
4565
  async function previewRemoteNotebook(reader, indexPath) {
4214
4566
  const raw = decodeUtf8(await reader.read(indexPath));
4215
4567
  return assertNotebookIndex(JSON.parse(raw));
4216
4568
  }
4217
- async function previewRemoteRecord(reader, recordPath) {
4218
- const raw = decodeUtf8(await reader.read(recordPath));
4219
- return assertSeedRow(JSON.parse(raw));
4569
+ async function previewRemoteRecord(reader, recordOrPath, options) {
4570
+ if (typeof recordOrPath === "string") {
4571
+ if (/\.md$/i.test(recordOrPath)) {
4572
+ const markdown2 = await readTextFromReaderOrUrl(reader, recordOrPath, options?.fetchImpl);
4573
+ return compileSeedRowFromMarkdown({ path: recordOrPath, markdown: markdown2 });
4574
+ }
4575
+ const raw = await readTextFromReaderOrUrl(reader, recordOrPath, options?.fetchImpl);
4576
+ return assertSeedRow(JSON.parse(raw));
4577
+ }
4578
+ if (recordOrPath.recordPath) {
4579
+ try {
4580
+ const raw = await readTextFromReaderOrUrl(reader, recordOrPath.recordPath, options?.fetchImpl);
4581
+ return assertSeedRow(JSON.parse(raw));
4582
+ } catch (err) {
4583
+ const hasMarkdownFallback = Boolean(recordOrPath.rawUrl || /\.md$/i.test(recordOrPath.path));
4584
+ const isNotFound = err instanceof FeedTreeError && err.code === "not-found";
4585
+ if (!isNotFound || !hasMarkdownFallback) throw err;
4586
+ }
4587
+ }
4588
+ const rawTarget = recordOrPath.rawUrl ?? recordOrPath.path;
4589
+ const markdown = await readTextFromReaderOrUrl(reader, rawTarget, options?.fetchImpl);
4590
+ return compileSeedRowFromMarkdown({
4591
+ path: recordOrPath.path,
4592
+ markdown,
4593
+ uuid: recordOrPath.uuid,
4594
+ commit: recordOrPath.commit,
4595
+ version: recordOrPath.version,
4596
+ title: recordOrPath.title,
4597
+ date: recordOrPath.date
4598
+ });
4220
4599
  }
4221
4600
  async function cloneRemoteRecord(storage, reader, input) {
4222
4601
  const targetNotebookId = wodWikiCore.toNotebookId(input.targetNotebookId);
4223
- const seedRow = await previewRemoteRecord(reader, input.record.recordPath);
4602
+ if (wodWikiCore.isSystemReadOnlyNotebook(targetNotebookId)) {
4603
+ throw new Error(`Target notebook '${targetNotebookId}' is read-only`);
4604
+ }
4605
+ const seedRow = await previewRemoteRecord(reader, input.record);
4224
4606
  const newNoteId = mintUuidV4();
4225
4607
  const now = Date.now();
4226
4608
  const sourceRevision = 1;
@@ -4263,6 +4645,20 @@ async function cloneRemoteRecord(storage, reader, input) {
4263
4645
  noteId: newNoteId,
4264
4646
  isStatic: false
4265
4647
  }));
4648
+ const inferredNbSlug = notebookSlugFromFeedPath(seedRow.path);
4649
+ const sourceNotebookId = input.sourceNotebookId ? wodWikiCore.toNotebookId(input.sourceNotebookId) : inferredNbSlug ? wodWikiCore.toNotebookId(inferredNbSlug) : void 0;
4650
+ const sourceNoteId = input.record.uuid || seedRow.uuid || await seedNoteId(seedRow.path);
4651
+ const sourceVersion = input.record.version ?? seedRow.version;
4652
+ const sourceCommit = input.record.commit || seedRow.commit || void 0;
4653
+ const provenance = {
4654
+ sourceNoteId,
4655
+ ...sourceVersion !== void 0 ? { sourceVersion } : {},
4656
+ ...sourceCommit ? { sourceCommit } : {},
4657
+ feedSourceId: input.feedId,
4658
+ ...sourceNotebookId ? { sourceNotebookId } : {},
4659
+ sourcePath: seedRow.path,
4660
+ clonedAt: now
4661
+ };
4266
4662
  const clonedNote = {
4267
4663
  id: newNoteId,
4268
4664
  title: input.record.title || seedRow.blockIndex[0]?.noteTitle || "Cloned Note",
@@ -4272,6 +4668,8 @@ async function cloneRemoteRecord(storage, reader, input) {
4272
4668
  ...input.record.date !== void 0 ? { date: input.record.date } : {},
4273
4669
  createdAt: now,
4274
4670
  notebookId: targetNotebookId,
4671
+ notebookIds: [targetNotebookId],
4672
+ provenance,
4275
4673
  sourceId: `feed:${input.feedId}/${seedRow.path}`,
4276
4674
  sourcePath: seedRow.path,
4277
4675
  seedOrigin: "user"
@@ -4301,8 +4699,16 @@ async function cloneRemoteRecord(storage, reader, input) {
4301
4699
  });
4302
4700
  }
4303
4701
  }
4702
+ const notebookLink = {
4703
+ id: makeNotebookLinkId(targetNotebookId, "note", newNoteId),
4704
+ notebookId: targetNotebookId,
4705
+ targetKind: "note",
4706
+ targetId: newNoteId,
4707
+ noteId: newNoteId,
4708
+ createdAt: now
4709
+ };
4304
4710
  await storage.transaction(
4305
- ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "sessions", "events"],
4711
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "sessions", "events", "notebook_links"],
4306
4712
  "readwrite",
4307
4713
  async (tx) => {
4308
4714
  const landing = await tx.readonly("notes").get(targetNotebookId);
@@ -4310,6 +4716,7 @@ async function cloneRemoteRecord(storage, reader, input) {
4310
4716
  throw new Error(`Target notebook '${targetNotebookId}' is read-only`);
4311
4717
  }
4312
4718
  await tx.readwrite("notes").put(clonedNote);
4719
+ await tx.readwrite("notebook_links").put(notebookLink);
4313
4720
  if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
4314
4721
  if (blockIndex.length > 0) await tx.readwrite("block_index").putMany(blockIndex);
4315
4722
  if (blockEfforts.length > 0) await tx.readwrite("block_efforts").putMany(blockEfforts);
@@ -4320,6 +4727,129 @@ async function cloneRemoteRecord(storage, reader, input) {
4320
4727
  );
4321
4728
  return clonedNote;
4322
4729
  }
4730
+ async function clearRowsByNoteIndex(store, noteId, keyOf) {
4731
+ let rows;
4732
+ try {
4733
+ rows = await store.getAllFromIndex("by-note", noteId);
4734
+ } catch {
4735
+ rows = await store.getAll();
4736
+ }
4737
+ for (const row of rows) {
4738
+ const rec = row;
4739
+ if (!rec || rec["noteId"] !== noteId) continue;
4740
+ const key = keyOf(row);
4741
+ if (key !== void 0) await store.delete(key);
4742
+ }
4743
+ }
4744
+ async function materializeCachedRemoteRecord(storage, input) {
4745
+ const canonicalId = input.record?.uuid || input.seedRow.uuid || await seedNoteId(input.seedRow.path);
4746
+ const inferredNbSlug = input.notebookSlug ?? notebookSlugFromFeedPath(input.seedRow.path);
4747
+ const notebookId = input.notebookId ? wodWikiCore.toNotebookId(input.notebookId) : inferredNbSlug ? wodWikiCore.toNotebookId(inferredNbSlug) : void 0;
4748
+ const seedChunkId = inferredNbSlug ? `notebook.${inferredNbSlug}` : notebookId ? `notebook.${notebookId.replace(/^notebook\//, "")}` : void 0;
4749
+ const version = input.record?.version ?? input.seedRow.version ?? 1;
4750
+ const title = input.record?.title || input.seedRow.blockIndex[0]?.noteTitle || titleFromMarkdown(input.seedRow.path, input.seedRow.content);
4751
+ const commit = input.record?.commit || input.seedRow.commit || void 0;
4752
+ const now = Date.now();
4753
+ return storage.transaction(
4754
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment"],
4755
+ "readwrite",
4756
+ async (tx) => {
4757
+ const notesStore = tx.readwrite("notes");
4758
+ const existing = await notesStore.get(canonicalId);
4759
+ if (existing) {
4760
+ const isUserOwned = existing.seedOrigin !== "seed" && existing.feedOrigin !== "feed" && !existing.retention;
4761
+ if (isUserOwned || existing.retention === "session-pinned" || existing.retention === "schedule-pinned") {
4762
+ return existing;
4763
+ }
4764
+ if (existing.rawContent === input.seedRow.content && Object.keys(existing.blocks).length > 0 && existing.retention === "cached") {
4765
+ if (existing.upstreamStatus !== (input.upstreamStatus ?? "live") || input.feedId && existing.feedSourceId !== input.feedId) {
4766
+ const refreshed = {
4767
+ ...existing,
4768
+ ...input.feedId ? { feedOrigin: "feed", feedSourceId: input.feedId } : {},
4769
+ upstreamStatus: input.upstreamStatus ?? "live"
4770
+ };
4771
+ await notesStore.put(refreshed);
4772
+ return refreshed;
4773
+ }
4774
+ return existing;
4775
+ }
4776
+ }
4777
+ const sourceRevision = existing ? existing.sourceRevision + 1 : 1;
4778
+ const blocks = {};
4779
+ const revisions = [];
4780
+ const revStore = tx.readwrite("block_revisions");
4781
+ const blockVer = existing ? sourceRevision : 1;
4782
+ for (const [key, block] of Object.entries(input.seedRow.blocks)) {
4783
+ blocks[key] = { ...block, version: blockVer, sourceRevision };
4784
+ revisions.push({
4785
+ noteId: canonicalId,
4786
+ blockId: block.id,
4787
+ version: blockVer,
4788
+ kind: block.kind,
4789
+ rawContent: input.seedRow.content.slice(block.from, block.to),
4790
+ savedAt: now,
4791
+ ...block.dialect ? { dialect: block.dialect } : {},
4792
+ ...block.sport ? { sport: block.sport } : {}
4793
+ });
4794
+ }
4795
+ const cachedSourceId = input.feedId ? `feed:${input.feedId}/${input.seedRow.path}` : input.seedRow.path;
4796
+ const blockIndexStore = tx.readwrite("block_index");
4797
+ const blockEffortsStore = tx.readwrite("block_efforts");
4798
+ const blockEquipmentStore = tx.readwrite("block_equipment");
4799
+ await clearRowsByNoteIndex(blockIndexStore, canonicalId, (r) => r.id);
4800
+ await clearRowsByNoteIndex(blockEffortsStore, canonicalId, (r) => r.id);
4801
+ await clearRowsByNoteIndex(blockEquipmentStore, canonicalId, (r) => r.id);
4802
+ const blockIndex = input.seedRow.blockIndex.map((proj) => ({
4803
+ ...proj,
4804
+ id: `${canonicalId}:${proj.blockId}`,
4805
+ noteId: canonicalId,
4806
+ blockVersion: blockVer,
4807
+ sourceRevision,
4808
+ isStatic: true,
4809
+ sourceId: cachedSourceId,
4810
+ sourcePath: input.seedRow.path,
4811
+ ...notebookId ? { notebookId } : {}
4812
+ }));
4813
+ const blockEfforts = input.seedRow.blockEfforts.map((eff) => ({
4814
+ ...eff,
4815
+ id: `${canonicalId}:${eff.blockId}:${eff.effortSlug}`,
4816
+ noteId: canonicalId,
4817
+ isStatic: true
4818
+ }));
4819
+ const blockEquipment = input.seedRow.blockEquipment.map((eq) => ({
4820
+ ...eq,
4821
+ id: `${canonicalId}:${eq.blockId}:${eq.equipmentSlug}`,
4822
+ noteId: canonicalId,
4823
+ isStatic: true
4824
+ }));
4825
+ const cachedNote = {
4826
+ id: canonicalId,
4827
+ title,
4828
+ rawContent: input.seedRow.content,
4829
+ sourceRevision,
4830
+ blocks,
4831
+ ...input.record?.date !== void 0 ? { date: input.record.date } : existing?.date !== void 0 ? { date: existing.date } : {},
4832
+ createdAt: existing?.createdAt ?? input.record?.date ?? now,
4833
+ ...notebookId ? { notebookId, notebookIds: [notebookId] } : existing?.notebookId ? { notebookId: existing.notebookId } : {},
4834
+ ...input.feedId ? { feedOrigin: "feed", feedSourceId: input.feedId } : existing?.feedOrigin ? { feedOrigin: existing.feedOrigin, feedSourceId: existing.feedSourceId } : {},
4835
+ seedOrigin: "seed",
4836
+ ...seedChunkId ? { seedChunkId } : existing?.seedChunkId ? { seedChunkId: existing.seedChunkId } : {},
4837
+ seedVersion: version,
4838
+ ...commit ? { seedCommit: commit } : {},
4839
+ sourceId: cachedSourceId,
4840
+ sourcePath: input.seedRow.path,
4841
+ retention: input.retention ?? "cached",
4842
+ upstreamStatus: input.upstreamStatus ?? "live"
4843
+ };
4844
+ await notesStore.put(cachedNote);
4845
+ if (revisions.length > 0) await revStore.putMany(revisions);
4846
+ if (blockIndex.length > 0) await blockIndexStore.putMany(blockIndex);
4847
+ if (blockEfforts.length > 0) await blockEffortsStore.putMany(blockEfforts);
4848
+ if (blockEquipment.length > 0) await blockEquipmentStore.putMany(blockEquipment);
4849
+ return cachedNote;
4850
+ }
4851
+ );
4852
+ }
4323
4853
  var portableTextDecoder = new TextDecoder();
4324
4854
  function decodePortableFileContent(entry) {
4325
4855
  if (typeof entry.content === "string") return entry.content;
@@ -4596,6 +5126,37 @@ async function ingestPortableFilesIntoStorage(storage, files, options = {}) {
4596
5126
  };
4597
5127
  }
4598
5128
  var FEED_SUBSCRIPTIONS_META_KEY = "feed:subscriptions";
5129
+ var FEED_REGISTRY_META_KEY = "feed:registry";
5130
+ async function noteHasSessions(tx, noteId) {
5131
+ const sessionStore = tx.readonly("sessions");
5132
+ try {
5133
+ if (typeof sessionStore.countFromIndex === "function") {
5134
+ return await sessionStore.countFromIndex("by-note", noteId) > 0;
5135
+ }
5136
+ const rows = await sessionStore.getAllFromIndex("by-note", noteId);
5137
+ return rows.length > 0;
5138
+ } catch {
5139
+ const all = await sessionStore.getAll();
5140
+ return all.some((s) => s.noteId === noteId);
5141
+ }
5142
+ }
5143
+ async function noteHasScheduleItems(tx, noteId) {
5144
+ try {
5145
+ const schedStore = tx.readonly("schedule_items");
5146
+ if (typeof schedStore.countFromIndex === "function") {
5147
+ return await schedStore.countFromIndex("by-note", noteId) > 0;
5148
+ }
5149
+ const rows = await schedStore.getAllFromIndex("by-note", noteId);
5150
+ return rows.length > 0;
5151
+ } catch {
5152
+ try {
5153
+ const all = await tx.readonly("schedule_items").getAll();
5154
+ return all.some((s) => s.noteId === noteId);
5155
+ } catch {
5156
+ return false;
5157
+ }
5158
+ }
5159
+ }
4599
5160
  async function removeSeedSourceContent(storage, meta) {
4600
5161
  return storage.transaction(
4601
5162
  [
@@ -4607,13 +5168,18 @@ async function removeSeedSourceContent(storage, meta) {
4607
5168
  "block_efforts",
4608
5169
  "block_equipment",
4609
5170
  "page_notes",
5171
+ "schedule_items",
4610
5172
  "efforts",
4611
5173
  "equipment",
4612
5174
  "property_overrides",
5175
+ "sessions",
4613
5176
  "meta"
4614
5177
  ],
4615
5178
  "readwrite",
4616
5179
  async (tx) => {
5180
+ const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
5181
+ const chunkKeys = Object.keys(meta.chunks);
5182
+ const isWholeFeedSweep = chunkKeys.length === 0 || Object.values(meta.chunks).length > 0;
4617
5183
  const targetIds = /* @__PURE__ */ new Set();
4618
5184
  const legacyChunks = [];
4619
5185
  for (const [chunkId, chunk] of Object.entries(meta.chunks)) {
@@ -4623,16 +5189,31 @@ async function removeSeedSourceContent(storage, meta) {
4623
5189
  legacyChunks.push(chunkId);
4624
5190
  }
4625
5191
  }
5192
+ const allNotes = legacyChunks.length || isWholeFeedSweep ? await tx.readwrite("notes").getAll() : [];
4626
5193
  if (legacyChunks.length) {
4627
- for (const note of await tx.readwrite("notes").getAll()) {
5194
+ for (const note of allNotes) {
4628
5195
  if (note.seedOrigin === "seed" && note.seedChunkId && legacyChunks.includes(note.seedChunkId)) {
4629
5196
  targetIds.add(note.id);
4630
5197
  }
4631
5198
  }
4632
5199
  }
5200
+ if (isWholeFeedSweep) {
5201
+ for (const note of allNotes) {
5202
+ const rNote = note;
5203
+ if (note.seedOrigin === "seed" && note.feedSourceId === removedSourceId && (chunkKeys.length === 0 || rNote.retention === "cached" || rNote.retention === "schedule-pinned" || rNote.retention === "session-pinned")) {
5204
+ targetIds.add(note.id);
5205
+ }
5206
+ }
5207
+ }
4633
5208
  const metaStore = tx.readwrite("meta");
4634
5209
  const otherCheckpoints = [];
5210
+ const indexKeysToDelete = [];
5211
+ const indexPrefix = `${FEED_INDEX_META_PREFIX}${removedSourceId}:`;
4635
5212
  for (const row of await metaStore.getAll()) {
5213
+ const key = row?.key;
5214
+ if (typeof key === "string" && key.startsWith(indexPrefix)) {
5215
+ indexKeysToDelete.push(key);
5216
+ }
4636
5217
  const other = row;
4637
5218
  if (!other || typeof other.key !== "string" || !other.key.startsWith("seed:") || other.key === meta.key) {
4638
5219
  continue;
@@ -4651,50 +5232,28 @@ async function removeSeedSourceContent(storage, meta) {
4651
5232
  }
4652
5233
  otherCheckpoints.sort((a, b) => b.rank - a.rank);
4653
5234
  const isClaimedByOther = (noteId) => otherCheckpoints.some((cp) => cp.noteIds.has(noteId));
4654
- const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
4655
5235
  const notes = tx.readwrite("notes");
4656
- const noteTags = tx.readwrite("note_tags");
4657
5236
  let deleted = 0;
5237
+ let preservedPinned = 0;
4658
5238
  const removedPaths = /* @__PURE__ */ new Set();
4659
5239
  const touchedTagIds = /* @__PURE__ */ new Set();
4660
5240
  for (const id of targetIds) {
4661
5241
  if (isClaimedByOther(id)) continue;
4662
5242
  const note = await notes.get(id);
4663
5243
  if (!note || note.seedOrigin !== "seed") continue;
4664
- if (note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
4665
- if (note.sourcePath) removedPaths.add(note.sourcePath);
4666
- await notes.delete(id);
4667
- const attachments = tx.readwrite("attachments");
4668
- for (const attachment of await attachments.getAllFromIndex("by-note", id)) {
4669
- await attachments.delete(attachment.id);
4670
- }
4671
- for (const link of await noteTags.getAllFromIndex("by-note", id)) {
4672
- touchedTagIds.add(link.tagId);
4673
- await noteTags.delete(link.id);
4674
- }
4675
- const blockIndex = tx.readwrite("block_index");
4676
- for (const row of await blockIndex.getAllFromIndex("by-note", id)) await blockIndex.delete(row.id);
4677
- const blockEfforts = tx.readwrite("block_efforts");
4678
- for (const row of await blockEfforts.getAllFromIndex("by-note", id)) await blockEfforts.delete(row.id);
4679
- const blockEquipment = tx.readwrite("block_equipment");
4680
- for (const row of await blockEquipment.getAllFromIndex("by-note", id)) await blockEquipment.delete(row.id);
4681
- const pageNotes = tx.readwrite("page_notes");
4682
- for (const link of await pageNotes.getAllFromIndex("by-note", id)) await pageNotes.delete(link.id);
4683
- deleted++;
4684
- }
4685
- if (touchedTagIds.size > 0) {
4686
- const tagsStore = tx.readwrite("tags");
4687
- for (const tagId of touchedTagIds) {
4688
- const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
4689
- if (remainingLinks > 0) continue;
4690
- const tag = await tagsStore.get(tagId);
4691
- if (!tag) continue;
4692
- if (tag.contributions && tag.contributions.length > 0) continue;
4693
- const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
4694
- if (refNote) continue;
4695
- await tagsStore.delete(tagId);
4696
- }
5244
+ const ownedByFeedStamp = note.feedSourceId === removedSourceId && (chunkKeys.length === 0 || note.retention === "cached" || note.retention === "schedule-pinned" || note.retention === "session-pinned");
5245
+ if (!ownedByFeedStamp && note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
5246
+ const outcome = await deleteOrPreserveFeedNote(
5247
+ tx,
5248
+ note,
5249
+ "unsubscribed",
5250
+ touchedTagIds,
5251
+ removedPaths
5252
+ );
5253
+ if (outcome === "pinned") preservedPinned++;
5254
+ else deleted++;
4697
5255
  }
5256
+ await pruneOrphanTags(tx, touchedTagIds);
4698
5257
  const defFamilies = [
4699
5258
  { storeName: "efforts", familyPathPrefix: "markdown/efforts/", parse: wodWikiLang.parseEffortFile },
4700
5259
  { storeName: "equipment", familyPathPrefix: "markdown/equipment/", parse: wodWikiLang.parseEquipmentFile }
@@ -4739,11 +5298,140 @@ async function removeSeedSourceContent(storage, meta) {
4739
5298
  }
4740
5299
  } catch {
4741
5300
  }
5301
+ for (const idxKey of indexKeysToDelete) {
5302
+ await metaStore.delete(idxKey);
5303
+ }
4742
5304
  await metaStore.delete(meta.key);
4743
- return deleted;
5305
+ return { deleted, preservedPinned };
5306
+ }
5307
+ );
5308
+ }
5309
+ async function pruneOrphanTags(tx, touchedTagIds) {
5310
+ if (touchedTagIds.size === 0) return;
5311
+ const notes = tx.readwrite("notes");
5312
+ const noteTags = tx.readwrite("note_tags");
5313
+ const tagsStore = tx.readwrite("tags");
5314
+ for (const tagId of touchedTagIds) {
5315
+ const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
5316
+ if (remainingLinks > 0) continue;
5317
+ const tag = await tagsStore.get(tagId);
5318
+ if (!tag) continue;
5319
+ if (tag.contributions && tag.contributions.length > 0) continue;
5320
+ const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
5321
+ if (refNote) continue;
5322
+ await tagsStore.delete(tagId);
5323
+ }
5324
+ }
5325
+ async function deleteOrPreserveFeedNote(tx, note, upstreamStatus, touchedTagIds, removedPaths) {
5326
+ const notes = tx.readwrite("notes");
5327
+ const hasSessions = await noteHasSessions(tx, note.id);
5328
+ const isSessionPinned = note.retention === "session-pinned" || hasSessions;
5329
+ const hasSchedules = !isSessionPinned && await noteHasScheduleItems(tx, note.id);
5330
+ const isSchedulePinned = note.retention === "schedule-pinned" || hasSchedules;
5331
+ if (isSessionPinned || isSchedulePinned) {
5332
+ await notes.put({
5333
+ ...note,
5334
+ retention: isSessionPinned ? "session-pinned" : "schedule-pinned",
5335
+ upstreamStatus
5336
+ });
5337
+ return "pinned";
5338
+ }
5339
+ if (note.sourcePath && removedPaths) removedPaths.add(note.sourcePath);
5340
+ await notes.delete(note.id);
5341
+ const attachments = tx.readwrite("attachments");
5342
+ for (const attachment of await attachments.getAllFromIndex("by-note", note.id)) {
5343
+ await attachments.delete(attachment.id);
5344
+ }
5345
+ const noteTags = tx.readwrite("note_tags");
5346
+ for (const link of await noteTags.getAllFromIndex("by-note", note.id)) {
5347
+ touchedTagIds.add(link.tagId);
5348
+ await noteTags.delete(link.id);
5349
+ }
5350
+ const blockIndex = tx.readwrite("block_index");
5351
+ for (const row of await blockIndex.getAllFromIndex("by-note", note.id)) await blockIndex.delete(row.id);
5352
+ const blockEfforts = tx.readwrite("block_efforts");
5353
+ for (const row of await blockEfforts.getAllFromIndex("by-note", note.id)) await blockEfforts.delete(row.id);
5354
+ const blockEquipment = tx.readwrite("block_equipment");
5355
+ for (const row of await blockEquipment.getAllFromIndex("by-note", note.id)) await blockEquipment.delete(row.id);
5356
+ const pageNotes = tx.readwrite("page_notes");
5357
+ for (const link of await pageNotes.getAllFromIndex("by-note", note.id)) await pageNotes.delete(link.id);
5358
+ return "deleted";
5359
+ }
5360
+ async function removeFeedSourceContentById(storage, sourceId) {
5361
+ const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
5362
+ return removeSeedSourceContent(storage, meta ?? emptySeedMeta(seedMetaKey(sourceId)));
5363
+ }
5364
+ async function removeFeedNotebookContent(storage, feedId, chunkId) {
5365
+ return storage.transaction(
5366
+ ["notes", "attachments", "tags", "note_tags", "block_index", "block_efforts", "block_equipment", "page_notes", "schedule_items", "sessions", "meta"],
5367
+ "readwrite",
5368
+ async (tx) => {
5369
+ const notes = tx.readwrite("notes");
5370
+ const allNotes = await notes.getAll();
5371
+ let deleted = 0;
5372
+ let preservedPinned = 0;
5373
+ const touchedTagIds = /* @__PURE__ */ new Set();
5374
+ for (const rawNote of allNotes) {
5375
+ const note = rawNote;
5376
+ if (note.seedOrigin !== "seed") continue;
5377
+ if (note.feedSourceId !== feedId || note.seedChunkId !== chunkId) continue;
5378
+ const outcome = await deleteOrPreserveFeedNote(tx, note, "unsubscribed", touchedTagIds);
5379
+ if (outcome === "pinned") preservedPinned++;
5380
+ else deleted++;
5381
+ }
5382
+ await pruneOrphanTags(tx, touchedTagIds);
5383
+ await tx.readwrite("meta").delete(`${FEED_INDEX_META_PREFIX}${feedId}:${chunkId}`);
5384
+ return { deleted, preservedPinned };
5385
+ }
5386
+ );
5387
+ }
5388
+ async function reconcileRemovedFeedRecords(storage, feedId, notebookId, liveUuids) {
5389
+ return storage.transaction(
5390
+ ["notes", "attachments", "tags", "note_tags", "block_index", "block_efforts", "block_equipment", "page_notes", "schedule_items", "sessions"],
5391
+ "readwrite",
5392
+ async (tx) => {
5393
+ const notes = tx.readwrite("notes");
5394
+ const allNotes = await notes.getAll();
5395
+ let deleted = 0;
5396
+ let preservedPinned = 0;
5397
+ const touchedTagIds = /* @__PURE__ */ new Set();
5398
+ for (const rawNote of allNotes) {
5399
+ const note = rawNote;
5400
+ if (note.seedOrigin !== "seed") continue;
5401
+ if (note.feedSourceId !== feedId || note.seedChunkId !== notebookId) continue;
5402
+ if (liveUuids.has(note.id)) continue;
5403
+ const outcome = await deleteOrPreserveFeedNote(tx, note, "removed", touchedTagIds);
5404
+ if (outcome === "pinned") preservedPinned++;
5405
+ else deleted++;
5406
+ }
5407
+ await pruneOrphanTags(tx, touchedTagIds);
5408
+ return { deleted, preservedPinned };
4744
5409
  }
4745
5410
  );
4746
5411
  }
5412
+ async function readFeedRegistryHeadless(storage) {
5413
+ const row = await storage.readonly("meta").get(FEED_REGISTRY_META_KEY);
5414
+ return {
5415
+ key: FEED_REGISTRY_META_KEY,
5416
+ customFeeds: Array.isArray(row?.customFeeds) ? [...row.customFeeds] : [],
5417
+ hiddenFeedIds: Array.isArray(row?.hiddenFeedIds) ? [...row.hiddenFeedIds] : [],
5418
+ updatedAt: typeof row?.updatedAt === "number" ? row.updatedAt : 0,
5419
+ ...row?.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
5420
+ };
5421
+ }
5422
+ async function writeFeedRegistryHeadless(storage, next) {
5423
+ const record = {
5424
+ key: FEED_REGISTRY_META_KEY,
5425
+ customFeeds: next.customFeeds,
5426
+ hiddenFeedIds: next.hiddenFeedIds,
5427
+ updatedAt: next.updatedAt,
5428
+ ...next.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
5429
+ };
5430
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
5431
+ await tx.readwrite("meta").put(record);
5432
+ });
5433
+ return record;
5434
+ }
4747
5435
  async function readFeedSubscriptionsMap(storage) {
4748
5436
  const row = await storage.readonly("meta").get(FEED_SUBSCRIPTIONS_META_KEY);
4749
5437
  return { ...row?.entries ?? {} };
@@ -4753,7 +5441,11 @@ async function writeFeedSubscriptionEntry(storage, sourceId, entry) {
4753
5441
  const metaStore = tx.readwrite("meta");
4754
5442
  const existing = await metaStore.get(FEED_SUBSCRIPTIONS_META_KEY);
4755
5443
  const entries = { ...existing?.entries ?? {}, [sourceId]: entry };
4756
- await metaStore.put({ key: FEED_SUBSCRIPTIONS_META_KEY, entries });
5444
+ await metaStore.put({
5445
+ key: FEED_SUBSCRIPTIONS_META_KEY,
5446
+ entries,
5447
+ ...existing?.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
5448
+ });
4757
5449
  });
4758
5450
  }
4759
5451
  async function listFeedSubscriptionsHeadless(storage) {
@@ -4761,48 +5453,163 @@ async function listFeedSubscriptionsHeadless(storage) {
4761
5453
  }
4762
5454
  async function subscribeFeedSourceHeadless(storage, sourceId, options) {
4763
5455
  const notebookIds = options?.notebookIds && options.notebookIds.length > 0 ? options.notebookIds : null;
5456
+ const existingMap = await readFeedSubscriptionsMap(storage);
5457
+ const prev = existingMap[sourceId];
5458
+ const offlinePolicy = sourceId === "core" ? "offline-full" : options?.offlinePolicy ?? prev?.offlinePolicy ?? "index-only";
4764
5459
  await writeFeedSubscriptionEntry(storage, sourceId, {
5460
+ ...prev,
4765
5461
  subscribed: true,
4766
5462
  notebookIds,
5463
+ offlinePolicy,
5464
+ ...options?.autoSync !== void 0 ? { autoSync: options.autoSync } : {},
4767
5465
  hidden: false,
4768
5466
  ...options?.url ? { url: options.url } : {},
4769
5467
  ...options?.name ? { name: options.name } : {},
4770
5468
  updatedAt: Date.now()
4771
5469
  });
4772
- return { sourceId, subscribed: true, notebookIds };
5470
+ return { sourceId, subscribed: true, notebookIds, offlinePolicy };
4773
5471
  }
4774
5472
  async function unsubscribeFeedSourceHeadless(storage, sourceId) {
4775
5473
  if (sourceId === "core") {
4776
5474
  throw new Error("Core feed cannot be unsubscribed.");
4777
5475
  }
4778
- const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
4779
- const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
5476
+ const { deleted, preservedPinned } = await removeFeedSourceContentById(storage, sourceId);
5477
+ const existingMap = await readFeedSubscriptionsMap(storage);
5478
+ const prev = existingMap[sourceId];
4780
5479
  await writeFeedSubscriptionEntry(storage, sourceId, {
5480
+ ...prev,
4781
5481
  subscribed: false,
5482
+ autoSync: false,
4782
5483
  hidden: false,
4783
5484
  updatedAt: Date.now()
4784
5485
  });
4785
- return { sourceId, unsubscribed: true, deletedNotes };
5486
+ return { sourceId, unsubscribed: true, deletedNotes: deleted, deleted, preservedPinned };
4786
5487
  }
4787
5488
  async function deleteFeedSourceHeadless(storage, sourceId) {
4788
5489
  if (sourceId === "core") {
4789
5490
  throw new Error("Core feed cannot be deleted.");
4790
5491
  }
4791
- const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
4792
- const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
5492
+ const { deleted, preservedPinned } = await removeFeedSourceContentById(storage, sourceId);
5493
+ const existingMap = await readFeedSubscriptionsMap(storage);
5494
+ const prev = existingMap[sourceId];
4793
5495
  await writeFeedSubscriptionEntry(storage, sourceId, {
5496
+ ...prev,
4794
5497
  subscribed: false,
5498
+ autoSync: false,
4795
5499
  hidden: true,
4796
5500
  updatedAt: Date.now()
4797
5501
  });
4798
- return { sourceId, deleted: true, deletedNotes };
5502
+ const registry = await readFeedRegistryHeadless(storage);
5503
+ const isCustom = registry.customFeeds.some((f) => f.id === sourceId);
5504
+ await writeFeedRegistryHeadless(storage, {
5505
+ customFeeds: isCustom ? registry.customFeeds.filter((f) => f.id !== sourceId) : registry.customFeeds,
5506
+ hiddenFeedIds: isCustom || registry.hiddenFeedIds.includes(sourceId) ? registry.hiddenFeedIds : [...registry.hiddenFeedIds, sourceId],
5507
+ updatedAt: Date.now(),
5508
+ migratedFromLocalStorage: registry.migratedFromLocalStorage
5509
+ });
5510
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
5511
+ await tx.readwrite("meta").delete(`catalog:${sourceId}`);
5512
+ });
5513
+ return { sourceId, deleted: true, deletedNotes: deleted, preservedPinned };
4799
5514
  }
4800
- function mintUuid() {
4801
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
4802
- return crypto.randomUUID();
5515
+ var RESERVED_SLUGS = new Set(wodWikiCore.BUILTIN_NOTEBOOKS.map((b) => b.slug));
5516
+ async function deleteUserNotebook(storage, notebookIdOrSlug) {
5517
+ const nbId = wodWikiCore.toNotebookId(notebookIdOrSlug);
5518
+ const slug = wodWikiCore.notebookSlugFromId(nbId);
5519
+ if (RESERVED_SLUGS.has(slug)) {
5520
+ throw new Error(`Notebook '${nbId}' is always present and cannot be deleted.`);
4803
5521
  }
4804
- const bytes = new Uint8Array(16);
4805
- crypto.getRandomValues(bytes);
5522
+ return storage.transaction(
5523
+ [
5524
+ "notes",
5525
+ "notebook_links",
5526
+ "attachments",
5527
+ "note_tags",
5528
+ "block_index",
5529
+ "block_efforts",
5530
+ "block_equipment",
5531
+ "page_notes",
5532
+ "meta"
5533
+ ],
5534
+ "readwrite",
5535
+ async (tx) => {
5536
+ const allNotes = await tx.readonly("notes").getAll();
5537
+ const links = await tx.readonly("notebook_links").getAllFromIndex("by-notebook", nbId).catch(() => []);
5538
+ const linkedNoteIds = new Set(
5539
+ links.filter((l) => l.targetKind === "note").map((l) => l.noteId)
5540
+ );
5541
+ let touchedMembers = 0;
5542
+ const noteWriter = tx.readwrite("notes");
5543
+ for (const note of allNotes) {
5544
+ if (wodWikiCore.isNotebookLanding(note)) continue;
5545
+ const hasSingle = note.notebookId === nbId;
5546
+ const hasMulti = (note.notebookIds ?? []).includes(nbId);
5547
+ const hasLink = linkedNoteIds.has(note.id);
5548
+ if (!hasSingle && !hasMulti && !hasLink) continue;
5549
+ const baseIds = note.notebookIds !== void 0 ? note.notebookIds : note.notebookId ? [note.notebookId] : [];
5550
+ const remaining = baseIds.map((id) => wodWikiCore.toNotebookId(id)).filter((id) => id !== nbId);
5551
+ const primaryUser = remaining.find(
5552
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
5553
+ );
5554
+ const { notebookId: _droppedSingle, notebookIds: _droppedMulti, ...rest } = note;
5555
+ await noteWriter.put({
5556
+ ...rest,
5557
+ notebookIds: remaining,
5558
+ ...primaryUser ? { notebookId: primaryUser } : {}
5559
+ });
5560
+ touchedMembers++;
5561
+ }
5562
+ if (links.length > 0) {
5563
+ const linkWriter = tx.readwrite("notebook_links");
5564
+ for (const link of links) {
5565
+ await linkWriter.delete(link.id);
5566
+ }
5567
+ }
5568
+ const landing = allNotes.find((n) => n.id === nbId);
5569
+ if (landing) {
5570
+ await noteWriter.delete(nbId);
5571
+ try {
5572
+ for (const att of await tx.readonly("attachments").getAllFromIndex("by-note", nbId)) {
5573
+ await tx.readwrite("attachments").delete(att.id);
5574
+ }
5575
+ for (const link of await tx.readonly("note_tags").getAllFromIndex("by-note", nbId)) {
5576
+ await tx.readwrite("note_tags").delete(link.id);
5577
+ }
5578
+ for (const row of await tx.readonly("block_index").getAllFromIndex("by-note", nbId)) {
5579
+ await tx.readwrite("block_index").delete(row.id);
5580
+ }
5581
+ for (const row of await tx.readonly("block_efforts").getAllFromIndex("by-note", nbId)) {
5582
+ await tx.readwrite("block_efforts").delete(row.id);
5583
+ }
5584
+ for (const row of await tx.readonly("block_equipment").getAllFromIndex("by-note", nbId)) {
5585
+ await tx.readwrite("block_equipment").delete(row.id);
5586
+ }
5587
+ for (const pn of await tx.readonly("page_notes").getAllFromIndex("by-note", nbId)) {
5588
+ await tx.readwrite("page_notes").delete(pn.id);
5589
+ }
5590
+ for (const nl of await tx.readonly("notebook_links").getAllFromIndex("by-note", nbId)) {
5591
+ await tx.readwrite("notebook_links").delete(nl.id);
5592
+ }
5593
+ } catch {
5594
+ }
5595
+ if (landing.seedOrigin === "seed" || landing.seedChunkId !== void 0 || landing.sourcePath !== void 0) {
5596
+ await tx.readwrite("meta").put({ key: wodWikiStorage.userDeletedSeedKey(nbId), value: Date.now() });
5597
+ }
5598
+ }
5599
+ return {
5600
+ deleted: Boolean(landing || touchedMembers > 0 || links.length > 0),
5601
+ notebookId: nbId,
5602
+ slug
5603
+ };
5604
+ }
5605
+ );
5606
+ }
5607
+ function mintUuid() {
5608
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
5609
+ return crypto.randomUUID();
5610
+ }
5611
+ const bytes = new Uint8Array(16);
5612
+ crypto.getRandomValues(bytes);
4806
5613
  bytes[6] = bytes[6] & 15 | 64;
4807
5614
  bytes[8] = bytes[8] & 63 | 128;
4808
5615
  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
@@ -4815,6 +5622,16 @@ function utcCivilDateKey(epochMs) {
4815
5622
  const day = String(d.getDate()).padStart(2, "0");
4816
5623
  return `${y}-${m}-${day}`;
4817
5624
  }
5625
+ function parseRemoteNoteId(noteId) {
5626
+ if (!noteId.startsWith("remote:")) return { isRemote: false };
5627
+ const rest = noteId.slice("remote:".length);
5628
+ const sep = rest.indexOf(":");
5629
+ if (sep <= 0) return { isRemote: false };
5630
+ const feedId = rest.slice(0, sep);
5631
+ const uuid = rest.slice(sep + 1);
5632
+ if (!uuid) return { isRemote: false };
5633
+ return { isRemote: true, feedId, uuid };
5634
+ }
4818
5635
  function computeWodContentId(blockSource) {
4819
5636
  const sec = wodWikiCore.parseDocumentSections(blockSource, { registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS }).find(
4820
5637
  (s) => s.scriptBlock
@@ -4823,15 +5640,381 @@ function computeWodContentId(blockSource) {
4823
5640
  if (sec?.scriptBlock?.content) return wodWikiCore.blockContentId(sec.scriptBlock.content);
4824
5641
  return void 0;
4825
5642
  }
5643
+ function selectWorkoutBlock(sourceNote, ownershipKind, blockId, blockContentId6) {
5644
+ const sourceBlocks = Object.values(sourceNote.blocks ?? {});
5645
+ if (blockId) {
5646
+ const exact = sourceNote.blocks?.[blockId] ?? sourceBlocks.find((b) => b.id === blockId);
5647
+ if (exact) return exact;
5648
+ if (ownershipKind !== "user" && blockContentId6) {
5649
+ return sourceBlocks.find(
5650
+ (b) => b.kind === "wod" && computeWodContentId(sourceNote.rawContent.slice(b.from, b.to)) === blockContentId6
5651
+ );
5652
+ }
5653
+ return void 0;
5654
+ }
5655
+ return sourceBlocks.find((b) => b.kind === "wod");
5656
+ }
5657
+ function extractTitleFromMarkdown(rawContent, sourcePath) {
5658
+ const fm = readFrontmatterMeta(rawContent);
5659
+ if (typeof fm["title"] === "string" && fm["title"].trim()) return fm["title"].trim();
5660
+ const withoutFm = rawContent.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
5661
+ for (const line of withoutFm.split(/\r?\n/)) {
5662
+ const m = /^#\s+(.+)$/.exec(line);
5663
+ if (m?.[1]?.trim()) return m[1].trim();
5664
+ }
5665
+ if (sourcePath) {
5666
+ const stem = (sourcePath.split("/").at(-1) ?? "").replace(/\.md$/i, "");
5667
+ if (stem) return stem.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
5668
+ }
5669
+ return "Workout";
5670
+ }
5671
+ function parseFrontmatterDateEpoch(rawContent) {
5672
+ const fm = readFrontmatterMeta(rawContent);
5673
+ const rawDate = typeof fm["date"] === "string" ? fm["date"].trim() : "";
5674
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(rawDate);
5675
+ if (!match) return void 0;
5676
+ const ts = Date.parse(`${rawDate}T12:00:00Z`);
5677
+ if (!Number.isFinite(ts)) return void 0;
5678
+ const d = new Date(ts);
5679
+ if (d.getUTCMonth() !== Number(match[2]) - 1 || d.getUTCDate() !== Number(match[3])) {
5680
+ return void 0;
5681
+ }
5682
+ return ts;
5683
+ }
5684
+ function deriveNotebookSourceMeta(sourcePath, notebookSlug) {
5685
+ if (sourcePath?.startsWith("markdown/notebooks/")) {
5686
+ const rel = sourcePath.slice("markdown/notebooks/".length).replace(/\.md$/i, "");
5687
+ const segs = rel.split("/");
5688
+ const slug = segs[0];
5689
+ if (slug) {
5690
+ const isLanding = segs.length === 2 && segs[1].toLowerCase() === "readme";
5691
+ return {
5692
+ sourceId: isLanding ? `notebook:${slug}` : `notebook:${rel}`,
5693
+ seedChunkId: `notebook.${slug}`,
5694
+ sourceNotebookId: wodWikiCore.toNotebookId(slug)
5695
+ };
5696
+ }
5697
+ }
5698
+ if (notebookSlug) {
5699
+ const clean = wodWikiCore.notebookSlugFromId(notebookSlug);
5700
+ return {
5701
+ sourceId: `notebook:${clean}`,
5702
+ seedChunkId: `notebook.${clean}`,
5703
+ sourceNotebookId: wodWikiCore.toNotebookId(clean)
5704
+ };
5705
+ }
5706
+ return {};
5707
+ }
5708
+ function isEnvelope(val) {
5709
+ return typeof val === "object" && val !== null && !("rawContent" in val) && !("content" in val) && ("row" in val || "note" in val || "canonicalNoteId" in val);
5710
+ }
5711
+ function isBareSeedRow(val) {
5712
+ return typeof val === "object" && val !== null && "content" in val && "path" in val && !("rawContent" in val);
5713
+ }
5714
+ function normalizeRemoteResolution(requestedNoteId, resolution, now) {
5715
+ const parsedRemote = parseRemoteNoteId(requestedNoteId);
5716
+ let notePart;
5717
+ let seedRow;
5718
+ let envelopeFeedId;
5719
+ let envelopeNbSlug;
5720
+ let envelopeCanonicalId;
5721
+ let recordMeta;
5722
+ if (isEnvelope(resolution)) {
5723
+ notePart = resolution.note;
5724
+ seedRow = resolution.row;
5725
+ envelopeFeedId = resolution.feedId;
5726
+ envelopeNbSlug = resolution.notebookSlug;
5727
+ envelopeCanonicalId = resolution.canonicalNoteId;
5728
+ recordMeta = resolution.record;
5729
+ } else if (isBareSeedRow(resolution)) {
5730
+ seedRow = resolution;
5731
+ } else {
5732
+ notePart = resolution;
5733
+ if ("seedRow" in resolution && resolution.seedRow) {
5734
+ seedRow = resolution.seedRow;
5735
+ }
5736
+ }
5737
+ const rawContent = notePart?.rawContent ?? seedRow?.content ?? "";
5738
+ if (!rawContent) {
5739
+ throw new Error(`Resolved remote workout '${requestedNoteId}' has no Markdown content.`);
5740
+ }
5741
+ const canonicalNoteId = envelopeCanonicalId ?? (notePart?.id && !notePart.id.startsWith("remote:") ? notePart.id : void 0) ?? seedRow?.uuid ?? recordMeta?.uuid ?? (parsedRemote.isRemote ? parsedRemote.uuid : requestedNoteId);
5742
+ const sourcePath = notePart?.sourcePath ?? seedRow?.path ?? recordMeta?.path;
5743
+ const pathDerived = deriveNotebookSourceMeta(sourcePath, envelopeNbSlug);
5744
+ const feedSourceId = notePart?.feedSourceId ?? envelopeFeedId ?? (parsedRemote.isRemote ? parsedRemote.feedId : void 0);
5745
+ const sourceNotebookId = notePart?.sourceNotebookId ?? notePart?.provenance?.sourceNotebookId ?? pathDerived.sourceNotebookId ?? (notePart ? wodWikiWql.notebookOfItem(notePart) : void 0);
5746
+ const sourceId = notePart?.sourceId ?? pathDerived.sourceId;
5747
+ const seedChunkId = notePart?.seedChunkId ?? pathDerived.seedChunkId;
5748
+ const seedVersion = notePart?.seedVersion ?? seedRow?.version ?? recordMeta?.version ?? 1;
5749
+ const seedCommit = notePart?.seedCommit ?? seedRow?.commit ?? recordMeta?.commit;
5750
+ const date = notePart?.date ?? recordMeta?.date ?? parseFrontmatterDateEpoch(rawContent);
5751
+ const title = notePart?.title?.trim() || recordMeta?.title?.trim() || seedRow?.blockIndex?.[0]?.noteTitle?.trim() || extractTitleFromMarkdown(rawContent, sourcePath);
5752
+ const rawBlocks = notePart?.blocks && Object.keys(notePart.blocks).length > 0 ? notePart.blocks : seedRow?.blocks && Object.keys(seedRow.blocks).length > 0 ? seedRow.blocks : void 0;
5753
+ let ordinal = 0;
5754
+ const blocks = rawBlocks ? Object.fromEntries(
5755
+ Object.entries(rawBlocks).map(([k, b]) => [
5756
+ k,
5757
+ { ...b, version: b.version || 1, sourceRevision: 1 }
5758
+ ])
5759
+ ) : wodWikiCore.reconcileNoteBlocks(rawContent, {
5760
+ sourceRevision: 1,
5761
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS,
5762
+ createId: () => `blk-${canonicalNoteId.slice(0, 8)}-${ordinal++}`
5763
+ });
5764
+ return {
5765
+ canonicalNoteId,
5766
+ title,
5767
+ rawContent,
5768
+ blocks,
5769
+ ...date !== void 0 ? { date } : {},
5770
+ createdAt: notePart?.createdAt ?? date ?? now,
5771
+ ...notePart?.tags?.length ? { tags: notePart.tags.filter((t) => t !== "preview:remote") } : {},
5772
+ type: notePart?.type ?? "note",
5773
+ ...sourceId ? { sourceId } : {},
5774
+ ...sourcePath ? { sourcePath } : {},
5775
+ seedOrigin: notePart?.seedOrigin ?? "seed",
5776
+ feedOrigin: notePart?.feedOrigin ?? "feed",
5777
+ ...feedSourceId ? { feedSourceId } : {},
5778
+ seedVersion,
5779
+ ...seedChunkId ? { seedChunkId } : {},
5780
+ ...seedCommit ? { seedCommit } : {},
5781
+ ...sourceNotebookId ? { sourceNotebookId } : {},
5782
+ upstreamStatus: notePart?.upstreamStatus ?? "live",
5783
+ ...seedRow ? { seedRow } : {}
5784
+ };
5785
+ }
5786
+ async function ensureNoteBlockRevisionsAndIndexInTx(tx, note, now, seedRow) {
5787
+ const revStore = tx.readwrite("block_revisions");
5788
+ const idxStore = tx.readwrite("block_index");
5789
+ const blockList = Object.values(note.blocks ?? {}).sort((a, b) => a.from - b.from);
5790
+ const isStatic = note.seedOrigin === "seed" || note.feedOrigin === "feed" || void 0;
5791
+ const resolvedNb = wodWikiWql.notebookOfItem(note);
5792
+ const missingRevs = [];
5793
+ const missingIdx = [];
5794
+ const existingIdxRows = await idxStore.getAllFromIndex("by-note", note.id);
5795
+ const existingIdxIds = new Set(existingIdxRows.map((r) => r.id));
5796
+ for (const [pos, b] of blockList.entries()) {
5797
+ const slice = note.rawContent.slice(b.from, b.to);
5798
+ const existingRev = await revStore.get([note.id, b.id, b.version]);
5799
+ if (!existingRev) {
5800
+ missingRevs.push({
5801
+ noteId: note.id,
5802
+ blockId: b.id,
5803
+ version: b.version,
5804
+ kind: b.kind,
5805
+ rawContent: slice,
5806
+ savedAt: now,
5807
+ ...b.dialect ? { dialect: b.dialect } : {},
5808
+ ...b.sport ? { sport: b.sport } : {}
5809
+ });
5810
+ }
5811
+ const rowId = `${note.id}:${b.id}`;
5812
+ if (!existingIdxIds.has(rowId)) {
5813
+ const cid = b.kind === "wod" ? computeWodContentId(slice) : void 0;
5814
+ missingIdx.push({
5815
+ id: rowId,
5816
+ noteId: note.id,
5817
+ blockId: b.id,
5818
+ blockVersion: b.version,
5819
+ sourceRevision: note.sourceRevision,
5820
+ from: b.from,
5821
+ to: b.to,
5822
+ position: pos,
5823
+ dataType: b.kind,
5824
+ ...cid ? { blockContentId: cid } : {},
5825
+ rawContent: slice,
5826
+ noteTitle: note.title,
5827
+ createdAt: note.date ?? note.createdAt ?? now,
5828
+ ...isStatic ? { isStatic: true } : {},
5829
+ ...note.sourceId ? { sourceId: note.sourceId } : {},
5830
+ ...note.sourcePath ? { sourcePath: note.sourcePath } : {},
5831
+ ...resolvedNb ? { notebookId: resolvedNb } : {}
5832
+ });
5833
+ }
5834
+ }
5835
+ if (missingRevs.length > 0) await revStore.putMany(missingRevs);
5836
+ if (missingIdx.length > 0) await idxStore.putMany(missingIdx);
5837
+ if (seedRow?.blockEfforts?.length) {
5838
+ try {
5839
+ const effortStore = tx.readwrite("block_efforts");
5840
+ const rows = seedRow.blockEfforts.map((eff) => ({
5841
+ ...eff,
5842
+ id: `${note.id}:${eff.blockId}:${eff.effortSlug}`,
5843
+ noteId: note.id,
5844
+ ...isStatic ? { isStatic: true } : {}
5845
+ }));
5846
+ if (rows.length > 0) await effortStore.putMany(rows);
5847
+ } catch {
5848
+ }
5849
+ }
5850
+ if (seedRow?.blockEquipment?.length) {
5851
+ try {
5852
+ const eqStore = tx.readwrite("block_equipment");
5853
+ const rows = seedRow.blockEquipment.map((eq) => ({
5854
+ ...eq,
5855
+ id: `${note.id}:${eq.blockId}:${eq.equipmentSlug}`,
5856
+ noteId: note.id,
5857
+ ...isStatic ? { isStatic: true } : {}
5858
+ }));
5859
+ if (rows.length > 0) await eqStore.putMany(rows);
5860
+ } catch {
5861
+ }
5862
+ }
5863
+ }
5864
+ async function getOrCreateJournalPageInTx(tx, journalDate, now) {
5865
+ let existingPages;
5866
+ try {
5867
+ existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
5868
+ } catch {
5869
+ existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
5870
+ }
5871
+ if (existingPages[0]) return existingPages[0];
5872
+ const page = {
5873
+ id: mintUuid(),
5874
+ date: journalDate,
5875
+ title: journalDate,
5876
+ createdAt: now
5877
+ };
5878
+ await tx.readwrite("page").put(page);
5879
+ return page;
5880
+ }
5881
+ function promoteExternalNoteInPlace(existing, ownership, now, requestedRetention = "session-pinned") {
5882
+ const nextRetention = existing.retention === "session-pinned" || requestedRetention === "session-pinned" ? "session-pinned" : "schedule-pinned";
5883
+ const nextUpstreamStatus = existing.upstreamStatus ?? "live";
5884
+ const nextProvenance = existing.provenance ?? buildNoteProvenance(existing, ownership.sourceNotebookId ?? wodWikiWql.notebookOfItem(existing), now);
5885
+ const changed = existing.retention !== nextRetention || existing.upstreamStatus !== nextUpstreamStatus || !existing.provenance;
5886
+ if (!changed) return { updated: existing, changed: false };
5887
+ return {
5888
+ updated: {
5889
+ ...existing,
5890
+ retention: nextRetention,
5891
+ upstreamStatus: nextUpstreamStatus,
5892
+ provenance: nextProvenance
5893
+ },
5894
+ changed: true
5895
+ };
5896
+ }
5897
+ async function ensurePinnedExternalWorkout(storage, input) {
5898
+ const now = input.now ?? Date.now();
5899
+ const parsedRemote = parseRemoteNoteId(input.noteId);
5900
+ const initialCandidateId = parsedRemote.isRemote ? parsedRemote.uuid : input.noteId;
5901
+ let preloaded = await storage.readonly("notes").get(initialCandidateId) ?? (input.noteId !== initialCandidateId ? await storage.readonly("notes").get(input.noteId) : void 0);
5902
+ let materialized;
5903
+ if (!preloaded) {
5904
+ const resolved = input.remotePayload ?? (input.resolveRemoteWorkout ? await input.resolveRemoteWorkout(input.noteId) : void 0);
5905
+ if (!resolved) {
5906
+ throw new Error(`Note not found: ${input.noteId}`);
5907
+ }
5908
+ materialized = normalizeRemoteResolution(input.noteId, resolved, now);
5909
+ preloaded = await storage.readonly("notes").get(materialized.canonicalNoteId);
5910
+ }
5911
+ return storage.transaction(
5912
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment"],
5913
+ "readwrite",
5914
+ async (tx) => {
5915
+ const targetId = materialized?.canonicalNoteId ?? preloaded?.id ?? initialCandidateId;
5916
+ const existing = await tx.readonly("notes").get(targetId);
5917
+ if (existing) {
5918
+ const ownership2 = wodWikiCore.resolveNoteOwnership(
5919
+ existing,
5920
+ wodWikiWql.notebookOriginOfItem(existing),
5921
+ wodWikiWql.notebookOfItem(existing)
5922
+ );
5923
+ if (ownership2.kind === "user") {
5924
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, existing, now);
5925
+ return {
5926
+ note: existing,
5927
+ created: false,
5928
+ promotedFromLocal: false,
5929
+ ownership: ownership2
5930
+ };
5931
+ }
5932
+ const { updated, changed } = promoteExternalNoteInPlace(
5933
+ existing,
5934
+ ownership2,
5935
+ now,
5936
+ input.retention ?? "session-pinned"
5937
+ );
5938
+ if (changed) {
5939
+ await tx.readwrite("notes").put(updated);
5940
+ }
5941
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, updated, now);
5942
+ const nextOwnership = wodWikiCore.resolveNoteOwnership(
5943
+ updated,
5944
+ wodWikiWql.notebookOriginOfItem(updated),
5945
+ wodWikiWql.notebookOfItem(updated)
5946
+ );
5947
+ return {
5948
+ note: updated,
5949
+ created: false,
5950
+ promotedFromLocal: changed,
5951
+ ownership: nextOwnership
5952
+ };
5953
+ }
5954
+ if (!materialized) {
5955
+ throw new Error(`Note not found: ${input.noteId}`);
5956
+ }
5957
+ const newNote = {
5958
+ id: materialized.canonicalNoteId,
5959
+ title: materialized.title,
5960
+ rawContent: materialized.rawContent,
5961
+ sourceRevision: 1,
5962
+ blocks: materialized.blocks,
5963
+ ...materialized.date !== void 0 ? { date: materialized.date } : {},
5964
+ createdAt: materialized.createdAt,
5965
+ type: materialized.type,
5966
+ ...materialized.sourceId ? { sourceId: materialized.sourceId } : {},
5967
+ ...materialized.tags?.length ? { tags: materialized.tags } : {},
5968
+ seedOrigin: materialized.seedOrigin,
5969
+ seedVersion: materialized.seedVersion,
5970
+ ...materialized.seedChunkId ? { seedChunkId: materialized.seedChunkId } : {},
5971
+ ...materialized.feedOrigin ? { feedOrigin: materialized.feedOrigin } : {},
5972
+ ...materialized.feedSourceId ? { feedSourceId: materialized.feedSourceId } : {},
5973
+ ...materialized.sourcePath ? { sourcePath: materialized.sourcePath } : {},
5974
+ ...materialized.seedCommit ? { seedCommit: materialized.seedCommit } : {},
5975
+ retention: input.retention ?? "session-pinned",
5976
+ upstreamStatus: materialized.upstreamStatus,
5977
+ provenance: {
5978
+ sourceNoteId: materialized.canonicalNoteId,
5979
+ sourceVersion: materialized.seedVersion,
5980
+ ...materialized.seedCommit ? { sourceCommit: materialized.seedCommit } : {},
5981
+ ...materialized.feedSourceId ? { feedSourceId: materialized.feedSourceId } : {},
5982
+ ...materialized.sourceNotebookId ? { sourceNotebookId: materialized.sourceNotebookId } : {},
5983
+ ...materialized.sourcePath ? { sourcePath: materialized.sourcePath } : {},
5984
+ clonedAt: now
5985
+ }
5986
+ };
5987
+ await tx.readwrite("notes").put(newNote);
5988
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, newNote, now, materialized.seedRow);
5989
+ const ownership = wodWikiCore.resolveNoteOwnership(
5990
+ newNote,
5991
+ wodWikiWql.notebookOriginOfItem(newNote),
5992
+ wodWikiWql.notebookOfItem(newNote)
5993
+ );
5994
+ return {
5995
+ note: newNote,
5996
+ created: true,
5997
+ promotedFromLocal: false,
5998
+ ownership
5999
+ };
6000
+ }
6001
+ );
6002
+ }
4826
6003
  async function prepareJournalSessionRun(storage, input) {
4827
6004
  const startedAt = input.startedAt ?? Date.now();
4828
6005
  const sessionId = input.sessionId ?? mintUuid();
4829
6006
  const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
6007
+ const pinned = await ensurePinnedExternalWorkout(storage, {
6008
+ noteId: input.noteId,
6009
+ remotePayload: input.remotePayload,
6010
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
6011
+ now: startedAt
6012
+ });
4830
6013
  return storage.transaction(
4831
- ["notes", "block_revisions", "block_index", "sessions", "page", "page_notes", "notebook_links"],
6014
+ ["notes", "block_revisions", "block_index", "sessions", "page", "notebook_links"],
4832
6015
  "readwrite",
4833
6016
  async (tx) => {
4834
- const sourceNote = await tx.readonly("notes").get(input.noteId);
6017
+ const sourceNote = await tx.readonly("notes").get(pinned.note.id);
4835
6018
  if (!sourceNote) {
4836
6019
  throw new Error(`Note not found: ${input.noteId}`);
4837
6020
  }
@@ -4839,113 +6022,46 @@ async function prepareJournalSessionRun(storage, input) {
4839
6022
  if (existingSession) {
4840
6023
  throw new Error(`Session already exists: ${sessionId}`);
4841
6024
  }
4842
- const sourceBlocks = Object.values(sourceNote.blocks);
4843
- const selectedSourceBlock = input.blockId ? sourceNote.blocks[input.blockId] ?? sourceBlocks.find((b) => b.id === input.blockId) : sourceBlocks.find((b) => b.kind === "wod");
6025
+ const nbOrigin = wodWikiWql.notebookOriginOfItem(sourceNote);
6026
+ const resolvedNb = wodWikiWql.notebookOfItem(sourceNote);
6027
+ const ownership = wodWikiCore.resolveNoteOwnership(sourceNote, nbOrigin, resolvedNb);
6028
+ const selectedSourceBlock = selectWorkoutBlock(
6029
+ sourceNote,
6030
+ ownership.kind,
6031
+ input.blockId,
6032
+ input.blockContentId
6033
+ );
4844
6034
  if (!selectedSourceBlock || selectedSourceBlock.kind !== "wod") {
4845
6035
  throw new Error(`Selected workout block is unavailable on Note '${input.noteId}'.`);
4846
6036
  }
4847
- const nbOrigin = wodWikiWql.notebookOriginOfItem(sourceNote);
4848
- const resolvedNb = wodWikiWql.notebookOfItem(sourceNote);
4849
- const editable = wodWikiCore.isNoteEditable(sourceNote, nbOrigin, resolvedNb);
4850
- if (!editable) {
4851
- const clonedNoteId = mintUuid();
4852
- let ordinal = 0;
4853
- const clonedBlocks = wodWikiCore.reconcileNoteBlocks(sourceNote.rawContent, {
4854
- sourceRevision: 1,
4855
- registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS,
4856
- createId: () => `blk-${clonedNoteId.slice(0, 8)}-${ordinal++}`
4857
- });
4858
- const clonedBlockList = Object.values(clonedBlocks);
4859
- const mappedBlock = clonedBlockList.find(
4860
- (b) => b.kind === "wod" && b.from === selectedSourceBlock.from && b.to === selectedSourceBlock.to
4861
- ) ?? clonedBlockList.find((b) => b.kind === "wod");
4862
- if (!mappedBlock) {
4863
- throw new Error("Cloned Journal Note contains no runnable workout block.");
4864
- }
4865
- const revisions = [];
4866
- const projections = [];
4867
- let pinnedRevision;
4868
- for (const [pos, b] of clonedBlockList.entries()) {
4869
- const slice = sourceNote.rawContent.slice(b.from, b.to);
4870
- const rev = {
4871
- noteId: clonedNoteId,
4872
- blockId: b.id,
4873
- version: 1,
4874
- kind: b.kind,
4875
- rawContent: slice,
4876
- savedAt: startedAt,
4877
- ...b.dialect ? { dialect: b.dialect } : {},
4878
- ...b.sport ? { sport: b.sport } : {}
4879
- };
4880
- revisions.push(rev);
4881
- if (b.id === mappedBlock.id) pinnedRevision = rev;
4882
- const cid3 = b.kind === "wod" ? computeWodContentId(slice) : void 0;
4883
- projections.push({
4884
- id: `${clonedNoteId}:${b.id}`,
4885
- noteId: clonedNoteId,
4886
- blockId: b.id,
4887
- blockVersion: 1,
4888
- sourceRevision: 1,
4889
- from: b.from,
4890
- to: b.to,
4891
- position: pos,
4892
- dataType: b.kind,
4893
- ...cid3 ? { blockContentId: cid3 } : {},
4894
- rawContent: slice,
4895
- noteTitle: sourceNote.title,
4896
- createdAt: startedAt,
4897
- isStatic: false,
4898
- notebookId: "notebook/journal"
4899
- });
4900
- }
4901
- const provenance = buildNoteProvenance(sourceNote, resolvedNb, startedAt);
4902
- const dateEpoch = Date.parse(`${journalDate}T12:00:00Z`);
4903
- const clonedNote = {
4904
- id: clonedNoteId,
4905
- title: sourceNote.title,
4906
- rawContent: sourceNote.rawContent,
4907
- sourceRevision: 1,
4908
- blocks: clonedBlocks,
4909
- ...Number.isFinite(dateEpoch) ? { date: dateEpoch } : {},
4910
- createdAt: startedAt,
4911
- type: "journal",
4912
- sourceId: sourceNote.id,
4913
- notebookIds: ["notebook/journal"],
4914
- provenance,
4915
- ...sourceNote.tags?.length ? { tags: [...sourceNote.tags] } : {},
4916
- seedOrigin: "user"
4917
- };
4918
- let existingPages;
4919
- try {
4920
- existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
4921
- } catch {
4922
- existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
4923
- }
4924
- let targetPage = existingPages[0];
4925
- if (!targetPage) {
4926
- targetPage = {
4927
- id: mintUuid(),
4928
- date: journalDate,
4929
- title: journalDate,
4930
- createdAt: startedAt
4931
- };
4932
- await tx.readwrite("page").put(targetPage);
4933
- }
4934
- const pageNote = {
4935
- id: mintUuid(),
4936
- pageId: targetPage.id,
4937
- noteId: clonedNoteId,
4938
- createdAt: startedAt
6037
+ const targetPage = await getOrCreateJournalPageInTx(tx, journalDate, startedAt);
6038
+ let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
6039
+ if (!revision) {
6040
+ revision = {
6041
+ noteId: sourceNote.id,
6042
+ blockId: selectedSourceBlock.id,
6043
+ version: selectedSourceBlock.version,
6044
+ kind: selectedSourceBlock.kind,
6045
+ rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
6046
+ savedAt: startedAt,
6047
+ ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
6048
+ ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
4939
6049
  };
4940
- const cid2 = computeWodContentId(pinnedRevision.rawContent);
6050
+ await tx.readwrite("block_revisions").put(revision);
6051
+ }
6052
+ const cid = computeWodContentId(revision.rawContent);
6053
+ if (ownership.kind !== "user") {
4941
6054
  const session2 = {
4942
6055
  id: sessionId,
4943
- noteId: clonedNoteId,
4944
- blockId: mappedBlock.id,
4945
- blockVersion: 1,
4946
- ...cid2 ? { blockContentId: cid2 } : {},
6056
+ noteId: sourceNote.id,
6057
+ noteSourceRevision: sourceNote.sourceRevision,
6058
+ blockId: selectedSourceBlock.id,
6059
+ blockVersion: revision.version,
6060
+ ...cid ? { blockContentId: cid } : {},
4947
6061
  origin: input.origin ?? "journal",
4948
6062
  pageId: targetPage.id,
6063
+ sessionDate: journalDate,
6064
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
4949
6065
  status: "in-progress",
4950
6066
  startTime: startedAt,
4951
6067
  endTime: startedAt,
@@ -4954,74 +6070,49 @@ async function prepareJournalSessionRun(storage, input) {
4954
6070
  createdAt: startedAt,
4955
6071
  notebookIds: ["notebook/journal"]
4956
6072
  };
4957
- const links2 = [
4958
- {
4959
- id: makeNotebookLinkId("notebook/journal", "note", clonedNoteId),
4960
- notebookId: "notebook/journal",
4961
- targetKind: "note",
4962
- targetId: clonedNoteId,
4963
- noteId: clonedNoteId,
4964
- createdAt: startedAt
4965
- }
4966
- ];
4967
- await tx.readwrite("notes").put(clonedNote);
4968
- if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
4969
- if (projections.length > 0) await tx.readwrite("block_index").putMany(projections);
4970
- await tx.readwrite("page_notes").put(pageNote);
4971
- await tx.readwrite("notebook_links").putMany(links2);
4972
6073
  return {
4973
- note: clonedNote,
4974
- revision: pinnedRevision,
6074
+ note: sourceNote,
6075
+ revision,
4975
6076
  session: session2,
4976
- clonedFromReadOnly: true,
6077
+ clonedFromReadOnly: false,
6078
+ pinnedExternalWorkout: true,
4977
6079
  upstreamNoteId: sourceNote.id
4978
6080
  };
4979
6081
  }
4980
6082
  const isPlayground = sourceNote.type === "playground" || sourceNote.sourceId === "playground" || sourceNote.notebookId === "notebook/playground";
4981
- const baseNotebooks = isPlayground ? ["notebook/journal", "notebook/playground"] : ["notebook/journal"];
4982
- const mergedNotebooks = [
6083
+ const currentNotebooks = [
4983
6084
  .../* @__PURE__ */ new Set([
4984
- ...baseNotebooks,
6085
+ ...isPlayground ? ["notebook/playground"] : [],
4985
6086
  ...sourceNote.notebookIds ?? [],
4986
6087
  ...sourceNote.notebookId ? [sourceNote.notebookId] : []
4987
6088
  ])
4988
6089
  ];
4989
- const updatedNote = JSON.stringify(sourceNote.notebookIds) === JSON.stringify(mergedNotebooks) ? sourceNote : { ...sourceNote, notebookIds: mergedNotebooks };
6090
+ const updatedNote = sourceNote.notebookIds !== void 0 && JSON.stringify(sourceNote.notebookIds) === JSON.stringify(currentNotebooks) ? sourceNote : { ...sourceNote, notebookIds: currentNotebooks };
4990
6091
  if (updatedNote !== sourceNote) {
4991
6092
  await tx.readwrite("notes").put(updatedNote);
4992
6093
  }
4993
- let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
4994
- if (!revision) {
4995
- revision = {
4996
- noteId: sourceNote.id,
4997
- blockId: selectedSourceBlock.id,
4998
- version: selectedSourceBlock.version,
4999
- kind: selectedSourceBlock.kind,
5000
- rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
5001
- savedAt: startedAt,
5002
- ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
5003
- ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
5004
- };
5005
- await tx.readwrite("block_revisions").put(revision);
5006
- }
5007
- const cid = computeWodContentId(revision.rawContent);
5008
6094
  const effectiveOrigin = input.origin ?? (isPlayground ? "playground" : "journal");
6095
+ const sessionNotebooks = currentNotebooks.length > 0 ? [...currentNotebooks] : ["notebook/journal"];
5009
6096
  const session = {
5010
6097
  id: sessionId,
5011
6098
  noteId: sourceNote.id,
6099
+ noteSourceRevision: sourceNote.sourceRevision,
5012
6100
  blockId: selectedSourceBlock.id,
5013
6101
  blockVersion: revision.version,
5014
6102
  ...cid ? { blockContentId: cid } : {},
5015
6103
  origin: effectiveOrigin,
6104
+ pageId: targetPage.id,
6105
+ sessionDate: journalDate,
6106
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
5016
6107
  status: "in-progress",
5017
6108
  startTime: startedAt,
5018
6109
  endTime: startedAt,
5019
6110
  duration: 0,
5020
6111
  completed: false,
5021
6112
  createdAt: startedAt,
5022
- notebookIds: [...baseNotebooks]
6113
+ notebookIds: sessionNotebooks
5023
6114
  };
5024
- const links = mergedNotebooks.map((nbId) => ({
6115
+ const links = currentNotebooks.map((nbId) => ({
5025
6116
  id: makeNotebookLinkId(nbId, "note", sourceNote.id),
5026
6117
  notebookId: nbId,
5027
6118
  targetKind: "note",
@@ -5029,23 +6120,284 @@ async function prepareJournalSessionRun(storage, input) {
5029
6120
  noteId: sourceNote.id,
5030
6121
  createdAt: startedAt
5031
6122
  }));
5032
- await tx.readwrite("notebook_links").putMany(links);
6123
+ if (links.length > 0) {
6124
+ await tx.readwrite("notebook_links").putMany(links);
6125
+ }
5033
6126
  return {
5034
6127
  note: updatedNote,
5035
6128
  revision,
5036
6129
  session,
5037
- clonedFromReadOnly: false
6130
+ clonedFromReadOnly: false,
6131
+ pinnedExternalWorkout: false
5038
6132
  };
5039
6133
  }
5040
6134
  );
5041
6135
  }
6136
+ async function logSessionAgainstExternalWorkout(storage, input) {
6137
+ const startedAt = input.startedAt ?? Date.now();
6138
+ const duration = Math.max(0, input.durationMs ?? (input.endedAt !== void 0 ? input.endedAt - startedAt : 0));
6139
+ const endTime = input.endedAt ?? startedAt + duration;
6140
+ const sessionId = input.sessionId ?? mintUuid();
6141
+ const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
6142
+ const pinnedResult = await ensurePinnedExternalWorkout(storage, {
6143
+ noteId: input.noteId,
6144
+ remotePayload: input.remotePayload,
6145
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
6146
+ now: startedAt
6147
+ });
6148
+ return storage.transaction(
6149
+ ["notes", "block_revisions", "sessions", "events", "page", "notebook_links", "schedule_items"],
6150
+ "readwrite",
6151
+ async (tx) => {
6152
+ const note = await tx.readonly("notes").get(pinnedResult.note.id);
6153
+ if (!note) {
6154
+ throw new Error(`Pinned workout note disappeared: ${pinnedResult.note.id}`);
6155
+ }
6156
+ const existingSession = await tx.readonly("sessions").get(sessionId);
6157
+ if (existingSession) {
6158
+ throw new Error(`Session already exists: ${sessionId}`);
6159
+ }
6160
+ const ownership = wodWikiCore.resolveNoteOwnership(note, wodWikiWql.notebookOriginOfItem(note), wodWikiWql.notebookOfItem(note));
6161
+ const selectedBlock = selectWorkoutBlock(
6162
+ note,
6163
+ ownership.kind,
6164
+ input.blockId,
6165
+ input.blockContentId
6166
+ );
6167
+ if (!selectedBlock || selectedBlock.kind !== "wod") {
6168
+ throw new Error(`Selected workout block is unavailable on Note '${note.id}'.`);
6169
+ }
6170
+ let revision = await tx.readonly("block_revisions").get([note.id, selectedBlock.id, selectedBlock.version]);
6171
+ if (!revision) {
6172
+ revision = {
6173
+ noteId: note.id,
6174
+ blockId: selectedBlock.id,
6175
+ version: selectedBlock.version,
6176
+ kind: selectedBlock.kind,
6177
+ rawContent: note.rawContent.slice(selectedBlock.from, selectedBlock.to),
6178
+ savedAt: startedAt,
6179
+ ...selectedBlock.dialect ? { dialect: selectedBlock.dialect } : {},
6180
+ ...selectedBlock.sport ? { sport: selectedBlock.sport } : {}
6181
+ };
6182
+ await tx.readwrite("block_revisions").put(revision);
6183
+ }
6184
+ const page = await getOrCreateJournalPageInTx(tx, journalDate, startedAt);
6185
+ const cid = computeWodContentId(revision.rawContent);
6186
+ const session = {
6187
+ id: sessionId,
6188
+ noteId: note.id,
6189
+ noteSourceRevision: note.sourceRevision,
6190
+ blockId: selectedBlock.id,
6191
+ blockVersion: revision.version,
6192
+ ...cid ? { blockContentId: cid } : {},
6193
+ origin: input.origin ?? "journal",
6194
+ pageId: page.id,
6195
+ sessionDate: journalDate,
6196
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
6197
+ status: "completed",
6198
+ startTime: startedAt,
6199
+ endTime,
6200
+ duration,
6201
+ ...input.roundsCompleted !== void 0 ? { roundsCompleted: input.roundsCompleted } : {},
6202
+ ...input.totalRounds !== void 0 ? { totalRounds: input.totalRounds } : {},
6203
+ ...input.repsCompleted !== void 0 ? { repsCompleted: input.repsCompleted } : {},
6204
+ completed: input.completed ?? true,
6205
+ createdAt: endTime,
6206
+ ...input.public !== void 0 ? { public: input.public } : {},
6207
+ notebookIds: ["notebook/journal"]
6208
+ };
6209
+ const links = [
6210
+ {
6211
+ id: makeNotebookLinkId("notebook/journal", "session", session.id),
6212
+ notebookId: "notebook/journal",
6213
+ targetKind: "session",
6214
+ targetId: session.id,
6215
+ noteId: note.id,
6216
+ createdAt: endTime
6217
+ }
6218
+ ];
6219
+ const normalizedEvents = (input.events ?? []).map((ev) => ({
6220
+ ...ev,
6221
+ resultId: session.id,
6222
+ noteId: note.id,
6223
+ blockId: selectedBlock.id,
6224
+ blockVersion: revision.version,
6225
+ ...cid ? { blockContentId: cid } : {},
6226
+ pageId: page.id
6227
+ }));
6228
+ await tx.readwrite("sessions").put(session);
6229
+ if (input.scheduleItemId) {
6230
+ const schedItem = await tx.readonly("schedule_items").get(input.scheduleItemId);
6231
+ if (schedItem && schedItem.status !== "completed") {
6232
+ await tx.readwrite("schedule_items").put({
6233
+ ...schedItem,
6234
+ status: "completed",
6235
+ updatedAt: endTime
6236
+ });
6237
+ }
6238
+ }
6239
+ await tx.readwrite("notebook_links").putMany(links);
6240
+ if (normalizedEvents.length > 0) {
6241
+ await tx.readwrite("events").putMany(normalizedEvents);
6242
+ }
6243
+ return {
6244
+ note,
6245
+ revision,
6246
+ session,
6247
+ page,
6248
+ links,
6249
+ events: normalizedEvents,
6250
+ pinnedResult
6251
+ };
6252
+ }
6253
+ );
6254
+ }
6255
+ async function forkNoteToUserNotebook(storage, sourceNoteId, targetNotebookId, options = {}) {
6256
+ const targetNb = wodWikiCore.toNotebookId(targetNotebookId);
6257
+ if (wodWikiCore.isSystemReadOnlyNotebook(targetNb)) {
6258
+ throw new Error(`Target notebook '${targetNb}' is read-only and cannot receive forked notes.`);
6259
+ }
6260
+ const now = options.now ?? Date.now();
6261
+ const parsedRemote = parseRemoteNoteId(sourceNoteId);
6262
+ const candidateId = parsedRemote.isRemote ? parsedRemote.uuid : sourceNoteId;
6263
+ let sourceNote = await storage.readonly("notes").get(candidateId) ?? (sourceNoteId !== candidateId ? await storage.readonly("notes").get(sourceNoteId) : void 0);
6264
+ let fallbackMat;
6265
+ if (!sourceNote) {
6266
+ const resolved = options.remotePayload ?? (options.resolveRemoteWorkout ? await options.resolveRemoteWorkout(sourceNoteId) : void 0);
6267
+ if (!resolved) {
6268
+ throw new Error(`Source Note not found: ${sourceNoteId}`);
6269
+ }
6270
+ fallbackMat = normalizeRemoteResolution(sourceNoteId, resolved, now);
6271
+ sourceNote = await storage.readonly("notes").get(fallbackMat.canonicalNoteId);
6272
+ }
6273
+ const sourceIdForProvenance = sourceNote?.id ?? fallbackMat.canonicalNoteId;
6274
+ const sourceTitle = options.title?.trim() || sourceNote?.title || fallbackMat.title;
6275
+ const rawContent = sourceNote?.rawContent ?? fallbackMat.rawContent;
6276
+ const sourceTags = sourceNote?.tags ?? fallbackMat?.tags;
6277
+ const sourceNb = sourceNote ? wodWikiWql.notebookOfItem(sourceNote) : fallbackMat?.sourceNotebookId;
6278
+ const provenance = sourceNote ? buildNoteProvenance(sourceNote, sourceNb, now) : {
6279
+ sourceNoteId: sourceIdForProvenance,
6280
+ sourceVersion: fallbackMat.seedVersion,
6281
+ ...fallbackMat.seedCommit ? { sourceCommit: fallbackMat.seedCommit } : {},
6282
+ ...fallbackMat.feedSourceId ? { feedSourceId: fallbackMat.feedSourceId } : {},
6283
+ ...sourceNb ? { sourceNotebookId: sourceNb } : {},
6284
+ ...fallbackMat.sourcePath ? { sourcePath: fallbackMat.sourcePath } : {},
6285
+ clonedAt: now
6286
+ };
6287
+ const forkedId = mintUuid();
6288
+ let ordinal = 0;
6289
+ const blocks = wodWikiCore.reconcileNoteBlocks(rawContent, {
6290
+ sourceRevision: 1,
6291
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS,
6292
+ createId: () => `blk-${forkedId.slice(0, 8)}-${ordinal++}`
6293
+ });
6294
+ const notebookIds = [targetNb];
6295
+ if (targetNb === "notebook/playground" && !notebookIds.includes("notebook/playground")) {
6296
+ notebookIds.push("notebook/playground");
6297
+ }
6298
+ const dateMs = options.journalDate ? Date.parse(`${options.journalDate}T12:00:00Z`) : sourceNote?.date ?? fallbackMat?.date;
6299
+ const forkedNote = {
6300
+ id: forkedId,
6301
+ title: sourceTitle,
6302
+ rawContent,
6303
+ sourceRevision: 1,
6304
+ blocks,
6305
+ ...dateMs !== void 0 && Number.isFinite(dateMs) ? { date: dateMs } : {},
6306
+ createdAt: now,
6307
+ type: targetNb === "notebook/playground" ? "playground" : targetNb === "notebook/journal" ? "journal" : "note",
6308
+ sourceId: sourceIdForProvenance,
6309
+ ...targetNb !== "notebook/journal" && targetNb !== "notebook/playground" ? { notebookId: targetNb } : {},
6310
+ notebookIds,
6311
+ provenance,
6312
+ ...sourceTags?.length ? { tags: sourceTags.filter((t) => t !== "preview:remote") } : {},
6313
+ seedOrigin: "user"
6314
+ };
6315
+ return storage.transaction(
6316
+ ["notes", "block_revisions", "block_index", "notebook_links", "page", "page_notes", "schedule_items"],
6317
+ "readwrite",
6318
+ async (tx) => {
6319
+ if (targetNb !== "notebook/journal" && targetNb !== "notebook/playground") {
6320
+ const landing = await tx.readonly("notes").get(targetNb);
6321
+ if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
6322
+ throw new Error(`Target notebook '${targetNb}' is feed-delivered and read-only.`);
6323
+ }
6324
+ if (!landing && !wodWikiCore.isNonPublishableNotebook(targetNb)) {
6325
+ const slug = wodWikiCore.notebookSlugFromId(targetNb);
6326
+ const landingTitle = slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ") || slug;
6327
+ await tx.readwrite("notes").put({
6328
+ id: targetNb,
6329
+ title: landingTitle,
6330
+ rawContent: `# ${landingTitle}
6331
+ `,
6332
+ sourceRevision: 1,
6333
+ blocks: {},
6334
+ createdAt: now,
6335
+ notebookId: targetNb,
6336
+ seedOrigin: "user"
6337
+ });
6338
+ }
6339
+ }
6340
+ await tx.readwrite("notes").put(forkedNote);
6341
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, forkedNote, now);
6342
+ const links = notebookIds.map((nbId) => ({
6343
+ id: makeNotebookLinkId(nbId, "note", forkedNote.id),
6344
+ notebookId: nbId,
6345
+ targetKind: "note",
6346
+ targetId: forkedNote.id,
6347
+ noteId: forkedNote.id,
6348
+ createdAt: now
6349
+ }));
6350
+ await tx.readwrite("notebook_links").putMany(links);
6351
+ if (options.journalDate) {
6352
+ const page = await getOrCreateJournalPageInTx(tx, options.journalDate, now);
6353
+ const pageNote = {
6354
+ id: mintUuid(),
6355
+ pageId: page.id,
6356
+ noteId: forkedNote.id,
6357
+ createdAt: now
6358
+ };
6359
+ await tx.readwrite("page_notes").put(pageNote);
6360
+ await tx.readwrite("schedule_items").put({
6361
+ id: mintUuid(),
6362
+ date: options.journalDate,
6363
+ noteId: forkedNote.id,
6364
+ pageId: page.id,
6365
+ sourceNotebookId: targetNb,
6366
+ fallbackTitle: forkedNote.title,
6367
+ position: 0,
6368
+ status: "planned",
6369
+ createdAt: now,
6370
+ updatedAt: now
6371
+ });
6372
+ }
6373
+ return forkedNote;
6374
+ }
6375
+ );
6376
+ }
5042
6377
  async function resolveUpstreamProvenance(storage, note) {
5043
- const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : void 0);
6378
+ const isExternalPinned = Boolean(note.id) && (note.retention === "session-pinned" || note.upstreamStatus !== void 0 || note.seedOrigin === "seed" || note.feedOrigin === "feed");
6379
+ const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : isExternalPinned ? note.id : void 0);
5044
6380
  if (!sourceNoteId) return null;
6381
+ if (note.id && sourceNoteId === note.id) {
6382
+ const status = note.upstreamStatus ?? "live";
6383
+ const isLive = status === "live";
6384
+ return {
6385
+ exists: isLive,
6386
+ sourceNoteId,
6387
+ ...isLive ? { currentUpstreamVersion: note.seedVersion ?? note.sourceRevision } : {},
6388
+ sourceVersion: note.provenance?.sourceVersion ?? note.seedVersion ?? note.sourceRevision,
6389
+ sourceCommit: note.provenance?.sourceCommit ?? note.seedCommit,
6390
+ feedSourceId: note.provenance?.feedSourceId ?? note.feedSourceId,
6391
+ sourceNotebookId: note.provenance?.sourceNotebookId,
6392
+ sourcePath: note.provenance?.sourcePath ?? note.sourcePath,
6393
+ upstreamStatus: status
6394
+ };
6395
+ }
5045
6396
  const upstream = await storage.readonly("notes").get(sourceNoteId);
5046
6397
  if (upstream) {
6398
+ const upstreamGone = upstream.upstreamStatus === "unsubscribed" || upstream.upstreamStatus === "removed";
5047
6399
  return {
5048
- exists: true,
6400
+ exists: !upstreamGone,
5049
6401
  sourceNoteId,
5050
6402
  title: upstream.title,
5051
6403
  sourceVersion: note.provenance?.sourceVersion,
@@ -5053,7 +6405,8 @@ async function resolveUpstreamProvenance(storage, note) {
5053
6405
  sourceCommit: note.provenance?.sourceCommit ?? upstream.seedCommit,
5054
6406
  feedSourceId: note.provenance?.feedSourceId ?? upstream.feedSourceId,
5055
6407
  sourceNotebookId: note.provenance?.sourceNotebookId ?? wodWikiWql.notebookOfItem(upstream),
5056
- sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath
6408
+ sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath,
6409
+ upstreamStatus: upstream.upstreamStatus ?? "live"
5057
6410
  };
5058
6411
  }
5059
6412
  return {
@@ -5063,7 +6416,8 @@ async function resolveUpstreamProvenance(storage, note) {
5063
6416
  sourceCommit: note.provenance?.sourceCommit,
5064
6417
  feedSourceId: note.provenance?.feedSourceId,
5065
6418
  sourceNotebookId: note.provenance?.sourceNotebookId,
5066
- sourcePath: note.provenance?.sourcePath
6419
+ sourcePath: note.provenance?.sourcePath,
6420
+ ...note.upstreamStatus ? { upstreamStatus: note.upstreamStatus } : {}
5067
6421
  };
5068
6422
  }
5069
6423
  function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
@@ -5077,9 +6431,434 @@ function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
5077
6431
  clonedAt
5078
6432
  };
5079
6433
  }
6434
+
6435
+ // src/notebook/schedule.ts
6436
+ function mintUuid2() {
6437
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
6438
+ return crypto.randomUUID();
6439
+ }
6440
+ const bytes = new Uint8Array(16);
6441
+ crypto.getRandomValues(bytes);
6442
+ bytes[6] = bytes[6] & 15 | 64;
6443
+ bytes[8] = bytes[8] & 63 | 128;
6444
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
6445
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
6446
+ }
6447
+ function localCivilDateKey(ms = Date.now(), timeZone) {
6448
+ if (timeZone) {
6449
+ return new Intl.DateTimeFormat("en-CA", {
6450
+ timeZone,
6451
+ year: "numeric",
6452
+ month: "2-digit",
6453
+ day: "2-digit"
6454
+ }).format(new Date(ms));
6455
+ }
6456
+ const d = new Date(ms);
6457
+ const y = d.getFullYear();
6458
+ const m = String(d.getMonth() + 1).padStart(2, "0");
6459
+ const day = String(d.getDate()).padStart(2, "0");
6460
+ return `${y}-${m}-${day}`;
6461
+ }
6462
+ function normalizeCivilDate(input, nowMs = Date.now(), timeZone) {
6463
+ if (!input || input.trim().toLowerCase() === "today") {
6464
+ return localCivilDateKey(nowMs, timeZone);
6465
+ }
6466
+ const trimmed = input.trim();
6467
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
6468
+ throw new Error(`Invalid civil date '${input}'; expected YYYY-MM-DD or 'today'.`);
6469
+ }
6470
+ return trimmed;
6471
+ }
6472
+ function addDaysToCivilDate(dateKey, deltaDays) {
6473
+ const [y, m, d] = dateKey.split("-").map(Number);
6474
+ const dt = new Date(Date.UTC(y, m - 1, d + deltaDays, 12, 0, 0));
6475
+ return `${dt.getUTCFullYear()}-${String(dt.getUTCMonth() + 1).padStart(2, "0")}-${String(dt.getUTCDate()).padStart(2, "0")}`;
6476
+ }
6477
+ function diffDaysCivil(a, b) {
6478
+ const pa = Date.parse(`${a}T12:00:00Z`);
6479
+ const pb = Date.parse(`${b}T12:00:00Z`);
6480
+ return Math.round((pa - pb) / 864e5);
6481
+ }
6482
+ async function getOrCreatePageForDateInTx(tx, dateKey, now) {
6483
+ let existing;
6484
+ try {
6485
+ existing = await tx.readonly("page").getAllFromIndex("by-date", dateKey);
6486
+ } catch {
6487
+ existing = (await tx.readonly("page").getAll()).filter((p) => p.date === dateKey);
6488
+ }
6489
+ if (existing[0]) return existing[0];
6490
+ const created = {
6491
+ id: mintUuid2(),
6492
+ date: dateKey,
6493
+ title: dateKey,
6494
+ createdAt: now
6495
+ };
6496
+ await tx.readwrite("page").put(created);
6497
+ return created;
6498
+ }
6499
+ async function noteHasRecordedSessionsInTx(tx, noteId) {
6500
+ try {
6501
+ const count = await tx.readonly("sessions").countFromIndex("by-note", noteId);
6502
+ if (count > 0) return true;
6503
+ } catch {
6504
+ const all = await tx.readonly("sessions").getAll();
6505
+ return all.some((s) => s.noteId === noteId);
6506
+ }
6507
+ return false;
6508
+ }
6509
+ async function snapshotNoteRevisionIfHasSessionsInTx(tx, previous, now = Date.now()) {
6510
+ if (!previous) return void 0;
6511
+ const hasSessions = await noteHasRecordedSessionsInTx(tx, previous.id);
6512
+ if (!hasSessions) return void 0;
6513
+ const existingRev = await tx.readonly("note_revisions").get([previous.id, previous.sourceRevision]).catch(() => void 0);
6514
+ if (existingRev) return existingRev;
6515
+ const snapshot = {
6516
+ noteId: previous.id,
6517
+ version: previous.sourceRevision,
6518
+ title: previous.title,
6519
+ rawContent: previous.rawContent,
6520
+ ...previous.tags ? { tags: [...previous.tags] } : {},
6521
+ ...previous.type ? { type: previous.type } : {},
6522
+ ...previous.notebookIds ? { notebookIds: [...previous.notebookIds] } : {},
6523
+ blocks: structuredClone(previous.blocks),
6524
+ savedAt: now
6525
+ };
6526
+ await tx.readwrite("note_revisions").put(snapshot);
6527
+ return snapshot;
6528
+ }
6529
+ async function getNoteRevision(storage, noteId, version) {
6530
+ return storage.readonly("note_revisions").get([noteId, version]);
6531
+ }
6532
+ async function listNoteRevisions(storage, noteId) {
6533
+ try {
6534
+ const rows = await storage.readonly("note_revisions").getAllFromIndex("by-note", noteId);
6535
+ return rows.sort((a, b) => b.version - a.version);
6536
+ } catch {
6537
+ const all = await storage.readonly("note_revisions").getAll();
6538
+ return all.filter((r) => r.noteId === noteId).sort((a, b) => b.version - a.version);
6539
+ }
6540
+ }
6541
+ async function scheduleNoteOnDate(storage, input) {
6542
+ const now = input.now ?? Date.now();
6543
+ const dateKey = normalizeCivilDate(input.date, now);
6544
+ const pinned = await ensurePinnedExternalWorkout(storage, {
6545
+ noteId: input.noteId,
6546
+ remotePayload: input.remotePayload,
6547
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
6548
+ retention: "schedule-pinned",
6549
+ now
6550
+ });
6551
+ return storage.transaction(
6552
+ ["schedule_items", "page", "notes"],
6553
+ "readwrite",
6554
+ async (tx) => {
6555
+ const note = await tx.readonly("notes").get(pinned.note.id) ?? pinned.note;
6556
+ const page = await getOrCreatePageForDateInTx(tx, dateKey, now);
6557
+ let existingForDate;
6558
+ try {
6559
+ existingForDate = await tx.readonly("schedule_items").getAllFromIndex("by-date", dateKey);
6560
+ } catch {
6561
+ existingForDate = (await tx.readonly("schedule_items").getAll()).filter((s) => s.date === dateKey);
6562
+ }
6563
+ const nextPos = input.position ?? existingForDate.reduce((max, item2) => Math.max(max, item2.position), -1) + 1;
6564
+ const resolvedNb = input.sourceNotebookId ?? wodWikiWql.notebookOfItem(note) ?? pinned.ownership.sourceNotebookId;
6565
+ const item = {
6566
+ id: input.id ?? mintUuid2(),
6567
+ date: dateKey,
6568
+ noteId: note.id,
6569
+ pageId: page.id,
6570
+ ...resolvedNb ? { sourceNotebookId: wodWikiCore.toNotebookId(resolvedNb) } : {},
6571
+ ...note.title ? { fallbackTitle: note.title } : {},
6572
+ ...input.blockId ? { blockId: input.blockId } : {},
6573
+ position: nextPos,
6574
+ ...input.slot?.trim() ? { slot: input.slot.trim() } : {},
6575
+ status: input.status ?? "planned",
6576
+ ...input.notes !== void 0 && input.notes.trim() ? { notes: input.notes.trim() } : {},
6577
+ createdAt: now,
6578
+ updatedAt: now
6579
+ };
6580
+ await tx.readwrite("schedule_items").put(item);
6581
+ return item;
6582
+ }
6583
+ );
6584
+ }
6585
+ async function batchScheduleNotes(storage, entries) {
6586
+ const created = [];
6587
+ for (const entry of entries) {
6588
+ created.push(await scheduleNoteOnDate(storage, entry));
6589
+ }
6590
+ return created;
6591
+ }
6592
+ async function updateScheduleItem(storage, id, patch) {
6593
+ const now = patch.now ?? Date.now();
6594
+ return storage.transaction(["schedule_items", "page"], "readwrite", async (tx) => {
6595
+ const existing = await tx.readonly("schedule_items").get(id);
6596
+ if (!existing) throw new Error(`ScheduleItem not found: ${id}`);
6597
+ const nextDate = patch.date !== void 0 ? normalizeCivilDate(patch.date, now) : existing.date;
6598
+ let nextPageId = existing.pageId;
6599
+ let movedFromDate = existing.movedFromDate;
6600
+ let nextStatus = patch.status ?? existing.status;
6601
+ if (nextDate !== existing.date) {
6602
+ const page = await getOrCreatePageForDateInTx(tx, nextDate, now);
6603
+ nextPageId = page.id;
6604
+ if (patch.status === void 0 && existing.status === "planned") {
6605
+ movedFromDate = existing.date;
6606
+ } else if (patch.status === "moved") {
6607
+ movedFromDate = existing.date;
6608
+ }
6609
+ }
6610
+ const updated = {
6611
+ ...existing,
6612
+ date: nextDate,
6613
+ ...nextPageId ? { pageId: nextPageId } : {},
6614
+ position: patch.position ?? existing.position,
6615
+ status: nextStatus,
6616
+ ...movedFromDate ? { movedFromDate } : {},
6617
+ updatedAt: now
6618
+ };
6619
+ if (patch.slot === null) delete updated.slot;
6620
+ else if (patch.slot !== void 0) updated.slot = patch.slot.trim() || void 0;
6621
+ if (patch.notes === null) delete updated.notes;
6622
+ else if (patch.notes !== void 0) updated.notes = patch.notes.trim() || void 0;
6623
+ if (patch.blockId === null) delete updated.blockId;
6624
+ else if (patch.blockId !== void 0) updated.blockId = patch.blockId.trim() || void 0;
6625
+ await tx.readwrite("schedule_items").put(updated);
6626
+ return updated;
6627
+ });
6628
+ }
6629
+ async function removeScheduleItem(storage, id) {
6630
+ return storage.transaction(["schedule_items"], "readwrite", async (tx) => {
6631
+ const existing = await tx.readonly("schedule_items").get(id);
6632
+ if (!existing) return false;
6633
+ await tx.readwrite("schedule_items").delete(id);
6634
+ return true;
6635
+ });
6636
+ }
6637
+ async function listScheduleItemsByDateRange(storage, fromDate, toDate) {
6638
+ const fromKey = normalizeCivilDate(fromDate);
6639
+ const toKey = normalizeCivilDate(toDate);
6640
+ let rows;
6641
+ try {
6642
+ rows = await storage.readonly("schedule_items").getAll();
6643
+ } catch {
6644
+ rows = [];
6645
+ }
6646
+ 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);
6647
+ }
6648
+ async function listScheduleItemsForNote(storage, noteId) {
6649
+ let rows;
6650
+ try {
6651
+ rows = await storage.readonly("schedule_items").getAllFromIndex("by-note", noteId);
6652
+ } catch {
6653
+ rows = (await storage.readonly("schedule_items").getAll()).filter((item) => item.noteId === noteId);
6654
+ }
6655
+ return rows.sort((a, b) => a.date.localeCompare(b.date) || a.position - b.position);
6656
+ }
6657
+ async function getScheduleAndSessionCountsByNote(storage) {
6658
+ const [schedules, sessions] = await Promise.all([
6659
+ storage.readonly("schedule_items").getAll().catch(() => []),
6660
+ storage.readonly("sessions").getAll().catch(() => [])
6661
+ ]);
6662
+ const counts = /* @__PURE__ */ new Map();
6663
+ const ensure = (noteId) => {
6664
+ let entry = counts.get(noteId);
6665
+ if (!entry) {
6666
+ entry = { scheduleCount: 0, sessionCount: 0, scheduledDates: [] };
6667
+ counts.set(noteId, entry);
6668
+ }
6669
+ return entry;
6670
+ };
6671
+ for (const s of schedules) {
6672
+ if (s.status === "skipped") continue;
6673
+ const entry = ensure(s.noteId);
6674
+ entry.scheduleCount += 1;
6675
+ if (!entry.scheduledDates.includes(s.date)) entry.scheduledDates.push(s.date);
6676
+ }
6677
+ for (const sess of sessions) {
6678
+ const entry = ensure(sess.noteId);
6679
+ entry.sessionCount += 1;
6680
+ }
6681
+ for (const entry of counts.values()) {
6682
+ entry.scheduledDates.sort();
6683
+ }
6684
+ return counts;
6685
+ }
6686
+ async function attributeSession(storage, input) {
6687
+ const now = input.now ?? Date.now();
6688
+ return storage.transaction(["sessions", "schedule_items", "page"], "readwrite", async (tx) => {
6689
+ const session = await tx.readonly("sessions").get(input.sessionId);
6690
+ if (!session) throw new Error(`Session not found: ${input.sessionId}`);
6691
+ let nextSessionDate = session.sessionDate;
6692
+ let nextPageId = session.pageId;
6693
+ let nextScheduleItemId = session.scheduleItemId;
6694
+ if (input.scheduleItemId === null) {
6695
+ if (session.scheduleItemId) {
6696
+ const prevItem = await tx.readonly("schedule_items").get(session.scheduleItemId);
6697
+ if (prevItem && prevItem.status === "completed") {
6698
+ await tx.readwrite("schedule_items").put({
6699
+ ...prevItem,
6700
+ status: "planned",
6701
+ updatedAt: now
6702
+ });
6703
+ }
6704
+ }
6705
+ nextScheduleItemId = void 0;
6706
+ } else if (input.scheduleItemId !== void 0) {
6707
+ const targetItem = await tx.readonly("schedule_items").get(input.scheduleItemId);
6708
+ if (!targetItem) throw new Error(`ScheduleItem not found: ${input.scheduleItemId}`);
6709
+ if (session.scheduleItemId && session.scheduleItemId !== targetItem.id) {
6710
+ const prevItem = await tx.readonly("schedule_items").get(session.scheduleItemId);
6711
+ if (prevItem && prevItem.status === "completed") {
6712
+ await tx.readwrite("schedule_items").put({
6713
+ ...prevItem,
6714
+ status: "planned",
6715
+ updatedAt: now
6716
+ });
6717
+ }
6718
+ }
6719
+ nextScheduleItemId = targetItem.id;
6720
+ if (input.sessionDate === void 0) {
6721
+ nextSessionDate = targetItem.date;
6722
+ }
6723
+ if (targetItem.status !== "completed") {
6724
+ await tx.readwrite("schedule_items").put({
6725
+ ...targetItem,
6726
+ status: "completed",
6727
+ updatedAt: now
6728
+ });
6729
+ }
6730
+ }
6731
+ if (input.sessionDate !== void 0) {
6732
+ nextSessionDate = normalizeCivilDate(input.sessionDate, now);
6733
+ }
6734
+ if (nextSessionDate) {
6735
+ const page = await getOrCreatePageForDateInTx(tx, nextSessionDate, now);
6736
+ nextPageId = page.id;
6737
+ }
6738
+ const updated = {
6739
+ ...session,
6740
+ ...nextPageId !== void 0 ? { pageId: nextPageId } : {},
6741
+ ...nextSessionDate !== void 0 ? { sessionDate: nextSessionDate } : {}
6742
+ };
6743
+ if (nextScheduleItemId !== void 0) updated.scheduleItemId = nextScheduleItemId;
6744
+ else delete updated.scheduleItemId;
6745
+ await tx.readwrite("sessions").put(updated);
6746
+ return updated;
6747
+ });
6748
+ }
6749
+ async function findNearbyMatchingScheduleItems(storage, session, windowDays = 2) {
6750
+ if (session.scheduleItemId) return [];
6751
+ const baseDate = session.sessionDate ?? localCivilDateKey(session.startTime);
6752
+ const fromDate = addDaysToCivilDate(baseDate, -windowDays);
6753
+ const toDate = addDaysToCivilDate(baseDate, windowDays);
6754
+ const candidates = await listScheduleItemsForNote(storage, session.noteId);
6755
+ return candidates.filter((item) => item.status === "planned" && item.date >= fromDate && item.date <= toDate).sort((a, b) => Math.abs(diffDaysCivil(a.date, baseDate)) - Math.abs(diffDaysCivil(b.date, baseDate)) || a.date.localeCompare(b.date));
6756
+ }
6757
+ function resolveSessionCivilDate(session, pageDateById, sessionPageId) {
6758
+ if (session.sessionDate) return session.sessionDate;
6759
+ if (sessionPageId && pageDateById?.has(sessionPageId)) {
6760
+ return pageDateById.get(sessionPageId);
6761
+ }
6762
+ return localCivilDateKey(session.startTime || session.createdAt);
6763
+ }
6764
+ async function getJournalDayOverlay(storage, rawDate) {
6765
+ const dateKey = normalizeCivilDate(rawDate);
6766
+ const [pages, daySchedules, allSessions, allNotes] = await Promise.all([
6767
+ storage.readonly("page").getAll().catch(() => []),
6768
+ listScheduleItemsByDateRange(storage, dateKey, dateKey),
6769
+ storage.readonly("sessions").getAll().catch(() => []),
6770
+ storage.readonly("notes").getAll().catch(() => [])
6771
+ ]);
6772
+ const pageDateById = /* @__PURE__ */ new Map();
6773
+ let pageId = null;
6774
+ for (const p of pages) {
6775
+ if (p.date) {
6776
+ pageDateById.set(p.id, p.date);
6777
+ if (p.date === dateKey && !pageId) pageId = p.id;
6778
+ }
6779
+ }
6780
+ const notesById = new Map(allNotes.map((n) => [n.id, n]));
6781
+ const daySessions = allSessions.filter((s) => resolveSessionCivilDate(s, pageDateById, s.pageId) === dateKey).sort((a, b) => a.startTime - b.startTime);
6782
+ const pairedByScheduleId = /* @__PURE__ */ new Map();
6783
+ const pairedSessionIds = /* @__PURE__ */ new Set();
6784
+ for (const s of daySessions) {
6785
+ if (!s.scheduleItemId) continue;
6786
+ const match = daySchedules.find((item) => item.id === s.scheduleItemId);
6787
+ if (match) {
6788
+ const bucket = pairedByScheduleId.get(match.id) ?? [];
6789
+ bucket.push(s);
6790
+ pairedByScheduleId.set(match.id, bucket);
6791
+ pairedSessionIds.add(s.id);
6792
+ }
6793
+ }
6794
+ const planned = daySchedules.map((item) => ({
6795
+ item,
6796
+ note: notesById.get(item.noteId),
6797
+ pairedSessions: pairedByScheduleId.get(item.id) ?? []
6798
+ }));
6799
+ const adhocSessions = daySessions.filter((s) => !pairedSessionIds.has(s.id)).map((session) => ({
6800
+ session,
6801
+ note: notesById.get(session.noteId)
6802
+ }));
6803
+ return {
6804
+ date: dateKey,
6805
+ pageId,
6806
+ planned,
6807
+ adhocSessions,
6808
+ allSessions: daySessions
6809
+ };
6810
+ }
6811
+ async function migrateDatedPageNotesToSchedule(storage) {
6812
+ return storage.transaction(["page", "page_notes", "schedule_items", "notes"], "readwrite", async (tx) => {
6813
+ const [pages, pageNotes, existingSchedules, notes] = await Promise.all([
6814
+ tx.readonly("page").getAll(),
6815
+ tx.readonly("page_notes").getAll(),
6816
+ tx.readonly("schedule_items").getAll(),
6817
+ tx.readonly("notes").getAll()
6818
+ ]);
6819
+ const dateByPage = /* @__PURE__ */ new Map();
6820
+ for (const p of pages) {
6821
+ if (p.date) dateByPage.set(p.id, p.date);
6822
+ }
6823
+ const existingIds = new Set(existingSchedules.map((s) => s.id));
6824
+ const notesById = new Map(notes.map((n) => [n.id, n]));
6825
+ const toCreate = [];
6826
+ for (const pn of pageNotes) {
6827
+ const date = dateByPage.get(pn.pageId);
6828
+ if (!date) continue;
6829
+ const deterministicId = `sched-${pn.id}`;
6830
+ if (existingIds.has(deterministicId)) continue;
6831
+ const alreadySameNoteOnDate = existingSchedules.some(
6832
+ (s) => s.date === date && s.noteId === pn.noteId && s.pageId === pn.pageId
6833
+ );
6834
+ if (alreadySameNoteOnDate) continue;
6835
+ const note = notesById.get(pn.noteId);
6836
+ const createdAt = pn.createdAt ?? Date.now();
6837
+ const ownership = note ? wodWikiCore.resolveNoteOwnership(note, wodWikiWql.notebookOriginOfItem(note), wodWikiWql.notebookOfItem(note)) : void 0;
6838
+ const resolvedNb = note ? wodWikiWql.notebookOfItem(note) ?? ownership?.sourceNotebookId : void 0;
6839
+ toCreate.push({
6840
+ id: deterministicId,
6841
+ date,
6842
+ noteId: pn.noteId,
6843
+ pageId: pn.pageId,
6844
+ ...resolvedNb ? { sourceNotebookId: resolvedNb } : {},
6845
+ ...note?.title ? { fallbackTitle: note.title } : {},
6846
+ position: pn.position ?? 0,
6847
+ status: "planned",
6848
+ createdAt,
6849
+ updatedAt: createdAt
6850
+ });
6851
+ }
6852
+ if (toCreate.length > 0) {
6853
+ await tx.readwrite("schedule_items").putMany(toCreate);
6854
+ }
6855
+ return toCreate.length;
6856
+ });
6857
+ }
5080
6858
  var PERSIST_WORLD_STORES = [
5081
6859
  "notes",
5082
6860
  "block_revisions",
6861
+ "note_revisions",
5083
6862
  "block_index",
5084
6863
  "block_efforts",
5085
6864
  "block_equipment",
@@ -5092,6 +6871,7 @@ var PERSIST_WORLD_STORES = [
5092
6871
  "equipment",
5093
6872
  "page",
5094
6873
  "page_notes",
6874
+ "schedule_items",
5095
6875
  "sessions",
5096
6876
  "events"
5097
6877
  ];
@@ -5113,6 +6893,7 @@ async function persistDomainWorld(storage, worldInput) {
5113
6893
  }
5114
6894
  if (world.notes.length) await tx.readwrite("notes").putMany(world.notes);
5115
6895
  if (world.revisions.length) await tx.readwrite("block_revisions").putMany(world.revisions);
6896
+ if (world.noteRevisions?.length) await tx.readwrite("note_revisions").putMany(world.noteRevisions);
5116
6897
  if (world.blockIndex.length) await tx.readwrite("block_index").putMany(world.blockIndex);
5117
6898
  if (world.blockEfforts.length) await tx.readwrite("block_efforts").putMany(world.blockEfforts);
5118
6899
  if (world.blockEquipment.length) await tx.readwrite("block_equipment").putMany(world.blockEquipment);
@@ -5162,6 +6943,7 @@ async function persistDomainWorld(storage, worldInput) {
5162
6943
  }
5163
6944
  if (world.pages.length) await tx.readwrite("page").putMany(world.pages);
5164
6945
  if (world.pageNotes.length) await tx.readwrite("page_notes").putMany(world.pageNotes);
6946
+ if (world.scheduleItems?.length) await tx.readwrite("schedule_items").putMany(world.scheduleItems);
5165
6947
  if (world.sessions.length) await tx.readwrite("sessions").putMany(world.sessions);
5166
6948
  if (world.events.length) await tx.readwrite("events").putMany(world.events);
5167
6949
  });
@@ -5457,8 +7239,8 @@ function buildSessionLogs(session) {
5457
7239
  const monotony = round1(1.1 + dayPhase(4) * 0.7);
5458
7240
  const acwr = round1(0.85 + dayPhase(5) * 0.4);
5459
7241
  push("Readiness", readiness, "pts", "calc.readiness", { intensityTier: sessionIntensity });
5460
- push("HRV", hrvMs, "pts", "calc.hrv", { intensityTier: sessionIntensity });
5461
- push("Sleep", sleepHours, "pts", "calc.sleep", { intensityTier: sessionIntensity });
7242
+ push("HRV", hrvMs, "ms", "calc.hrv", { intensityTier: sessionIntensity });
7243
+ push("Sleep", sleepHours, "h", "calc.sleep", { intensityTier: sessionIntensity });
5462
7244
  push("Soreness", soreness, "rating", "calc.soreness", { intensityTier: sessionIntensity });
5463
7245
  push("Monotony", monotony, "ratio", "calc.monotony", { intensityTier: sessionIntensity });
5464
7246
  push("ACWR", acwr, "ratio", "calc.acwr", { intensityTier: sessionIntensity });
@@ -6693,6 +8475,8 @@ exports.DASHBOARDS_CHUNK_ID = DASHBOARDS_CHUNK_ID;
6693
8475
  exports.DirectoryHandleFeedTree = DirectoryHandleFeedTree;
6694
8476
  exports.EFFORTS_CHUNK_ID = EFFORTS_CHUNK_ID;
6695
8477
  exports.EQUIPMENT_CHUNK_ID = EQUIPMENT_CHUNK_ID;
8478
+ exports.FEED_INDEX_META_PREFIX = FEED_INDEX_META_PREFIX;
8479
+ exports.FEED_REGISTRY_META_KEY = FEED_REGISTRY_META_KEY;
6696
8480
  exports.FEED_SUBSCRIPTIONS_META_KEY = FEED_SUBSCRIPTIONS_META_KEY;
6697
8481
  exports.FeedTreeError = FeedTreeError;
6698
8482
  exports.GIT_SHA = GIT_SHA;
@@ -6717,7 +8501,9 @@ exports.assertNotebookIndex = assertNotebookIndex;
6717
8501
  exports.assertSeedManifest = assertSeedManifest;
6718
8502
  exports.assertSeedRow = assertSeedRow;
6719
8503
  exports.assertSeedRows = assertSeedRows;
8504
+ exports.attributeSession = attributeSession;
6720
8505
  exports.backfillFeedProvenance = backfillFeedProvenance;
8506
+ exports.batchScheduleNotes = batchScheduleNotes;
6721
8507
  exports.buildContextualPageSource = buildContextualPageSource;
6722
8508
  exports.buildNoteProvenance = buildNoteProvenance;
6723
8509
  exports.buildQueryServiceStoresFromStorage = buildQueryServiceStoresFromStorage;
@@ -6728,6 +8514,7 @@ exports.buildStatementTree = buildStatementTree;
6728
8514
  exports.canvasRouteSlug = canvasRouteSlug;
6729
8515
  exports.checkUnpublishedFeedChanges = checkUnpublishedFeedChanges;
6730
8516
  exports.cloneRemoteRecord = cloneRemoteRecord;
8517
+ exports.compileSeedRowFromMarkdown = compileSeedRowFromMarkdown;
6731
8518
  exports.composeNoteMarkdown = composeNoteMarkdown;
6732
8519
  exports.createIRFile = createIRFile;
6733
8520
  exports.createUserNotebookLanding = createUserNotebookLanding;
@@ -6737,34 +8524,52 @@ exports.csvToTelemetryBundle = csvToTelemetryBundle;
6737
8524
  exports.decodeUtf8 = decodeUtf8;
6738
8525
  exports.defineLanguagePack = defineLanguagePack;
6739
8526
  exports.deleteFeedSourceHeadless = deleteFeedSourceHeadless;
8527
+ exports.deleteUserNotebook = deleteUserNotebook;
6740
8528
  exports.effortToMarkdown = effortToMarkdown;
6741
8529
  exports.emptySeedMeta = emptySeedMeta;
6742
8530
  exports.encodeUtf8 = encodeUtf8;
8531
+ exports.ensurePinnedExternalWorkout = ensurePinnedExternalWorkout;
6743
8532
  exports.equipmentToCsv = equipmentToCsv;
6744
8533
  exports.equipmentToMarkdown = equipmentToMarkdown;
6745
8534
  exports.exportPortableFilesFromStorage = exportPortableFilesFromStorage;
6746
8535
  exports.extractNoteIdentity = extractNoteIdentity;
6747
8536
  exports.extractTypedTags = extractTypedTags;
6748
8537
  exports.feedIdOfMetaKey = feedIdOfMetaKey;
8538
+ exports.feedIndexMetaKey = feedIndexMetaKey;
8539
+ exports.findNearbyMatchingScheduleItems = findNearbyMatchingScheduleItems;
8540
+ exports.forkNoteToUserNotebook = forkNoteToUserNotebook;
6749
8541
  exports.generateSampleSessions = generateSampleSessions;
8542
+ exports.getJournalDayOverlay = getJournalDayOverlay;
6750
8543
  exports.getNoteNotebooks = getNoteNotebooks;
6751
8544
  exports.getNotePublicationSummary = getNotePublicationSummary;
8545
+ exports.getNoteRevision = getNoteRevision;
6752
8546
  exports.getRegisteredLanguagePacks = getRegisteredLanguagePacks;
8547
+ exports.getScheduleAndSessionCountsByNote = getScheduleAndSessionCountsByNote;
6753
8548
  exports.inMemoryEventStore = inMemoryEventStore;
6754
8549
  exports.ingestPortableFilesIntoStorage = ingestPortableFilesIntoStorage;
6755
8550
  exports.injectIdentityFrontmatter = injectIdentityFrontmatter;
6756
8551
  exports.isIRFile = isIRFile;
6757
8552
  exports.listFeedSubscriptionsHeadless = listFeedSubscriptionsHeadless;
6758
8553
  exports.listLanguagePacks = listLanguagePacks;
8554
+ exports.listNoteRevisions = listNoteRevisions;
8555
+ exports.listScheduleItemsByDateRange = listScheduleItemsByDateRange;
8556
+ exports.listScheduleItemsForNote = listScheduleItemsForNote;
6759
8557
  exports.listScopedPropertyOverrides = listScopedPropertyOverrides;
8558
+ exports.localCivilDateKey = localCivilDateKey;
8559
+ exports.logSessionAgainstExternalWorkout = logSessionAgainstExternalWorkout;
6760
8560
  exports.makeNotebookLinkId = makeNotebookLinkId;
6761
8561
  exports.makeScopedOverrideId = makeScopedOverrideId;
8562
+ exports.materializeCachedRemoteRecord = materializeCachedRemoteRecord;
8563
+ exports.migrateDatedPageNotesToSchedule = migrateDatedPageNotesToSchedule;
6762
8564
  exports.migrateNotebookVocabulary = migrateNotebookVocabulary;
8565
+ exports.normalizeCivilDate = normalizeCivilDate;
6763
8566
  exports.normalizeFeedTreePath = normalizeFeedTreePath;
8567
+ exports.noteHasRecordedSessionsInTx = noteHasRecordedSessionsInTx;
6764
8568
  exports.notebookSlugForChunkId = notebookSlugForChunkId;
6765
8569
  exports.parseCsvLine = parseCsvLine;
6766
8570
  exports.parseFrontmatterDateMs = parseFrontmatterDateMs;
6767
8571
  exports.parseNoteMarkdown = parseNoteMarkdown;
8572
+ exports.parseRemoteNoteId = parseRemoteNoteId;
6768
8573
  exports.persistDomainWorld = persistDomainWorld;
6769
8574
  exports.prepareJournalSessionRun = prepareJournalSessionRun;
6770
8575
  exports.previewRemoteNotebook = previewRemoteNotebook;
@@ -6773,16 +8578,23 @@ exports.promoteNoteToNotebooks = promoteNoteToNotebooks;
6773
8578
  exports.promoteReferencedOverridesToNotebook = promoteReferencedOverridesToNotebook;
6774
8579
  exports.publishFeedFromStorage = publishFeedFromStorage;
6775
8580
  exports.qrInlineScript = qrInlineScript;
8581
+ exports.readFeedRegistryHeadless = readFeedRegistryHeadless;
6776
8582
  exports.readFrontmatterMeta = readFrontmatterMeta;
8583
+ exports.reconcileRemovedFeedRecords = reconcileRemovedFeedRecords;
6777
8584
  exports.recordPublishedFeedCheckpoint = recordPublishedFeedCheckpoint;
6778
8585
  exports.registerLanguagePack = registerLanguagePack;
8586
+ exports.removeFeedNotebookContent = removeFeedNotebookContent;
8587
+ exports.removeFeedSourceContentById = removeFeedSourceContentById;
6779
8588
  exports.removeNoteFromNotebook = removeNoteFromNotebook;
8589
+ exports.removeScheduleItem = removeScheduleItem;
6780
8590
  exports.removeSeedSourceContent = removeSeedSourceContent;
6781
8591
  exports.renderFeedLandingHtml = renderFeedLandingHtml;
6782
8592
  exports.resolveScopedPropertyCatalog = resolveScopedPropertyCatalog;
8593
+ exports.resolveSessionCivilDate = resolveSessionCivilDate;
6783
8594
  exports.resolveUpstreamProvenance = resolveUpstreamProvenance;
6784
8595
  exports.round1 = round1;
6785
8596
  exports.saveScopedPropertyOverride = saveScopedPropertyOverride;
8597
+ exports.scheduleNoteOnDate = scheduleNoteOnDate;
6786
8598
  exports.seedMetaKey = seedMetaKey;
6787
8599
  exports.seedNoteId = seedNoteId;
6788
8600
  exports.seedNoteSourceId = seedNoteSourceId;
@@ -6793,12 +8605,15 @@ exports.setNoteNotebooks = setNoteNotebooks;
6793
8605
  exports.setNotebookPublic = setNotebookPublic;
6794
8606
  exports.setSessionPublic = setSessionPublic;
6795
8607
  exports.sha256HexAsync = sha256HexAsync;
8608
+ exports.snapshotNoteRevisionIfHasSessionsInTx = snapshotNoteRevisionIfHasSessionsInTx;
6796
8609
  exports.splitCsvRecords = splitCsvRecords;
6797
8610
  exports.statementToNode = statementToNode;
6798
8611
  exports.subscribeFeedSourceHeadless = subscribeFeedSourceHeadless;
6799
8612
  exports.telemetryBundleToCsv = telemetryBundleToCsv;
6800
8613
  exports.unregisterLanguagePack = unregisterLanguagePack;
6801
8614
  exports.unsubscribeFeedSourceHeadless = unsubscribeFeedSourceHeadless;
8615
+ exports.updateScheduleItem = updateScheduleItem;
8616
+ exports.writeFeedRegistryHeadless = writeFeedRegistryHeadless;
6802
8617
  Object.keys(wodWikiCore).forEach(function (k) {
6803
8618
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6804
8619
  enumerable: true,