Personal Telegram developer console for GitHub

feat: complete Phase 2 multi-file workspace (#54)

* docs: specify phase 2 multi-file workspace * docs: add phase 2 multi-file implementation plan * feat: complete multi-file change sets

davoodmehraban89 committed Oct 5, 2026 at 17:03 UTC c2aafc36950e39f06e11c940d29a1692d527c526
7 files changed +385 -37
docs/superpowers/plans/2026-10-05-phase2-multifile-workspace.md new
+203
@@ -0,0 +1,203 @@
1 +# Phase 2 Multi-file Workspace Implementation Plan
2 +
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4 +
5 +**Goal:** Complete the existing partially implemented multi-file Workspace so an owner can build, review, seal, approve and atomically publish a bounded multi-file Change Set to a dedicated `nexa/edit-*` branch without weakening the current security gates.
6 +
7 +**Architecture:** Reuse the existing schemaVersion 2 Durable Workspace model, multi-file store methods and atomic Git blob/tree/commit orchestration already present on `main`. Finish the user-facing controller/editor/sealing path so every material file is represented in one deterministic immutable intent, and harden reconciliation/security tests around the existing single branch-ref publication point.
8 +
9 +**Tech Stack:** JavaScript ES modules, Node built-in test runner, Cloudflare Workers + Durable Objects, Telegram Bot API/Mini App, GitHub Git Data API.
10 +
11 +**Spec:** `docs/superpowers/specs/2026-10-05-phase2-multifile-workspace-design.md`
12 +
13 +## Global Constraints
14 +
15 +- Owner-only Telegram boundary remains mandatory.
16 +- READ stays owner-only; WRITE/DESTRUCTIVE stay behind central Policy and Safe Approval.
17 +- Kill Switch is checked before mutation and mutation fails closed when Kill Switch state is unreadable.
18 +- No direct default-branch mutation, force update, automatic merge/rebase or silent conflict resolution.
19 +- The only publication point is advancing the dedicated `nexa/edit-<workspaceId>` branch ref after all blobs/tree/commit objects exist.
20 +- Source/draft bodies, secrets and signed approval material never enter callbacks, audit, incident data or logs.
21 +- Single-file Workspace remains compatible as a one-entry Change Set.
22 +- Existing size/path/binary/LFS safety policy remains enforced for every file.
23 +- Every implementation change follows RED → GREEN TDD and lands in small reviewable commits.
24 +
25 +## Review Focus
26 +
27 +- Adding the same normalized path twice must be rejected without changing the Change Set.
28 +- Reordering, adding, removing or editing files after Ready must invalidate the sealed intent and require a fresh approval.
29 +- Mixed changed/unchanged files must seal and publish only a deterministic ordered descriptor set while keeping the aggregate intent stable.
30 +- Failure after Git commit creation but before/around ref creation must reconcile against exact candidate/ref evidence and never publish a different commit.
31 +- Multi-file Editor/API input must remain owner-bound and must never introduce a GitHub provider write path.
32 +
33 +---
34 +
35 +### Task 1: Complete multi-file Change Set controller and views
36 +
37 +**Files:**
38 +- Modify: `src/plugins/github/workspace.js`
39 +- Test: `test/workspace-multifile.test.js`
40 +- Test: `test/workspace-editor-v2.test.js`
41 +
42 +**Interfaces:**
43 +- Consumes: `DurableWorkspaceStoreClient.getWorkspace()`, `upsertWorkspaceFile()`, `updateWorkspaceFileDraft()`, `removeWorkspaceFile()`.
44 +- Produces: controller callbacks that render all Change Set files, allow adding a safe repository file to the existing Workspace, remove a non-final file, and preserve the existing one-file UX.
45 +
46 +- [ ] **Step 1: Write failing controller tests**
47 + - Workspace view with two files lists both paths and a bounded file count.
48 + - A callback for adding a repository file resolves to a READ operation first and performs no provider mutation.
49 + - Removing a file updates durable state and returns to the same Workspace.
50 + - Duplicate path addition is surfaced as a validation error.
51 +
52 +- [ ] **Step 2: Run focused tests**
53 + Run: `node --test test/workspace-multifile.test.js test/workspace-editor-v2.test.js`
54 + Expected: new assertions FAIL because controller/UI only treats the primary file as editable material.
55 +
56 +- [ ] **Step 3: Implement bounded multi-file controller behavior**
57 + Add callback parsing and rendering around existing store methods; keep callback payloads to opaque Workspace/navigation handles and never embed source/draft text.
58 +
59 +- [ ] **Step 4: Run focused tests**
60 + Run: `node --test test/workspace-multifile.test.js test/workspace-editor-v2.test.js`
61 + Expected: PASS.
62 +
63 +- [ ] **Step 5: Commit**
64 + `git commit -am "feat(workspace): expose multi-file change set controls"`
65 +
66 +### Task 2: Make Mini App editor file-aware without adding provider mutation
67 +
68 +**Files:**
69 +- Modify: `src/workspace-editor.js`
70 +- Test: `test/workspace-editor-v2.test.js`
71 +- Test: `test/workspace-editor-worker.test.js`
72 +
73 +**Interfaces:**
74 +- Consumes: Workspace `files[]`, `updateWorkspaceFileDraft({ ownerId, workspaceId, path, text, digest })`.
75 +- Produces: GET response containing bounded file metadata and selected file draft; PUT accepting `workspaceId`, `path`, `text`.
76 +
77 +- [ ] **Step 1: Write failing editor API tests**
78 + - GET returns all file paths plus the selected file.
79 + - PUT for a non-primary path calls only `updateWorkspaceFileDraft`.
80 + - Invalid/non-member path returns an explicit error.
81 + - No GitHub/provider object is accepted or invoked.
82 +
83 +- [ ] **Step 2: Run focused tests**
84 + Run: `node --test test/workspace-editor-v2.test.js test/workspace-editor-worker.test.js`
85 + Expected: FAIL on non-primary selection/save.
86 +
87 +- [ ] **Step 3: Implement file selection**
88 + Extend the editor request/page with a bounded file selector and path-scoped Draft save while preserving Telegram `initData` validation, CSP and existing size limits.
89 +
90 +- [ ] **Step 4: Run focused tests**
91 + Run: `node --test test/workspace-editor-v2.test.js test/workspace-editor-worker.test.js`
92 + Expected: PASS.
93 +
94 +- [ ] **Step 5: Commit**
95 + `git commit -am "feat(workspace): make mini app editor file-aware"`
96 +
97 +### Task 3: Seal deterministic multi-file Ready intents and aggregate Diff
98 +
99 +**Files:**
100 +- Modify: `src/plugins/github/workspace.js`
101 +- Modify: `src/core/workspace-policy.js` only if a focused aggregate helper is needed
102 +- Test: `test/workspace-multifile.test.js`
103 +- Test: `test/workspace-policy.test.js`
104 +- Test: `test/workspace-store.test.js`
105 +
106 +**Interfaces:**
107 +- Consumes: ordered `workspace.files[]`, `digestText()`, existing `sealIntent()`.
108 +- Produces: immutable intent with `files: [{ path, sourceBlobSha, contentDigest }]`, aggregate deterministic `intentDigest`, one `commitMessageDigest`, target branch and exact base SHA/tree SHA.
109 +
110 +- [ ] **Step 1: Write failing sealing/diff tests**
111 + - Two changed files produce one aggregate view and one ordered `files[]` intent.
112 + - File order/list/material change alters the intent digest and invalidates prior Ready.
113 + - Unchanged Change Set cannot Ready.
114 + - Single-file intent stays compatible.
115 +
116 +- [ ] **Step 2: Run focused tests**
117 + Run: `node --test test/workspace-multifile.test.js test/workspace-policy.test.js test/workspace-store.test.js`
118 + Expected: FAIL because current controller seals only legacy primary-file fields.
119 +
120 +- [ ] **Step 3: Implement deterministic Change Set material**
121 + Use the durable `files[]` order, validate every file against existing policy, include only bounded descriptors/digests in the sealed intent, and render per-file plus aggregate Diff without exposing draft bodies outside the normal bounded UI.
122 +
123 +- [ ] **Step 4: Run focused tests**
124 + Run: `node --test test/workspace-multifile.test.js test/workspace-policy.test.js test/workspace-store.test.js`
125 + Expected: PASS.
126 +
127 +- [ ] **Step 5: Commit**
128 + `git commit -am "feat(workspace): seal deterministic multi-file intents"`
129 +
130 +### Task 4: Harden atomic publication, reconciliation and security gates
131 +
132 +**Files:**
133 +- Modify: `src/plugins/github/workspace-commit.js`
134 +- Modify: `src/plugins/github/workspace.js` only for evidence output
135 +- Test: `test/workspace-multifile-commit.test.js`
136 +- Test: `test/kill-switch.test.js`
137 +- Test: `test/approval-flow.test.js`
138 +- Test: `test/audit.test.js`
139 +
140 +**Interfaces:**
141 +- Consumes: existing GitHub `createGitBlob`, `createGitTree`, `createGitCommit`, `createGitBranchRef`, `getGitRef`, exact sealed intent and durable commit state.
142 +- Produces: one deterministic candidate commit and one branch-ref publication result with bounded evidence.
143 +
144 +- [ ] **Step 1: Write failing negative tests**
145 + - Partial blob/tree/commit failure never calls `createGitBranchRef`.
146 + - Ambiguous ref-create failure reconciles only when observed ref equals exact candidate SHA.
147 + - Existing unexpected target ref fails explicitly.
148 + - Changed file list/order/digest after Ready is stale.
149 + - Kill Switch locked/unreadable blocks provider mutation.
150 + - Audit result contains descriptors/digests/SHA only, never source/draft content or approval token.
151 +
152 +- [ ] **Step 2: Run focused tests**
153 + Run: `node --test test/workspace-multifile-commit.test.js test/kill-switch.test.js test/approval-flow.test.js test/audit.test.js`
154 + Expected: any uncovered contract FAILS before production code is changed.
155 +
156 +- [ ] **Step 3: Implement minimal reconciliation/security fixes**
157 + Preserve the branch ref as the only publication point; do not add compensating writes, force updates or default-branch mutation.
158 +
159 +- [ ] **Step 4: Run focused tests**
160 + Run: `node --test test/workspace-multifile-commit.test.js test/kill-switch.test.js test/approval-flow.test.js test/audit.test.js`
161 + Expected: PASS.
162 +
163 +- [ ] **Step 5: Commit**
164 + `git commit -am "fix(workspace): harden atomic multi-file publication"`
165 +
166 +### Task 5: Whole-phase regression, docs and production acceptance gate
167 +
168 +**Files:**
169 +- Modify: `README.md`
170 +- Modify: `docs/OPERATIONS_RUNBOOK.md`
171 +- Modify: `PROJECT_MEMORY.md`
172 +- Create: `docs/PHASE2_MULTIFILE_ACCEPTANCE.md`
173 +- Test: `test/final-acceptance-contract.test.js` or a focused new `test/phase2-multifile-acceptance.test.js`
174 +
175 +**Interfaces:**
176 +- Consumes: all prior task behavior.
177 +- Produces: permanent regression contract and production acceptance record.
178 +
179 +- [ ] **Step 1: Add documentation contract test**
180 + Assert docs state: multi-file Change Set, branch-only publication, exact base SHA, Safe Approval, Kill Switch, no direct `main` mutation, evidence requirements and single-file compatibility.
181 +
182 +- [ ] **Step 2: Run full suite**
183 + Run: `npm test`
184 + Expected: all tests PASS with zero fail/skip/cancelled.
185 +
186 +- [ ] **Step 3: Update operational docs**
187 + Document the multi-file user flow, failure recovery, stale/reseal behavior and production smoke procedure without storing source bodies or secrets.
188 +
189 +- [ ] **Step 4: Re-run full suite**
190 + Run: `npm test`
191 + Expected: all tests PASS.
192 +
193 +- [ ] **Step 5: Commit**
194 + `git commit -am "docs(workspace): record phase 2 multi-file acceptance gate"`
195 +
196 +- [ ] **Step 6: PR and production verification**
197 + Open one Phase 2 PR from the implementation branch. Require exact-head green CI, review the exact diff, merge with expected-head locking, then verify post-merge exact-SHA CI and Cloudflare deploy/runtime evidence.
198 +
199 +- [ ] **Step 7: Owner-device production smoke**
200 + On a safe repository text change set with at least two files: confirm exact aggregate/per-file Diff, enter one commit message, Ready, Safe Approval, verify no provider mutation before approval, then approve and verify one `nexa/edit-*` branch commit contains both intended changes while `main` remains unchanged.
201 +
202 +- [ ] **Step 8: Close acceptance**
203 + Record exact merge SHA, CI run, deploy/version evidence, target branch, resulting commit SHA and owner-device/runtime outcome in `docs/PHASE2_MULTIFILE_ACCEPTANCE.md`. Only then mark Phase 2 complete.
docs/superpowers/specs/2026-10-05-phase2-multifile-workspace-design.md new
+49
@@ -0,0 +1,49 @@
1 +# Phase 2 Multi-file Workspace Design
2 +
3 +## Goal
4 +Extend the production-accepted owner-only Repository Workspace from one-file intents to bounded atomic multi-file Change Sets without weakening branch-first, Safe Approval, replay protection, Kill Switch, fail-closed behavior, or evidence requirements.
5 +
6 +## Scope
7 +Phase 2 adds a multi-file Change Set model and the minimum useful GitHub WRITE orchestration needed to commit that set to a dedicated `nexa/edit-*` branch. It does not add direct default-branch writes, automatic merge/rebase/conflict resolution, RBAC, Level-C autonomy, or AI-driven mutation.
8 +
9 +## User flow
10 +1. Owner opens a repository Workspace at an exact base SHA.
11 +2. Owner adds/edits multiple bounded text files. Each file remains subject to the existing path/content safety policy.
12 +3. Nexa persists drafts owner-scoped in Durable Object state; source/draft bodies never enter callback data, logs, incidents, or audit metadata.
13 +4. Nexa renders per-file and aggregate Diff plus the exact base SHA.
14 +5. Owner supplies one commit message for the complete Change Set.
15 +6. Ready seals an immutable intent containing repository, base SHA, target branch, ordered file descriptors/digests, aggregate digest and commit message digest.
16 +7. Safe Approval binds to that immutable intent. Any material change invalidates Ready and requires a fresh approval.
17 +8. After approval, Nexa revalidates base/material, checks Kill Switch, creates Git objects for all files, builds one tree and one commit, and advances only the dedicated `nexa/edit-*` branch.
18 +9. Nexa verifies the resulting branch/commit and reports evidence. `main` is never mutated by this flow.
19 +
20 +## Atomicity and idempotency
21 +The provider orchestration constructs blobs/tree/commit before the final branch-ref mutation. The branch ref is the single publication point. If any pre-publication operation fails, the branch must not advance. Reconciliation after ambiguous provider/network failure reads the target ref and commit/tree evidence before deciding whether to retry. Repeating the same sealed intent must converge to the same accepted result or an explicit conflict; it must not create a second logical mutation.
22 +
23 +## State model
24 +A Workspace owns a Change Set with bounded file entries. Each entry records path, base blob identity/digest, draft digest and state; bodies remain only in durable Workspace storage. A sealed Ready Intent is immutable and stores only bounded metadata/digests needed for approval and reconciliation. Existing single-file state is migrated/read compatibly rather than discarded.
25 +
26 +## Security invariants
27 +- Telegram private operations remain owner-only.
28 +- READ is owner-only; WRITE/DESTRUCTIVE stay behind central Policy and Safe Approval.
29 +- Kill Switch is evaluated before every provider mutation and fails closed on unreadable durable state.
30 +- Approval remains owner/action/risk/target/expiry-bound and one-time through durable replay protection.
31 +- No direct `main` mutation, force update, auto-merge, auto-rebase, or silent conflict resolution.
32 +- Stale base, changed draft, changed file list/order, changed target or changed commit message invalidates the sealed intent.
33 +- Sensitive paths, binary-like content, Git LFS pointers and configured size ceilings remain rejected.
34 +- Secret/source/draft bodies/signed approval material never enter logs, audit, incident records or callback payloads.
35 +
36 +## Failure and recovery
37 +Validation failures are explicit and preserve the durable Change Set. Provider failures are explicit and never reported as success without fresh evidence. Stale-base or target collision returns the owner to review/reseal rather than mutating around the conflict. A consumed approval is never reused after failure. Recovery routes preserve owner context and offer retry only when the operation can be safely reconciled.
38 +
39 +## Evidence
40 +Every successful WRITE result records bounded non-secret evidence: repository, sealed intent ID/digest, exact base SHA, target branch, resulting commit SHA, action outcome and timestamp. Production acceptance requires exact-SHA CI, deployment evidence, runtime evidence and an owner-device multi-file smoke proving the branch changed as intended while `main` remained unchanged.
41 +
42 +## TDD acceptance
43 +Negative tests must prove: no mutation before approval; Kill Switch blocks mutation; non-owner cannot access; replay fails; stale base fails; changed material after Ready fails; partial provider failure does not advance branch; ambiguous failure reconciles before retry; sensitive/binary/oversized file rejection applies per file; callback/log/audit redaction holds; and `main` is never the target. Positive tests must prove two-or-more-file Change Sets produce one branch commit/tree with all intended file changes and deterministic idempotent reconciliation.
44 +
45 +## Compatibility
46 +Single-file Workspace behavior remains a one-entry Change Set and existing production flows continue to work. Existing Durable Object namespaces and approval semantics are reused; no destructive migration is required.
47 +
48 +## Out of scope
49 +Multi-user RBAC, full multi-project control plane, automatic PR merge, natural-language change requests, browser QA execution, marketplace, Level-C autonomy and broad self-healing remain deferred.
\ No newline at end of file
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)});