Personal Telegram developer console for GitHub

feat: complete multi-file change sets

Davood Mehraban committed Oct 5, 2026 at 17:02 UTC ec64e8386288416a4315b6aff8867704190cfc68
5 files changed +133 -37
src/plugins/github/workspace.js
+61 -24
@@ -38,6 +38,12 @@ function parseCallback(data) {
38 if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
39 match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
40 if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
41 + match = value.match(new RegExp(`^wadd:(${HANDLE_10})$`));
42 + if (match) return { actionId: 'github.workspace.file.add', kind: 'add_file', refId: match[1] };
43 + match = value.match(new RegExp(`^wremove:(${HANDLE_10})$`));
44 + if (match) return { actionId: 'github.workspace.file.remove', kind: 'remove_file', refId: match[1] };
45 + match = value.match(new RegExp(`^wfiles:(${HANDLE_10}):(\\d+)$`));
46 + if (match) return { actionId: 'github.workspace.file.pick', kind: 'pick_file', workspaceId: match[1], repoId: Number(match[2]) };
47 match = value.match(new RegExp(`^wfile:(${HANDLE_10})$`));
48 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft_file' };
49 match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
@@ -195,16 +201,44 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
201 };
202 };
203
198 - const renderWorkspace = async (workspaceId, ownerId) => {
204 + const renderWorkspaceObject = async (workspace, ownerId) => {
205 + const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, originalText: workspace.originalText, draftText: workspace.draftText }];
206 + const changedCount = files.filter(file => file.draftText !== file.originalText).length;
207 + const refs = await workspaces.createNavigationRefs?.({ ownerId, refs: files.map(file => ({ workspaceId: workspace.id, path: file.path, type: 'workspace-file', repoId: workspace.repoId })) }) || [];
208 + const commitMessage = workspace.commitMessage ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>` : '<i>ثبت نشده</i>';
209 + const list = files.map((file, i) => `${file.draftText !== file.originalText ? '●' : '○'} <code>${escapeHtml(file.path)}</code>${refs[i]?.refId && files.length > 1 ? ` — <i>قابل حذف</i>` : ''}`).join('\n');
210 + const buttons = workspaceButtons(workspace, editorUrl);
211 + buttons.unshift([{ text: '➕ افزودن فایل', callback_data: `wfiles:${workspace.id}:${workspace.repoId}` }]);
212 + if (files.length > 1 && refs[1]?.refId) buttons.unshift([{ text: `➖ حذف ${short(files[1].path, 28)}`, callback_data: `wremove:${refs[1].refId}` }]);
213 + return { text: `📝 <b>Repository Workspace</b>\nChange Set: <b>${files.length} فایل</b> · تغییرکرده: <b>${changedCount}</b>\n${list}\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nپیام Commit: ${commitMessage}\n\nذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`, reply_markup:{inline_keyboard:buttons} };
214 + };
215 +
216 + const renderWorkspace = async (workspaceId, ownerId) => renderWorkspaceObject(await requireWorkspace(workspaceId, ownerId), ownerId);
217 +
218 + const pickWorkspaceFile = async (workspaceId, repoId, ownerId) => {
219 const workspace = await requireWorkspace(workspaceId, ownerId);
200 - const changed = workspace.draftText !== workspace.originalText;
201 - const commitMessage = workspace.commitMessage
202 - ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>`
203 - : '<i>ثبت نشده</i>';
204 - return {
205 - text: `📝 <b>Repository Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nتغییر محلی: <b>${changed ? 'دارد' : 'ندارد'}</b>\nپیام Commit: ${commitMessage}\n\nبرای ویرایش دقیق و Paste بدون به‌هم‌ریختن فرمت، Editor را باز کنید. ذخیره در Editor فقط Draft محلی را تغییر می‌دهد؛ GitHub همچنان فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`,
206 - reply_markup: { inline_keyboard: workspaceButtons(workspace, editorUrl) }
207 - };
220 + const items = (await github.listFiles(repoId, '')).filter(item => item.type === 'file' && !(workspace.files || []).some(file => file.path === item.path)).slice(0, 20);
221 + const refs = await workspaces.createNavigationRefs({ ownerId, refs: items.map(item => ({ repoId, workspaceId, path:item.path, type:'workspace-add', sha:item.sha })) });
222 + return { text:`➕ <b>افزودن فایل به Change Set</b>\n${items.length ? 'یک فایل را انتخاب کنید.' : 'فایل قابل افزودن دیگری در این نما نیست.'}`, reply_markup:{inline_keyboard:items.map((item,i)=>[{text:`📄 ${short(item.path,42)}`,callback_data:`wadd:${refs[i].refId}`}]).concat([[{text:'↩️ Workspace',callback_data:`ws:${workspaceId}`} ]])} };
223 + };
224 +
225 + const addWorkspaceFile = async (refId, ownerId) => {
226 + const ref = await workspaces.resolveNavigationRef({ownerId,refId});
227 + if (!ref || ref.type !== 'workspace-add') throw new Error('Workspace add-file reference is missing or expired');
228 + const workspace = await requireWorkspace(ref.workspaceId, ownerId);
229 + const file = await github.getFileAtRef(ref.repoId, ref.path, workspace.baseHeadSha);
230 + const policy = validateEditableFile({path:file.path,text:file.content,byteLength:file.size});
231 + if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
232 + const digest = await digestText(file.content);
233 + const updated = await workspaces.upsertWorkspaceFile({ownerId,workspaceId:workspace.id,file:{path:file.path,blobSha:file.sha,originalText:file.content,originalDigest:digest,draftText:file.content,draftDigest:digest}});
234 + const view = await renderWorkspaceObject(updated, ownerId); view.text = `✅ فایل <code>${escapeHtml(file.path)}</code> اضافه شد.\n\n${view.text}`; return view;
235 + };
236 +
237 + const removeWorkspaceFile = async (refId, ownerId) => {
238 + const ref=await workspaces.resolveNavigationRef({ownerId,refId});
239 + if(!ref || ref.type!=='workspace-file') throw new Error('Workspace file reference is missing or expired');
240 + const updated=await workspaces.removeWorkspaceFile({ownerId,workspaceId:ref.workspaceId,path:ref.path});
241 + return renderWorkspaceObject(updated,ownerId);
242 };
243
244 const prepareInput = async (workspaceId, mode, ownerId) => {
@@ -277,29 +311,29 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
311
312 const renderDiff = async (workspaceId, ownerId) => {
313 const workspace = await requireWorkspace(workspaceId, ownerId);
280 - const diff = buildUnifiedDiff({
281 - path: workspace.path,
282 - before: workspace.originalText,
283 - after: workspace.draftText,
284 - maxChars: 2400
285 - });
286 - const truncation = diff.truncated ? '\n⚠️ نمایش Diff کوتاه شده؛ شمارش‌ها بر اساس محتوای کامل هستند.' : '';
287 - return {
288 - text: `🔍 <b>Diff محلی</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n+${diff.additions} / -${diff.deletions}${truncation}\n➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(diff.text)}</pre>`,
289 - reply_markup: { inline_keyboard: [[{ text: '📝 Draft', callback_data: `ws:${workspace.id}` }, { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }]] }
290 - };
314 + const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{path:workspace.path,originalText:workspace.originalText,draftText:workspace.draftText}];
315 + const changed = files.filter(file => file.draftText !== file.originalText);
316 + const diffs = changed.map(file => ({file,diff:buildUnifiedDiff({path:file.path,before:file.originalText,after:file.draftText,maxChars:Math.max(500,Math.floor(2200/Math.max(1,changed.length)))})}));
317 + const additions=diffs.reduce((n,x)=>n+x.diff.additions,0), deletions=diffs.reduce((n,x)=>n+x.diff.deletions,0);
318 + const body=diffs.length ? diffs.map(({file,diff})=>`<b>${escapeHtml(file.path)}</b> · +${diff.additions}/-${diff.deletions}${diff.truncated?' ⚠️':''}\n<pre>${escapeHtml(diff.text)}</pre>`).join('\n') : '<i>هیچ تغییر محلی وجود ندارد.</i>';
319 + return { text:`🔍 <b>Diff تجمیعی Change Set</b>\n${changed.length} فایل تغییرکرده · +${additions} / -${deletions}\n➖➖➖➖➖➖➖➖➖➖\n${body}`, reply_markup:{inline_keyboard:[[{text:'📝 Draft',callback_data:`ws:${workspace.id}`},{text:'✅ آماده Commit',callback_data:`wready:${workspace.id}`}]]} };
320 };
321
322 const sealReadyIntent = async (workspaceId, ownerId) => {
323 const workspace = await requireWorkspace(workspaceId, ownerId);
295 - if (workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
324 + const workspaceFiles = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : null;
325 + const changedFiles = workspaceFiles ? workspaceFiles.filter(file => file.draftText !== file.originalText) : null;
326 + if (workspaceFiles ? changedFiles.length === 0 : workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
327 const commitMessage = normalizeCommitMessage(workspace.commitMessage);
297 - const contentDigest = await digestText(workspace.draftText);
328 const commitMessageDigest = await digestText(commitMessage);
329 const targetBranch = makeTargetBranch(workspace.id);
330 const createdAt = Number(workspace.createdAt);
331 const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
302 - const material = {
332 + const fileDescriptors = workspaceFiles ? await Promise.all(workspaceFiles.map(async file => ({ path:file.path, sourceBlobSha:file.blobSha, contentDigest:file.draftDigest || await digestText(file.draftText) }))) : null;
333 + const material = workspaceFiles ? {
334 + repoId:Number(workspace.repoId), workspaceId:workspace.id, baseBranch:workspace.baseBranch, baseHeadSha:workspace.baseHeadSha, baseTreeSha:workspace.baseTreeSha,
335 + files:fileDescriptors, commitMessageDigest, targetBranch, commitTimestamp
336 + } : {
337 repoId: Number(workspace.repoId),
338 workspaceId: workspace.id,
339 baseBranch: workspace.baseBranch,
@@ -307,7 +341,7 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
341 baseTreeSha: workspace.baseTreeSha,
342 path: workspace.path,
343 sourceBlobSha: workspace.blobSha,
310 - contentDigest,
344 + contentDigest: await digestText(workspace.draftText),
345 commitMessageDigest,
346 targetBranch,
347 commitTimestamp
@@ -390,6 +424,9 @@ export function createWorkspaceController({ github, workspaces, editorUrl = DEFA
424 const ownerId = ownerFrom(context);
425 if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
426 if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
427 + if (parsed.kind === 'pick_file') return pickWorkspaceFile(parsed.workspaceId, parsed.repoId, ownerId);
428 + if (parsed.kind === 'add_file') return addWorkspaceFile(parsed.refId, ownerId);
429 + if (parsed.kind === 'remove_file') return removeWorkspaceFile(parsed.refId, ownerId);
430 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
431 if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
432 if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
src/workspace-editor.js
+25 -13
@@ -26,7 +26,7 @@ function statusForError(error) {
26 if (/signature|hash|auth_date|owner|initData|user/i.test(message)) return 403;
27 if (/not found|expired/i.test(message)) return 404;
28 if (/limited|not editable|binary|LFS|sensitive/i.test(message)) return 422;
29 - if (/invalid|required|JSON|body/i.test(message)) return 400;
29 + if (/invalid|required|JSON|body|path|member|Change Set/i.test(message)) return 400;
30 return 500;
31 }
32
@@ -52,13 +52,18 @@ export async function handleWorkspaceEditorRequest(request, {
52 const workspaceId = safeWorkspaceId(url.searchParams.get('workspaceId'));
53 const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId });
54 if (!workspace) throw new Error('Workspace not found or expired');
55 + const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }];
56 + const requestedPath = String(url.searchParams.get('path') || workspace.path || files[0].path);
57 + const selected = files.find(file => file.path === requestedPath);
58 + if (!selected) throw new Error('Editor path is not a member of this Change Set');
59 return jsonResponse({
60 workspace: {
61 id: workspace.id,
58 - path: workspace.path,
62 + path: selected.path,
63 + files: files.map(file => ({ path: file.path })),
64 state: workspace.state || 'DRAFT',
65 baseHeadSha: String(workspace.baseHeadSha || '').slice(0, 10),
61 - draftText: String(workspace.draftText ?? '')
66 + draftText: String(selected.draftText ?? '')
67 },
68 limits: WORKSPACE_EDITOR_LIMITS
69 });
@@ -78,20 +83,21 @@ export async function handleWorkspaceEditorRequest(request, {
83 const workspaceId = safeWorkspaceId(body?.workspaceId);
84 const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId });
85 if (!workspace) throw new Error('Workspace not found or expired');
81 - const policy = validateEditableFile({ path: workspace.path, text: body?.text });
86 + const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }];
87 + const requestedPath = String(body?.path || workspace.path || files[0].path);
88 + const selected = files.find(file => file.path === requestedPath);
89 + if (!selected) throw new Error('Editor path is not a member of this Change Set');
90 + const policy = validateEditableFile({ path: selected.path, text: body?.text });
91 if (!policy.editable) return jsonResponse({ ok: false, error: policy.reason }, 422);
92 const digest = await digestText(policy.text);
84 - const updated = await workspaces.updateDraft({
85 - ownerId: owner,
86 - workspaceId,
87 - text: policy.text,
88 - digest
89 - });
93 + const updated = typeof workspaces.updateWorkspaceFileDraft === 'function'
94 + ? await workspaces.updateWorkspaceFileDraft({ ownerId: owner, workspaceId, path: selected.path, text: policy.text, digest })
95 + : await workspaces.updateDraft({ ownerId: owner, workspaceId, text: policy.text, digest });
96 return jsonResponse({
97 ok: true,
98 workspace: {
99 id: updated?.id || workspaceId,
94 - path: updated?.path || workspace.path,
100 + path: selected.path,
101 state: updated?.state || 'DRAFT',
102 charLength: policy.charLength,
103 byteLength: policy.byteLength
@@ -127,6 +133,7 @@ export function renderWorkspaceEditorPage() {
133 <body>
134 <main>
135 <div class="meta"><strong>🧑‍💻 Workspace Editor</strong><span id="counter">—</span></div>
136 + <select id="files" aria-label="فایل Change Set" disabled></select>
137 <div id="path" class="path">در حال بارگذاری…</div>
138 <textarea id="editor" spellcheck="false" autocapitalize="off" autocomplete="off" disabled></textarea>
139 <div id="status" class="status">در حال اتصال امن به Workspace…</div>
@@ -138,6 +145,7 @@ export function renderWorkspaceEditorPage() {
145 const editor = document.getElementById('editor');
146 const status = document.getElementById('status');
147 const path = document.getElementById('path');
148 + const files = document.getElementById('files');
149 const counter = document.getElementById('counter');
150 const save = document.getElementById('save');
151 const close = document.getElementById('close');
@@ -166,8 +174,11 @@ export function renderWorkspaceEditorPage() {
174 if (!tg || !tg.initData) throw new Error('این Editor باید از داخل Telegram باز شود.');
175 tg.ready(); tg.expand();
176 if (!/^[A-Za-z0-9_-]{10}$/.test(workspaceId)) throw new Error('Workspace نامعتبر است.');
169 - const body = await api('/workspace/api/editor?workspaceId=' + encodeURIComponent(workspaceId));
177 + const selectedPath = params.get('path') || '';
178 + const body = await api('/workspace/api/editor?workspaceId=' + encodeURIComponent(workspaceId) + (selectedPath ? '&path=' + encodeURIComponent(selectedPath) : ''));
179 limits = body.limits || limits;
180 + files.innerHTML = (body.workspace.files || [{path:body.workspace.path}]).map(file => '<option value="' + file.path.replaceAll('&','&amp;').replaceAll('"','&quot;') + '">' + file.path.replaceAll('&','&amp;').replaceAll('<','&lt;') + '</option>').join('');
181 + files.value = body.workspace.path; files.disabled = false;
182 path.textContent = body.workspace.path;
183 editor.value = body.workspace.draftText || '';
184 editor.disabled = false;
@@ -175,10 +186,11 @@ export function renderWorkspaceEditorPage() {
186 updateCounter();
187 }
188 editor.addEventListener('input', updateCounter);
189 + files.addEventListener('change', () => { params.set('path', files.value); location.search = params.toString(); });
190 save.addEventListener('click', async () => {
191 save.disabled = true; setStatus('در حال ذخیره Draft…');
192 try {
181 - await api('/workspace/api/editor', { method:'PUT', headers:{'content-type':'application/json'}, body:JSON.stringify({workspaceId, text:editor.value}) });
193 + await api('/workspace/api/editor', { method:'PUT', headers:{'content-type':'application/json'}, body:JSON.stringify({workspaceId, path:files.value, text:editor.value}) });
194 setStatus('Draft ذخیره شد. برای Diff و Commit به ربات برگردید.', 'ok');
195 updateCounter();
196 if (tg && tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success');
test/phase2-controller.test.js new
+30
@@ -0,0 +1,30 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { createWorkspaceController } from '../src/plugins/github/workspace.js';
4 +
5 +const ws = { id:'W000000001', repoId:1, repoFullName:'o/r', baseBranch:'main', baseHeadSha:'a'.repeat(40), baseTreeSha:'b'.repeat(40), state:'DRAFT', path:'README.md', originalText:'one', draftText:'two', commitMessage:'msg', files:[{path:'README.md',blobSha:'c'.repeat(40),originalText:'one',draftText:'two',draftDigest:'1'.repeat(64)},{path:'src/a.js',blobSha:'d'.repeat(40),originalText:'a',draftText:'b',draftDigest:'2'.repeat(64)}] };
6 +
7 +test('workspace view lists every change-set file and exposes add control', async()=>{
8 + const workspaces={async getWorkspace(){return structuredClone(ws)},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:`R00000000${i}`}))}};
9 + const c=createWorkspaceController({github:{},workspaces,editorUrl:'https://example.com/editor'});
10 + const v=await c.resolveCallback('ws:W000000001',{ownerId:'42'}).execute();
11 + assert.match(v.text,/README\.md/); assert.match(v.text,/src\/a\.js/); assert.match(v.text,/2 فایل/);
12 + assert.ok(v.reply_markup.inline_keyboard.flat().some(b=>b.callback_data==='wfiles:W000000001:1'));
13 +});
14 +
15 +test('adding a file reads pinned source then upserts durable workspace only', async()=>{
16 + const calls=[];
17 + const workspaces={async resolveNavigationRef(){return {repoId:1,path:'src/b.js',type:'workspace-add',workspaceId:'W000000001'}},async getWorkspace(){return structuredClone(ws)},async upsertWorkspaceFile(x){calls.push(['upsert',x]);return {...ws,files:[...ws.files,x.file]}},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:`R00000000${i}`}))}};
18 + const github={async getRepository(){return {fullName:'o/r',defaultBranch:'main'}},async getBranchSnapshot(){return {headSha:ws.baseHeadSha,treeSha:ws.baseTreeSha}},async getFileAtRef(_r,path){calls.push(['read',path]);return {path,sha:'e'.repeat(40),content:'safe',size:4}}};
19 + const c=createWorkspaceController({github,workspaces});
20 + const v=await c.resolveCallback('wadd:R000000001',{ownerId:'42'}).execute();
21 + assert.equal(calls[0][0],'read'); assert.equal(calls[1][0],'upsert'); assert.match(v.text,/اضافه|added/i);
22 +});
23 +
24 +test('removing a change-set file uses opaque ref and durable remove', async()=>{
25 + let removed='';
26 + const workspaces={async resolveNavigationRef(){return {workspaceId:'W000000001',path:'src/a.js',type:'workspace-file'}},async removeWorkspaceFile({path}){removed=path;return {...ws,files:[ws.files[0]]}},async createNavigationRefs({refs}){return refs.map((_,i)=>({refId:`R00000000${i}`}))}};
27 + const c=createWorkspaceController({github:{},workspaces});
28 + const v=await c.resolveCallback('wremove:R000000001',{ownerId:'42'}).execute();
29 + assert.equal(removed,'src/a.js'); assert.match(v.text,/README\.md/);
30 +});
test/phase2-editor-multifile.test.js new
+11
@@ -0,0 +1,11 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { handleWorkspaceEditorRequest } from '../src/workspace-editor.js';
4 +import { createHmac } from 'node:crypto';
5 +function initData(token='123:TEST',userId=42,authDate=1800000000){const p=new URLSearchParams({auth_date:String(authDate),query_id:'q',user:JSON.stringify({id:userId})});const s=[...p].sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${k}=${v}`).join('\n');const key=createHmac('sha256','WebAppData').update(token).digest();p.set('hash',createHmac('sha256',key).update(s).digest('hex'));return p.toString()}
6 +const workspace={id:'W000000001',state:'DRAFT',baseHeadSha:'a'.repeat(40),path:'README.md',draftText:'one',files:[{path:'README.md',draftText:'one',originalText:'zero'},{path:'src/a.js',draftText:'a',originalText:'a'}]};
7 +const context=(calls)=>({botToken:'123:TEST',ownerId:'42',now:()=>1800000000*1000,workspaces:{async getWorkspace(){return structuredClone(workspace)},async updateWorkspaceFileDraft(x){calls.push(x);return {...workspace,files:workspace.files.map(f=>f.path===x.path?{...f,draftText:x.text}:f)}}}});
8 +const headers={'x-telegram-init-data':initData()};
9 +test('editor GET exposes bounded file metadata and selects requested member path',async()=>{const r=await handleWorkspaceEditorRequest(new Request('https://x/workspace/api/editor?workspaceId=W000000001&path=src%2Fa.js',{headers}),context([]));assert.equal(r.status,200);const b=await r.json();assert.deepEqual(b.workspace.files.map(f=>f.path),['README.md','src/a.js']);assert.equal(b.workspace.path,'src/a.js');assert.equal(b.workspace.draftText,'a')});
10 +test('editor PUT updates selected member through path-scoped durable method',async()=>{const calls=[];const r=await handleWorkspaceEditorRequest(new Request('https://x/workspace/api/editor',{method:'PUT',headers:{...headers,'content-type':'application/json'},body:JSON.stringify({workspaceId:'W000000001',path:'src/a.js',text:'b'})}),context(calls));assert.equal(r.status,200);assert.equal(calls.length,1);assert.equal(calls[0].path,'src/a.js');assert.equal(calls[0].text,'b')});
11 +test('editor rejects path outside change set',async()=>{const r=await handleWorkspaceEditorRequest(new Request('https://x/workspace/api/editor',{method:'PUT',headers:{...headers,'content-type':'application/json'},body:JSON.stringify({workspaceId:'W000000001',path:'evil.js',text:'x'})}),context([]));assert.equal(r.status,400);const b=await r.json();assert.match(b.error,/path|member|change set/i)});
test/phase2-ready.test.js new
+6
@@ -0,0 +1,6 @@
1 +import test from 'node:test';import assert from 'node:assert/strict';import {createWorkspaceController} from '../src/plugins/github/workspace.js';
2 +const files=[{path:'README.md',blobSha:'c'.repeat(40),originalText:'one',draftText:'two',draftDigest:'1'.repeat(64)},{path:'src/a.js',blobSha:'d'.repeat(40),originalText:'a',draftText:'b',draftDigest:'2'.repeat(64)}];
3 +function setup(order=files){let sealed;const workspace={id:'W000000001',repoId:1,baseBranch:'main',baseHeadSha:'a'.repeat(40),baseTreeSha:'b'.repeat(40),createdAt:1000,commitMessage:'msg',commitMessageDigest:'9'.repeat(64),files:order};const workspaces={async getWorkspace(){return structuredClone(workspace)},async sealIntent({intent}){sealed=intent;return{id:'I0000001',...intent}}};return{c:createWorkspaceController({github:{},workspaces}),get:()=>sealed}}
4 +test('Ready seals ordered descriptors for every changed file',async()=>{const x=setup();await x.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();const i=x.get();assert.deepEqual(i.files.map(f=>f.path),['README.md','src/a.js']);assert.ok(i.files.every(f=>f.sourceBlobSha&&f.contentDigest));assert.equal(i.path,undefined)});
5 +test('file order changes aggregate intent digest',async()=>{const a=setup(files),b=setup([...files].reverse());await a.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();await b.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute();assert.notEqual(a.get().intentDigest,b.get().intentDigest)});
6 +test('Ready rejects a change set with no changed files',async()=>{const same=files.map(f=>({...f,draftText:f.originalText}));const x=setup(same);await assert.rejects(()=>x.c.resolveCallback('wready:W000000001',{ownerId:'42'}).execute(),/No draft change/i)});