Personal Telegram developer console for GitHub

feat/cp2-multifile-workspace
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 342 lines 14.7 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { ApprovalService } from '../src/core/approval.js';
4 import { PluginRegistry } from '../src/core/plugin-registry.js';
5 import { ActionPolicy } from '../src/core/action-policy.js';
6 import { AuditLogger } from '../src/core/audit.js';
7 import { PluginRouter } from '../src/core/router.js';
8 import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
9 import * as workspaceModule from '../src/plugins/github/workspace.js';
10
11 const OWNER = '42';
12 const REPO_ID = 123;
13 const WORKSPACE_ID = 'W123456789';
14 const INTENT_ID = 'Ab12_cdE';
15 const BASE_HEAD = 'a'.repeat(40);
16 const BASE_TREE = 'b'.repeat(40);
17 const SOURCE_BLOB = 'c'.repeat(40);
18 const CONTENT_BLOB = 'd'.repeat(40);
19 const NEW_TREE = 'e'.repeat(40);
20 const COMMIT_SHA = 'f'.repeat(40);
21 const TARGET_BRANCH = `nexa/edit-${WORKSPACE_ID}`;
22 const TIMESTAMP = '2026-10-03T09:00:00.000Z';
23 const CONTENT_DIGEST = '1'.repeat(64);
24 const MESSAGE_DIGEST = '2'.repeat(64);
25
26 function replayStore() {
27 const seen = new Set();
28 return {
29 async consume({ ownerId, nonce }) {
30 const key = `${ownerId}:${nonce}`;
31 if (seen.has(key)) return false;
32 seen.add(key);
33 return true;
34 }
35 };
36 }
37
38 function makeIntent(overrides = {}) {
39 return {
40 id: INTENT_ID,
41 workspaceId: WORKSPACE_ID,
42 repoId: REPO_ID,
43 baseBranch: 'main',
44 baseHeadSha: BASE_HEAD,
45 baseTreeSha: BASE_TREE,
46 path: 'src/app.js',
47 sourceBlobSha: SOURCE_BLOB,
48 contentDigest: CONTENT_DIGEST,
49 commitMessageDigest: MESSAGE_DIGEST,
50 targetBranch: TARGET_BRANCH,
51 commitTimestamp: TIMESTAMP,
52 intentDigest: '3'.repeat(64),
53 state: 'READY',
54 candidateCommitSha: null,
55 commitSha: null,
56 branch: null,
57 ...overrides
58 };
59 }
60
61 function makeWorkspace(overrides = {}) {
62 return {
63 id: WORKSPACE_ID,
64 repoId: REPO_ID,
65 currentIntentId: INTENT_ID,
66 state: 'READY',
67 baseBranch: 'main',
68 baseHeadSha: BASE_HEAD,
69 baseTreeSha: BASE_TREE,
70 path: 'src/app.js',
71 blobSha: SOURCE_BLOB,
72 originalText: 'before\n',
73 draftText: 'after\n',
74 draftDigest: CONTENT_DIGEST,
75 commitMessage: 'edit app',
76 commitMessageDigest: MESSAGE_DIGEST,
77 ...overrides
78 };
79 }
80
81 function makeWorkspaces({ intent = makeIntent(), workspace = makeWorkspace(), disposition = 'start' } = {}) {
82 const calls = [];
83 let mutableIntent = structuredClone(intent);
84 return {
85 calls,
86 async getIntent({ ownerId, intentId }) {
87 calls.push(['getIntent', ownerId, intentId]);
88 return ownerId === OWNER && intentId === mutableIntent.id ? structuredClone(mutableIntent) : null;
89 },
90 async getWorkspace({ ownerId, workspaceId }) {
91 calls.push(['getWorkspace', ownerId, workspaceId]);
92 return ownerId === OWNER && workspaceId === workspace.id ? structuredClone(workspace) : null;
93 },
94 async beginCommit({ ownerId, intentId }) {
95 calls.push(['beginCommit', ownerId, intentId]);
96 if (mutableIntent.state === 'COMMITTED') return { disposition: 'committed', intent: structuredClone(mutableIntent) };
97 if (mutableIntent.state === 'COMMITTING') return { disposition: 'resume', intent: structuredClone(mutableIntent) };
98 mutableIntent = { ...mutableIntent, state: 'COMMITTING' };
99 return { disposition, intent: structuredClone(mutableIntent) };
100 },
101 async setCandidateCommit({ ownerId, intentId, commitSha }) {
102 calls.push(['setCandidateCommit', ownerId, intentId, commitSha]);
103 mutableIntent = { ...mutableIntent, candidateCommitSha: commitSha, state: 'COMMITTING' };
104 return structuredClone(mutableIntent);
105 },
106 async completeCommit({ ownerId, intentId, commitSha, branch }) {
107 calls.push(['completeCommit', ownerId, intentId, commitSha, branch]);
108 mutableIntent = { ...mutableIntent, commitSha, branch, state: 'COMMITTED' };
109 return structuredClone(mutableIntent);
110 },
111 async markStale({ ownerId, intentId, reason }) {
112 calls.push(['markStale', ownerId, intentId, reason]);
113 mutableIntent = { ...mutableIntent, state: 'STALE', staleReason: reason };
114 return structuredClone(mutableIntent);
115 }
116 };
117 }
118
119 function makeGitHub({ baseHead = BASE_HEAD, existingRef = null, createRefError = null } = {}) {
120 const calls = [];
121 return {
122 calls,
123 async getBranchSnapshot(repoId, branch) {
124 calls.push(['getBranchSnapshot', repoId, branch]);
125 return { branch, headSha: baseHead, treeSha: BASE_TREE };
126 },
127 async getGitRef(repoId, branch, options) {
128 calls.push(['getGitRef', repoId, branch, options]);
129 return existingRef ? structuredClone(existingRef) : null;
130 },
131 async createGitBlob(repoId, text) {
132 calls.push(['createGitBlob', repoId, text]);
133 return { sha: CONTENT_BLOB };
134 },
135 async createGitTree(repoId, input) {
136 calls.push(['createGitTree', repoId, structuredClone(input)]);
137 return { sha: NEW_TREE };
138 },
139 async createGitCommit(repoId, input) {
140 calls.push(['createGitCommit', repoId, structuredClone(input)]);
141 return { sha: COMMIT_SHA };
142 },
143 async createGitBranchRef(repoId, input) {
144 calls.push(['createGitBranchRef', repoId, structuredClone(input)]);
145 if (createRefError) throw createRefError;
146 return { ref: `refs/heads/${input.branch}`, sha: input.sha };
147 }
148 };
149 }
150
151 function minimalMenu() {
152 return {
153 async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
154 async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
155 };
156 }
157
158 test('workspace approval uses compact <=56 byte token and binds owner action risk repo and exact 8-char intent', async () => {
159 let now = 1_700_000_000_000;
160 const approvals = new ApprovalService({
161 secret: 'workspace-secret',
162 now: () => now,
163 ttlMs: 120_000,
164 replayStore: replayStore()
165 });
166 const token = await approvals.issue({
167 pluginId: 'github',
168 actionId: 'github.workspace.commit_branch',
169 risk: 'WRITE',
170 ownerId: OWNER,
171 input: { repoId: REPO_ID, intentId: INTENT_ID }
172 });
173 assert.ok(new TextEncoder().encode(token).byteLength <= 56);
174 assert.ok(new TextEncoder().encode(`approve:${token}`).byteLength <= 64);
175 const payload = await approvals.consume(token, {
176 ownerId: OWNER,
177 pluginId: 'github',
178 actionId: 'github.workspace.commit_branch',
179 risk: 'WRITE'
180 });
181 assert.deepEqual(payload.input, { repoId: REPO_ID, intentId: INTENT_ID });
182 await assert.rejects(() => approvals.consume(token, { ownerId: OWNER }), /already used/i);
183
184 const second = await approvals.issue({
185 pluginId: 'github', actionId: 'github.workspace.commit_branch', risk: 'WRITE', ownerId: OWNER,
186 input: { repoId: REPO_ID, intentId: INTENT_ID }
187 });
188 now += 121_000;
189 await assert.rejects(() => approvals.verify(second, { ownerId: OWNER }), /expired/i);
190 await assert.rejects(() => approvals.issue({
191 pluginId: 'github', actionId: 'github.workspace.commit_branch', risk: 'WRITE', ownerId: OWNER,
192 input: { repoId: REPO_ID, intentId: 'too-short' }
193 }), /intent/i);
194 });
195
196 test('wscommit resolves to WRITE approval metadata before execution and performs zero GitHub or workspace calls pre-approval', async () => {
197 const github = makeGitHub();
198 const workspaces = makeWorkspaces();
199 const plugin = createGitHubPlugin({ github, menu: minimalMenu(), workspaces });
200 const router = new PluginRouter({
201 registry: new PluginRegistry([plugin]),
202 policy: new ActionPolicy(),
203 audit: new AuditLogger({ sink: () => {} })
204 });
205 const result = await router.dispatchCallback(`wscommit:${REPO_ID}:${INTENT_ID}`, { isOwner: true, ownerId: OWNER });
206 assert.equal(result.requiresApproval, true);
207 assert.equal(result.actionId, 'github.workspace.commit_branch');
208 assert.deepEqual(result.approval.input, { repoId: REPO_ID, intentId: INTENT_ID });
209 assert.equal(result.approval.cancelCallback, `repo:${REPO_ID}`);
210 assert.deepEqual(github.calls, []);
211 assert.deepEqual(workspaces.calls, []);
212 });
213
214 test('approved orchestration fails closed on changed workspace material or stale base before any Git object creation', async () => {
215 assert.equal(typeof workspaceModule.commitWorkspaceIntent, 'function');
216
217 const changedWorkspaces = makeWorkspaces({ workspace: makeWorkspace({ currentIntentId: null, draftDigest: '9'.repeat(64) }) });
218 const changedGitHub = makeGitHub();
219 await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
220 github: changedGitHub, workspaces: changedWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
221 }), /intent|material|changed|stale/i);
222 assert.equal(changedGitHub.calls.some(call => call[0].startsWith('createGit')), false);
223
224 const staleWorkspaces = makeWorkspaces();
225 const staleGitHub = makeGitHub({ baseHead: '9'.repeat(40) });
226 await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
227 github: staleGitHub, workspaces: staleWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
228 }), /base|stale|changed/i);
229 assert.equal(staleGitHub.calls.some(call => call[0].startsWith('createGit')), false);
230 assert.ok(staleWorkspaces.calls.some(call => call[0] === 'markStale'));
231 });
232
233 test('approved orchestration rejects an unexpected existing target branch without creating Git objects', async () => {
234 const workspaces = makeWorkspaces();
235 const github = makeGitHub({ existingRef: { branch: TARGET_BRANCH, sha: '8'.repeat(40) } });
236 await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
237 github, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
238 }), /already exists|target branch|unexpected/i);
239 assert.equal(github.calls.some(call => call[0].startsWith('createGit')), false);
240 });
241
242 test('successful approved orchestration is blob -> tree -> commit -> durable candidate -> create ref -> durable COMMITTED', async () => {
243 const workspaces = makeWorkspaces();
244 const github = makeGitHub();
245 const result = await workspaceModule.commitWorkspaceIntent({ github, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID });
246 assert.deepEqual(result, { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: false });
247 assert.deepEqual(github.calls.map(call => call[0]), [
248 'getBranchSnapshot', 'getGitRef', 'createGitBlob', 'createGitTree', 'createGitCommit', 'createGitBranchRef'
249 ]);
250 const blobCall = github.calls.find(call => call[0] === 'createGitBlob');
251 assert.equal(blobCall[2], 'after\n');
252 const treeCall = github.calls.find(call => call[0] === 'createGitTree');
253 assert.deepEqual(treeCall[2], {
254 baseTreeSha: BASE_TREE,
255 entries: [{ path: 'src/app.js', mode: '100644', type: 'blob', sha: CONTENT_BLOB }]
256 });
257 const commitCall = github.calls.find(call => call[0] === 'createGitCommit');
258 assert.deepEqual(commitCall[2], {
259 message: 'edit app', treeSha: NEW_TREE, parentSha: BASE_HEAD, timestamp: TIMESTAMP
260 });
261 assert.ok(workspaces.calls.some(call => call[0] === 'setCandidateCommit' && call[3] === COMMIT_SHA));
262 assert.ok(workspaces.calls.some(call => call[0] === 'completeCommit' && call[3] === COMMIT_SHA && call[4] === TARGET_BRANCH));
263 });
264
265 test('COMMITTED and COMMITTING retries reconcile idempotently without a second provider write', async () => {
266 const committedIntent = makeIntent({ state: 'COMMITTED', commitSha: COMMIT_SHA, branch: TARGET_BRANCH });
267 const committedWorkspaces = makeWorkspaces({ intent: committedIntent });
268 const committedGitHub = makeGitHub();
269 assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
270 github: committedGitHub, workspaces: committedWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
271 }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
272 assert.deepEqual(committedGitHub.calls, []);
273
274 const resumingIntent = makeIntent({ state: 'COMMITTING', candidateCommitSha: COMMIT_SHA });
275 const resumingWorkspaces = makeWorkspaces({ intent: resumingIntent });
276 const resumingGitHub = makeGitHub({ existingRef: { branch: TARGET_BRANCH, sha: COMMIT_SHA } });
277 assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
278 github: resumingGitHub, workspaces: resumingWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
279 }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
280 assert.deepEqual(resumingGitHub.calls.map(call => call[0]), ['getGitRef']);
281 assert.ok(resumingWorkspaces.calls.some(call => call[0] === 'completeCommit'));
282 });
283
284 test('ambiguous create-ref error reconciles only the exact candidate SHA and rejects different or missing refs', async () => {
285 const ambiguous = new Error('GitHub create branch ref failed: 422 Reference already exists');
286 const sequenceGitHub = makeGitHub({ createRefError: ambiguous });
287 let refReads = 0;
288 sequenceGitHub.getGitRef = async (repoId, branch, options) => {
289 sequenceGitHub.calls.push(['getGitRef', repoId, branch, options]);
290 refReads += 1;
291 return refReads === 1 ? null : { branch, sha: COMMIT_SHA };
292 };
293 const workspaces = makeWorkspaces();
294 assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
295 github: sequenceGitHub, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
296 }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
297
298 for (const ref of [null, { branch: TARGET_BRANCH, sha: '7'.repeat(40) }]) {
299 const github = makeGitHub({ createRefError: ambiguous });
300 let reads = 0;
301 github.getGitRef = async (repoId, branch, options) => {
302 github.calls.push(['getGitRef', repoId, branch, options]);
303 reads += 1;
304 return reads === 1 ? null : ref;
305 };
306 await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
307 github, workspaces: makeWorkspaces(), ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
308 }), /422|reconcile|branch|candidate/i);
309 }
310 });
311
312 test('router audit merges only allowlisted workspace metadata and never source draft text or signed token material', async () => {
313 const events = [];
314 const plugin = {
315 manifest: { id: 'safe', name: 'safe', version: 1, commands: [], actions: { 'safe.write': { risk: 'WRITE' } } },
316 resolveCallback() {
317 return {
318 actionId: 'safe.write',
319 audit: {
320 repoId: REPO_ID,
321 workspaceId: WORKSPACE_ID,
322 intentId: INTENT_ID,
323 path: 'src/app.js',
324 contentDigest: CONTENT_DIGEST,
325 commitSha: COMMIT_SHA,
326 draftText: 'DO NOT LOG THIS',
327 token: 'approve:DO_NOT_LOG'
328 },
329 execute: async () => ({ text: 'ok' })
330 };
331 }
332 };
333 const router = new PluginRouter({
334 registry: new PluginRegistry([plugin]), policy: new ActionPolicy(),
335 audit: new AuditLogger({ sink: event => events.push(event) })
336 });
337 await router.dispatchCallback('x', { isOwner: true, approved: true });
338 const serialized = JSON.stringify(events);
339 assert.match(serialized, /src\/app\.js/);
340 assert.match(serialized, new RegExp(INTENT_ID));
341 assert.doesNotMatch(serialized, /DO NOT LOG THIS|DO_NOT_LOG|draftText|token/);
342 });