@bitcobblers/wod-wiki-engine 0.60.2258 → 0.62.2260

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- import { KNOWN_SECTION_WIDGETS, MetricType, reconcileNoteBlocks, validateNoteBlocks, parseDocumentSections, blockContentId, toNotebookId as toNotebookId$1, isSystemReadOnlyNotebook, notebookSlugFromId as notebookSlugFromId$1, patchFrontmatterProperty, createTagIndex, isNonPublishableNotebook, serializeNoteBundleToJsonl, derivePublicationVisibility, isPublishableNotebookLanding, parseNoteBundleFromJsonl, isNoteEditable, mapNoteBlockChanges } from '@bitcobblers/wod-wiki-core';
2
- import { getHints, documentToEffort, documentToEquipment, documentToTag, createReferenceIndex, parseEffortFile, parseEquipmentFile, bundledEfforts, parseScript, extractStatementRefs } from '@bitcobblers/wod-wiki-lang';
1
+ import { BUILTIN_NOTEBOOKS, KNOWN_SECTION_WIDGETS, MetricType, reconcileNoteBlocks, validateNoteBlocks, parseDocumentSections, blockContentId, toNotebookId as toNotebookId$1, isSystemReadOnlyNotebook, notebookSlugFromId as notebookSlugFromId$1, patchFrontmatterProperty, createTagIndex, isNonPublishableNotebook, serializeNoteBundleToJsonl, derivePublicationVisibility, isPublishableNotebookLanding, parseNoteBundleFromJsonl, isNotebookLanding, resolveNoteOwnership, mapNoteBlockChanges } from '@bitcobblers/wod-wiki-core';
2
+ import { getHints, documentToEffort, documentToEquipment, documentToTag, createReferenceIndex, parseEffortFile, parseEquipmentFile, parseScript, extractStatementRefs, bundledEfforts } from '@bitcobblers/wod-wiki-lang';
3
3
  import { WQL_TYPED_TAG_KEYS, notebookSlugFromId, toNotebookId, migrateLegacyChunkId, hasLegacyIdentity, migrateLegacyRow, coalescingEventStore, notebooksOfItem, notebookOfItem, notebookOriginOfItem, notebookSlugOfSourceId } from '@bitcobblers/wod-wiki-wql';
4
- import { userDeletedSeedNoteId } from '@bitcobblers/wod-wiki-storage';
4
+ import { userDeletedSeedNoteId, userDeletedSeedKey } from '@bitcobblers/wod-wiki-storage';
5
5
 
6
6
  // src/ir.ts
7
7
  function createIRFile(kind, data, optionsOrSource, generatedAt) {
@@ -858,13 +858,13 @@ function csvToTelemetryBundle(csv) {
858
858
  }
859
859
 
860
860
  // src/version.ts
861
- var VERSION = "0.60.2258";
862
- var GIT_SHA = "d5f50d9";
863
- var BUILD_TIME = "2026-11-20T19:08:09.031Z";
861
+ var VERSION = "0.62.2260";
862
+ var GIT_SHA = "d3581b3";
863
+ var BUILD_TIME = "2026-11-23T01:01:07.332Z";
864
864
  var SEMVER = {
865
- version: "0.60.2258",
866
- gitSha: "d5f50d9",
867
- buildTime: "2026-11-20T19:08:09.031Z"
865
+ version: "0.62.2260",
866
+ gitSha: "d3581b3",
867
+ buildTime: "2026-11-23T01:01:07.332Z"
868
868
  };
869
869
  var SEED_SCHEMA = 9;
870
870
  var SEED_REGISTERED_WIDGETS = KNOWN_SECTION_WIDGETS;
@@ -888,6 +888,10 @@ function seedPrecedenceRank(sourceIdOrMetaKey, explicitTier) {
888
888
  return SEED_PRECEDENCE_RANK[seedSourceTier(sourceIdOrMetaKey, explicitTier)];
889
889
  }
890
890
  var SEED_BROADCAST_CHANNEL = "wodwiki.seed";
891
+ var FEED_INDEX_META_PREFIX = "feed:index:";
892
+ function feedIndexMetaKey(feedId, notebookId) {
893
+ return `${FEED_INDEX_META_PREFIX}${feedId}:${notebookId}`;
894
+ }
891
895
  var EFFORTS_CHUNK_ID = "efforts";
892
896
  var EQUIPMENT_CHUNK_ID = "equipment";
893
897
  var CANVAS_CHUNK_ID = "canvas";
@@ -936,42 +940,149 @@ function nonnegative(value) {
936
940
  function finite(value) {
937
941
  return typeof value === "number" && Number.isFinite(value);
938
942
  }
943
+ function isSafeRelativePath(value) {
944
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split("/").includes("..");
945
+ }
946
+ function isSafeRawUrlOrPath(value) {
947
+ if (typeof value !== "string" || !value.trim()) return false;
948
+ if (/^https?:\/\//i.test(value)) {
949
+ try {
950
+ const parsed = new URL(value);
951
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && !parsed.username && !parsed.password;
952
+ } catch {
953
+ return false;
954
+ }
955
+ }
956
+ return isSafeRelativePath(value);
957
+ }
939
958
  function assertSeedManifest(value) {
940
- if (!object(value) || value.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; rebuild seed artifacts");
941
- 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");
942
- for (const key of ["versionLabel", "commit", "name", "description"]) if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
943
- 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");
959
+ if (!object(value)) throw new Error("Incompatible seed schema; rebuild seed artifacts");
960
+ const hasNotebooks = Array.isArray(value.notebooks);
961
+ if (value.schema === void 0) {
962
+ if (!hasNotebooks) throw new Error("Incompatible seed schema; rebuild seed artifacts");
963
+ } else if (!positive(value.schema) || value.schema !== SEED_SCHEMA && !hasNotebooks) {
964
+ throw new Error("Incompatible seed schema; rebuild seed artifacts");
965
+ }
966
+ const normalizedSchema = value.schema === void 0 ? SEED_SCHEMA : value.schema;
967
+ const normalizedVersion = value.version === void 0 && hasNotebooks ? 1 : value.version;
968
+ const normalizedBuiltAt = value.builtAt === void 0 && hasNotebooks ? (/* @__PURE__ */ new Date(0)).toISOString() : value.builtAt;
969
+ const normalizedChunks = value.chunks === void 0 && hasNotebooks ? [] : value.chunks;
970
+ if (!nonnegative(normalizedVersion) || typeof normalizedBuiltAt !== "string" || !Number.isFinite(Date.parse(normalizedBuiltAt)) || !Array.isArray(normalizedChunks)) {
971
+ throw new Error("seed manifest failed shape validation");
972
+ }
973
+ for (const key of ["versionLabel", "commit", "name", "description"]) {
974
+ if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
975
+ }
976
+ if (value.repositoryUrl !== void 0 && (typeof value.repositoryUrl !== "string" || !/^https:\/\//.test(value.repositoryUrl) || new URL(value.repositoryUrl).username || new URL(value.repositoryUrl).password)) {
977
+ throw new Error("invalid seed repository URL");
978
+ }
944
979
  if (value.dirty !== void 0 && typeof value.dirty !== "boolean") throw new Error("invalid seed manifest metadata");
980
+ for (const key of ["indexBytes", "chunkBytes"]) {
981
+ if (value[key] !== void 0 && !nonnegative(value[key])) throw new Error("invalid seed manifest metadata");
982
+ }
945
983
  const ids = /* @__PURE__ */ new Set(), paths = /* @__PURE__ */ new Set();
946
- for (const chunk of value.chunks) {
947
- 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");
984
+ for (const chunk of normalizedChunks) {
985
+ 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)) {
986
+ throw new Error("seed manifest failed shape validation");
987
+ }
948
988
  ids.add(chunk.id);
949
989
  paths.add(chunk.path);
950
990
  }
991
+ let normalizedNotebooks;
951
992
  if (value.notebooks !== void 0) {
952
993
  if (!Array.isArray(value.notebooks)) throw new Error("seed manifest failed shape validation");
994
+ normalizedNotebooks = [];
953
995
  for (const nb of value.notebooks) {
954
- 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)) {
996
+ if (!object(nb) || typeof nb.notebookId !== "string" || !nb.notebookId || typeof nb.label !== "string" || !nonnegative(nb.count) || !isSafeRawUrlOrPath(nb.indexPath)) {
955
997
  throw new Error("seed manifest failed shape validation");
956
998
  }
957
999
  if ("records" in nb && Array.isArray(nb.records)) {
958
1000
  throw new Error("seed manifest failed shape validation: manifest.notebooks must not contain inline records");
959
1001
  }
1002
+ if (nb.version !== void 0 && !nonnegative(nb.version)) throw new Error("seed manifest failed shape validation");
1003
+ if (nb.commit !== void 0 && typeof nb.commit !== "string") throw new Error("seed manifest failed shape validation");
1004
+ if (nb.builtAt !== void 0 && typeof nb.builtAt !== "string") throw new Error("seed manifest failed shape validation");
1005
+ if (nb.sha256 !== void 0 && typeof nb.sha256 !== "string") throw new Error("seed manifest failed shape validation");
1006
+ if (nb.bytes !== void 0 && !nonnegative(nb.bytes)) throw new Error("seed manifest failed shape validation");
1007
+ if (nb.indexBytes !== void 0 && !nonnegative(nb.indexBytes)) throw new Error("seed manifest failed shape validation");
1008
+ if (nb.chunkBytes !== void 0 && !nonnegative(nb.chunkBytes)) throw new Error("seed manifest failed shape validation");
1009
+ normalizedNotebooks.push({
1010
+ ...nb,
1011
+ version: nb.version ?? normalizedVersion,
1012
+ commit: nb.commit ?? "",
1013
+ builtAt: nb.builtAt ?? normalizedBuiltAt,
1014
+ sha256: nb.sha256 ?? "",
1015
+ bytes: nb.bytes ?? nb.indexBytes ?? 0
1016
+ });
960
1017
  }
961
1018
  }
962
- return value;
1019
+ return {
1020
+ ...value,
1021
+ schema: normalizedSchema,
1022
+ version: normalizedVersion,
1023
+ builtAt: normalizedBuiltAt,
1024
+ chunks: normalizedChunks,
1025
+ ...normalizedNotebooks !== void 0 ? { notebooks: normalizedNotebooks } : {}
1026
+ };
963
1027
  }
964
1028
  function assertNotebookIndex(value) {
965
1029
  if (!object(value)) throw new Error("notebook index failed shape validation");
966
- 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)) {
1030
+ if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || !value.label || !isSafeRawUrlOrPath(value.indexPath) || !nonnegative(value.count) || !Array.isArray(value.records)) {
967
1031
  throw new Error("notebook index failed shape validation: missing required index summary or records");
968
1032
  }
1033
+ if (value.version !== void 0 && !nonnegative(value.version)) throw new Error("notebook index failed shape validation: missing required index summary or records");
1034
+ if (value.commit !== void 0 && typeof value.commit !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
1035
+ if (value.builtAt !== void 0 && typeof value.builtAt !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
1036
+ if (value.sha256 !== void 0 && typeof value.sha256 !== "string") throw new Error("notebook index failed shape validation: missing required index summary or records");
1037
+ if (value.bytes !== void 0 && !nonnegative(value.bytes)) throw new Error("notebook index failed shape validation: missing required index summary or records");
1038
+ const normalizedRecords = [];
969
1039
  for (const r of value.records) {
970
- 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") {
1040
+ if (!object(r) || typeof r.uuid !== "string" || !r.uuid || !isSafeRelativePath(r.path)) {
1041
+ throw new Error("notebook index failed shape validation: invalid record ref");
1042
+ }
1043
+ const hasRecordPath = r.recordPath !== void 0;
1044
+ const hasRawUrl = r.rawUrl !== void 0;
1045
+ const hasMdPath = /\.md$/i.test(r.path);
1046
+ if (hasRecordPath && !isSafeRelativePath(r.recordPath)) {
971
1047
  throw new Error("notebook index failed shape validation: invalid record ref");
972
1048
  }
1049
+ if (hasRawUrl && !isSafeRawUrlOrPath(r.rawUrl)) {
1050
+ throw new Error("notebook index failed shape validation: invalid record ref");
1051
+ }
1052
+ if (!hasRecordPath && !hasRawUrl && !hasMdPath) {
1053
+ throw new Error("notebook index failed shape validation: invalid record ref");
1054
+ }
1055
+ if (r.commit !== void 0 && typeof r.commit !== "string") {
1056
+ throw new Error("notebook index failed shape validation: invalid record ref");
1057
+ }
1058
+ if (r.version !== void 0 && !nonnegative(r.version)) {
1059
+ throw new Error("notebook index failed shape validation: invalid record ref");
1060
+ }
1061
+ if (r.sha256 !== void 0 && typeof r.sha256 !== "string") {
1062
+ throw new Error("notebook index failed shape validation: invalid record ref");
1063
+ }
1064
+ if (r.title !== void 0 && typeof r.title !== "string") {
1065
+ throw new Error("notebook index failed shape validation: invalid record ref");
1066
+ }
1067
+ if (r.date !== void 0 && !finite(r.date)) {
1068
+ throw new Error("notebook index failed shape validation: invalid record ref");
1069
+ }
1070
+ normalizedRecords.push({
1071
+ ...r,
1072
+ commit: r.commit ?? "",
1073
+ version: r.version ?? 1,
1074
+ sha256: r.sha256 ?? ""
1075
+ });
973
1076
  }
974
- return value;
1077
+ return {
1078
+ ...value,
1079
+ version: value.version ?? 1,
1080
+ commit: value.commit ?? "",
1081
+ builtAt: value.builtAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
1082
+ sha256: value.sha256 ?? "",
1083
+ bytes: value.bytes ?? 0,
1084
+ records: normalizedRecords
1085
+ };
975
1086
  }
976
1087
  function assertTelemetry(row, blockIndex) {
977
1088
  if (row.telemetry === void 0) return;
@@ -1597,31 +1708,38 @@ async function prepareSeedChunkWrite(write) {
1597
1708
  return { write, ids, pagesBySlug, linkIds, tagIds };
1598
1709
  }
1599
1710
  async function applySeedChunks(storage, writes) {
1600
- const empty = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1711
+ const empty = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, preservedPinned: 0, addedNotes: 0, updatedNotes: 0 };
1601
1712
  if (!writes.length) return empty;
1602
1713
  const prepared = await Promise.all(writes.map(prepareSeedChunkWrite));
1603
- return storage.transaction(SEED_TX_STORES, "readwrite", async (tx) => {
1604
- const total = { ...empty };
1605
- for (const item of prepared) {
1606
- const part = await applyPreparedSeedChunkInTx(tx, item);
1607
- total.totalNotes += part.totalNotes;
1608
- total.totalEfforts += part.totalEfforts;
1609
- total.totalEquipment += part.totalEquipment;
1610
- total.totalBlocks += part.totalBlocks;
1611
- total.skippedUserOwned += part.skippedUserOwned;
1612
- total.deleted += part.deleted;
1613
- total.addedNotes += part.addedNotes;
1614
- total.updatedNotes += part.updatedNotes;
1615
- }
1616
- return total;
1617
- });
1714
+ const total = { ...empty };
1715
+ for (let i = 0; i < prepared.length; i++) {
1716
+ const item = prepared[i];
1717
+ const part = await storage.transaction(
1718
+ SEED_TX_STORES,
1719
+ "readwrite",
1720
+ (tx) => applyPreparedSeedChunkInTx(tx, item)
1721
+ );
1722
+ total.totalNotes += part.totalNotes;
1723
+ total.totalEfforts += part.totalEfforts;
1724
+ total.totalEquipment += part.totalEquipment;
1725
+ total.totalBlocks += part.totalBlocks;
1726
+ total.skippedUserOwned += part.skippedUserOwned;
1727
+ total.deleted += part.deleted;
1728
+ total.preservedPinned = (total.preservedPinned ?? 0) + (part.preservedPinned ?? 0);
1729
+ total.addedNotes += part.addedNotes;
1730
+ total.updatedNotes += part.updatedNotes;
1731
+ if (i + 1 < prepared.length) {
1732
+ await new Promise((resolve) => setTimeout(resolve, 0));
1733
+ }
1734
+ }
1735
+ return total;
1618
1736
  }
1619
1737
  async function applySeedChunk(storage, write) {
1620
1738
  return applySeedChunks(storage, [write]);
1621
1739
  }
1622
1740
  async function applyPreparedSeedChunkInTx(tx, prepared) {
1623
1741
  const { write, ids, pagesBySlug, linkIds, tagIds } = prepared;
1624
- const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1742
+ const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, preservedPinned: 0, addedNotes: 0, updatedNotes: 0 };
1625
1743
  const metaStore = tx.readwrite("meta");
1626
1744
  const userDeleted = /* @__PURE__ */ new Set();
1627
1745
  for (const row of await metaStore.getAll()) {
@@ -1630,7 +1748,9 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1630
1748
  }
1631
1749
  const actualMeta = await metaStore.get(write.meta.key);
1632
1750
  if (!equal(actualMeta, write.expectedMeta)) throw new Error("Seed checkpoint changed during import");
1633
- if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; recreate artifacts");
1751
+ if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA && !Array.isArray(write.manifest.notebooks)) {
1752
+ throw new Error("Incompatible seed schema; recreate artifacts");
1753
+ }
1634
1754
  const noteStore = tx.readwrite("notes");
1635
1755
  const priorIds = write.chunkId ? write.expectedMeta?.chunks[write.chunkId]?.noteIds ?? [] : [];
1636
1756
  const declared = new Set((write.chunkId ? write.meta.chunks[write.chunkId]?.noteIds : void 0) ?? ids);
@@ -1694,6 +1814,23 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1694
1814
  const changedTags = [], changedNotes = [], revisions = [], pages = [], pageNotes = [], noteTags = [];
1695
1815
  const blocks = [], blockEfforts = [], blockEquipment = [];
1696
1816
  const sessionStore = tx.readwrite("sessions"), eventStore = tx.readwrite("events");
1817
+ const pinnedNoteIds = /* @__PURE__ */ new Set();
1818
+ if (ownedIds.length > 0) {
1819
+ let existingSessionsByNote;
1820
+ try {
1821
+ existingSessionsByNote = await sessionStore.getAllFromIndexMany("by-note", ownedIds);
1822
+ } catch {
1823
+ const allSessions = await sessionStore.getAll();
1824
+ existingSessionsByNote = ownedIds.map((nid) => allSessions.filter((s) => s.noteId === nid));
1825
+ }
1826
+ for (let i = 0; i < ownedIds.length; i++) {
1827
+ const nid = ownedIds[i];
1828
+ const existing = existingById.get(nid);
1829
+ if (existing?.retention === "session-pinned" || (existingSessionsByNote[i]?.length ?? 0) > 0) {
1830
+ pinnedNoteIds.add(nid);
1831
+ }
1832
+ }
1833
+ }
1697
1834
  const telemetrySessionIds = write.rows.flatMap((row) => row.telemetry?.sessions.map((session) => session.id) ?? []);
1698
1835
  const storedTelemetrySessions = await sessionStore.getMany(telemetrySessionIds);
1699
1836
  const existingTelemetrySessions = new Map(telemetrySessionIds.map((sessionId, i) => [sessionId, storedTelemetrySessions[i]]));
@@ -1733,7 +1870,29 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1733
1870
  date = ts;
1734
1871
  }
