Personal Telegram developer console for GitHub

feat/studio-g0-foundation
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 303 lines 9.24 KB
Raw
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 });