diff --git a/server/scripts/mcp-inline-zod-baseline.json b/server/scripts/mcp-inline-zod-baseline.json index 76081dbdb..c10e4b222 100644 --- a/server/scripts/mcp-inline-zod-baseline.json +++ b/server/scripts/mcp-inline-zod-baseline.json @@ -14,7 +14,7 @@ "src/nest/help/help.mcp.ts": 4, "src/nest/integrations/airtrail.mcp.ts": 2, "src/nest/integrations/dawarich.mcp.ts": 13, - "src/nest/journey/journey.mcp.ts": 46, + "src/nest/journey/journey.mcp.ts": 30, "src/nest/maps/maps.mcp.ts": 18, "src/nest/memories/memories.mcp.ts": 8, "src/nest/notifications/notifications.mcp.ts": 2, diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index 648efa905..63ba869e9 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -11,7 +11,7 @@ "src/nest/collections/collections.service.ts": 1478, "src/nest/doc-sync/doc-sync.service.ts": 1060, "src/nest/doc-sync/providers/synology-drive.client.ts": 1160, - "src/nest/journey/journey-domain.service.ts": 1725, + "src/nest/journey/journey-domain.service.ts": 1659, "src/nest/places/places.service.ts": 1592, "src/nest/plugins/plugin-runtime.service.ts": 1463, "src/nest/plugins/runtime/plugin-sdk.ts": 1093, diff --git a/server/src/nest/journey/journey-domain.service.ts b/server/src/nest/journey/journey-domain.service.ts index 75ff77657..d01364c3d 100644 --- a/server/src/nest/journey/journey-domain.service.ts +++ b/server/src/nest/journey/journey-domain.service.ts @@ -27,9 +27,9 @@ import { Trips } from '../../db/entities/Trips.entity'; import type { TripsRepository } from '../../db/repositories/Trips.repository'; import { Places } from '../../db/entities/Places.entity'; import type { PlacesRepository } from '../../db/repositories/Places.repository'; -import { presenceSet } from '../../db/repositories/_shared/presence-set'; import { parseRouteGeometry } from './journey-geometry'; import { journeySettingsPatch, type JourneySettingsInput } from './journey-settings.helpers'; +import { entryPrevious, entryUpdatePatch, type JourneyEntryPrevious, type JourneyEntryUpdateInput } from './journey-entry-patch.helpers'; /** * What makes a journal skeleton unique: the place *and* the day assignment it @@ -1158,107 +1158,30 @@ export class JourneyDomainService { return created; } - async updateEntry( + async updateEntry(entryId: number, userId: number, data: JourneyEntryUpdateInput, sid?: string): Promise { + return (await this.updateEntryWithPrevious(entryId, userId, data, sid))?.entry ?? null; + } + + /** The update every surface makes, with what it replaced (journey-entry-patch.helpers.ts), for the assistant's undo. */ + async updateEntryWithPrevious( entryId: number, userId: number, - data: Partial<{ - type: string; - title: string; - story: string; - entry_date: string; - entry_time: string; - location_name: string; - location_lat: number; - location_lng: number; - mood: string; - weather: string; - tags: string[]; - pros_cons: { pros: string[]; cons: string[] }; - visibility: string; - sort_order: number; - stats_excluded: boolean; - dismissed: boolean; - is_draft: boolean; - }>, + data: JourneyEntryUpdateInput, sid?: string, - ): Promise { + ): Promise<{ entry: JourneyEntryWire; previous: JourneyEntryPrevious } | null> { // JG77 — same text as JG76. const entry = await this.entriesRepo.findById(entryId); if (!entry) return null; if (!(await this.canEdit(entry.journey_id, userId))) return null; - // JG78 — R6's `presenceSet` conversion, the SECOND consumer of this - // pattern (JG24's `updateJourney`, Task 1's, is the first — same shape, - // not re-derived). The SERVICE resolves every field to its final bound - // value first: `tags`/`pros_cons` JSON-encoded, `stats_excluded`/ - // `dismissed` boolean-coerced to 0/1 (better-sqlite3 refuses a JS - // boolean bind), `country_code` recomputed whenever EITHER half of the - // lat/lng pair is present in the patch — including when explicitly - // `null`, which means "take this entry off the map" and must clear the - // country rather than fall back to the old one, hence `!== undefined`, - // never `??` — before handing any of it to the repository. - // - // The skeleton→entry promotion preserves a real legacy nuance: the - // original dynamic-SET-list pushed a SECOND `type = ?` binding when a - // story was added to a skeleton, even when the caller's own `data.type` - // had already pushed one — SQLite's `SET col = a, col = b` keeps the - // LAST assignment, so the promotion always won over an explicit - // `data.type` whenever both applied. `presenceSet` takes one value per - // key, so that "last one wins" resolution happens here instead, in the - // same effective order the legacy statement's own field list built it. - const promoteToEntry = entry.type === 'skeleton' && !!data.story && data.story.trim().length > 0; - const patch = presenceSet<{ - type: string; - title: string | null; - story: string | null; - entry_date: string; - entry_time: string | null; - location_name: string | null; - location_lat: number | null; - location_lng: number | null; - mood: string | null; - weather: string | null; - tags: string | null; - pros_cons: string | null; - visibility: string; - sort_order: number; - stats_excluded: number; - dismissed: number; - is_draft: number; - country_code: string | null; - updated_at: number; - }>({ - type: [data.type !== undefined || promoteToEntry, promoteToEntry ? 'entry' : (data.type as string)], - title: [data.title !== undefined, data.title as string], - story: [data.story !== undefined, data.story as string], - entry_date: [data.entry_date !== undefined, data.entry_date as string], - entry_time: [data.entry_time !== undefined, data.entry_time as string], - location_name: [data.location_name !== undefined, data.location_name as string], - location_lat: [data.location_lat !== undefined, data.location_lat as number | null], - location_lng: [data.location_lng !== undefined, data.location_lng as number | null], - mood: [data.mood !== undefined, data.mood as string], - weather: [data.weather !== undefined, data.weather as string], - // `Array.isArray(val) ? JSON.stringify(val) : val` (legacy) — a caller - // sending `tags: null`/`pros_cons: null` explicitly (to CLEAR the - // field, not touch it) must write SQL NULL, not the JSON string - // `"null"` (`JSON.stringify(null)`) — caught live by - // `tools-journey.test.ts`'s own "clears a field on null" case. - tags: [data.tags !== undefined, Array.isArray(data.tags) ? JSON.stringify(data.tags) : null], - pros_cons: [data.pros_cons !== undefined, data.pros_cons && typeof data.pros_cons === 'object' ? JSON.stringify(data.pros_cons) : null], - visibility: [data.visibility !== undefined, data.visibility as string], - sort_order: [data.sort_order !== undefined, data.sort_order as number], - stats_excluded: [data.stats_excluded !== undefined, data.stats_excluded ? 1 : 0], - dismissed: [data.dismissed !== undefined, data.dismissed ? 1 : 0], - is_draft: [data.is_draft !== undefined, data.is_draft ? 1 : 0], - country_code: [ - data.location_lat !== undefined || data.location_lng !== undefined, - this.countryFor( - data.location_lat !== undefined ? data.location_lat : entry.location_lat, - data.location_lng !== undefined ? data.location_lng : entry.location_lng, - ), - ], - updated_at: [true, this.ts()], - }); + // JG78 — the patch is built in one place for every surface; the country is recomputed whenever + // EITHER half of the lat/lng pair is named, including as null, so it clears rather than falls back. + const country = this.countryFor( + data.location_lat !== undefined ? data.location_lat : entry.location_lat, + data.location_lng !== undefined ? data.location_lng : entry.location_lng, + ); + const patch = entryUpdatePatch(entry, data, country, this.ts()); + const previous = entryPrevious(entry, data); // M3 (parity) — the legacy no-op check (`fields.length === 0`) fires // exactly when NO allow-listed key made it into the dynamic SET list. @@ -1266,10 +1189,10 @@ export class JourneyDomainService { // of that: `data` is `journeyEntryUpdateRequestSchema`'s `z.looseObject`, // so a PATCH body carrying only non-allow-listed keys (`{"foo":1}`) has // a defined value there and this used to write and broadcast anyway. - // `patch` (built above by `presenceSet`) always carries `updated_at` + // `patch` (built above by `entryUpdatePatch`) always carries `updated_at` // unconditionally, so its length is 1 exactly when nothing allow-listed // was provided — the same condition the legacy field-count check tested. - if (Object.keys(patch).length === 1) return decodeEntryRow(entry); + if (Object.keys(patch).length === 1) return { entry: decodeEntryRow(entry), previous: {} }; await this.uow.transactional(async () => { await placeMovedEntry(this.entriesRepo, entry, patch, this.ts()); @@ -1280,19 +1203,26 @@ export class JourneyDomainService { // JG80 — same text as JG76. const updated = decodeEntryRow((await this.entriesRepo.findById(entryId)) as JourneyEntry); await this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entry: updated }, sid); - return updated; + return { entry: updated, previous }; } // Reorder entries (typically within a single day). Caller passes the new // desired order of ids; each entry's sort_order is set to its index in the // array. Only entries owned by this journey are accepted. async reorderEntries(journeyId: number, userId: number, orderedIds: number[], sid?: string): Promise { - if (!(await this.canEdit(journeyId, userId))) return false; - if (!orderedIds.length) return true; + return (await this.reorderEntriesWithPrevious(journeyId, userId, orderedIds, sid)) !== null; + } + + /** The reorder every surface makes, with the order the ids stood in before it (the journal's reading order). */ + async reorderEntriesWithPrevious(journeyId: number, userId: number, orderedIds: number[], sid?: string): Promise<{ previousOrder: number[] } | null> { + if (!(await this.canEdit(journeyId, userId))) return null; + if (!orderedIds.length) return { previousOrder: [] }; // JG81 — ownership verification. const matchedIds = await this.entriesRepo.listIdsIn(journeyId, orderedIds); - if (matchedIds.length !== orderedIds.length) return false; + if (matchedIds.length !== orderedIds.length) return null; + const named = new Set(orderedIds); + const previousOrder = (await this.entriesRepo.listForJourney(journeyId)).map((e) => e.id).filter((id) => named.has(id)); const now = this.ts(); // JG82/JG83 (the fourth `uow.transactional` block) — the legacy @@ -1311,7 +1241,7 @@ export class JourneyDomainService { }); await this.broadcastJourneyEvent(journeyId, 'journey:entries:reordered', { orderedIds }, sid); - return true; + return { previousOrder }; } /** diff --git a/server/src/nest/journey/journey-entry-patch.helpers.ts b/server/src/nest/journey/journey-entry-patch.helpers.ts new file mode 100644 index 000000000..5d4da55f1 --- /dev/null +++ b/server/src/nest/journey/journey-entry-patch.helpers.ts @@ -0,0 +1,132 @@ +import { presenceSet } from '../../db/repositories/_shared/presence-set'; +import type { JourneyEntry } from '../../types'; +import { decodeEntryRow } from './journey-entry-row'; + +/** + * An update of a journal entry as every surface hands it in (the REST route, + * the MCP tool, the plugin RPC), the columns it writes, and what it replaced. + * Pure: the service resolves the entry's country from its coordinates and + * the clock, and hands both in. + */ + +export type JourneyEntryUpdateInput = Partial<{ + type: string; + title: string; + story: string; + entry_date: string; + entry_time: string; + location_name: string; + location_lat: number; + location_lng: number; + mood: string; + weather: string; + tags: string[]; + pros_cons: { pros: string[]; cons: string[] }; + visibility: string; + sort_order: number; + stats_excluded: boolean; + dismissed: boolean; + is_draft: boolean; +}>; + +/** The columns an update writes, as they are stored. */ +export interface JourneyEntryColumns { + type: string; + title: string | null; + story: string | null; + entry_date: string; + entry_time: string | null; + location_name: string | null; + location_lat: number | null; + location_lng: number | null; + mood: string | null; + weather: string | null; + tags: string | null; + pros_cons: string | null; + visibility: string; + sort_order: number; + stats_excluded: number; + dismissed: number; + is_draft: number; + country_code: string | null; + updated_at: number; +} + +/** + * JG78: the columns an update of `entry` with `data` writes, each resolved to + * its bound value (`tags`/`pros_cons` JSON-encoded, the flags 0/1, the + * country recomputed whenever either half of the coordinates is named, + * including as null, which takes the entry off the map). The skeleton to + * entry promotion keeps the legacy nuance: a story written onto a skeleton + * makes it an entry even over an explicit `data.type`, as the legacy SET + * list's last assignment did. `updated_at` is always written. + */ +export function entryUpdatePatch( + entry: JourneyEntry, + data: JourneyEntryUpdateInput, + country: string | null, + now: number, +): Partial { + const promoteToEntry = entry.type === 'skeleton' && !!data.story && data.story.trim().length > 0; + const proscons = data.pros_cons && typeof data.pros_cons === 'object' ? JSON.stringify(data.pros_cons) : null; + return presenceSet({ + type: [data.type !== undefined || promoteToEntry, promoteToEntry ? 'entry' : (data.type as string)], + title: [data.title !== undefined, data.title as string], + story: [data.story !== undefined, data.story as string], + entry_date: [data.entry_date !== undefined, data.entry_date as string], + entry_time: [data.entry_time !== undefined, data.entry_time as string], + location_name: [data.location_name !== undefined, data.location_name as string], + location_lat: [data.location_lat !== undefined, data.location_lat as number | null], + location_lng: [data.location_lng !== undefined, data.location_lng as number | null], + mood: [data.mood !== undefined, data.mood as string], + weather: [data.weather !== undefined, data.weather as string], + // A caller sending `tags: null`/`pros_cons: null` to CLEAR the field must write SQL NULL, never the + // JSON string "null" (tools-journey.test.ts, "clears a field on null"). + tags: [data.tags !== undefined, Array.isArray(data.tags) ? JSON.stringify(data.tags) : null], + pros_cons: [data.pros_cons !== undefined, proscons], + visibility: [data.visibility !== undefined, data.visibility as string], + sort_order: [data.sort_order !== undefined, data.sort_order as number], + stats_excluded: [data.stats_excluded !== undefined, data.stats_excluded ? 1 : 0], + dismissed: [data.dismissed !== undefined, data.dismissed ? 1 : 0], + is_draft: [data.is_draft !== undefined, data.is_draft ? 1 : 0], + country_code: [data.location_lat !== undefined || data.location_lng !== undefined, country], + updated_at: [true, now], + }); +} + +/** The fields an update can write back, as the MCP tool takes them. */ +const RESTORABLE = [ + 'title', + 'story', + 'entry_date', + 'entry_time', + 'location_name', + 'location_lat', + 'location_lng', + 'mood', + 'weather', + 'tags', + 'pros_cons', + 'visibility', + 'type', + 'stats_excluded', + 'dismissed', + 'is_draft', +] as const; + +/** What an entry update replaced: the fields `data` names, as the entry held them on the wire, decoded. */ +export type JourneyEntryPrevious = Partial>; + +/** + * The entry's values, as read before the update, of exactly the fields the + * update names (the sort order aside, which reorder takes back): what writing + * the change back sets again. JSON columns decoded, flags as booleans. + */ +export function entryPrevious(entry: JourneyEntry, data: JourneyEntryUpdateInput): JourneyEntryPrevious { + const wire = decodeEntryRow(entry) as unknown as Record; + const previous: JourneyEntryPrevious = {}; + for (const key of RESTORABLE) if (data[key] !== undefined) previous[key] = wire[key] ?? null; + // A story written onto a suggestion makes it an entry: going back makes it a suggestion again. + if (entry.type === 'skeleton' && typeof data.story === 'string' && data.story.trim()) previous.type = 'skeleton'; + return previous; +} diff --git a/server/src/nest/journey/journey.mcp.ts b/server/src/nest/journey/journey.mcp.ts index f61921b60..53ed0e446 100644 --- a/server/src/nest/journey/journey.mcp.ts +++ b/server/src/nest/journey/journey.mcp.ts @@ -22,6 +22,8 @@ import { idSchema, journeyCreateToolSchema, journeyEntriesRangeSchema, + journeyEntryUpdateToolSchema, + journeyReorderEntriesToolSchema, journeyEntryProsConsSchema, journeyEntryTypeSchema, journeyEntryVisibilitySchema, @@ -29,7 +31,9 @@ import { journeyUpdateToolSchema, type JourneyCreateTool, type JourneyEntryType, + type JourneyEntryUpdateTool, type JourneyEntryVisibility, + type JourneyReorderEntriesTool, type JourneyUpdateTool, } from '@trek/shared'; @@ -428,87 +432,21 @@ export class JourneyMcp { @Tool({ name: 'update_journey_entry', description: - 'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, visibility, whether it is a draft, or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here.', - inputSchema: { - entryId: idSchema, - title: z.string().max(300).nullable().optional(), - story: z.string().nullable().optional(), - entry_date: z - .string() - .regex(/^\d{4}-\d{2}-\d{2}$/) - .optional(), - entry_time: z.string().nullable().optional(), - location_name: z.string().nullable().optional(), - location_lat: z - .number() - .min(-90) - .max(90) - .nullable() - .optional() - .describe('Latitude, or null to take the entry off the journey map'), - location_lng: z.number().min(-180).max(180).nullable().optional(), - mood: z.string().nullable().optional(), - weather: z.string().max(100).nullable().optional(), - tags: z.array(z.string()).nullable().optional(), - pros_cons: PROS_CONS.nullable().optional().describe('Replaces the whole verdict; null clears it'), - visibility: ENTRY_VISIBILITY.optional(), - type: ENTRY_TYPE.optional().describe( - 'Promote a trip-derived "skeleton" to a real "entry" once it has been written up', - ), - sort_order: z.number().int().min(0).optional(), - stats_excluded: z - .boolean() - .optional() - .describe( - 'True leaves the entry in the journal but takes it off the journey route and out of its distance, countries and step count (see get_journey_stats); false puts it back. For the home airport, a stopover, the place the trip was planned from', - ), - dismissed: z - .boolean() - .optional() - .describe( - 'True waves a trip-derived suggestion away: it leaves the journey without being deleted, so the trip sync does not offer it again. restore_journey_suggestions brings every dismissed one back', - ), - is_draft: z - .boolean() - .optional() - .describe('True turns the entry into a draft that the journey share link leaves out; false publishes it'), - }, + 'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, visibility, whether it is a draft, or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.', + inputSchema: { entryId: idSchema, ...journeyEntryUpdateToolSchema.shape }, annotations: TOOL_ANNOTATIONS_WRITE, when: journeyAddonOn, access: { group: 'journey', mode: 'write' }, }) - async updateJourneyEntry( - { - entryId, - ...data - }: { - entryId: number; - title?: string | null; - story?: string | null; - entry_date?: string; - entry_time?: string | null; - location_name?: string | null; - location_lat?: number | null; - location_lng?: number | null; - mood?: string | null; - weather?: string | null; - tags?: string[] | null; - pros_cons?: { pros: string[]; cons: string[] } | null; - visibility?: JourneyEntryVisibility; - type?: JourneyEntryType; - sort_order?: number; - stats_excluded?: boolean; - dismissed?: boolean; - is_draft?: boolean; - }, - ctx: McpContext, - ) { - const entry = await this.journey.updateEntry(entryId, ctx.userId, data, undefined); - if (!entry) return notFound('Entry not found or access denied.'); + async updateJourneyEntry({ entryId, ...data }: JourneyEntryUpdateTool & { entryId: number }, ctx: McpContext) { + // The update PATCH /api/journeys/entries/:entryId makes, with what it replaced. + const updated = await this.journey.updateEntryWithPrevious(entryId, ctx.userId, data, undefined); + if (!updated) return notFound('Entry not found or access denied.'); + const { entry, previous } = updated; // Return through the listEntries enrichment (parsed tags/pros_cons, photos), matching create_journey_entry. const enriched = (await this.journey.listEntries(entry.journey_id, ctx.userId))?.find((e) => e.id === entry.id) ?? entry; - return ok({ entry: enriched }); + return ok({ entry: enriched, previous }); } @Tool({ @@ -527,19 +465,20 @@ export class JourneyMcp { @Tool({ name: 'reorder_journey_entries', - description: 'Reorder entries within a journey by providing the desired order of entry IDs.', - inputSchema: { - journeyId: idSchema, - orderedIds: z.array(idSchema), - }, + description: + 'Reorder entries within a journey by providing the desired order of entry IDs. Answers with previous_order, the same ids in the order they stood in before.', + inputSchema: { journeyId: idSchema, ...journeyReorderEntriesToolSchema.shape }, annotations: TOOL_ANNOTATIONS_WRITE, when: journeyAddonOn, access: { group: 'journey', mode: 'write' }, }) - async reorderJourneyEntries({ journeyId, orderedIds }: { journeyId: number; orderedIds: number[] }, ctx: McpContext) { - const success = await this.journey.reorderEntries(journeyId, ctx.userId, orderedIds, undefined); - if (!success) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.'); - return ok({ success: true }); + async reorderJourneyEntries( + { journeyId, orderedIds }: JourneyReorderEntriesTool & { journeyId: number }, + ctx: McpContext, + ) { + const reordered = await this.journey.reorderEntriesWithPrevious(journeyId, ctx.userId, orderedIds, undefined); + if (!reordered) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.'); + return ok({ success: true, previous_order: reordered.previousOrder }); } @Tool({ diff --git a/server/tests/unit/mcp/tools-journey.test.ts b/server/tests/unit/mcp/tools-journey.test.ts index 42ebb09ad..7a3c6145e 100644 --- a/server/tests/unit/mcp/tools-journey.test.ts +++ b/server/tests/unit/mcp/tools-journey.test.ts @@ -661,6 +661,8 @@ describe('journey write tools', () => { }), ) as any; expect(reordered.success).toBe(true); + // The ids as they stood before, in the journal's reading order, for a way back. + expect(reordered.previous_order).toEqual([a.id, b.id]); expect( ( await h.client.callTool({ @@ -969,6 +971,33 @@ describe('journey entry fields', () => { }); }); + it('update_journey_entry answers what the named fields held before, decoded, and nothing for the rest', async () => { + const { user } = createUser(testDb); + await withHarness(user.id, async (h) => { + const journey = await seedJourney(h); + const entry = await seedEntry(h, journey.id, { + title: 'Vik', + tags: ['beach'], + pros_cons: { pros: ['the stacks'], cons: [] }, + is_draft: true, + }); + const updated = parseToolResult( + await h.client.callTool({ + name: 'update_journey_entry', + arguments: { entryId: entry.id, title: 'Reynisfjara', tags: null, is_draft: false, location_lat: 63.4 }, + }), + ) as { entry: { title: string }; previous: Record }; + expect(updated.entry.title).toBe('Reynisfjara'); + expect(updated.previous).toEqual({ title: 'Vik', tags: ['beach'], is_draft: true, location_lat: null }); + // Written back through the same tool, the entry reads as it did. + await h.client.callTool({ name: 'update_journey_entry', arguments: { entryId: entry.id, ...updated.previous } }); + const row = await entryRow(entry.id); + expect(row.title).toBe('Vik'); + expect(row.tags).toBe('["beach"]'); + expect(row.is_draft).toBe(1); + }); + }); + /* * The stop switch (discussion #2064). The REST route takes it, so the tool * does too, and get_journey_stats is where the effect shows. diff --git a/server/tests/unit/nest/journey-entry-patch.helpers.test.ts b/server/tests/unit/nest/journey-entry-patch.helpers.test.ts new file mode 100644 index 000000000..6ddb453e0 --- /dev/null +++ b/server/tests/unit/nest/journey-entry-patch.helpers.test.ts @@ -0,0 +1,68 @@ +/** + * The one reading of an entry update every surface makes, and what it + * replaced: the columns it writes as they are stored, the skeleton promoted + * by a story, and the entry's earlier values of exactly the fields it names. + */ +import { entryPrevious, entryUpdatePatch } from '../../../src/nest/journey/journey-entry-patch.helpers'; +import type { JourneyEntry } from '../../../src/types'; + +import { describe, expect, it } from 'vitest'; + +function entry(over: Partial = {}): JourneyEntry { + return { + id: 12, + journey_id: 3, + author_id: 7, + type: 'entry', + title: 'Vik', + story: null, + entry_date: '2026-07-01', + entry_time: '14:30', + location_lat: 63.4, + location_lng: -19.04, + tags: '["beach"]', + pros_cons: null, + visibility: 'private', + sort_order: 0, + dismissed: 0, + stats_excluded: 0, + is_draft: 1, + ...over, + } as JourneyEntry; +} + +describe('entryUpdatePatch', () => { + it('JEPATCH-001: writes the named columns as stored, the country only with a coordinate, and always the time', () => { + const patch = entryUpdatePatch(entry(), { title: 'Reynisfjara', tags: ['sand'], is_draft: false }, 'IS', 99); + expect(patch).toEqual({ title: 'Reynisfjara', tags: '["sand"]', is_draft: 0, updated_at: 99 }); + const placed = entryUpdatePatch(entry(), { location_lat: null as unknown as number }, null, 99); + expect(placed).toEqual({ location_lat: null, country_code: null, updated_at: 99 }); + expect(entryUpdatePatch(entry(), { tags: null as unknown as string[] }, null, 1)).toEqual({ + tags: null, + updated_at: 1, + }); + }); + + it('JEPATCH-002: a story on a suggestion makes it an entry, over the type the call names', () => { + const skeleton = entry({ type: 'skeleton' }); + expect(entryUpdatePatch(skeleton, { story: 'Windy', type: 'checkin' }, null, 1)).toMatchObject({ type: 'entry' }); + expect(entryUpdatePatch(skeleton, { story: ' ' }, null, 1)).not.toHaveProperty('type'); + }); +}); + +describe('entryPrevious', () => { + it('JEPATCH-010: answers the entry earlier values of the fields named, decoded, nothing else', () => { + expect(entryPrevious(entry(), { title: 'X', tags: [], is_draft: false, location_lat: 1 })).toEqual({ + title: 'Vik', + tags: ['beach'], + is_draft: true, + location_lat: 63.4, + }); + expect(entryPrevious(entry(), { sort_order: 4 })).toEqual({}); + }); + + it('JEPATCH-011: a suggestion written up goes back to being a suggestion', () => { + expect(entryPrevious(entry({ type: 'skeleton' }), { story: 'Windy' })).toEqual({ story: null, type: 'skeleton' }); + expect(entryPrevious(entry({ type: 'skeleton' }), { story: '' })).toEqual({ story: null }); + }); +}); diff --git a/shared/src/journey/journey.schema.ts b/shared/src/journey/journey.schema.ts index c4c8e448a..3a5cea801 100644 --- a/shared/src/journey/journey.schema.ts +++ b/shared/src/journey/journey.schema.ts @@ -220,6 +220,62 @@ export const journeyEntriesRangeSchema = z.object({ }); export type JourneyEntriesRange = z.infer; +/** + * The change the MCP tool `update_journey_entry` makes to an entry. Fields + * left out keep their value; null clears one. Strict, unlike the REST body, + * which forwards whatever it is given. + */ +export const journeyEntryUpdateToolSchema = z.strictObject({ + title: z.string().max(300).nullable().optional(), + story: z.string().nullable().optional(), + entry_date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .optional(), + entry_time: z.string().nullable().optional(), + location_name: z.string().nullable().optional(), + location_lat: z + .number() + .min(-90) + .max(90) + .nullable() + .optional() + .describe('Latitude, or null to take the entry off the journey map'), + location_lng: z.number().min(-180).max(180).nullable().optional(), + mood: z.string().nullable().optional(), + weather: z.string().max(100).nullable().optional(), + tags: z.array(z.string()).nullable().optional(), + pros_cons: journeyEntryProsConsSchema.nullable().optional().describe('Replaces the whole verdict; null clears it'), + visibility: journeyEntryVisibilitySchema.optional(), + type: journeyEntryTypeSchema + .optional() + .describe('Promote a trip-derived "skeleton" to a real "entry" once it has been written up'), + sort_order: z.number().int().min(0).optional(), + stats_excluded: z + .boolean() + .optional() + .describe( + 'True leaves the entry in the journal but takes it off the journey route and out of its distance, countries and step count (see get_journey_stats); false puts it back. For the home airport, a stopover, the place the trip was planned from', + ), + dismissed: z + .boolean() + .optional() + .describe( + 'True waves a trip-derived suggestion away: it leaves the journey without being deleted, so the trip sync does not offer it again. restore_journey_suggestions brings every dismissed one back', + ), + is_draft: z + .boolean() + .optional() + .describe('True turns the entry into a draft that the journey share link leaves out; false publishes it'), +}); +export type JourneyEntryUpdateTool = z.infer; + +/** The new order the MCP tool `reorder_journey_entries` sets: entry ids, first first. */ +export const journeyReorderEntriesToolSchema = z.strictObject({ + orderedIds: z.array(idSchema), +}); +export type JourneyReorderEntriesTool = z.infer; + /** Free-form plus the entry_date the handler demands itself. */ export const journeyEntryCreateRequestSchema = z.looseObject({ entry_date: z.unknown().optional(),