@bitcobblers/wod-wiki-engine 0.53.2204 → 0.54.2205

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.mjs ADDED
@@ -0,0 +1,2701 @@
1
+ import { extractNoteIdentity, extractTypedTags, makeNotebookLinkId, resolveScopedPropertyCatalog, effortToMarkdown, equipmentToMarkdown, saveScopedPropertyOverride, seedMetaKey, checkUnpublishedFeedChanges, MemoryFeedTree, publishFeedFromStorage, ingestPortableFilesIntoStorage, exportPortableFilesFromStorage, readFrontmatterMeta, createUserNotebookLanding, setNotebookPublic, promoteNoteToNotebooks, removeNoteFromNotebook, getNoteNotebooks, resolveUpstreamProvenance, getNotePublicationSummary, composeNoteMarkdown, buildNoteProvenance, buildStatementTree, prepareJournalSessionRun, setSessionPublic } from './chunk-FSWOTQ5M.mjs';
2
+ import { BUILTIN_NOTEBOOKS, parseDocumentSections, KNOWN_SECTION_WIDGETS, isNoteEditable, reconcileNoteBlocks, validateNoteBlocks, toNotebookId, blockContentId, MetricType, orderPlacements, isSystemReadOnlyNotebook, notebookSlugFromId, isNonPublishableNotebook } from '@bitcobblers/wod-wiki-core';
3
+ import { bundledEfforts, createReferenceIndex, parseScript, extractStatementRefs, createParser, findUnresolvedChoices, createMockClock, RuntimeStack, EventBus, frozenNow, ScriptRuntime, createCompiler, createAnalyticsEngineForBlock, StartSessionAction, NextEvent, toStoredOutputStatement } from '@bitcobblers/wod-wiki-lang';
4
+ import { rowsEqual, userDeletedSeedKey } from '@bitcobblers/wod-wiki-storage';
5
+ import { QueryService, notebookOriginOfItem, notebookOfItem, notebooksOfItem, toEventRows, toSummaryEventRows, parseQuery, isPipelineQuery, isFindQuery, isAggregateQuery, WQL_ROLLUP_PERIODS, WQL_AGGREGATORS, WQL_FIND_TARGETS, wqlGroupingDimensions, wqlFilterKeys, normalizeWql, WQL_COMPARISON_OPS, CONTENT_GROUPING_DIMENSIONS, WQL_VIRTUAL_DIMS, WQL_TAG_KEYS, WQL_TYPED_TAG_KEYS, WQL_METRIC_AGGREGATES, WQL_METRIC_FAMILIES } from '@bitcobblers/wod-wiki-wql';
6
+ import { z } from 'zod';
7
+
8
+ // src/agent/types.ts
9
+ var AgentConfirmationRequiredError = class extends Error {
10
+ code = "CONFIRMATION_REQUIRED";
11
+ targetId;
12
+ action;
13
+ constructor(req, detail) {
14
+ super(
15
+ detail ?? `Destructive action '${req.action}' on '${req.targetId}' requires confirmation (${req.summary}).`
16
+ );
17
+ this.name = "AgentConfirmationRequiredError";
18
+ this.action = req.action;
19
+ this.targetId = req.targetId;
20
+ }
21
+ };
22
+ function defineAgentTool(spec) {
23
+ return spec;
24
+ }
25
+ async function requireDestructiveConfirmation(ctx, req, explicitConfirmId) {
26
+ if (explicitConfirmId !== void 0 && explicitConfirmId === req.targetId) {
27
+ return;
28
+ }
29
+ if (ctx.confirmDestructive) {
30
+ const approved = await ctx.confirmDestructive(req);
31
+ if (approved) return;
32
+ throw new AgentConfirmationRequiredError(
33
+ req,
34
+ `User declined or did not confirm '${req.action}' on '${req.targetId}'.`
35
+ );
36
+ }
37
+ throw new AgentConfirmationRequiredError(
38
+ req,
39
+ `Destructive action '${req.action}' requires confirmId="${req.targetId}" (or --yes "${req.targetId}" on CLI).`
40
+ );
41
+ }
42
+ function mintAgentUuid() {
43
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
44
+ return crypto.randomUUID();
45
+ }
46
+ const bytes = new Uint8Array(16);
47
+ crypto.getRandomValues(bytes);
48
+ bytes[6] = bytes[6] & 15 | 64;
49
+ bytes[8] = bytes[8] & 63 | 128;
50
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
51
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
52
+ }
53
+ function extractHeadingTitleFromMarkdown(rawContent) {
54
+ const withoutFm = rawContent.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
55
+ for (const line of withoutFm.split(/\r?\n/)) {
56
+ const m = line.match(/^#\s+(.+)$/);
57
+ if (m?.[1]?.trim()) return m[1].trim();
58
+ }
59
+ return void 0;
60
+ }
61
+ function normalizeMarkdownOrBareScript(source, sport, title) {
62
+ const trimmed = source.trim();
63
+ if (!trimmed) return title ? `# ${title}
64
+ ` : "";
65
+ const rewrittenFences = source.replace(/^(\s*`{3,})(?:wod|whiteboard)(?=(?::[\w-]+)?\s*$)/gim, "$1time");
66
+ const sections = parseDocumentSections(rewrittenFences, { registeredWidgets: KNOWN_SECTION_WIDGETS });
67
+ if (sections.some((s) => s.scriptBlock) || /^---\r?\n/.test(rewrittenFences) || /^#\s+/m.test(rewrittenFences)) {
68
+ return rewrittenFences.endsWith("\n") ? rewrittenFences : `${rewrittenFences}
69
+ `;
70
+ }
71
+ let fenceLen = 3;
72
+ for (const match of rewrittenFences.matchAll(/`+/g)) {
73
+ fenceLen = Math.max(fenceLen, match[0].length + 1);
74
+ }
75
+ const fence = "`".repeat(fenceLen);
76
+ const heading = title ? `# ${title}
77
+
78
+ ` : "";
79
+ return `${heading}${fence}time${sport ? `:${sport}` : ""}
80
+ ${trimmed}
81
+ ${fence}
82
+ `;
83
+ }
84
+ function civilDateKey(input, nowMs = Date.now()) {
85
+ if (!input || input.trim().toLowerCase() === "today") {
86
+ const d = new Date(nowMs);
87
+ const y = d.getUTCFullYear();
88
+ const m = String(d.getUTCMonth() + 1).padStart(2, "0");
89
+ const day = String(d.getUTCDate()).padStart(2, "0");
90
+ return `${y}-${m}-${day}`;
91
+ }
92
+ const trimmed = input.trim();
93
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
94
+ throw new Error(`Invalid date '${input}'; expected YYYY-MM-DD or 'today'.`);
95
+ }
96
+ return trimmed;
97
+ }
98
+ function buildQueryServiceStoresFromStorage(storage) {
99
+ const asRange = (lower, upper) => typeof IDBKeyRange !== "undefined" ? IDBKeyRange.bound(lower, upper) : { lower, upper };
100
+ const resultRows = (key) => asRange([key, ""], [`${key}\uFFFF`, "\uFFFF"]);
101
+ const eventStore = {
102
+ getEventsByTimeRange: async (start, end) => storage.readonly("events").getAllFromIndex("by-timestamp", asRange(start, end)),
103
+ getEventsByResult: async (resultId) => storage.readonly("events").getAllFromIndex("by-result-grain", resultRows(resultId)),
104
+ getEventsForNote: async (noteId) => (await storage.readonly("events").getAll()).filter((row) => row.noteId === noteId),
105
+ getEventsByContent: async (cid) => storage.readonly("events").getAllFromIndex("by-content-grain", resultRows(cid)),
106
+ scanAll: () => storage.readonly("events").getAll(),
107
+ appendEvents: async (rows) => {
108
+ if (rows.length > 0) await storage.readwrite("events").putMany(rows);
109
+ },
110
+ finalizeSummaries: async (resultId, rows) => {
111
+ await storage.transaction(["events"], "readwrite", async (tx) => {
112
+ const allForResult = (await tx.readonly("events").getAll()).filter(
113
+ (r) => r.resultId === resultId && r.grain === "summary" && r.origin !== "user"
114
+ );
115
+ for (const r of allForResult) await tx.readwrite("events").delete(r.id);
116
+ if (rows.length > 0) await tx.readwrite("events").putMany(rows);
117
+ });
118
+ },
119
+ deleteEvents: async (ids) => {
120
+ for (const id of ids) await storage.readwrite("events").delete(id);
121
+ }
122
+ };
123
+ const noteStore = {
124
+ getAllNotes: () => storage.readonly("notes").getAll(),
125
+ getNotesByIds: async (ids) => {
126
+ const rows = await storage.readonly("notes").getMany([...ids]);
127
+ return rows.filter((row) => row !== void 0);
128
+ },
129
+ getNoteIdsForTag: async (label) => {
130
+ const ids = /* @__PURE__ */ new Set();
131
+ for (const tag of await storage.readonly("tags").getAllFromIndex("by-label", label)) {
132
+ for (const link of await storage.readonly("note_tags").getAllFromIndex("by-tag", tag.id)) {
133
+ ids.add(link.noteId);
134
+ }
135
+ }
136
+ return ids;
137
+ },
138
+ getNoteTagLabels: async (noteId) => {
139
+ const links = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
140
+ const tags = await storage.readonly("tags").getMany(links.map((l) => l.tagId));
141
+ return tags.flatMap((t) => t ? [t.label] : []);
142
+ },
143
+ queryDomain: async (request) => {
144
+ if (!storage.queryDomain) return void 0;
145
+ const result = await storage.queryDomain({ ...request, plan: "notes" });
146
+ return result && result.plan === "notes" ? result : void 0;
147
+ }
148
+ };
149
+ const blockStore = {
150
+ getAllBlocks: () => storage.readonly("block_index").getAll(),
151
+ queryDomain: async (request) => {
152
+ if (!storage.queryDomain) return void 0;
153
+ const result = await storage.queryDomain({ ...request, plan: "blocks" });
154
+ return result && result.plan === "blocks" ? result : void 0;
155
+ }
156
+ };
157
+ const effortStore = {
158
+ getAllEfforts: async () => {
159
+ const stored = await storage.readonly("efforts").getAll();
160
+ const bySlug = /* @__PURE__ */ new Map();
161
+ for (const eff of bundledEfforts) bySlug.set(eff.slug, eff);
162
+ for (const eff of stored) bySlug.set(eff.slug, eff);
163
+ return [...bySlug.values()];
164
+ }
165
+ };
166
+ return {
167
+ eventStore,
168
+ noteStore,
169
+ blockStore,
170
+ effortStore,
171
+ blockEffortsStore: {
172
+ getAllFromIndex: (index, key) => storage.readonly("block_efforts").getAllFromIndex(index, key)
173
+ },
174
+ blockEquipmentStore: {
175
+ getAllFromIndex: (index, key) => storage.readonly("block_equipment").getAllFromIndex(index, key)
176
+ },
177
+ tagsStore: {
178
+ getAllFromIndex: (index, key) => storage.readonly("tags").getAllFromIndex(index, key),
179
+ getAll: () => storage.readonly("tags").getAll()
180
+ },
181
+ noteTagsStore: {
182
+ getAllFromIndex: (index, key) => storage.readonly("note_tags").getAllFromIndex(index, key)
183
+ },
184
+ pageStore: {
185
+ getNotePages: (noteId) => storage.readonly("page_notes").getAllFromIndex("by-note", noteId),
186
+ getPage: (pageId) => storage.readonly("page").get(pageId),
187
+ getAllPages: () => storage.readonly("page").getAll(),
188
+ getAllLinks: () => storage.readonly("page_notes").getAll()
189
+ },
190
+ relationStore: {
191
+ getBatches: async (noteIds) => {
192
+ const bundles = /* @__PURE__ */ new Map();
193
+ for (const noteId of noteIds) {
194
+ const links = await storage.readonly("page_notes").getAllFromIndex("by-note", noteId);
195
+ const tagLinks = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
196
+ const tags = await storage.readonly("tags").getMany(tagLinks.map((l) => l.tagId));
197
+ const pages = await storage.readonly("page").getMany([...new Set(links.map((l) => l.pageId))]);
198
+ bundles.set(noteId, {
199
+ tags: tags.flatMap((t) => t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : []),
200
+ links,
201
+ pages: pages.filter((p) => p !== void 0)
202
+ });
203
+ }
204
+ return bundles;
205
+ }
206
+ },
207
+ feedCatalogStore: {
208
+ getAllFeeds: async () => {
209
+ const rows = [];
210
+ for (const row of await storage.readonly("meta").getAll()) {
211
+ const key = row.key;
212
+ if (typeof key !== "string" || !key.startsWith("seed:") || key === seedMetaKey("user")) continue;
213
+ const id = key.slice("seed:".length);
214
+ rows.push({
215
+ id,
216
+ label: id,
217
+ url: `https://${id}.example/feed/`,
218
+ tier: "imported",
219
+ subscribed: true,
220
+ installed: true,
221
+ notebookCount: 0,
222
+ itemCount: 0
223
+ });
224
+ }
225
+ return rows;
226
+ },
227
+ getAllNotebooks: async () => {
228
+ const links = await storage.readonly("notebook_links").getAll().catch(() => []);
229
+ const notes = await storage.readonly("notes").getAll();
230
+ const memberCount = /* @__PURE__ */ new Map();
231
+ for (const link of links) {
232
+ if (link.targetKind === "note") {
233
+ memberCount.set(link.notebookId, (memberCount.get(link.notebookId) ?? 0) + 1);
234
+ }
235
+ }
236
+ const rows = [];
237
+ for (const [notebookId, count] of memberCount) {
238
+ const slug = notebookId.startsWith("notebook/") ? notebookId.slice("notebook/".length) : notebookId;
239
+ const landing = notes.find((n) => n.id === notebookId);
240
+ const feedSourceId = landing?.feedSourceId;
241
+ rows.push({
242
+ id: notebookId,
243
+ feedId: feedSourceId ?? "local",
244
+ feedLabel: feedSourceId ?? "Yours (Local)",
245
+ chunkId: `notebook.${slug}`,
246
+ slug,
247
+ label: landing?.title ?? slug,
248
+ count,
249
+ subscribed: feedSourceId !== void 0,
250
+ installed: true,
251
+ origin: feedSourceId ? "feed" : "user",
252
+ ...landing?.public !== void 0 ? { public: landing.public } : {}
253
+ });
254
+ }
255
+ return rows;
256
+ }
257
+ }
258
+ };
259
+ }
260
+ function createQueryServiceForStorage(storage) {
261
+ return new QueryService(buildQueryServiceStoresFromStorage(storage));
262
+ }
263
+ async function diffProjectionRows(tx, store, previous, next) {
264
+ const nextIds = new Set(next.map((r) => r.id));
265
+ for (const r of previous) {
266
+ if (!nextIds.has(r.id)) {
267
+ await tx.readwrite(store).delete(r.id);
268
+ }
269
+ }
270
+ const oldById = new Map(previous.map((r) => [r.id, r]));
271
+ for (const r of next) {
272
+ if (!rowsEqual(oldById.get(r.id), r)) {
273
+ if (store === "block_index" && "blockVersion" in r) await tx.readwrite("block_index").put(r);
274
+ if (store === "block_efforts" && "effortSlug" in r) await tx.readwrite("block_efforts").put(r);
275
+ if (store === "block_equipment" && "equipmentSlug" in r) await tx.readwrite("block_equipment").put(r);
276
+ }
277
+ }
278
+ }
279
+ async function upsertNoteInStorage(storage, input) {
280
+ const now = input.now ?? Date.now();
281
+ const stampedIdentity = extractNoteIdentity(input.rawContent);
282
+ const noteId = input.noteId ?? stampedIdentity?.noteId ?? mintAgentUuid();
283
+ const extractedTags = input.tags ?? extractTypedTags(input.rawContent);
284
+ return storage.transaction(
285
+ [
286
+ "notes",
287
+ "block_revisions",
288
+ "block_index",
289
+ "block_efforts",
290
+ "block_equipment",
291
+ "efforts",
292
+ "equipment",
293
+ "tags",
294
+ "note_tags",
295
+ "page",
296
+ "page_notes",
297
+ "notebook_links"
298
+ ],
299
+ "readwrite",
300
+ async (tx) => {
301
+ const existing = await tx.readonly("notes").get(noteId);
302
+ if (existing) {
303
+ const nbOrigin = notebookOriginOfItem(existing);
304
+ const resolvedNb = notebookOfItem(existing);
305
+ const editable = existing.seedOrigin !== "seed" && existing.feedOrigin !== "feed" && isNoteEditable(existing, nbOrigin, resolvedNb);
306
+ if (!editable) {
307
+ throw new Error(
308
+ `Note '${noteId}' is read-only (seed/feed). Clone it first with wod_note_clone before editing.`
309
+ );
310
+ }
311
+ }
312
+ if (input.expectedSourceRevision !== void 0 && (existing?.sourceRevision ?? 0) !== input.expectedSourceRevision) {
313
+ throw new Error(
314
+ `CONFLICT: Stale sourceRevision on note '${noteId}': expected ${input.expectedSourceRevision}, actual ${existing?.sourceRevision ?? 0}.`
315
+ );
316
+ }
317
+ let sourceRevision = existing && existing.rawContent === input.rawContent ? existing.sourceRevision : (existing?.sourceRevision ?? 0) + 1;
318
+ const history = await tx.readonly("block_revisions").getAllFromIndex("by-note", noteId);
319
+ const latestRevByBlock = /* @__PURE__ */ new Map();
320
+ for (const rev of history) {
321
+ if ((latestRevByBlock.get(rev.blockId)?.version ?? 0) < rev.version) {
322
+ latestRevByBlock.set(rev.blockId, rev);
323
+ }
324
+ }
325
+ let ordinal = 0;
326
+ const blocks = reconcileNoteBlocks(input.rawContent, {
327
+ sourceRevision,
328
+ blocks: existing?.blocks,
329
+ registeredWidgets: KNOWN_SECTION_WIDGETS,
330
+ createId: () => {
331
+ while (true) {
332
+ const candidate = `blk-${noteId.slice(0, 8)}-${ordinal++}`;
333
+ if (!latestRevByBlock.has(candidate)) return candidate;
334
+ }
335
+ }
336
+ });
337
+ validateNoteBlocks(input.rawContent, blocks, sourceRevision, {
338
+ registeredWidgets: KNOWN_SECTION_WIDGETS
339
+ });
340
+ const newRevisions = [];
341
+ for (const block of Object.values(blocks)) {
342
+ const saved = latestRevByBlock.get(block.id);
343
+ const rawSlice = input.rawContent.slice(block.from, block.to);
344
+ const unchanged = saved && saved.rawContent === rawSlice && saved.kind === block.kind && saved.dialect === block.dialect && saved.sport === block.sport;
345
+ block.version = unchanged ? saved.version : (saved?.version ?? 0) + 1;
346
+ if (!unchanged) {
347
+ newRevisions.push({
348
+ noteId,
349
+ blockId: block.id,
350
+ version: block.version,
351
+ kind: block.kind,
352
+ rawContent: rawSlice,
353
+ savedAt: now,
354
+ ...block.dialect ? { dialect: block.dialect } : {},
355
+ ...block.sport ? { sport: block.sport } : {}
356
+ });
357
+ }
358
+ }
359
+ if (existing?.rawContent === input.rawContent && !rowsEqual(existing.blocks, blocks)) {
360
+ sourceRevision += 1;
361
+ for (const block of Object.values(blocks)) block.sourceRevision = sourceRevision;
362
+ }
363
+ const resolvedTitle = input.title ?? stampedIdentity?.title ?? extractHeadingTitleFromMarkdown(input.rawContent) ?? existing?.title ?? "Untitled Workout";
364
+ const targetNotebookId = input.notebookId ? toNotebookId(input.notebookId) : existing?.notebookId;
365
+ const notebookIds = Array.from(
366
+ /* @__PURE__ */ new Set([
367
+ "notebook/journal",
368
+ ...existing?.notebookIds ?? [],
369
+ ...targetNotebookId ? [targetNotebookId] : []
370
+ ])
371
+ );
372
+ const dateMs = input.journalDate ? Date.parse(`${civilDateKey(input.journalDate, now)}T12:00:00Z`) : existing?.date ?? now;
373
+ const note = {
374
+ ...existing ?? {},
375
+ id: noteId,
376
+ title: resolvedTitle,
377
+ rawContent: input.rawContent,
378
+ sourceRevision,
379
+ blocks,
380
+ type: input.type ?? existing?.type ?? (input.journalDate ? "journal" : "note"),
381
+ date: dateMs,
382
+ createdAt: existing?.createdAt ?? now,
383
+ notebookIds,
384
+ ...targetNotebookId && targetNotebookId !== "notebook/journal" ? { notebookId: targetNotebookId } : {},
385
+ tags: extractedTags.map((t) => t.label),
386
+ seedOrigin: "user"
387
+ };
388
+ const storedEfforts = await tx.readonly("efforts").getAll();
389
+ const effortsBySlug = /* @__PURE__ */ new Map();
390
+ for (const eff of bundledEfforts) effortsBySlug.set(eff.slug, eff);
391
+ for (const eff of storedEfforts) effortsBySlug.set(eff.slug, eff);
392
+ const referenceIndex = createReferenceIndex({
393
+ efforts: [...effortsBySlug.values()],
394
+ equipment: await tx.readonly("equipment").getAll()
395
+ });
396
+ const priorRows = await tx.readonly("block_index").getAllFromIndex("by-note", noteId);
397
+ const priorEfforts = await tx.readonly("block_efforts").getAllFromIndex("by-note", noteId);
398
+ const priorEquipment = await tx.readonly("block_equipment").getAllFromIndex("by-note", noteId);
399
+ const priorById = new Map(priorRows.map((r) => [r.id, r]));
400
+ const nextRows = [];
401
+ const nextEfforts = [];
402
+ const nextEquipment = [];
403
+ const allEffortSlugs = /* @__PURE__ */ new Set();
404
+ const allEquipSlugs = /* @__PURE__ */ new Set();
405
+ for (const [position, block] of Object.values(blocks).sort((a, b) => a.from - b.from).entries()) {
406
+ const rowId = `${noteId}:${block.id}`;
407
+ const prior = priorById.get(rowId);
408
+ const rawSlice = input.rawContent.slice(block.from, block.to);
409
+ const body = parseDocumentSections(rawSlice, { registeredWidgets: KNOWN_SECTION_WIDGETS })[0]?.displayContent ?? rawSlice;
410
+ const fingerprint = block.kind === "wod" ? blockContentId(body) : void 0;
411
+ nextRows.push({
412
+ ...prior ?? {},
413
+ id: rowId,
414
+ noteId,
415
+ blockId: block.id,
416
+ blockVersion: block.version,
417
+ dataType: block.kind,
418
+ sourceRevision,
419
+ from: block.from,
420
+ to: block.to,
421
+ position,
422
+ rawContent: rawSlice,
423
+ noteTitle: note.title,
424
+ createdAt: prior?.createdAt ?? now,
425
+ ...fingerprint ? { blockContentId: fingerprint } : {},
426
+ ...note.notebookId ? { notebookId: note.notebookId } : {}
427
+ });
428
+ if (block.kind === "wod") {
429
+ const parsedScript = parseScript(body, {
430
+ ...block.sport ? { sport: block.sport } : {},
431
+ references: referenceIndex
432
+ });
433
+ const refs = extractStatementRefs(parsedScript.statements);
434
+ const effortSlugs = new Set(refs.efforts);
435
+ if (effortSlugs.size === 0) {
436
+ for (const stmt of parsedScript.statements) {
437
+ const m = stmt.metrics?.getMetric?.(MetricType.Effort);
438
+ const val = typeof m?.value === "string" ? m.value : "";
439
+ const slug = val.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
440
+ if (slug && !["rest", "amrap", "emom", "tabata", "for-time"].includes(slug)) {
441
+ effortSlugs.add(slug);
442
+ }
443
+ }
444
+ }
445
+ for (const effortSlug of effortSlugs) {
446
+ allEffortSlugs.add(effortSlug);
447
+ const effId = `${noteId}:${block.id}:${effortSlug}`;
448
+ const prev = priorEfforts.find((r) => r.id === effId);
449
+ nextEfforts.push({
450
+ ...prev ?? {},
451
+ id: effId,
452
+ noteId,
453
+ blockId: block.id,
454
+ ...fingerprint ? { blockContentId: fingerprint } : {},
455
+ effortSlug,
456
+ createdAt: prev?.createdAt ?? now
457
+ });
458
+ }
459
+ for (const eqSlug of refs.equipment) {
460
+ allEquipSlugs.add(eqSlug);
461
+ const eqId = `${noteId}:${block.id}:${eqSlug}`;
462
+ const prev = priorEquipment.find((r) => r.id === eqId);
463
+ nextEquipment.push({
464
+ ...prev ?? {},
465
+ id: eqId,
466
+ noteId,
467
+ blockId: block.id,
468
+ ...fingerprint ? { blockContentId: fingerprint } : {},
469
+ equipmentSlug: eqSlug,
470
+ createdAt: prev?.createdAt ?? now
471
+ });
472
+ }
473
+ }
474
+ }
475
+ if (!rowsEqual(existing, note)) {
476
+ await tx.readwrite("notes").put(note);
477
+ }
478
+ if (newRevisions.length > 0) {
479
+ await tx.readwrite("block_revisions").putMany(newRevisions);
480
+ }
481
+ await diffProjectionRows(tx, "block_index", priorRows, nextRows);
482
+ await diffProjectionRows(tx, "block_efforts", priorEfforts, nextEfforts);
483
+ await diffProjectionRows(tx, "block_equipment", priorEquipment, nextEquipment);
484
+ const prevNoteTags = await tx.readonly("note_tags").getAllFromIndex("by-note", noteId);
485
+ const nextNoteTags = /* @__PURE__ */ new Map();
486
+ for (const item of extractedTags) {
487
+ const label = item.label.trim();
488
+ if (!label) continue;
489
+ const found = (await tx.readonly("tags").getAllFromIndex("by-label", label))[0];
490
+ const tagRow = found ? { ...found, ...!found.type && item.type ? { type: item.type } : {} } : { id: mintAgentUuid(), label, ...item.type ? { type: item.type } : {}, createdAt: now };
491
+ if (!rowsEqual(found, tagRow)) await tx.readwrite("tags").put(tagRow);
492
+ const linkId = prevNoteTags.find((l) => l.tagId === tagRow.id)?.id ?? `${noteId}:${tagRow.id}`;
493
+ nextNoteTags.set(linkId, { id: linkId, noteId, tagId: tagRow.id });
494
+ }
495
+ for (const prev of prevNoteTags) {
496
+ if (!nextNoteTags.has(prev.id)) await tx.readwrite("note_tags").delete(prev.id);
497
+ }
498
+ for (const link of nextNoteTags.values()) {
499
+ await tx.readwrite("note_tags").put(link);
500
+ }
501
+ const links = notebookIds.map((nbId) => ({
502
+ id: makeNotebookLinkId(toNotebookId(nbId), "note", noteId),
503
+ notebookId: toNotebookId(nbId),
504
+ targetKind: "note",
505
+ targetId: noteId,
506
+ noteId,
507
+ createdAt: now
508
+ }));
509
+ if (links.length > 0) {
510
+ await tx.readwrite("notebook_links").putMany(links);
511
+ }
512
+ if (input.journalDate) {
513
+ const dateKey = civilDateKey(input.journalDate, now);
514
+ let pages;
515
+ try {
516
+ pages = await tx.readonly("page").getAllFromIndex("by-date", dateKey);
517
+ } catch {
518
+ pages = (await tx.readonly("page").getAll()).filter((p) => p.date === dateKey);
519
+ }
520
+ let targetPage = pages[0];
521
+ if (!targetPage) {
522
+ targetPage = {
523
+ id: mintAgentUuid(),
524
+ date: dateKey,
525
+ title: dateKey,
526
+ createdAt: now
527
+ };
528
+ await tx.readwrite("page").put(targetPage);
529
+ }
530
+ const existingPlacements = await tx.readonly("page_notes").getAllFromIndex("by-page", targetPage.id);
531
+ if (!existingPlacements.some((p) => p.noteId === noteId)) {
532
+ const maxPos = existingPlacements.reduce(
533
+ (m, p) => typeof p.position === "number" && p.position > m ? p.position : m,
534
+ -1
535
+ );
536
+ await tx.readwrite("page_notes").put({
537
+ id: mintAgentUuid(),
538
+ pageId: targetPage.id,
539
+ noteId,
540
+ position: maxPos + 1,
541
+ createdAt: now
542
+ });
543
+ }
544
+ }
545
+ return {
546
+ note,
547
+ created: !existing,
548
+ blockCount: nextRows.length,
549
+ effortSlugs: [...allEffortSlugs],
550
+ equipmentSlugs: [...allEquipSlugs],
551
+ tagLabels: extractedTags.map((t) => t.label)
552
+ };
553
+ }
554
+ );
555
+ }
556
+ async function deleteNoteFromStorage(storage, noteId) {
557
+ return storage.transaction(
558
+ [
559
+ "notes",
560
+ "attachments",
561
+ "note_tags",
562
+ "block_index",
563
+ "block_efforts",
564
+ "block_equipment",
565
+ "page_notes",
566
+ "notebook_links",
567
+ "meta"
568
+ ],
569
+ "readwrite",
570
+ async (tx) => {
571
+ const note = await tx.readonly("notes").get(noteId);
572
+ if (!note) return false;
573
+ await tx.readwrite("notes").delete(noteId);
574
+ for (const att of await tx.readonly("attachments").getAllFromIndex("by-note", noteId)) {
575
+ await tx.readwrite("attachments").delete(att.id);
576
+ }
577
+ for (const link of await tx.readonly("note_tags").getAllFromIndex("by-note", noteId)) {
578
+ await tx.readwrite("note_tags").delete(link.id);
579
+ }
580
+ for (const row of await tx.readonly("block_index").getAllFromIndex("by-note", noteId)) {
581
+ await tx.readwrite("block_index").delete(row.id);
582
+ }
583
+ for (const row of await tx.readonly("block_efforts").getAllFromIndex("by-note", noteId)) {
584
+ await tx.readwrite("block_efforts").delete(row.id);
585
+ }
586
+ for (const row of await tx.readonly("block_equipment").getAllFromIndex("by-note", noteId)) {
587
+ await tx.readwrite("block_equipment").delete(row.id);
588
+ }
589
+ for (const pn of await tx.readonly("page_notes").getAllFromIndex("by-note", noteId)) {
590
+ await tx.readwrite("page_notes").delete(pn.id);
591
+ }
592
+ try {
593
+ for (const nl of await tx.readonly("notebook_links").getAllFromIndex("by-note", noteId)) {
594
+ await tx.readwrite("notebook_links").delete(nl.id);
595
+ }
596
+ } catch {
597
+ }
598
+ if (note.seedOrigin === "seed" || note.seedChunkId !== void 0 || note.sourcePath !== void 0) {
599
+ await tx.readwrite("meta").put({ key: userDeletedSeedKey(noteId), value: Date.now() });
600
+ }
601
+ return true;
602
+ }
603
+ );
604
+ }
605
+ async function deleteSessionFromStorage(storage, sessionId) {
606
+ return storage.transaction(["sessions", "events", "notebook_links"], "readwrite", async (tx) => {
607
+ const existing = await tx.readonly("sessions").get(sessionId);
608
+ if (!existing) return false;
609
+ await tx.readwrite("sessions").delete(sessionId);
610
+ const allEvents = await tx.readonly("events").getAll();
611
+ for (const ev of allEvents) {
612
+ if (ev.resultId === sessionId) {
613
+ await tx.readwrite("events").delete(ev.id);
614
+ }
615
+ }
616
+ try {
617
+ const links = await tx.readonly("notebook_links").getAll();
618
+ for (const link of links) {
619
+ if (link.targetKind === "session" && link.targetId === sessionId) {
620
+ await tx.readwrite("notebook_links").delete(link.id);
621
+ }
622
+ }
623
+ } catch {
624
+ }
625
+ return true;
626
+ });
627
+ }
628
+ function noteDeepLink(note, baseUrl = "") {
629
+ const prefix = baseUrl.replace(/\/+$/, "");
630
+ return `${prefix}/note/${encodeURIComponent(note.id)}`;
631
+ }
632
+ var catalogLookupInputSchema = z.object({
633
+ kind: z.enum(["effort", "equipment", "tag", "tag-type"]).describe("Catalog family to search or inspect."),
634
+ search: z.string().optional().describe("Case-insensitive slug, label, or alias filter."),
635
+ slug: z.string().optional().describe("Exact canonical slug/name to look up."),
636
+ notebookId: z.string().optional().describe("Optional Notebook scope for property inheritance resolution."),
637
+ limit: z.number().int().min(1).max(250).optional().describe("Max entries to return (default 50).")
638
+ });
639
+ var wodCatalogLookupTool = defineAgentTool({
640
+ name: "wod_catalog_lookup",
641
+ title: "Lookup Efforts, Equipment & Tags",
642
+ description: "Search or inspect the Effort movement registry, Equipment catalog, Tags, and Tag Categories with Notebook-scoped override precedence (`notebook/defaults` -> Feed/Notebook -> `notebook/custom`).",
643
+ tier: 0,
644
+ domain: "catalog",
645
+ annotations: {
646
+ title: "Lookup Catalog",
647
+ readOnlyHint: true,
648
+ destructiveHint: false,
649
+ idempotentHint: true,
650
+ openWorldHint: false
651
+ },
652
+ inputSchema: catalogLookupInputSchema,
653
+ cliEquivalent: "wod catalog <efforts|equipment|tags> --json",
654
+ async execute(args, ctx) {
655
+ const resolved = await resolveScopedPropertyCatalog(ctx.storage, {
656
+ ...args.notebookId ? { notebookId: args.notebookId } : {},
657
+ mode: "custom-runtime"
658
+ });
659
+ const limit = args.limit ?? 50;
660
+ const q = args.search?.trim().toLowerCase();
661
+ const exactSlug = args.slug?.trim().toLowerCase();
662
+ if (args.kind === "effort") {
663
+ const merged = /* @__PURE__ */ new Map();
664
+ for (const eff of bundledEfforts) merged.set(eff.slug, eff);
665
+ for (const eff of resolved.efforts) merged.set(eff.slug, eff);
666
+ const items2 = [...merged.values()].filter((e) => {
667
+ if (exactSlug) return e.slug.toLowerCase() === exactSlug;
668
+ if (!q) return true;
669
+ return e.slug.toLowerCase().includes(q) || e.label.toLowerCase().includes(q) || (e.aliases ?? []).some((a) => a.toLowerCase().includes(q));
670
+ });
671
+ return {
672
+ kind: "effort",
673
+ totalCount: items2.length,
674
+ items: items2.slice(0, limit).map((e) => ({
675
+ slug: e.slug,
676
+ label: e.label,
677
+ aliases: e.aliases ?? [],
678
+ met: e.baseAttributes?.met,
679
+ scope: resolved.originByKey.get(`effort:${e.slug}`) ?? "notebook/defaults",
680
+ ...exactSlug ? { markdown: effortToMarkdown(e) } : {}
681
+ }))
682
+ };
683
+ }
684
+ if (args.kind === "equipment") {
685
+ const items2 = resolved.equipment.filter((eq) => {
686
+ if (exactSlug) return eq.slug.toLowerCase() === exactSlug;
687
+ if (!q) return true;
688
+ return eq.slug.toLowerCase().includes(q) || eq.label.toLowerCase().includes(q) || (eq.aliases ?? []).some((a) => a.toLowerCase().includes(q));
689
+ });
690
+ return {
691
+ kind: "equipment",
692
+ totalCount: items2.length,
693
+ items: items2.slice(0, limit).map((eq) => ({
694
+ slug: eq.slug,
695
+ label: eq.label,
696
+ aliases: eq.aliases ?? [],
697
+ scope: resolved.originByKey.get(`equipment:${eq.slug}`) ?? "notebook/defaults",
698
+ ...exactSlug ? { markdown: equipmentToMarkdown(eq) } : {}
699
+ }))
700
+ };
701
+ }
702
+ if (args.kind === "tag") {
703
+ const items2 = resolved.tags.filter((t) => {
704
+ if (exactSlug) return t.label.toLowerCase() === exactSlug;
705
+ if (!q) return true;
706
+ return t.label.toLowerCase().includes(q) || (t.type ?? "").toLowerCase().includes(q);
707
+ });
708
+ return {
709
+ kind: "tag",
710
+ totalCount: items2.length,
711
+ items: items2.slice(0, limit).map((t) => ({
712
+ id: t.id,
713
+ label: t.label,
714
+ type: t.type ?? "general",
715
+ contributions: t.contributions ?? [],
716
+ scope: resolved.originByKey.get(`tag:${t.label}`) ?? "notebook/defaults"
717
+ }))
718
+ };
719
+ }
720
+ const items = resolved.tagTypes.filter((tt) => {
721
+ if (exactSlug) return tt.name.toLowerCase() === exactSlug;
722
+ if (!q) return true;
723
+ return tt.name.toLowerCase().includes(q) || tt.label.toLowerCase().includes(q);
724
+ });
725
+ return {
726
+ kind: "tag-type",
727
+ totalCount: items.length,
728
+ items: items.slice(0, limit)
729
+ };
730
+ }
731
+ });
732
+ var catalogUpsertInputSchema = z.object({
733
+ kind: z.enum(["effort", "equipment", "tag", "tag-type"]).describe("Property definition family to create or override."),
734
+ slug: z.string().min(1).describe('Canonical kebab-case slug (e.g. "kettlebell-swing", "barbell").'),
735
+ label: z.string().optional().describe("Human-readable display label."),
736
+ targetNotebookId: z.string().optional().describe('Target Notebook scope: defaults to "notebook/custom" (personal runtime) or a writable user Notebook.'),
737
+ markdown: z.string().optional().describe("Full Property Note Markdown with YAML frontmatter. If omitted, synthesized from structured fields below."),
738
+ met: z.number().positive().optional().describe('MET metabolic equivalent (for kind="effort", default 5.0).'),
739
+ aliases: z.array(z.string()).optional().describe("Optional movement/equipment aliases."),
740
+ category: z.string().optional().describe('Tag category when kind="tag" (e.g. "equipment", "quality", "format").'),
741
+ color: z.string().optional().describe('Hex color when kind="tag-type" (e.g. "#10b981").')
742
+ });
743
+ function synthesizePropertyMarkdown(args) {
744
+ if (args.markdown?.trim()) return args.markdown;
745
+ const slug = args.slug.trim().toLowerCase();
746
+ const label = args.label?.trim() || slug;
747
+ const aliasesYaml = args.aliases && args.aliases.length > 0 ? `
748
+ aliases:
749
+ ${args.aliases.map((a) => ` - ${JSON.stringify(a)}`).join("\n")}` : "";
750
+ if (args.kind === "effort") {
751
+ const met = args.met ?? 5;
752
+ return `---
753
+ id: effort-${slug}
754
+ slug: ${slug}
755
+ label: ${JSON.stringify(label)}${aliasesYaml}
756
+ baseAttributes:
757
+ met: ${met}
758
+ ---
759
+
760
+ # ${label}
761
+ `;
762
+ }
763
+ if (args.kind === "equipment") {
764
+ return `---
765
+ type: equipment
766
+ id: equipment-${slug}
767
+ slug: ${slug}
768
+ label: ${JSON.stringify(label)}${aliasesYaml}
769
+ ---
770
+
771
+ # ${label}
772
+ `;
773
+ }
774
+ if (args.kind === "tag") {
775
+ const cat = args.category ?? "general";
776
+ return `---
777
+ type: tag
778
+ id: tag-${slug}
779
+ slug: ${slug}
780
+ label: ${JSON.stringify(label)}
781
+ category: ${cat}
782
+ ---
783
+
784
+ # ${label}
785
+ `;
786
+ }
787
+ const color = args.color ?? "#6366f1";
788
+ return `---
789
+ type: tag-type
790
+ id: type-${slug}
791
+ slug: ${slug}
792
+ label: ${JSON.stringify(label)}
793
+ color: ${JSON.stringify(color)}
794
+ ---
795
+
796
+ # ${label}
797
+ `;
798
+ }
799
+ var wodCatalogUpsertTool = defineAgentTool({
800
+ name: "wod_catalog_upsert",
801
+ title: "Save Effort, Equipment, or Tag Property Note",
802
+ description: "Create or update a Scoped Property Override (`effort`, `equipment`, `tag`, or `tag-type`) in `notebook/custom` or a shared user Notebook.",
803
+ tier: 1,
804
+ domain: "catalog",
805
+ annotations: {
806
+ title: "Save Catalog Property",
807
+ readOnlyHint: false,
808
+ destructiveHint: false,
809
+ idempotentHint: true,
810
+ openWorldHint: false
811
+ },
812
+ inputSchema: catalogUpsertInputSchema,
813
+ cliEquivalent: "wod catalog save <kind> <file|-> --json",
814
+ async execute(args, ctx) {
815
+ const rawContent = synthesizePropertyMarkdown(args);
816
+ const saved = await saveScopedPropertyOverride(ctx.storage, {
817
+ targetNotebookId: args.targetNotebookId ?? "notebook/custom",
818
+ kind: args.kind,
819
+ slug: args.slug,
820
+ rawContent,
821
+ title: args.label,
822
+ category: args.category
823
+ });
824
+ await ctx.onMutated?.([
825
+ "notes",
826
+ "block_revisions",
827
+ "property_overrides",
828
+ "efforts",
829
+ "equipment",
830
+ "tags",
831
+ "tag_types"
832
+ ]);
833
+ return {
834
+ id: saved.id,
835
+ kind: saved.kind,
836
+ slug: saved.slug,
837
+ label: saved.label,
838
+ notebookId: saved.notebookId,
839
+ ownerNoteId: saved.ownerNoteId
840
+ };
841
+ }
842
+ });
843
+ var CATALOG_AGENT_TOOLS = [wodCatalogLookupTool, wodCatalogUpsertTool];
844
+ var feedManageInputSchema = z.object({
845
+ action: z.enum(["list", "status", "publish", "import-bundle"]).describe("Feed or portability operation to run."),
846
+ notebookSlug: z.string().optional().describe("Optional Notebook slug filter when publishing."),
847
+ name: z.string().optional().describe("Optional Feed display name when publishing."),
848
+ description: z.string().optional().describe("Optional Feed description when publishing."),
849
+ files: z.array(
850
+ z.object({
851
+ path: z.string().min(1),
852
+ content: z.string()
853
+ })
854
+ ).optional().describe('Portable `.md` / `.jsonl` / `.csv` files when action="import-bundle".')
855
+ });
856
+ var wodFeedManageTool = defineAgentTool({
857
+ name: "wod_feed_manage",
858
+ title: "Manage Feeds & Portability",
859
+ description: "Inspect installed Seed/Feed sources (`list`), check unpublished public Notebook changes (`status`), compile and publish public Notebooks (`publish`), or import portable Markdown + JSONL/CSV files (`import-bundle`).",
860
+ tier: 1,
861
+ domain: "feed",
862
+ annotations: {
863
+ title: "Manage Feeds",
864
+ readOnlyHint: false,
865
+ destructiveHint: false,
866
+ idempotentHint: true,
867
+ openWorldHint: false
868
+ },
869
+ inputSchema: feedManageInputSchema,
870
+ cliEquivalent: "wod feed <list|status|publish> --json",
871
+ async execute(args, ctx) {
872
+ if (args.action === "list") {
873
+ const metaRows = await ctx.storage.readonly("meta").getAll();
874
+ const installedFeeds = [];
875
+ for (const row of metaRows) {
876
+ const obj = row;
877
+ if (typeof obj.key === "string" && obj.key.startsWith("seed:") && obj.key !== seedMetaKey("user")) {
878
+ installedFeeds.push({
879
+ sourceId: obj.key.slice("seed:".length),
880
+ seedVersion: obj.seedVersion,
881
+ builtAt: obj.builtAt,
882
+ importedAt: obj.importedAt,
883
+ chunkCount: Object.keys(obj.chunks ?? {}).length
884
+ });
885
+ }
886
+ }
887
+ return {
888
+ action: "list",
889
+ installedCount: installedFeeds.length,
890
+ feeds: installedFeeds
891
+ };
892
+ }
893
+ if (args.action === "status") {
894
+ const status = await checkUnpublishedFeedChanges(ctx.storage, ctx.feedTree);
895
+ return {
896
+ action: "status",
897
+ ...status
898
+ };
899
+ }
900
+ if (args.action === "publish") {
901
+ const tree = ctx.feedTree ?? new MemoryFeedTree();
902
+ const report2 = await publishFeedFromStorage(ctx.storage, tree, {
903
+ layout: "feed",
904
+ notebookSlug: args.notebookSlug,
905
+ name: args.name,
906
+ description: args.description
907
+ });
908
+ await ctx.onMutated?.(["meta", "property_overrides"]);
909
+ return {
910
+ action: "publish",
911
+ notebooks: report2.notebooks,
912
+ totalNotes: report2.totalNotes,
913
+ totalPublicSessions: report2.totalPublicSessions,
914
+ manifestVersion: report2.manifest.version,
915
+ manifestSha256: report2.manifestSha256
916
+ };
917
+ }
918
+ if (!args.files || args.files.length === 0) {
919
+ throw new Error('Provide non-empty `files` array when action="import-bundle".');
920
+ }
921
+ const report = await ingestPortableFilesIntoStorage(ctx.storage, args.files, {
922
+ defaultNotebookId: args.notebookSlug
923
+ });
924
+ await ctx.onMutated?.([
925
+ "notes",
926
+ "block_revisions",
927
+ "block_index",
928
+ "tags",
929
+ "note_tags",
930
+ "sessions",
931
+ "events"
932
+ ]);
933
+ return {
934
+ action: "import-bundle",
935
+ ...report
936
+ };
937
+ }
938
+ });
939
+ var exportBundleInputSchema = z.object({
940
+ noteIds: z.array(z.string()).optional().describe("Optional Note IDs to export (defaults to all user-owned Notes)."),
941
+ telemetryFormat: z.enum(["jsonl", "csv", "both"]).optional().describe('Format for companion Session/Event telemetry files (default "jsonl").')
942
+ });
943
+ var wodExportBundleTool = defineAgentTool({
944
+ name: "wod_export_bundle",
945
+ title: "Export Portable Markdown & Telemetry Bundle",
946
+ description: "Export user Notes and attached Session telemetry directly as structured `{ path, content }` strings (Markdown + JSONL/CSV) without triggering synthetic browser file downloads.",
947
+ tier: 0,
948
+ domain: "feed",
949
+ annotations: {
950
+ title: "Export Portable Bundle",
951
+ readOnlyHint: true,
952
+ destructiveHint: false,
953
+ idempotentHint: true,
954
+ openWorldHint: false
955
+ },
956
+ inputSchema: exportBundleInputSchema,
957
+ cliEquivalent: "wod export note <id> -o -",
958
+ async execute(args, ctx) {
959
+ const files = await exportPortableFilesFromStorage(ctx.storage, {
960
+ noteIds: args.noteIds,
961
+ telemetryFormat: args.telemetryFormat ?? "jsonl"
962
+ });
963
+ return {
964
+ fileCount: files.length,
965
+ files
966
+ };
967
+ }
968
+ });
969
+ var resetStorageInputSchema = z.object({
970
+ confirmToken: z.string().optional().describe('For non-interactive MCP/CLI calls, pass confirmToken="WIPE_STORAGE" to confirm wiping user storage.')
971
+ });
972
+ var wodResetStorageTool = defineAgentTool({
973
+ name: "wod_reset_storage",
974
+ title: "Wipe Storage Data",
975
+ description: "Wipe user Notes, Sessions, Events, and Notebook data from the active storage backend (Tier 2 destructive \u2014 requires explicit user confirmation).",
976
+ tier: 2,
977
+ domain: "system",
978
+ annotations: {
979
+ title: "Wipe Storage Data",
980
+ readOnlyHint: false,
981
+ destructiveHint: true,
982
+ idempotentHint: true,
983
+ openWorldHint: false
984
+ },
985
+ inputSchema: resetStorageInputSchema,
986
+ cliEquivalent: "wod reset --yes WIPE_STORAGE --json",
987
+ async execute(args, ctx) {
988
+ await requireDestructiveConfirmation(
989
+ ctx,
990
+ {
991
+ action: "wod_reset_storage",
992
+ targetId: "WIPE_STORAGE",
993
+ summary: "Wipe all user Notes, Sessions, and telemetry from WOD Wiki storage"
994
+ },
995
+ args.confirmToken
996
+ );
997
+ await ctx.storage.wipe();
998
+ await ctx.onMutated?.(["notes", "sessions", "events", "page", "page_notes", "notebook_links"]);
999
+ return { wiped: true };
1000
+ }
1001
+ });
1002
+ var FEED_AGENT_TOOLS = [
1003
+ wodFeedManageTool,
1004
+ wodExportBundleTool,
1005
+ wodResetStorageTool
1006
+ ];
1007
+ var journalDayInputSchema = z.object({
1008
+ date: z.string().optional().describe('Calendar date in YYYY-MM-DD format, or "today" (defaults to "today").')
1009
+ });
1010
+ var wodJournalDayTool = defineAgentTool({
1011
+ name: "wod_journal_day",
1012
+ title: "Get Journal Day",
1013
+ description: "Fetch all scheduled/authored workout Notes and recorded Sessions for a specific Journal calendar day (`YYYY-MM-DD` or `today`).",
1014
+ tier: 0,
1015
+ domain: "journal",
1016
+ annotations: {
1017
+ title: "Get Journal Day",
1018
+ readOnlyHint: true,
1019
+ destructiveHint: false,
1020
+ idempotentHint: true,
1021
+ openWorldHint: false
1022
+ },
1023
+ inputSchema: journalDayInputSchema,
1024
+ cliEquivalent: "wod journal [today|YYYY-MM-DD] --json",
1025
+ async execute(args, ctx) {
1026
+ const dateKey = civilDateKey(args.date);
1027
+ const dayStart = Date.parse(`${dateKey}T00:00:00Z`);
1028
+ const dayEnd = Date.parse(`${dateKey}T23:59:59.999Z`);
1029
+ let pages;
1030
+ try {
1031
+ pages = await ctx.storage.readonly("page").getAllFromIndex("by-date", dateKey);
1032
+ } catch {
1033
+ pages = (await ctx.storage.readonly("page").getAll()).filter((p) => p.date === dateKey);
1034
+ }
1035
+ const page = pages[0];
1036
+ const placedNoteIds = [];
1037
+ if (page) {
1038
+ const links = orderPlacements(
1039
+ await ctx.storage.readonly("page_notes").getAllFromIndex("by-page", page.id)
1040
+ );
1041
+ for (const link of links) {
1042
+ if (!placedNoteIds.includes(link.noteId)) placedNoteIds.push(link.noteId);
1043
+ }
1044
+ }
1045
+ const [allNotes, allSessions] = await Promise.all([
1046
+ ctx.storage.readonly("notes").getAll(),
1047
+ ctx.storage.readonly("sessions").getAll()
1048
+ ]);
1049
+ const notesById = new Map(allNotes.map((n) => [n.id, n]));
1050
+ const dayNotes = [];
1051
+ const seenIds = /* @__PURE__ */ new Set();
1052
+ for (const id of placedNoteIds) {
1053
+ const n = notesById.get(id);
1054
+ if (n) {
1055
+ dayNotes.push(n);
1056
+ seenIds.add(n.id);
1057
+ }
1058
+ }
1059
+ for (const n of allNotes) {
1060
+ if (seenIds.has(n.id)) continue;
1061
+ if (n.seedOrigin === "seed" || n.feedOrigin === "feed") continue;
1062
+ if (n.id.startsWith("notebook/") && n.notebookId === n.id) continue;
1063
+ const effectiveDate = n.date ?? n.createdAt;
1064
+ if (effectiveDate >= dayStart && effectiveDate <= dayEnd) {
1065
+ dayNotes.push(n);
1066
+ seenIds.add(n.id);
1067
+ }
1068
+ }
1069
+ const daySessions = allSessions.filter((s) => {
1070
+ if (page && s.pageId === page.id) return true;
1071
+ if (seenIds.has(s.noteId) && s.startTime >= dayStart && s.startTime <= dayEnd) return true;
1072
+ return s.startTime >= dayStart && s.startTime <= dayEnd;
1073
+ }).sort((a, b) => a.startTime - b.startTime);
1074
+ const prefix = (ctx.baseUrl ?? "").replace(/\/+$/, "");
1075
+ return {
1076
+ date: dateKey,
1077
+ url: `${prefix}/journal/${dateKey}`,
1078
+ pageId: page?.id ?? null,
1079
+ noteCount: dayNotes.length,
1080
+ notes: dayNotes.map((n) => ({
1081
+ id: n.id,
1082
+ title: n.title,
1083
+ sourceRevision: n.sourceRevision,
1084
+ rawContent: n.rawContent,
1085
+ tags: n.tags ?? [],
1086
+ wodBlockIds: Object.values(n.blocks ?? {}).filter((b) => b.kind === "wod").map((b) => b.id),
1087
+ url: noteDeepLink(n, ctx.baseUrl)
1088
+ })),
1089
+ sessionCount: daySessions.length,
1090
+ sessions: daySessions.map((s) => ({
1091
+ id: s.id,
1092
+ noteId: s.noteId,
1093
+ blockId: s.blockId,
1094
+ status: s.status,
1095
+ completed: s.completed,
1096
+ duration: s.duration,
1097
+ startTime: s.startTime
1098
+ }))
1099
+ };
1100
+ }
1101
+ });
1102
+ var journalAddInputSchema = z.object({
1103
+ date: z.string().optional().describe('Target Journal date in YYYY-MM-DD format or "today" (defaults to "today").'),
1104
+ title: z.string().optional().describe("Workout title (defaults to # H1 heading or date)."),
1105
+ content: z.string().min(1).describe("Markdown workout note or bare Whiteboard Script to schedule onto the Journal day."),
1106
+ sport: z.string().optional().describe("Optional sport fence tag when passing bare Whiteboard Script."),
1107
+ notebookId: z.string().optional().describe("Optional additional user Notebook to promote this Journal Note into.")
1108
+ });
1109
+ var wodJournalAddTool = defineAgentTool({
1110
+ name: "wod_journal_add",
1111
+ title: "Add Workout to Journal Day",
1112
+ description: "Create a new workout Note in `notebook/journal` and place it onto the specified calendar day (`YYYY-MM-DD` or `today`).",
1113
+ tier: 1,
1114
+ domain: "journal",
1115
+ annotations: {
1116
+ title: "Add Workout to Journal Day",
1117
+ readOnlyHint: false,
1118
+ destructiveHint: false,
1119
+ idempotentHint: false,
1120
+ openWorldHint: false
1121
+ },
1122
+ inputSchema: journalAddInputSchema,
1123
+ cliEquivalent: "wod journal add <file|-> --date YYYY-MM-DD --json",
1124
+ async execute(args, ctx) {
1125
+ const dateKey = civilDateKey(args.date);
1126
+ const effectiveTitle = args.title ?? `Workout ${dateKey}`;
1127
+ const rawContent = normalizeMarkdownOrBareScript(args.content, args.sport, args.title);
1128
+ const saved = await upsertNoteInStorage(ctx.storage, {
1129
+ title: effectiveTitle,
1130
+ rawContent,
1131
+ journalDate: dateKey,
1132
+ notebookId: args.notebookId,
1133
+ type: "journal"
1134
+ });
1135
+ await ctx.onMutated?.([
1136
+ "notes",
1137
+ "block_revisions",
1138
+ "block_index",
1139
+ "block_efforts",
1140
+ "block_equipment",
1141
+ "page",
1142
+ "page_notes",
1143
+ "notebook_links"
1144
+ ]);
1145
+ const prefix = (ctx.baseUrl ?? "").replace(/\/+$/, "");
1146
+ return {
1147
+ date: dateKey,
1148
+ noteId: saved.note.id,
1149
+ journalUrl: `${prefix}/journal/${dateKey}`,
1150
+ note: {
1151
+ id: saved.note.id,
1152
+ title: saved.note.title,
1153
+ sourceRevision: saved.note.sourceRevision,
1154
+ blockCount: saved.blockCount,
1155
+ effortSlugs: saved.effortSlugs,
1156
+ url: noteDeepLink(saved.note, ctx.baseUrl)
1157
+ }
1158
+ };
1159
+ }
1160
+ });
1161
+ var JOURNAL_AGENT_TOOLS = [wodJournalDayTool, wodJournalAddTool];
1162
+ function isLandingNote(note) {
1163
+ return note.id.startsWith("notebook/") && note.notebookId === note.id;
1164
+ }
1165
+ var RESERVED_SLUGS = new Set(BUILTIN_NOTEBOOKS.map((b) => b.slug));
1166
+ var notebookListInputSchema = z.object({
1167
+ origin: z.enum(["all", "default", "user", "feed"]).optional().describe('Filter notebooks by origin (default "all").')
1168
+ });
1169
+ var wodNotebookListTool = defineAgentTool({
1170
+ name: "wod_notebook_list",
1171
+ title: "List Notebooks",
1172
+ description: "List built-in, user-created, and feed-subscribed Notebooks along with member Note counts and publication status.",
1173
+ tier: 0,
1174
+ domain: "notebook",
1175
+ annotations: {
1176
+ title: "List Notebooks",
1177
+ readOnlyHint: true,
1178
+ destructiveHint: false,
1179
+ idempotentHint: true,
1180
+ openWorldHint: false
1181
+ },
1182
+ inputSchema: notebookListInputSchema,
1183
+ cliEquivalent: "wod notebook list --json",
1184
+ async execute(args, ctx) {
1185
+ const [allNotes, allLinks] = await Promise.all([
1186
+ ctx.storage.readonly("notes").getAll(),
1187
+ ctx.storage.readonly("notebook_links").getAll().catch(() => [])
1188
+ ]);
1189
+ const counts = /* @__PURE__ */ new Map();
1190
+ const countedPairs = /* @__PURE__ */ new Set();
1191
+ const bump = (nbId, noteId) => {
1192
+ const key = `${nbId}\0${noteId}`;
1193
+ if (countedPairs.has(key)) return;
1194
+ countedPairs.add(key);
1195
+ counts.set(nbId, (counts.get(nbId) ?? 0) + 1);
1196
+ };
1197
+ for (const link of allLinks) {
1198
+ if (link.targetKind === "note") bump(toNotebookId(link.notebookId), link.noteId);
1199
+ }
1200
+ for (const n of allNotes) {
1201
+ if (isLandingNote(n)) continue;
1202
+ for (const nbId of notebooksOfItem(n)) {
1203
+ bump(toNotebookId(nbId), n.id);
1204
+ }
1205
+ }
1206
+ const byId = /* @__PURE__ */ new Map();
1207
+ for (const spec of BUILTIN_NOTEBOOKS) {
1208
+ byId.set(spec.notebookId, {
1209
+ notebookId: spec.notebookId,
1210
+ slug: spec.slug,
1211
+ name: spec.name,
1212
+ description: spec.description,
1213
+ icon: spec.icon,
1214
+ origin: "default",
1215
+ writable: !isSystemReadOnlyNotebook(spec.notebookId),
1216
+ public: false,
1217
+ noteCount: counts.get(spec.notebookId) ?? 0
1218
+ });
1219
+ }
1220
+ for (const n of allNotes) {
1221
+ if (!isLandingNote(n)) continue;
1222
+ const slug = notebookSlugFromId(n.id);
1223
+ const fm = readFrontmatterMeta(n.rawContent);
1224
+ const description = typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : "";
1225
+ const icon = typeof fm["icon"] === "string" ? fm["icon"].replace(/^"|"$/g, "") : "\u{1F4D3}";
1226
+ const isFeed = n.feedOrigin === "feed" || n.seedOrigin === "seed";
1227
+ const existing = byId.get(n.id);
1228
+ byId.set(n.id, {
1229
+ notebookId: n.id,
1230
+ slug,
1231
+ name: n.title || existing?.name || slug,
1232
+ description: description || existing?.description || "",
1233
+ icon: icon || existing?.icon || "\u{1F4D3}",
1234
+ origin: existing?.origin ?? (isFeed ? "feed" : "user"),
1235
+ writable: !isSystemReadOnlyNotebook(n.id) && !isFeed,
1236
+ public: n.public === true,
1237
+ noteCount: counts.get(n.id) ?? 0
1238
+ });
1239
+ }
1240
+ const filterOrigin = args.origin ?? "all";
1241
+ const prefix = (ctx.baseUrl ?? "").replace(/\/+$/, "");
1242
+ const notebooks = [...byId.values()].filter((nb) => filterOrigin === "all" || nb.origin === filterOrigin).map((nb) => ({
1243
+ id: nb.notebookId,
1244
+ ...nb,
1245
+ url: `${prefix}/notebooks/${encodeURIComponent(nb.slug)}`
1246
+ }));
1247
+ return {
1248
+ totalCount: notebooks.length,
1249
+ notebooks
1250
+ };
1251
+ }
1252
+ });
1253
+ var notebookSaveInputSchema = z.object({
1254
+ action: z.enum(["create", "update", "promote", "detach", "set-public"]).describe("Operation to perform on a user Notebook."),
1255
+ notebookId: z.string().optional().describe("Target Notebook slug or ID (required for update, promote, detach, set-public)."),
1256
+ name: z.string().optional().describe("Display name when creating or renaming a Notebook."),
1257
+ description: z.string().optional().describe("Notebook description."),
1258
+ icon: z.string().optional().describe("Notebook icon/emoji."),
1259
+ noteId: z.string().optional().describe("Note ID to promote into or detach from the Notebook."),
1260
+ sessionIds: z.array(z.string()).optional().describe("Optional Session IDs on `noteId` to promote alongside the Note."),
1261
+ public: z.boolean().optional().describe('Visibility flag when action="set-public" or promoting sessions.')
1262
+ });
1263
+ var wodNotebookSaveTool = defineAgentTool({
1264
+ name: "wod_notebook_save",
1265
+ title: "Create, Update, or Promote Notebook",
1266
+ description: "Create or update a user-owned Notebook, promote/detach a Note across Notebooks (`notebook/journal` permanence preserved), or toggle Notebook publication visibility.",
1267
+ tier: 1,
1268
+ domain: "notebook",
1269
+ annotations: {
1270
+ title: "Save or Promote Notebook",
1271
+ readOnlyHint: false,
1272
+ destructiveHint: false,
1273
+ idempotentHint: true,
1274
+ openWorldHint: false
1275
+ },
1276
+ inputSchema: notebookSaveInputSchema,
1277
+ cliEquivalent: "wod notebook <create|update|promote> --json",
1278
+ async execute(args, ctx) {
1279
+ if (args.action === "create") {
1280
+ const name = args.name?.trim() || args.notebookId?.trim();
1281
+ if (!name) throw new Error('`name` is required when action="create".');
1282
+ const nbId2 = await createUserNotebookLanding(ctx.storage, name);
1283
+ if (args.description !== void 0 || args.icon !== void 0) {
1284
+ const rawContent = `---
1285
+ description: ${JSON.stringify(args.description ?? "")}
1286
+ icon: ${JSON.stringify(args.icon ?? "\u{1F4D3}")}
1287
+ ---
1288
+
1289
+ # ${name}
1290
+ `;
1291
+ const saved = await upsertNoteInStorage(ctx.storage, {
1292
+ noteId: nbId2,
1293
+ title: name,
1294
+ rawContent
1295
+ });
1296
+ await ctx.storage.readwrite("notes").put({ ...saved.note, notebookId: nbId2 });
1297
+ }
1298
+ if (args.public !== void 0) {
1299
+ await setNotebookPublic(ctx.storage, nbId2, args.public);
1300
+ }
1301
+ await ctx.onMutated?.(["notes", "block_revisions", "notebook_links"]);
1302
+ return {
1303
+ action: "create",
1304
+ notebookId: nbId2,
1305
+ slug: notebookSlugFromId(nbId2),
1306
+ name
1307
+ };
1308
+ }
1309
+ if (!args.notebookId) {
1310
+ throw new Error(`'notebookId' is required for action="${args.action}".`);
1311
+ }
1312
+ const nbId = toNotebookId(args.notebookId);
1313
+ const slug = notebookSlugFromId(nbId);
1314
+ if (args.action === "update") {
1315
+ if (RESERVED_SLUGS.has(slug)) {
1316
+ throw new Error(`Built-in Notebook '${nbId}' cannot be modified.`);
1317
+ }
1318
+ const existing = await ctx.storage.readonly("notes").get(nbId);
1319
+ if (!existing) throw new Error(`Notebook not found: ${nbId}`);
1320
+ const fm = readFrontmatterMeta(existing.rawContent);
1321
+ const nextName = args.name ?? existing.title ?? slug;
1322
+ const nextDesc = args.description ?? (typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : "");
1323
+ const nextIcon = args.icon ?? (typeof fm["icon"] === "string" ? fm["icon"].replace(/^"|"$/g, "") : "\u{1F4D3}");
1324
+ const rawContent = `---
1325
+ description: ${JSON.stringify(nextDesc)}
1326
+ icon: ${JSON.stringify(nextIcon)}
1327
+ ---
1328
+
1329
+ # ${nextName}
1330
+ `;
1331
+ const saved = await upsertNoteInStorage(ctx.storage, {
1332
+ noteId: nbId,
1333
+ title: nextName,
1334
+ rawContent
1335
+ });
1336
+ await ctx.storage.readwrite("notes").put({
1337
+ ...saved.note,
1338
+ notebookId: nbId,
1339
+ ...existing.public !== void 0 ? { public: existing.public } : {}
1340
+ });
1341
+ await ctx.onMutated?.(["notes", "block_revisions"]);
1342
+ return { action: "update", notebookId: nbId, slug, name: nextName };
1343
+ }
1344
+ if (args.action === "promote") {
1345
+ if (!args.noteId) throw new Error('`noteId` is required when action="promote".');
1346
+ const promoted = await promoteNoteToNotebooks(ctx.storage, {
1347
+ noteId: args.noteId,
1348
+ notebookIds: [nbId],
1349
+ sessionIds: args.sessionIds,
1350
+ shareSessionsPublicly: args.public
1351
+ });
1352
+ await ctx.onMutated?.(["notes", "sessions", "notebook_links"]);
1353
+ return {
1354
+ action: "promote",
1355
+ noteId: args.noteId,
1356
+ notebookIds: promoted.notebookIds,
1357
+ promotedSessionIds: promoted.promotedSessionIds
1358
+ };
1359
+ }
1360
+ if (args.action === "detach") {
1361
+ if (!args.noteId) throw new Error('`noteId` is required when action="detach".');
1362
+ const remaining = await removeNoteFromNotebook(ctx.storage, args.noteId, nbId);
1363
+ await ctx.onMutated?.(["notes", "notebook_links"]);
1364
+ return {
1365
+ action: "detach",
1366
+ noteId: args.noteId,
1367
+ notebookIds: remaining
1368
+ };
1369
+ }
1370
+ if (isNonPublishableNotebook(nbId)) {
1371
+ throw new Error(`Notebook '${nbId}' is private/system and cannot be published.`);
1372
+ }
1373
+ const updated = await setNotebookPublic(ctx.storage, nbId, args.public ?? true);
1374
+ await ctx.onMutated?.(["notes"]);
1375
+ return {
1376
+ action: "set-public",
1377
+ notebookId: nbId,
1378
+ public: updated.public === true
1379
+ };
1380
+ }
1381
+ });
1382
+ var notebookDeleteInputSchema = z.object({
1383
+ notebookId: z.string().min(1).describe("User Notebook ID or slug to delete (member Notes stay safe in notebook/journal)."),
1384
+ confirmId: z.string().optional().describe("For non-interactive MCP/CLI calls, repeat the exact notebookId or slug to confirm deletion.")
1385
+ });
1386
+ var wodNotebookDeleteTool = defineAgentTool({
1387
+ name: "wod_notebook_delete",
1388
+ title: "Delete User Notebook",
1389
+ description: "Delete a user-created Notebook landing note and detach member links while keeping all member Notes safely in `notebook/journal` (Tier 2 destructive).",
1390
+ tier: 2,
1391
+ domain: "notebook",
1392
+ annotations: {
1393
+ title: "Delete User Notebook",
1394
+ readOnlyHint: false,
1395
+ destructiveHint: true,
1396
+ idempotentHint: true,
1397
+ openWorldHint: false
1398
+ },
1399
+ inputSchema: notebookDeleteInputSchema,
1400
+ cliEquivalent: "wod notebook delete <slug> --yes <slug> --json",
1401
+ async execute(args, ctx) {
1402
+ const nbId = toNotebookId(args.notebookId);
1403
+ const slug = notebookSlugFromId(nbId);
1404
+ if (RESERVED_SLUGS.has(slug)) {
1405
+ throw new Error(`Built-in Notebook '${nbId}' cannot be deleted.`);
1406
+ }
1407
+ const matchedConfirm = args.confirmId === nbId || args.confirmId === slug ? nbId : void 0;
1408
+ await requireDestructiveConfirmation(
1409
+ ctx,
1410
+ {
1411
+ action: "wod_notebook_delete",
1412
+ targetId: nbId,
1413
+ summary: `Delete user Notebook "${slug}" (${nbId}); member Notes remain in notebook/journal`
1414
+ },
1415
+ matchedConfirm
1416
+ );
1417
+ const allNotes = await ctx.storage.readonly("notes").getAll();
1418
+ for (const note of allNotes) {
1419
+ if (isLandingNote(note)) continue;
1420
+ if (note.notebookId === nbId || (note.notebookIds ?? []).includes(nbId)) {
1421
+ const remaining = (note.notebookIds ?? ["notebook/journal"]).map((id) => toNotebookId(id)).filter((id) => id !== nbId);
1422
+ const primaryUser = remaining.find(
1423
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
1424
+ );
1425
+ const { notebookId: _oldSingle, ...rest } = note;
1426
+ await ctx.storage.readwrite("notes").put({
1427
+ ...rest,
1428
+ notebookIds: remaining.length > 0 ? remaining : ["notebook/journal"],
1429
+ ...primaryUser ? { notebookId: primaryUser } : {}
1430
+ });
1431
+ }
1432
+ }
1433
+ try {
1434
+ const links = await ctx.storage.readonly("notebook_links").getAllFromIndex("by-notebook", nbId);
1435
+ for (const link of links) {
1436
+ await ctx.storage.readwrite("notebook_links").delete(link.id);
1437
+ }
1438
+ } catch {
1439
+ }
1440
+ const deleted = await deleteNoteFromStorage(ctx.storage, nbId);
1441
+ await ctx.onMutated?.(["notes", "notebook_links"]);
1442
+ return { deleted, notebookId: nbId, slug };
1443
+ }
1444
+ });
1445
+ var NOTEBOOK_AGENT_TOOLS = [
1446
+ wodNotebookListTool,
1447
+ wodNotebookSaveTool,
1448
+ wodNotebookDeleteTool
1449
+ ];
1450
+ function isLandingNote2(note) {
1451
+ return note.id.startsWith("notebook/") && note.notebookId === note.id;
1452
+ }
1453
+ var noteListInputSchema = z.object({
1454
+ notebookId: z.string().optional().describe('Filter by notebook ID or slug (e.g. "journal", "custom", "guides", "notebook/strength").'),
1455
+ search: z.string().optional().describe("Case-insensitive substring filter over title and Markdown content."),
1456
+ tag: z.string().optional().describe("Filter to Notes carrying this tag label."),
1457
+ includeSeed: z.boolean().optional().describe("Include read-only Seed/Feed notes (default true when notebookId is specified, false otherwise)."),
1458
+ limit: z.number().int().min(1).max(200).optional().describe("Max notes to return (default 50).")
1459
+ });
1460
+ var wodNoteListTool = defineAgentTool({
1461
+ name: "wod_note_list",
1462
+ title: "List Notes",
1463
+ description: "List workout and reference Notes with optional filtering by Notebook, search query, tag, and origin.",
1464
+ tier: 0,
1465
+ domain: "note",
1466
+ annotations: {
1467
+ title: "List Notes",
1468
+ readOnlyHint: true,
1469
+ destructiveHint: false,
1470
+ idempotentHint: true,
1471
+ openWorldHint: false
1472
+ },
1473
+ inputSchema: noteListInputSchema,
1474
+ cliEquivalent: "wod note list --json",
1475
+ async execute(args, ctx) {
1476
+ const allNotes = await ctx.storage.readonly("notes").getAll();
1477
+ const targetNb = args.notebookId ? toNotebookId(args.notebookId) : void 0;
1478
+ const includeSeed = args.includeSeed ?? Boolean(targetNb);
1479
+ const searchLower = args.search?.trim().toLowerCase();
1480
+ const tagLower = args.tag?.trim().toLowerCase();
1481
+ const limit = args.limit ?? 50;
1482
+ let linkedNoteIdsForNb;
1483
+ if (targetNb) {
1484
+ try {
1485
+ const links = await ctx.storage.readonly("notebook_links").getAllFromIndex("by-notebook", targetNb);
1486
+ linkedNoteIdsForNb = new Set(
1487
+ links.filter((l) => l.targetKind === "note").map((l) => l.noteId)
1488
+ );
1489
+ } catch {
1490
+ linkedNoteIdsForNb = /* @__PURE__ */ new Set();
1491
+ }
1492
+ }
1493
+ const filtered = allNotes.filter((n) => {
1494
+ if (isLandingNote2(n)) return false;
1495
+ if (!includeSeed && (n.seedOrigin === "seed" || n.feedOrigin === "feed")) return false;
1496
+ if (targetNb) {
1497
+ const inNb = linkedNoteIdsForNb?.has(n.id) || n.notebookId === targetNb || (n.notebookIds ?? []).includes(targetNb) || notebooksOfItem(n).includes(targetNb);
1498
+ if (!inNb) return false;
1499
+ }
1500
+ if (tagLower && !(n.tags ?? []).some((t) => t.toLowerCase() === tagLower)) {
1501
+ return false;
1502
+ }
1503
+ if (searchLower && !n.title.toLowerCase().includes(searchLower) && !n.rawContent.toLowerCase().includes(searchLower)) {
1504
+ return false;
1505
+ }
1506
+ return true;
1507
+ }).sort((a, b) => (b.date ?? b.createdAt) - (a.date ?? a.createdAt));
1508
+ return {
1509
+ totalCount: filtered.length,
1510
+ notes: filtered.slice(0, limit).map((n) => {
1511
+ const nbOrigin = notebookOriginOfItem(n);
1512
+ const resolvedNb = notebookOfItem(n);
1513
+ return {
1514
+ id: n.id,
1515
+ title: n.title,
1516
+ sourceRevision: n.sourceRevision,
1517
+ date: n.date,
1518
+ createdAt: n.createdAt,
1519
+ editable: isNoteEditable(n, nbOrigin, resolvedNb),
1520
+ notebooks: notebooksOfItem(n),
1521
+ tags: n.tags ?? [],
1522
+ wodBlockCount: Object.values(n.blocks ?? {}).filter((b) => b.kind === "wod").length,
1523
+ url: noteDeepLink(n, ctx.baseUrl)
1524
+ };
1525
+ })
1526
+ };
1527
+ }
1528
+ });
1529
+ var noteGetInputSchema = z.object({
1530
+ noteId: z.string().min(1).describe("Unique Note ID (UUID or seed route ID).")
1531
+ });
1532
+ var wodNoteGetTool = defineAgentTool({
1533
+ name: "wod_note_get",
1534
+ title: "Get Note Details",
1535
+ description: "Read a full Note by ID including authored Markdown, `sourceRevision`, parsed workout blocks, attached Session count, upstream provenance, and publication visibility.",
1536
+ tier: 0,
1537
+ domain: "note",
1538
+ annotations: {
1539
+ title: "Get Note Details",
1540
+ readOnlyHint: true,
1541
+ destructiveHint: false,
1542
+ idempotentHint: true,
1543
+ openWorldHint: false
1544
+ },
1545
+ inputSchema: noteGetInputSchema,
1546
+ cliEquivalent: "wod note get <noteId> --json",
1547
+ async execute(args, ctx) {
1548
+ const note = await ctx.storage.readonly("notes").get(args.noteId);
1549
+ if (!note) {
1550
+ throw new Error(`Note not found: ${args.noteId}`);
1551
+ }
1552
+ const nbOrigin = notebookOriginOfItem(note);
1553
+ const resolvedNb = notebookOfItem(note);
1554
+ const editable = isNoteEditable(note, nbOrigin, resolvedNb);
1555
+ const [notebooks, provenance, visibility, sessions] = await Promise.all([
1556
+ getNoteNotebooks(ctx.storage, note.id),
1557
+ resolveUpstreamProvenance(ctx.storage, note),
1558
+ getNotePublicationSummary(ctx.storage, note.id),
1559
+ ctx.storage.readonly("sessions").getAllFromIndex("by-note", note.id).catch(
1560
+ async () => (await ctx.storage.readonly("sessions").getAll()).filter((s) => s.noteId === note.id)
1561
+ )
1562
+ ]);
1563
+ const sections = parseDocumentSections(note.rawContent, {
1564
+ registeredWidgets: KNOWN_SECTION_WIDGETS
1565
+ });
1566
+ const blocks = Object.values(note.blocks ?? {}).sort((a, b) => a.from - b.from).map((b) => {
1567
+ const sec = sections.find((s) => s.from === b.from && s.to === b.to);
1568
+ return {
1569
+ id: b.id,
1570
+ kind: b.kind,
1571
+ version: b.version,
1572
+ ...b.dialect ? { dialect: b.dialect } : {},
1573
+ ...b.sport ? { sport: b.sport } : {},
1574
+ content: sec?.scriptBlock?.content ?? note.rawContent.slice(b.from, b.to)
1575
+ };
1576
+ });
1577
+ return {
1578
+ id: note.id,
1579
+ title: note.title,
1580
+ rawContent: note.rawContent,
1581
+ portableMarkdown: composeNoteMarkdown(note),
1582
+ sourceRevision: note.sourceRevision,
1583
+ editable,
1584
+ date: note.date,
1585
+ createdAt: note.createdAt,
1586
+ tags: note.tags ?? [],
1587
+ notebooks,
1588
+ blocks,
1589
+ sessionCount: sessions.length,
1590
+ recentSessions: sessions.sort((a, b) => b.startTime - a.startTime).slice(0, 10).map((s) => ({
1591
+ id: s.id,
1592
+ blockId: s.blockId,
1593
+ status: s.status,
1594
+ completed: s.completed,
1595
+ duration: s.duration,
1596
+ startTime: s.startTime,
1597
+ public: s.public === true
1598
+ })),
1599
+ ...provenance ? { provenance } : {},
1600
+ visibility,
1601
+ url: noteDeepLink(note, ctx.baseUrl)
1602
+ };
1603
+ }
1604
+ });
1605
+ var noteUpsertInputSchema = z.object({
1606
+ noteId: z.string().optional().describe("Existing Note ID to update, or omit to create a new Note."),
1607
+ title: z.string().optional().describe("Note title (defaults to # H1 heading in content)."),
1608
+ content: z.string().min(1).describe("Full Markdown document or Whiteboard Script body."),
1609
+ sport: z.string().optional().describe("Optional sport fence tag when passing bare Whiteboard Script."),
1610
+ expectedSourceRevision: z.number().int().min(0).optional().describe("Optimistic concurrency guard: pass the current sourceRevision from wod_note_get when updating."),
1611
+ notebookId: z.string().optional().describe("Optional user Notebook ID/slug to link this Note into (always stays anchored in notebook/journal)."),
1612
+ journalDate: z.string().optional().describe('Optional YYYY-MM-DD or "today" to place the Note on that Journal calendar day.')
1613
+ });
1614
+ var wodNoteUpsertTool = defineAgentTool({
1615
+ name: "wod_note_upsert",
1616
+ title: "Create or Update Note",
1617
+ description: "Create a new workout/reference Note or update an existing editable Note with full block-revision pinning, effort/equipment indexing, and optimistic concurrency (`expectedSourceRevision`).",
1618
+ tier: 1,
1619
+ domain: "note",
1620
+ annotations: {
1621
+ title: "Create or Update Note",
1622
+ readOnlyHint: false,
1623
+ destructiveHint: false,
1624
+ idempotentHint: true,
1625
+ openWorldHint: false
1626
+ },
1627
+ inputSchema: noteUpsertInputSchema,
1628
+ cliEquivalent: "wod note save <file|-> --json",
1629
+ async execute(args, ctx) {
1630
+ const rawContent = normalizeMarkdownOrBareScript(args.content, args.sport, args.title);
1631
+ const saved = await upsertNoteInStorage(ctx.storage, {
1632
+ noteId: args.noteId,
1633
+ title: args.title,
1634
+ rawContent,
1635
+ expectedSourceRevision: args.expectedSourceRevision,
1636
+ notebookId: args.notebookId,
1637
+ journalDate: args.journalDate
1638
+ });
1639
+ await ctx.onMutated?.([
1640
+ "notes",
1641
+ "block_revisions",
1642
+ "block_index",
1643
+ "block_efforts",
1644
+ "block_equipment",
1645
+ "tags",
1646
+ "note_tags",
1647
+ "page",
1648
+ "page_notes",
1649
+ "notebook_links"
1650
+ ]);
1651
+ return {
1652
+ id: saved.note.id,
1653
+ noteId: saved.note.id,
1654
+ title: saved.note.title,
1655
+ created: saved.created,
1656
+ sourceRevision: saved.note.sourceRevision,
1657
+ blockCount: saved.blockCount,
1658
+ effortSlugs: saved.effortSlugs,
1659
+ equipmentSlugs: saved.equipmentSlugs,
1660
+ tags: saved.tagLabels,
1661
+ url: noteDeepLink(saved.note, ctx.baseUrl)
1662
+ };
1663
+ }
1664
+ });
1665
+ var noteCloneInputSchema = z.object({
1666
+ sourceNoteId: z.string().min(1).describe("Source Note ID (including read-only Seed/Feed Notes) to clone."),
1667
+ targetNotebookId: z.string().optional().describe('Target writable user Notebook ID/slug (defaults to "notebook/journal").'),
1668
+ title: z.string().optional().describe("Optional title override for the cloned Note."),
1669
+ journalDate: z.string().optional().describe('Optional YYYY-MM-DD or "today" to pin the clone onto a Journal day.')
1670
+ });
1671
+ var wodNoteCloneTool = defineAgentTool({
1672
+ name: "wod_note_clone",
1673
+ title: "Clone Note with Provenance",
1674
+ description: "Clone any Note (especially read-only Seed or Feed workouts) into a writable user Notebook or Journal day while recording structured upstream `NoteProvenance`.",
1675
+ tier: 1,
1676
+ domain: "note",
1677
+ annotations: {
1678
+ title: "Clone Note",
1679
+ readOnlyHint: false,
1680
+ destructiveHint: false,
1681
+ idempotentHint: false,
1682
+ openWorldHint: false
1683
+ },
1684
+ inputSchema: noteCloneInputSchema,
1685
+ cliEquivalent: "wod note clone <sourceNoteId> --notebook <slug> --json",
1686
+ async execute(args, ctx) {
1687
+ const source = await ctx.storage.readonly("notes").get(args.sourceNoteId);
1688
+ if (!source) {
1689
+ throw new Error(`Source Note not found: ${args.sourceNoteId}`);
1690
+ }
1691
+ const targetNb = toNotebookId(args.targetNotebookId ?? "notebook/journal");
1692
+ if (isSystemReadOnlyNotebook(targetNb)) {
1693
+ throw new Error(`Target Notebook '${targetNb}' is read-only.`);
1694
+ }
1695
+ const now = Date.now();
1696
+ const newId = mintAgentUuid();
1697
+ const sourceNb = notebooksOfItem(source)[0];
1698
+ const provenance = buildNoteProvenance(source, sourceNb, now);
1699
+ const saved = await upsertNoteInStorage(ctx.storage, {
1700
+ noteId: newId,
1701
+ title: args.title ?? source.title,
1702
+ rawContent: source.rawContent,
1703
+ notebookId: targetNb,
1704
+ journalDate: args.journalDate,
1705
+ tags: (source.tags ?? []).map((label) => ({ label })),
1706
+ now
1707
+ });
1708
+ const withProvenance = {
1709
+ ...saved.note,
1710
+ sourceId: source.id,
1711
+ provenance
1712
+ };
1713
+ await ctx.storage.readwrite("notes").put(withProvenance);
1714
+ if (targetNb !== "notebook/journal") {
1715
+ await promoteNoteToNotebooks(ctx.storage, {
1716
+ noteId: newId,
1717
+ notebookIds: [targetNb]
1718
+ });
1719
+ }
1720
+ await ctx.onMutated?.(["notes", "block_revisions", "block_index", "notebook_links", "page", "page_notes"]);
1721
+ return {
1722
+ id: withProvenance.id,
1723
+ noteId: withProvenance.id,
1724
+ title: withProvenance.title,
1725
+ sourceRevision: withProvenance.sourceRevision,
1726
+ targetNotebookId: targetNb,
1727
+ provenance,
1728
+ url: noteDeepLink(withProvenance, ctx.baseUrl)
1729
+ };
1730
+ }
1731
+ });
1732
+ var noteDeleteInputSchema = z.object({
1733
+ noteId: z.string().min(1).describe("ID of the Note to delete."),
1734
+ confirmId: z.string().optional().describe("For non-interactive MCP/CLI calls, repeat the exact noteId to confirm deletion.")
1735
+ });
1736
+ var wodNoteDeleteTool = defineAgentTool({
1737
+ name: "wod_note_delete",
1738
+ title: "Delete Note",
1739
+ description: "Permanently delete a Note and detach its projections, tag links, and calendar placements (Tier 2 destructive \u2014 requires user confirmation or matching confirmId).",
1740
+ tier: 2,
1741
+ domain: "note",
1742
+ annotations: {
1743
+ title: "Delete Note",
1744
+ readOnlyHint: false,
1745
+ destructiveHint: true,
1746
+ idempotentHint: true,
1747
+ openWorldHint: false
1748
+ },
1749
+ inputSchema: noteDeleteInputSchema,
1750
+ cliEquivalent: "wod note delete <noteId> --yes <noteId> --json",
1751
+ async execute(args, ctx) {
1752
+ const existing = await ctx.storage.readonly("notes").get(args.noteId);
1753
+ if (!existing) {
1754
+ return { deleted: false, noteId: args.noteId, reason: "not_found" };
1755
+ }
1756
+ await requireDestructiveConfirmation(
1757
+ ctx,
1758
+ {
1759
+ action: "wod_note_delete",
1760
+ targetId: args.noteId,
1761
+ summary: `Delete Note "${existing.title || args.noteId}" (${args.noteId})`
1762
+ },
1763
+ args.confirmId
1764
+ );
1765
+ const deleted = await deleteNoteFromStorage(ctx.storage, args.noteId);
1766
+ if (deleted) {
1767
+ await ctx.onMutated?.([
1768
+ "notes",
1769
+ "block_index",
1770
+ "block_efforts",
1771
+ "block_equipment",
1772
+ "note_tags",
1773
+ "page_notes",
1774
+ "notebook_links",
1775
+ "meta"
1776
+ ]);
1777
+ }
1778
+ return { deleted, noteId: args.noteId, title: existing.title };
1779
+ }
1780
+ });
1781
+ var NOTE_AGENT_TOOLS = [
1782
+ wodNoteListTool,
1783
+ wodNoteGetTool,
1784
+ wodNoteUpsertTool,
1785
+ wodNoteCloneTool,
1786
+ wodNoteDeleteTool
1787
+ ];
1788
+ function collectCollectibles(node, out = []) {
1789
+ for (const metric of node.metrics ?? []) {
1790
+ if (metric.value === "?" || metric.origin === "collectible") {
1791
+ out.push({
1792
+ ...node.id !== void 0 ? { id: node.id } : {},
1793
+ text: node.raw ?? "",
1794
+ metricType: metric.type
1795
+ });
1796
+ }
1797
+ }
1798
+ for (const child of node.children ?? []) {
1799
+ collectCollectibles(child, out);
1800
+ }
1801
+ return out;
1802
+ }
1803
+ var parseScriptInputSchema = z.object({
1804
+ source: z.string().min(1).describe("Whiteboard Script body OR full Markdown document containing ```time / ```wod blocks."),
1805
+ sport: z.string().optional().describe('Optional sport fence dialect override (e.g. "crossfit", "climbing", "running").'),
1806
+ save: z.boolean().optional().describe("Default false (dry-run syntax & metric inspection). Set true to persist as a Note."),
1807
+ noteId: z.string().optional().describe("Optional target Note ID when save=true."),
1808
+ title: z.string().optional().describe("Optional Note title when save=true."),
1809
+ notebookId: z.string().optional().describe("Optional user Notebook slug/ID when save=true.")
1810
+ });
1811
+ var wodParseScriptTool = defineAgentTool({
1812
+ name: "wod_parse_script",
1813
+ title: "Parse Whiteboard Script",
1814
+ description: "Validate Whiteboard Script syntax, inspect parsed statements, typed metrics, unresolved choices, and collectible `?` placeholders. Defaults to dry-run (`save: false`); pass `save: true` to persist as a Note.",
1815
+ tier: 0,
1816
+ domain: "script",
1817
+ annotations: {
1818
+ title: "Parse Whiteboard Script",
1819
+ readOnlyHint: true,
1820
+ destructiveHint: false,
1821
+ idempotentHint: true,
1822
+ openWorldHint: false
1823
+ },
1824
+ inputSchema: parseScriptInputSchema,
1825
+ cliEquivalent: "wod parse - --no-save --json",
1826
+ async execute(args, ctx) {
1827
+ const catalog = await resolveScopedPropertyCatalog(ctx.storage, {
1828
+ ...args.notebookId ? { notebookId: args.notebookId } : {}
1829
+ }).catch(() => void 0);
1830
+ const sections = parseDocumentSections(args.source, {
1831
+ registeredWidgets: KNOWN_SECTION_WIDGETS
1832
+ });
1833
+ const scriptSections = sections.filter((s) => s.scriptBlock);
1834
+ const parser = createParser({
1835
+ ...catalog ? { references: catalog.referenceIndex, tags: catalog.tagIndex } : {}
1836
+ });
1837
+ const blocks = scriptSections.length > 0 ? scriptSections.map((s, idx) => ({
1838
+ index: idx,
1839
+ sport: args.sport ?? s.scriptBlock?.sport,
1840
+ dialect: s.scriptBlock?.dialect ?? "time",
1841
+ body: s.scriptBlock.content
1842
+ })) : [
1843
+ {
1844
+ index: 0,
1845
+ sport: args.sport,
1846
+ dialect: "time",
1847
+ body: args.source
1848
+ }
1849
+ ];
1850
+ const parsedBlocks = blocks.map((blk) => {
1851
+ const script = parser.read(blk.body, blk.sport);
1852
+ const tree = buildStatementTree(script);
1853
+ const unresolvedChoices = findUnresolvedChoices(script.statements).map((c) => ({
1854
+ statementIndex: c.statementIndex,
1855
+ statementId: c.statementId,
1856
+ choice: c.choice
1857
+ }));
1858
+ const collectibles = collectCollectibles(tree);
1859
+ return {
1860
+ index: blk.index,
1861
+ dialect: blk.dialect,
1862
+ ...blk.sport ? { sport: blk.sport } : {},
1863
+ valid: (script.errors?.length ?? 0) === 0,
1864
+ errors: script.errors ?? [],
1865
+ statementCount: script.statements.length,
1866
+ tree,
1867
+ unresolvedChoices,
1868
+ collectibles
1869
+ };
1870
+ });
1871
+ const valid = parsedBlocks.every((b) => b.valid);
1872
+ let savedNote;
1873
+ if (args.save && valid) {
1874
+ const markdown = normalizeMarkdownOrBareScript(args.source, args.sport, args.title);
1875
+ const upserted = await upsertNoteInStorage(ctx.storage, {
1876
+ noteId: args.noteId,
1877
+ title: args.title,
1878
+ rawContent: markdown,
1879
+ notebookId: args.notebookId
1880
+ });
1881
+ await ctx.onMutated?.(["notes", "block_revisions", "block_index", "block_efforts", "block_equipment"]);
1882
+ savedNote = {
1883
+ noteId: upserted.note.id,
1884
+ title: upserted.note.title,
1885
+ sourceRevision: upserted.note.sourceRevision,
1886
+ created: upserted.created
1887
+ };
1888
+ }
1889
+ return {
1890
+ valid,
1891
+ blockCount: parsedBlocks.length,
1892
+ blocks: parsedBlocks,
1893
+ ...savedNote ? { savedNote } : {}
1894
+ };
1895
+ }
1896
+ });
1897
+ var SCRIPT_AGENT_TOOLS = [wodParseScriptTool];
1898
+ function applyCollectibleOverrides(body, overrides) {
1899
+ if (!overrides || Object.keys(overrides).length === 0) return body;
1900
+ const entries = Object.entries(overrides);
1901
+ let updated = body;
1902
+ for (const [key, val] of entries) {
1903
+ const valStr = String(val);
1904
+ if (key === "?" || key === "default") {
1905
+ updated = updated.replace(/\?/g, valStr);
1906
+ } else {
1907
+ const unitRe = new RegExp(`\\?\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "gi");
1908
+ if (unitRe.test(updated)) {
1909
+ updated = updated.replace(unitRe, `${valStr} ${key}`);
1910
+ } else {
1911
+ updated = updated.replace(/\?/, valStr);
1912
+ }
1913
+ }
1914
+ }
1915
+ return updated;
1916
+ }
1917
+ var sessionRunHeadlessInputSchema = z.object({
1918
+ noteId: z.string().optional().describe("Existing Note ID to execute (read-only Seed/Feed Notes are automatically cloned to notebook/journal)."),
1919
+ blockId: z.string().optional().describe("Optional workout block ID on `noteId` (defaults to first wod block)."),
1920
+ source: z.string().optional().describe("Inline Whiteboard Script or Markdown to persist & run when `noteId` is not supplied."),
1921
+ title: z.string().optional().describe("Optional Note title when running inline `source`."),
1922
+ sport: z.string().optional().describe("Optional sport dialect override."),
1923
+ journalDate: z.string().optional().describe('Optional YYYY-MM-DD or "today" Journal calendar date.'),
1924
+ collectibles: z.record(z.string(), z.union([z.string(), z.number()])).optional().describe('Optional values for collectible `?` metrics (e.g. `{ "lb": 185, "reps": 12 }`).'),
1925
+ stepAdvanceMs: z.number().int().min(100).max(36e5).optional().describe("Simulated clock advance per step in milliseconds (default 10000)."),
1926
+ maxSteps: z.number().int().min(1).max(5e3).optional().describe("Safety cap on execution steps (default 500)."),
1927
+ public: z.boolean().optional().describe("Mark the recorded Session public for Feed publication.")
1928
+ });
1929
+ var wodSessionRunHeadlessTool = defineAgentTool({
1930
+ name: "wod_session_run_headless",
1931
+ title: "Run Workout Session Headlessly",
1932
+ description: "Execute a workout block through the headless JIT compiler and runtime state machine, recording a pinned `Session` and derived `EventRecord`s in storage. Automatically clones read-only Seed/Feed Notes into `notebook/journal`.",
1933
+ tier: 1,
1934
+ domain: "session",
1935
+ annotations: {
1936
+ title: "Run Workout Headlessly",
1937
+ readOnlyHint: false,
1938
+ destructiveHint: false,
1939
+ idempotentHint: false,
1940
+ openWorldHint: false
1941
+ },
1942
+ inputSchema: sessionRunHeadlessInputSchema,
1943
+ cliEquivalent: "wod run <file|--note id> --json",
1944
+ async execute(args, ctx) {
1945
+ let targetNoteId = args.noteId;
1946
+ if (!targetNoteId) {
1947
+ if (!args.source?.trim()) {
1948
+ throw new Error("Provide either `noteId` or inline `source` to execute a workout session.");
1949
+ }
1950
+ const md = normalizeMarkdownOrBareScript(args.source, args.sport, args.title);
1951
+ const saved = await upsertNoteInStorage(ctx.storage, {
1952
+ title: args.title,
1953
+ rawContent: md,
1954
+ journalDate: args.journalDate,
1955
+ type: "journal"
1956
+ });
1957
+ targetNoteId = saved.note.id;
1958
+ }
1959
+ const startedAt = Date.now();
1960
+ const intake = await prepareJournalSessionRun(ctx.storage, {
1961
+ noteId: targetNoteId,
1962
+ blockId: args.blockId,
1963
+ journalDate: args.journalDate,
1964
+ startedAt
1965
+ });
1966
+ const sec = parseDocumentSections(intake.revision.rawContent, {
1967
+ registeredWidgets: KNOWN_SECTION_WIDGETS
1968
+ }).find((s) => s.scriptBlock);
1969
+ const rawBody = sec?.scriptBlock?.content ?? intake.revision.rawContent;
1970
+ const bodyWithCollectibles = applyCollectibleOverrides(rawBody, args.collectibles);
1971
+ const catalog = await resolveScopedPropertyCatalog(ctx.storage, {
1972
+ note: intake.note
1973
+ }).catch(() => void 0);
1974
+ const sport = args.sport ?? intake.revision.sport;
1975
+ const script = createParser({
1976
+ ...catalog ? { references: catalog.referenceIndex, tags: catalog.tagIndex } : {}
1977
+ }).read(bodyWithCollectibles, sport);
1978
+ if (script.errors && script.errors.length > 0) {
1979
+ throw new Error(
1980
+ `Whiteboard Script syntax error: ${script.errors.map((e) => e.message).join("; ")}`
1981
+ );
1982
+ }
1983
+ const clock = createMockClock(new Date(startedAt));
1984
+ const stack = new RuntimeStack();
1985
+ const eventBus = new EventBus();
1986
+ const nowProvider = frozenNow(new Date(startedAt));
1987
+ const runtime = new ScriptRuntime(
1988
+ script,
1989
+ createCompiler(),
1990
+ { stack, clock, eventBus },
1991
+ {},
1992
+ nowProvider
1993
+ );
1994
+ const { engine, analyticsContext } = createAnalyticsEngineForBlock({
1995
+ id: intake.session.blockId,
1996
+ content: bodyWithCollectibles,
1997
+ statements: script.statements,
1998
+ sport,
1999
+ version: intake.session.blockVersion,
2000
+ startLine: 0,
2001
+ endLine: 0,
2002
+ dialect: intake.revision.dialect ?? "time",
2003
+ state: "idle",
2004
+ createdAt: startedAt
2005
+ });
2006
+ runtime.analyticsContext = analyticsContext;
2007
+ runtime.setAnalyticsEngine(engine);
2008
+ const outputs = [];
2009
+ runtime.subscribeToOutput((out) => {
2010
+ outputs.push(out);
2011
+ });
2012
+ runtime.do(new StartSessionAction());
2013
+ const stepAdvanceMs = args.stepAdvanceMs ?? 1e4;
2014
+ const maxSteps = args.maxSteps ?? 500;
2015
+ let steps = 0;
2016
+ while (stack.count > 0 && steps < maxSteps) {
2017
+ clock.advance(stepAdvanceMs);
2018
+ runtime.handle(new NextEvent(void 0, { nowMs: () => clock.currentDate.getTime(), now: () => clock.currentDate }));
2019
+ steps += 1;
2020
+ }
2021
+ const completed = stack.count === 0;
2022
+ const endTime = clock.currentDate.getTime();
2023
+ runtime.dispose();
2024
+ const storedLogs = outputs.map(toStoredOutputStatement);
2025
+ const identity = {
2026
+ noteId: intake.session.noteId,
2027
+ resultId: intake.session.id,
2028
+ blockId: intake.session.blockId,
2029
+ blockVersion: intake.session.blockVersion,
2030
+ ...intake.session.blockContentId ? { blockContentId: intake.session.blockContentId } : {},
2031
+ ...intake.session.pageId ? { pageId: intake.session.pageId } : {},
2032
+ origin: intake.session.origin,
2033
+ workoutTimestamp: endTime
2034
+ };
2035
+ const eventRows = toEventRows(storedLogs, identity);
2036
+ const summaryRows = toSummaryEventRows(storedLogs, identity);
2037
+ const allEvents = [...eventRows, ...summaryRows];
2038
+ const finalizedSession = {
2039
+ ...intake.session,
2040
+ status: completed ? "completed" : "in-progress",
2041
+ endTime,
2042
+ duration: Math.max(0, endTime - startedAt),
2043
+ completed,
2044
+ ...args.public !== void 0 ? { public: args.public } : {}
2045
+ };
2046
+ await ctx.storage.transaction(["sessions", "events"], "readwrite", async (tx) => {
2047
+ await tx.readwrite("sessions").put(finalizedSession);
2048
+ if (allEvents.length > 0) {
2049
+ await tx.readwrite("events").putMany(allEvents);
2050
+ }
2051
+ });
2052
+ if (args.public !== void 0) {
2053
+ await setSessionPublic(ctx.storage, finalizedSession.id, args.public);
2054
+ }
2055
+ await ctx.onMutated?.(["notes", "block_revisions", "block_index", "sessions", "events", "page", "page_notes", "notebook_links"]);
2056
+ return {
2057
+ sessionId: finalizedSession.id,
2058
+ noteId: finalizedSession.noteId,
2059
+ blockId: finalizedSession.blockId,
2060
+ blockVersion: finalizedSession.blockVersion,
2061
+ clonedFromReadOnly: intake.clonedFromReadOnly,
2062
+ ...intake.upstreamNoteId ? { upstreamNoteId: intake.upstreamNoteId } : {},
2063
+ completed,
2064
+ stepsExecuted: steps,
2065
+ durationMs: finalizedSession.duration,
2066
+ eventCount: eventRows.length,
2067
+ summaryCount: summaryRows.length
2068
+ };
2069
+ }
2070
+ });
2071
+ var sessionListInputSchema = z.object({
2072
+ noteId: z.string().optional().describe("Filter Sessions by owning Note ID."),
2073
+ completedOnly: z.boolean().optional().describe("Filter to completed Sessions only."),
2074
+ limit: z.number().int().min(1).max(200).optional().describe("Max Sessions to return (default 50).")
2075
+ });
2076
+ var wodSessionListTool = defineAgentTool({
2077
+ name: "wod_session_list",
2078
+ title: "List Recorded Sessions",
2079
+ description: "List recorded workout Sessions ordered newest-first, optionally filtered by Note ID.",
2080
+ tier: 0,
2081
+ domain: "session",
2082
+ annotations: {
2083
+ title: "List Sessions",
2084
+ readOnlyHint: true,
2085
+ destructiveHint: false,
2086
+ idempotentHint: true,
2087
+ openWorldHint: false
2088
+ },
2089
+ inputSchema: sessionListInputSchema,
2090
+ cliEquivalent: "wod session list --json",
2091
+ async execute(args, ctx) {
2092
+ const limit = args.limit ?? 50;
2093
+ let sessions;
2094
+ if (args.noteId) {
2095
+ try {
2096
+ sessions = await ctx.storage.readonly("sessions").getAllFromIndex("by-note", args.noteId);
2097
+ } catch {
2098
+ sessions = (await ctx.storage.readonly("sessions").getAll()).filter(
2099
+ (s) => s.noteId === args.noteId
2100
+ );
2101
+ }
2102
+ } else {
2103
+ sessions = await ctx.storage.readonly("sessions").getAll();
2104
+ }
2105
+ if (args.completedOnly) {
2106
+ sessions = sessions.filter((s) => s.completed);
2107
+ }
2108
+ sessions.sort((a, b) => b.startTime - a.startTime);
2109
+ const noteIds = [...new Set(sessions.slice(0, limit).map((s) => s.noteId))];
2110
+ const notes = await ctx.storage.readonly("notes").getMany(noteIds);
2111
+ const titleById = /* @__PURE__ */ new Map();
2112
+ notes.forEach((n, idx) => {
2113
+ if (n) titleById.set(noteIds[idx], n.title);
2114
+ });
2115
+ return {
2116
+ totalCount: sessions.length,
2117
+ sessions: sessions.slice(0, limit).map((s) => ({
2118
+ id: s.id,
2119
+ noteId: s.noteId,
2120
+ noteTitle: titleById.get(s.noteId) ?? s.noteId,
2121
+ blockId: s.blockId,
2122
+ blockVersion: s.blockVersion,
2123
+ status: s.status,
2124
+ completed: s.completed,
2125
+ duration: s.duration,
2126
+ startTime: s.startTime,
2127
+ endTime: s.endTime,
2128
+ public: s.public === true
2129
+ }))
2130
+ };
2131
+ }
2132
+ });
2133
+ var sessionGetInputSchema = z.object({
2134
+ sessionId: z.string().min(1).describe("Session ID to inspect.")
2135
+ });
2136
+ var wodSessionGetTool = defineAgentTool({
2137
+ name: "wod_session_get",
2138
+ title: "Get Session Telemetry",
2139
+ description: "Read a recorded workout Session along with its pinned `BlockRevision` and derived event/summary telemetry rows.",
2140
+ tier: 0,
2141
+ domain: "session",
2142
+ annotations: {
2143
+ title: "Get Session Telemetry",
2144
+ readOnlyHint: true,
2145
+ destructiveHint: false,
2146
+ idempotentHint: true,
2147
+ openWorldHint: false
2148
+ },
2149
+ inputSchema: sessionGetInputSchema,
2150
+ cliEquivalent: "wod session get <sessionId> --json",
2151
+ async execute(args, ctx) {
2152
+ const session = await ctx.storage.readonly("sessions").get(args.sessionId);
2153
+ if (!session) {
2154
+ throw new Error(`Session not found: ${args.sessionId}`);
2155
+ }
2156
+ const [note, revision, allEvents] = await Promise.all([
2157
+ ctx.storage.readonly("notes").get(session.noteId),
2158
+ ctx.storage.readonly("block_revisions").get([session.noteId, session.blockId, session.blockVersion]),
2159
+ ctx.storage.readonly("events").getAll()
2160
+ ]);
2161
+ const events = allEvents.filter((e) => e.resultId === session.id).sort((a, b) => a.timestamp - b.timestamp);
2162
+ return {
2163
+ session,
2164
+ noteTitle: note?.title,
2165
+ pinnedRevision: revision ?? null,
2166
+ eventCount: events.filter((e) => e.grain === "event").length,
2167
+ summaryCount: events.filter((e) => e.grain === "summary").length,
2168
+ events
2169
+ };
2170
+ }
2171
+ });
2172
+ var sessionDeleteInputSchema = z.object({
2173
+ sessionId: z.string().min(1).describe("Session ID to delete."),
2174
+ confirmId: z.string().optional().describe("For non-interactive MCP/CLI calls, repeat the exact sessionId to confirm deletion.")
2175
+ });
2176
+ var wodSessionDeleteTool = defineAgentTool({
2177
+ name: "wod_session_delete",
2178
+ title: "Delete Recorded Session",
2179
+ description: "Permanently delete a recorded workout Session and its telemetry events (Tier 2 destructive \u2014 requires confirmation).",
2180
+ tier: 2,
2181
+ domain: "session",
2182
+ annotations: {
2183
+ title: "Delete Session",
2184
+ readOnlyHint: false,
2185
+ destructiveHint: true,
2186
+ idempotentHint: true,
2187
+ openWorldHint: false
2188
+ },
2189
+ inputSchema: sessionDeleteInputSchema,
2190
+ cliEquivalent: "wod session delete <sessionId> --yes <sessionId> --json",
2191
+ async execute(args, ctx) {
2192
+ const existing = await ctx.storage.readonly("sessions").get(args.sessionId);
2193
+ if (!existing) {
2194
+ return { deleted: false, sessionId: args.sessionId, reason: "not_found" };
2195
+ }
2196
+ await requireDestructiveConfirmation(
2197
+ ctx,
2198
+ {
2199
+ action: "wod_session_delete",
2200
+ targetId: args.sessionId,
2201
+ summary: `Delete workout Session ${args.sessionId} on Note ${existing.noteId}`
2202
+ },
2203
+ args.confirmId
2204
+ );
2205
+ const deleted = await deleteSessionFromStorage(ctx.storage, args.sessionId);
2206
+ if (deleted) {
2207
+ await ctx.onMutated?.(["sessions", "events", "notebook_links"]);
2208
+ }
2209
+ return { deleted, sessionId: args.sessionId };
2210
+ }
2211
+ });
2212
+ var SESSION_AGENT_TOOLS = [
2213
+ wodSessionRunHeadlessTool,
2214
+ wodSessionListTool,
2215
+ wodSessionGetTool,
2216
+ wodSessionDeleteTool
2217
+ ];
2218
+ var validateWqlInputSchema = z.object({
2219
+ query: z.string().describe('WQL query string to validate and inspect (e.g. ":note{notebook:journal} last 7d" or "sum:volume by {effort}").'),
2220
+ targetHint: z.string().optional().describe("Optional target plane to list valid filter keys & grouping dimensions for (note, session, effort, equipment, tag, feed, block, event).")
2221
+ });
2222
+ var wodValidateWqlTool = defineAgentTool({
2223
+ name: "wod_validate_wql",
2224
+ title: "Validate & Inspect WQL Query",
2225
+ description: "Parse a WQL string without executing it. Returns syntax validity, query family (find, aggregate, pipeline), normalized WQL string, and the allowed filter keys and `by {}` grouping dimensions for that plane.",
2226
+ tier: 0,
2227
+ domain: "wql",
2228
+ annotations: {
2229
+ title: "Validate WQL Query",
2230
+ readOnlyHint: true,
2231
+ destructiveHint: false,
2232
+ idempotentHint: true,
2233
+ openWorldHint: false
2234
+ },
2235
+ inputSchema: validateWqlInputSchema,
2236
+ cliEquivalent: 'wod query "<wql>" --format json',
2237
+ async execute(args) {
2238
+ const parsed = parseQuery(args.query);
2239
+ const valid = !parsed.error;
2240
+ const family = isPipelineQuery(parsed) ? "pipeline" : isFindQuery(parsed) ? "find" : "aggregate";
2241
+ const target = args.targetHint ?? (isFindQuery(parsed) ? parsed.target : isAggregateQuery(parsed) ? "event" : "note");
2242
+ const capFamily = family === "find" ? "find" : "aggregate";
2243
+ return {
2244
+ valid,
2245
+ ...parsed.error ? { error: parsed.error } : {},
2246
+ family,
2247
+ target,
2248
+ normalized: valid ? normalizeWql(args.query) : args.query,
2249
+ allowedTargets: [...WQL_FIND_TARGETS],
2250
+ allowedAggregators: [...WQL_AGGREGATORS],
2251
+ allowedRollupPeriods: [...WQL_ROLLUP_PERIODS],
2252
+ validFilterKeys: [...wqlFilterKeys(target, capFamily)],
2253
+ validGroupingDimensions: [...wqlGroupingDimensions(target, capFamily)]
2254
+ };
2255
+ }
2256
+ });
2257
+ var queryWqlInputSchema = z.object({
2258
+ query: z.string().min(1).describe('WQL query expression (e.g. ":note{notebook:journal}", ":session last 30d", "sum:volume by {week}").'),
2259
+ preferredUnit: z.string().optional().describe('Optional display unit conversion preference (e.g. "lb", "kg", "m", "mi").'),
2260
+ limit: z.number().int().min(1).max(500).optional().describe("Maximum rows/items to return in the response payload (default 100).")
2261
+ });
2262
+ var wodQueryWqlTool = defineAgentTool({
2263
+ name: "wod_query_wql",
2264
+ title: "Execute WQL Query",
2265
+ description: "Run any WQL find (`:note`, `:session`, `:effort`, `:equipment`, `:tag`, `:feed`, `:block`), aggregate (`sum:volume`, `max:weight`, `count:sessions`), or pipeline query against the active WOD Wiki storage.",
2266
+ tier: 0,
2267
+ domain: "wql",
2268
+ annotations: {
2269
+ title: "Execute WQL Query",
2270
+ readOnlyHint: true,
2271
+ destructiveHint: false,
2272
+ idempotentHint: true,
2273
+ openWorldHint: false
2274
+ },
2275
+ inputSchema: queryWqlInputSchema,
2276
+ cliEquivalent: "wod query '<wql>' --format json",
2277
+ async execute(args, ctx) {
2278
+ const parsed = parseQuery(args.query);
2279
+ if (parsed.error) {
2280
+ throw new Error(
2281
+ `WQL Syntax Error in "${args.query}": ${parsed.error}. Call wod_validate_wql to inspect valid targets and filter keys.`
2282
+ );
2283
+ }
2284
+ const service = createQueryServiceForStorage(ctx.storage);
2285
+ const limit = args.limit ?? 100;
2286
+ if (isPipelineQuery(parsed)) {
2287
+ const result2 = await service.runPipeline(args.query, {
2288
+ preferredUnit: args.preferredUnit
2289
+ });
2290
+ return {
2291
+ kind: "pipeline-result",
2292
+ query: args.query,
2293
+ result: result2
2294
+ };
2295
+ }
2296
+ if (isFindQuery(parsed)) {
2297
+ const result2 = await service.runFind(parsed);
2298
+ if (Array.isArray(result2.runs)) {
2299
+ return {
2300
+ kind: "rows-result",
2301
+ target: parsed.target,
2302
+ query: args.query,
2303
+ totalRuns: result2.runs.length,
2304
+ totalCount: result2.runs.length,
2305
+ runs: result2.runs.slice(0, limit),
2306
+ truncated: result2.runs.length > limit
2307
+ };
2308
+ }
2309
+ if (Array.isArray(result2.efforts)) {
2310
+ return {
2311
+ kind: "find-result",
2312
+ target: parsed.target,
2313
+ query: args.query,
2314
+ totalCount: result2.efforts.length,
2315
+ items: result2.efforts.slice(0, limit),
2316
+ truncated: result2.efforts.length > limit
2317
+ };
2318
+ }
2319
+ if (result2.table) {
2320
+ return {
2321
+ kind: "find-result",
2322
+ target: parsed.target,
2323
+ query: args.query,
2324
+ columns: result2.table.columns,
2325
+ totalCount: result2.table.rows.length,
2326
+ items: result2.table.rows.slice(0, limit),
2327
+ truncated: result2.table.rows.length > limit
2328
+ };
2329
+ }
2330
+ if (parsed.target === "block") {
2331
+ return {
2332
+ kind: "find-result",
2333
+ target: parsed.target,
2334
+ query: args.query,
2335
+ totalCount: result2.blocks.length,
2336
+ items: result2.blocks.slice(0, limit),
2337
+ truncated: result2.blocks.length > limit
2338
+ };
2339
+ }
2340
+ return {
2341
+ kind: "find-result",
2342
+ target: parsed.target,
2343
+ query: args.query,
2344
+ totalCount: result2.notes.length,
2345
+ items: result2.notes.slice(0, limit),
2346
+ truncated: result2.notes.length > limit
2347
+ };
2348
+ }
2349
+ const result = await service.runQuery(args.query, {
2350
+ preferredUnit: args.preferredUnit
2351
+ });
2352
+ return {
2353
+ kind: "query-result",
2354
+ query: args.query,
2355
+ result
2356
+ };
2357
+ }
2358
+ });
2359
+ var WQL_AGENT_TOOLS = [wodQueryWqlTool, wodValidateWqlTool];
2360
+
2361
+ // src/agent/manifest.ts
2362
+ var DOMAIN_AGENT_TOOLS = [
2363
+ ...SCRIPT_AGENT_TOOLS,
2364
+ ...WQL_AGENT_TOOLS,
2365
+ ...NOTE_AGENT_TOOLS,
2366
+ ...JOURNAL_AGENT_TOOLS,
2367
+ ...NOTEBOOK_AGENT_TOOLS,
2368
+ ...SESSION_AGENT_TOOLS,
2369
+ ...CATALOG_AGENT_TOOLS,
2370
+ ...FEED_AGENT_TOOLS
2371
+ ];
2372
+ var DOMAIN_AGENT_TOOLS_BY_NAME = new Map(
2373
+ DOMAIN_AGENT_TOOLS.map((tool) => [tool.name, tool])
2374
+ );
2375
+ var WHITEBOARD_SCRIPT_REFERENCE_MARKDOWN = `# Whiteboard Language Reference
2376
+
2377
+ Fence tags: \`\`\`time (optional sport suffix e.g. \`\`\`time:cardio, \`\`\`time:crossfit, \`\`\`time:climb) or \`\`\`log.
2378
+
2379
+ ## Core Tokens & Metrics
2380
+ - **Timestamps / Durations**: \`20:00\` (20 min countdown), \`:30\` (30 sec), \`1:05:00\` (1 hr 5 min).
2381
+ - **Timers & Rounds**: \`(21-15-9)\` rep scheme, \`5 Rounds\`, \`EMOM 10:00\`, \`Tabata\`, \`AMRAP 12:00\`.
2382
+ - **Reps & Resistance**: \`21 Thrusters @95lb\`, \`5x5 Back Squat @80%\`, \`15 Kettlebell Swings @24kg\`.
2383
+ - **Distance**: \`400m Run\`, \`2km Row\`, \`50ft Handstand Walk\`.
2384
+ - **Action Modifiers**: \`[:Rest 1:00]\`, \`+Compose\`.
2385
+ - **Grouping / Indentation**: Indent child movements by 2 spaces beneath timer or round headers.
2386
+
2387
+ ## Canonical Example
2388
+ \`\`\`time
2389
+ # Fran
2390
+ (21-15-9)
2391
+ Thrusters @95lb
2392
+ Pull-ups
2393
+ \`\`\`
2394
+ `;
2395
+ function buildWqlReferenceObject() {
2396
+ const targets = [
2397
+ "note",
2398
+ "block",
2399
+ "effort",
2400
+ "session",
2401
+ "segment",
2402
+ "event",
2403
+ "notebook",
2404
+ "page",
2405
+ "tag",
2406
+ "equipment",
2407
+ "feed"
2408
+ ];
2409
+ const filtersByTarget = {};
2410
+ for (const target of targets) {
2411
+ filtersByTarget[target] = wqlFilterKeys(target, "find");
2412
+ }
2413
+ return {
2414
+ families: ["find", "aggregate"],
2415
+ aggregators: WQL_AGGREGATORS,
2416
+ metricFamilies: WQL_METRIC_FAMILIES,
2417
+ metricAggregates: WQL_METRIC_AGGREGATES,
2418
+ typedTagKeys: WQL_TYPED_TAG_KEYS,
2419
+ factTagKeys: WQL_TAG_KEYS,
2420
+ virtualDimensions: WQL_VIRTUAL_DIMS,
2421
+ contentGroupingDimensions: CONTENT_GROUPING_DIMENSIONS,
2422
+ comparisonOperators: WQL_COMPARISON_OPS,
2423
+ filtersByFindTarget: filtersByTarget,
2424
+ examples: [
2425
+ ":note{tags:benchmark}",
2426
+ ":note{notebook:journal time:7d}",
2427
+ ":session{time:30d}",
2428
+ ":sum{metric:reps effort:thrusters time:90d} by {week}",
2429
+ ":effort{discipline:weightlifting}"
2430
+ ]
2431
+ };
2432
+ }
2433
+ var AGENT_STATIC_RESOURCES = [
2434
+ {
2435
+ uri: "wod://schema/whiteboard-script",
2436
+ name: "Whiteboard Language Reference",
2437
+ description: "Compact syntax, metric token, and fence-tag guide for authoring Whiteboard Language workouts.",
2438
+ mimeType: "text/markdown"
2439
+ },
2440
+ {
2441
+ uri: "wod://schema/wql",
2442
+ name: "WQL Grammar & Capabilities",
2443
+ description: "Machine-readable WQL targets, aggregators, filter keys, metric families, and examples.",
2444
+ mimeType: "application/json"
2445
+ },
2446
+ {
2447
+ uri: "wod://notebooks",
2448
+ name: "Notebooks Snapshot",
2449
+ description: "Current local and subscribed feed notebooks with member counts.",
2450
+ mimeType: "application/json"
2451
+ }
2452
+ ];
2453
+ var AGENT_RESOURCE_TEMPLATES = [
2454
+ {
2455
+ uriTemplate: "wod://note/{noteId}",
2456
+ name: "Workout Note by ID",
2457
+ description: "Full Markdown source, block map, tags, and recent sessions for a Note.",
2458
+ mimeType: "application/json"
2459
+ },
2460
+ {
2461
+ uriTemplate: "wod://journal/{date}",
2462
+ name: "Journal Day Stream",
2463
+ description: "Scheduled notes and logged sessions for YYYY-MM-DD or today.",
2464
+ mimeType: "application/json"
2465
+ },
2466
+ {
2467
+ uriTemplate: "wod://session/{sessionId}",
2468
+ name: "Workout Session Detail",
2469
+ description: "Session record and full segment/summary event ledger.",
2470
+ mimeType: "application/json"
2471
+ }
2472
+ ];
2473
+ var AGENT_PROMPTS = [
2474
+ {
2475
+ name: "encode-workout",
2476
+ title: "Encode Plain-Text Workout into Whiteboard Language",
2477
+ description: "Convert unstructured workout text into valid ```wod Markdown and verify with wod_parse_script.",
2478
+ arguments: [
2479
+ {
2480
+ name: "workoutText",
2481
+ description: "Plain-text description of the workout to encode.",
2482
+ required: true
2483
+ },
2484
+ {
2485
+ name: "sport",
2486
+ description: "Optional sport dialect (e.g. crossfit, running, weightlifting).",
2487
+ required: false
2488
+ }
2489
+ ]
2490
+ },
2491
+ {
2492
+ name: "analyze-training-load",
2493
+ title: "Analyze Recent Training Load via WQL",
2494
+ description: "Inspect recent sessions, volume rollups, and movement balance over a date window.",
2495
+ arguments: [
2496
+ {
2497
+ name: "window",
2498
+ description: "Relative WQL window such as 7d, 30d, or 90d (defaults to 30d).",
2499
+ required: false
2500
+ }
2501
+ ]
2502
+ },
2503
+ {
2504
+ name: "program-journal-day",
2505
+ title: "Program a Training Day on the Journal",
2506
+ description: "Review recent training history, avoid movement interference, and schedule a workout on a date.",
2507
+ arguments: [
2508
+ {
2509
+ name: "date",
2510
+ description: "Target civil date YYYY-MM-DD or today.",
2511
+ required: false
2512
+ },
2513
+ {
2514
+ name: "goal",
2515
+ description: "Training focus, time cap, or equipment constraints.",
2516
+ required: false
2517
+ }
2518
+ ]
2519
+ }
2520
+ ];
2521
+ async function readAgentResource(uri, ctx) {
2522
+ if (uri === "wod://schema/whiteboard-script") {
2523
+ return {
2524
+ uri,
2525
+ mimeType: "text/markdown",
2526
+ text: WHITEBOARD_SCRIPT_REFERENCE_MARKDOWN
2527
+ };
2528
+ }
2529
+ if (uri === "wod://schema/wql") {
2530
+ return {
2531
+ uri,
2532
+ mimeType: "application/json",
2533
+ text: JSON.stringify(buildWqlReferenceObject(), null, 2)
2534
+ };
2535
+ }
2536
+ if (uri === "wod://notebooks") {
2537
+ const result = await wodNotebookListTool.execute({ origin: "all" }, ctx);
2538
+ return {
2539
+ uri,
2540
+ mimeType: "application/json",
2541
+ text: JSON.stringify(result, null, 2)
2542
+ };
2543
+ }
2544
+ const noteMatch = uri.match(/^wod:\/\/note\/(.+)$/);
2545
+ if (noteMatch?.[1]) {
2546
+ const noteId = decodeURIComponent(noteMatch[1]);
2547
+ const result = await wodNoteGetTool.execute({ noteId }, ctx);
2548
+ return {
2549
+ uri,
2550
+ mimeType: "application/json",
2551
+ text: JSON.stringify(result, null, 2)
2552
+ };
2553
+ }
2554
+ const journalMatch = uri.match(/^wod:\/\/journal\/(.+)$/);
2555
+ if (journalMatch?.[1]) {
2556
+ const date = decodeURIComponent(journalMatch[1]);
2557
+ const result = await wodJournalDayTool.execute({ date }, ctx);
2558
+ return {
2559
+ uri,
2560
+ mimeType: "application/json",
2561
+ text: JSON.stringify(result, null, 2)
2562
+ };
2563
+ }
2564
+ const sessionMatch = uri.match(/^wod:\/\/session\/(.+)$/);
2565
+ if (sessionMatch?.[1]) {
2566
+ const sessionId = decodeURIComponent(sessionMatch[1]);
2567
+ const result = await wodSessionGetTool.execute({ sessionId }, ctx);
2568
+ return {
2569
+ uri,
2570
+ mimeType: "application/json",
2571
+ text: JSON.stringify(result, null, 2)
2572
+ };
2573
+ }
2574
+ throw new Error(`Unknown WOD resource URI: '${uri}'.`);
2575
+ }
2576
+ function renderAgentPrompt(name, args = {}) {
2577
+ if (name === "encode-workout") {
2578
+ const workoutText = args.workoutText ?? "(provide workout description)";
2579
+ const sport = args.sport ? ` using sport dialect "${args.sport}"` : "";
2580
+ return {
2581
+ description: "Encode plain-text workout into verified Whiteboard Language Markdown.",
2582
+ messages: [
2583
+ {
2584
+ role: "user",
2585
+ content: {
2586
+ type: "text",
2587
+ text: `Convert the following workout into a clean Markdown document with a \`# Title\` and a \`\`\`wod fence${sport}.
2588
+ 1. Read \`wod://schema/whiteboard-script\` if needed.
2589
+ 2. Call \`wod_parse_script\` on the script body and fix any parse errors.
2590
+ 3. Return the verified Markdown (and save via \`wod_note_upsert\` only if requested).
2591
+
2592
+ Workout:
2593
+ ${workoutText}`
2594
+ }
2595
+ }
2596
+ ]
2597
+ };
2598
+ }
2599
+ if (name === "analyze-training-load") {
2600
+ const window = args.window || "30d";
2601
+ return {
2602
+ description: `Analyze training load over ${window}.`,
2603
+ messages: [
2604
+ {
2605
+ role: "user",
2606
+ content: {
2607
+ type: "text",
2608
+ text: `Analyze my training load over the past ${window}:
2609
+ 1. Call \`wod_session_list\` or \`wod_query_wql\` with \`:session{time:${window}}\`.
2610
+ 2. Aggregate rep/volume trends using \`wod_query_wql\` (e.g. \`:sum{metric:reps time:${window}} by {week}\`).
2611
+ 3. Summarize volume distribution, movement gaps, and recovery recommendations.`
2612
+ }
2613
+ }
2614
+ ]
2615
+ };
2616
+ }
2617
+ if (name === "program-journal-day") {
2618
+ const date = args.date || "today";
2619
+ const goal = args.goal ? `
2620
+ Goal / constraints: ${args.goal}` : "";
2621
+ return {
2622
+ description: `Program a workout for ${date}.`,
2623
+ messages: [
2624
+ {
2625
+ role: "user",
2626
+ content: {
2627
+ type: "text",
2628
+ text: `Program a workout for ${date}.${goal}
2629
+ 1. Inspect recent sessions via \`wod_session_list\` (limit 10) and existing items on \`${date}\` via \`wod_journal_day\`.
2630
+ 2. Draft a complementary workout in Whiteboard Language and verify it with \`wod_parse_script\`.
2631
+ 3. Schedule it onto \`${date}\` using \`wod_journal_add\`.`
2632
+ }
2633
+ }
2634
+ ]
2635
+ };
2636
+ }
2637
+ throw new Error(`Unknown WOD prompt: '${name}'.`);
2638
+ }
2639
+ function zodSchemaToJsonSchema(schema) {
2640
+ return z.toJSONSchema(schema, { target: "draft-2020-12" });
2641
+ }
2642
+ function exportAgentCapabilitiesManifest(options) {
2643
+ return {
2644
+ schemaVersion: "1.0.0",
2645
+ name: "WOD Wiki Agent Surface",
2646
+ description: "Tri-surface agent capabilities for WOD Wiki across Browser WebMCP, HTTP/Stdio MCP Server, and local CLI.",
2647
+ surfaces: {
2648
+ webmcp: {
2649
+ supported: true,
2650
+ globalNamespace: "navigator.modelContext",
2651
+ library: "@mcp-b/react-webmcp"
2652
+ },
2653
+ mcp: {
2654
+ httpEndpoint: "/api/mcp",
2655
+ stdioCommand: "wod mcp",
2656
+ sdk: "@modelcontextprotocol/sdk"
2657
+ },
2658
+ cli: {
2659
+ binary: "wod",
2660
+ jsonFlag: "--json",
2661
+ confirmationExitCode: 4
2662
+ }
2663
+ },
2664
+ domainTools: DOMAIN_AGENT_TOOLS.map((tool) => ({
2665
+ name: tool.name,
2666
+ title: tool.title,
2667
+ description: tool.description,
2668
+ tier: tool.tier,
2669
+ domain: tool.domain,
2670
+ surfaces: ["webmcp", "mcp", "cli"],
2671
+ cliEquivalent: tool.cliEquivalent,
2672
+ annotations: tool.annotations,
2673
+ inputSchema: zodSchemaToJsonSchema(tool.inputSchema)
2674
+ })),
2675
+ ...options?.uiTools ? { uiTools: options.uiTools } : {},
2676
+ resources: [
2677
+ ...AGENT_STATIC_RESOURCES.map((r) => ({
2678
+ uri: r.uri,
2679
+ name: r.name,
2680
+ description: r.description,
2681
+ mimeType: r.mimeType
2682
+ })),
2683
+ ...AGENT_RESOURCE_TEMPLATES.map((t) => ({
2684
+ uri: t.uriTemplate,
2685
+ name: t.name,
2686
+ description: t.description,
2687
+ mimeType: t.mimeType
2688
+ }))
2689
+ ],
2690
+ prompts: AGENT_PROMPTS.map((p) => ({
2691
+ name: p.name,
2692
+ title: p.title,
2693
+ description: p.description,
2694
+ arguments: p.arguments.map((a) => ({ ...a }))
2695
+ }))
2696
+ };
2697
+ }
2698
+
2699
+ export { AGENT_PROMPTS, AGENT_RESOURCE_TEMPLATES, AGENT_STATIC_RESOURCES, AgentConfirmationRequiredError, DOMAIN_AGENT_TOOLS, DOMAIN_AGENT_TOOLS_BY_NAME, WHITEBOARD_SCRIPT_REFERENCE_MARKDOWN, buildWqlReferenceObject, civilDateKey, createQueryServiceForStorage, defineAgentTool, deleteNoteFromStorage, deleteSessionFromStorage, exportAgentCapabilitiesManifest, normalizeMarkdownOrBareScript, noteDeepLink, readAgentResource, renderAgentPrompt, requireDestructiveConfirmation, upsertNoteInStorage, wodCatalogLookupTool, wodCatalogUpsertTool, wodExportBundleTool, wodFeedManageTool, wodJournalAddTool, wodJournalDayTool, wodNoteCloneTool, wodNoteDeleteTool, wodNoteGetTool, wodNoteListTool, wodNoteUpsertTool, wodNotebookDeleteTool, wodNotebookListTool, wodNotebookSaveTool, wodParseScriptTool, wodQueryWqlTool, wodResetStorageTool, wodSessionDeleteTool, wodSessionGetTool, wodSessionListTool, wodSessionRunHeadlessTool, wodValidateWqlTool, zodSchemaToJsonSchema };
2700
+ //# sourceMappingURL=agent.mjs.map
2701
+ //# sourceMappingURL=agent.mjs.map