diff --git a/docs/plans/2026-10-31-secretary-invitation-incident.md b/docs/plans/2026-10-31-secretary-invitation-incident.md index e7aaab21..dd85541a 100644 --- a/docs/plans/2026-10-31-secretary-invitation-incident.md +++ b/docs/plans/2026-10-31-secretary-invitation-incident.md @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 82b39787..3d3c9759 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "hypercalendarbot" -version = "0.3.6" +version = "0.3.7" requires-python = ">=3.12" dependencies = [ "pyrofork>=2.3", diff --git a/src/config/constants/messages/en/workflow.ts b/src/config/constants/messages/en/workflow.ts index 666aa250..4122b081 100644 --- a/src/config/constants/messages/en/workflow.ts +++ b/src/config/constants/messages/en/workflow.ts @@ -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', @@ -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', diff --git a/src/config/constants/messages/ru/workflow.ts b/src/config/constants/messages/ru/workflow.ts index 60c67653..5bae4bac 100644 --- a/src/config/constants/messages/ru/workflow.ts +++ b/src/config/constants/messages/ru/workflow.ts @@ -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: 'весь день', @@ -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: 'Создано', diff --git a/src/services/ai/agent/receipt-confirmation.ts b/src/services/ai/agent/receipt-confirmation.ts index 63b44221..ff77d1b2 100644 --- a/src/services/ai/agent/receipt-confirmation.ts +++ b/src/services/ai/agent/receipt-confirmation.ts @@ -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'); } diff --git a/src/services/ai/agent/tool-round.ts b/src/services/ai/agent/tool-round.ts index d0403b83..86e13bc6 100644 --- a/src/services/ai/agent/tool-round.ts +++ b/src/services/ai/agent/tool-round.ts @@ -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, }); } diff --git a/src/services/ai/response-grounding.ts b/src/services/ai/response-grounding.ts index c169b7b9..9f298ef1 100644 --- a/src/services/ai/response-grounding.ts +++ b/src/services/ai/response-grounding.ts @@ -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 = new Set([ @@ -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 { diff --git a/src/services/ai/write-outcomes.ts b/src/services/ai/write-outcomes.ts index 6a91eb4b..e47be653 100644 --- a/src/services/ai/write-outcomes.ts +++ b/src/services/ai/write-outcomes.ts @@ -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), @@ -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; } /** diff --git a/src/services/ai/write-receipt.ts b/src/services/ai/write-receipt.ts index 4b72a488..2c515809 100644 --- a/src/services/ai/write-receipt.ts +++ b/src/services/ai/write-receipt.ts @@ -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. */ @@ -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; @@ -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, @@ -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); diff --git a/test/services/ai/receipt-confirmation.test.ts b/test/services/ai/receipt-confirmation.test.ts index 58b7725b..cc73e709 100644 --- a/test/services/ai/receipt-confirmation.test.ts +++ b/test/services/ai/receipt-confirmation.test.ts @@ -22,7 +22,12 @@ function view(language: string, overrides: Partial = {}): 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'] }[] @@ -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 }; } @@ -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'); + }); + }); }); diff --git a/test/services/ai/write-receipt-existing-event.test.ts b/test/services/ai/write-receipt-existing-event.test.ts new file mode 100644 index 00000000..3b34c1c2 --- /dev/null +++ b/test/services/ai/write-receipt-existing-event.test.ts @@ -0,0 +1,165 @@ +/** + * The write receipt reads create_event's idempotent "already exists" result as the same event, not as a + * second creation and never as a failure (#929, #520). Built on the real create_event handler and the + * real WriteOutcomes ledger with synthetic data: the shape of the repeat is the handler's, not a fixture. + */ +import { beforeEach, describe, expect, test } from 'bun:test'; +import { _resetToolThrottleForTest, executeTool, WRITE_TOOLS } from '../../../src/services/ai/tool-executor.ts'; +import type { AgentContext } from '../../../src/services/ai/types.ts'; +import { WriteOutcomes } from '../../../src/services/ai/write-outcomes.ts'; +import { receiptView } from '../../../src/services/ai/write-receipt.ts'; +import { createEventToolFixture } from './tool-handlers/events-fixtures.ts'; + +const STANDUP = { title: 'Synthetic Standup', start_at: '2030-03-05T10:00:00Z', end_at: '2030-03-05T10:30:00Z' }; +const LUNCH = { title: 'Synthetic Lunch', start_at: '2030-03-06T12:00:00Z', end_at: '2030-03-06T13:00:00Z' }; +const rejected = { success: false, disposition: 'failed', mutationState: 'not_applied', error: 'bad end_at' } as const; +const unknown = { success: false, disposition: 'failed', mutationState: 'uncertain', error: 'timeout' } as const; + +const inLanguage = (ctx: AgentContext, language: 'en' | 'ru'): AgentContext => ({ + ...ctx, + user: { ...ctx.user, language }, +}); + +describe.each([ + [ + 'en', + { created: 'Created', notCreated: 'Not created', existing: 'Already in the calendar', duplicate: 'duplicate' }, + ], + ['ru', { created: 'Создано', notCreated: 'Не создано', existing: 'Уже есть в календаре', duplicate: 'дубль' }], +] as const)('create_event repeat in the receipt (%s)', (language, words) => { + let ctx: AgentContext; + let ledger: WriteOutcomes; + let otherRun: AgentContext; + + beforeEach(() => { + _resetToolThrottleForTest(); + ctx = inLanguage(createEventToolFixture().ctx, language); + otherRun = { ...ctx, createdEventIds: undefined }; + ledger = new WriteOutcomes(WRITE_TOOLS); + }); + + /** One create_event call of the run under test: executed for real, then recorded as the agent loop does. */ + async function create(input: object): Promise { + _resetToolThrottleForTest(); + ledger.record('create_event', input, await executeTool(ctx, 'create_event', input), false, 'UTC'); + } + + /** Another run of the chat saves the event: it is in the calendar, but this run's ledger never saw it. */ + async function saveInAnotherRun(input: object): Promise { + _resetToolThrottleForTest(); + await executeTool(otherRun, 'create_event', input); + } + + const lines = (): string[] => ledger.summary(receiptView(ctx))?.split('\n') ?? []; + + test('a creation and its repeat read as one created event, with nothing to guard', async () => { + await create(STANDUP); + await create(STANDUP); + + expect(lines()).toHaveLength(1); + expect(lines()[0]).toStartWith(`${words.created}: `); + expect(lines()[0]).toContain('Synthetic Standup'); + expect(ledger.finalNotice(receiptView(ctx))).toBeNull(); + }); + + test('a repeat spelled differently is the same event and still one line', async () => { + await create(STANDUP); + await create({ ...STANDUP, title: ' synthetic STANDUP ' }); + await create(STANDUP); + + expect(lines()).toHaveLength(1); + expect(ledger.finalNotice(receiptView(ctx))).toBeNull(); + }); + + test('a refused first attempt followed by the repeat result is no failure', async () => { + await saveInAnotherRun(STANDUP); // another run saved it; this run only sees the repeat + ledger.record('create_event', STANDUP, rejected, false, 'UTC'); + await create(STANDUP); + + expect(ledger.finalNotice(receiptView(ctx))).toBeNull(); + expect(lines()).toHaveLength(1); + expect(lines()[0]).toStartWith(`${words.existing}: `); + expect(lines().join('\n')).not.toContain(words.notCreated); + }); + + test('an earlier try of unknown result keeps its duplicate warning next to the repeat result', async () => { + await saveInAnotherRun(STANDUP); + // A deliberate second copy this run never saw the result of: finding the first row cannot settle it. + await saveInAnotherRun({ ...STANDUP, allow_duplicate: true }); + ledger.record('create_event', { ...STANDUP, allow_duplicate: true }, unknown, false, 'UTC'); + await create(STANDUP); + + const notice = ledger.finalNotice(receiptView(ctx)) ?? ''; + expect(notice).toStartWith(`${words.existing}: `); + expect(notice).toContain(words.duplicate); + }); + + test('a refused try with other details is settled by the repeat of the original request', async () => { + await create(STANDUP); + await create({ ...STANDUP, end_at: '2030-03-05T11:00:00Z' }); // same title and day, other end: refused + expect(ledger.finalNotice(receiptView(ctx))).toContain(words.notCreated); + await create(STANDUP); + + expect(ledger.finalNotice(receiptView(ctx))).toBeNull(); + expect(lines()).toHaveLength(1); + expect(lines()[0]).toStartWith(`${words.created}: `); + }); + + test('a throttled repeat of a request an earlier repeat answered is not a skipped create of its own', async () => { + const saved = { ...STANDUP, description: 'saved description' }; + await saveInAnotherRun(saved); + await create(STANDUP); // answered "already exists" with the saved event, which has a description + await create({ ...saved, force: true }); // the same event again, asking for the saved description + const again = { ...saved, force: 'true' }; // the same call spelled differently: throttled after normalization + const throttled = await executeTool(ctx, 'create_event', again); + expect(throttled.disposition).toBe('skipped'); + ledger.record('create_event', again, throttled, false, 'UTC'); + + expect(ledger.finalNotice(receiptView(ctx))).toBeNull(); + expect(lines()).toHaveLength(1); + expect(lines()[0]).toStartWith(`${words.existing}: `); + }); + + test('a repeat of an event this run did not create is told as already there, once', async () => { + await saveInAnotherRun(STANDUP); + await create(STANDUP); + await create(STANDUP); + + expect(lines()).toHaveLength(1); + expect(lines()[0]).toStartWith(`${words.existing}: `); + expect(lines()[0]).toContain('Synthetic Standup'); + expect(lines()[0]).not.toStartWith(words.created); + }); + + test('a different event of the same run stays a separate line', async () => { + await create(STANDUP); + await create(LUNCH); + await create(STANDUP); + await create(LUNCH); + + expect(lines()).toHaveLength(2); + expect(lines().every((line) => line.startsWith(`${words.created}: `))).toBe(true); + expect(lines()[0]).toContain('Synthetic Standup'); + expect(lines()[1]).toContain('Synthetic Lunch'); + expect(ledger.finalNotice(receiptView(ctx))).toBeNull(); + }); + + test('a deliberate second copy (allow_duplicate) is a second created event', async () => { + await create(STANDUP); + await create({ ...STANDUP, allow_duplicate: true }); + + expect(lines()).toHaveLength(2); + expect(lines().every((line) => line.startsWith(`${words.created}: `))).toBe(true); + }); + + test('a group chat still names no event in the repeat line', async () => { + await saveInAnotherRun(STANDUP); + await create(STANDUP); + const hidden = { ...receiptView(ctx), hideTargets: true }; + + const receipt = ledger.summary(hidden) ?? ''; + expect(receipt).toStartWith(`${words.existing}: `); + expect(receipt).not.toContain('Synthetic'); + expect(receipt.split('\n')).toHaveLength(1); + }); +}); diff --git a/uv.lock b/uv.lock index 5895ba5d..755e9fc9 100644 --- a/uv.lock +++ b/uv.lock @@ -335,7 +335,7 @@ wheels = [ [[package]] name = "hypercalendarbot" -version = "0.3.6" +version = "0.3.7" source = { virtual = "." } dependencies = [ { name = "numpy" },