Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/plans/2026-10-31-secretary-invitation-incident.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ Scope: one private conversation in which a write-secretary asked the bot to crea
- Tests: `test/services/ai/write-receipt.test.ts` (day and time from the write, create identity, update re-keying, repeat warnings, invitee spellings and slots, `fields:` labels, offsets) and `test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts`.
- Open, tracked in #922: reminders and `location_abstract` are not compared when deciding whether two creates are the same; a create retired by an unconfirmed update is not re-keyed by a later successful retry; a later success of the same identity is taken for a corrected retry, so a refusal of a genuinely separate second event with the same title and start can disappear; two same-titled events in one receipt are told apart by nothing but their own write's time; one contact named by id and by username is two writes in the ledger (so a delivery by id followed by a refusal by `@name` shows both lines; needs a shared person resolution and the rejection reason class of #910); a long chain of mixed invitation outcomes (a delivery, a created-but-undelivered repeat, then an unknown one) can lose a line; a refused create whose start has no offset and its corrected retry read as two lines; `send_invitation` without `owner_id` on another member's group event answers a plain not found; `update_event` with `all_day: "false"` is stored truthy (the update schema lacks `all_day`); cancel, resend and the roster still call a group event of the owner not found.

## Receipt for a repeated create (2026-11-07, #929, #520)

