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
2 changes: 2 additions & 0 deletions apps/server/src/modules/ai-dm/ai-dm.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ProposalRecordsModule } from '../proposals/proposal-records.module';
import { AiPricingModule } from '../ai-pricing/ai-pricing.module';
import { SessionZeroModule } from '../session-zero/session-zero.module';
import { StorylinesModule } from '../storylines/storylines.module';
import { TimelineModule } from '../timeline/timeline.module';
import { AiDmService } from './ai-dm.service';
import { AiDmController } from './ai-dm.controller';
import { CoDmService } from './co-dm.service';
Expand All @@ -30,6 +31,7 @@ import { AI_DM_PROVIDER, NoopAiDmProvider } from './ai-dm.provider';
ProposalRecordsModule,
SessionZeroModule,
StorylinesModule,
TimelineModule,
AiPricingModule,
],
controllers: [AiDmController, CoDmController],
Expand Down
67 changes: 62 additions & 5 deletions apps/server/src/modules/ai-dm/co-dm.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
StoryBeatProposalCreate,
StoryBeatUpdate,
StoryArcUpdate,
TimelineEventCreate,
TimelineEventUpdate,
ruleSystemAdapter,
} from '@campfire/schema';
import type { AiExternalContentPolicy, AiGenerationProvenance, CoDmDraftRequest, CoDmDraftResult, CoDmDraftTarget, HomebrewMechanicsProfile, NarrationLanguage, Proposal, Role, RuleSystemAdapter } from '@campfire/schema';
Expand All @@ -42,6 +44,7 @@ import { isWithheldFinishReason, describeWithheldTurn } from '../ai-driver/drive
import { AiProviderConfigService } from '../ai-provider-config/ai-provider-config.service';
import { provenanceEndpointBaseUrl, resolveAiProvenanceEgress } from '../../common/ai-provenance-endpoint';
import { StorylinesService } from '../storylines/storylines.service';
import { TimelineService, toEventDomain } from '../timeline/timeline.service';

type CoDmDraftRequestInput = z.infer<typeof CoDmDraftRequest>;

Expand All @@ -62,10 +65,11 @@ const TARGET_ENTITY_TYPE: Record<CoDmDraftTarget, ProposableEntityType> = {
recap: 'session', // a session recap is filed as a session
encounter: 'encounter',
map: 'map',
timeline_event: 'timeline_event',
};

/** Targets that support drafting N items at once; the rest ignore `count`. */
const MULTI_TARGETS = new Set<CoDmDraftTarget>(['npc', 'location', 'beat', 'quest', 'faction']);
const MULTI_TARGETS = new Set<CoDmDraftTarget>(['npc', 'location', 'beat', 'quest', 'faction', 'timeline_event']);