1735
1872
  const seedCommit = row.commit ?? write.manifest.commit;
1736
- 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 } : {} };
1873
+ const existingRetention = existing;
1874
+ const resolvedPin = pinnedNoteIds.has(id) || existingRetention?.retention === "session-pinned" ? "session-pinned" : existingRetention?.retention === "schedule-pinned" ? "schedule-pinned" : void 0;
1875
+ const note = {
1876
+ ...existing,
1877
+ id,
1878
+ title,
1879
+ rawContent: row.content,
1880
+ sourceRevision,
1881
+ blocks: map,
1882
+ createdAt: write.manifest.version,
1883
+ ...date === void 0 ? {} : { date },
1884
+ type: write.chunkId === DASHBOARDS_CHUNK_ID ? "dashboard" : "note",
1885
+ sourceId,
1886
+ seedOrigin: "seed",
1887
+ seedVersion: write.manifest.version,
1888
+ seedChunkId: write.chunkId ?? void 0,
1889
+ feedOrigin: "feed",
1890
+ feedSourceId,
1891
+ sourcePath: row.path,
1892
+ ...seedCommit ? { seedCommit } : {},
1893
+ ...resolvedPin ? { retention: resolvedPin } : existingRetention?.retention ? { retention: existingRetention.retention } : {},
1894
+ ...resolvedPin || existingRetention?.upstreamStatus ? { upstreamStatus: "live" } : {}
1895
+ };
1737
1896
  if (date === void 0) delete note.date;
1738
1897
  if (!equal(note, existing)) changedNotes.push(note);
1739
1898
  const byRange = new Map(Object.values(map).map((b) => [`${b.from}:${b.to}`, b]));
@@ -1825,12 +1984,30 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1825
1984
  result.totalNotes++;
1826
1985
  result.totalBlocks += Object.keys(map).length;
1827
1986
  }
1987
+ const preservedGoneIds = new Set(
1988
+ goneIds.filter(
1989
+ (id) => owned.has(id) && (pinnedNoteIds.has(id) || existingById.get(id)?.retention === "schedule-pinned")
1990
+ )
1991
+ );
1828
1992
  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));
1829
- for (const rows of currentIndexes) for (const row of rows) if (row.isStatic === true && !wantedBlocks.has(row.id)) await indexStore.delete(row.id);
1830
- for (const rows of currentEfforts) for (const row of rows) if (row.isStatic === true && !wantedEfforts.has(row.id)) await effortLinks.delete(row.id);
1831
- for (const rows of currentEquipment) for (const row of rows) if (row.isStatic === true && !wantedEquipment.has(row.id)) await equipmentLinks.delete(row.id);
1993
+ 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);
1994
+ 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);
1995
+ 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);
1832
1996
  for (const id of goneIds) {
1833
- if (!owned.has(id) || !existingById.get(id)) continue;
1997
+ if (!owned.has(id)) continue;
1998
+ const existing = existingById.get(id);
1999
+ if (!existing) continue;
2000
+ const preservedRetention = pinnedNoteIds.has(id) || existing.retention === "session-pinned" ? "session-pinned" : existing.retention === "schedule-pinned" ? "schedule-pinned" : void 0;
2001
+ if (preservedRetention) {
2002
+ const preserved = {
2003
+ ...existing,
2004
+ retention: preservedRetention,
2005
+ upstreamStatus: "removed"
2006
+ };
2007
+ if (!equal(preserved, existing)) changedNotes.push(preserved);
2008
+ result.preservedPinned = (result.preservedPinned ?? 0) + 1;
2009
+ continue;
2010
+ }
1834
2011
  const n = slot.get(id);
1835
2012
  await noteStore.delete(id);
1836
2013
  for (const link of currentTags[n]) await tagLinks.delete(link.id);
@@ -2149,22 +2326,58 @@ function buildQueryServiceStoresFromStorage(storage, options = {}) {
2149
2326
  relationStore: {
2150
2327
  getBatches: async (noteIds) => {
2151
2328
  const bundles = /* @__PURE__ */ new Map();
2152
- for (const noteId of noteIds) {
2153
- const links = await storage.readonly("page_notes").getAllFromIndex("by-note", noteId);
2154
- const tagLinks = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
2155
- const tags = await storage.readonly("tags").getMany(tagLinks.map((l) => l.tagId));
2156
- const pages = await storage.readonly("page").getMany([...new Set(links.map((l) => l.pageId))]);
2157
- bundles.set(noteId, {
2158
- tags: tags.flatMap((t) => t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : []),
2159
- links,
2160
- pages: pages.filter((p) => p !== void 0)
2161
- });
2162
- }
2163
- return bundles;
2329
+ const uniqueIds = [...new Set(noteIds)];
2330
+ if (uniqueIds.length === 0) return bundles;
2331
+ return storage.transaction(["page_notes", "note_tags", "tags", "page"], "readonly", async (tx) => {
2332
+ const [pageLinkGroups, tagLinkGroups] = await Promise.all([
2333
+ tx.readonly("page_notes").getAllFromIndexMany("by-note", uniqueIds),
2334
+ tx.readonly("note_tags").getAllFromIndexMany("by-note", uniqueIds)
2335
+ ]);
2336
+ const tagIds = /* @__PURE__ */ new Set();
2337
+ const pageIds = /* @__PURE__ */ new Set();
2338
+ for (const group of tagLinkGroups) for (const link of group) tagIds.add(link.tagId);
2339
+ for (const group of pageLinkGroups) for (const link of group) pageIds.add(link.pageId);
2340
+ const [tagRows, pageRows] = await Promise.all([
2341
+ tx.readonly("tags").getMany([...tagIds]),
2342
+ tx.readonly("page").getMany([...pageIds])
2343
+ ]);
2344
+ const tagById = new Map([...tagIds].map((id, i) => [id, tagRows[i]]));
2345
+ const pageById = new Map([...pageIds].map((id, i) => [id, pageRows[i]]));
2346
+ for (let i = 0; i < uniqueIds.length; i++) {
2347
+ const noteId = uniqueIds[i];
2348
+ const links = pageLinkGroups[i] ?? [];
2349
+ const tagLinks = tagLinkGroups[i] ?? [];
2350
+ bundles.set(noteId, {
2351
+ tags: tagLinks.flatMap((l) => {
2352
+ const t = tagById.get(l.tagId);
2353
+ return t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : [];
2354
+ }),
2355
+ links,
2356
+ pages: links.flatMap((l) => {
2357
+ const p = pageById.get(l.pageId);
2358
+ return p ? [p] : [];
2359
+ })
2360
+ });
2361
+ }
2362
+ return bundles;
2363
+ });
2164
2364
  }
2165
2365
  },
2166
2366
  feedCatalogStore
2167
2367
  };
2368
+ const scheduleStore = {
2369
+ getAll: async () => storage.readonly("schedule_items").getAll().catch(() => []),
2370
+ getForNote: async (noteId) => storage.readonly("schedule_items").getAllFromIndex("by-note", noteId).catch(() => []),
2371
+ getByDateRange: async (fromDate, toDate) => {
2372
+ try {
2373
+ return (await storage.readonly("schedule_items").getAll()).filter(
2374
+ (item) => item.date >= fromDate && item.date <= toDate
2375
+ );
2376
+ } catch {
2377
+ return [];
2378
+ }
2379
+ }
2380
+ };
2168
2381
  const sessionStore = {
2169
2382
  getAll: async () => {
2170
2383
  const rows = await storage.readonly("sessions").getAll();
@@ -2177,11 +2390,13 @@ function buildQueryServiceStoresFromStorage(storage, options = {}) {
2177
2390
  createdAt: s.createdAt,
2178
2391
  ...s.notebookIds ? { notebookIds: s.notebookIds } : {},
2179
2392
  ...s.blockContentId ? { blockContentId: s.blockContentId } : {},
2180
- ...s.completed !== void 0 ? { completed: s.completed } : {}
2393
+ ...s.completed !== void 0 ? { completed: s.completed } : {},
2394
+ ...s.sessionDate ? { sessionDate: s.sessionDate } : {},
2395
+ ...s.scheduleItemId ? { scheduleItemId: s.scheduleItemId } : {}
2181
2396
  }));
2182
2397
  }
2183
2398
  };
2184
- Object.assign(stores, { sessionStore });
2399
+ Object.assign(stores, { scheduleStore, sessionStore });
2185
2400
  if (options.datasetStore) {
2186
2401
  stores.datasetStore = options.datasetStore;
2187
2402
  }
@@ -2947,6 +3162,9 @@ var HttpFeedTree = class {
2947
3162
  const text = decodeUtf8(await this.read(path));
2948
3163
  return JSON.parse(text);
2949
3164
  }