`create_event` answers a repeat of a request saved moments ago with `success: true` and `ToolResult.alreadyExists = { entity: 'event', id }` (#942). The write ledger records that structured field on the attempt (never the output prose) and treats the repeat like any other success of the same request: it settles an earlier refused try, and an earlier try of unknown result keeps its duplicate warning (a deliberate `allow_duplicate` copy may have been written, and finding the first row cannot prove otherwise). The receipt then tells a repeat of an event that a recorded successful create already told as nothing, so a creation and its repeat read as one created event and the guard does not fire; a repeat of an event this run did not create is told once as "Already in the calendar" / "Уже есть в календаре" (the run wrote nothing). A different event, a deliberate `allow_duplicate` copy and the group-chat target hiding are unchanged. The receipt-only confirmation (`buildReceiptConfirmation`) follows the same rule. Tests: `test/services/ai/write-receipt-existing-event.test.ts` (real handler and ledger), `test/services/ai/receipt-confirmation.test.ts`.

## Completion

Record the exact merged commit, server full suite, typecheck and lint, independent review, the normal `gh ship` result and the deployed image revision as separate statuses in #908, #909 and #526. A conversation-level acceptance run (secretary invites a named person; a long-option question is answered once) is a separate, authorized live test. Do not close #910–#915 with these commits.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "hypercalendarbot"
version = "0.3.6"
version = "0.3.7"
requires-python = ">=3.12"
dependencies = [
"pyrofork>=2.3",
Expand Down
3 changes: 3 additions & 0 deletions src/config/constants/messages/en/workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const enWorkflow = {
receipt: {
intro: 'Done in your calendar:',
created: (title: string, when: string) => `Created: "${title}" — ${when}`,
alreadyThere: (title: string, when: string) => `Already in the calendar: "${title}" — ${when}`,
updated: (title: string, when: string) => `Updated: "${title}" — now ${when}`,
deleted: (title: string, when: string) => `Deleted: "${title}" (was ${when})`,
allDay: 'all day',
Expand Down Expand Up @@ -85,6 +86,8 @@ export const enWorkflow = {
? `The invitation to ${event} was skipped and not sent again: ${who}.`
: `The invitations to ${event} were skipped and not sent again: ${who}.`,
},
// A create that found its event already saved (same event, nothing written by this run).
alreadyThere: 'Already in the calendar',
operations: {
create_event: {
done: 'Created',
Expand Down
3 changes: 3 additions & 0 deletions src/config/constants/messages/ru/workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const ruWorkflow = {
receipt: {
intro: 'Сделано в календаре:',
created: (title: string, when: string) => `Создано: «${title}» — ${when}`,
alreadyThere: (title: string, when: string) => `Уже есть в календаре: «${title}» — ${when}`,
updated: (title: string, when: string) => `Изменено: «${title}» — теперь ${when}`,
deleted: (title: string, when: string) => `Удалено: «${title}» (было ${when})`,
allDay: 'весь день',
Expand Down Expand Up @@ -82,6 +83,8 @@ export const ruWorkflow = {
? `Приглашение на ${event} пропущено, повторно не отправлялось: ${who}.`
: `Приглашения на ${event} пропущены, повторно не отправлялись: ${who}.`,
},
// A create that found its event already saved (same event, nothing written by this run).
alreadyThere: 'Уже есть в календаре',
operations: {
create_event: {
done: 'Создано',
Expand Down
8 changes: 7 additions & 1 deletion src/services/ai/agent/receipt-confirmation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@ function eventLines(language: string, writes: readonly ToolEvidence[]): string |
const verb = receiptVerbOf(write.name);
const event = write.success ? extractEventSummaries(write.data)?.[0] : undefined;
if (!verb || !event) return null;
lines.set(`${verb}:${event.id}`, `• ${tr[verb](event.title, whenLabel(event, language))}`);
const text = `• ${(write.alreadyExists ? tr.alreadyThere : tr[verb])(event.title, whenLabel(event, language))}`;
if (!write.alreadyExists) {
lines.set(`${verb}:${event.id}`, text);
continue;
}
// A repeat answered "already exists" is the event itself: a creation of this run already stands for it.
if (!lines.has(`${verb}:${event.id}`)) lines.set(`existing:${event.id}`, text);
}
return [...lines.values()].join('\n');
}
1 change: 1 addition & 0 deletions src/services/ai/agent/tool-round.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ function recordExecuted(ledger: ToolRunLedger, name: string, input: ToolInput, t
success: toolResult.success,
output: toolResult.output,
data: toolResult.data,
alreadyExists: toolResult.alreadyExists,
});
}

Expand Down
4 changes: 3 additions & 1 deletion src/services/ai/response-grounding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { TZDate } from '@date-fns/tz';
import { addDays, format } from 'date-fns';
import type { EventSummary } from '../intent/variable-resolver.ts';
import type { ToolResultData } from './types.ts';
import type { ToolResult, ToolResultData } from './types.ts';

/** Tools whose results describe the user's schedule. */
export const SCHEDULE_READ_TOOLS: ReadonlySet<string> = new Set([
Expand All @@ -25,6 +25,8 @@ export interface ToolEvidence {
success: boolean;
output?: string;
data?: ToolResultData;
/** A create that found its event already saved: the same event, not a creation of this run. */
alreadyExists?: ToolResult['alreadyExists'];
}

export interface GroundingReport {
Expand Down
6 changes: 4 additions & 2 deletions src/services/ai/write-outcomes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ export class WriteOutcomes {
disposition: result.disposition,
mutationState: result.mutationState,
effect: result.effect,
alreadyExists: result.alreadyExists,
unknownRetried: false,
repeatUnknown: [],
create: createKeysOf(requested, owner, fields, isGroup, timezone),
Expand Down Expand Up @@ -458,9 +459,10 @@ export class WriteOutcomes {
});
}

/** The id of the event a successful create returned. */
/** The id of the event a successful create returned: the saved one when the create found it already there. */
private createdEventId(operation: string, result: ToolResult): number | null {
return operation === 'create_event' ? (extractEventSummaries(result.data)?.[0]?.id ?? null) : null;
if (operation !== 'create_event') return null;
return result.alreadyExists?.id ?? extractEventSummaries(result.data)?.[0]?.id ?? null;
}

/**
Expand Down
23 changes: 21 additions & 2 deletions src/services/ai/write-receipt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export interface WriteOutcome {
disposition: 'executed' | 'failed' | 'skipped' | 'waiting';
mutationState?: ToolResult['mutationState'];
effect?: ToolResult['effect'];
/** A create that wrote nothing because the calendar already held that event: the same event, not a second creation. */
alreadyExists?: ToolResult['alreadyExists'];
/** An earlier try at this same write ended unknown: this success may have been written twice. */
unknownRetried: boolean;
/** Later repeats of this successful create that ended unknown (what each asked for): the event may now exist twice. */
Expand Down Expand Up @@ -372,7 +374,8 @@ function plainLineOf(
): { base: string; reason: string | null } {
const standing = standingOf(outcome);
const labels = isEventOperation(outcome.operation) ? tr.operations[outcome.operation] : tr.otherWrite;
const prefix = standing === 'done' ? labels.done : standing === 'unknown' ? labels.unknown : labels.notDone;
const done = outcome.alreadyExists ? tr.alreadyThere : labels.done;
const prefix = standing === 'done' ? done : standing === 'unknown' ? labels.unknown : labels.notDone;
const when = ref ? whenOf(ref, view) : null;
const subject = isEventOperation(outcome.operation) ? (ref ? tr.eventNamed(ref.title, when) : tr.anEvent) : tr.change;
const reason = standing === 'rejected' ? tr.nothingChanged : standing === 'skipped' ? tr.skipped : null;
Expand Down Expand Up @@ -414,6 +417,20 @@ function inertRef(named: EventRef | null, view: ReceiptView): EventRef | null {
return view.hideTargets || !named ? null : { ...named, title: inert(named.title) };
}

/**
* A create answered "already exists" is the event found again by its id: it tells nothing that a successful
* create of that same event recorded before it (made by this run, or found there by an earlier repeat) has not told.
*/
function repeatsToldEvent(outcomes: readonly WriteOutcome[], index: number): boolean {
const id = outcomes[index]?.alreadyExists?.id;
return (
id !== undefined &&
outcomes.some(
(other, i) => i < index && other.operation === 'create_event' && other.success && other.eventId === id,
)
);
}

/** Files one recorded write under the kind of line it is told as: an invitation, a side effect or an event change. */
function addOutcome(
draft: Draft,
Expand Down Expand Up @@ -472,7 +489,9 @@ export function renderReceipt(
const rejected = standings.includes('rejected');
const duplicateRisk = outcomes.some((outcome) => outcome.unknownRetried);

for (const outcome of outcomes) addOutcome(draft, outcome, events, view, tr, outcomes);
outcomes.forEach((outcome, index) => {
if (!repeatsToldEvent(outcomes, index)) addOutcome(draft, outcome, events, view, tr, outcomes);
});

const lines = draft.entries.flatMap((entry) => renderEntry(entry, view, tr));
if (duplicateRisk) lines.push(tr.retriedAfterUnknown);
Expand Down
53 changes: 51 additions & 2 deletions test/services/ai/receipt-confirmation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ function view(language: string, overrides: Partial<ReceiptView> = {}): ReceiptVi
};
}

type Result = { success: boolean; disposition: 'executed' | 'failed'; mutationState?: 'confirmed' | 'uncertain' };
type Result = {
success: boolean;
disposition: 'executed' | 'failed';
mutationState?: 'confirmed' | 'uncertain' | 'not_applied';
alreadyExists?: ToolEvidence['alreadyExists'];
};

function run(
...calls: { name: string; input: { [key: string]: unknown }; result: Result; data?: ToolEvidence['data'] }[]
Expand All @@ -31,7 +36,13 @@ function run(
const evidence: ToolEvidence[] = [];
for (const call of calls) {
ledger.record(call.name, call.input, call.result);
evidence.push({ name: call.name, input: call.input, success: call.result.success, data: call.data });
evidence.push({
name: call.name,
input: call.input,
success: call.result.success,
data: call.data,
alreadyExists: call.result.alreadyExists,
});
}
return { ledger, evidence };
}
Expand Down Expand Up @@ -127,4 +138,42 @@ describe('receipt-only confirmation', () => {
const receipt = buildReceiptConfirmation(view('en'), evidence, ledger) ?? '';
expect(receipt.match(/Synthetic twin/g)).toHaveLength(2);
});

describe('a create answered "already exists"', () => {
const saved = event('Synthetic standup', '2035-03-06', '09:00', 7);
const created = { name: 'create_event', input: { title: 'Synthetic standup' }, result: OK, data: saved };
const repeat = {
name: 'create_event',
input: { title: 'Synthetic standup' },
result: { ...OK, mutationState: 'not_applied', alreadyExists: { entity: 'event', id: 7 } } as const,
data: saved,
};

test('after the creation is the same event: one created line (en, ru)', () => {
const { ledger, evidence } = run(created, repeat);
const en = buildReceiptConfirmation(view('en'), evidence, ledger) ?? '';
expect(en.match(/Synthetic standup/g)).toHaveLength(1);
expect(en).toContain('Created: "Synthetic standup" — Tuesday, March 6, 09:00');
const ru = buildReceiptConfirmation(view('ru'), evidence, ledger) ?? '';
expect(ru.match(/Synthetic standup/g)).toHaveLength(1);
expect(ru).toContain('Создано: «Synthetic standup» — вторник, 6 марта, 09:00');
});

test('alone is told as already in the calendar, not as created by this run (en, ru)', () => {
const { ledger, evidence } = run(repeat);
const en = buildReceiptConfirmation(view('en'), evidence, ledger) ?? '';
expect(en).toContain('Already in the calendar: "Synthetic standup" — Tuesday, March 6, 09:00');
expect(en).not.toContain('Created');
const ru = buildReceiptConfirmation(view('ru'), evidence, ledger) ?? '';
expect(ru).toContain('Уже есть в календаре: «Synthetic standup» — вторник, 6 марта, 09:00');
expect(ru).not.toContain('Создано');
});

test('in a group names no event', () => {
const { ledger, evidence } = run(repeat);
const receipt = buildReceiptConfirmation(view('en', { hideTargets: true }), evidence, ledger) ?? '';
expect(receipt).toContain('Already in the calendar: event');
expect(receipt).not.toContain('Synthetic standup');
});
});
});
Loading
Loading