Personal Telegram developer console for GitHub

feat/cp3-github-write-final
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
md 512 lines 31.6 KB
Rendered Raw
1 # Repository Workspace / Code Editor 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:** Build an owner-only Telegram repository workspace that can open an eligible text file, create a durable draft, show the exact diff, and create exactly one approval-gated GitHub branch commit without mutating `main`.
6
7 **Architecture:** Keep workspace state in a dedicated owner-scoped Cloudflare Durable Object and keep GitHub provider mutation behind the existing Action Policy, HMAC approval, durable replay guard and audit boundary. New path-safe navigation uses short Durable Object references rather than putting repository paths or source content in Telegram callback data. The commit engine uses Git Data blobs/trees/commits/refs with a sealed immutable commit intent and deterministic commit metadata so retries reconcile to one branch commit and later multi-file workspaces can reuse the same engine.
8
9 **Tech Stack:** JavaScript ES modules, Node 22 test runner (`node --test`), Cloudflare Workers + SQLite-backed Durable Objects, Telegram Bot API, GitHub REST API 2022-11-28.
10
11 **Spec:** `docs/superpowers/specs/2026-10-03-repository-workspace-editor-design.md`
12
13 ## Global Constraints
14
15 - Only the configured Telegram owner may access repository/workspace data.
16 - Existing provider `READ` remains owner-only; provider `WRITE` / `DESTRUCTIVE` remains Safe-Approval gated.
17 - Phase 1 never commits directly to `main` or another repository default branch.
18 - No GitHub Git Data write may start before the approval token is consumed successfully.
19 - Draft/source text must never be placed in Telegram callback data, audit logs, or error logs.
20 - Approval callback data must remain within Telegram's 64-byte limit; existing `ApprovalService.maxTokenLength=56` remains the token ceiling.
21 - Navigation refs are 10 URL-safe random characters, workspace IDs are 10 URL-safe random characters, and commit-intent IDs are exactly 8 URL-safe random characters; all are non-secret and owner-scoped.
22 - Workspace draft TTL is 30 minutes; navigation-ref TTL is 15 minutes; committed intent/result metadata is retained for 24 hours; existing approval TTL remains 120 seconds.
23 - Phase 1 editable content is UTF-8 text with a maximum of 3,000 Unicode characters and 12,000 UTF-8 bytes; over-limit content remains readable but the Edit control is disabled with an explicit reason.
24 - Reject editor writes for Git LFS pointer content and sensitive paths matching `.env`, `.env.*`, `id_rsa`, `id_ed25519`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `credentials.json`, or `service-account*.json` case-insensitively.
25 - Generated target branch is `nexa/edit-<workspaceId>` and Phase 1 fails closed if that ref already exists unexpectedly.
26 - No automatic rebase, merge, conflict resolution, shell execution, binary/LFS editing, or direct-default-branch mutation.
27 - Workspace audit metadata may include IDs, paths, SHAs, counts and digests, but never full source/draft text, provider tokens, Telegram secrets, signing secrets or signed approval tokens.
28 - Every durable implementation checkpoint updates `PROJECT_MEMORY.md`; anything not actually verified is recorded as `NOT VERIFIED`.
29 - Cloudflare configuration keeps the existing declarative Durable Object `exports` model; add `WorkspaceStore` to `exports` with `storage: "sqlite"` and do not add a legacy `migrations` array alongside it.
30
31 ## Review Focus
32
33 1. **Multibyte/oversized Telegram input:** UTF-8 byte limits and Unicode-character limits are both enforced; input is rejected rather than silently truncated. Task 1 and Task 4 tests pin this.
34 2. **Late or duplicate Telegram draft input:** pending-input mode is consumed exactly once and only for the owning workspace; a second message cannot mutate the draft unexpectedly. Task 2 and Task 4 tests pin this.
35 3. **Base branch changes between review and confirmation:** the GitHub write sequence stops before blob/tree/commit creation and marks the intent stale. Task 6 tests pin this.
36 4. **Ambiguous provider result around ref creation:** Nexa re-reads the target ref and treats it as success only when it points to the deterministic expected commit SHA; otherwise it fails closed. Task 5 and Task 6 tests pin this.
37 5. **Target branch already exists or moved:** Phase 1 never overwrites/force-updates it; only an already-reconciled ref pointing to the exact expected commit is accepted. Task 5 and Task 6 tests pin this.
38
39 ---
40
41 ## File Structure
42
43 ### New files
44 - `src/core/workspace-policy.js` — editable-file validation, bounded text normalization, digest helpers and bounded exact line diff.
45 - `src/core/workspace-store.js` — owner-scoped client for the `WORKSPACE_STORE` Durable Object.
46 - `src/durable/workspace-store.js` — durable navigation refs, workspaces, pending-input state, immutable commit intents and committed result state.
47 - `src/plugins/github/workspace.js` — path-safe file/workspace views, local draft routes and approval-gated commit orchestration.
48 - `test/workspace-policy.test.js` — policy/diff bounds and sensitive-file coverage.
49 - `test/workspace-store.test.js` — Durable Object/client ownership, TTL, pending-input and intent-state coverage.
50 - `test/github-workspace-ui.test.js` — navigation, draft, input, diff and ready-to-commit Telegram flow.
51 - `test/github-workspace-provider.test.js` — Git Data read/write request construction and error/reconciliation behavior.
52 - `test/github-workspace-approval.test.js` — compact workspace approval codec and pre-approval no-write contract.
53 - `test/github-workspace-integration.test.js` — end-to-end in-memory draft -> diff -> approval -> one branch commit flow.
54
55 ### Modified files
56 - `src/index.js` — export `WorkspaceStore` alongside `ApprovalReplayGuard`.
57 - `wrangler.jsonc` — bind `WORKSPACE_STORE` to `WorkspaceStore` and declare it as SQLite storage in `exports`.
58 - `src/github.js` — add path-at-ref reads, branch/ref snapshot reads and Git Data write primitives.
59 - `src/plugins/github/manifest.js` — declare workspace actions and increment plugin manifest version.
60 - `src/plugins/github/plugin.js` — route root file browsing and short workspace callbacks to the workspace controller while retaining legacy callbacks for old Telegram messages.
61 - `src/core/router.js` — add message dispatch through the same policy/audit boundary and optional sanitized route audit metadata.
62 - `src/core/approval.js` — add compact workspace commit-intent codec while preserving rerun/cancel codecs and 56-character ceiling.
63 - `src/bot.js` — provide owner identity/workspace client to the plugin, route pending editor text, and generalize approval rendering/source reconstruction beyond workflow-run IDs.
64 - `PROJECT_MEMORY.md` — record each verified TDD/CI/deploy/runtime checkpoint.
65
66 ---
67
68 ### Task 1: Workspace Policy, Digests and Diff
69
70 **Files:**
71 - Create: `src/core/workspace-policy.js`
72 - Create: `test/workspace-policy.test.js`
73 - Modify: `PROJECT_MEMORY.md`
74
75 **Interfaces:**
76 - Produces: `validateEditableFile({ path, text, byteLength? }) -> { editable, reason, text, charLength, byteLength }`.
77 - Produces: `normalizeCommitMessage(value) -> string` with non-empty normalized message <= 120 characters.
78 - Produces: `makeTargetBranch(workspaceId) -> string` returning `nexa/edit-<workspaceId>` after safe-handle validation.
79 - Produces: `digestText(value) -> Promise<string>` returning lowercase 64-hex SHA-256.
80 - Produces: `buildUnifiedDiff({ path, before, after, maxChars = 2600 }) -> { text, additions, deletions, truncated }` with exact line counts and bounded raw diff text. HTML escaping belongs to the Telegram view layer, not this pure function.
81
82 - [ ] **Step 1: Write policy RED tests**
83
84 Add tests named:
85 - `editable file policy accepts bounded UTF-8 text`.
86 - `editable file policy rejects sensitive paths binary markers LFS and both size ceilings`.
87 - `editable file policy counts multibyte UTF-8 bytes instead of JavaScript characters`.
88 - `commit message and target branch normalization fail closed on empty or unsafe values`.
89 - `unified diff reports exact additions deletions and marks bounded truncation without changing counts`.
90 - `digestText is stable for identical content and changes with content`.
91
92 Assert exact limits from Global Constraints, including a multibyte string that is under 3,000 characters but over 12,000 UTF-8 bytes.
93
94 - [ ] **Step 2: Run the focused test and verify RED**
95
96 Run: `node --test test/workspace-policy.test.js`
97
98 Expected: FAIL because `src/core/workspace-policy.js` and exported functions do not exist.
99
100 - [ ] **Step 3: Implement the pure policy module**
101
102 Implement the signatures above without third-party dependencies. `buildUnifiedDiff` operates on complete line arrays, calculates exact additions/deletions before bounding the rendered diff, and returns raw text for the UI to escape.
103
104 - [ ] **Step 4: Run focused + full regression tests**
105
106 Run: `node --test test/workspace-policy.test.js && npm test`
107
108 Expected: workspace tests PASS and all existing tests PASS with 0 fail/skip/cancelled.
109
110 - [ ] **Step 5: Record checkpoint and commit**
111
112 Update `PROJECT_MEMORY.md` with Task 1 RED/GREEN evidence and `NOT VERIFIED` production status.
113
114 Commit: `feat: add workspace edit policy and diff`
115
116 ---
117
118 ### Task 2: Durable Owner-Scoped Workspace Store
119
120 **Files:**
121 - Create: `src/core/workspace-store.js`
122 - Create: `src/durable/workspace-store.js`
123 - Create: `test/workspace-store.test.js`
124 - Modify: `src/index.js`
125 - Modify: `wrangler.jsonc`
126 - Modify: `PROJECT_MEMORY.md`
127
128 **Interfaces:**
129 - `DurableWorkspaceStoreClient({ namespace, now? })` scopes one Durable Object by `namespace.idFromName(ownerId)`.
130 - `isConfigured() -> boolean`.
131 - `createNavigationRefs({ ownerId, refs, ttlMs = 900000 }) -> [{ refId }]` where each stored ref contains only `repoId`, `path`, `type`, `sha` and expiry.
132 - `resolveNavigationRef({ ownerId, refId }) -> ref | null`.
133 - `createWorkspace({ ownerId, repoId, repoFullName, baseBranch, baseHeadSha, baseTreeSha, path, blobSha, originalText, originalDigest, expiresAt }) -> workspace`.
134 - `getWorkspace({ ownerId, workspaceId }) -> workspace | null`.
135 - `updateDraft({ ownerId, workspaceId, text, digest }) -> workspace`; only a materially changed draft invalidates an existing READY intent.
136 - `setPendingInput({ ownerId, workspaceId, mode })`, `getPendingInput({ ownerId })`, `consumePendingInput({ ownerId, workspaceId, mode })` where mode is `draft` or `commit_message` and consume is one-time.
137 - `setCommitMessage({ ownerId, workspaceId, message, digest }) -> workspace`; only a materially changed message invalidates an existing READY intent.
138 - `sealIntent({ ownerId, workspaceId, intent }) -> intent` creates immutable `intent:<intentId>` and moves workspace to `READY`; when the canonical material digest is unchanged, it reuses the existing READY/COMMITTED intent instead of minting a new intent ID.
139 - `getIntent({ ownerId, intentId }) -> intent | null`.
140 - `beginCommit({ ownerId, intentId }) -> { disposition: 'start'|'resume'|'committed', intent }` atomically moves `READY -> COMMITTING`, returns `resume` for existing `COMMITTING`, and returns recorded result for `COMMITTED`.
141 - `setCandidateCommit({ ownerId, intentId, commitSha })`.
142 - `completeCommit({ ownerId, intentId, commitSha, branch }) -> intent` atomically records `COMMITTED`.
143 - `markStale({ ownerId, intentId, reason })`.
144 - `cancelWorkspace({ ownerId, workspaceId })`.
145
146 - [ ] **Step 1: Write Durable Object/client RED tests**
147
148 Cover:
149 - owner A cannot resolve owner B refs/workspaces;
150 - expired refs/workspaces read as missing and cleanup is scheduled;
151 - pending input is consumed once and duplicate/late messages are rejected;
152 - materially changed draft/message invalidates old READY intent while identical values do not;
153 - sealing identical material twice returns the same intent ID;
154 - sealIntent is immutable after creation;
155 - beginCommit is atomic and returns `committed` after success;
156 - committed result retains exact SHA/branch for idempotent retries;
157 - missing `WORKSPACE_STORE` fails closed.
158
159 - [ ] **Step 2: Run RED test**
160
161 Run: `node --test test/workspace-store.test.js`
162
163 Expected: FAIL because store/client/binding do not exist.
164
165 - [ ] **Step 3: Implement client + Durable Object**
166
167 Use one owner-named Durable Object instance. Store keys as `ref:<id>`, `ws:<id>`, `intent:<id>`, and one `pending` record. Generate 10-character navigation/workspace handles and 8-character intent handles from cryptographically random URL-safe bytes; do not use source text in IDs. Alarm cleanup removes expired refs/workspaces while retaining committed intent metadata for 24 hours to support reconciliation/idempotent retry.
168
169 - [ ] **Step 4: Wire Worker configuration**
170
171 Export `WorkspaceStore` from `src/index.js`. In `wrangler.jsonc`, add binding `{ "name": "WORKSPACE_STORE", "class_name": "WorkspaceStore" }` and declarative export `"WorkspaceStore": { "type": "durable-object", "storage": "sqlite" }`. Keep the existing `exports` lifecycle model; do not add `migrations`.
172
173 - [ ] **Step 5: Run focused + full tests**
174
175 Run: `node --test test/workspace-store.test.js && npm test`
176
177 Expected: 0 failures.
178
179 - [ ] **Step 6: Record checkpoint and commit**
180
181 Update `PROJECT_MEMORY.md` with RED/GREEN evidence and note that the new binding is `NOT VERIFIED` in production until deployment.
182
183 Commit: `feat: add durable repository workspace store`
184
185 ---
186
187 ### Task 3: Path-Safe File Navigation and Draft Creation
188
189 **Files:**
190 - Create: `src/plugins/github/workspace.js`
191 - Create: `test/github-workspace-ui.test.js`
192 - Modify: `src/github.js`
193 - Modify: `src/plugins/github/manifest.js`
194 - Modify: `src/plugins/github/plugin.js`
195 - Modify: `src/bot.js`
196 - Modify: `PROJECT_MEMORY.md`
197
198 **Interfaces:**
199 - Extend `GitHubService.listFiles(repoRef, path = '', { ref } = {})` without breaking existing callers.
200 - Add `getBranchSnapshot(repoRef, branch) -> { branch, headSha, treeSha }`.
201 - Add `getFileAtRef(repoRef, path, ref) -> { path, sha, size, encoding, content }` using the Contents API at the pinned ref.
202 - Add `createWorkspaceController({ github, workspaces })` returning route helpers used by `plugin.js`.
203 - New callback families remain <=64 bytes: `wnav:<refId>`, `wedit:<refId>`, `ws:<workspaceId>`, `wtext:<workspaceId>`, `wmsg:<workspaceId>`, `wdiff:<workspaceId>`, `wready:<workspaceId>`, `wcancel:<workspaceId>`.
204 - `plugin.resolveCallback(data, context)` consumes `context.ownerId` for workspace routes; no workspace/provider read happens before central policy evaluation.
205
206 - [ ] **Step 1: Write navigation/draft RED tests**
207
208 Cover:
209 - exact `files:<repoId>` is routed after policy to the new path-safe browser;
210 - visible file/directory buttons contain short refs, never raw long paths;
211 - a nested directory resolves through `wnav:<refId>` and still preserves full path server-side;
212 - an eligible text file view shows `✏️ Edit`;
213 - oversized/sensitive/LFS file view stays readable but gives the exact edit-disabled reason;
214 - `wedit:<refId>` pins current default-branch HEAD/tree and file blob/content before durable draft creation;
215 - archived repositories cannot create editable drafts;
216 - callbacks remain <=64 bytes;
217 - old `tree:`/`blob:` and old path-bearing `files:` Telegram callbacks continue to render through the legacy MenuManager path.
218
219 - [ ] **Step 2: Run RED tests**
220
221 Run: `node --test test/github-workspace-ui.test.js`
222
223 Expected: FAIL on missing workspace routes/provider readers.
224
225 - [ ] **Step 3: Implement provider read helpers**
226
227 `getBranchSnapshot` reads `git/ref/heads/<branch>` then the referenced Git commit to obtain `tree.sha`. `getFileAtRef` requests `/contents/<path>?ref=<full head SHA>`, rejects directory/non-file responses, checks path and provider-reported size first, then decodes base64 with fatal UTF-8 handling, and finally runs content/LFS/edit-size policy. Preserve the provider blob SHA.
228
229 - [ ] **Step 4: Implement path-safe browser/controller**
230
231 After the READ policy is allowed, list the directory by path, batch-store short navigation refs in `WORKSPACE_STORE`, and render `wnav` callbacks. File views resolve refs only after policy. Draft creation fetches the latest default-branch snapshot and exact file at that full SHA, then stores the original text/digest in the workspace; no GitHub write occurs.
232
233 - [ ] **Step 5: Wire owner context and manifest**
234
235 Pass `{ isOwner: true, ownerId: String(ownerId) }` from `NexaDevBot` callback dispatch. Register workspace navigation/create/view/diff/local-draft action IDs as owner-only `READ` risk because they do not mutate GitHub. Increment GitHub plugin manifest version.
236
237 - [ ] **Step 6: Run focused + full tests**
238
239 Run: `node --test test/github-workspace-ui.test.js && npm test`
240
241 Expected: 0 failures and existing legacy file-browser tests remain green.
242
243 - [ ] **Step 7: Record checkpoint and commit**
244
245 Update `PROJECT_MEMORY.md` with RED/GREEN evidence.
246
247 Commit: `feat: add path-safe editor workspace entry`
248
249 ---
250
251 ### Task 4: Telegram Draft Input, Diff and Sealed Intent UX
252
253 **Files:**
254 - Modify: `src/core/router.js`
255 - Modify: `src/plugins/github/workspace.js`
256 - Modify: `src/plugins/github/plugin.js`
257 - Modify: `src/bot.js`
258 - Modify: `test/github-workspace-ui.test.js`
259 - Create: `test/github-workspace-integration.test.js`
260 - Modify: `PROJECT_MEMORY.md`
261
262 **Interfaces:**
263 - Add `PluginRouter.dispatchMessage(payload, context = {})` using plugin resolver name `resolveMessage` and the same policy/audit path as commands/callbacks.
264 - `plugin.resolveMessage({ pending, text }, context)` owns only pending workspace input modes.
265 - `wtext:<workspaceId>` sets pending mode `draft`; the next owner text replaces the whole Phase-1 draft exactly if it satisfies the 3,000-char/12,000-byte bounds.
266 - `wmsg:<workspaceId>` sets pending mode `commit_message`; next owner text passes `normalizeCommitMessage`.
267 - `wdiff:<workspaceId>` returns bounded exact diff with additions/deletions and no provider mutation; the Telegram view HTML-escapes `buildUnifiedDiff().text` before rendering.
268 - `wready:<workspaceId>` requires non-empty changed draft + commit message, computes/stores content/message/intent digests, fixed commit timestamp, target branch and immutable intent, then renders `✅ تأیید و Commit` with `wscommit:<repoId>:<intentId>`.
269
270 - [ ] **Step 1: Extend RED tests for text input and ready state**
271
272 Assert:
273 - pressing draft/message input buttons does not call GitHub;
274 - one pending input consumes one message and a second late message falls back to normal bot behavior;
275 - multibyte/oversized input is visibly rejected without mutating the old draft;
276 - diff HTML is escaped and rendered text is bounded while counts/digest use complete content;
277 - no-change draft cannot become READY;
278 - materially changing draft or commit message after READY invalidates old intent;
279 - pressing Ready twice without material changes reuses the same intent ID;
280 - `wready` renders only a short `wscommit` callback.
281
282 - [ ] **Step 2: Run RED**
283
284 Run: `node --test test/github-workspace-ui.test.js test/github-workspace-integration.test.js`
285
286 Expected: FAIL because message dispatch/pending modes/intent sealing are not implemented.
287
288 - [ ] **Step 3: Add policy-routed message dispatch**
289
290 Add `dispatchMessage` to `PluginRouter`. In `NexaDevBot.handleMessage`, preserve `/start`, `/menu`, `/repos`, `/status` precedence; after commands, read owner pending-input metadata from the local Durable Object and dispatch the message through the plugin router. Source text must not be added to audit metadata.
291
292 - [ ] **Step 4: Implement draft/message/diff/ready views**
293
294 Keep all workspace rendering in `workspace.js`; return explicit edit limits and state. Seal intent with stable fields: `repoId`, `workspaceId`, `baseBranch`, `baseHeadSha`, `baseTreeSha`, `path`, `sourceBlobSha`, `contentDigest`, `commitMessageDigest`, `targetBranch`, `commitTimestamp`, and one `intentDigest` over the canonical material fields.
295
296 - [ ] **Step 5: Run focused + full tests**
297
298 Run: `node --test test/github-workspace-ui.test.js test/github-workspace-integration.test.js && npm test`
299
300 Expected: 0 failures.
301
302 - [ ] **Step 6: Record checkpoint and commit**
303
304 Update `PROJECT_MEMORY.md` and explicitly keep provider commit `NOT VERIFIED` because no GitHub mutation exists yet.
305
306 Commit: `feat: add workspace draft and diff flow`
307
308 ---
309
310 ### Task 5: GitHub Git Data Commit Primitives
311
312 **Files:**
313 - Modify: `src/github.js`
314 - Create: `test/github-workspace-provider.test.js`
315 - Modify: `PROJECT_MEMORY.md`
316
317 **Interfaces:**
318 - Extend `requestJson(..., { allowNotFound = false })` so only HTTP 404 may return `null` when requested; all other provider errors still throw.
319 - `getGitRef(repoRef, branch, { allowMissing = false } = {}) -> { branch, sha } | null`.
320 - `createGitBlob(repoRef, text) -> { sha }` via `POST /git/blobs` with `encoding:'utf-8'`.
321 - `createGitTree(repoRef, { baseTreeSha, entries }) -> { sha }`, where `entries` is multi-file capable `[{ path, mode:'100644', type:'blob', sha }]`.
322 - `createGitCommit(repoRef, { message, treeSha, parentSha, timestamp }) -> { sha }` via `POST /git/commits`, with deterministic `author` and `committer` both `{ name:'Nexa Dev Bot', email:'nexa-dev-bot@users.noreply.github.com', date: timestamp }`.
323 - `createGitBranchRef(repoRef, { branch, sha }) -> { ref, sha }` via `POST /git/refs` with `refs/heads/<branch>`.
324
325 - [ ] **Step 1: Write provider RED tests**
326
327 Assert exact HTTP method/URL/body for every primitive, including branch names containing `/`, full 40-hex validation, multi-file tree entries, deterministic commit identity/timestamp, 404 missing-ref behavior and normal 403/409/422 propagation.
328
329 Add the Review Focus case: a target ref lookup returns an existing different SHA and no update/force endpoint is called.
330
331 - [ ] **Step 2: Run RED**
332
333 Run: `node --test test/github-workspace-provider.test.js`
334
335 Expected: FAIL on missing methods.
336
337 - [ ] **Step 3: Implement minimal Git Data methods**
338
339 Reuse `getRepositoryContext`, `requestJson`, full-SHA validation and URL path-segment encoding. Do not add a force-update-ref primitive in Phase 1.
340
341 - [ ] **Step 4: Verify deterministic retry primitives**
342
343 Test that the same parent/tree/message/timestamp produces identical Git commit request bodies. Blob/tree/commit creation can therefore be retried after an ambiguous transport result without changing the intended Git object identity.
344
345 - [ ] **Step 5: Run focused + full tests**
346
347 Run: `node --test test/github-workspace-provider.test.js && npm test`
348
349 Expected: 0 failures.
350
351 - [ ] **Step 6: Record checkpoint and commit**
352
353 Update `PROJECT_MEMORY.md` with RED/GREEN evidence; provider writes remain `NOT VERIFIED` live.
354
355 Commit: `feat: add github workspace commit primitives`
356
357 ---
358
359 ### Task 6: Safe Approval, Idempotent Commit Orchestration and Audit
360
361 **Files:**
362 - Modify: `src/core/approval.js`
363 - Modify: `src/core/router.js`
364 - Modify: `src/plugins/github/manifest.js`
365 - Modify: `src/plugins/github/plugin.js`
366 - Modify: `src/plugins/github/workspace.js`
367 - Modify: `src/bot.js`
368 - Create: `test/github-workspace-approval.test.js`
369 - Modify: `test/github-workspace-integration.test.js`
370 - Modify: `PROJECT_MEMORY.md`
371
372 **Interfaces:**
373 - Add compact codec for `github.workspace.commit_branch` with action code `e`, `repoId` as base36 and exactly 8-character URL-safe `intentId`; preserve existing `r`/`c` codecs and the 56-character token maximum.
374 - `approvalSourceCallback(payload)` supports workspace input `{ repoId, intentId }` -> `wscommit:<repoId>:<intentId>`.
375 - Generalize approval UI metadata to accept `cancelCallback`; workflow-run approvals keep their existing Run fallback, while the workspace write route uses `repo:<repoId>` as its cancel fallback so approval preparation needs no pre-policy Durable Object read.
376 - Register `github.workspace.commit_branch` as `WRITE`.
377 - `commitWorkspaceIntent({ github, workspaces, ownerId, repoId, intentId }) -> { commitSha, branch, idempotent }`.
378 - Plugin route `wscommit:<repoId>:<intentId>` returns approval metadata before execution; provider calls remain deferred until approved dispatch.
379 - Route may supply sanitized `audit` metadata; Router merges only these safe fields into action attempt/result events.
380
381 - [ ] **Step 1: Write approval/orchestration RED tests**
382
383 Cover:
384 - workspace approval token stays <=56 bytes, verifies owner/action/risk/repo/intent, expires and rejects replay;
385 - clicking `wscommit` before approval performs zero GitHub Git Data writes;
386 - approval binds the immutable intent ID; changed draft/message causes old intent execution to fail closed;
387 - approved action re-reads base HEAD and creates zero Git objects when it changed;
388 - approved action rejects an unexpected existing target branch;
389 - successful path is exactly blob -> tree -> commit -> branch ref -> durable `COMMITTED` result;
390 - replayed approval performs zero second writes;
391 - fresh approval for an already `COMMITTED` intent returns recorded SHA with zero provider writes;
392 - if create-ref returns an ambiguous/409/422 error, orchestration reads the ref: same expected commit => mark success, different/missing => error;
393 - `COMMITTING` retry with stored candidate SHA reconciles before any new branch ref creation;
394 - audit contains workspace/intent/repo/path/digest/SHA metadata but never original/draft source or signed token.
395
396 - [ ] **Step 2: Run RED**
397
398 Run: `node --test test/github-workspace-approval.test.js test/github-workspace-integration.test.js`
399
400 Expected: FAIL on codec, route and commit orchestration.
401
402 - [ ] **Step 3: Add compact approval codec without regressing Actions approvals**
403
404 Implement a dedicated workspace-intent compact encoding branch rather than expanding generic JSON. Reject malformed/non-8-character intent IDs. Re-run existing `test/approval*.test.js` together with workspace approval tests and assert the final callback data remains <=64 bytes.
405
406 - [ ] **Step 4: Implement commit orchestration**
407
408 Algorithm:
409 1. load immutable owner-scoped intent and call `beginCommit`;
410 2. return recorded result immediately for `COMMITTED`;
411 3. re-read base branch snapshot and require exact `baseHeadSha` before object creation;
412 4. if a stored candidate commit exists, read target ref first and reconcile exact SHA before any further ref write;
413 5. otherwise require the target ref to be absent before object creation;
414 6. create content blob, tree and deterministic commit; persist candidate commit SHA before ref creation;
415 7. create target branch ref;
416 8. on provider ambiguity, re-read ref and accept only exact candidate SHA;
417 9. persist `COMMITTED` result before returning Telegram success.
418
419 No force update, default-branch update or retry with changed material is allowed.
420
421 - [ ] **Step 5: Generalize approval/error UI and add CI handoff**
422
423 Success view shows exact provider commit SHA + branch and buttons for `🧪 CI / Actions` and repository/workspace navigation. Workspace stale/provider-failure views show explicit reason and never use the old Actions-specific 403 copy.
424
425 - [ ] **Step 6: Run all security, approval and integration tests**
426
427 Run: `node --test test/approval*.test.js test/security.test.js test/github-workspace-approval.test.js test/github-workspace-integration.test.js && npm test`
428
429 Expected: all tests PASS, 0 fail/skip/cancelled.
430
431 - [ ] **Step 7: Record checkpoint and commit**
432
433 Update `PROJECT_MEMORY.md` with RED/GREEN evidence and mark live GitHub commit as `NOT VERIFIED` until owner-device production smoke.
434
435 Commit: `feat: add safe approval gated workspace commits`
436
437 ---
438
439 ### Task 7: Whole-Branch Verification, Deployment and Owner-Device Production Acceptance
440
441 **Files:**
442 - Modify: `PROJECT_MEMORY.md`
443 - Modify: `README.md` only if user-facing workflow documentation is missing after implementation review.
444
445 **Interfaces:**
446 - Consumes all prior tasks.
447 - Produces production-acceptance evidence; no new product interface should be invented in this task.
448
449 - [ ] **Step 1: Run fresh full local/CI-equivalent verification**
450
451 Run: `npm test`
452
453 Expected: every discovered `test/*.test.js` passes; 0 fail/skip/cancelled.
454
455 Run static secret-pattern checks over changed source/docs for `ghp_`, `github_pat_`, Telegram bot-token patterns and accidental signed `approve:` payload logging. Expected: no secrets.
456
457 - [ ] **Step 2: Review exact branch diff against the spec and acceptance criteria**
458
459 Verify line-by-line that Phase 1 includes: owner isolation, path-safe file navigation, eligible-file policy, durable draft, exact diff, branch-first target, stale-base protection, no pre-approval Git write, one-time approval, idempotent committed result, visible provider errors, exact SHA feedback and CI handoff. Anything missing returns to the owning task before merge.
460
461 - [ ] **Step 3: Merge only a reviewed green head and verify exact post-merge CI**
462
463 After the plan-approved implementation branch is reviewed, merge the exact head to `main`. Record main merge SHA and post-merge CI run ID in `PROJECT_MEMORY.md`. Do not treat PR CI alone as production acceptance.
464
465 - [ ] **Step 4: Verify Cloudflare deploy and new Durable Object binding**
466
467 Verify deploy checked out the exact main merge SHA. Verify active Worker version at 100% traffic and confirm both `APPROVAL_REPLAY_GUARD` and `WORKSPACE_STORE` bindings/classes are present. If binding/class deployment fails, stop before owner smoke and fix the configuration.
468
469 - [ ] **Step 5: Owner-device pre-approval smoke on a safe branch-only edit**
470
471 Use Telegram to open `davoodmehraban89/nexa-dev-bot` -> Files -> an eligible harmless text file (recommended `README.md`) -> Edit. Replace a tiny bounded portion so the diff is unmistakable; set commit message `test: verify nexa mobile editor`.
472
473 Before pressing Confirm, verify from GitHub that `nexa/edit-<workspaceId>` does not exist and `main` is unchanged. Verify Cloudflare audit shows draft/diff/approval-issued metadata only and no `github.workspace.commit_branch` success/provider mutation.
474
475 - [ ] **Step 6: Owner confirms Safe Approval and verify one provider commit**
476
477 Owner presses `✅ تأیید و Commit` while the 120-second approval is valid. Verify GitHub target branch now exists with exactly one new commit parented to the pinned base HEAD, the changed path/diff matches the reviewed draft, and `main` remains unchanged. Verify Telegram shows the same commit SHA/branch that GitHub reports.
478
479 - [ ] **Step 7: Verify replay and fresh-retry idempotency**
480
481 Reusing the same approval callback must be rejected by `APPROVAL_REPLAY_GUARD`. Re-opening the already committed workspace and requesting confirmation again for unchanged material must reuse the same intent and return the recorded commit SHA without a second commit/ref movement. Compare GitHub branch history before/after.
482
483 - [ ] **Step 8: Verify Cloudflare runtime/audit agreement**
484
485 Telemetry must show the same workspace/intent/action lifecycle and resulting commit SHA without full source/draft contents or secrets. Check for runtime exceptions around the smoke window.
486
487 - [ ] **Step 9: Close production acceptance in project memory**
488
489 Update `PROJECT_MEMORY.md` with exact merge SHA, CI/deploy run IDs, active Cloudflare version, owner-device evidence, branch/commit SHA, replay/idempotency evidence and every item still `NOT VERIFIED`.
490
491 Commit the checkpoint through the normal reviewed branch/PR flow; do not mutate production docs directly without CI.
492
493 ---
494
495 ## Execution Order and Stop Conditions
496
497 1. Tasks 1-2 establish pure policy + durable state and may not call GitHub WRITE.
498 2. Tasks 3-4 establish a complete mobile draft/diff flow with no provider mutation.
499 3. Task 5 adds provider primitives but does not expose them to Telegram.
500 4. Task 6 is the only task that connects those primitives to an approval-gated provider WRITE.
501 5. Task 7 is the only production-acceptance gate.
502
503 Stop and fail closed if any of these occur:
504 - source/path/workspace ownership cannot be proven;
505 - `WORKSPACE_STORE` is missing or unhealthy;
506 - base HEAD changed;
507 - target branch exists at a different SHA;
508 - draft or commit message changed after intent sealing;
509 - approval token is missing/expired/replayed/mismatched;
510 - provider result cannot be reconciled to the exact expected commit/ref;
511 - full source/draft content appears in audit logs;
512 - exact deployed main SHA cannot be proven.