Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(tours): prepare_tour_change drops the shaping of legs it takes apart and guards a loop's closing leg

Maurice1993ed4d28e1
diff --git a/server/src/nest/tours/tour-change-apply.ts b/server/src/nest/tours/tour-change-apply.ts
index c116b6e7b..9c03081e5 100644
--- a/server/src/nest/tours/tour-change-apply.ts
+++ b/server/src/nest/tours/tour-change-apply.ts
@@ -9,7 +9,15 @@
* already done stays as it is: a station visited or skipped on any of its days
* is neither removed, replaced nor moved, nothing new goes before it, and a
* protected station (CW-10) keeps its place. A leg drawn by hand is kept as
- * drawn, so neither of its ends changes and nothing is put into it.
+ * drawn, so neither of its ends changes and nothing is put into it; the
+ * closing leg of a loop counts as the leg into its first station.
+ *
+ * A leg runs from one station to the next through the shaping points that
+ * steer it. Once a change takes a station out of a leg or puts one into it,
+ * that leg is not the one its shaping points were set for, so they go with
+ * it and the answer names them: the way after the change is routed through
+ * the stations as they are, never past points steering a leg that is gone.
+ * The ends of the walk therefore stay stations.
*/
import {
CITY_WALK_MAX_STATIONS,
@@ -96,6 +104,8 @@ type ChangeOutcome =
/** The saved stations a remove took out, and those a replace stands in for. */
removed: DraftPoint[];
replaced: DraftPoint[];
+ /** The shaping points dropped with a leg a change took apart, each with that change. */
+ shapingDropped: DraftPoint[];
}
| { kind: 'refused'; refused: ChangeRefusal[] };
@@ -123,6 +133,7 @@ class ChangeRun {
readonly body: DraftPoint[];
readonly removed: DraftPoint[] = [];
readonly replaced: DraftPoint[] = [];
+ readonly shapingDropped: DraftPoint[] = [];
readonly refused: ChangeRefusal[] = [];
/** The saved stations a change removed or replaced, which no later change can name. */
private readonly gone = new Set<string>();
@@ -142,31 +153,24 @@ class ChangeRun {
const before = this.refused.length;
if ('station' in change) this.checkLink(change.station, (reason) => refuse(reason, null));
if (change.op === 'add') {
- const at = this.slotAfter(change.after_key, null, refuse);
- if (at !== null && this.refused.length === before) {
- this.body.splice(at, 0, { ...newStation(change.station, number), after: change.after_key });
- }
+ if (!this.slotAfter(change.after_key, null, refuse) || this.refused.length > before) return;
+ const at = this.openSlot(change.after_key, number);
+ this.body.splice(at, 0, { ...newStation(change.station, number), after: change.after_key });
return;
}
const station = this.station(change.key, refuse);
if (station === null) return;
+ if (change.op === 'move' && !this.slotAfter(change.after_key, change.key, refuse)) return;
+ if (this.refused.length > before) return;
+ const { point, at } = this.takeOut(station, number);
if (change.op === 'move') {
- const at = this.slotAfter(change.after_key, change.key, refuse);
- if (at === null || this.refused.length > before) return;
- const moved = this.body.splice(station, 1)[0] as DraftPoint;
- this.body.splice(at > station ? at - 1 : at, 0, {
- ...moved,
- origin: 'moved',
- change: number,
- after: change.after_key,
- });
+ const slot = this.openSlot(change.after_key, number);
+ this.body.splice(slot, 0, { ...point, origin: 'moved', change: number, after: change.after_key });
return;
}
- if (this.refused.length > before) return;
this.gone.add(change.key);
- const replacing = change.op === 'replace' ? [this.replacing(change.station, number, change.key)] : [];
- const gone = this.body.splice(station, 1, ...replacing)[0] as DraftPoint;
- (change.op === 'remove' ? this.removed : this.replaced).push({ ...gone, change: number });
+ if (change.op === 'replace') this.body.splice(at, 0, this.replacing(change.station, number, change.key));
+ (change.op === 'remove' ? this.removed : this.replaced).push({ ...point, change: number });
}
private replacing(station: CityWalkStation, change: number, key: string): DraftPoint {
@@ -181,10 +185,68 @@ class ChangeRun {
const done = this.basis.done.get(key);
if (point.protected === true) refuse('protected', key);
if (done && done.length > 0) refuse('done', key, [...done]);
- if (point.fixed_leg || this.body[index - 1]?.fixed_leg) refuse('fixed_leg', key);
+ if (this.anyFixed([...this.legInto(index), ...this.legOutOf(index)])) refuse('fixed_leg', key);
return index;
}
+ /**
+ * The points whose legs run into the station at `index`: the station before
+ * it and the shaping points between. The first station of a loop is reached
+ * by the closing leg, from the last station through the way back.
+ */
+ private legInto(index: number): number[] {
+ let from = index - 1;
+ while (from >= 0 && this.body[from]?.shaping) from -= 1;
+ if (from >= 0) return range(from, index);
+ if (!this.loop || index !== 0) return [];
+ let last = this.body.length - 1;
+ while (last > 0 && this.body[last]?.shaping) last -= 1;
+ return last > 0 ? range(last, this.body.length) : [];
+ }
+
+ /** The points whose legs run out of the point at `index` to the next station: it and the shaping points after it. */
+ private legOutOf(index: number): number[] {
+ let to = index + 1;
+ while (this.body[to]?.shaping) to += 1;
+ return range(index, to);
+ }
+
+ private anyFixed(indexes: readonly number[]): boolean {
+ return indexes.some((index) => this.body[index]?.fixed_leg);
+ }
+
+ /** The shaping points among these indexes taken out with the leg they steered, each recorded with the change. */
+ private dropShaping(indexes: readonly number[], change: number): void {
+ const shaping = [...new Set(indexes)].filter((index) => this.body[index]?.shaping).sort((a, b) => a - b);
+ const dropped = shaping.map((index) => ({ ...(this.body[index] as DraftPoint), change }));
+ for (const index of [...shaping].reverse()) this.body.splice(index, 1);
+ this.shapingDropped.push(...dropped);
+ }
+
+ /** The station at `index` taken out with the shaping points of its legs, and where it stood once they are gone. */
+ private takeOut(index: number, change: number): { point: DraftPoint; at: number } {
+ const point = this.body[index] as DraftPoint;
+ this.dropShaping([...this.legInto(index), ...this.legOutOf(index)], change);
+ const at = this.body.indexOf(point);
+ this.body.splice(at, 1);
+ return { point, at };
+ }
+
+ /** Where a stop put after `anchor` goes, once the shaping points of the leg it splits are gone. */
+ private openSlot(anchor: string, change: number): number {
+ const at = this.slotIndex(this.body.findIndex((point) => point.ref === anchor && !point.shaping));
+ this.dropShaping(this.legOutOf(at - 1), change);
+ return at;
+ }
+
+ /** Right after the station at `index` and the stops already put after it, stopping at the one being moved. */
+ private slotIndex(index: number, moving: string | null = null): number {
+ const anchor = this.body[index]?.ref;
+ let at = index + 1;
+ while (this.body[at]?.after === anchor && this.body[at]?.ref !== moving) at += 1;
+ return at;
+ }
+
/** Where a saved station stands now, or why it cannot be named. */
private indexOfStation(key: string, refuse: (reason: RefusalReason, key: string) => void): number | null {
const index = this.body.findIndex((point) => point.ref === key && !point.shaping);
@@ -194,26 +256,26 @@ class ChangeRun {
}
/**
- * Where something put after a saved station goes: right after it and after
- * the stops already put there, never into a hand-drawn leg and never before
- * a station the travellers already did.
+ * Whether something may be put after a saved station: it goes right after
+ * it and after the stops already put there, never into a hand-drawn leg and
+ * never before a station the travellers already did. False when the anchor
+ * cannot be named at all.
*/
private slotAfter(
anchor: string,
moving: string | null,
refuse: (reason: RefusalReason, key: string) => void,
- ): number | null {
+ ): boolean {
if (anchor === moving) {
refuse('anchor_is_station', anchor);
- return null;
+ return false;
}
const index = this.indexOfStation(anchor, refuse);
- if (index === null) return null;
- let at = index + 1;
- while (this.body[at]?.after === anchor && this.body[at]?.ref !== moving) at += 1;
- if (this.body[index]?.fixed_leg) refuse('fixed_leg', anchor);
+ if (index === null) return false;
+ const at = this.slotIndex(index, moving);
+ if (this.anyFixed(this.legOutOf(at - 1))) refuse('fixed_leg', anchor);
if (at <= this.lastDoneIndex()) refuse('before_done', anchor);
- return at;
+ return true;
}
private lastDoneIndex(): number {
@@ -244,6 +306,11 @@ class ChangeRun {
}
}
+/** The whole numbers from `from` up to, not including, `to`. */
+function range(from: number, to: number): number[] {
+ return Array.from({ length: Math.max(0, to - from) }, (_, offset) => from + offset);
+}
+
function stationCount(points: readonly DraftPoint[], loop: boolean): number {
return (loop ? points.slice(0, -1) : points).filter((point) => !point.shaping).length;
}
@@ -266,7 +333,13 @@ export function applyChanges(basis: ChangeBasis, changes: readonly TourChange[])
if (count > CITY_WALK_MAX_STATIONS && count > stationCount(basis.points.map(savedPoint), loop)) {
return whole('too_many_stations');
}
- return { kind: 'ready', points, removed: run.removed, replaced: run.replaced };
+ return {
+ kind: 'ready',
+ points,
+ removed: run.removed,
+ replaced: run.replaced,
+ shapingDropped: run.shapingDropped,
+ };
}
const REFUSAL_TEXT: Record<RefusalReason, string> = {
@@ -281,7 +354,8 @@ const REFUSAL_TEXT: Record<RefusalReason, string> = {
done: 'the travellers already visited or skipped this station on a day of the walk; what was done stays as it is',
before_done:
'this would put a station before one the travellers already visited or skipped; add it after the last of those',
- fixed_leg: 'a leg drawn by hand in the planner starts or ends here and stays as drawn; change it in the planner',
+ fixed_leg:
+ 'a leg drawn by hand in the planner starts or ends here (for the first station of a loop, its closing leg too) and stays as drawn; change it in the planner',
place_not_linkable: 'the new station names a place that is not a place of this trip, or is a tour',
too_few_stations: 'a city walk keeps at least two stations',
too_many_stations: `a city walk holds at most ${CITY_WALK_MAX_STATIONS} stations`,
diff --git a/server/src/nest/tours/tour-change-effects.ts b/server/src/nest/tours/tour-change-effects.ts
index e048f2593..79ce0101d 100644
--- a/server/src/nest/tours/tour-change-effects.ts
+++ b/server/src/nest/tours/tour-change-effects.ts
@@ -16,6 +16,8 @@ interface ChangeEffectsInput {
after: readonly DraftPoint[];
removed: readonly DraftPoint[];
replaced: readonly DraftPoint[];
+ /** The shaping points dropped with a leg a change took apart. */
+ shapingDropped: readonly DraftPoint[];
wayBefore: FootWay;
wayAfter: FootWay;
/** As stored with the walk when it was last saved: kilometres and minutes, null when not known. */
@@ -128,6 +130,15 @@ function gapsOf(input: ChangeEffectsInput, stationsAfter: readonly DraftPoint[])
...(input.saved.some((point) => point.fixed_leg)
? [{ about: 'walking' as const, why: 'hand_drawn_leg_routed' as const }]
: []),
+ ...(input.shapingDropped.length > 0
+ ? [
+ {
+ about: 'walking' as const,
+ why: 'shaping_dropped' as const,
+ shaping_points: input.shapingDropped.map((point) => ({ key: keyOf(point), by_change: point.change })),
+ },
+ ]
+ : []),
...(unknownStays.length > 0
? [
{
@@ -154,9 +165,15 @@ function asWaypoint(draft: DraftPoint): TourWaypoint {
return point;
}
-/** A new station as create_place takes it, to keep it as a place of the trip instead of putting it in the walk. */
-function forLater(point: DraftPoint) {
- return { change: point.change, name: point.name ?? null, lat: point.lat, lng: point.lng };
+/**
+ * A new station as create_place takes it, to keep it as a place of the trip
+ * instead of putting it in the walk. A station linked to a place of the trip
+ * already is one, so it is left out rather than offered as a second copy.
+ */
+function forLater(after: readonly DraftPoint[]) {
+ return after
+ .filter((point) => (point.origin === 'added' || point.origin === 'replacing') && point.linked_place_id == null)
+ .map((point) => ({ change: point.change, name: point.name ?? null, lat: point.lat, lng: point.lng }));
}
/** The changed walk set against the saved one: its stations, what went, the effects and the gaps. */
@@ -181,7 +198,7 @@ export function describeChange(input: ChangeEffectsInput) {
},
data_gaps: gapsOf(input, stationsAfter),
warnings: warningsOf([...input.removed, ...input.replaced]),
- for_later: input.after.filter((point) => point.origin === 'added' || point.origin === 'replacing').map(forLater),
+ for_later: forLater(input.after),
waypoints_after: input.after.map(asWaypoint),
};
}
diff --git a/server/src/nest/tours/tour-change-preview.service.ts b/server/src/nest/tours/tour-change-preview.service.ts
index 5e1b96e17..f4bde1869 100644
--- a/server/src/nest/tours/tour-change-preview.service.ts
+++ b/server/src/nest/tours/tour-change-preview.service.ts
@@ -85,6 +85,7 @@ export class TourChangePreviewService {
after: outcome.points,
removed: outcome.removed,
replaced: outcome.replaced,
+ shapingDropped: outcome.shapingDropped,
wayBefore,
wayAfter,
stored: { distance_km: tour.distance, walking_minutes: tour.duration },
diff --git a/server/src/nest/tours/tour-change.mcp.ts b/server/src/nest/tours/tour-change.mcp.ts
index 392d94a1c..69142eef6 100644
--- a/server/src/nest/tours/tour-change.mcp.ts
+++ b/server/src/nest/tours/tour-change.mcp.ts
@@ -32,7 +32,7 @@ export class TourChangeMcp {
@Tool({
name: 'prepare_tour_change',
description:
- "Prepare a change to a saved tour for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it is. Read the tour with get_tour_plan first. A city walk (tour_type walk) takes changes so far; every other type, and a walk that is a recorded track without stations of its own, is refused with the reason. changes apply in order, each naming saved stations by their key: add (a new station after after_key; a spontaneous stop is an add after the station the traveller is at), remove, replace (a new station in the place of key) and move (key to after after_key). Stops put after the same station keep the order given. A station protected, or visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn; such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times), warnings (a must station removed or replaced), for_later (each new station as create_place takes it, to keep it as a place of the trip instead) and waypoints_after. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
+ "Prepare a change to a saved tour for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it is. Read the tour with get_tour_plan first. A city walk (tour_type walk) takes changes so far; every other type, and a walk that is a recorded track without stations of its own, is refused with the reason. changes apply in order, each naming saved stations by their key: add (a new station after after_key; a spontaneous stop is an add after the station the traveller is at), remove, replace (a new station in the place of key) and move (key to after after_key). Stops put after the same station keep the order given. A station protected, or visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn (the closing leg of a loop included); such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times, shaping points dropped because the leg they steered changed), warnings (a must station removed or replaced), for_later (each new station not yet a place of the trip as create_place takes it, to keep it as a place instead; a station with linked_place_id already is one and is left out) and waypoints_after. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
diff --git a/server/tests/unit/nest/tour-change-apply.test.ts b/server/tests/unit/nest/tour-change-apply.test.ts
index 8c980d77c..2bd349c59 100644
--- a/server/tests/unit/nest/tour-change-apply.test.ts
+++ b/server/tests/unit/nest/tour-change-apply.test.ts
@@ -8,7 +8,7 @@ import { CITY_WALK_MAX_STATIONS, type TourChange, type TourWaypoint } from '@tre
import { describe, expect, it } from 'vitest';
-// TCHG-APPLY-001 to TCHG-APPLY-007
+// TCHG-APPLY-001 to TCHG-APPLY-009
const point = (key: string, sequence: number, extra: Partial<TourWaypoint> = {}): TourWaypoint => ({
lat: 48 + sequence * 0.01,
@@ -53,21 +53,22 @@ describe('a change laid onto a saved walk (MCP-T02)', () => {
{ op: 'add', station: cafe, after_key: 'stop-museum' },
{ op: 'add', station: { ...cafe, name: 'Bakery', linked_place_id: 7 }, after_key: 'stop-museum' },
];
- const { points, removed, replaced } = ready(applyChanges(basis(), changes));
- expect(refs(points)).toEqual(['stop-gate', 'stop-museum', 'new:1', 'new:2', 'shape-0001', 'stop-park', 'stop-end']);
+ const { points, removed, replaced, shapingDropped } = ready(applyChanges(basis(), changes));
+ // The shaping point steered the museum to park leg the first stop split, so it goes with that leg.
+ expect(refs(points)).toEqual(['stop-gate', 'stop-museum', 'new:1', 'new:2', 'stop-park', 'stop-end']);
expect(points.map((p) => [p.sequence, p.role])).toEqual([
[0, 'start'],
[1, 'via'],
[2, 'via'],
[3, 'via'],
[4, 'via'],
- [5, 'via'],
- [6, 'end'],
+ [5, 'end'],
]);
expect(points[2]).toMatchObject({ name: 'Cafe', origin: 'added', change: 1, after: 'stop-museum', replaces: null });
expect(points[2]?.key).toBeUndefined();
expect(points[3]).toMatchObject({ name: 'Bakery', linked_place_id: 7, change: 2 });
expect([removed, replaced]).toEqual([[], []]);
+ expect(shapingDropped.map((p) => [p.ref, p.change])).toEqual([['shape-0001', 1]]);
});
it('TCHG-APPLY-002: remove, replace and move each say what they did, and a move goes before or after where it was', () => {
@@ -77,13 +78,14 @@ describe('a change laid onto a saved walk (MCP-T02)', () => {
{ op: 'move', key: 'stop-end', after_key: 'stop-gate' },
{ op: 'move', key: 'stop-gate', after_key: 'stop-end' },
];
- const { points, removed, replaced } = ready(applyChanges(basis(), changes));
- expect(refs(points)).toEqual(['stop-end', 'stop-gate', 'new:2', 'shape-0001']);
+ const { points, removed, replaced, shapingDropped } = ready(applyChanges(basis(), changes));
+ expect(refs(points)).toEqual(['stop-end', 'stop-gate', 'new:2']);
expect(points[0]).toMatchObject({ origin: 'moved', change: 3, role: 'start' });
- expect(points[2]).toMatchObject({ origin: 'replacing', replaces: 'stop-museum', name: 'Cafe' });
- expect(points[3]?.role).toBe('end');
+ expect(points[2]).toMatchObject({ origin: 'replacing', replaces: 'stop-museum', name: 'Cafe', role: 'end' });
expect(removed.map((p) => [p.ref, p.change])).toEqual([['stop-park', 1]]);
expect(replaced.map((p) => [p.ref, p.change, p.importance])).toEqual([['stop-museum', 2, 'must']]);
+ // Removing the park took the leg the shaping point steered into it, so the walk never ends on it.
+ expect(shapingDropped.map((p) => [p.ref, p.change])).toEqual([['shape-0001', 1]]);
});
it('TCHG-APPLY-003: what the travellers did, a protected station and a hand-drawn leg stay as they are', () => {
@@ -185,7 +187,97 @@ describe('a change laid onto a saved walk (MCP-T02)', () => {
const points = walk();
points[3] = { ...points[3], key: undefined } as TourWaypoint;
const add: TourChange[] = [{ op: 'add', station: cafe, after_key: 'stop-gate' }];
- const { points: after } = ready(applyChanges(basis({ points }), add));
+ const { points: after, shapingDropped } = ready(applyChanges(basis({ points }), add));
expect(refs(after)).toEqual(['stop-gate', 'new:1', 'stop-museum', 'shape-0001', 'saved:3', 'stop-end']);
+ expect(shapingDropped).toEqual([]);
+ });
+
+ it('TCHG-APPLY-008: the shaping points of the legs a change takes apart go with them, those of other legs stay', () => {
+ // The gate, shaping a, the museum, shaping b and c, the park, shaping d, the end.
+ const shaped = [
+ point('stop-gate', 0, { role: 'start' }),
+ point('shape-a', 1, { shaping: true, name: null }),
+ point('stop-museum', 2),
+ point('shape-b', 3, { shaping: true, name: null }),
+ point('shape-c', 4, { shaping: true, name: null }),
+ point('stop-park', 5),
+ point('shape-d', 6, { shaping: true, name: null }),
+ point('stop-end', 7, { role: 'end' }),
+ ];
+ const dropped = (outcome: ReturnType<typeof applyChanges>) =>
+ ready(outcome).shapingDropped.map((p) => [p.ref, p.change]);
+
+ const removeMuseum = applyChanges(basis({ points: shaped }), [{ op: 'remove', key: 'stop-museum' }]);
+ expect(refs(ready(removeMuseum).points)).toEqual(['stop-gate', 'stop-park', 'shape-d', 'stop-end']);
+ expect(dropped(removeMuseum)).toEqual([
+ ['shape-a', 1],
+ ['shape-b', 1],
+ ['shape-c', 1],
+ ]);
+
+ // Moving the end takes its leg in with it, and the leg it is put into loses its shaping too.
+ const moveEnd = applyChanges(basis({ points: shaped }), [
+ { op: 'move', key: 'stop-end', after_key: 'stop-museum' },
+ ]);
+ const moved = ready(moveEnd).points;
+ expect(refs(moved)).toEqual(['stop-gate', 'shape-a', 'stop-museum', 'stop-end', 'stop-park']);
+ expect(moved.map((p) => p.role)).toEqual(['start', 'via', 'via', 'via', 'end']);
+ expect(dropped(moveEnd)).toEqual([
+ ['shape-d', 1],
+ ['shape-b', 1],
+ ['shape-c', 1],
+ ]);
+
+ const replaceGate = applyChanges(basis({ points: shaped }), [{ op: 'replace', key: 'stop-gate', station: cafe }]);
+ expect(refs(ready(replaceGate).points)).toEqual([
+ 'new:1',
+ 'stop-museum',
+ 'shape-b',
+ 'shape-c',
+ 'stop-park',
+ 'shape-d',
+ 'stop-end',
+ ]);
+ expect(dropped(replaceGate)).toEqual([['shape-a', 1]]);
+ });
+
+ it('TCHG-APPLY-009: the closing leg of a loop belongs to its first station, as drawn by hand and as shaped', () => {
+ const free = {
+ kind: 'free',
+ geometry: [
+ [48.02, 11],
+ [48, 11],
+ ],
+ } as TourWaypoint['fixed_leg'];
+ const loop = (closing: Partial<TourWaypoint>) => [
+ point('stop-gate', 0, { role: 'start' }),
+ point('stop-museum', 1),
+ point('stop-park', 2),
+ point('shape-home', 3, { shaping: true, name: null, ...closing }),
+ point('stop-back', 4, { role: 'end', lat: 48 }),
+ ];
+ const handDrawn = basis({ points: loop({ fixed_leg: free }) });
+ const outcome = applyChanges(handDrawn, [
+ { op: 'remove', key: 'stop-gate' },
+ { op: 'replace', key: 'stop-gate', station: cafe },
+ { op: 'move', key: 'stop-gate', after_key: 'stop-museum' },
+ { op: 'add', station: cafe, after_key: 'stop-park' },
+ ]);
+ expect(outcome.kind === 'refused' && outcome.refused.map((r) => [r.change, r.key, r.reason])).toEqual([
+ [1, 'stop-gate', 'fixed_leg'],
+ [2, 'stop-gate', 'fixed_leg'],
+ [3, 'stop-gate', 'fixed_leg'],
+ [4, 'stop-park', 'fixed_leg'],
+ ]);
+ // The middle of the loop can still change while its closing leg stays as drawn.
+ const middle = ready(applyChanges(handDrawn, [{ op: 'remove', key: 'stop-museum' }]));
+ expect(refs(middle.points)).toEqual(['stop-gate', 'stop-park', 'shape-home', 'stop-back']);
+ expect(middle.shapingDropped).toEqual([]);
+
+ // Without a hand-drawn leg, a new first station takes the way back along and the closing leg loses its shaping.
+ const shaped = ready(applyChanges(basis({ points: loop({}) }), [{ op: 'remove', key: 'stop-gate' }]));
+ expect(refs(shaped.points)).toEqual(['stop-museum', 'stop-park', 'stop-back']);
+ expect(shaped.points[2]).toMatchObject({ lat: shaped.points[0]?.lat, role: 'end' });
+ expect(shaped.shapingDropped.map((p) => [p.ref, p.change])).toEqual([['shape-home', 1]]);
});
});
diff --git a/server/tests/unit/nest/tour-change-effects.test.ts b/server/tests/unit/nest/tour-change-effects.test.ts
index 526517c4f..1f0dbfadd 100644
--- a/server/tests/unit/nest/tour-change-effects.test.ts
+++ b/server/tests/unit/nest/tour-change-effects.test.ts
@@ -5,7 +5,7 @@ import type { TourChange, TourWaypoint } from '@trek/shared';
import { describe, expect, it } from 'vitest';
-// TCHG-EFFECTS-001 to TCHG-EFFECTS-003
+// TCHG-EFFECTS-001 to TCHG-EFFECTS-004
const point = (key: string, sequence: number, extra: Partial<TourWaypoint> = {}): TourWaypoint => ({
lat: 48 + sequence * 0.01,
@@ -57,6 +57,7 @@ describe('what a prepared change does to a walk (MCP-T02)', () => {
after: outcome.points,
removed: outcome.removed,
replaced: outcome.replaced,
+ shapingDropped: outcome.shapingDropped,
wayBefore: routed([800, 900, 700], 1860),
wayAfter: routed([300, 450, 1500], 1700),
stored: { distance_km: 2.3, walking_minutes: 32 },
@@ -108,6 +109,7 @@ describe('what a prepared change does to a walk (MCP-T02)', () => {
after: outcome.points,
removed: outcome.removed,
replaced: outcome.replaced,
+ shapingDropped: outcome.shapingDropped,
wayBefore: routed([1], 60),
wayAfter: routed([1], 60),
stored: { distance_km: null, walking_minutes: null },
@@ -139,6 +141,7 @@ describe('what a prepared change does to a walk (MCP-T02)', () => {
after: outcome.points,
removed: outcome.removed,
replaced: outcome.replaced,
+ shapingDropped: outcome.shapingDropped,
wayBefore: { kind: 'unrouted', why: 'router_unavailable', position: null },
wayAfter: { kind: 'unrouted', why: 'station_off_the_way', position: 2 },
stored: { distance_km: 2.3, walking_minutes: null },
@@ -155,4 +158,37 @@ describe('what a prepared change does to a walk (MCP-T02)', () => {
{ about: 'walking', why: 'hand_drawn_leg_routed' },
]);
});
+
+ it('TCHG-EFFECTS-004: names the shaping points a change dropped, and keeps a station already a place out of for_later', () => {
+ const shaped = [...saved.slice(0, 2), point('shape-0001', 2, { shaping: true, name: null }), ...saved.slice(2)];
+ const outcome = applyChanges(
+ { tourType: 'walk', recorded: false, points: shaped, done: new Map(), linkable: new Set([7]) },
+ [
+ { op: 'add', station: { ...cafe, linked_place_id: 7 }, after_key: 'stop-museum' },
+ { op: 'add', station: { lat: 48.03, lng: 11, name: 'Kiosk' }, after_key: 'stop-park' },
+ ],
+ );
+ if (outcome.kind !== 'ready') throw new Error('refused');
+ const described = describeChange({
+ saved: shaped,
+ after: outcome.points,
+ removed: outcome.removed,
+ replaced: outcome.replaced,
+ shapingDropped: outcome.shapingDropped,
+ wayBefore: routed([1], 60),
+ wayAfter: routed([1], 60),
+ stored: { distance_km: null, walking_minutes: null },
+ });
+ expect(described.data_gaps).toContainEqual({
+ about: 'walking',
+ why: 'shaping_dropped',
+ shaping_points: [{ key: 'shape-0001', by_change: 1 }],
+ });
+ expect(described.waypoints_after.some((p) => p.shaping)).toBe(false);
+ expect(described.for_later).toEqual([{ change: 2, name: 'Kiosk', lat: 48.03, lng: 11 }]);
+ expect(described.stations_after.find((s) => s.name === 'Cafe')).toMatchObject({
+ change: 'added',
+ linked_place_id: 7,
+ });
+ });
});
diff --git a/server/tests/unit/nest/tour-change.mcp.test.ts b/server/tests/unit/nest/tour-change.mcp.test.ts
index 98dfa47af..19bdb0566 100644
--- a/server/tests/unit/nest/tour-change.mcp.test.ts
+++ b/server/tests/unit/nest/tour-change.mcp.test.ts
@@ -179,7 +179,9 @@ describe('TourChangeMcp (MCP-T02)', () => {
});
expect(proposal.effects.stays).toMatchObject({ change_minutes_known: 15, complete: false });
expect(proposal.warnings).toEqual([{ change: 2, key: 'stop-park', name: 'Park', why: 'must_station' }]);
- expect(proposal.for_later.map((stop: { name: string }) => stop.name)).toEqual(['Bakery', 'Beer garden']);
+ // The Bakery is linked to a place of the trip already, so only the beer garden is offered to keep for later.
+ expect(proposal.for_later.map((stop: { name: string }) => stop.name)).toEqual(['Beer garden']);
+ expect(proposal.stations_after[3]).toMatchObject({ name: 'Bakery', linked_place_id: f.bakery.id });
expect(proposal.waypoints_after.map((p: { key?: string }) => p.key ?? null)).toEqual([
'stop-gate',
'stop-cathedral',
diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md
index 4f6034326..51748d694 100644
--- a/wiki/MCP-Addon-Tools.md
+++ b/wiki/MCP-Addon-Tools.md
@@ -248,7 +248,7 @@ The saved tours of a trip, as the Tours list and the tour detail show them, how
| `preview_google_maps_walk` | Reads the stops of a Google Maps walking route shared as a link (a `maps.app.goo.gl` short link or a `google.com/maps/dir` link), in order, for a city walk: each stop's name and position, or no position when the link gives none (nothing is looked up or guessed), and the long link that was read. Only a route Google Maps marks as on foot is read; a car, bike or transit route, or a link that does not say, is refused. A short link is followed only to Google Maps itself. Nothing is saved, and the line drawn in Google Maps is not taken over: TREK plans the way on foot between the stops again. Needs `place_edit` on the trip | `trips:read` |
| `propose_city_walk` | Proposes a city walk from a briefing without saving anything: start (and end), the time frame on a day, the themes (`culture`, `parks`, `food`, `mixed`), the stations the traveller wished for, the places of the trip it may use and fixed appointments. Places for the themes come from the same search as `search_tour_pois`, up to 8, each with its source, theme and category; nothing is made up. Answers the stations in order with the walking distance and time from the one before, the arrival and leave times, the stay where the traveller gave it (unknown otherwise, which makes later arrivals the earliest possible), and the opening hours checked against the arrival on that day. The order is chosen on estimates; the walk in that order is then planned on foot by the router TREK uses for road trips (the traveller's own routing server where they set one), whose legs give the distances and times. Where it gives no way, because the router cannot be reached or a station lies more than 300 m off every way, the times are estimates over the straight distance with an allowance for streets at 4.5 km/h, and the answer says so and why. Walking and stays are kept apart, a complete total only when every stay is known, with the minutes the frame leaves for the stays not known. Lists free time, the wishes and appointments that cannot be kept as asked, what was left out and why, and `stations_for_create` for `create_city_walk` | `trips:read` |
| `create_city_walk` | Creates a city walk from stations the traveller confirmed (for instance `stations_for_create` of `propose_city_walk`), through the same creation the planner's save uses: a key for every station, its name, stay, importance, protection, opening hours and the place of the trip it stands for. The way on foot is planned by the same router as for the proposal, and the walk is saved with it, its distance and its walking time. Where the router gives no way, the walk is saved with its stations only (`route_pending`), says why, and has no line, distance or walking time until someone opens it in the planner, where TREK plans the way on foot and the walk can be saved with it. Needs `place_edit` on the trip | `trips:write` |
-| `prepare_tour_change` | Prepares a change to a saved city walk for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it was. The changes apply in order and name the saved stations by their keys: `add` (a new station after a station; a spontaneous stop on the way is an add after the station the traveller is at), `remove`, `replace` and `move`. A protected station, or one visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn; such a change is refused, and with it the whole proposal, naming every change and why. Another type of tour, or a walk that is a recorded track without stations of its own, is refused as well: so far only a city walk takes prepared changes. The answer names the tour and the `revision` it was prepared on (a save has to name it, and a tour changed since is refused rather than overwritten), the stations after the change with what changed each and where it stood before, what was removed, the way on foot before and after planned by the same router TREK uses for city walks and its change in metres and minutes (the distance and walking time stored with the walk given apart), the stays as far as known before and after, every leg after the change with the new ones marked, `data_gaps` for what could not be worked out (no way from the router, stays not known, no arrival times), a warning for a station of importance must removed or replaced, each new station as `create_place` takes it to keep it as a place of the trip instead, and whether the traveller may change the trip's places at all (`can_save`) | `trips:read` |
+| `prepare_tour_change` | Prepares a change to a saved city walk for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it was. The changes apply in order and name the saved stations by their keys: `add` (a new station after a station; a spontaneous stop on the way is an add after the station the traveller is at), `remove`, `replace` and `move`. A protected station, or one visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn, the closing leg of a loop included; such a change is refused, and with it the whole proposal, naming every change and why. Another type of tour, or a walk that is a recorded track without stations of its own, is refused as well: so far only a city walk takes prepared changes. The answer names the tour and the `revision` it was prepared on (a save has to name it, and a tour changed since is refused rather than overwritten), the stations after the change with what changed each and where it stood before, what was removed, the way on foot before and after planned by the same router TREK uses for city walks and its change in metres and minutes (the distance and walking time stored with the walk given apart), the stays as far as known before and after, every leg after the change with the new ones marked, `data_gaps` for what could not be worked out (no way from the router, stays not known, no arrival times, shaping points dropped because the leg they steered changed), a warning for a station of importance must removed or replaced, each new station that is not yet a place of the trip as `create_place` takes it to keep it as a place instead (a station linked to a place of the trip is left out), and whether the traveller may change the trip's places at all (`can_save`) | `trips:read` |
| `plan_paddle_route` | Plans the legs of a paddle tour on the water network TREK builds from the paddle regions an admin added: each leg (`from`, `to`) along rivers and canals and across lakes, carried round weirs, dams and waterfalls, through or round locks (`lock_policy`), with `boat` and `lake_style` (`direct` or `shore`). Answers per leg its length, how far its ends were moved onto the water and its stretches (water, lake, whitewater, boat pass, portage with its source, lock, gap); a leg that cannot be planned says why (`not_on_water`, `no_region`, `cross_region`, `no_water_path`, `busy`, `timeout`). Nothing is saved; a planning aid, never a safety or legal clearance | `trips:read` |
### Road trip _(Road trip addon required)_