fix(tours): save_tour_change says nothing was saved and answers a proposal saved once already

A save refused by the rules of the tour now says "Nothing was saved and
nothing changed." instead of the preparation's wording: lay() takes what
the changes are laid for, and refusalText() leads with that action.

A save sent again after it committed (a retry after a lost answer) used
to meet the conflict of a tour that moved on, which tells the assistant
to prepare the change anew, so an add could be saved twice. The save now
looks up the step its proposal was saved as from the revision it was
prepared on, before the stale check and once more inside the write, and
answers already_saved with that step instead, writing nothing.
This commit is contained in:
Maurice
2026-10-20 14:52:41 +02:00
parent b177daea3c
commit ad2d653e9a
8 changed files with 147 additions and 21 deletions
@@ -87,6 +87,25 @@ export class TourChangeStepsRepository extends TrekRepository<TourChangeSteps> {
.executeTakeFirst();
}
/**
* The step a proposal of this tour was saved as, from the revision it was
* prepared on; undefined while it is not saved. A proposal is saved once, so
* a save sent again finds the step its first one recorded.
*/
async findSavedProposal(
place_id: number,
proposal_id: string,
base_revision: number,
): Promise<TourChangeStepRow | undefined> {
return await this.db()
.selectFrom('tour_change_steps')
.select(STEP_COLUMNS)
.where('place_id', '=', place_id)
.where('proposal_id', '=', proposal_id)
.where('base_revision', '=', base_revision)
.executeTakeFirst();
}
/**
* Marks a step taken back, inside the caller's transaction. Only a step that
* still stands is marked, so it is taken back once: false when it was already.
+6 -3
View File
@@ -369,7 +369,10 @@ function refusalLine(refusal: ChangeRefusal): string {
return `${about}: ${REFUSAL_TEXT[refusal.reason]}${days}.`;
}
/** Every refusal of a proposal, one per line, under a line saying nothing was prepared or saved. */
export function refusalText(refused: readonly ChangeRefusal[]): string {
return ['Nothing was prepared and nothing changed.', ...refused.map(refusalLine)].join('\n');
/** What a refused proposal was asked for: prepared for review, or saved once the traveller confirmed it. */
export type RefusedAction = 'prepared' | 'saved';
/** Every refusal of a proposal, one per line, under a line saying it was not prepared, or not saved. */
export function refusalText(refused: readonly ChangeRefusal[], action: RefusedAction): string {
return [`Nothing was ${action} and nothing changed.`, ...refused.map(refusalLine)].join('\n');
}
@@ -4,7 +4,7 @@ import type { TourStationVisitsRepository } from '../../db/repositories/TourStat
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
import { DomainError } from '../common/domain-error';
import { CityWalkFootWayService } from './city-walk-foot-way.service';
import { applyChanges, refusalText, type StationDone } from './tour-change-apply';
import { applyChanges, refusalText, type RefusedAction, type StationDone } from './tour-change-apply';
import { describeChange } from './tour-change-effects';
import { proposalIdOf, staleProposal } from './tour-change-proposal';
import { ToursService } from './tours.service';
@@ -15,6 +15,12 @@ import type { TourChange, TourChangeRequest } from '@trek/shared';
/** The refusal of a proposal the rules of its tour do not allow; its text names every change and why. */
export const TOUR_CHANGE_REFUSED = 'tour_change_refused';
/**
* What the changes are laid for: a preparation, or the save of a proposal
* prepared on a revision, whose refusal then says nothing was saved.
*/
export type LayFor = { action: Extract<RefusedAction, 'prepared'> } | { action: 'saved'; preparedOn: number };
/** The places of the trip the new stations of a proposal name. */
function linkedIds(changes: readonly TourChange[]): number[] {
return changes.flatMap((change) => {
@@ -55,15 +61,15 @@ export class TourChangePreviewService {
/**
* The changes laid onto the tour as it is saved now, with the visits of all
* its days and the places the new stations name, or the refusal naming
* every change the rules of the tour do not allow. A save lays them again
* on the tour it is about to write, so it is held to the same rules, and
* names the revision they were prepared on: a tour that moved past it is a
* conflict before any rule is asked.
* every change the rules of the tour do not allow, saying it was not
* `layFor.action`. A save lays them again on the tour it is about to write, so
* it is held to the same rules, and names the revision they were prepared
* on: a tour that moved past it is a conflict before any rule is asked.
*/
async lay(tripId: number, placeId: number, changes: readonly TourChange[], preparedOn?: number) {
async lay(tripId: number, placeId: number, changes: readonly TourChange[], layFor: LayFor) {
const { tour, waypoints } = await this.tours.getTour(String(tripId), String(placeId));
if (preparedOn !== undefined && tour.revision !== preparedOn) {
throw staleProposal(preparedOn, tour.revision ?? null);
if (layFor.action === 'saved' && tour.revision !== layFor.preparedOn) {
throw staleProposal(layFor.preparedOn, tour.revision ?? null);
}
const [visits, linkable] = await Promise.all([
this.visitsRepo.listForPlace(tripId, placeId),
@@ -80,7 +86,7 @@ export class TourChangePreviewService {
changes,
);
if (outcome.kind === 'refused') {
throw new DomainError(422, refusalText(outcome.refused), {
throw new DomainError(422, refusalText(outcome.refused, layFor.action), {
code: TOUR_CHANGE_REFUSED,
details: { refused: outcome.refused },
});
@@ -89,7 +95,7 @@ export class TourChangePreviewService {
}
async prepare(tripId: number, placeId: number, userId: number, { changes }: TourChangeRequest) {
const { tour, waypoints, outcome } = await this.lay(tripId, placeId, changes);
const { tour, waypoints, outcome } = await this.lay(tripId, placeId, changes, { action: 'prepared' });
const [wayBefore, wayAfter] = await Promise.all([
this.footWays.plan(userId, tripId, waypoints),
this.footWays.plan(userId, tripId, outcome.points),
@@ -1,6 +1,6 @@
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
import { TOUR_CHANGE_STEP_BEFORE, TOUR_CHANGE_STEP_CHANGES } from '../../db/json-columns';
import type { TourChangeStepsRepository } from '../../db/repositories/TourChangeSteps.repository';
import type { TourChangeStepRow, TourChangeStepsRepository } from '../../db/repositories/TourChangeSteps.repository';
import { encodeJson } from '../../utils/json-column';
import { DomainError } from '../common/domain-error';
import { UnitOfWork } from '../database/unit-of-work';
@@ -63,6 +63,29 @@ function savedAnswer(detail: TourDetailResponse, step: SavedStep, { way, prepare
};
}
/**
* The answer to a save of a proposal already saved, a save sent again after
* its answer was lost, say: it writes nothing and points at the step the
* first save recorded, so the assistant neither prepares the same changes
* again on the new revision nor saves them twice.
*/
function alreadySavedAnswer(step: TourChangeStepRow) {
const undone =
step.undone_revision === null
? ''
: ` It was taken back since, at revision ${step.undone_revision}: ` +
'prepare it anew only if the traveller asks for it again.';
return {
saved: true as const,
already_saved: true as const,
step: { id: step.id, base_revision: step.base_revision, revision: step.revision },
undone_revision: step.undone_revision,
message:
`This very proposal was already saved as step ${step.id}, raising the tour to revision ${step.revision}, ` +
`and this save wrote nothing. Do not prepare or save it again: read the tour with get_tour_plan.${undone}`,
};
}
/**
* MCP-T03: a prepared change the traveller confirmed, saved whole or not at
* all through the write the planner's save uses. The save names the revision
@@ -72,6 +95,8 @@ function savedAnswer(detail: TourDetailResponse, step: SavedStep, { way, prepare
* the same rules: first to plan the way on foot, then once more inside the
* write, so a station visited or a place gone in between refuses the save
* instead of being written over, and a failure leaves the tour as it was.
* A proposal is saved once: sent again once saved, it answers the step it
* was saved as instead of the conflict of a tour that moved on.
*
* The write records the step: the proposal, both revisions, the changes and
* the tour as it was before them (its line, its points, its measures), so it
@@ -98,13 +123,18 @@ export class TourChangeSaveService {
{ code: TOUR_CHANGE_NOT_PREPARED },
);
}
const laid = await this.preview.lay(tripId, placeId, changes, preparedOn);
const earlier = await this.stepsRepo.findSavedProposal(placeId, proposalId, preparedOn);
if (earlier) return alreadySavedAnswer(earlier);
const laid = await this.preview.lay(tripId, placeId, changes, { action: 'saved', preparedOn });
const way = await this.footWays.plan(userId, tripId, laid.outcome.points);
const changed: ChangedTour = { tour: laid.tour, points: laid.outcome.points, way, preparedOn };
const write = await this.tours.routeWrite(writeOf(changed));
const saved = await this.uow.transactional(async () => {
// The same proposal saved by a save sent alongside this one while the way was planned.
const savedMeanwhile = await this.stepsRepo.findSavedProposal(placeId, proposalId, preparedOn);
if (savedMeanwhile) return { earlier: savedMeanwhile };
// Laid once more on the tour as it is now: a tour moved on, a station done or a place gone refuses here.
const now = await this.preview.lay(tripId, placeId, changes, preparedOn);
const now = await this.preview.lay(tripId, placeId, changes, { action: 'saved', preparedOn });
const before = await this.beforeState(tripId, placeId, now);
const { revision, visitsDropped } = await this.tours.replaceRoute(tripId, placeId, write);
const id = await this.stepsRepo.record({
@@ -118,6 +148,7 @@ export class TourChangeSaveService {
});
return { step: { id, revision }, visitsDropped };
});
if ('earlier' in saved) return alreadySavedAnswer(saved.earlier);
const detail = await this.tours.announceRouteUpdate(String(tripId), placeId, saved.visitsDropped);
return savedAnswer(detail, saved.step, changed);
}
+1 -1
View File
@@ -82,7 +82,7 @@ export class TourChangeMcp {
@Tool({
name: 'save_tour_change',
description:
"Save a change to a saved tour that prepare_tour_change prepared and the traveller confirmed, whole or not at all. Call it only after the traveller said yes to the proposal exactly as it was shown to them, with confirmed true, the same changes, expected_revision set to base.revision and the proposal_id of that proposal; anything else is refused and nothing is saved. Before anything is written the trip permission and the tour are checked again: a tour changed since the proposal was prepared is refused as a conflict (prepare the change again from get_tour_plan, never retry the old one), and a change the rules no longer allow (a station visited or skipped meanwhile, a place of the trip gone) is refused with every reason. The save writes the stations, their keys and the way on foot as the planner's save does, planned by the same router as the proposal: where the router gives no way the walk keeps its stations only (route_pending true, distance and walking time null) until the planner plans it. Stations kept keep their keys and their visits. The answer: saved, step (its id, base_revision and the revision the save raised the tour to; the step keeps the changes and the tour as it was before, so it can be taken back with prepare_tour_undo and undo_tour_change while it is the latest change, and nothing of the conversation), the tour as now saved (revision, distance_km, walking_minutes, route_pending), foot_way (planned, or why not) and the stations in order with their keys. Read the result with get_tour_plan. A new walk has no revision yet: create it with create_city_walk instead. Needs place editing permission on the trip.",
"Save a change to a saved tour that prepare_tour_change prepared and the traveller confirmed, whole or not at all. Call it only after the traveller said yes to the proposal exactly as it was shown to them, with confirmed true, the same changes, expected_revision set to base.revision and the proposal_id of that proposal; anything else is refused and nothing is saved. Before anything is written the trip permission and the tour are checked again: a tour changed since the proposal was prepared is refused as a conflict (prepare the change again from get_tour_plan, never retry the old one), a proposal already saved, a save sent again after its answer was lost, writes nothing and answers already_saved with the step it was saved as (never prepare or save it again), and a change the rules no longer allow (a station visited or skipped meanwhile, a place of the trip gone) is refused with every reason. The save writes the stations, their keys and the way on foot as the planner's save does, planned by the same router as the proposal: where the router gives no way the walk keeps its stations only (route_pending true, distance and walking time null) until the planner plans it. Stations kept keep their keys and their visits. The answer: saved, step (its id, base_revision and the revision the save raised the tour to; the step keeps the changes and the tour as it was before, so it can be taken back with prepare_tour_undo and undo_tour_change while it is the latest change, and nothing of the conversation), the tour as now saved (revision, distance_km, walking_minutes, route_pending), foot_way (planned, or why not) and the stations in order with their keys. Read the result with get_tour_plan. A new walk has no revision yet: create it with create_city_walk instead. Needs place editing permission on the trip.",
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),