3165
+ async readText(path) {
3166
+ return decodeUtf8(await this.read(path));
3167
+ }
2950
3168
  async stat(path) {
2951
3169
  try {
2952
3170
  const bytes = await this.read(path);
@@ -3781,7 +3999,7 @@ function isNotebookLandingNote(note) {
3781
3999
  function baseUserMemberships(note) {
3782
4000
  if (note.seedOrigin === "seed" || note.feedOrigin === "feed") return [];
3783
4001
  if (isNotebookLandingNote(note) || isPropertyDefinitionNoteId(note.id)) return [];
3784
- const base = ["notebook/journal"];
4002
+ const base = [];
3785
4003
  if (note.type === "playground" || note.sourceId === "playground") {
3786
4004
  base.push("notebook/playground");
3787
4005
  }
@@ -3899,7 +4117,6 @@ async function promoteNoteToNotebooks(storage, input) {
3899
4117
  for (const sess of sessions) {
3900
4118
  if (!wantedSessions.has(sess.id)) continue;
3901
4119
  const sessNotebooks = dedupeNotebooks([
3902
- "notebook/journal",
3903
4120
  ...sess.notebookIds ?? [],
3904
4121
  ...requestedTargets
3905
4122
  ]);
@@ -3942,12 +4159,12 @@ async function setNoteNotebooks(storage, input) {
3942
4159
  if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
3943
4160
  throw new Error(`Read-only Feed Note '${input.noteId}' cannot change Notebook membership.`);
3944
4161
  }
3945
- const userTargets = requested.filter(
3946
- (id) => id !== "notebook/journal" && id !== "notebook/playground"
3947
- );
4162
+ const userTargets = requested.filter((id) => id !== "notebook/playground");
3948
4163
  for (const target of userTargets) {
3949
- await assertWritableTargetNotebook(tx, target);
3950
- await ensureUserNotebookLanding(tx, target, now);
4164
+ if (target !== "notebook/journal") {
4165
+ await assertWritableTargetNotebook(tx, target);
4166
+ await ensureUserNotebookLanding(tx, target, now);
4167
+ }
3951
4168
  }
3952
4169
  const finalMemberships = dedupeNotebooks([
3953
4170
  ...baseUserMemberships(note),
@@ -3987,9 +4204,6 @@ async function setNoteNotebooks(storage, input) {
3987
4204
  }
3988
4205
  async function removeNoteFromNotebook(storage, noteId, notebookIdOrSlug) {
3989
4206
  const target = toNotebookId$1(notebookIdOrSlug);
3990
- if (target === "notebook/journal") {
3991
- throw new Error("Notes cannot be removed from private notebook/journal.");
3992
- }
3993
4207
  const current = await getNoteNotebooks(storage, noteId);
3994
4208
  const remaining = current.filter((id) => id !== target);
3995
4209
  return setNoteNotebooks(storage, { noteId, notebookIds: remaining });
@@ -4003,11 +4217,12 @@ async function getNoteNotebooks(storage, noteId) {
4003
4217
  linkNotebookIds = links.filter((l) => l.targetKind === "note" && l.targetId === noteId).map((l) => l.notebookId);
4004
4218
  } catch {
4005
4219
  }
4220
+ const hasExplicitArray = Array.isArray(note.notebookIds);
4006
4221
  return dedupeNotebooks([
4007
4222
  ...baseUserMemberships(note),
4008
4223
  ...note.notebookIds ?? [],
4009
4224
  ...linkNotebookIds,
4010
- ...notebooksOfItem(note)
4225
+ ...hasExplicitArray ? [] : notebooksOfItem(note)
4011
4226
  ]);
4012
4227
  }
4013
4228
  function mintUuidV4() {
@@ -4123,17 +4338,184 @@ async function setSessionPublic(storage, sessionId, isPublic) {
4123
4338
  return updated;
4124
4339
  });
4125
4340
  }
4341
+ var cachedDefaultReferenceIndex = null;
4342
+ function defaultLazyReferenceIndex() {
4343
+ if (!cachedDefaultReferenceIndex) {
4344
+ cachedDefaultReferenceIndex = createReferenceIndex({
4345
+ efforts: [...bundledEfforts],
4346
+ equipment: []
4347
+ });
4348
+ }
4349
+ return cachedDefaultReferenceIndex;
4350
+ }
4351
+ function titleFromMarkdown(path, markdown) {
4352
+ const fm = readFrontmatterMeta(markdown);
4353
+ const fmTitle = typeof fm["title"] === "string" ? fm["title"].trim().replace(/^["']|["']$/g, "") : "";
4354
+ if (fmTitle) return fmTitle;
4355
+ const heading = markdown.match(/^#\s+(.+)$/m)?.[1]?.trim();
4356
+ if (heading) return heading;
4357
+ return (path.split("/").at(-1) ?? path).replace(/\.md$/i, "").replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
4358
+ }
4359
+ function notebookSlugFromFeedPath(path) {
4360
+ const match = /^markdown\/notebooks\/([^/]+)\//.exec(path);
4361
+ return match?.[1] && match[1] !== "_root" ? match[1] : void 0;
4362
+ }
4363
+ async function compileSeedRowFromMarkdown(input) {
4364
+ const path = input.path.replace(/^\/+/, "");
4365
+ if (!path || path.split("/").includes("..")) {
4366
+ throw new Error(`Invalid seed markdown path: '${input.path}'`);
4367
+ }
4368
+ const content = input.markdown;
4369
+ const uuid = input.uuid || await seedNoteId(path);
4370
+ const fm = readFrontmatterMeta(content);
4371
+ const title = input.title?.trim() || titleFromMarkdown(path, content);
4372
+ const rawDate = typeof fm["date"] === "string" ? fm["date"] : void 0;
4373
+ const parsedDate = parseFrontmatterDateMs(rawDate);
4374
+ const createdAt = input.date ?? parsedDate ?? input.createdAt ?? 0;
4375
+ let ordinal = 0;
4376
+ const blocks = reconcileNoteBlocks(content, {
4377
+ sourceRevision: 1,
4378
+ registeredWidgets: SEED_REGISTERED_WIDGETS,
4379
+ createId: () => `seed:${path}:${ordinal++}`
4380
+ });
4381
+ const sections = parseDocumentSections(content, { registeredWidgets: SEED_REGISTERED_WIDGETS });
4382
+ const blockIndex = Object.values(blocks).map((block, position) => {
4383
+ const section = sections.find((s) => s.from === block.from && s.to === block.to);
4384
+ const fingerprint = block.kind === "wod" ? blockContentId(section?.scriptBlock?.content ?? content.slice(block.from, block.to)) : void 0;
4385
+ return {
4386
+ id: `${uuid}:${block.id}`,
4387
+ noteId: uuid,
4388
+ blockId: block.id,
4389
+ blockVersion: 1,
4390
+ sourceRevision: 1,
4391
+ from: block.from,
4392
+ to: block.to,
4393
+ position,
4394
+ dataType: block.kind,
4395
+ ...fingerprint ? { blockContentId: fingerprint } : {},
4396
+ rawContent: content.slice(block.from, block.to),
4397
+ noteTitle: title,
4398
+ createdAt,
4399
+ isStatic: true,
4400
+ ...input.sourceId ? { sourceId: input.sourceId } : {},
4401
+ sourcePath: path,
4402
+ ...input.routeId ? { routeId: input.routeId } : {}
4403
+ };
4404
+ });
4405
+ const referenceIndex = input.referenceIndex ?? defaultLazyReferenceIndex();
4406
+ const blockEfforts = [];
4407
+ const blockEquipment = [];
4408
+ for (const proj of blockIndex) {
4409
+ if (proj.dataType !== "wod" || !proj.rawContent) continue;
4410
+ const sec = parseDocumentSections(proj.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find(
4411
+ (s) => s.scriptBlock
4412
+ );
4413
+ const parsed = parseScript(sec?.scriptBlock?.content ?? proj.rawContent, { references: referenceIndex });
4414
+ const refs = extractStatementRefs(parsed.statements);
4415
+ const seenEfforts = /* @__PURE__ */ new Set();
4416
+ for (const rawSlug of refs.efforts) {
4417
+ const canonical = referenceIndex.resolveEffort(rawSlug)?.slug;
4418
+ if (!canonical || seenEfforts.has(canonical)) continue;
4419
+ seenEfforts.add(canonical);
4420
+ blockEfforts.push({
4421
+ id: `${proj.id}:${canonical}`,
4422
+ noteId: uuid,
4423
+ blockId: proj.blockId,
4424
+ ...proj.blockContentId ? { blockContentId: proj.blockContentId } : {},
4425
+ effortSlug: canonical,
4426
+ isStatic: true,
4427
+ sourcePath: path,
4428
+ createdAt
4429
+ });
4430
+ }
4431
+ const seenEquipment = /* @__PURE__ */ new Set();
4432
+ for (const rawSlug of refs.equipment) {
4433
+ const canonical = referenceIndex.resolveEquipment(rawSlug)?.slug;
4434
+ if (!canonical || seenEquipment.has(canonical)) continue;
4435
+ seenEquipment.add(canonical);
4436
+ blockEquipment.push({
4437
+ id: `${proj.id}:${canonical}`,
4438
+ noteId: uuid,
4439
+ blockId: proj.blockId,
4440
+ ...proj.blockContentId ? { blockContentId: proj.blockContentId } : {},
4441
+ equipmentSlug: canonical,
4442
+ isStatic: true,
4443
+ sourcePath: path,
4444
+ createdAt
4445
+ });
4446
+ }
4447
+ }
4448
+ return assertSeedRow({
4449
+ path,
4450
+ content,
4451
+ blocks,
4452
+ blockIndex,
4453
+ blockEfforts,
4454
+ blockEquipment,
4455
+ uuid,
4456
+ commit: input.commit ?? "",
4457
+ version: input.version ?? 1
4458
+ });
4459
+ }
4460
+ async function readTextFromReaderOrUrl(reader, target, fetchImpl) {
4461
+ if (/^https?:\/\//i.test(target)) {
4462
+ const parsed = new URL(target);
4463
+ if (parsed.username || parsed.password) {
4464
+ throw new FeedTreeError("permission", "Disallowed credentials in feed URL");
4465
+ }
4466
+ const doFetch = fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
4467
+ const res = await doFetch(parsed.toString());
4468
+ if (res.status === 404) {
4469
+ throw new FeedTreeError("not-found", `HTTP 404 for ${parsed.toString()}`);
4470
+ }
4471
+ if (!res.ok) {
4472
+ throw new FeedTreeError("permission", `HTTP ${res.status} fetching ${parsed.toString()}`);
4473
+ }
4474
+ return await res.text();
4475
+ }
4476
+ return decodeUtf8(await reader.read(target));
4477
+ }
4126
4478
  async function previewRemoteNotebook(reader, indexPath) {
4127
4479
  const raw = decodeUtf8(await reader.read(indexPath));
4128
4480
  return assertNotebookIndex(JSON.parse(raw));
4129
4481
  }
4130
- async function previewRemoteRecord(reader, recordPath) {
4131
- const raw = decodeUtf8(await reader.read(recordPath));
4132
- return assertSeedRow(JSON.parse(raw));
4482
+ async function previewRemoteRecord(reader, recordOrPath, options) {
4483
+ if (typeof recordOrPath === "string") {
4484
+ if (/\.md$/i.test(recordOrPath)) {
4485
+ const markdown2 = await readTextFromReaderOrUrl(reader, recordOrPath, options?.fetchImpl);
4486
+ return compileSeedRowFromMarkdown({ path: recordOrPath, markdown: markdown2 });
4487
+ }
4488
+ const raw = await readTextFromReaderOrUrl(reader, recordOrPath, options?.fetchImpl);
4489
+ return assertSeedRow(JSON.parse(raw));
4490
+ }
4491
+ if (recordOrPath.recordPath) {
4492
+ try {
4493
+ const raw = await readTextFromReaderOrUrl(reader, recordOrPath.recordPath, options?.fetchImpl);
4494
+ return assertSeedRow(JSON.parse(raw));
4495
+ } catch (err) {
4496
+ const hasMarkdownFallback = Boolean(recordOrPath.rawUrl || /\.md$/i.test(recordOrPath.path));
4497
+ const isNotFound = err instanceof FeedTreeError && err.code === "not-found";
4498
+ if (!isNotFound || !hasMarkdownFallback) throw err;
4499
+ }
4500
+ }
4501
+ const rawTarget = recordOrPath.rawUrl ?? recordOrPath.path;
4502
+ const markdown = await readTextFromReaderOrUrl(reader, rawTarget, options?.fetchImpl);
4503
+ return compileSeedRowFromMarkdown({
4504
+ path: recordOrPath.path,
4505
+ markdown,
4506
+ uuid: recordOrPath.uuid,
4507
+ commit: recordOrPath.commit,
4508
+ version: recordOrPath.version,
4509
+ title: recordOrPath.title,
4510
+ date: recordOrPath.date
4511
+ });
4133
4512
  }
4134
4513
  async function cloneRemoteRecord(storage, reader, input) {
4135
4514
  const targetNotebookId = toNotebookId$1(input.targetNotebookId);
4136
- const seedRow = await previewRemoteRecord(reader, input.record.recordPath);
4515
+ if (isSystemReadOnlyNotebook(targetNotebookId)) {
4516
+ throw new Error(`Target notebook '${targetNotebookId}' is read-only`);
4517
+ }
4518
+ const seedRow = await previewRemoteRecord(reader, input.record);
4137
4519
  const newNoteId = mintUuidV4();
4138
4520
  const now = Date.now();
4139
4521
  const sourceRevision = 1;
@@ -4176,6 +4558,20 @@ async function cloneRemoteRecord(storage, reader, input) {
4176
4558
  noteId: newNoteId,
4177
4559
  isStatic: false
4178
4560
  }));
4561
+ const inferredNbSlug = notebookSlugFromFeedPath(seedRow.path);
4562
+ const sourceNotebookId = input.sourceNotebookId ? toNotebookId$1(input.sourceNotebookId) : inferredNbSlug ? toNotebookId$1(inferredNbSlug) : void 0;
4563
+ const sourceNoteId = input.record.uuid || seedRow.uuid || await seedNoteId(seedRow.path);
4564
+ const sourceVersion = input.record.version ?? seedRow.version;
4565
+ const sourceCommit = input.record.commit || seedRow.commit || void 0;
4566
+ const provenance = {
4567
+ sourceNoteId,
4568
+ ...sourceVersion !== void 0 ? { sourceVersion } : {},
4569
+ ...sourceCommit ? { sourceCommit } : {},
4570
+ feedSourceId: input.feedId,
4571
+ ...sourceNotebookId ? { sourceNotebookId } : {},
4572
+ sourcePath: seedRow.path,
4573
+ clonedAt: now
4574
+ };
4179
4575
  const clonedNote = {
4180
4576
  id: newNoteId,
4181
4577
  title: input.record.title || seedRow.blockIndex[0]?.noteTitle || "Cloned Note",
@@ -4185,6 +4581,8 @@ async function cloneRemoteRecord(storage, reader, input) {
4185
4581
  ...input.record.date !== void 0 ? { date: input.record.date } : {},
4186
4582
  createdAt: now,
4187
4583
  notebookId: targetNotebookId,
4584
+ notebookIds: [targetNotebookId],
4585
+ provenance,
4188
4586
  sourceId: `feed:${input.feedId}/${seedRow.path}`,
4189
4587
  sourcePath: seedRow.path,
4190
4588
  seedOrigin: "user"
@@ -4214,8 +4612,16 @@ async function cloneRemoteRecord(storage, reader, input) {
4214
4612
  });
4215
4613
  }
4216
4614
  }
4615
+ const notebookLink = {
4616
+ id: makeNotebookLinkId(targetNotebookId, "note", newNoteId),
4617
+ notebookId: targetNotebookId,
4618
+ targetKind: "note",
4619
+ targetId: newNoteId,
4620
+ noteId: newNoteId,
4621
+ createdAt: now
4622
+ };
4217
4623
  await storage.transaction(
4218
- ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "sessions", "events"],
4624
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "sessions", "events", "notebook_links"],
4219
4625
  "readwrite",
4220
4626
  async (tx) => {
4221
4627
  const landing = await tx.readonly("notes").get(targetNotebookId);
@@ -4223,6 +4629,7 @@ async function cloneRemoteRecord(storage, reader, input) {
4223
4629
  throw new Error(`Target notebook '${targetNotebookId}' is read-only`);
4224
4630
  }
4225
4631
  await tx.readwrite("notes").put(clonedNote);
4632
+ await tx.readwrite("notebook_links").put(notebookLink);
4226
4633
  if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
4227
4634
  if (blockIndex.length > 0) await tx.readwrite("block_index").putMany(blockIndex);
4228
4635
  if (blockEfforts.length > 0) await tx.readwrite("block_efforts").putMany(blockEfforts);
@@ -4233,6 +4640,129 @@ async function cloneRemoteRecord(storage, reader, input) {
4233
4640
  );
4234
4641
  return clonedNote;
4235
4642
  }
4643
+ async function clearRowsByNoteIndex(store, noteId, keyOf) {
4644
+ let rows;
4645
+ try {
4646
+ rows = await store.getAllFromIndex("by-note", noteId);
4647
+ } catch {
4648
+ rows = await store.getAll();
4649
+ }
4650
+ for (const row of rows) {
4651
+ const rec = row;
4652
+ if (!rec || rec["noteId"] !== noteId) continue;
4653
+ const key = keyOf(row);
4654
+ if (key !== void 0) await store.delete(key);
4655
+ }
4656
+ }
4657
+ async function materializeCachedRemoteRecord(storage, input) {
4658
+ const canonicalId = input.record?.uuid || input.seedRow.uuid || await seedNoteId(input.seedRow.path);
4659
+ const inferredNbSlug = input.notebookSlug ?? notebookSlugFromFeedPath(input.seedRow.path);
4660
+ const notebookId = input.notebookId ? toNotebookId$1(input.notebookId) : inferredNbSlug ? toNotebookId$1(inferredNbSlug) : void 0;
4661
+ const seedChunkId = inferredNbSlug ? `notebook.${inferredNbSlug}` : notebookId ? `notebook.${notebookId.replace(/^notebook\//, "")}` : void 0;
4662
+ const version = input.record?.version ?? input.seedRow.version ?? 1;
4663
+ const title = input.record?.title || input.seedRow.blockIndex[0]?.noteTitle || titleFromMarkdown(input.seedRow.path, input.seedRow.content);
4664
+ const commit = input.record?.commit || input.seedRow.commit || void 0;
4665
+ const now = Date.now();
4666
+ return storage.transaction(
4667
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment"],
4668
+ "readwrite",
4669
+ async (tx) => {
4670
+ const notesStore = tx.readwrite("notes");
4671
+ const existing = await notesStore.get(canonicalId);
4672
+ if (existing) {
4673
+ const isUserOwned = existing.seedOrigin !== "seed" && existing.feedOrigin !== "feed" && !existing.retention;
4674
+ if (isUserOwned || existing.retention === "session-pinned" || existing.retention === "schedule-pinned") {
4675
+ return existing;
4676
+ }
4677
+ if (existing.rawContent === input.seedRow.content && Object.keys(existing.blocks).length > 0 && existing.retention === "cached") {
4678
+ if (existing.upstreamStatus !== (input.upstreamStatus ?? "live") || input.feedId && existing.feedSourceId !== input.feedId) {
4679
+ const refreshed = {
4680
+ ...existing,
4681
+ ...input.feedId ? { feedOrigin: "feed", feedSourceId: input.feedId } : {},
4682
+ upstreamStatus: input.upstreamStatus ?? "live"
4683
+ };
4684
+ await notesStore.put(refreshed);
4685
+ return refreshed;
4686
+ }
4687
+ return existing;
4688
+ }
4689
+ }
4690
+ const sourceRevision = existing ? existing.sourceRevision + 1 : 1;
4691
+ const blocks = {};
4692
+ const revisions = [];
4693
+ const revStore = tx.readwrite("block_revisions");
4694
+ const blockVer = existing ? sourceRevision : 1;
4695
+ for (const [key, block] of Object.entries(input.seedRow.blocks)) {
4696
+ blocks[key] = { ...block, version: blockVer, sourceRevision };
4697
+ revisions.push({
4698
+ noteId: canonicalId,
4699
+ blockId: block.id,
4700
+ version: blockVer,
4701
+ kind: block.kind,
4702
+ rawContent: input.seedRow.content.slice(block.from, block.to),
4703
+ savedAt: now,
4704
+ ...block.dialect ? { dialect: block.dialect } : {},
4705
+ ...block.sport ? { sport: block.sport } : {}
4706
+ });
4707
+ }
4708
+ const cachedSourceId = input.feedId ? `feed:${input.feedId}/${input.seedRow.path}` : input.seedRow.path;
4709
+ const blockIndexStore = tx.readwrite("block_index");
4710
+ const blockEffortsStore = tx.readwrite("block_efforts");
4711
+ const blockEquipmentStore = tx.readwrite("block_equipment");
4712
+ await clearRowsByNoteIndex(blockIndexStore, canonicalId, (r) => r.id);
4713
+ await clearRowsByNoteIndex(blockEffortsStore, canonicalId, (r) => r.id);
4714
+ await clearRowsByNoteIndex(blockEquipmentStore, canonicalId, (r) => r.id);
4715
+ const blockIndex = input.seedRow.blockIndex.map((proj) => ({
4716
+ ...proj,
4717
+ id: `${canonicalId}:${proj.blockId}`,
4718
+ noteId: canonicalId,
4719
+ blockVersion: blockVer,
4720
+ sourceRevision,
4721
+ isStatic: true,
4722
+ sourceId: cachedSourceId,
4723
+ sourcePath: input.seedRow.path,
4724
+ ...notebookId ? { notebookId } : {}
4725
+ }));
4726
+ const blockEfforts = input.seedRow.blockEfforts.map((eff) => ({
4727
+ ...eff,
4728
+ id: `${canonicalId}:${eff.blockId}:${eff.effortSlug}`,
4729
+ noteId: canonicalId,
4730
+ isStatic: true
4731
+ }));
4732
+ const blockEquipment = input.seedRow.blockEquipment.map((eq) => ({
4733
+ ...eq,
4734
+ id: `${canonicalId}:${eq.blockId}:${eq.equipmentSlug}`,
4735
+ noteId: canonicalId,
4736
+ isStatic: true
4737
+ }));
4738
+ const cachedNote = {
4739
+ id: canonicalId,
4740
+ title,
4741
+ rawContent: input.seedRow.content,
4742
+ sourceRevision,
4743
+ blocks,
4744
+ ...input.record?.date !== void 0 ? { date: input.record.date } : existing?.date !== void 0 ? { date: existing.date } : {},
4745
+ createdAt: existing?.createdAt ?? input.record?.date ?? now,
4746
+ ...notebookId ? { notebookId, notebookIds: [notebookId] } : existing?.notebookId ? { notebookId: existing.notebookId } : {},
4747
+ ...input.feedId ? { feedOrigin: "feed", feedSourceId: input.feedId } : existing?.feedOrigin ? { feedOrigin: existing.feedOrigin, feedSourceId: existing.feedSourceId } : {},
4748
+ seedOrigin: "seed",
4749
+ ...seedChunkId ? { seedChunkId } : existing?.seedChunkId ? { seedChunkId: existing.seedChunkId } : {},
4750
+ seedVersion: version,
4751
+ ...commit ? { seedCommit: commit } : {},
4752
+ sourceId: cachedSourceId,
4753
+ sourcePath: input.seedRow.path,
4754
+ retention: input.retention ?? "cached",
4755
+ upstreamStatus: input.upstreamStatus ?? "live"
4756
+ };
4757
+ await notesStore.put(cachedNote);
4758
+ if (revisions.length > 0) await revStore.putMany(revisions);
4759
+ if (blockIndex.length > 0) await blockIndexStore.putMany(blockIndex);
4760
+ if (blockEfforts.length > 0) await blockEffortsStore.putMany(blockEfforts);
4761
+ if (blockEquipment.length > 0) await blockEquipmentStore.putMany(blockEquipment);
4762
+ return cachedNote;
4763
+ }
4764
+ );
4765
+ }
4236
4766
  var portableTextDecoder = new TextDecoder();
4237
4767
  function decodePortableFileContent(entry) {
4238
4768
  if (typeof entry.content === "string") return entry.content;
@@ -4509,6 +5039,37 @@ async function ingestPortableFilesIntoStorage(storage, files, options = {}) {
4509
5039
  };
4510
5040
  }
4511
5041
  var FEED_SUBSCRIPTIONS_META_KEY = "feed:subscriptions";
5042
+ var FEED_REGISTRY_META_KEY = "feed:registry";
5043
+ async function noteHasSessions(tx, noteId) {
5044
+ const sessionStore = tx.readonly("sessions");
5045
+ try {
5046
+ if (typeof sessionStore.countFromIndex === "function") {
5047
+ return await sessionStore.countFromIndex("by-note", noteId) > 0;
5048
+ }
5049
+ const rows = await sessionStore.getAllFromIndex("by-note", noteId);
5050
+ return rows.length > 0;
5051
+ } catch {
5052
+ const all = await sessionStore.getAll();
5053
+ return all.some((s) => s.noteId === noteId);
5054
+ }
5055
+ }
5056
+ async function noteHasScheduleItems(tx, noteId) {
5057
+ try {
5058
+ const schedStore = tx.readonly("schedule_items");
5059
+ if (typeof schedStore.countFromIndex === "function") {
5060
+ return await schedStore.countFromIndex("by-note", noteId) > 0;
5061
+ }
5062
+ const rows = await schedStore.getAllFromIndex("by-note", noteId);
5063
+ return rows.length > 0;
5064
+ } catch {
5065
+ try {
5066
+ const all = await tx.readonly("schedule_items").getAll();
5067
+ return all.some((s) => s.noteId === noteId);
5068
+ } catch {
5069
+ return false;
5070
+ }
5071
+ }
5072
+ }
4512
5073
  async function removeSeedSourceContent(storage, meta) {
4513
5074
  return storage.transaction(
4514
5075
  [
@@ -4520,13 +5081,18 @@ async function removeSeedSourceContent(storage, meta) {
4520
5081
  "block_efforts",
4521
5082
  "block_equipment",
4522
5083
  "page_notes",
5084
+ "schedule_items",
4523
5085
  "efforts",
4524
5086
  "equipment",
4525
5087
  "property_overrides",
5088
+ "sessions",
4526
5089
  "meta"
4527
5090
  ],
4528
5091
  "readwrite",
4529
5092
  async (tx) => {
5093
+ const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
5094
+ const chunkKeys = Object.keys(meta.chunks);
5095
+ const isWholeFeedSweep = chunkKeys.length === 0 || Object.values(meta.chunks).length > 0;
4530
5096
  const targetIds = /* @__PURE__ */ new Set();
4531
5097
  const legacyChunks = [];
4532
5098
  for (const [chunkId, chunk] of Object.entries(meta.chunks)) {
@@ -4536,16 +5102,31 @@ async function removeSeedSourceContent(storage, meta) {
4536
5102
  legacyChunks.push(chunkId);
4537
5103
  }
4538
5104
  }
5105
+ const allNotes = legacyChunks.length || isWholeFeedSweep ? await tx.readwrite("notes").getAll() : [];
4539
5106
  if (legacyChunks.length) {
4540
- for (const note of await tx.readwrite("notes").getAll()) {
5107
+ for (const note of allNotes) {
4541
5108
  if (note.seedOrigin === "seed" && note.seedChunkId && legacyChunks.includes(note.seedChunkId)) {
4542
5109
  targetIds.add(note.id);
4543
5110
  }
4544
5111
  }
4545
5112
  }
5113
+ if (isWholeFeedSweep) {
5114
+ for (const note of allNotes) {
5115
+ const rNote = note;
5116
+ if (note.seedOrigin === "seed" && note.feedSourceId === removedSourceId && (chunkKeys.length === 0 || rNote.retention === "cached" || rNote.retention === "schedule-pinned" || rNote.retention === "session-pinned")) {
5117
+ targetIds.add(note.id);
5118
+ }
5119
+ }
5120
+ }
4546
5121
  const metaStore = tx.readwrite("meta");
4547
5122
  const otherCheckpoints = [];
5123
+ const indexKeysToDelete = [];
5124
+ const indexPrefix = `${FEED_INDEX_META_PREFIX}${removedSourceId}:`;
4548
5125
  for (const row of await metaStore.getAll()) {
5126
+ const key = row?.key;
5127
+ if (typeof key === "string" && key.startsWith(indexPrefix)) {
5128
+ indexKeysToDelete.push(key);
5129
+ }
4549
5130
  const other = row;
4550
5131
  if (!other || typeof other.key !== "string" || !other.key.startsWith("seed:") || other.key === meta.key) {
4551
5132
  continue;
@@ -4564,50 +5145,28 @@ async function removeSeedSourceContent(storage, meta) {
4564
5145
  }
4565
5146
  otherCheckpoints.sort((a, b) => b.rank - a.rank);
4566
5147
  const isClaimedByOther = (noteId) => otherCheckpoints.some((cp) => cp.noteIds.has(noteId));
4567
- const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
4568
5148
  const notes = tx.readwrite("notes");
4569
- const noteTags = tx.readwrite("note_tags");
4570
5149
  let deleted = 0;
5150
+ let preservedPinned = 0;
4571
5151
  const removedPaths = /* @__PURE__ */ new Set();
4572
5152
  const touchedTagIds = /* @__PURE__ */ new Set();
4573
5153
  for (const id of targetIds) {
4574
5154
  if (isClaimedByOther(id)) continue;
4575
5155
  const note = await notes.get(id);
4576
5156
  if (!note || note.seedOrigin !== "seed") continue;
4577
- if (note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
4578
- if (note.sourcePath) removedPaths.add(note.sourcePath);
4579
- await notes.delete(id);
4580
- const attachments = tx.readwrite("attachments");
4581
- for (const attachment of await attachments.getAllFromIndex("by-note", id)) {
4582
- await attachments.delete(attachment.id);
4583
- }
4584
- for (const link of await noteTags.getAllFromIndex("by-note", id)) {
4585
- touchedTagIds.add(link.tagId);
4586
- await noteTags.delete(link.id);
4587
- }
4588
- const blockIndex = tx.readwrite("block_index");
4589
- for (const row of await blockIndex.getAllFromIndex("by-note", id)) await blockIndex.delete(row.id);
4590
- const blockEfforts = tx.readwrite("block_efforts");
4591
- for (const row of await blockEfforts.getAllFromIndex("by-note", id)) await blockEfforts.delete(row.id);
4592
- const blockEquipment = tx.readwrite("block_equipment");
4593
- for (const row of await blockEquipment.getAllFromIndex("by-note", id)) await blockEquipment.delete(row.id);
4594
- const pageNotes = tx.readwrite("page_notes");
4595
- for (const link of await pageNotes.getAllFromIndex("by-note", id)) await pageNotes.delete(link.id);
4596
- deleted++;
4597
- }
4598
- if (touchedTagIds.size > 0) {
4599
- const tagsStore = tx.readwrite("tags");
4600
- for (const tagId of touchedTagIds) {
4601
- const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
4602
- if (remainingLinks > 0) continue;
4603
- const tag = await tagsStore.get(tagId);
4604
- if (!tag) continue;
4605
- if (tag.contributions && tag.contributions.length > 0) continue;
4606
- const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
4607
- if (refNote) continue;
4608
- await tagsStore.delete(tagId);
4609
- }
5157
+ const ownedByFeedStamp = note.feedSourceId === removedSourceId && (chunkKeys.length === 0 || note.retention === "cached" || note.retention === "schedule-pinned" || note.retention === "session-pinned");
5158
+ if (!ownedByFeedStamp && note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
5159
+ const outcome = await deleteOrPreserveFeedNote(
5160
+ tx,
5161
+ note,
5162
+ "unsubscribed",
5163
+ touchedTagIds,
5164
+ removedPaths
5165
+ );
5166
+ if (outcome === "pinned") preservedPinned++;
5167
+ else deleted++;
4610
5168
  }
5169
+ await pruneOrphanTags(tx, touchedTagIds);
4611
5170
  const defFamilies = [
4612
5171
  { storeName: "efforts", familyPathPrefix: "markdown/efforts/", parse: parseEffortFile },
4613
5172
  { storeName: "equipment", familyPathPrefix: "markdown/equipment/", parse: parseEquipmentFile }
@@ -4652,11 +5211,140 @@ async function removeSeedSourceContent(storage, meta) {
4652
5211
  }
4653
5212
  } catch {
4654
5213
  }
5214
+ for (const idxKey of indexKeysToDelete) {
5215
+ await metaStore.delete(idxKey);
5216
+ }
4655
5217
  await metaStore.delete(meta.key);
4656
- return deleted;
5218
+ return { deleted, preservedPinned };
5219
+ }
5220
+ );
5221
+ }
5222
+ async function pruneOrphanTags(tx, touchedTagIds) {
5223
+ if (touchedTagIds.size === 0) return;
5224
+ const notes = tx.readwrite("notes");
5225
+ const noteTags = tx.readwrite("note_tags");
5226
+ const tagsStore = tx.readwrite("tags");
5227
+ for (const tagId of touchedTagIds) {
5228
+ const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
5229
+ if (remainingLinks > 0) continue;
5230
+ const tag = await tagsStore.get(tagId);
5231
+ if (!tag) continue;
5232
+ if (tag.contributions && tag.contributions.length > 0) continue;
5233
+ const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
5234
+ if (refNote) continue;
5235
+ await tagsStore.delete(tagId);
5236
+ }
5237
+ }
5238
+ async function deleteOrPreserveFeedNote(tx, note, upstreamStatus, touchedTagIds, removedPaths) {
5239
+ const notes = tx.readwrite("notes");
5240
+ const hasSessions = await noteHasSessions(tx, note.id);
5241
+ const isSessionPinned = note.retention === "session-pinned" || hasSessions;
5242
+ const hasSchedules = !isSessionPinned && await noteHasScheduleItems(tx, note.id);
5243
+ const isSchedulePinned = note.retention === "schedule-pinned" || hasSchedules;
5244
+ if (isSessionPinned || isSchedulePinned) {
5245
+ await notes.put({
5246
+ ...note,
5247
+ retention: isSessionPinned ? "session-pinned" : "schedule-pinned",
5248
+ upstreamStatus
5249
+ });
5250
+ return "pinned";
5251
+ }
5252
+ if (note.sourcePath && removedPaths) removedPaths.add(note.sourcePath);
5253
+ await notes.delete(note.id);
5254
+ const attachments = tx.readwrite("attachments");
5255
+ for (const attachment of await attachments.getAllFromIndex("by-note", note.id)) {
5256
+ await attachments.delete(attachment.id);
5257
+ }
5258
+ const noteTags = tx.readwrite("note_tags");
5259
+ for (const link of await noteTags.getAllFromIndex("by-note", note.id)) {
5260
+ touchedTagIds.add(link.tagId);
5261
+ await noteTags.delete(link.id);
5262
+ }
5263
+ const blockIndex = tx.readwrite("block_index");
5264
+ for (const row of await blockIndex.getAllFromIndex("by-note", note.id)) await blockIndex.delete(row.id);
5265
+ const blockEfforts = tx.readwrite("block_efforts");
5266
+ for (const row of await blockEfforts.getAllFromIndex("by-note", note.id)) await blockEfforts.delete(row.id);
5267
+ const blockEquipment = tx.readwrite("block_equipment");
5268
+ for (const row of await blockEquipment.getAllFromIndex("by-note", note.id)) await blockEquipment.delete(row.id);
5269
+ const pageNotes = tx.readwrite("page_notes");
5270
+ for (const link of await pageNotes.getAllFromIndex("by-note", note.id)) await pageNotes.delete(link.id);
5271
+ return "deleted";
5272
+ }
5273
+ async function removeFeedSourceContentById(storage, sourceId) {
5274
+ const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
5275
+ return removeSeedSourceContent(storage, meta ?? emptySeedMeta(seedMetaKey(sourceId)));
5276
+ }
5277
+ async function removeFeedNotebookContent(storage, feedId, chunkId) {
5278
+ return storage.transaction(
5279
+ ["notes", "attachments", "tags", "note_tags", "block_index", "block_efforts", "block_equipment", "page_notes", "schedule_items", "sessions", "meta"],
5280
+ "readwrite",
5281
+ async (tx) => {
5282
+ const notes = tx.readwrite("notes");
5283
+ const allNotes = await notes.getAll();
5284
+ let deleted = 0;
5285
+ let preservedPinned = 0;
5286
+ const touchedTagIds = /* @__PURE__ */ new Set();
5287
+ for (const rawNote of allNotes) {
5288
+ const note = rawNote;
5289
+ if (note.seedOrigin !== "seed") continue;
5290
+ if (note.feedSourceId !== feedId || note.seedChunkId !== chunkId) continue;
5291
+ const outcome = await deleteOrPreserveFeedNote(tx, note, "unsubscribed", touchedTagIds);
5292
+ if (outcome === "pinned") preservedPinned++;
5293
+ else deleted++;
5294
+ }
5295
+ await pruneOrphanTags(tx, touchedTagIds);
5296
+ await tx.readwrite("meta").delete(`${FEED_INDEX_META_PREFIX}${feedId}:${chunkId}`);
5297
+ return { deleted, preservedPinned };
5298
+ }
5299
+ );
5300
+ }
5301
+ async function reconcileRemovedFeedRecords(storage, feedId, notebookId, liveUuids) {
5302
+ return storage.transaction(
5303
+ ["notes", "attachments", "tags", "note_tags", "block_index", "block_efforts", "block_equipment", "page_notes", "schedule_items", "sessions"],
5304
+ "readwrite",
5305
+ async (tx) => {
5306
+ const notes = tx.readwrite("notes");
5307
+ const allNotes = await notes.getAll();
5308
+ let deleted = 0;
5309
+ let preservedPinned = 0;
5310
+ const touchedTagIds = /* @__PURE__ */ new Set();
5311
+ for (const rawNote of allNotes) {
5312
+ const note = rawNote;
5313
+ if (note.seedOrigin !== "seed") continue;
5314
+ if (note.feedSourceId !== feedId || note.seedChunkId !== notebookId) continue;
5315
+ if (liveUuids.has(note.id)) continue;
5316
+ const outcome = await deleteOrPreserveFeedNote(tx, note, "removed", touchedTagIds);
5317
+ if (outcome === "pinned") preservedPinned++;
5318
+ else deleted++;
5319
+ }
5320
+ await pruneOrphanTags(tx, touchedTagIds);
5321
+ return { deleted, preservedPinned };
4657
5322
  }
4658
5323
  );
4659
5324
  }
5325
+ async function readFeedRegistryHeadless(storage) {
5326
+ const row = await storage.readonly("meta").get(FEED_REGISTRY_META_KEY);
5327
+ return {
5328
+ key: FEED_REGISTRY_META_KEY,
5329
+ customFeeds: Array.isArray(row?.customFeeds) ? [...row.customFeeds] : [],
5330
+ hiddenFeedIds: Array.isArray(row?.hiddenFeedIds) ? [...row.hiddenFeedIds] : [],
5331
+ updatedAt: typeof row?.updatedAt === "number" ? row.updatedAt : 0,
5332
+ ...row?.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
5333
+ };
5334
+ }
5335
+ async function writeFeedRegistryHeadless(storage, next) {
5336
+ const record = {
5337
+ key: FEED_REGISTRY_META_KEY,
5338
+ customFeeds: next.customFeeds,
5339
+ hiddenFeedIds: next.hiddenFeedIds,
5340
+ updatedAt: next.updatedAt,
5341
+ ...next.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
5342
+ };
5343
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
5344
+ await tx.readwrite("meta").put(record);
5345
+ });
5346
+ return record;
5347
+ }
4660
5348
  async function readFeedSubscriptionsMap(storage) {
4661
5349
  const row = await storage.readonly("meta").get(FEED_SUBSCRIPTIONS_META_KEY);
4662
5350
  return { ...row?.entries ?? {} };
@@ -4666,7 +5354,11 @@ async function writeFeedSubscriptionEntry(storage, sourceId, entry) {
4666
5354
  const metaStore = tx.readwrite("meta");
4667
5355
  const existing = await metaStore.get(FEED_SUBSCRIPTIONS_META_KEY);
4668
5356
  const entries = { ...existing?.entries ?? {}, [sourceId]: entry };
4669
- await metaStore.put({ key: FEED_SUBSCRIPTIONS_META_KEY, entries });
5357
+ await metaStore.put({
5358
+ key: FEED_SUBSCRIPTIONS_META_KEY,
5359
+ entries,
5360
+ ...existing?.migratedFromLocalStorage ? { migratedFromLocalStorage: true } : {}
5361
+ });
4670
5362
  });
4671
5363
  }
4672
5364
  async function listFeedSubscriptionsHeadless(storage) {
@@ -4674,43 +5366,158 @@ async function listFeedSubscriptionsHeadless(storage) {
4674
5366
  }
4675
5367
  async function subscribeFeedSourceHeadless(storage, sourceId, options) {
4676
5368
  const notebookIds = options?.notebookIds && options.notebookIds.length > 0 ? options.notebookIds : null;
5369
+ const existingMap = await readFeedSubscriptionsMap(storage);
5370
+ const prev = existingMap[sourceId];
5371
+ const offlinePolicy = sourceId === "core" ? "offline-full" : options?.offlinePolicy ?? prev?.offlinePolicy ?? "index-only";
4677
5372
  await writeFeedSubscriptionEntry(storage, sourceId, {
5373
+ ...prev,
4678
5374
  subscribed: true,
4679
5375
  notebookIds,
5376
+ offlinePolicy,
5377
+ ...options?.autoSync !== void 0 ? { autoSync: options.autoSync } : {},
4680
5378
  hidden: false,
4681
5379
  ...options?.url ? { url: options.url } : {},
4682
5380
  ...options?.name ? { name: options.name } : {},
4683
5381
  updatedAt: Date.now()
4684
5382
  });
4685
- return { sourceId, subscribed: true, notebookIds };
5383
+ return { sourceId, subscribed: true, notebookIds, offlinePolicy };
4686
5384
  }
4687
5385
  async function unsubscribeFeedSourceHeadless(storage, sourceId) {
4688
5386
  if (sourceId === "core") {
4689
5387
  throw new Error("Core feed cannot be unsubscribed.");
4690
5388
  }
4691
- const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
4692
- const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
5389
+ const { deleted, preservedPinned } = await removeFeedSourceContentById(storage, sourceId);
5390
+ const existingMap = await readFeedSubscriptionsMap(storage);
5391
+ const prev = existingMap[sourceId];
4693
5392
  await writeFeedSubscriptionEntry(storage, sourceId, {
5393
+ ...prev,
4694
5394
  subscribed: false,
5395
+ autoSync: false,
4695
5396
  hidden: false,
4696
5397
  updatedAt: Date.now()
4697
5398
  });
4698
- return { sourceId, unsubscribed: true, deletedNotes };
5399
+ return { sourceId, unsubscribed: true, deletedNotes: deleted, deleted, preservedPinned };
4699
5400
  }
4700
5401
  async function deleteFeedSourceHeadless(storage, sourceId) {
4701
5402
  if (sourceId === "core") {
4702
5403
  throw new Error("Core feed cannot be deleted.");
4703
5404
  }
4704
- const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
4705
- const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
5405
+ const { deleted, preservedPinned } = await removeFeedSourceContentById(storage, sourceId);
5406
+ const existingMap = await readFeedSubscriptionsMap(storage);
5407
+ const prev = existingMap[sourceId];
4706
5408
  await writeFeedSubscriptionEntry(storage, sourceId, {
5409
+ ...prev,
4707
5410
  subscribed: false,
5411
+ autoSync: false,
4708
5412
  hidden: true,
4709
5413
  updatedAt: Date.now()
4710
5414
  });
4711
- return { sourceId, deleted: true, deletedNotes };
4712
- }
4713
- function mintUuid() {
5415
+ const registry = await readFeedRegistryHeadless(storage);
5416
+ const isCustom = registry.customFeeds.some((f) => f.id === sourceId);
5417
+ await writeFeedRegistryHeadless(storage, {
5418
+ customFeeds: isCustom ? registry.customFeeds.filter((f) => f.id !== sourceId) : registry.customFeeds,
5419
+ hiddenFeedIds: isCustom || registry.hiddenFeedIds.includes(sourceId) ? registry.hiddenFeedIds : [...registry.hiddenFeedIds, sourceId],
5420
+ updatedAt: Date.now(),
5421
+ migratedFromLocalStorage: registry.migratedFromLocalStorage
5422
+ });
5423
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
5424
+ await tx.readwrite("meta").delete(`catalog:${sourceId}`);
5425
+ });
5426
+ return { sourceId, deleted: true, deletedNotes: deleted, preservedPinned };
5427
+ }
5428
+ var RESERVED_SLUGS = new Set(BUILTIN_NOTEBOOKS.map((b) => b.slug));
5429
+ async function deleteUserNotebook(storage, notebookIdOrSlug) {
5430
+ const nbId = toNotebookId$1(notebookIdOrSlug);
5431
+ const slug = notebookSlugFromId$1(nbId);
5432
+ if (RESERVED_SLUGS.has(slug)) {
5433
+ throw new Error(`Notebook '${nbId}' is always present and cannot be deleted.`);
5434
+ }
5435
+ return storage.transaction(
5436
+ [
5437
+ "notes",
5438
+ "notebook_links",
5439
+ "attachments",
5440
+ "note_tags",
5441
+ "block_index",
5442
+ "block_efforts",
5443
+ "block_equipment",
5444
+ "page_notes",
5445
+ "meta"
5446
+ ],
5447
+ "readwrite",
5448
+ async (tx) => {
5449
+ const allNotes = await tx.readonly("notes").getAll();
5450
+ const links = await tx.readonly("notebook_links").getAllFromIndex("by-notebook", nbId).catch(() => []);
5451
+ const linkedNoteIds = new Set(
5452
+ links.filter((l) => l.targetKind === "note").map((l) => l.noteId)
5453
+ );
5454
+ let touchedMembers = 0;
5455
+ const noteWriter = tx.readwrite("notes");
5456
+ for (const note of allNotes) {
5457
+ if (isNotebookLanding(note)) continue;
5458
+ const hasSingle = note.notebookId === nbId;
5459
+ const hasMulti = (note.notebookIds ?? []).includes(nbId);
5460
+ const hasLink = linkedNoteIds.has(note.id);
5461
+ if (!hasSingle && !hasMulti && !hasLink) continue;
5462
+ const baseIds = note.notebookIds !== void 0 ? note.notebookIds : note.notebookId ? [note.notebookId] : [];
5463
+ const remaining = baseIds.map((id) => toNotebookId$1(id)).filter((id) => id !== nbId);
5464
+ const primaryUser = remaining.find(
5465
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
5466
+ );
5467
+ const { notebookId: _droppedSingle, notebookIds: _droppedMulti, ...rest } = note;
5468
+ await noteWriter.put({
5469
+ ...rest,
5470
+ notebookIds: remaining,
5471
+ ...primaryUser ? { notebookId: primaryUser } : {}
5472
+ });
5473
+ touchedMembers++;
5474
+ }
5475
+ if (links.length > 0) {
5476
+ const linkWriter = tx.readwrite("notebook_links");
5477
+ for (const link of links) {
5478
+ await linkWriter.delete(link.id);
5479
+ }
5480
+ }
5481
+ const landing = allNotes.find((n) => n.id === nbId);
5482
+ if (landing) {
5483
+ await noteWriter.delete(nbId);
5484
+ try {
5485
+ for (const att of await tx.readonly("attachments").getAllFromIndex("by-note", nbId)) {
5486
+ await tx.readwrite("attachments").delete(att.id);
5487
+ }
5488
+ for (const link of await tx.readonly("note_tags").getAllFromIndex("by-note", nbId)) {
5489
+ await tx.readwrite("note_tags").delete(link.id);
5490
+ }
5491
+ for (const row of await tx.readonly("block_index").getAllFromIndex("by-note", nbId)) {
5492
+ await tx.readwrite("block_index").delete(row.id);
5493
+ }
5494
+ for (const row of await tx.readonly("block_efforts").getAllFromIndex("by-note", nbId)) {
5495
+ await tx.readwrite("block_efforts").delete(row.id);
5496
+ }
5497
+ for (const row of await tx.readonly("block_equipment").getAllFromIndex("by-note", nbId)) {
5498
+ await tx.readwrite("block_equipment").delete(row.id);
5499
+ }
5500
+ for (const pn of await tx.readonly("page_notes").getAllFromIndex("by-note", nbId)) {
5501
+ await tx.readwrite("page_notes").delete(pn.id);
5502
+ }
5503
+ for (const nl of await tx.readonly("notebook_links").getAllFromIndex("by-note", nbId)) {
5504
+ await tx.readwrite("notebook_links").delete(nl.id);
5505
+ }
5506
+ } catch {
5507
+ }
5508
+ if (landing.seedOrigin === "seed" || landing.seedChunkId !== void 0 || landing.sourcePath !== void 0) {
5509
+ await tx.readwrite("meta").put({ key: userDeletedSeedKey(nbId), value: Date.now() });
5510
+ }
5511
+ }
5512
+ return {
5513
+ deleted: Boolean(landing || touchedMembers > 0 || links.length > 0),
5514
+ notebookId: nbId,
5515
+ slug
5516
+ };
5517
+ }
5518
+ );
5519
+ }
5520
+ function mintUuid() {
4714
5521
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
4715
5522
  return crypto.randomUUID();
4716
5523
  }
@@ -4728,6 +5535,16 @@ function utcCivilDateKey(epochMs) {
4728
5535
  const day = String(d.getDate()).padStart(2, "0");
4729
5536
  return `${y}-${m}-${day}`;
4730
5537
  }
5538
+ function parseRemoteNoteId(noteId) {
5539
+ if (!noteId.startsWith("remote:")) return { isRemote: false };
5540
+ const rest = noteId.slice("remote:".length);
5541
+ const sep = rest.indexOf(":");
5542
+ if (sep <= 0) return { isRemote: false };
5543
+ const feedId = rest.slice(0, sep);
5544
+ const uuid = rest.slice(sep + 1);
5545
+ if (!uuid) return { isRemote: false };
5546
+ return { isRemote: true, feedId, uuid };
5547
+ }
4731
5548
  function computeWodContentId(blockSource) {
4732
5549
  const sec = parseDocumentSections(blockSource, { registeredWidgets: KNOWN_SECTION_WIDGETS }).find(
4733
5550
  (s) => s.scriptBlock
@@ -4736,15 +5553,381 @@ function computeWodContentId(blockSource) {
4736
5553
  if (sec?.scriptBlock?.content) return blockContentId(sec.scriptBlock.content);
4737
5554
  return void 0;
4738
5555
  }
5556
+ function selectWorkoutBlock(sourceNote, ownershipKind, blockId, blockContentId5) {
5557
+ const sourceBlocks = Object.values(sourceNote.blocks ?? {});
5558
+ if (blockId) {
5559
+ const exact = sourceNote.blocks?.[blockId] ?? sourceBlocks.find((b) => b.id === blockId);
5560
+ if (exact) return exact;
5561
+ if (ownershipKind !== "user" && blockContentId5) {
5562
+ return sourceBlocks.find(
5563
+ (b) => b.kind === "wod" && computeWodContentId(sourceNote.rawContent.slice(b.from, b.to)) === blockContentId5
5564
+ );
5565
+ }
5566
+ return void 0;
5567
+ }
5568
+ return sourceBlocks.find((b) => b.kind === "wod");
5569
+ }
5570
+ function extractTitleFromMarkdown(rawContent, sourcePath) {
5571
+ const fm = readFrontmatterMeta(rawContent);
5572
+ if (typeof fm["title"] === "string" && fm["title"].trim()) return fm["title"].trim();
5573
+ const withoutFm = rawContent.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
5574
+ for (const line of withoutFm.split(/\r?\n/)) {
5575
+ const m = /^#\s+(.+)$/.exec(line);
5576
+ if (m?.[1]?.trim()) return m[1].trim();
5577
+ }
5578
+ if (sourcePath) {
5579
+ const stem = (sourcePath.split("/").at(-1) ?? "").replace(/\.md$/i, "");
5580
+ if (stem) return stem.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
5581
+ }
5582
+ return "Workout";
5583
+ }
5584
+ function parseFrontmatterDateEpoch(rawContent) {
5585
+ const fm = readFrontmatterMeta(rawContent);
5586
+ const rawDate = typeof fm["date"] === "string" ? fm["date"].trim() : "";
5587
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(rawDate);
5588
+ if (!match) return void 0;
5589
+ const ts = Date.parse(`${rawDate}T12:00:00Z`);
5590
+ if (!Number.isFinite(ts)) return void 0;
5591
+ const d = new Date(ts);
5592
+ if (d.getUTCMonth() !== Number(match[2]) - 1 || d.getUTCDate() !== Number(match[3])) {
5593
+ return void 0;
5594
+ }
5595
+ return ts;
5596
+ }
5597
+ function deriveNotebookSourceMeta(sourcePath, notebookSlug) {
5598
+ if (sourcePath?.startsWith("markdown/notebooks/")) {
5599
+ const rel = sourcePath.slice("markdown/notebooks/".length).replace(/\.md$/i, "");
5600
+ const segs = rel.split("/");
5601
+ const slug = segs[0];
5602
+ if (slug) {
5603
+ const isLanding = segs.length === 2 && segs[1].toLowerCase() === "readme";
5604
+ return {
5605
+ sourceId: isLanding ? `notebook:${slug}` : `notebook:${rel}`,
5606
+ seedChunkId: `notebook.${slug}`,
5607
+ sourceNotebookId: toNotebookId$1(slug)
5608
+ };
5609
+ }
5610
+ }
5611
+ if (notebookSlug) {
5612
+ const clean = notebookSlugFromId$1(notebookSlug);
5613
+ return {
5614
+ sourceId: `notebook:${clean}`,
5615
+ seedChunkId: `notebook.${clean}`,
5616
+ sourceNotebookId: toNotebookId$1(clean)
5617
+ };
5618
+ }
5619
+ return {};
5620
+ }
5621
+ function isEnvelope(val) {
5622
+ return typeof val === "object" && val !== null && !("rawContent" in val) && !("content" in val) && ("row" in val || "note" in val || "canonicalNoteId" in val);
5623
+ }
5624
+ function isBareSeedRow(val) {
5625
+ return typeof val === "object" && val !== null && "content" in val && "path" in val && !("rawContent" in val);
5626
+ }
5627
+ function normalizeRemoteResolution(requestedNoteId, resolution, now) {
5628
+ const parsedRemote = parseRemoteNoteId(requestedNoteId);
5629
+ let notePart;
5630
+ let seedRow;
5631
+ let envelopeFeedId;
5632
+ let envelopeNbSlug;
5633
+ let envelopeCanonicalId;
5634
+ let recordMeta;
5635
+ if (isEnvelope(resolution)) {
5636
+ notePart = resolution.note;
5637
+ seedRow = resolution.row;
5638
+ envelopeFeedId = resolution.feedId;
5639
+ envelopeNbSlug = resolution.notebookSlug;
5640
+ envelopeCanonicalId = resolution.canonicalNoteId;
5641
+ recordMeta = resolution.record;
5642
+ } else if (isBareSeedRow(resolution)) {
5643
+ seedRow = resolution;
5644
+ } else {
5645
+ notePart = resolution;
5646
+ if ("seedRow" in resolution && resolution.seedRow) {
5647
+ seedRow = resolution.seedRow;
5648
+ }
5649
+ }
5650
+ const rawContent = notePart?.rawContent ?? seedRow?.content ?? "";
5651
+ if (!rawContent) {
5652
+ throw new Error(`Resolved remote workout '${requestedNoteId}' has no Markdown content.`);
5653
+ }
5654
+ const canonicalNoteId = envelopeCanonicalId ?? (notePart?.id && !notePart.id.startsWith("remote:") ? notePart.id : void 0) ?? seedRow?.uuid ?? recordMeta?.uuid ?? (parsedRemote.isRemote ? parsedRemote.uuid : requestedNoteId);
5655
+ const sourcePath = notePart?.sourcePath ?? seedRow?.path ?? recordMeta?.path;
5656
+ const pathDerived = deriveNotebookSourceMeta(sourcePath, envelopeNbSlug);
5657
+ const feedSourceId = notePart?.feedSourceId ?? envelopeFeedId ?? (parsedRemote.isRemote ? parsedRemote.feedId : void 0);
5658
+ const sourceNotebookId = notePart?.sourceNotebookId ?? notePart?.provenance?.sourceNotebookId ?? pathDerived.sourceNotebookId ?? (notePart ? notebookOfItem(notePart) : void 0);
5659
+ const sourceId = notePart?.sourceId ?? pathDerived.sourceId;
5660
+ const seedChunkId = notePart?.seedChunkId ?? pathDerived.seedChunkId;
5661
+ const seedVersion = notePart?.seedVersion ?? seedRow?.version ?? recordMeta?.version ?? 1;
5662
+ const seedCommit = notePart?.seedCommit ?? seedRow?.commit ?? recordMeta?.commit;
5663
+ const date = notePart?.date ?? recordMeta?.date ?? parseFrontmatterDateEpoch(rawContent);
5664
+ const title = notePart?.title?.trim() || recordMeta?.title?.trim() || seedRow?.blockIndex?.[0]?.noteTitle?.trim() || extractTitleFromMarkdown(rawContent, sourcePath);
5665
+ const rawBlocks = notePart?.blocks && Object.keys(notePart.blocks).length > 0 ? notePart.blocks : seedRow?.blocks && Object.keys(seedRow.blocks).length > 0 ? seedRow.blocks : void 0;
5666
+ let ordinal = 0;
5667
+ const blocks = rawBlocks ? Object.fromEntries(
5668
+ Object.entries(rawBlocks).map(([k, b]) => [
5669
+ k,
5670
+ { ...b, version: b.version || 1, sourceRevision: 1 }
5671
+ ])
5672
+ ) : reconcileNoteBlocks(rawContent, {
5673
+ sourceRevision: 1,
5674
+ registeredWidgets: KNOWN_SECTION_WIDGETS,
5675
+ createId: () => `blk-${canonicalNoteId.slice(0, 8)}-${ordinal++}`
5676
+ });
5677
+ return {
5678
+ canonicalNoteId,
5679
+ title,
5680
+ rawContent,
5681
+ blocks,
5682
+ ...date !== void 0 ? { date } : {},
5683
+ createdAt: notePart?.createdAt ?? date ?? now,
5684
+ ...notePart?.tags?.length ? { tags: notePart.tags.filter((t) => t !== "preview:remote") } : {},
5685
+ type: notePart?.type ?? "note",
5686
+ ...sourceId ? { sourceId } : {},
5687
+ ...sourcePath ? { sourcePath } : {},
5688
+ seedOrigin: notePart?.seedOrigin ?? "seed",
5689
+ feedOrigin: notePart?.feedOrigin ?? "feed",
5690
+ ...feedSourceId ? { feedSourceId } : {},
5691
+ seedVersion,
5692
+ ...seedChunkId ? { seedChunkId } : {},
5693
+ ...seedCommit ? { seedCommit } : {},
5694
+ ...sourceNotebookId ? { sourceNotebookId } : {},
5695
+ upstreamStatus: notePart?.upstreamStatus ?? "live",
5696
+ ...seedRow ? { seedRow } : {}
5697
+ };
5698
+ }
5699
+ async function ensureNoteBlockRevisionsAndIndexInTx(tx, note, now, seedRow) {
5700
+ const revStore = tx.readwrite("block_revisions");
5701
+ const idxStore = tx.readwrite("block_index");
5702
+ const blockList = Object.values(note.blocks ?? {}).sort((a, b) => a.from - b.from);
5703
+ const isStatic = note.seedOrigin === "seed" || note.feedOrigin === "feed" || void 0;
5704
+ const resolvedNb = notebookOfItem(note);
5705
+ const missingRevs = [];
5706
+ const missingIdx = [];
5707
+ const existingIdxRows = await idxStore.getAllFromIndex("by-note", note.id);
5708
+ const existingIdxIds = new Set(existingIdxRows.map((r) => r.id));
5709
+ for (const [pos, b] of blockList.entries()) {
5710
+ const slice = note.rawContent.slice(b.from, b.to);
5711
+ const existingRev = await revStore.get([note.id, b.id, b.version]);
5712
+ if (!existingRev) {
5713
+ missingRevs.push({
5714
+ noteId: note.id,
5715
+ blockId: b.id,
5716
+ version: b.version,
5717
+ kind: b.kind,
5718
+ rawContent: slice,
5719
+ savedAt: now,
5720
+ ...b.dialect ? { dialect: b.dialect } : {},
5721
+ ...b.sport ? { sport: b.sport } : {}
5722
+ });
5723
+ }
5724
+ const rowId = `${note.id}:${b.id}`;
5725
+ if (!existingIdxIds.has(rowId)) {
5726
+ const cid = b.kind === "wod" ? computeWodContentId(slice) : void 0;
5727
+ missingIdx.push({
5728
+ id: rowId,
5729
+ noteId: note.id,
5730
+ blockId: b.id,
5731
+ blockVersion: b.version,
5732
+ sourceRevision: note.sourceRevision,
5733
+ from: b.from,
5734
+ to: b.to,
5735
+ position: pos,
5736
+ dataType: b.kind,
5737
+ ...cid ? { blockContentId: cid } : {},
5738
+ rawContent: slice,
5739
+ noteTitle: note.title,
5740
+ createdAt: note.date ?? note.createdAt ?? now,
5741
+ ...isStatic ? { isStatic: true } : {},
5742
+ ...note.sourceId ? { sourceId: note.sourceId } : {},
5743
+ ...note.sourcePath ? { sourcePath: note.sourcePath } : {},
5744
+ ...resolvedNb ? { notebookId: resolvedNb } : {}
5745
+ });
5746
+ }
5747
+ }
5748
+ if (missingRevs.length > 0) await revStore.putMany(missingRevs);
5749
+ if (missingIdx.length > 0) await idxStore.putMany(missingIdx);
5750
+ if (seedRow?.blockEfforts?.length) {
5751
+ try {
5752
+ const effortStore = tx.readwrite("block_efforts");
5753
+ const rows = seedRow.blockEfforts.map((eff) => ({
5754
+ ...eff,
5755
+ id: `${note.id}:${eff.blockId}:${eff.effortSlug}`,
5756
+ noteId: note.id,
5757
+ ...isStatic ? { isStatic: true } : {}
5758
+ }));
5759
+ if (rows.length > 0) await effortStore.putMany(rows);
5760
+ } catch {
5761
+ }
5762
+ }
5763
+ if (seedRow?.blockEquipment?.length) {
5764
+ try {
5765
+ const eqStore = tx.readwrite("block_equipment");
5766
+ const rows = seedRow.blockEquipment.map((eq) => ({
5767
+ ...eq,
5768
+ id: `${note.id}:${eq.blockId}:${eq.equipmentSlug}`,
5769
+ noteId: note.id,
5770
+ ...isStatic ? { isStatic: true } : {}
5771
+ }));
5772
+ if (rows.length > 0) await eqStore.putMany(rows);
5773
+ } catch {
5774
+ }
5775
+ }
5776
+ }
5777
+ async function getOrCreateJournalPageInTx(tx, journalDate, now) {
5778
+ let existingPages;
5779
+ try {
5780
+ existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
5781
+ } catch {
5782
+ existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
5783
+ }
5784
+ if (existingPages[0]) return existingPages[0];
5785
+ const page = {
5786
+ id: mintUuid(),
5787
+ date: journalDate,
5788
+ title: journalDate,
5789
+ createdAt: now
5790
+ };
5791
+ await tx.readwrite("page").put(page);
5792
+ return page;
5793
+ }
5794
+ function promoteExternalNoteInPlace(existing, ownership, now, requestedRetention = "session-pinned") {
5795
+ const nextRetention = existing.retention === "session-pinned" || requestedRetention === "session-pinned" ? "session-pinned" : "schedule-pinned";
5796
+ const nextUpstreamStatus = existing.upstreamStatus ?? "live";
5797
+ const nextProvenance = existing.provenance ?? buildNoteProvenance(existing, ownership.sourceNotebookId ?? notebookOfItem(existing), now);
5798
+ const changed = existing.retention !== nextRetention || existing.upstreamStatus !== nextUpstreamStatus || !existing.provenance;
5799
+ if (!changed) return { updated: existing, changed: false };
5800
+ return {
5801
+ updated: {
5802
+ ...existing,
5803
+ retention: nextRetention,
5804
+ upstreamStatus: nextUpstreamStatus,
5805
+ provenance: nextProvenance
5806
+ },
5807
+ changed: true
5808
+ };
5809
+ }
5810
+ async function ensurePinnedExternalWorkout(storage, input) {
5811
+ const now = input.now ?? Date.now();
5812
+ const parsedRemote = parseRemoteNoteId(input.noteId);
5813
+ const initialCandidateId = parsedRemote.isRemote ? parsedRemote.uuid : input.noteId;
5814
+ let preloaded = await storage.readonly("notes").get(initialCandidateId) ?? (input.noteId !== initialCandidateId ? await storage.readonly("notes").get(input.noteId) : void 0);
5815
+ let materialized;
5816
+ if (!preloaded) {
5817
+ const resolved = input.remotePayload ?? (input.resolveRemoteWorkout ? await input.resolveRemoteWorkout(input.noteId) : void 0);
5818
+ if (!resolved) {
5819
+ throw new Error(`Note not found: ${input.noteId}`);
5820
+ }
5821
+ materialized = normalizeRemoteResolution(input.noteId, resolved, now);
5822
+ preloaded = await storage.readonly("notes").get(materialized.canonicalNoteId);
5823
+ }
5824
+ return storage.transaction(
5825
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment"],
5826
+ "readwrite",
5827
+ async (tx) => {
5828
+ const targetId = materialized?.canonicalNoteId ?? preloaded?.id ?? initialCandidateId;
5829
+ const existing = await tx.readonly("notes").get(targetId);
5830
+ if (existing) {
5831
+ const ownership2 = resolveNoteOwnership(
5832
+ existing,
5833
+ notebookOriginOfItem(existing),
5834
+ notebookOfItem(existing)
5835
+ );
5836
+ if (ownership2.kind === "user") {
5837
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, existing, now);
5838
+ return {
5839
+ note: existing,
5840
+ created: false,
5841
+ promotedFromLocal: false,
5842
+ ownership: ownership2
5843
+ };
5844
+ }
5845
+ const { updated, changed } = promoteExternalNoteInPlace(
5846
+ existing,
5847
+ ownership2,
5848
+ now,
5849
+ input.retention ?? "session-pinned"
5850
+ );
5851
+ if (changed) {
5852
+ await tx.readwrite("notes").put(updated);
5853
+ }
5854
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, updated, now);
5855
+ const nextOwnership = resolveNoteOwnership(
5856
+ updated,
5857
+ notebookOriginOfItem(updated),
5858
+ notebookOfItem(updated)
5859
+ );
5860
+ return {
5861
+ note: updated,
5862
+ created: false,
5863
+ promotedFromLocal: changed,
5864
+ ownership: nextOwnership
5865
+ };
5866
+ }
5867
+ if (!materialized) {
5868
+ throw new Error(`Note not found: ${input.noteId}`);
5869
+ }
5870
+ const newNote = {
5871
+ id: materialized.canonicalNoteId,
5872
+ title: materialized.title,
5873
+ rawContent: materialized.rawContent,
5874
+ sourceRevision: 1,
5875
+ blocks: materialized.blocks,
5876
+ ...materialized.date !== void 0 ? { date: materialized.date } : {},
5877
+ createdAt: materialized.createdAt,
5878
+ type: materialized.type,
5879
+ ...materialized.sourceId ? { sourceId: materialized.sourceId } : {},
5880
+ ...materialized.tags?.length ? { tags: materialized.tags } : {},
5881
+ seedOrigin: materialized.seedOrigin,
5882
+ seedVersion: materialized.seedVersion,
5883
+ ...materialized.seedChunkId ? { seedChunkId: materialized.seedChunkId } : {},
5884
+ ...materialized.feedOrigin ? { feedOrigin: materialized.feedOrigin } : {},
5885
+ ...materialized.feedSourceId ? { feedSourceId: materialized.feedSourceId } : {},
5886
+ ...materialized.sourcePath ? { sourcePath: materialized.sourcePath } : {},
5887
+ ...materialized.seedCommit ? { seedCommit: materialized.seedCommit } : {},
5888
+ retention: input.retention ?? "session-pinned",
5889
+ upstreamStatus: materialized.upstreamStatus,
5890
+ provenance: {
5891
+ sourceNoteId: materialized.canonicalNoteId,
5892
+ sourceVersion: materialized.seedVersion,
5893
+ ...materialized.seedCommit ? { sourceCommit: materialized.seedCommit } : {},
5894
+ ...materialized.feedSourceId ? { feedSourceId: materialized.feedSourceId } : {},
5895
+ ...materialized.sourceNotebookId ? { sourceNotebookId: materialized.sourceNotebookId } : {},
5896
+ ...materialized.sourcePath ? { sourcePath: materialized.sourcePath } : {},
5897
+ clonedAt: now
5898
+ }
5899
+ };
5900
+ await tx.readwrite("notes").put(newNote);
5901
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, newNote, now, materialized.seedRow);
5902
+ const ownership = resolveNoteOwnership(
5903
+ newNote,
5904
+ notebookOriginOfItem(newNote),
5905
+ notebookOfItem(newNote)
5906
+ );
5907
+ return {
5908
+ note: newNote,
5909
+ created: true,
5910
+ promotedFromLocal: false,
5911
+ ownership
5912
+ };
5913
+ }
5914
+ );
5915
+ }
4739
5916
  async function prepareJournalSessionRun(storage, input) {
4740
5917
  const startedAt = input.startedAt ?? Date.now();
4741
5918
  const sessionId = input.sessionId ?? mintUuid();
4742
5919
  const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
5920
+ const pinned = await ensurePinnedExternalWorkout(storage, {
5921
+ noteId: input.noteId,
5922
+ remotePayload: input.remotePayload,
5923
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
5924
+ now: startedAt
5925
+ });
4743
5926
  return storage.transaction(
4744
- ["notes", "block_revisions", "block_index", "sessions", "page", "page_notes", "notebook_links"],
5927
+ ["notes", "block_revisions", "block_index", "sessions", "page", "notebook_links"],
4745
5928
  "readwrite",
4746
5929
  async (tx) => {
4747
- const sourceNote = await tx.readonly("notes").get(input.noteId);
5930
+ const sourceNote = await tx.readonly("notes").get(pinned.note.id);
4748
5931
  if (!sourceNote) {
4749
5932
  throw new Error(`Note not found: ${input.noteId}`);
4750
5933
  }
@@ -4752,113 +5935,46 @@ async function prepareJournalSessionRun(storage, input) {
4752
5935
  if (existingSession) {
4753
5936
  throw new Error(`Session already exists: ${sessionId}`);
4754
5937
  }
4755
- const sourceBlocks = Object.values(sourceNote.blocks);
4756
- const selectedSourceBlock = input.blockId ? sourceNote.blocks[input.blockId] ?? sourceBlocks.find((b) => b.id === input.blockId) : sourceBlocks.find((b) => b.kind === "wod");
5938
+ const nbOrigin = notebookOriginOfItem(sourceNote);
5939
+ const resolvedNb = notebookOfItem(sourceNote);
5940
+ const ownership = resolveNoteOwnership(sourceNote, nbOrigin, resolvedNb);
5941
+ const selectedSourceBlock = selectWorkoutBlock(
5942
+ sourceNote,
5943
+ ownership.kind,
5944
+ input.blockId,
5945
+ input.blockContentId
5946
+ );
4757
5947
  if (!selectedSourceBlock || selectedSourceBlock.kind !== "wod") {
4758
5948
  throw new Error(`Selected workout block is unavailable on Note '${input.noteId}'.`);
4759
5949
  }
4760
- const nbOrigin = notebookOriginOfItem(sourceNote);
4761
- const resolvedNb = notebookOfItem(sourceNote);
4762
- const editable = isNoteEditable(sourceNote, nbOrigin, resolvedNb);
4763
- if (!editable) {
4764
- const clonedNoteId = mintUuid();
4765
- let ordinal = 0;
4766
- const clonedBlocks = reconcileNoteBlocks(sourceNote.rawContent, {
4767
- sourceRevision: 1,
4768
- registeredWidgets: KNOWN_SECTION_WIDGETS,
4769
- createId: () => `blk-${clonedNoteId.slice(0, 8)}-${ordinal++}`
4770
- });
4771
- const clonedBlockList = Object.values(clonedBlocks);
4772
- const mappedBlock = clonedBlockList.find(
4773
- (b) => b.kind === "wod" && b.from === selectedSourceBlock.from && b.to === selectedSourceBlock.to
4774
- ) ?? clonedBlockList.find((b) => b.kind === "wod");
4775
- if (!mappedBlock) {
4776
- throw new Error("Cloned Journal Note contains no runnable workout block.");
4777
- }
4778
- const revisions = [];
4779
- const projections = [];
4780
- let pinnedRevision;
4781
- for (const [pos, b] of clonedBlockList.entries()) {
4782
- const slice = sourceNote.rawContent.slice(b.from, b.to);
4783
- const rev = {
4784
- noteId: clonedNoteId,
4785
- blockId: b.id,
4786
- version: 1,
4787
- kind: b.kind,
4788
- rawContent: slice,
4789
- savedAt: startedAt,
4790
- ...b.dialect ? { dialect: b.dialect } : {},
4791
- ...b.sport ? { sport: b.sport } : {}
4792
- };
4793
- revisions.push(rev);
4794
- if (b.id === mappedBlock.id) pinnedRevision = rev;
4795
- const cid3 = b.kind === "wod" ? computeWodContentId(slice) : void 0;
4796
- projections.push({
4797
- id: `${clonedNoteId}:${b.id}`,
4798
- noteId: clonedNoteId,
4799
- blockId: b.id,
4800
- blockVersion: 1,
4801
- sourceRevision: 1,
4802
- from: b.from,
4803
- to: b.to,
4804
- position: pos,
4805
- dataType: b.kind,
4806
- ...cid3 ? { blockContentId: cid3 } : {},
4807
- rawContent: slice,
4808
- noteTitle: sourceNote.title,
4809
- createdAt: startedAt,
4810
- isStatic: false,
4811
- notebookId: "notebook/journal"
4812
- });
4813
- }
4814
- const provenance = buildNoteProvenance(sourceNote, resolvedNb, startedAt);
4815
- const dateEpoch = Date.parse(`${journalDate}T12:00:00Z`);
4816
- const clonedNote = {
4817
- id: clonedNoteId,
4818
- title: sourceNote.title,
4819
- rawContent: sourceNote.rawContent,
4820
- sourceRevision: 1,
4821
- blocks: clonedBlocks,
4822
- ...Number.isFinite(dateEpoch) ? { date: dateEpoch } : {},
4823
- createdAt: startedAt,
4824
- type: "journal",
4825
- sourceId: sourceNote.id,
4826
- notebookIds: ["notebook/journal"],
4827
- provenance,
4828
- ...sourceNote.tags?.length ? { tags: [...sourceNote.tags] } : {},
4829
- seedOrigin: "user"
4830
- };
4831
- let existingPages;
4832
- try {
4833
- existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
4834
- } catch {
4835
- existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
4836
- }
4837
- let targetPage = existingPages[0];
4838
- if (!targetPage) {
4839
- targetPage = {
4840
- id: mintUuid(),
4841
- date: journalDate,
4842
- title: journalDate,
4843
- createdAt: startedAt
4844
- };
4845
- await tx.readwrite("page").put(targetPage);
4846
- }
4847
- const pageNote = {
4848
- id: mintUuid(),
4849
- pageId: targetPage.id,
4850
- noteId: clonedNoteId,
4851
- createdAt: startedAt
5950
+ const targetPage = await getOrCreateJournalPageInTx(tx, journalDate, startedAt);
5951
+ let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
5952
+ if (!revision) {
5953
+ revision = {
5954
+ noteId: sourceNote.id,
5955
+ blockId: selectedSourceBlock.id,
5956
+ version: selectedSourceBlock.version,
5957
+ kind: selectedSourceBlock.kind,
5958
+ rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
5959
+ savedAt: startedAt,
5960
+ ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
5961
+ ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
4852
5962
  };
4853
- const cid2 = computeWodContentId(pinnedRevision.rawContent);
5963
+ await tx.readwrite("block_revisions").put(revision);
5964
+ }
5965
+ const cid = computeWodContentId(revision.rawContent);
5966
+ if (ownership.kind !== "user") {
4854
5967
  const session2 = {
4855
5968
  id: sessionId,
4856
- noteId: clonedNoteId,
4857
- blockId: mappedBlock.id,
4858
- blockVersion: 1,
4859
- ...cid2 ? { blockContentId: cid2 } : {},
5969
+ noteId: sourceNote.id,
5970
+ noteSourceRevision: sourceNote.sourceRevision,
5971
+ blockId: selectedSourceBlock.id,
5972
+ blockVersion: revision.version,
5973
+ ...cid ? { blockContentId: cid } : {},
4860
5974
  origin: input.origin ?? "journal",
4861
5975
  pageId: targetPage.id,
5976
+ sessionDate: journalDate,
5977
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
4862
5978
  status: "in-progress",
4863
5979
  startTime: startedAt,
4864
5980
  endTime: startedAt,
@@ -4867,74 +5983,49 @@ async function prepareJournalSessionRun(storage, input) {
4867
5983
  createdAt: startedAt,
4868
5984
  notebookIds: ["notebook/journal"]
4869
5985
  };
4870
- const links2 = [
4871
- {
4872
- id: makeNotebookLinkId("notebook/journal", "note", clonedNoteId),
4873
- notebookId: "notebook/journal",
4874
- targetKind: "note",
4875
- targetId: clonedNoteId,
4876
- noteId: clonedNoteId,
4877
- createdAt: startedAt
4878
- }
4879
- ];
4880
- await tx.readwrite("notes").put(clonedNote);
4881
- if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
4882
- if (projections.length > 0) await tx.readwrite("block_index").putMany(projections);
4883
- await tx.readwrite("page_notes").put(pageNote);
4884
- await tx.readwrite("notebook_links").putMany(links2);
4885
5986
  return {
4886
- note: clonedNote,
4887
- revision: pinnedRevision,
5987
+ note: sourceNote,
5988
+ revision,
4888
5989
  session: session2,
4889
- clonedFromReadOnly: true,
5990
+ clonedFromReadOnly: false,
5991
+ pinnedExternalWorkout: true,
4890
5992
  upstreamNoteId: sourceNote.id
4891
5993
  };
4892
5994
  }
4893
5995
  const isPlayground = sourceNote.type === "playground" || sourceNote.sourceId === "playground" || sourceNote.notebookId === "notebook/playground";
4894
- const baseNotebooks = isPlayground ? ["notebook/journal", "notebook/playground"] : ["notebook/journal"];
4895
- const mergedNotebooks = [
5996
+ const currentNotebooks = [
4896
5997
  .../* @__PURE__ */ new Set([
4897
- ...baseNotebooks,
5998
+ ...isPlayground ? ["notebook/playground"] : [],
4898
5999
  ...sourceNote.notebookIds ?? [],
4899
6000
  ...sourceNote.notebookId ? [sourceNote.notebookId] : []
4900
6001
  ])
4901
6002
  ];
4902
- const updatedNote = JSON.stringify(sourceNote.notebookIds) === JSON.stringify(mergedNotebooks) ? sourceNote : { ...sourceNote, notebookIds: mergedNotebooks };
6003
+ const updatedNote = sourceNote.notebookIds !== void 0 && JSON.stringify(sourceNote.notebookIds) === JSON.stringify(currentNotebooks) ? sourceNote : { ...sourceNote, notebookIds: currentNotebooks };
4903
6004
  if (updatedNote !== sourceNote) {
4904
6005
  await tx.readwrite("notes").put(updatedNote);
4905
6006
  }
4906
- let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
4907
- if (!revision) {
4908
- revision = {
4909
- noteId: sourceNote.id,
4910
- blockId: selectedSourceBlock.id,
4911
- version: selectedSourceBlock.version,
4912
- kind: selectedSourceBlock.kind,
4913
- rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
4914
- savedAt: startedAt,
4915
- ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
4916
- ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
4917
- };
4918
- await tx.readwrite("block_revisions").put(revision);
4919
- }
4920
- const cid = computeWodContentId(revision.rawContent);
4921
6007
  const effectiveOrigin = input.origin ?? (isPlayground ? "playground" : "journal");
6008
+ const sessionNotebooks = currentNotebooks.length > 0 ? [...currentNotebooks] : ["notebook/journal"];
4922
6009
  const session = {
4923
6010
  id: sessionId,
4924
6011
  noteId: sourceNote.id,
6012
+ noteSourceRevision: sourceNote.sourceRevision,
4925
6013
  blockId: selectedSourceBlock.id,
4926
6014
  blockVersion: revision.version,
4927
6015
  ...cid ? { blockContentId: cid } : {},
4928
6016
  origin: effectiveOrigin,
6017
+ pageId: targetPage.id,
6018
+ sessionDate: journalDate,
6019
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
4929
6020
  status: "in-progress",
4930
6021
  startTime: startedAt,
4931
6022
  endTime: startedAt,
4932
6023
  duration: 0,
4933
6024
  completed: false,
4934
6025
  createdAt: startedAt,
4935
- notebookIds: [...baseNotebooks]
6026
+ notebookIds: sessionNotebooks
4936
6027
  };
4937
- const links = mergedNotebooks.map((nbId) => ({
6028
+ const links = currentNotebooks.map((nbId) => ({
4938
6029
  id: makeNotebookLinkId(nbId, "note", sourceNote.id),
4939
6030
  notebookId: nbId,
4940
6031
  targetKind: "note",
@@ -4942,23 +6033,284 @@ async function prepareJournalSessionRun(storage, input) {
4942
6033
  noteId: sourceNote.id,
4943
6034
  createdAt: startedAt
4944
6035
  }));
4945
- await tx.readwrite("notebook_links").putMany(links);
6036
+ if (links.length > 0) {
6037
+ await tx.readwrite("notebook_links").putMany(links);
6038
+ }
4946
6039
  return {
4947
6040
  note: updatedNote,
4948
6041
  revision,
4949
6042
  session,
4950
- clonedFromReadOnly: false
6043
+ clonedFromReadOnly: false,
6044
+ pinnedExternalWorkout: false
6045
+ };
6046
+ }
6047
+ );
6048
+ }
6049
+ async function logSessionAgainstExternalWorkout(storage, input) {
6050
+ const startedAt = input.startedAt ?? Date.now();
6051
+ const duration = Math.max(0, input.durationMs ?? (input.endedAt !== void 0 ? input.endedAt - startedAt : 0));
6052
+ const endTime = input.endedAt ?? startedAt + duration;
6053
+ const sessionId = input.sessionId ?? mintUuid();
6054
+ const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
6055
+ const pinnedResult = await ensurePinnedExternalWorkout(storage, {
6056
+ noteId: input.noteId,
6057
+ remotePayload: input.remotePayload,
6058
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
6059
+ now: startedAt
6060
+ });
6061
+ return storage.transaction(
6062
+ ["notes", "block_revisions", "sessions", "events", "page", "notebook_links", "schedule_items"],
6063
+ "readwrite",
6064
+ async (tx) => {
6065
+ const note = await tx.readonly("notes").get(pinnedResult.note.id);
6066
+ if (!note) {
6067
+ throw new Error(`Pinned workout note disappeared: ${pinnedResult.note.id}`);
6068
+ }
6069
+ const existingSession = await tx.readonly("sessions").get(sessionId);
6070
+ if (existingSession) {
6071
+ throw new Error(`Session already exists: ${sessionId}`);
6072
+ }
6073
+ const ownership = resolveNoteOwnership(note, notebookOriginOfItem(note), notebookOfItem(note));
6074
+ const selectedBlock = selectWorkoutBlock(
6075
+ note,
6076
+ ownership.kind,
6077
+ input.blockId,
6078
+ input.blockContentId
6079
+ );
6080
+ if (!selectedBlock || selectedBlock.kind !== "wod") {
6081
+ throw new Error(`Selected workout block is unavailable on Note '${note.id}'.`);
6082
+ }
6083
+ let revision = await tx.readonly("block_revisions").get([note.id, selectedBlock.id, selectedBlock.version]);
6084
+ if (!revision) {
6085
+ revision = {
6086
+ noteId: note.id,
6087
+ blockId: selectedBlock.id,
6088
+ version: selectedBlock.version,
6089
+ kind: selectedBlock.kind,
6090
+ rawContent: note.rawContent.slice(selectedBlock.from, selectedBlock.to),
6091
+ savedAt: startedAt,
6092
+ ...selectedBlock.dialect ? { dialect: selectedBlock.dialect } : {},
6093
+ ...selectedBlock.sport ? { sport: selectedBlock.sport } : {}
6094
+ };
6095
+ await tx.readwrite("block_revisions").put(revision);
6096
+ }
6097
+ const page = await getOrCreateJournalPageInTx(tx, journalDate, startedAt);
6098
+ const cid = computeWodContentId(revision.rawContent);
6099
+ const session = {
6100
+ id: sessionId,
6101
+ noteId: note.id,
6102
+ noteSourceRevision: note.sourceRevision,
6103
+ blockId: selectedBlock.id,
6104
+ blockVersion: revision.version,
6105
+ ...cid ? { blockContentId: cid } : {},
6106
+ origin: input.origin ?? "journal",
6107
+ pageId: page.id,
6108
+ sessionDate: journalDate,
6109
+ ...input.scheduleItemId ? { scheduleItemId: input.scheduleItemId } : {},
6110
+ status: "completed",
6111
+ startTime: startedAt,
6112
+ endTime,
6113
+ duration,
6114
+ ...input.roundsCompleted !== void 0 ? { roundsCompleted: input.roundsCompleted } : {},
6115
+ ...input.totalRounds !== void 0 ? { totalRounds: input.totalRounds } : {},
6116
+ ...input.repsCompleted !== void 0 ? { repsCompleted: input.repsCompleted } : {},
6117
+ completed: input.completed ?? true,
6118
+ createdAt: endTime,
6119
+ ...input.public !== void 0 ? { public: input.public } : {},
6120
+ notebookIds: ["notebook/journal"]
6121
+ };
6122
+ const links = [
6123
+ {
6124
+ id: makeNotebookLinkId("notebook/journal", "session", session.id),
6125
+ notebookId: "notebook/journal",
6126
+ targetKind: "session",
6127
+ targetId: session.id,
6128
+ noteId: note.id,
6129
+ createdAt: endTime
6130
+ }
6131
+ ];
6132
+ const normalizedEvents = (input.events ?? []).map((ev) => ({
6133
+ ...ev,
6134
+ resultId: session.id,
6135
+ noteId: note.id,
6136
+ blockId: selectedBlock.id,
6137
+ blockVersion: revision.version,
6138
+ ...cid ? { blockContentId: cid } : {},
6139
+ pageId: page.id
6140
+ }));
6141
+ await tx.readwrite("sessions").put(session);
6142
+ if (input.scheduleItemId) {
6143
+ const schedItem = await tx.readonly("schedule_items").get(input.scheduleItemId);
6144
+ if (schedItem && schedItem.status !== "completed") {
6145
+ await tx.readwrite("schedule_items").put({
6146
+ ...schedItem,
6147
+ status: "completed",
6148
+ updatedAt: endTime
6149
+ });
6150
+ }
6151
+ }
6152
+ await tx.readwrite("notebook_links").putMany(links);
6153
+ if (normalizedEvents.length > 0) {
6154
+ await tx.readwrite("events").putMany(normalizedEvents);
6155
+ }
6156
+ return {
6157
+ note,
6158
+ revision,
6159
+ session,
6160
+ page,
6161
+ links,
6162
+ events: normalizedEvents,
6163
+ pinnedResult
4951
6164
  };
4952
6165
  }
4953
6166
  );
4954
6167
  }
6168
+ async function forkNoteToUserNotebook(storage, sourceNoteId, targetNotebookId, options = {}) {
6169
+ const targetNb = toNotebookId$1(targetNotebookId);
6170
+ if (isSystemReadOnlyNotebook(targetNb)) {
6171
+ throw new Error(`Target notebook '${targetNb}' is read-only and cannot receive forked notes.`);
6172
+ }
6173
+ const now = options.now ?? Date.now();
6174
+ const parsedRemote = parseRemoteNoteId(sourceNoteId);
6175
+ const candidateId = parsedRemote.isRemote ? parsedRemote.uuid : sourceNoteId;
6176
+ let sourceNote = await storage.readonly("notes").get(candidateId) ?? (sourceNoteId !== candidateId ? await storage.readonly("notes").get(sourceNoteId) : void 0);
6177
+ let fallbackMat;
6178
+ if (!sourceNote) {
6179
+ const resolved = options.remotePayload ?? (options.resolveRemoteWorkout ? await options.resolveRemoteWorkout(sourceNoteId) : void 0);
6180
+ if (!resolved) {
6181
+ throw new Error(`Source Note not found: ${sourceNoteId}`);
6182
+ }
6183
+ fallbackMat = normalizeRemoteResolution(sourceNoteId, resolved, now);
6184
+ sourceNote = await storage.readonly("notes").get(fallbackMat.canonicalNoteId);
6185
+ }
6186
+ const sourceIdForProvenance = sourceNote?.id ?? fallbackMat.canonicalNoteId;
6187
+ const sourceTitle = options.title?.trim() || sourceNote?.title || fallbackMat.title;
6188
+ const rawContent = sourceNote?.rawContent ?? fallbackMat.rawContent;
6189
+ const sourceTags = sourceNote?.tags ?? fallbackMat?.tags;
6190
+ const sourceNb = sourceNote ? notebookOfItem(sourceNote) : fallbackMat?.sourceNotebookId;
6191
+ const provenance = sourceNote ? buildNoteProvenance(sourceNote, sourceNb, now) : {
6192
+ sourceNoteId: sourceIdForProvenance,
6193
+ sourceVersion: fallbackMat.seedVersion,
6194
+ ...fallbackMat.seedCommit ? { sourceCommit: fallbackMat.seedCommit } : {},
6195
+ ...fallbackMat.feedSourceId ? { feedSourceId: fallbackMat.feedSourceId } : {},
6196
+ ...sourceNb ? { sourceNotebookId: sourceNb } : {},
6197
+ ...fallbackMat.sourcePath ? { sourcePath: fallbackMat.sourcePath } : {},
6198
+ clonedAt: now
6199
+ };
6200
+ const forkedId = mintUuid();
6201
+ let ordinal = 0;
6202
+ const blocks = reconcileNoteBlocks(rawContent, {
6203
+ sourceRevision: 1,
6204
+ registeredWidgets: KNOWN_SECTION_WIDGETS,
6205
+ createId: () => `blk-${forkedId.slice(0, 8)}-${ordinal++}`
6206
+ });
6207
+ const notebookIds = [targetNb];
6208
+ if (targetNb === "notebook/playground" && !notebookIds.includes("notebook/playground")) {
6209
+ notebookIds.push("notebook/playground");
6210
+ }
6211
+ const dateMs = options.journalDate ? Date.parse(`${options.journalDate}T12:00:00Z`) : sourceNote?.date ?? fallbackMat?.date;
6212
+ const forkedNote = {
6213
+ id: forkedId,
6214
+ title: sourceTitle,
6215
+ rawContent,
6216
+ sourceRevision: 1,
6217
+ blocks,
6218
+ ...dateMs !== void 0 && Number.isFinite(dateMs) ? { date: dateMs } : {},
6219
+ createdAt: now,
6220
+ type: targetNb === "notebook/playground" ? "playground" : targetNb === "notebook/journal" ? "journal" : "note",
6221
+ sourceId: sourceIdForProvenance,
6222
+ ...targetNb !== "notebook/journal" && targetNb !== "notebook/playground" ? { notebookId: targetNb } : {},
6223
+ notebookIds,
6224
+ provenance,
6225
+ ...sourceTags?.length ? { tags: sourceTags.filter((t) => t !== "preview:remote") } : {},
6226
+ seedOrigin: "user"
6227
+ };
6228
+ return storage.transaction(
6229
+ ["notes", "block_revisions", "block_index", "notebook_links", "page", "page_notes", "schedule_items"],
6230
+ "readwrite",
6231
+ async (tx) => {
6232
+ if (targetNb !== "notebook/journal" && targetNb !== "notebook/playground") {
6233
+ const landing = await tx.readonly("notes").get(targetNb);
6234
+ if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
6235
+ throw new Error(`Target notebook '${targetNb}' is feed-delivered and read-only.`);
6236
+ }
6237
+ if (!landing && !isNonPublishableNotebook(targetNb)) {
6238
+ const slug = notebookSlugFromId$1(targetNb);
6239
+ const landingTitle = slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ") || slug;
6240
+ await tx.readwrite("notes").put({
6241
+ id: targetNb,
6242
+ title: landingTitle,
6243
+ rawContent: `# ${landingTitle}
6244
+ `,
6245
+ sourceRevision: 1,
6246
+ blocks: {},
6247
+ createdAt: now,
6248
+ notebookId: targetNb,
6249
+ seedOrigin: "user"
6250
+ });
6251
+ }
6252
+ }
6253
+ await tx.readwrite("notes").put(forkedNote);
6254
+ await ensureNoteBlockRevisionsAndIndexInTx(tx, forkedNote, now);
6255
+ const links = notebookIds.map((nbId) => ({
6256
+ id: makeNotebookLinkId(nbId, "note", forkedNote.id),
6257
+ notebookId: nbId,
6258
+ targetKind: "note",
6259
+ targetId: forkedNote.id,
6260
+ noteId: forkedNote.id,
6261
+ createdAt: now
6262
+ }));
6263
+ await tx.readwrite("notebook_links").putMany(links);
6264
+ if (options.journalDate) {
6265
+ const page = await getOrCreateJournalPageInTx(tx, options.journalDate, now);
6266
+ const pageNote = {
6267
+ id: mintUuid(),
6268
+ pageId: page.id,
6269
+ noteId: forkedNote.id,
6270
+ createdAt: now
6271
+ };
6272
+ await tx.readwrite("page_notes").put(pageNote);
6273
+ await tx.readwrite("schedule_items").put({
6274
+ id: mintUuid(),
6275
+ date: options.journalDate,
6276
+ noteId: forkedNote.id,
6277
+ pageId: page.id,
6278
+ sourceNotebookId: targetNb,
6279
+ fallbackTitle: forkedNote.title,
6280
+ position: 0,
6281
+ status: "planned",
6282
+ createdAt: now,
6283
+ updatedAt: now
6284
+ });
6285
+ }
6286
+ return forkedNote;
6287
+ }
6288
+ );
6289
+ }
4955
6290
  async function resolveUpstreamProvenance(storage, note) {
4956
- const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : void 0);
6291
+ const isExternalPinned = Boolean(note.id) && (note.retention === "session-pinned" || note.upstreamStatus !== void 0 || note.seedOrigin === "seed" || note.feedOrigin === "feed");
6292
+ const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : isExternalPinned ? note.id : void 0);
4957
6293
  if (!sourceNoteId) return null;
6294
+ if (note.id && sourceNoteId === note.id) {
6295
+ const status = note.upstreamStatus ?? "live";
6296
+ const isLive = status === "live";
6297
+ return {
6298
+ exists: isLive,
6299
+ sourceNoteId,
6300
+ ...isLive ? { currentUpstreamVersion: note.seedVersion ?? note.sourceRevision } : {},
6301
+ sourceVersion: note.provenance?.sourceVersion ?? note.seedVersion ?? note.sourceRevision,
6302
+ sourceCommit: note.provenance?.sourceCommit ?? note.seedCommit,
6303
+ feedSourceId: note.provenance?.feedSourceId ?? note.feedSourceId,
6304
+ sourceNotebookId: note.provenance?.sourceNotebookId,
6305
+ sourcePath: note.provenance?.sourcePath ?? note.sourcePath,
6306
+ upstreamStatus: status
6307
+ };
6308
+ }
4958
6309
  const upstream = await storage.readonly("notes").get(sourceNoteId);
4959
6310
  if (upstream) {
6311
+ const upstreamGone = upstream.upstreamStatus === "unsubscribed" || upstream.upstreamStatus === "removed";
4960
6312
  return {
4961
- exists: true,
6313
+ exists: !upstreamGone,
4962
6314
  sourceNoteId,
4963
6315
  title: upstream.title,
4964
6316
  sourceVersion: note.provenance?.sourceVersion,
@@ -4966,7 +6318,8 @@ async function resolveUpstreamProvenance(storage, note) {
4966
6318
  sourceCommit: note.provenance?.sourceCommit ?? upstream.seedCommit,
4967
6319
  feedSourceId: note.provenance?.feedSourceId ?? upstream.feedSourceId,
4968
6320
  sourceNotebookId: note.provenance?.sourceNotebookId ?? notebookOfItem(upstream),
4969
- sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath
6321
+ sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath,
6322
+ upstreamStatus: upstream.upstreamStatus ?? "live"
4970
6323
  };
4971
6324
  }
4972
6325
  return {
@@ -4976,7 +6329,8 @@ async function resolveUpstreamProvenance(storage, note) {
4976
6329
  sourceCommit: note.provenance?.sourceCommit,
4977
6330
  feedSourceId: note.provenance?.feedSourceId,
4978
6331
  sourceNotebookId: note.provenance?.sourceNotebookId,
4979
- sourcePath: note.provenance?.sourcePath
6332
+ sourcePath: note.provenance?.sourcePath,
6333
+ ...note.upstreamStatus ? { upstreamStatus: note.upstreamStatus } : {}
4980
6334
  };
4981
6335
  }
4982
6336
  function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
@@ -4990,7 +6344,429 @@ function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
4990
6344
  clonedAt
4991
6345
  };
4992
6346
  }
6347
+ function mintUuid2() {
6348
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
6349
+ return crypto.randomUUID();
6350
+ }
6351
+ const bytes = new Uint8Array(16);
6352
+ crypto.getRandomValues(bytes);
6353
+ bytes[6] = bytes[6] & 15 | 64;
6354
+ bytes[8] = bytes[8] & 63 | 128;
6355
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
6356
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
6357
+ }
6358
+ function localCivilDateKey(ms = Date.now(), timeZone) {
6359
+ if (timeZone) {
6360
+ return new Intl.DateTimeFormat("en-CA", {
6361
+ timeZone,
6362
+ year: "numeric",
6363
+ month: "2-digit",
6364
+ day: "2-digit"
6365
+ }).format(new Date(ms));
6366
+ }
6367
+ const d = new Date(ms);
6368
+ const y = d.getFullYear();
6369
+ const m = String(d.getMonth() + 1).padStart(2, "0");
6370
+ const day = String(d.getDate()).padStart(2, "0");
6371
+ return `${y}-${m}-${day}`;
6372
+ }
6373
+ function normalizeCivilDate(input, nowMs = Date.now(), timeZone) {
6374
+ if (!input || input.trim().toLowerCase() === "today") {
6375
+ return localCivilDateKey(nowMs, timeZone);
6376
+ }
6377
+ const trimmed = input.trim();
6378
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
6379
+ throw new Error(`Invalid civil date '${input}'; expected YYYY-MM-DD or 'today'.`);
6380
+ }
6381
+ return trimmed;
6382
+ }
6383
+ function addDaysToCivilDate(dateKey, deltaDays) {
6384
+ const [y, m, d] = dateKey.split("-").map(Number);
6385
+ const dt = new Date(Date.UTC(y, m - 1, d + deltaDays, 12, 0, 0));
6386
+ return `${dt.getUTCFullYear()}-${String(dt.getUTCMonth() + 1).padStart(2, "0")}-${String(dt.getUTCDate()).padStart(2, "0")}`;
6387
+ }
6388
+ function diffDaysCivil(a, b) {
6389
+ const pa = Date.parse(`${a}T12:00:00Z`);
6390
+ const pb = Date.parse(`${b}T12:00:00Z`);
6391
+ return Math.round((pa - pb) / 864e5);
6392
+ }
6393
+ async function getOrCreatePageForDateInTx(tx, dateKey, now) {
6394
+ let existing;
6395
+ try {
6396
+ existing = await tx.readonly("page").getAllFromIndex("by-date", dateKey);
6397
+ } catch {
6398
+ existing = (await tx.readonly("page").getAll()).filter((p) => p.date === dateKey);
6399
+ }
6400
+ if (existing[0]) return existing[0];
6401
+ const created = {
6402
+ id: mintUuid2(),
6403
+ date: dateKey,
6404
+ title: dateKey,
6405
+ createdAt: now
6406
+ };
6407
+ await tx.readwrite("page").put(created);
6408
+ return created;
6409
+ }
6410
+ async function noteHasRecordedSessionsInTx(tx, noteId) {
6411
+ try {
6412
+ const count = await tx.readonly("sessions").countFromIndex("by-note", noteId);
6413
+ if (count > 0) return true;
6414
+ } catch {
6415
+ const all = await tx.readonly("sessions").getAll();
6416
+ return all.some((s) => s.noteId === noteId);
6417
+ }
6418
+ return false;
6419
+ }
6420
+ async function snapshotNoteRevisionIfHasSessionsInTx(tx, previous, now = Date.now()) {
6421
+ if (!previous) return void 0;
6422
+ const hasSessions = await noteHasRecordedSessionsInTx(tx, previous.id);
6423
+ if (!hasSessions) return void 0;
6424
+ const existingRev = await tx.readonly("note_revisions").get([previous.id, previous.sourceRevision]).catch(() => void 0);
6425
+ if (existingRev) return existingRev;
6426
+ const snapshot = {
6427
+ noteId: previous.id,
6428
+ version: previous.sourceRevision,
6429
+ title: previous.title,
6430
+ rawContent: previous.rawContent,
6431
+ ...previous.tags ? { tags: [...previous.tags] } : {},
6432
+ ...previous.type ? { type: previous.type } : {},
6433
+ ...previous.notebookIds ? { notebookIds: [...previous.notebookIds] } : {},
6434
+ blocks: structuredClone(previous.blocks),
6435
+ savedAt: now
6436
+ };
6437
+ await tx.readwrite("note_revisions").put(snapshot);
6438
+ return snapshot;
6439
+ }
6440
+ async function getNoteRevision(storage, noteId, version) {
6441
+ return storage.readonly("note_revisions").get([noteId, version]);
6442
+ }
6443
+ async function listNoteRevisions(storage, noteId) {
6444
+ try {
6445
+ const rows = await storage.readonly("note_revisions").getAllFromIndex("by-note", noteId);
6446
+ return rows.sort((a, b) => b.version - a.version);
6447
+ } catch {
6448
+ const all = await storage.readonly("note_revisions").getAll();
6449
+ return all.filter((r) => r.noteId === noteId).sort((a, b) => b.version - a.version);
6450
+ }
6451
+ }
6452
+ async function scheduleNoteOnDate(storage, input) {
6453
+ const now = input.now ?? Date.now();
6454
+ const dateKey = normalizeCivilDate(input.date, now);
6455
+ const pinned = await ensurePinnedExternalWorkout(storage, {
6456
+ noteId: input.noteId,
6457
+ remotePayload: input.remotePayload,
6458
+ resolveRemoteWorkout: input.resolveRemoteWorkout,
6459
+ retention: "schedule-pinned",
6460
+ now
6461
+ });
6462
+ return storage.transaction(
6463
+ ["schedule_items", "page", "notes"],
6464
+ "readwrite",
6465
+ async (tx) => {
6466
+ const note = await tx.readonly("notes").get(pinned.note.id) ?? pinned.note;
6467
+ const page = await getOrCreatePageForDateInTx(tx, dateKey, now);
6468
+ let existingForDate;
6469
+ try {
6470
+ existingForDate = await tx.readonly("schedule_items").getAllFromIndex("by-date", dateKey);
6471
+ } catch {
6472
+ existingForDate = (await tx.readonly("schedule_items").getAll()).filter((s) => s.date === dateKey);
6473
+ }
6474
+ const nextPos = input.position ?? existingForDate.reduce((max, item2) => Math.max(max, item2.position), -1) + 1;
6475
+ const resolvedNb = input.sourceNotebookId ?? notebookOfItem(note) ?? pinned.ownership.sourceNotebookId;
6476
+ const item = {
6477
+ id: input.id ?? mintUuid2(),
6478
+ date: dateKey,
6479
+ noteId: note.id,
6480
+ pageId: page.id,
6481
+ ...resolvedNb ? { sourceNotebookId: toNotebookId$1(resolvedNb) } : {},
6482
+ ...note.title ? { fallbackTitle: note.title } : {},
6483
+ ...input.blockId ? { blockId: input.blockId } : {},
6484
+ position: nextPos,
6485
+ ...input.slot?.trim() ? { slot: input.slot.trim() } : {},
6486
+ status: input.status ?? "planned",
6487
+ ...input.notes !== void 0 && input.notes.trim() ? { notes: input.notes.trim() } : {},
6488
+ createdAt: now,
6489
+ updatedAt: now
6490
+ };
6491
+ await tx.readwrite("schedule_items").put(item);
6492
+ return item;
6493
+ }
6494
+ );
6495
+ }
6496
+ async function batchScheduleNotes(storage, entries) {
6497
+ const created = [];
6498
+ for (const entry of entries) {
6499
+ created.push(await scheduleNoteOnDate(storage, entry));
6500
+ }
6501
+ return created;
6502
+ }
6503
+ async function updateScheduleItem(storage, id, patch) {
6504
+ const now = patch.now ?? Date.now();
6505
+ return storage.transaction(["schedule_items", "page"], "readwrite", async (tx) => {
6506
+ const existing = await tx.readonly("schedule_items").get(id);
6507
+ if (!existing) throw new Error(`ScheduleItem not found: ${id}`);
6508
+ const nextDate = patch.date !== void 0 ? normalizeCivilDate(patch.date, now) : existing.date;
6509
+ let nextPageId = existing.pageId;
6510
+ let movedFromDate = existing.movedFromDate;
6511
+ let nextStatus = patch.status ?? existing.status;
6512
+ if (nextDate !== existing.date) {
6513
+ const page = await getOrCreatePageForDateInTx(tx, nextDate, now);
6514
+ nextPageId = page.id;
6515
+ if (patch.status === void 0 && existing.status === "planned") {
6516
+ movedFromDate = existing.date;
6517
+ } else if (patch.status === "moved") {
6518
+ movedFromDate = existing.date;
6519
+ }
6520
+ }
6521
+ const updated = {
6522
+ ...existing,
6523
+ date: nextDate,
6524
+ ...nextPageId ? { pageId: nextPageId } : {},
6525
+ position: patch.position ?? existing.position,
6526
+ status: nextStatus,
6527
+ ...movedFromDate ? { movedFromDate } : {},
6528
+ updatedAt: now
6529
+ };
6530
+ if (patch.slot === null) delete updated.slot;
6531
+ else if (patch.slot !== void 0) updated.slot = patch.slot.trim() || void 0;
6532
+ if (patch.notes === null) delete updated.notes;
6533
+ else if (patch.notes !== void 0) updated.notes = patch.notes.trim() || void 0;
6534
+ if (patch.blockId === null) delete updated.blockId;
6535
+ else if (patch.blockId !== void 0) updated.blockId = patch.blockId.trim() || void 0;
6536
+ await tx.readwrite("schedule_items").put(updated);
6537
+ return updated;
6538
+ });
6539
+ }
6540
+ async function removeScheduleItem(storage, id) {
6541
+ return storage.transaction(["schedule_items"], "readwrite", async (tx) => {
6542
+ const existing = await tx.readonly("schedule_items").get(id);
6543
+ if (!existing) return false;
6544
+ await tx.readwrite("schedule_items").delete(id);
6545
+ return true;
6546
+ });
6547
+ }
6548
+ async function listScheduleItemsByDateRange(storage, fromDate, toDate) {
6549
+ const fromKey = normalizeCivilDate(fromDate);
6550
+ const toKey = normalizeCivilDate(toDate);
6551
+ let rows;
6552
+ try {
6553
+ rows = await storage.readonly("schedule_items").getAll();
6554
+ } catch {
6555
+ rows = [];
6556
+ }
6557
+ 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);
6558
+ }
6559
+ async function listScheduleItemsForNote(storage, noteId) {
6560
+ let rows;
6561
+ try {
6562
+ rows = await storage.readonly("schedule_items").getAllFromIndex("by-note", noteId);
6563
+ } catch {
6564
+ rows = (await storage.readonly("schedule_items").getAll()).filter((item) => item.noteId === noteId);
6565
+ }
6566
+ return rows.sort((a, b) => a.date.localeCompare(b.date) || a.position - b.position);
6567
+ }
6568
+ async function getScheduleAndSessionCountsByNote(storage) {
6569
+ const [schedules, sessions] = await Promise.all([
6570
+ storage.readonly("schedule_items").getAll().catch(() => []),
6571
+ storage.readonly("sessions").getAll().catch(() => [])
6572
+ ]);
6573
+ const counts = /* @__PURE__ */ new Map();
6574
+ const ensure = (noteId) => {
6575
+ let entry = counts.get(noteId);
6576
+ if (!entry) {
6577
+ entry = { scheduleCount: 0, sessionCount: 0, scheduledDates: [] };
6578
+ counts.set(noteId, entry);
6579
+ }
6580
+ return entry;
6581
+ };
6582
+ for (const s of schedules) {
6583
+ if (s.status === "skipped") continue;
6584
+ const entry = ensure(s.noteId);
6585
+ entry.scheduleCount += 1;
6586
+ if (!entry.scheduledDates.includes(s.date)) entry.scheduledDates.push(s.date);
6587
+ }
6588
+ for (const sess of sessions) {
6589
+ const entry = ensure(sess.noteId);
6590
+ entry.sessionCount += 1;
6591
+ }
6592
+ for (const entry of counts.values()) {
6593
+ entry.scheduledDates.sort();
6594
+ }
6595
+ return counts;
6596
+ }
6597
+ async function attributeSession(storage, input) {
6598
+ const now = input.now ?? Date.now();
6599
+ return storage.transaction(["sessions", "schedule_items", "page"], "readwrite", async (tx) => {
6600
+ const session = await tx.readonly("sessions").get(input.sessionId);
6601
+ if (!session) throw new Error(`Session not found: ${input.sessionId}`);
6602
+ let nextSessionDate = session.sessionDate;
6603
+ let nextPageId = session.pageId;
6604
+ let nextScheduleItemId = session.scheduleItemId;
6605
+ if (input.scheduleItemId === null) {
6606
+ if (session.scheduleItemId) {
6607
+ const prevItem = await tx.readonly("schedule_items").get(session.scheduleItemId);
6608
+ if (prevItem && prevItem.status === "completed") {
6609
+ await tx.readwrite("schedule_items").put({
6610
+ ...prevItem,
6611
+ status: "planned",
6612
+ updatedAt: now
6613
+ });
6614
+ }
6615
+ }
6616
+ nextScheduleItemId = void 0;
6617
+ } else if (input.scheduleItemId !== void 0) {
6618
+ const targetItem = await tx.readonly("schedule_items").get(input.scheduleItemId);
6619
+ if (!targetItem) throw new Error(`ScheduleItem not found: ${input.scheduleItemId}`);
6620
+ if (session.scheduleItemId && session.scheduleItemId !== targetItem.id) {
6621
+ const prevItem = await tx.readonly("schedule_items").get(session.scheduleItemId);
6622
+ if (prevItem && prevItem.status === "completed") {
6623
+ await tx.readwrite("schedule_items").put({
6624
+ ...prevItem,
6625
+ status: "planned",
6626
+ updatedAt: now
6627
+ });
6628
+ }
6629
+ }
6630
+ nextScheduleItemId = targetItem.id;
6631
+ if (input.sessionDate === void 0) {
6632
+ nextSessionDate = targetItem.date;
6633
+ }
6634
+ if (targetItem.status !== "completed") {
6635
+ await tx.readwrite("schedule_items").put({
6636
+ ...targetItem,
6637
+ status: "completed",
6638
+ updatedAt: now
6639
+ });
6640
+ }
6641
+ }
6642
+ if (input.sessionDate !== void 0) {
6643
+ nextSessionDate = normalizeCivilDate(input.sessionDate, now);
6644
+ }
6645
+ if (nextSessionDate) {
6646
+ const page = await getOrCreatePageForDateInTx(tx, nextSessionDate, now);
6647
+ nextPageId = page.id;
6648
+ }
6649
+ const updated = {
6650
+ ...session,
6651
+ ...nextPageId !== void 0 ? { pageId: nextPageId } : {},
6652
+ ...nextSessionDate !== void 0 ? { sessionDate: nextSessionDate } : {}
6653
+ };
6654
+ if (nextScheduleItemId !== void 0) updated.scheduleItemId = nextScheduleItemId;
6655
+ else delete updated.scheduleItemId;
6656
+ await tx.readwrite("sessions").put(updated);
6657
+ return updated;
6658
+ });
6659
+ }
6660
+ async function findNearbyMatchingScheduleItems(storage, session, windowDays = 2) {
6661
+ if (session.scheduleItemId) return [];
6662
+ const baseDate = session.sessionDate ?? localCivilDateKey(session.startTime);
6663
+ const fromDate = addDaysToCivilDate(baseDate, -windowDays);
6664
+ const toDate = addDaysToCivilDate(baseDate, windowDays);
6665
+ const candidates = await listScheduleItemsForNote(storage, session.noteId);
6666
+ 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));
6667
+ }
6668
+ function resolveSessionCivilDate(session, pageDateById, sessionPageId) {
6669
+ if (session.sessionDate) return session.sessionDate;
6670
+ if (sessionPageId && pageDateById?.has(sessionPageId)) {
6671
+ return pageDateById.get(sessionPageId);
6672
+ }
6673
+ return localCivilDateKey(session.startTime || session.createdAt);
6674
+ }
6675
+ async function getJournalDayOverlay(storage, rawDate) {
6676
+ const dateKey = normalizeCivilDate(rawDate);
6677
+ const [pages, daySchedules, allSessions, allNotes] = await Promise.all([
6678
+ storage.readonly("page").getAll().catch(() => []),
6679
+ listScheduleItemsByDateRange(storage, dateKey, dateKey),
6680
+ storage.readonly("sessions").getAll().catch(() => []),
6681
+ storage.readonly("notes").getAll().catch(() => [])
6682
+ ]);
6683
+ const pageDateById = /* @__PURE__ */ new Map();
6684
+ let pageId = null;
6685
+ for (const p of pages) {
6686
+ if (p.date) {
6687
+ pageDateById.set(p.id, p.date);
6688
+ if (p.date === dateKey && !pageId) pageId = p.id;
6689
+ }
6690
+ }
6691
+ const notesById = new Map(allNotes.map((n) => [n.id, n]));
6692
+ const daySessions = allSessions.filter((s) => resolveSessionCivilDate(s, pageDateById, s.pageId) === dateKey).sort((a, b) => a.startTime - b.startTime);
6693
+ const pairedByScheduleId = /* @__PURE__ */ new Map();
6694
+ const pairedSessionIds = /* @__PURE__ */ new Set();
6695
+ for (const s of daySessions) {
6696
+ if (!s.scheduleItemId) continue;
6697
+ const match = daySchedules.find((item) => item.id === s.scheduleItemId);
6698
+ if (match) {
6699
+ const bucket = pairedByScheduleId.get(match.id) ?? [];
6700
+ bucket.push(s);
6701
+ pairedByScheduleId.set(match.id, bucket);
6702
+ pairedSessionIds.add(s.id);
6703
+ }
6704
+ }
6705
+ const planned = daySchedules.map((item) => ({
6706
+ item,
6707
+ note: notesById.get(item.noteId),
6708
+ pairedSessions: pairedByScheduleId.get(item.id) ?? []
6709
+ }));
6710
+ const adhocSessions = daySessions.filter((s) => !pairedSessionIds.has(s.id)).map((session) => ({
6711
+ session,
6712
+ note: notesById.get(session.noteId)
6713
+ }));
6714
+ return {
6715
+ date: dateKey,
6716
+ pageId,
6717
+ planned,
6718
+ adhocSessions,
6719
+ allSessions: daySessions
6720
+ };
6721
+ }
6722
+ async function migrateDatedPageNotesToSchedule(storage) {
6723
+ return storage.transaction(["page", "page_notes", "schedule_items", "notes"], "readwrite", async (tx) => {
6724
+ const [pages, pageNotes, existingSchedules, notes] = await Promise.all([
6725
+ tx.readonly("page").getAll(),
6726
+ tx.readonly("page_notes").getAll(),
6727
+ tx.readonly("schedule_items").getAll(),
6728
+ tx.readonly("notes").getAll()
6729
+ ]);
6730
+ const dateByPage = /* @__PURE__ */ new Map();
6731
+ for (const p of pages) {
6732
+ if (p.date) dateByPage.set(p.id, p.date);
6733
+ }
6734
+ const existingIds = new Set(existingSchedules.map((s) => s.id));
6735
+ const notesById = new Map(notes.map((n) => [n.id, n]));
6736
+ const toCreate = [];
6737
+ for (const pn of pageNotes) {
6738
+ const date = dateByPage.get(pn.pageId);
6739
+ if (!date) continue;
6740
+ const deterministicId = `sched-${pn.id}`;
6741
+ if (existingIds.has(deterministicId)) continue;
6742
+ const alreadySameNoteOnDate = existingSchedules.some(
6743
+ (s) => s.date === date && s.noteId === pn.noteId && s.pageId === pn.pageId
6744
+ );
6745
+ if (alreadySameNoteOnDate) continue;
6746
+ const note = notesById.get(pn.noteId);
6747
+ const createdAt = pn.createdAt ?? Date.now();
6748
+ const ownership = note ? resolveNoteOwnership(note, notebookOriginOfItem(note), notebookOfItem(note)) : void 0;
6749
+ const resolvedNb = note ? notebookOfItem(note) ?? ownership?.sourceNotebookId : void 0;
6750
+ toCreate.push({
6751
+ id: deterministicId,
6752
+ date,
6753
+ noteId: pn.noteId,
6754
+ pageId: pn.pageId,
6755
+ ...resolvedNb ? { sourceNotebookId: resolvedNb } : {},
6756
+ ...note?.title ? { fallbackTitle: note.title } : {},
6757
+ position: pn.position ?? 0,
6758
+ status: "planned",
6759
+ createdAt,
6760
+ updatedAt: createdAt
6761
+ });
6762
+ }
6763
+ if (toCreate.length > 0) {
6764
+ await tx.readwrite("schedule_items").putMany(toCreate);
6765
+ }
6766
+ return toCreate.length;
6767
+ });
6768
+ }
4993
6769
 
4994
- export { APP_ORIGIN, BUILD_TIME, CANVAS_CHUNK_ID, DASHBOARDS_CHUNK_ID, DirectoryHandleFeedTree, EFFORTS_CHUNK_ID, EQUIPMENT_CHUNK_ID, FEED_SUBSCRIPTIONS_META_KEY, FeedTreeError, GIT_SHA, HttpFeedTree, MemoryFeedTree, NOTE_ID_FRONTMATTER_KEY, PUBLISHED_FEED_META_KEY, QR_SCRIPT_ID, SEED_BROADCAST_CHANNEL, SEED_NAMESPACE, SEED_REGISTERED_WIDGETS, SEED_SCHEMA, SEMVER, SESSION_CSV_HEADER, TELEMETRY_CSV_HEADER, VERSION, applySeedChunk, applySeedChunks, assertNotebookIndex, assertSeedManifest, assertSeedRow, assertSeedRows, backfillFeedProvenance, buildContextualPageSource, buildNoteProvenance, buildQueryServiceStoresFromStorage, buildStatementTree, canvasRouteSlug, checkUnpublishedFeedChanges, cloneRemoteRecord, composeNoteMarkdown, createIRFile, createUserNotebookLanding, csvToEquipmentLabels, csvToSessionRows, csvToTelemetryBundle, decodeUtf8, deleteFeedSourceHeadless, effortToMarkdown, emptySeedMeta, encodeUtf8, equipmentToCsv, equipmentToMarkdown, exportPortableFilesFromStorage, extractNoteIdentity, extractTypedTags, feedIdOfMetaKey, getNoteNotebooks, getNotePublicationSummary, ingestPortableFilesIntoStorage, injectIdentityFrontmatter, isIRFile, listFeedSubscriptionsHeadless, listScopedPropertyOverrides, makeNotebookLinkId, makeScopedOverrideId, migrateNotebookVocabulary, normalizeFeedTreePath, notebookSlugForChunkId, parseCsvLine, parseFrontmatterDateMs, parseNoteMarkdown, prepareJournalSessionRun, previewRemoteNotebook, previewRemoteRecord, promoteNoteToNotebooks, promoteReferencedOverridesToNotebook, publishFeedFromStorage, qrInlineScript, readFrontmatterMeta, recordPublishedFeedCheckpoint, removeNoteFromNotebook, removeSeedSourceContent, renderFeedLandingHtml, resolveScopedPropertyCatalog, resolveUpstreamProvenance, saveScopedPropertyOverride, seedMetaKey, seedNoteId, seedNoteSourceId, seedPrecedenceRank, seedSourceTier, sessionToCsv, setNoteNotebooks, setNotebookPublic, setSessionPublic, sha256HexAsync, splitCsvRecords, statementToNode, subscribeFeedSourceHeadless, telemetryBundleToCsv, unsubscribeFeedSourceHeadless };
4995
- //# sourceMappingURL=chunk-4F6VCY2U.mjs.map
4996
- //# sourceMappingURL=chunk-4F6VCY2U.mjs.map
6770
+ export { APP_ORIGIN, BUILD_TIME, CANVAS_CHUNK_ID, DASHBOARDS_CHUNK_ID, DirectoryHandleFeedTree, EFFORTS_CHUNK_ID, EQUIPMENT_CHUNK_ID, FEED_INDEX_META_PREFIX, FEED_REGISTRY_META_KEY, FEED_SUBSCRIPTIONS_META_KEY, FeedTreeError, GIT_SHA, HttpFeedTree, MemoryFeedTree, NOTE_ID_FRONTMATTER_KEY, PUBLISHED_FEED_META_KEY, QR_SCRIPT_ID, SEED_BROADCAST_CHANNEL, SEED_NAMESPACE, SEED_REGISTERED_WIDGETS, SEED_SCHEMA, SEMVER, SESSION_CSV_HEADER, TELEMETRY_CSV_HEADER, VERSION, applySeedChunk, applySeedChunks, assertNotebookIndex, assertSeedManifest, assertSeedRow, assertSeedRows, attributeSession, backfillFeedProvenance, batchScheduleNotes, buildContextualPageSource, buildNoteProvenance, buildQueryServiceStoresFromStorage, buildStatementTree, canvasRouteSlug, checkUnpublishedFeedChanges, cloneRemoteRecord, compileSeedRowFromMarkdown, composeNoteMarkdown, createIRFile, createUserNotebookLanding, csvToEquipmentLabels, csvToSessionRows, csvToTelemetryBundle, decodeUtf8, deleteFeedSourceHeadless, deleteUserNotebook, effortToMarkdown, emptySeedMeta, encodeUtf8, ensurePinnedExternalWorkout, equipmentToCsv, equipmentToMarkdown, exportPortableFilesFromStorage, extractNoteIdentity, extractTypedTags, feedIdOfMetaKey, feedIndexMetaKey, findNearbyMatchingScheduleItems, forkNoteToUserNotebook, getJournalDayOverlay, getNoteNotebooks, getNotePublicationSummary, getNoteRevision, getScheduleAndSessionCountsByNote, ingestPortableFilesIntoStorage, injectIdentityFrontmatter, isIRFile, listFeedSubscriptionsHeadless, listNoteRevisions, listScheduleItemsByDateRange, listScheduleItemsForNote, listScopedPropertyOverrides, localCivilDateKey, logSessionAgainstExternalWorkout, makeNotebookLinkId, makeScopedOverrideId, materializeCachedRemoteRecord, migrateDatedPageNotesToSchedule, migrateNotebookVocabulary, normalizeCivilDate, normalizeFeedTreePath, noteHasRecordedSessionsInTx, notebookSlugForChunkId, parseCsvLine, parseFrontmatterDateMs, parseNoteMarkdown, parseRemoteNoteId, prepareJournalSessionRun, previewRemoteNotebook, previewRemoteRecord, promoteNoteToNotebooks, promoteReferencedOverridesToNotebook, publishFeedFromStorage, qrInlineScript, readFeedRegistryHeadless, readFrontmatterMeta, reconcileRemovedFeedRecords, recordPublishedFeedCheckpoint, removeFeedNotebookContent, removeFeedSourceContentById, removeNoteFromNotebook, removeScheduleItem, removeSeedSourceContent, renderFeedLandingHtml, resolveScopedPropertyCatalog, resolveSessionCivilDate, resolveUpstreamProvenance, saveScopedPropertyOverride, scheduleNoteOnDate, seedMetaKey, seedNoteId, seedNoteSourceId, seedPrecedenceRank, seedSourceTier, sessionToCsv, setNoteNotebooks, setNotebookPublic, setSessionPublic, sha256HexAsync, snapshotNoteRevisionIfHasSessionsInTx, splitCsvRecords, statementToNode, subscribeFeedSourceHeadless, telemetryBundleToCsv, unsubscribeFeedSourceHeadless, updateScheduleItem, writeFeedRegistryHeadless };
6771
+ //# sourceMappingURL=chunk-QVYGLAEZ.mjs.map
6772
+ //# sourceMappingURL=chunk-QVYGLAEZ.mjs.map