diff --git a/.tours/01-primary-user-flow.tour b/.tours/01-primary-user-flow.tour
index 548d50b..df4347d 100644
--- a/.tours/01-primary-user-flow.tour
+++ b/.tours/01-primary-user-flow.tour
@@ -25,12 +25,12 @@
},
{
"file": "convex/nodeslideAgent.ts",
- "line": 1704,
+ "line": 1712,
"description": "**The trust boundary.**\n\nAbove this line, values came from a browser and are suspect. Below it, everything is typed and checked.\n\nConvex validates every argument against this `args` object *before* the handler body runs, and rejects any undeclared field. Read the comment on `durableJob` below — declaring that one field was the difference between working durable jobs and every job dying at 35% progress."
},
{
"file": "convex/nodeslideAgent.ts",
- "line": 1760,
+ "line": 1768,
"description": "**Why the cheap checks run first.**\n\nBoth checks below are pure string comparisons over arguments already in hand: no database read, no quota, no provider call. A caller that cannot name the job whose deck it claims to produce is refused *for free*.\n\nMoving either check later would turn a free refusal into one that arrives after a paid completion. This ordering is the rule the whole file obeys."
},
{
@@ -40,22 +40,22 @@
},
{
"file": "convex/nodeslideAgent.ts",
- "line": 1882,
+ "line": 1890,
"description": "**The model is asked for intent, not geometry.**\n\nSlide count, allowed element kinds, and required provenance fields are enforced by this JSON schema — not hoped for in prose. `minItems`/`maxItems` come from the count the user actually asked for.\n\nA model that returns coordinates cannot be checked. A model that returns a typed plan can, and deterministic code turns the plan into positioned elements."
},
{
"file": "convex/nodeslideAgent.ts",
- "line": 2013,
+ "line": 2021,
"description": "**A ceiling enforced by code, not by prompt.**\n\nThe dispatch reserves budget against a ledger row keyed by the run id, calls the provider with a hard timeout, and reconciles the spend afterwards.\n\nNote the comment on `timeoutMs`: the create path carries its own wire ceiling because full-deck generation legitimately takes minutes, and the 30-second edit-path default would guarantee a timeout and a silently degraded deck."
},
{
"file": "convex/nodeslideAgent.ts",
- "line": 2058,
+ "line": 2066,
"description": "**Fail closed on an ambiguous charge.**\n\nIf the paid call ended without a reconcilable billing receipt, creation stops here. No fallback deck is produced under an unresolved charge.\n\nA provider *failure* is different and does fall back to the deterministic generator. Failure and ambiguity are not the same thing, and this repository refuses to treat them alike."
},
{
"file": "convex/nodeslideAgent.ts",
- "line": 2150,
+ "line": 2158,
"description": "**The only write.**\n\nEverything above was computation. This one mutation persists the deck, its slides, its elements and their version clocks in a single transaction.\n\nFrom here on, every change to this deck goes through the version check in tour 2."
},
{
diff --git a/.tours/02-agent-execution.tour b/.tours/02-agent-execution.tour
index 2fe243c..987acda 100644
--- a/.tours/02-agent-execution.tour
+++ b/.tours/02-agent-execution.tour
@@ -30,7 +30,7 @@
},
{
"file": "convex/nodeslide.ts",
- "line": 1180,
+ "line": 1184,
"description": "**Where every change enters, whoever made it.**\n\n`applyPatch` (direct), `proposePatch` (review first) and `proposePropagation` (apply an accepted change to matching slides) all normalise into the same shape and all end up at the same check."
},
{
@@ -45,7 +45,7 @@
},
{
"file": "convex/nodeslide.ts",
- "line": 1224,
+ "line": 1228,
"description": "**Acceptance is one transaction.**\n\nThe commit, the version bump and the decision record either all land or all roll back. There is no window in which a deck has advanced but its receipt has not."
},
{
diff --git a/.tours/03-debug-and-recovery.tour b/.tours/03-debug-and-recovery.tour
index e31f3d7..e5c3917 100644
--- a/.tours/03-debug-and-recovery.tour
+++ b/.tours/03-debug-and-recovery.tour
@@ -20,7 +20,7 @@
},
{
"file": "convex/nodeslide.ts",
- "line": 3348,
+ "line": 3354,
"description": "**Failure 2: the worker died mid-run.**\n\nAn agent run holds a lease. This mutation finds runs whose `leaseExpiresAt` has passed and fails them honestly, so a crashed action stops spinning in the UI instead of hanging forever.\n\n'Honestly' is the operative word: it marks them failed with a reason rather than quietly deleting them."
},
{
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c4181e..bb5df73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,10 @@
### Agent surfaces
+- Bound edit proposal publication to the active run and attempt, so cancellation
+ that persists first prevents a new proposal. Publication links its patch and
+ trace atomically; later cancellation preserves the existing proposal and replay.
+ Both hosted and local-candidate edits retain the later stream/review checkpoint.
- Upgraded `nodeslide.create_deck` from draft creation to the same finished-deck
transaction used by the CLI.
- Added safe output-root containment, artifact size limits, public URL delivery,
diff --git a/convex/lib/nodeslideEditVerifyAction.test.ts b/convex/lib/nodeslideEditVerifyAction.test.ts
index 4febd5b..c70995c 100644
--- a/convex/lib/nodeslideEditVerifyAction.test.ts
+++ b/convex/lib/nodeslideEditVerifyAction.test.ts
@@ -69,8 +69,8 @@ function harness(current: NodeSlideWorkspace) {
const budgetReply = nodeSlideBudgetLedgerStubResponse(args);
if (budgetReply !== undefined) return budgetReply;
if ('buckets' in args) return { ok: true };
- if ('idempotencyKey' in args) return { created: true, run: { id: 'run-b4-test' } };
- if ('runId' in args) {
+ if ('idempotencyKey' in args) return { created: true, run: { id: 'run-b4-test', attempt: 1 } };
+ if ('runId' in args && 'status' in args) {
steps.push({
status: args.status as string | undefined,
message: args.message as string | undefined,
diff --git a/convex/nodeslide.ts b/convex/nodeslide.ts
index c9b7d23..949a9c5 100644
--- a/convex/nodeslide.ts
+++ b/convex/nodeslide.ts
@@ -976,7 +976,11 @@ export const cancelAgentRun = mutation({
.withIndex('by_stable_id', (query) => query.eq('id', args.runId))
.unique();
if (!row || row.deckId !== args.deckId) return null;
- if (['completed', 'failed', 'cancelled', 'awaiting_review'].includes(row.status)) {
+ if (
+ row.patchId ||
+ row.traceId ||
+ ['completed', 'failed', 'cancelled', 'awaiting_review'].includes(row.status)
+ ) {
const { _id, _creationTime, ownerDigest: _ownerDigest, ...run } = row;
return run;
}
@@ -3087,6 +3091,7 @@ export const advanceAgentRunInternal = internalMutation({
deckId: v.string(),
ownerAccessKey: v.string(),
runId: v.string(),
+ expectedAttempt: v.optional(v.number()),
status: v.union(
v.literal('researching'),
v.literal('planning'),
@@ -3120,6 +3125,7 @@ export const advanceAgentRunInternal = internalMutation({
.withIndex('by_stable_id', (query) => query.eq('id', args.runId))
.unique();
if (!row || row.deckId !== args.deckId) throw new Error('Agent run not found.');
+ if (args.expectedAttempt !== undefined && row.attempt !== args.expectedAttempt) return null;
if (row.status === 'cancelled' && args.status !== 'cancelled') return null;
const now = Date.now();
const terminal = ['completed', 'failed', 'cancelled'].includes(args.status);
@@ -3786,6 +3792,8 @@ export const createFromBriefInternal = internalMutation({
export const proposeAgentPatchInternal = internalMutation({
args: {
...internalAgentPatchArgs,
+ runId: v.string(),
+ runAttempt: v.number(),
instruction: v.string(),
planningInputDigest: v.optional(v.string()),
planningSnapshotDigest: v.optional(v.string()),
@@ -3809,6 +3817,22 @@ export const proposeAgentPatchInternal = internalMutation({
},
handler: async (ctx, args) => {
await requireOwnerAccess(ctx, args.deckId, args.ownerAccessKey);
+ const run = await ctx.db
+ .query('nodeslide_agent_runs')
+ .withIndex('by_stable_id', (query) => query.eq('id', args.runId))
+ .unique();
+ // Cancellation and publication decide against the same run in this transaction.
+ if (
+ !run ||
+ run.deckId !== args.deckId ||
+ run.ownerDigest !== `actor_${nodeslideContentDigest(args.ownerAccessKey)}` ||
+ run.attempt !== args.runAttempt ||
+ !['queued', 'researching', 'planning', 'validating'].includes(run.status) ||
+ run.patchId ||
+ run.traceId
+ ) {
+ throw new Error('Agent run is unavailable, cancelled, superseded, or already published.');
+ }
if (args.toolCalls.length > 16) throw new Error('Too many agent tool calls recorded.');
// A fallback reason without a fallback is a claim the record cannot support, and the
// absence of a reason on a fallback is the disclosure going missing at the source.
@@ -3898,6 +3922,12 @@ export const proposeAgentPatchInternal = internalMutation({
...(proposal.patch.status === 'stale' ? { completedAt: now } : {}),
};
await ctx.db.insert('nodeslide_traces', trace);
+ // Leave stream completion and the full awaiting-review checkpoint to the action.
+ await ctx.db.patch(run._id, {
+ patchId: proposal.patch.id,
+ traceId: args.traceId,
+ updatedAt: now,
+ });
if (args.shadowComparison) {
try {
assertNodeSlideShadowComparisonBounds(args.shadowComparison);
diff --git a/convex/nodeslideAgent.ts b/convex/nodeslideAgent.ts
index a1d1657..62becd1 100644
--- a/convex/nodeslideAgent.ts
+++ b/convex/nodeslideAgent.ts
@@ -591,6 +591,7 @@ export const proposeEdit = action({
webResearch: args.webResearch === true,
});
const runId = runStart.run.id as string;
+ const runAttempt = runStart.run.attempt as number;
if (!runStart.created) {
if (runStart.run.patchId) {
const current = (await ctx.runQuery(nodeslideInternal.getAgentContextInternal, {
@@ -1180,6 +1181,8 @@ export const proposeEdit = action({
const proposal = await ctx.runMutation(nodeslideInternal.proposeAgentPatchInternal, {
id: patchId,
traceId,
+ runId,
+ runAttempt,
deckId: args.deckId,
ownerAccessKey: args.ownerAccessKey,
baseDeckVersion: args.baseDeckVersion,
@@ -1293,6 +1296,7 @@ export const proposeEdit = action({
deckId: args.deckId,
ownerAccessKey: args.ownerAccessKey,
runId,
+ expectedAttempt: runAttempt,
status: 'failed',
error: message.slice(0, 600),
message: `No deck changes were applied. ${message}`.slice(0, 4000),
@@ -1392,6 +1396,7 @@ export const proposeExternalAgentEdit = action({
webResearch: false,
});
const runId = runStart.run.id as string;
+ const runAttempt = runStart.run.attempt as number;
if (!runStart.created) {
if (runStart.run.patchId) {
const current = (await ctx.runQuery(nodeslideInternal.getAgentContextInternal, {
@@ -1422,6 +1427,8 @@ export const proposeExternalAgentEdit = action({
const proposal = await ctx.runMutation(nodeslideInternal.proposeAgentPatchInternal, {
id: patchId,
traceId,
+ runId,
+ runAttempt,
deckId: args.deckId,
ownerAccessKey: args.ownerAccessKey,
baseDeckVersion: args.baseDeckVersion,
@@ -1470,6 +1477,7 @@ export const proposeExternalAgentEdit = action({
deckId: args.deckId,
ownerAccessKey: args.ownerAccessKey,
runId,
+ expectedAttempt: runAttempt,
status: 'failed',
error: agentRunErrorMessage(error).slice(0, 600),
message: `No deck changes were applied. ${agentRunErrorMessage(error)}`.slice(0, 4000),
diff --git a/convex/nodeslideAgentCancellation.test.ts b/convex/nodeslideAgentCancellation.test.ts
new file mode 100644
index 0000000..2933daa
--- /dev/null
+++ b/convex/nodeslideAgentCancellation.test.ts
@@ -0,0 +1,460 @@
+///
+
+import { convexTest } from 'convex-test';
+import { type FunctionReference, getFunctionName } from 'convex/server';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { type DeckPatch, NODESLIDE_LOCAL_BYOK_EDIT_CONSENT } from '../shared/nodeslide';
+import { api, internal } from './_generated/api';
+import type { MutationCtx } from './_generated/server';
+import { insertNodeSlideSnapshot, loadNodeSlideSnapshot } from './lib/nodeslideData';
+import { buildGoldenNodeSlide } from './lib/nodeslideSeed';
+import { proposeAgentPatchInternal } from './nodeslide';
+import { proposeEdit, proposeExternalAgentEdit } from './nodeslideAgent';
+import schema from './schema';
+
+const forbidden = vi.hoisted(() => ({ attempts: [] as string[] }));
+vi.mock('./lib/nodeslideProvider', async (importOriginal) => ({
+ ...(await importOriginal()),
+ callNodeSlideFreeJson: async () => {
+ forbidden.attempts.push('provider');
+ throw new Error('Cancellation scenarios must not call a provider.');
+ },
+}));
+
+const modules = import.meta.glob(['./**/*.ts', '!./**/*.test.ts']);
+const OWNER = 'a'.repeat(43);
+const NOW = 1_800_000_000_000;
+type Database = ReturnType;
+type Lane = 'deterministic' | 'local_candidate';
+type Args = Record;
+type ActionHandler = (ctx: unknown, args: Args) => Promise<{ patch: DeckPatch }>;
+type Run = { id: string; attempt: number };
+const handlers: Record = {
+ deterministic: (proposeEdit as unknown as { _handler: ActionHandler })._handler,
+ local_candidate: (proposeExternalAgentEdit as unknown as { _handler: ActionHandler })._handler,
+};
+const publish = (
+ proposeAgentPatchInternal as unknown as {
+ _handler: (ctx: MutationCtx, args: Args) => Promise<{ patch: DeckPatch }>;
+ }
+)._handler;
+
+afterEach(() => {
+ const attempts = [...forbidden.attempts];
+ forbidden.attempts.length = 0;
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ expect(attempts).toEqual([]);
+});
+
+function database() {
+ vi.stubEnv('NODESLIDE_AGENTIC_GLOBAL_ENABLED', 'false');
+ vi.stubGlobal('fetch', async () => {
+ forbidden.attempts.push('fetch');
+ throw new Error('Cancellation scenarios must not use the network.');
+ });
+ return convexTest(schema, modules);
+}
+
+async function state(t: Database, deckId: string) {
+ return t.run(async (ctx) => ({
+ snapshot: await loadNodeSlideSnapshot(ctx, deckId),
+ patches: await ctx.db
+ .query('nodeslide_patches')
+ .withIndex('by_deck_created', (q) => q.eq('deckId', deckId))
+ .collect(),
+ traces: await ctx.db
+ .query('nodeslide_traces')
+ .withIndex('by_deck_created', (q) => q.eq('deckId', deckId))
+ .collect(),
+ runs: await ctx.db
+ .query('nodeslide_agent_runs')
+ .withIndex('by_deck_created', (q) => q.eq('deckId', deckId))
+ .collect(),
+ }));
+}
+
+async function seed(t: Database, key: string) {
+ const built = buildGoldenNodeSlide(`cancel-${key}`, NOW);
+ const target = built.snapshot.elements.find((el) => el.kind === 'text' && !el.locked);
+ if (!target) throw new Error('Golden deck needs unlocked text.');
+ target.content = 'Before';
+ const slide = built.snapshot.slides.find((item) => item.id === target.slideId);
+ if (!slide) throw new Error('Selected text needs a slide.');
+ const deckId = built.snapshot.deck.id;
+ await t.run(async (ctx) => {
+ const projectRowId = await ctx.db.insert('projects', {
+ clientSessionId: key,
+ title: built.snapshot.deck.title,
+ domain: 'nodeslide',
+ brief: built.snapshot.deck.brief,
+ sourceType: 'prompt',
+ starred: false,
+ createdAt: NOW,
+ updatedAt: NOW,
+ });
+ await insertNodeSlideSnapshot(ctx as MutationCtx, {
+ snapshot: built.snapshot,
+ projectRowId,
+ clientSessionId: key,
+ ownerAccessKey: OWNER,
+ plan: built.plan,
+ spec: built.spec,
+ });
+ });
+ const args = {
+ deckId,
+ ownerAccessKey: OWNER,
+ instruction: 'Replace "Before" with "After".',
+ baseDeckVersion: built.snapshot.deck.version,
+ baseSlideVersions: { [slide.id]: slide.version },
+ baseElementVersions: { [target.id]: target.version },
+ scope: {
+ kind: 'elements',
+ deckId,
+ slideIds: [slide.id],
+ elementIds: [target.id],
+ operationMode: 'copy',
+ },
+ };
+ const operations = [
+ { op: 'replace_text', slideId: slide.id, elementId: target.id, text: 'After' },
+ ];
+ return { deckId, args, operations, before: await state(t, deckId) };
+}
+type Seed = Awaited>;
+
+function actionArgs(seeded: Seed, lane: Lane, key: string): Args {
+ return lane === 'deterministic'
+ ? { ...seeded.args, idempotencyKey: key, providerMode: 'deterministic', memoryMode: 'off' }
+ : {
+ ...seeded.args,
+ idempotencyKey: key,
+ operations: seeded.operations,
+ summary: 'Update selected text',
+ provider: 'offline-fixture',
+ model: 'supplied-candidate',
+ providerConsent: NODESLIDE_LOCAL_BYOK_EDIT_CONSENT,
+ };
+}
+
+function context(
+ t: Database,
+ hooks: {
+ started?: (run: Run) => Promise;
+ beforePublish?: (args: Args) => Promise;
+ published?: (patch: DeckPatch) => Promise;
+ } = {},
+) {
+ return {
+ runQuery: (ref: FunctionReference<'query'>, args: Args) => t.query(ref, args),
+ runMutation: async (ref: FunctionReference<'mutation'>, args: Args) => {
+ const name = getFunctionName(ref);
+ if (name === 'nodeslide:proposeAgentPatchInternal') await hooks.beforePublish?.(args);
+ const result = await t.mutation(ref, args);
+ if (name === 'nodeslide:beginAgentRunInternal' && result.created) {
+ await hooks.started?.(result.run);
+ }
+ if (name === 'nodeslide:proposeAgentPatchInternal') await hooks.published?.(result.patch);
+ return result;
+ },
+ };
+}
+
+function cancel(t: Database, seeded: Seed, runId: string) {
+ return t.mutation(api.nodeslide.cancelAgentRun, {
+ deckId: seeded.deckId,
+ ownerAccessKey: OWNER,
+ runId,
+ });
+}
+
+function begin(t: Database, seeded: Seed, key: string) {
+ return t.mutation(internal.nodeslide.beginAgentRunInternal, {
+ deckId: seeded.deckId,
+ ownerAccessKey: OWNER,
+ idempotencyKey: key,
+ instruction: seeded.args.instruction,
+ provider: 'deterministic',
+ model: 'fixture',
+ webResearch: false,
+ });
+}
+
+function publication(seeded: Seed, run: Run, key: string): Args {
+ return {
+ ...seeded.args,
+ runId: run.id,
+ runAttempt: run.attempt,
+ id: `patch-${key}`,
+ traceId: `trace-${key}`,
+ operations: seeded.operations,
+ source: 'agent',
+ summary: 'Update text',
+ shadowComparisonRequested: false,
+ traceSummary: 'An offline bounded candidate',
+ traceContext: [],
+ toolCalls: [],
+ };
+}
+
+describe.each(['deterministic', 'local_candidate'])('%s cancellation publication', (lane) => {
+ it.each(['before_planning', 'before_publication'] as const)(
+ 'an author cancelling %s gets no proposal or trace',
+ async (ordering) => {
+ const t = database();
+ const seeded = await seed(t, `${lane}-${ordering}`);
+ let run: Run;
+ const ctx = context(t, {
+ started: async (value) => {
+ run = value;
+ if (ordering === 'before_planning') await cancel(t, seeded, run.id);
+ },
+ beforePublish: async () => {
+ if (ordering === 'before_publication') await cancel(t, seeded, run.id);
+ },
+ });
+ await expect(handlers[lane](ctx, actionArgs(seeded, lane, ordering))).rejects.toThrow(
+ /cancel/i,
+ );
+ const after = await state(t, seeded.deckId);
+ expect(after.patches).toHaveLength(0);
+ expect(after.traces).toHaveLength(0);
+ expect(after.runs).toHaveLength(1);
+ expect(after.runs[0].status).toBe('cancelled');
+ expect(after.snapshot).toEqual(seeded.before.snapshot);
+ },
+ );
+
+ it('links publication before the final checkpoint so cancellation and replay preserve it', async () => {
+ const t = database();
+ const seeded = await seed(t, `${lane}-publication-gap`);
+ const args = actionArgs(seeded, lane, 'publication-gap');
+ let run: Run;
+ let gap: Awaited> | undefined;
+ let cancelled: unknown;
+ let replay: { patch: DeckPatch } | undefined;
+ const result = await handlers[lane](
+ context(t, {
+ started: async (value) => {
+ run = value;
+ },
+ published: async () => {
+ gap = await state(t, seeded.deckId);
+ cancelled = await cancel(t, seeded, run.id);
+ replay = await handlers[lane](context(t), args);
+ },
+ }),
+ args,
+ );
+ if (!gap) throw new Error('Publication checkpoint was not observed.');
+ expect(gap.runs[0].status).not.toBe('awaiting_review');
+ expect(gap.runs[0].patchId).toBe(result.patch.id);
+ expect(gap.runs[0].traceId).toBe(gap.traces[0].id);
+ expect(cancelled).toMatchObject({ patchId: result.patch.id, status: gap.runs[0].status });
+ expect(replay?.patch.id).toBe(result.patch.id);
+ const after = await state(t, seeded.deckId);
+ expect(after.patches).toHaveLength(1);
+ expect(after.traces).toHaveLength(1);
+ expect(after.runs).toHaveLength(1);
+ expect(after.runs[0].status).toBe('awaiting_review');
+ expect(after.snapshot).toEqual(seeded.before.snapshot);
+ });
+
+ it('preserves completed publication and ordinary idempotent replay', async () => {
+ const t = database();
+ const seeded = await seed(t, `${lane}-complete-first`);
+ const args = actionArgs(seeded, lane, 'complete-first');
+ const first = await handlers[lane](context(t), args);
+ const before = await state(t, seeded.deckId);
+ expect(await cancel(t, seeded, before.runs[0].id)).toMatchObject({ status: 'awaiting_review' });
+ const replay = await handlers[lane](context(t), args);
+ expect(replay.patch.id).toBe(first.patch.id);
+ const after = await state(t, seeded.deckId);
+ expect(after.patches).toEqual(before.patches);
+ expect(after.traces).toEqual(before.traces);
+ expect(after.runs).toEqual(before.runs);
+ expect(after.snapshot).toEqual(seeded.before.snapshot);
+ });
+
+ it('rejects an old attempt without failing the reopened current attempt', async () => {
+ const t = database();
+ const seeded = await seed(t, `${lane}-replacement`);
+ let captured: Run | undefined;
+ let replacement: Run | undefined;
+ const ctx = context(t, {
+ started: async (value) => {
+ captured = value;
+ },
+ beforePublish: async () => {
+ if (!captured) throw new Error('Original attempt was not observed.');
+ await t.mutation(internal.nodeslide.advanceAgentRunInternal, {
+ deckId: seeded.deckId,
+ ownerAccessKey: OWNER,
+ runId: captured.id,
+ status: 'failed',
+ error: 'Earlier worker failed',
+ });
+ replacement = (await begin(t, seeded, 'replacement')).run;
+ },
+ });
+ await expect(handlers[lane](ctx, actionArgs(seeded, lane, 'replacement'))).rejects.toThrow();
+ const after = await state(t, seeded.deckId);
+ if (!replacement || !captured) throw new Error('Attempt replacement was not observed.');
+ expect(replacement.id).toBe(captured.id);
+ expect(replacement.attempt).toBe(captured.attempt + 1);
+ expect(after.runs[0]).toMatchObject({ id: replacement.id, attempt: 2, status: 'queued' });
+ expect(after.runs[0].error).toBeUndefined();
+ expect(after.patches).toHaveLength(0);
+ expect(after.traces).toHaveLength(0);
+ expect(after.snapshot).toEqual(seeded.before.snapshot);
+ });
+});
+
+it('refuses invalid run/deck/owner/attempt bindings and terminal or published runs before writes', async () => {
+ const t = database();
+ const seeded = await seed(t, 'invalid-bindings');
+ const other = await seed(t, 'another-deck');
+ for (const kind of [
+ 'missing_run',
+ 'missing_attempt',
+ 'unknown_run',
+ 'other_deck',
+ 'other_owner',
+ 'old_attempt',
+ 'cancelled',
+ 'failed',
+ 'completed',
+ 'awaiting_review',
+ 'published',
+ ] as const) {
+ const start = await begin(t, kind === 'other_deck' ? other : seeded, kind);
+ const args = publication(seeded, start.run, kind);
+ if (kind === 'missing_run') args.runId = undefined;
+ if (kind === 'missing_attempt') args.runAttempt = undefined;
+ if (kind === 'unknown_run') args.runId = 'absent';
+ if (kind === 'old_attempt') args.runAttempt = 0;
+ await t.run(async (ctx) => {
+ const row = await ctx.db
+ .query('nodeslide_agent_runs')
+ .withIndex('by_stable_id', (q) => q.eq('id', start.run.id))
+ .unique();
+ if (!row) throw new Error('Seeded run missing');
+ if (kind === 'other_owner') await ctx.db.patch(row._id, { ownerDigest: 'different-owner' });
+ if (kind === 'published')
+ await ctx.db.patch(row._id, { patchId: 'existing-patch', traceId: 'existing-trace' });
+ if (['cancelled', 'failed', 'completed', 'awaiting_review'].includes(kind)) {
+ await ctx.db.patch(row._id, {
+ status: kind as 'cancelled' | 'failed' | 'completed' | 'awaiting_review',
+ });
+ }
+ });
+ const before = await state(t, seeded.deckId);
+ // The raw handler keeps this same-case RED meaningful before the new argument validators exist.
+ // It still runs inside an actual Convex-test transaction with all actual persistence helpers.
+ await expect(t.run((ctx) => publish(ctx as MutationCtx, args))).rejects.toThrow();
+ expect(await state(t, seeded.deckId)).toEqual(before);
+ }
+}, 20_000);
+
+it('admits the current retry once and rolls back invalid proposal writes', async () => {
+ const t = database();
+ const seeded = await seed(t, 'current-retry');
+ const first = await begin(t, seeded, 'retry');
+ await t.mutation(internal.nodeslide.advanceAgentRunInternal, {
+ deckId: seeded.deckId,
+ ownerAccessKey: OWNER,
+ runId: first.run.id,
+ status: 'failed',
+ });
+ const current = await begin(t, seeded, 'retry');
+ expect(current.run.attempt).toBe(2);
+ const args = publication(seeded, current.run, 'retry');
+ const before = await state(t, seeded.deckId);
+ await expect(
+ t.run((ctx) => publish(ctx as MutationCtx, { ...args, operations: [] })),
+ ).rejects.toThrow();
+ expect(await state(t, seeded.deckId)).toEqual(before);
+ const result = await t.run((ctx) => publish(ctx as MutationCtx, args));
+ const published = await state(t, seeded.deckId);
+ expect(published.patches).toHaveLength(1);
+ expect(published.traces).toHaveLength(1);
+ expect(published.runs[0]).toMatchObject({
+ patchId: result.patch.id,
+ traceId: 'trace-retry',
+ attempt: 2,
+ });
+ await expect(t.run((ctx) => publish(ctx as MutationCtx, args))).rejects.toThrow();
+ expect(await state(t, seeded.deckId)).toEqual(published);
+ expect(published.snapshot).toEqual(seeded.before.snapshot);
+});
+
+it('keeps four overlapping jobs cancelled without cross-deck publication', async () => {
+ const t = database();
+ const seeds: Seed[] = [];
+ for (let n = 0; n < 4; n++) seeds.push(await seed(t, `overlap-${n}`));
+ let arrivals = 0;
+ let release = () => {};
+ const gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const results = await Promise.allSettled(
+ seeds.map(async (seeded, n) => {
+ const lane: Lane = n % 2 ? 'local_candidate' : 'deterministic';
+ let run: Run;
+ return handlers[lane](
+ context(t, {
+ started: async (value) => {
+ run = value;
+ },
+ beforePublish: async () => {
+ if (++arrivals === 4) release();
+ await gate;
+ await cancel(t, seeded, run.id);
+ },
+ }),
+ actionArgs(seeded, lane, `overlap-${n}`),
+ );
+ }),
+ );
+ expect(arrivals).toBe(4);
+ expect(results.every((result) => result.status === 'rejected')).toBe(true);
+ for (const seeded of seeds) {
+ const after = await state(t, seeded.deckId);
+ expect(after.runs[0].status).toBe('cancelled');
+ expect(after.patches).toHaveLength(0);
+ expect(after.traces).toHaveLength(0);
+ expect(after.snapshot).toEqual(seeded.before.snapshot);
+ }
+}, 20_000);
+
+it('retains twelve cancellation/manual-recovery cycles without orphan proposals', async () => {
+ const t = database();
+ const seeded = await seed(t, 'retained');
+ for (let n = 0; n < 12; n++) {
+ const lane: Lane = n % 2 ? 'local_candidate' : 'deterministic';
+ let run: Run;
+ await expect(
+ handlers[lane](
+ context(t, {
+ started: async (value) => {
+ run = value;
+ },
+ beforePublish: async () => {
+ await cancel(t, seeded, run.id);
+ },
+ }),
+ actionArgs(seeded, lane, `cancel-${n}`),
+ ),
+ ).rejects.toThrow(/cancel/i);
+ const result = await handlers[lane](context(t), actionArgs(seeded, lane, `recover-${n}`));
+ const after = await state(t, seeded.deckId);
+ expect(after.runs).toHaveLength((n + 1) * 2);
+ expect(after.runs.filter((row) => row.status === 'cancelled')).toHaveLength(n + 1);
+ expect(after.runs.filter((row) => row.status === 'awaiting_review')).toHaveLength(n + 1);
+ expect(after.patches).toHaveLength(n + 1);
+ expect(after.traces).toHaveLength(n + 1);
+ expect(after.patches.some((patch) => patch.id === result.patch.id)).toBe(true);
+ expect(after.snapshot).toEqual(seeded.before.snapshot);
+ }
+}, 30_000);
diff --git a/docs/codebase/ARCHITECTURE.md b/docs/codebase/ARCHITECTURE.md
index 04b2e22..e96cb71 100644
--- a/docs/codebase/ARCHITECTURE.md
+++ b/docs/codebase/ARCHITECTURE.md
@@ -43,14 +43,14 @@ The browser calls `applyPatch` / `proposePatch` / `acceptPatch` in
published `@nodeslide/*` packages call the same functions over HTTP.
**Enforced by:** the absence of an alternative. There is no direct table write
-outside `convex/`, and `commitPatch` (`convex/nodeslide.ts:5304` (`commitPatch`)) is the only
+outside `convex/`, and `commitPatch` (`convex/nodeslide.ts:5334` (`commitPatch`)) is the only
function that advances a version.
## 4. The model chooses intent inside a bounded schema. Code produces geometry.
The model is never asked to invent pixel positions. It is asked for a typed
plan — narrative, slide roles, a typed artifact spec — constrained by
-`briefJsonSchema` (`convex/nodeslideAgent.ts:1882` (`briefJsonSchema`)). Deterministic code in
+`briefJsonSchema` (`convex/nodeslideAgent.ts:1890` (`briefJsonSchema`)). Deterministic code in
`convex/lib/nodeslideSeed.ts` turns that plan into positioned, typed elements.
**Why:** the same brief must be reproducible, validatable and repairable. A
@@ -62,7 +62,7 @@ can.
Inside `createDeckFromBrief`, every check that can be made from arguments
already in hand — argument shape, output-identity binding, admission, quota —
runs *before* the provider call. The comments in
-`convex/nodeslideAgent.ts:1757-1765` (`creationAttemptId`) say so explicitly, and they are worth
+`convex/nodeslideAgent.ts:1765-1773` (`creationAttemptId`) say so explicitly, and they are worth
reading before you reorder anything there.
The mirror of the same rule: if a paid call ends without a reconcilable billing
@@ -91,7 +91,7 @@ yet — put it there instead.
## 8. Crashes are cleaned up on a schedule, not hoped away.
Agent runs hold a lease. `recoverStaleAgentRunsInternal`
-(`convex/nodeslide.ts:3347` (`Fails abandoned active runs honestly`)), run every two minutes by `convex/crons.ts`, fails
+(`convex/nodeslide.ts:3353` (`Fails abandoned active runs honestly`)), run every two minutes by `convex/crons.ts`, fails
runs whose lease expired. A crashed action therefore stops spinning in the UI
within two minutes rather than forever.