Personal Telegram developer console for GitHub

fix: claim automation steps durably and transact incident updates

Codex committed Oct 25, 2026 at 07:26 UTC a9a082b40ab09ba5c8a1b491273099c291b97fc8
6 files changed +513 -77
src/core/automation-runner.js
+32 -37
@@ -6,54 +6,50 @@ export class AutomationRunner {
6 this.killSwitch = killSwitch;
7 }
8 async advance(state) {
9 - if (this.killSwitch && (await this.killSwitch.automationBlocked())) {
10 - const next = {
11 - ...structuredClone(state),
12 - status: 'paused_kill_switch',
13 - updatedAt: Date.now()
14 - };
15 - await this.store.put(next);
16 - return next;
17 - }
18 - const step = state.steps[state.cursor];
19 - if (!step) return state;
9 + if (
10 + typeof this.store?.claimStep !== 'function' ||
11 + typeof this.store?.completeStep !== 'function'
12 + )
13 + throw new Error('Persistent automation step claims are required');
14 + const blocked =
15 + this.killSwitch && (await this.killSwitch.automationBlocked());
16 + // Dispatch itself may perform provider effects. Reserve durably before it.
17 + const claim = await this.store.claimStep(state);
18 + if (!claim.claimed) return claim.state;
19 + const checkpoint = claim.state;
20 + const step = checkpoint.steps[checkpoint.cursor];
21 + const finish = (outcome, intent) =>
22 + this.store.completeStep(checkpoint.id, {
23 + token: claim.token,
24 + outcome,
25 + intent
26 + });
27 + if (blocked) return (await finish('pause_kill_switch')).state;
28 const routed = await this.router.dispatchCallback(step.callback, {
29 isOwner: true,
22 - ownerId: state.ownerId
30 + ownerId: checkpoint.ownerId
31 });
32 if (!routed) throw new Error('Automation action unavailable');
25 - if (routed.killSwitchLocked) {
26 - const next = {
27 - ...structuredClone(state),
28 - status: 'paused_kill_switch',
29 - updatedAt: Date.now()
30 - };
31 - await this.store.put(next);
32 - return next;
33 - }
33 + if (routed.killSwitchLocked)
34 + return (await finish('pause_kill_switch')).state;
35 if (routed.requiresApproval) {
35 - const next = transitionAutomation(state, {
36 - type: 'pause',
37 - intent: {
36 + return (
37 + await finish('pause_approval', {
38 pluginId: routed.pluginId,
39 actionId: routed.actionId,
40 risk: routed.risk,
41 input: routed.approval?.input,
42 callback: step.callback,
43 key: step.key
44 - }
45 - });
46 - await this.store.put(next);
47 - return next;
44 + })
45 + ).state;
46 }
49 - const checkpoint = await this.store.put(state);
47 + if (routed.denied) return (await finish('fail')).state;
48 const result = routed.execute ? await routed.execute() : routed;
51 - const next = transitionAutomation(checkpoint, {
52 - type: 'complete_step',
53 - key: step.key
54 - });
55 - await this.store.put(next);
56 - return { ...next, lastResult: result };
49 + const completed = await finish('complete');
50 + return completed.completed
51 + ? { ...completed.state, lastResult: result }
52 + : completed.state;
53 }
54 async resume(state, { approval, key }) {
55 if (this.killSwitch && (await this.killSwitch.automationBlocked()))
@@ -61,7 +57,6 @@ export class AutomationRunner {
57 if (!approval || state.approvalIntent?.key !== key)
58 throw new Error('Matching approval required');
59 const resumed = transitionAutomation(state, { type: 'resume', key });
64 - await this.store.put(resumed);
65 - return resumed;
60 + return this.store.put(resumed);
61 }
62 }
src/core/automation-store.js
+24
@@ -30,4 +30,28 @@ export class DurableAutomationStoreClient {
30 if (!r.ok) throw new Error('Automation write failed');
31 return r.json();
32 }
33 + async claimStep(state) {
34 + if (String(state.ownerId) !== this.ownerId)
35 + throw new Error('Automation claim owner mismatch');
36 + return this.stepRequest(state.id, 'claim', {
37 + cursor: state.cursor,
38 + key: state.steps?.[state.cursor]?.key,
39 + revision: state.revision || 0
40 + });
41 + }
42 + completeStep(id, { token, outcome, intent }) {
43 + return this.stepRequest(id, 'complete', { token, outcome, intent });
44 + }
45 + async stepRequest(id, operation, body) {
46 + const r = await this.stub(id).fetch(
47 + `https://automation.local/${operation}?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(id)}`,
48 + {
49 + method: 'POST',
50 + headers: { 'content-type': 'application/json' },
51 + body: JSON.stringify(body)
52 + }
53 + );
54 + if (!r.ok) throw new Error(`Automation ${operation} failed`);
55 + return r.json();
56 + }
57 }
src/durable/automation-store.js
+94 -2
@@ -1,3 +1,5 @@
1 +import { transitionAutomation } from '../core/automation.js';
2 +
3 const json = (x, s = 200) =>
4 new Response(JSON.stringify(x), {
5 status: s,
@@ -25,8 +27,98 @@ export class AutomationStore {
27 body.version !== 1
28 )
29 return json({ error: 'invalid state' }, 400);
28 - await this.storage.put(key, body);
29 - return json(body);
30 + return this.storage.transaction(async (txn) => {
31 + const current = await txn.get(key);
32 + // A claimed mutation cannot be safely revoked or reset by a snapshot PUT.
33 + if (
34 + body.stepClaim ||
35 + (current &&
36 + (current.stepClaim ||
37 + ['completed', 'cancelled', 'failed'].includes(current.status) ||
38 + (body.revision || 0) !== (current.revision || 0)))
39 + )
40 + return json({ error: 'automation state conflict' }, 409);
41 + const next = { ...body, revision: (current?.revision || 0) + 1 };
42 + await txn.put(key, next);
43 + return json(next);
44 + });
45 + }
46 + if (req.method === 'POST' && u.pathname === '/claim') {
47 + const body = await req.json();
48 + return this.storage.transaction(async (txn) => {
49 + const current = await txn.get(key);
50 + if (!current) return json({ error: 'not found' }, 404);
51 + const step = current.steps?.[current.cursor];
52 + if (
53 + !['ready', 'paused_kill_switch'].includes(current.status) ||
54 + current.stepClaim ||
55 + !step?.key ||
56 + current.completedKeys?.includes(step.key) ||
57 + body.cursor !== current.cursor ||
58 + body.key !== step.key ||
59 + (body.revision || 0) !== (current.revision || 0)
60 + )
61 + return json({ claimed: false, state: current });
62 + const token = crypto.randomUUID();
63 + // No expiry/reclaim: a crash can leave an ambiguous external mutation.
64 + const next = {
65 + ...current,
66 + status: 'step_unresolved',
67 + stepClaim: { token, key: step.key, cursor: current.cursor },
68 + revision: (current.revision || 0) + 1,
69 + updatedAt: Date.now()
70 + };
71 + await txn.put(key, next);
72 + return json({ claimed: true, token, state: next });
73 + });
74 + }
75 + if (req.method === 'POST' && u.pathname === '/complete') {
76 + const body = await req.json();
77 + if (
78 + !['complete', 'pause_approval', 'pause_kill_switch', 'fail'].includes(
79 + body.outcome
80 + )
81 + )
82 + return json({ error: 'invalid outcome' }, 400);
83 + return this.storage.transaction(async (txn) => {
84 + const current = await txn.get(key);
85 + if (!current) return json({ error: 'not found' }, 404);
86 + const claim = current.stepClaim;
87 + if (
88 + current.status !== 'step_unresolved' ||
89 + !claim?.token ||
90 + claim.token !== body.token ||
91 + claim.cursor !== current.cursor ||
92 + claim.key !== current.steps?.[current.cursor]?.key
93 + )
94 + return json({ completed: false, state: current });
95 + let next;
96 + if (body.outcome === 'complete')
97 + next = transitionAutomation(current, {
98 + type: 'complete_step',
99 + key: claim.key
100 + });
101 + else if (body.outcome === 'pause_approval')
102 + next = transitionAutomation(current, {
103 + type: 'pause',
104 + intent: { ...body.intent, key: claim.key }
105 + });
106 + else if (body.outcome === 'fail')
107 + next = transitionAutomation(current, {
108 + type: 'fail',
109 + error: 'Automation action denied'
110 + });
111 + else
112 + next = {
113 + ...current,
114 + status: 'paused_kill_switch',
115 + updatedAt: Date.now()
116 + };
117 + delete next.stepClaim;
118 + next.revision = (current.revision || 0) + 1;
119 + await txn.put(key, next);
120 + return json({ completed: true, state: next });
121 + });
122 }
123 return json({ error: 'not found' }, 404);
124 }
src/durable/incident-store.js
+37 -31
@@ -14,43 +14,49 @@ export class IncidentStore {
14 const owner = url.searchParams.get('owner') || '';
15 if (!owner) return json({ error: 'owner required' }, 400);
16 const key = 'incidents:' + owner;
17 - const items = (await this.storage.get(key)) || [];
18 - if (request.method === 'GET') return json({ version: 1, items });
17 + if (request.method === 'GET')
18 + return json({ version: 1, items: (await this.storage.get(key)) || [] });
19 const body = await request.json().catch(() => ({}));
20 if (request.method === 'POST' && url.pathname.endsWith('/upsert')) {
21 const next = normalizeIncident(body);
22 - const i = items.findIndex((x) => x.fingerprint === next.fingerprint);
23 - const now = Date.now();
24 - if (i >= 0) {
22 + return this.storage.transaction(async (txn) => {
23 + const items = (await txn.get(key)) || [];
24 + const i = items.findIndex((x) => x.fingerprint === next.fingerprint);
25 + const now = Date.now();
26 + if (i >= 0) {
27 + items[i] = {
28 + ...items[i],
29 + ...next,
30 + status: 'open',
31 + count: (items[i].count || 1) + 1,
32 + updatedAt: now
33 + };
34 + } else
35 + items.unshift({
36 + ...next,
37 + id: crypto.randomUUID(),
38 + count: 1,
39 + createdAt: now,
40 + updatedAt: now
41 + });
42 + await txn.put(key, items.slice(0, 100));
43 + return json(i >= 0 ? items[i] : items[0]);
44 + });
45 + }
46 + if (request.method === 'POST' && url.pathname.endsWith('/resolve')) {
47 + return this.storage.transaction(async (txn) => {
48 + const items = (await txn.get(key)) || [];
49 + const i = items.findIndex((x) => x.id === body.id);
50 + if (i < 0) return json({ error: 'not found' }, 404);
51 items[i] = {
52 ...items[i],
27 - ...next,
28 - status: 'open',
29 - count: (items[i].count || 1) + 1,
30 - updatedAt: now
53 + status: 'resolved',
54 + resolvedAt: Date.now(),
55 + updatedAt: Date.now()
56 };
32 - } else
33 - items.unshift({
34 - ...next,
35 - id: crypto.randomUUID(),
36 - count: 1,
37 - createdAt: now,
38 - updatedAt: now
39 - });
40 - await this.storage.put(key, items.slice(0, 100));
41 - return json(i >= 0 ? items[i] : items[0]);
42 - }
43 - if (request.method === 'POST' && url.pathname.endsWith('/resolve')) {
44 - const i = items.findIndex((x) => x.id === body.id);
45 - if (i < 0) return json({ error: 'not found' }, 404);
46 - items[i] = {
47 - ...items[i],
48 - status: 'resolved',
49 - resolvedAt: Date.now(),
50 - updatedAt: Date.now()
51 - };
52 - await this.storage.put(key, items);
53 - return json(items[i]);
57 + await txn.put(key, items);
58 + return json(items[i]);
59 + });
60 }
61 return json({ error: 'not found' }, 404);
62 }
test/durable-concurrency.test.js new
+303
@@ -0,0 +1,303 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { AutomationRunner } from '../src/core/automation-runner.js';
4 +import { DurableAutomationStoreClient } from '../src/core/automation-store.js';
5 +import { createAutomation } from '../src/core/automation.js';
6 +import { ActionPolicy } from '../src/core/action-policy.js';
7 +import { PluginRouter } from '../src/core/router.js';
8 +import { KillSwitch } from '../src/core/kill-switch.js';
9 +import { AutomationStore } from '../src/durable/automation-store.js';
10 +import { IncidentStore } from '../src/durable/incident-store.js';
11 +import { makeReplayState } from './helpers/replay-namespace.js';
12 +
13 +function deferred() {
14 + let resolve;
15 + const promise = new Promise((done) => (resolve = done));
16 + return { promise, resolve };
17 +}
18 +
19 +function automationNamespace() {
20 + const states = new Map();
21 + return {
22 + states,
23 + idFromName: (name) => name,
24 + get(id) {
25 + if (!states.has(id)) states.set(id, makeReplayState());
26 + return {
27 + fetch: (url, options) =>
28 + new AutomationStore(states.get(id)).fetch(new Request(url, options))
29 + };
30 + }
31 + };
32 +}
33 +
34 +function routerFor(execute, { risk = 'READ', killSwitch = null } = {}) {
35 + return new PluginRouter({
36 + registry: {
37 + getPlugins: () => [
38 + {
39 + manifest: { id: 'test' },
40 + resolveCallback: async () => ({ actionId: 'test.run', execute })
41 + }
42 + ],
43 + getAction: () => ({ pluginId: 'test', actionId: 'test.run', risk })
44 + },
45 + policy: new ActionPolicy(),
46 + audit: { log() {} },
47 + killSwitch
48 + });
49 +}
50 +
51 +async function automationFixture(execute, options = {}) {
52 + const namespace = automationNamespace();
53 + const store = new DurableAutomationStoreClient({ namespace, ownerId: 'o' });
54 + const state = await store.put(
55 + createAutomation({
56 + id: 'run',
57 + ownerId: 'o',
58 + recipe: 'test',
59 + steps: [
60 + { key: 'first', callback: 'read:first' },
61 + { key: 'second', callback: 'read:second' }
62 + ]
63 + })
64 + );
65 + const router = routerFor(execute, options);
66 + return {
67 + namespace,
68 + store,
69 + state,
70 + runner: new AutomationRunner({
71 + router,
72 + store,
73 + killSwitch: options.killSwitch
74 + })
75 + };
76 +}
77 +
78 +test('concurrent automation advances reserve the step before real router effects', async () => {
79 + const entered = deferred();
80 + const release = deferred();
81 + let effects = 0;
82 + const { runner, store, state } = await automationFixture(async () => {
83 + effects++;
84 + if (effects === 1) {
85 + entered.resolve();
86 + await release.promise;
87 + }
88 + return { ok: true };
89 + });
90 + const first = runner.advance(state);
91 + await entered.promise;
92 + try {
93 + const duplicate = await runner.advance(structuredClone(state));
94 + assert.equal(effects, 1);
95 + assert.equal(duplicate.status, 'step_unresolved');
96 + } finally {
97 + release.resolve();
98 + await first;
99 + }
100 + assert.equal((await store.get('run')).cursor, 1);
101 +});
102 +
103 +test('an old automation cursor cannot run a completed step or the next step', async () => {
104 + let effects = 0;
105 + const { runner, store, state } = await automationFixture(async () => {
106 + effects++;
107 + return { ok: true };
108 + });
109 + await runner.advance(state);
110 + const stale = await runner.advance(state);
111 + assert.equal(effects, 1);
112 + assert.equal(stale.cursor, 1);
113 + assert.equal((await store.get('run')).cursor, 1);
114 +});
115 +
116 +for (const status of [
117 + 'cancelled',
118 + 'failed',
119 + 'completed',
120 + 'awaiting_approval'
121 +]) {
122 + test(`durable ${status} automation rejects a caller's stale ready snapshot`, async () => {
123 + let effects = 0;
124 + const { runner, store, state } = await automationFixture(async () => {
125 + effects++;
126 + return { ok: true };
127 + });
128 + await store.put({ ...state, status });
129 + const result = await runner.advance(state);
130 + assert.equal(effects, 0);
131 + assert.equal(result.status, status);
132 + assert.equal((await store.get('run')).status, status);
133 + });
134 +}
135 +
136 +test('automation fails closed when persistent step claims are unavailable', async () => {
137 + let effects = 0;
138 + const runner = new AutomationRunner({
139 + store: { put: async (state) => state },
140 + router: routerFor(async () => {
141 + effects++;
142 + return { ok: true };
143 + })
144 + });
145 + await assert.rejects(
146 + runner.advance(
147 + createAutomation({
148 + id: 'run',
149 + ownerId: 'o',
150 + steps: [{ key: 'first', callback: 'read:first' }]
151 + })
152 + ),
153 + /claim/i
154 + );
155 + assert.equal(effects, 0);
156 +});
157 +
158 +test('an ambiguous automation provider failure remains unresolved across retries and eviction', async () => {
159 + let effects = 0;
160 + const { runner, store, state } = await automationFixture(async () => {
161 + effects++;
162 + throw new Error('provider result unknown');
163 + });
164 + await assert.rejects(runner.advance(state), /provider result unknown/);
165 + const durable = await store.get('run');
166 + assert.equal(durable.status, 'step_unresolved');
167 + assert.equal(durable.stepClaim.key, 'first');
168 + await runner.advance(state);
169 + await runner.advance(durable);
170 + assert.equal(effects, 1);
171 + assert.equal((await store.get('run')).cursor, 0);
172 +});
173 +
174 +test('durable claims cannot be overwritten by stale PUT or completed with another token', async () => {
175 + const { store, state } = await automationFixture(async () => ({ ok: true }));
176 + const claim = await store.claimStep(state);
177 + assert.equal(claim.claimed, true);
178 + await assert.rejects(store.put(state), /write|conflict/i);
179 + await assert.rejects(
180 + store.put({ ...claim.state, status: 'cancelled' }),
181 + /write|conflict/i
182 + );
183 + const forged = await store.completeStep('run', {
184 + token: 'another-claim',
185 + outcome: 'complete'
186 + });
187 + assert.equal(forged.completed, false);
188 + assert.equal((await store.get('run')).status, 'step_unresolved');
189 + const completed = await store.completeStep('run', {
190 + token: claim.token,
191 + outcome: 'complete'
192 + });
193 + assert.equal(completed.completed, true);
194 + assert.equal(completed.state.cursor, 1);
195 + const replay = await store.completeStep('run', {
196 + token: claim.token,
197 + outcome: 'complete'
198 + });
199 + assert.equal(replay.completed, false);
200 + assert.equal(replay.state.cursor, 1);
201 +});
202 +
203 +test('automation claims retain real router approval and kill-switch checks', async () => {
204 + let effects = 0;
205 + const needsApproval = await automationFixture(
206 + async () => {
207 + effects++;
208 + },
209 + { risk: 'WRITE' }
210 + );
211 + const approval = await needsApproval.runner.advance(needsApproval.state);
212 + assert.equal(approval.status, 'awaiting_approval');
213 + assert.equal(approval.approvalIntent.key, 'first');
214 + assert.equal(effects, 0);
215 +
216 + const killSwitch = new KillSwitch({
217 + store: { get: async () => ({ mode: 'LOCKED' }) }
218 + });
219 + const blocked = await automationFixture(
220 + async () => {
221 + effects++;
222 + },
223 + { killSwitch }
224 + );
225 + assert.equal(
226 + (await blocked.runner.advance(blocked.state)).status,
227 + 'paused_kill_switch'
228 + );
229 + assert.equal(effects, 0);
230 +});
231 +
232 +function incidentRequest(path, owner, body) {
233 + return new Request(`https://incident.local${path}?owner=${owner}`, {
234 + method: body ? 'POST' : 'GET',
235 + headers: { 'content-type': 'application/json' },
236 + body: body ? JSON.stringify(body) : undefined
237 + });
238 +}
239 +
240 +const incident = (repo) => ({
241 + provider: 'github',
242 + repo,
243 + sha: 'abc',
244 + kind: 'ci'
245 +});
246 +
247 +test('concurrent incident upserts preserve distinct incidents and owner isolation', async () => {
248 + const durable = makeReplayState();
249 + const fetch = (request) => new IncidentStore(durable).fetch(request);
250 + await Promise.all([
251 + fetch(incidentRequest('/upsert', 'o', incident('a'))),
252 + fetch(incidentRequest('/upsert', 'o', incident('b'))),
253 + fetch(incidentRequest('/upsert', 'other', incident('c')))
254 + ]);
255 + const result = await (await fetch(incidentRequest('/', 'o'))).json();
256 + assert.deepEqual(result.items.map((item) => item.repo).sort(), ['a', 'b']);
257 + const other = await (await fetch(incidentRequest('/', 'other'))).json();
258 + assert.deepEqual(
259 + other.items.map((item) => item.repo),
260 + ['c']
261 + );
262 +});
263 +
264 +test('concurrent duplicate incident evidence increments one durable incident', async () => {
265 + const durable = makeReplayState();
266 + const fetch = (request) => new IncidentStore(durable).fetch(request);
267 + await Promise.all([
268 + fetch(incidentRequest('/upsert', 'o', incident('a'))),
269 + fetch(incidentRequest('/upsert', 'o', incident('a')))
270 + ]);
271 + const result = await (await fetch(incidentRequest('/', 'o'))).json();
272 + assert.equal(result.items.length, 1);
273 + assert.equal(result.items[0].count, 2);
274 +});
275 +
276 +test('an incident resolve waiting for its body cannot erase a concurrent upsert', async () => {
277 + const durable = makeReplayState();
278 + const fetch = (request) => new IncidentStore(durable).fetch(request);
279 + const original = await (
280 + await fetch(incidentRequest('/upsert', 'o', incident('a')))
281 + ).json();
282 + const bodyEntered = deferred();
283 + const bodyRelease = deferred();
284 + const resolving = fetch({
285 + url: 'https://incident.local/resolve?owner=o',
286 + method: 'POST',
287 + async json() {
288 + bodyEntered.resolve();
289 + await bodyRelease.promise;
290 + return { id: original.id };
291 + }
292 + });
293 + await bodyEntered.promise;
294 + await fetch(incidentRequest('/upsert', 'o', incident('b')));
295 + bodyRelease.resolve();
296 + assert.equal((await resolving).status, 200);
297 + const result = await (await fetch(incidentRequest('/', 'o'))).json();
298 + assert.equal(result.items.length, 2);
299 + assert.equal(
300 + result.items.find((item) => item.id === original.id).status,
301 + 'resolved'
302 + );
303 +});
test/kill-switch.test.js
+23 -7
@@ -3,6 +3,10 @@ import assert from 'node:assert/strict';
3 import { KillSwitch } from '../src/core/kill-switch.js';
4 import { PluginRouter } from '../src/core/router.js';
5 import { AutomationRunner } from '../src/core/automation-runner.js';
6 +import { DurableAutomationStoreClient } from '../src/core/automation-store.js';
7 +import { AutomationStore } from '../src/durable/automation-store.js';
8 +import { createAutomation } from '../src/core/automation.js';
9 +import { makeReplayState } from './helpers/replay-namespace.js';
10 function registryFor(risk, execute) {
11 const actionId = `test.${risk.toLowerCase()}`;
12 const plugin = {
@@ -89,6 +93,17 @@ test('kill switch fails closed for WRITE when durable state cannot be read', asy
93 });
94 test('LOCKED kill switch blocks automation advance before routing any step', async () => {
95 let routed = 0;
96 + const durable = makeReplayState();
97 + const store = new DurableAutomationStoreClient({
98 + ownerId: '123',
99 + namespace: {
100 + idFromName: (name) => name,
101 + get: () => ({
102 + fetch: (url, options) =>
103 + new AutomationStore(durable).fetch(new Request(url, options))
104 + })
105 + }
106 + });
107 const runner = new AutomationRunner({
108 router: {
109 dispatchCallback: async () => {
@@ -96,17 +111,18 @@ test('LOCKED kill switch blocks automation advance before routing any step', asy
111 return { ok: true };
112 }
113 },
99 - store: { put: async (state) => state },
114 + store,
115 killSwitch: new KillSwitch({
116 store: { get: async () => ({ mode: 'LOCKED' }) }
117 })
118 });
104 - const state = {
105 - status: 'ready',
106 - cursor: 0,
107 - ownerId: '123',
108 - steps: [{ callback: 'write:x', key: 'k1' }]
109 - };
119 + const state = await store.put(
120 + createAutomation({
121 + id: 'blocked',
122 + ownerId: '123',
123 + steps: [{ callback: 'write:x', key: 'k1' }]
124 + })
125 + );
126 const blocked = await runner.advance(state);
127 assert.equal(blocked.status, 'paused_kill_switch');
128 assert.equal(routed, 0);