/**
* Co-DM authoring (issue #313) — the AI drafts content for the DM's approval queue.
Expand Down Expand Up @@ -103,6 +107,7 @@ export class CoDmService {
@Inject(AI_DM_PROVIDER) private readonly provider: AiDmProvider,
private readonly providerConfig: AiProviderConfigService,
private readonly storylines: StorylinesService,
private readonly timelineService: TimelineService,
) {}

/** 403 unless the server-wide experimental flag is on — the same choke point as the AI DM seat. */
Expand Down Expand Up @@ -133,8 +138,8 @@ export class CoDmService {
if (input.target === 'arc' && !editing) {
throw new BadRequestException('Story arcs can be rewritten with entityId; creating arcs with co-DM drafting is not supported');
}
if (editing && input.target !== 'arc' && input.target !== 'beat') {
throw new BadRequestException('entityId is supported only when rewriting an existing story arc or beat');
if (editing && input.target !== 'arc' && input.target !== 'beat' && input.target !== 'timeline_event') {
throw new BadRequestException('entityId is supported only when rewriting an existing story arc, beat, or timeline event');
Comment on lines +141 to +142
}
if (editing && (input.arcId != null || input.count != null)) {
throw new BadRequestException('arcId and count are not used when rewriting an existing storyline entity');
Expand All @@ -153,7 +158,9 @@ export class CoDmService {
);
}
const edit = editing
? await this.storylines.getRewriteContext(campaignId, input.target as 'arc' | 'beat', input.entityId!)
? (input.target === 'timeline_event'
? await this.getTimelineRewriteContext(campaignId, input.entityId!)
: await this.storylines.getRewriteContext(campaignId, input.target as 'arc' | 'beat', input.entityId!))
: null;
const providerPrompt = edit
? JSON.stringify({ rewriteInstructions: input.prompt, currentStoryline: edit.providerContext })
Expand Down Expand Up @@ -573,7 +580,8 @@ export class CoDmService {
case 'arc':
case 'beat':
case 'quest':
case 'faction': {
case 'faction':
case 'timeline_event': {
if (parsed === null) {
throw new UnprocessableEntityException(
`The AI did not return a JSON ${target} draft. Configure a real provider (the default no-op scaffold cannot author content) or retry.`,
Expand Down Expand Up @@ -649,6 +657,27 @@ export class CoDmService {
...(typeof raw.standing === 'string' ? { standing: raw.standing } : {}),
...(typeof raw.dmSecret === 'string' ? { dmSecret: raw.dmSecret } : {}),
}) as Record<string, unknown>;
case 'timeline_event':
if (opts?.editing) {
return TimelineEventUpdate.parse({
...(typeof raw.title === 'string' ? { title: raw.title } : {}),
...(typeof raw.inWorldDate === 'string' ? { inWorldDate: raw.inWorldDate } : {}),
...(typeof raw.era === 'string' ? { era: raw.era } : {}),
...(typeof raw.sortIndex === 'number' || typeof raw.sortIndex === 'string' ? { sortIndex: Number(raw.sortIndex) } : {}),
...(typeof raw.body === 'string' ? { body: raw.body } : {}),
...(typeof raw.dmSecret === 'string' ? { dmSecret: raw.dmSecret } : {}),
...(typeof raw.hidden === 'boolean' ? { hidden: raw.hidden } : {}),
}) as Record<string, unknown>;
}
return TimelineEventCreate.parse({
title: typeof raw.title === 'string' && raw.title.trim() ? raw.title : (typeof raw.name === 'string' && raw.name.trim() ? raw.name : 'Untitled event'),
...(typeof raw.inWorldDate === 'string' ? { inWorldDate: raw.inWorldDate } : {}),
...(typeof raw.era === 'string' ? { era: raw.era } : {}),
...(typeof raw.sortIndex === 'number' || typeof raw.sortIndex === 'string' ? { sortIndex: Number(raw.sortIndex) } : {}),
...(typeof raw.body === 'string' ? { body: raw.body } : {}),
...(typeof raw.dmSecret === 'string' ? { dmSecret: raw.dmSecret } : {}),
...(typeof raw.hidden === 'boolean' ? { hidden: raw.hidden } : {}),
}) as Record<string, unknown>;
case 'recap':
return SessionCreate.parse(raw) as Record<string, unknown>;
case 'encounter': {
Expand Down Expand Up @@ -683,6 +712,32 @@ export class CoDmService {
);
}
}

private async getTimelineRewriteContext(campaignId: number, eventId: number) {
const row = await this.timelineService.getEventRowOrThrow(eventId);
if (row.campaignId !== campaignId) {
throw new BadRequestException(`Timeline event ${eventId} does not belong to this campaign`);
}
const domain = toEventDomain(row);
const providerContext = {
target: 'timeline_event' as const,
event: {
id: domain.id,
title: domain.title,
inWorldDate: domain.inWorldDate,
era: domain.era,
sortIndex: domain.sortIndex,
body: domain.body,
dmSecret: domain.dmSecret,
},
};
const contextHash = crypto.createHash('sha256').update(JSON.stringify(providerContext)).digest('hex');
return {
providerContext,
contextHash,
baseSnapshot: { ...domain },
};
}
}

/** Per-target JSON hint the model is asked to fill (informational; the server re-validates). */
Expand All @@ -696,6 +751,8 @@ const DRAFT_JSON_SHAPE = (adapter: RuleSystemAdapter): Record<CoDmDraftTarget, s
'{"title": string (required), "body"?: string (markdown), "reward"?: string, "status"?: "available"|"active"|"completed"|"failed", "dmSecret"?: string}',
faction:
'{"name": string (required), "body"?: string (markdown), "kind"?: string, "goals"?: string, "standing"?: "hostile"|"unfriendly"|"neutral"|"friendly"|"allied", "dmSecret"?: string}',
timeline_event:
'{"title": string (required), "inWorldDate"?: string, "era"?: string, "sortIndex"?: number, "body"?: string (markdown), "dmSecret"?: string}',
recap: '{"title"?: string, "recap": string (markdown summary of the session)}',
encounter: adapter.supportsEncounterDifficulty
? '{"difficulty": "trivial"|"easy"|"medium"|"hard"|"deadly", "count"?: number, "shape"?: string}'
Expand Down
8 changes: 4 additions & 4 deletions apps/server/src/modules/mcp/mcp-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5649,20 +5649,20 @@ export class McpToolsService {
'budget; the proposer is recorded as the AI seat + model.',
{
campaignId: CampaignIdArg,
target: CoDmDraftTarget.describe('What to draft or rewrite: npc | location | arc | beat | quest | faction | recap | encounter | map'),
target: CoDmDraftTarget.describe('What to draft or rewrite: npc | location | arc | beat | quest | faction | timeline_event | recap | encounter | map'),
prompt: z.string().min(1).max(20_000).describe('Free-text brief, e.g. "a shady fence tied to the thieves guild"'),
count: z
.number()
.int()
.min(1)
.max(10)
.optional()
.describe('How many to draft (npc/location/beat/quest/faction only; ignored for recap/encounter/map)'),
.describe('How many to draft (npc/location/beat/quest/faction/timeline_event only; ignored for recap/encounter/map)'),
narrationLanguage: NarrationLanguage.optional().describe('Per-run override of the campaign narration language (#635)'),
arcId: Id.optional().describe('When target is beat, pin drafted beat(s) to this story arc id'),
entityId: Id.optional().describe('When target is arc or beat, rewrite this existing entity and file an update proposal'),
entityId: Id.optional().describe('When target is arc, beat, or timeline_event, rewrite this existing entity and file an update proposal'),
includeCampaignSecrets: z.boolean().default(false).describe(
'Storyline rewrites only: explicitly allow DM-only arc/beat context to be sent when the configured provider is external',
'Storyline/timeline rewrites only: explicitly allow DM-only arc/beat/timeline context to be sent when the configured provider is external',
),
},
async ({ campaignId, target, prompt, count, narrationLanguage, arcId, entityId, includeCampaignSecrets }) => {
Expand Down
30 changes: 27 additions & 3 deletions apps/server/src/modules/proposals/proposal-records.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { and, desc, eq, isNull } from 'drizzle-orm';
import { AiGenerationProvenance } from '@campfire/schema';
import type { EntityType, Proposal, ProposalAction, Role } from '@campfire/schema';
import { DB, type DrizzleDb } from '../../db/db.module';
import { proposals, quests, npcs, locations, sessions, characters, factions, storyArcs, storyBeats, auditLog, ruleEntries } from '../../db/schema';
import { proposals, quests, npcs, locations, sessions, characters, factions, storyArcs, storyBeats, auditLog, ruleEntries, timelineEvents } from '../../db/schema';
import { nowIso } from '../../common/time';
import { fromJsonText, toJsonText } from '../../common/json';
import { notDeleted } from '../../common/soft-delete';
Expand All @@ -20,6 +20,7 @@ import { toDomain as npcToDomain } from '../npcs/npcs.service';
import { toDomain as locationToDomain } from '../locations/locations.service';
import { toDomain as sessionToDomain } from '../sessions/sessions.service';
import { toDomain as characterToDomain } from '../characters/characters.service';
import { toEventDomain as timelineEventToDomain } from '../timeline/timeline.service';
import { projectProposal, projectProposals } from './proposal-projection';
import { hashProposalSnapshot } from './proposal-snapshot';

Expand All @@ -32,7 +33,7 @@ import { hashProposalSnapshot } from './proposal-snapshot';
// standalone rather than derived from EntityType. Factions (issue #1056) are also
// proposable for Co-DM drafting and are create-only in v1 (direct faction writes remain
// DM-gated; the proposal queue is the co-DM intermediary).
export type ProposableEntityType = Exclude<EntityType, 'campaign'> | 'map' | 'story_arc' | 'story_beat' | 'rule_entry';
export type ProposableEntityType = Exclude<EntityType, 'campaign'> | 'map' | 'story_arc' | 'story_beat' | 'timeline_event' | 'rule_entry';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add timeline events to the shared proposal contract

When a timeline draft is returned, toDomain() casts timeline_event to Proposal['entityType'], but the exported ProposalEntityType in packages/schema/src/index.ts:8718-8721 still excludes it. Consequently these REST/MCP responses violate the shared Proposal schema, and schema-validating clients will reject every timeline proposal even though the server accepts it; add timeline_event to the shared proposal entity contract instead of defining it only in the server union.

AGENTS.md reference: AGENTS.md:L34-L35

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add timeline events to the shared proposal contract

When a timeline draft is returned, toDomain() casts timeline_event to Proposal['entityType'], but the exported ProposalEntityType in packages/schema/src/index.ts:8718-8721 still excludes it. Consequently these REST/MCP responses violate the shared Proposal schema, and schema-validating clients will reject every timeline proposal even though the server accepts it; add timeline_event to the shared proposal entity contract instead of defining it only in the server union.

AGENTS.md reference: AGENTS.md:L34-L35

Useful? React with 👍 / 👎.

type ProposalTx = Parameters<Parameters<DrizzleDb['transaction']>[0]>[0];
type ProposalDb = DrizzleDb | ProposalTx;
type ProposalAttribution = {
Expand All @@ -42,7 +43,7 @@ type ProposalAttribution = {
generationProvenance?: AiGenerationProvenance | null;
};

const PROPOSABLE_ENTITY_TYPES: ProposableEntityType[] = ['quest', 'npc', 'location', 'session', 'character', 'encounter', 'map', 'faction', 'story_arc', 'story_beat', 'rule_entry'];
const PROPOSABLE_ENTITY_TYPES: ProposableEntityType[] = ['quest', 'npc', 'location', 'session', 'character', 'encounter', 'map', 'faction', 'story_arc', 'story_beat', 'timeline_event', 'rule_entry'];

export function isProposableEntityType(value: string): value is ProposableEntityType {
return (PROPOSABLE_ENTITY_TYPES as string[]).includes(value);
Expand Down Expand Up @@ -447,6 +448,17 @@ export class ProposalRecordsService {
if (!row) throw new NotFoundException(`Homebrew rule entry ${entityId} not found`);
return { id: row.id, slug: row.slug, name: row.name, type: row.type, summary: row.summary, body: row.body, dataJson: row.dataJson, rightsStatus: row.rightsStatus, license: row.license, attribution: row.attribution, author: row.author, sourceUrl: row.sourceUrl, iconSlug: row.iconSlug, updatedAt: row.updatedAt, archivedAt: row.archivedAt };
}
case 'timeline_event': {
const [row] = await this.db
.select()
.from(timelineEvents)
.where(and(eq(timelineEvents.id, entityId), eq(timelineEvents.campaignId, campaignId), notDeleted(timelineEvents.deletedAt)))
.limit(1);
if (!row) throw new NotFoundException(`Timeline event ${entityId} not found`);
const domain = timelineEventToDomain(row);
if (!isVisibleTo(domain, role)) throw new NotFoundException(`Timeline event ${entityId} not found`);
return { ...domain };
}
}
}

Expand Down Expand Up @@ -597,6 +609,18 @@ export class ProposalRecordsService {
archivedAt: row.archivedAt,
};
}
case 'timeline_event': {
const row = db
.select()
.from(timelineEvents)
.where(and(eq(timelineEvents.id, entityId), eq(timelineEvents.campaignId, campaignId), notDeleted(timelineEvents.deletedAt)))
.limit(1)
.get();
if (!row) throw new NotFoundException(`Timeline event ${entityId} not found`);
const domain = timelineEventToDomain(row);
if (!isVisibleTo(domain, role)) throw new NotFoundException(`Timeline event ${entityId} not found`);
return { ...domain };
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/modules/proposals/proposals.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { MapsModule } from '../maps/maps.module';
import { FactionsModule } from '../factions/factions.module';
import { StorylinesModule } from '../storylines/storylines.module';
import { RulesModule } from '../rules/rules.module';
import { TimelineModule } from '../timeline/timeline.module';
import { ProposalRecordsModule } from './proposal-records.module';
import { ProposalsService } from './proposals.service';
import { CampaignProposalsController, ProposalsController } from './proposals.controller';
Expand All @@ -32,6 +33,7 @@ import { CampaignProposalsController, ProposalsController } from './proposals.co
FactionsModule,
StorylinesModule,
RulesModule,
TimelineModule,
],
controllers: [CampaignProposalsController, ProposalsController],
providers: [ProposalsService],
Expand Down
31 changes: 31 additions & 0 deletions apps/server/src/modules/proposals/proposals.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {
ProposalResolve,
HomebrewRuleEntryInput,
HomebrewRuleEntryUpdate,
TimelineEventCreate,
TimelineEventUpdate,
} from '@campfire/schema';
import type { Proposal, ProposalAction, Role } from '@campfire/schema';
import { fromJsonText } from '../../common/json';
Expand All @@ -38,6 +40,7 @@ import { SessionsService } from '../sessions/sessions.service';
import { CharactersService } from '../characters/characters.service';
import { EncountersService } from '../encounters/encounters.service';
import { MapsService } from '../maps/maps.service';
import { TimelineService } from '../timeline/timeline.service';
import { FactionsService } from '../factions/factions.service';
import {
StorylineRewriteContextChangedError,
Expand Down Expand Up @@ -109,6 +112,7 @@ const CREATE_SCHEMAS: Record<ProposableEntityType, z.ZodTypeAny> = {
encounter: EncounterGenerate.strict(),
map: GenerateMapParams.strict(),
rule_entry: HomebrewRuleEntryInput,
timeline_event: TimelineEventCreate.strict(),
};
const UPDATE_SCHEMAS: Record<ProposableEntityType, z.ZodTypeAny> = {
quest: QuestUpdate.strict(),
Expand All @@ -122,6 +126,7 @@ const UPDATE_SCHEMAS: Record<ProposableEntityType, z.ZodTypeAny> = {
encounter: EncounterGenerate.strict(),
map: GenerateMapParams.strict(),
rule_entry: HomebrewRuleEntryUpdate.strict(),
timeline_event: TimelineEventUpdate.strict(),
};

@Injectable()
Expand All @@ -139,6 +144,7 @@ export class ProposalsService {
private readonly maps: MapsService,
private readonly factions: FactionsService,
@Inject(StorylinesService) private readonly storylines: ProposalStorylinesService,
private readonly timeline: TimelineService,
private readonly rules?: RulesService,
) {}

Expand Down Expand Up @@ -318,6 +324,31 @@ export class ProposalsService {
update: (id: number, payload: Record<string, unknown>, user: RequestUser) => this.rules!.updateCampaignHomebrewFromProposal(id, payload, user),
remove: () => Promise.reject(new BadRequestException('Homebrew archive proposals are not supported yet')),
};
case 'timeline_event':
return {
create: (campaignId: number, payload: Record<string, unknown>, user: RequestUser, role: Role) =>
this.timeline.createEvent(
campaignId,
payload as Parameters<TimelineService['createEvent']>[1],
user,
role,
),
update: (
id: number,
payload: Record<string, unknown>,
user: RequestUser,
role: Role,
opts?: Parameters<TimelineService['updateEvent']>[4],
) =>
this.timeline.updateEvent(
id,
payload as Parameters<TimelineService['updateEvent']>[1],
user,
role,
opts,
Comment on lines +343 to +348

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the timeline update concurrency token

When another DM edits the event after approve() performs its freshness read but before the proposal write runs, the generic approval branch invokes this adapter without opts, so TimelineService.updateEvent() receives no expectedUpdatedAt and unconditionally overwrites the intervening edit. Route timeline-event updates through the compare-and-set path using existing.baseUpdatedAt, as storyline updates already do, so this race returns a conflict rather than losing user changes.

Useful? React with 👍 / 👎.

Comment on lines +343 to +348

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the timeline update concurrency token

When another DM edits the event after approve() performs its freshness read but before the proposal write runs, the generic approval branch invokes this adapter without opts, so TimelineService.updateEvent() receives no expectedUpdatedAt and unconditionally overwrites the intervening edit. Route timeline-event updates through the compare-and-set path using existing.baseUpdatedAt, as storyline updates already do, so this race returns a conflict rather than losing user changes.

Useful? React with 👍 / 👎.

),
remove: (id: number, user: RequestUser, role: Role) => this.timeline.removeEvent(id, user, role),
};
}
}

Expand Down
Loading
Loading