Personal Telegram developer console for GitHub

docs: plan repository workspace editor

davoodmehraban89 committed Oct 3, 2026 at 12:14 UTC 5d3011b6d08d072e378aa0f2dbf0bdc82713d7d6
1 file changed +509
docs/superpowers/plans/2026-10-03-repository-workspace-editor.md new
+509
@@ -0,0 +1,509 @@
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 +- Workspace IDs and navigation refs are random non-secret handles; every store operation is owner-scoped.
22 +- Workspace draft TTL is 30 minutes; navigation-ref TTL is 15 minutes; 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, single bounded 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 rendered text.
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 escapes no data and marks bounded truncation`.
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 line arrays, counts the full before/after change exactly, and bounds only the rendered diff text; it never truncates input before calculating counts/digest.
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` and invalidates any previously sealed pending intent for later approval.
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`.
138 +- `sealIntent({ ownerId, workspaceId, intent }) -> intent` creates immutable `intent:<intentId>` and moves workspace to `READY`.
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 +- updateDraft invalidates old READY intent state;
153 +- sealIntent is immutable;
154 +- beginCommit is atomic and returns `committed` after success;
155 +- committed result retains exact SHA/branch for idempotent retries;
156 +- missing `WORKSPACE_STORE` fails closed.
157 +
158 +- [ ] **Step 2: Run RED test**
159 +
160 +Run: `node --test test/workspace-store.test.js`
161 +
162 +Expected: FAIL because store/client/binding do not exist.
163 +
164 +- [ ] **Step 3: Implement client + Durable Object**
165 +
166 +Use one owner-named Durable Object instance. Store keys as `ref:<id>`, `ws:<id>`, `intent:<id>`, and one `pending` record. Generate navigation/workspace/intent handles with `crypto.getRandomValues`; 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.
167 +
168 +- [ ] **Step 4: Wire Worker configuration**
169 +
170 +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`.
171 +
172 +- [ ] **Step 5: Run focused + full tests**
173 +
174 +Run: `node --test test/workspace-store.test.js && npm test`
175 +
176 +Expected: 0 failures.
177 +
178 +- [ ] **Step 6: Record checkpoint and commit**
179 +
180 +Update `PROJECT_MEMORY.md` with RED/GREEN evidence and note that the new binding is `NOT VERIFIED` in production until deployment.
181 +
182 +Commit: `feat: add durable repository workspace store`
183 +
184 +---
185 +
186 +### Task 3: Path-Safe File Navigation and Draft Creation
187 +
188 +**Files:**
189 +- Create: `src/plugins/github/workspace.js`
190 +- Create: `test/github-workspace-ui.test.js`
191 +- Modify: `src/github.js`
192 +- Modify: `src/plugins/github/manifest.js`
193 +- Modify: `src/plugins/github/plugin.js`
194 +- Modify: `src/bot.js`
195 +- Modify: `PROJECT_MEMORY.md`
196 +
197 +**Interfaces:**
198 +- Extend `GitHubService.listFiles(repoRef, path = '', { ref } = {})` without breaking existing callers.
199 +- Add `getBranchSnapshot(repoRef, branch) -> { branch, headSha, treeSha }`.
200 +- Add `getFileAtRef(repoRef, path, ref) -> { path, sha, size, encoding, content }` using the Contents API at the pinned ref.
201 +- Add `createWorkspaceController({ github, workspaces })` returning route helpers used by `plugin.js`.
202 +- New callback families remain <=64 bytes: `wnav:<refId>`, `wedit:<refId>`, `ws:<workspaceId>`, `wtext:<workspaceId>`, `wmsg:<workspaceId>`, `wdiff:<workspaceId>`, `wready:<workspaceId>`, `wcancel:<workspaceId>`.
203 +- `plugin.resolveCallback(data, context)` consumes `context.ownerId` for workspace routes; no workspace/provider read happens before central policy evaluation.
204 +
205 +- [ ] **Step 1: Write navigation/draft RED tests**
206 +
207 +Cover:
208 +- `files:<repoId>` is routed after policy to the new path-safe browser;
209 +- visible file/directory buttons contain short refs, never raw long paths;
210 +- a nested directory resolves through `wnav:<refId>` and still preserves full path server-side;
211 +- an eligible text file view shows `✏️ Edit`;
212 +- oversized/sensitive/LFS file view stays readable but gives the exact edit-disabled reason;
213 +- `wedit:<refId>` pins current default-branch HEAD/tree and file blob/content before durable draft creation;
214 +- archived repositories cannot create editable drafts;
215 +- callbacks remain <=64 bytes;
216 +- old `tree:`/`blob:` Telegram callbacks continue to render through the legacy MenuManager path.
217 +
218 +- [ ] **Step 2: Run RED tests**
219 +
220 +Run: `node --test test/github-workspace-ui.test.js`
221 +
222 +Expected: FAIL on missing workspace routes/provider readers.
223 +
224 +- [ ] **Step 3: Implement provider read helpers**
225 +
226 +`getBranchSnapshot` reads `git/ref/heads/<branch>` then the referenced Git commit to obtain `tree.sha`. `getFileAtRef` requests `/contents/<path>?ref=<full head SHA>` and rejects directory/non-file responses. Preserve raw blob SHA and decode only after editable-file validation.
227 +
228 +- [ ] **Step 4: Implement path-safe browser/controller**
229 +
230 +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.
231 +
232 +- [ ] **Step 5: Wire owner context and manifest**
233 +
234 +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.
235 +
236 +- [ ] **Step 6: Run focused + full tests**
237 +
238 +Run: `node --test test/github-workspace-ui.test.js && npm test`
239 +
240 +Expected: 0 failures and existing legacy file-browser tests remain green.
241 +
242 +- [ ] **Step 7: Record checkpoint and commit**
243 +
244 +Update `PROJECT_MEMORY.md` with RED/GREEN evidence.
245 +
246 +Commit: `feat: add path-safe editor workspace entry`
247 +
248 +---
249 +
250 +### Task 4: Telegram Draft Input, Diff and Sealed Intent UX
251 +
252 +**Files:**
253 +- Modify: `src/core/router.js`
254 +- Modify: `src/plugins/github/workspace.js`
255 +- Modify: `src/plugins/github/plugin.js`
256 +- Modify: `src/bot.js`
257 +- Modify: `test/github-workspace-ui.test.js`
258 +- Create: `test/github-workspace-integration.test.js`
259 +- Modify: `PROJECT_MEMORY.md`
260 +
261 +**Interfaces:**
262 +- Add `PluginRouter.dispatchMessage(payload, context = {})` using plugin resolver name `resolveMessage` and the same policy/audit path as commands/callbacks.
263 +- `plugin.resolveMessage({ pending, text }, context)` owns only pending workspace input modes.
264 +- `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.
265 +- `wmsg:<workspaceId>` sets pending mode `commit_message`; next owner text passes `normalizeCommitMessage`.
266 +- `wdiff:<workspaceId>` returns bounded exact diff with additions/deletions and no provider mutation.
267 +- `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>`.
268 +
269 +- [ ] **Step 1: Extend RED tests for text input and ready state**
270 +
271 +Assert:
272 +- pressing draft/message input buttons does not call GitHub;
273 +- one pending input consumes one message and a second late message falls back to normal bot behavior;
274 +- multibyte/oversized input is visibly rejected without mutating the old draft;
275 +- diff HTML is escaped and rendered text is bounded while counts/digest use complete content;
276 +- no-change draft cannot become READY;
277 +- changing draft or commit message after READY invalidates old intent;
278 +- `wready` creates an immutable intent and renders only a short `wscommit` callback.
279 +
280 +- [ ] **Step 2: Run RED**
281 +
282 +Run: `node --test test/github-workspace-ui.test.js test/github-workspace-integration.test.js`
283 +
284 +Expected: FAIL because message dispatch/pending modes/intent sealing are not implemented.
285 +
286 +- [ ] **Step 3: Add policy-routed message dispatch**
287 +
288 +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.
289 +
290 +- [ ] **Step 4: Implement draft/message/diff/ready views**
291 +
292 +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.
293 +
294 +- [ ] **Step 5: Run focused + full tests**
295 +
296 +Run: `node --test test/github-workspace-ui.test.js test/github-workspace-integration.test.js && npm test`
297 +
298 +Expected: 0 failures.
299 +
300 +- [ ] **Step 6: Record checkpoint and commit**
301 +
302 +Update `PROJECT_MEMORY.md` and explicitly keep provider commit `NOT VERIFIED` because no GitHub mutation exists yet.
303 +
304 +Commit: `feat: add workspace draft and diff flow`
305 +
306 +---
307 +
308 +### Task 5: GitHub Git Data Commit Primitives
309 +
310 +**Files:**
311 +- Modify: `src/github.js`
312 +- Create: `test/github-workspace-provider.test.js`
313 +- Modify: `PROJECT_MEMORY.md`
314 +
315 +**Interfaces:**
316 +- Extend `requestJson(..., { allowNotFound = false })` so only HTTP 404 may return `null` when requested; all other provider errors still throw.
317 +- `getGitRef(repoRef, branch, { allowMissing = false } = {}) -> { branch, sha } | null`.
318 +- `createGitBlob(repoRef, text) -> { sha }` via `POST /git/blobs` with `encoding:'utf-8'`.
319 +- `createGitTree(repoRef, { baseTreeSha, entries }) -> { sha }`, where `entries` is multi-file capable `[{ path, mode:'100644', type:'blob', sha }]`.
320 +- `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 }`.
321 +- `createGitBranchRef(repoRef, { branch, sha }) -> { ref, sha }` via `POST /git/refs` with `refs/heads/<branch>`.
322 +
323 +- [ ] **Step 1: Write provider RED tests**
324 +
325 +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.
326 +
327 +Add the Review Focus case: a target ref lookup returns an existing different SHA and no update/force endpoint is called.
328 +
329 +- [ ] **Step 2: Run RED**
330 +
331 +Run: `node --test test/github-workspace-provider.test.js`
332 +
333 +Expected: FAIL on missing methods.
334 +
335 +- [ ] **Step 3: Implement minimal Git Data methods**
336 +
337 +Reuse `getRepositoryContext`, `requestJson`, full-SHA validation and URL path-segment encoding. Do not add a force-update-ref primitive in Phase 1.
338 +
339 +- [ ] **Step 4: Verify deterministic retry primitives**
340 +
341 +Test that the same parent/tree/message/timestamp produces identical Git commit request bodies, allowing retries to resolve the same Git object SHA from GitHub.
342 +
343 +- [ ] **Step 5: Run focused + full tests**
344 +
345 +Run: `node --test test/github-workspace-provider.test.js && npm test`
346 +
347 +Expected: 0 failures.
348 +
349 +- [ ] **Step 6: Record checkpoint and commit**
350 +
351 +Update `PROJECT_MEMORY.md` with RED/GREEN evidence; provider writes remain `NOT VERIFIED` live.
352 +
353 +Commit: `feat: add github workspace commit primitives`
354 +
355 +---
356 +
357 +### Task 6: Safe Approval, Idempotent Commit Orchestration and Audit
358 +
359 +**Files:**
360 +- Modify: `src/core/approval.js`
361 +- Modify: `src/core/router.js`
362 +- Modify: `src/plugins/github/manifest.js`
363 +- Modify: `src/plugins/github/plugin.js`
364 +- Modify: `src/plugins/github/workspace.js`
365 +- Modify: `src/bot.js`
366 +- Create: `test/github-workspace-approval.test.js`
367 +- Modify: `test/github-workspace-integration.test.js`
368 +- Modify: `PROJECT_MEMORY.md`
369 +
370 +**Interfaces:**
371 +- 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.
372 +- `approvalSourceCallback(payload)` supports workspace input `{ repoId, intentId }` -> `wscommit:<repoId>:<intentId>`.
373 +- Generalize approval UI metadata to accept `cancelCallback`; workflow-run approvals keep their existing Run fallback, workspace approval falls back to `ws:<workspaceId>` via immutable intent metadata resolved before issuing approval.
374 +- Register `github.workspace.commit_branch` as `WRITE`.
375 +- `commitWorkspaceIntent({ github, workspaces, ownerId, repoId, intentId }) -> { commitSha, branch, idempotent }`.
376 +- Plugin route `wscommit:<repoId>:<intentId>` returns approval metadata before execution; provider calls remain deferred until approved dispatch.
377 +- Route may supply sanitized `audit` metadata; Router merges only these safe fields into action attempt/result events.
378 +
379 +- [ ] **Step 1: Write approval/orchestration RED tests**
380 +
381 +Cover:
382 +- workspace approval token stays <=56 bytes, verifies owner/action/risk/repo/intent, expires and rejects replay;
383 +- clicking `wscommit` before approval performs zero GitHub Git Data writes;
384 +- approval binds the immutable intent ID; changed draft/message causes old intent execution to fail closed;
385 +- approved action re-reads base HEAD and creates zero Git objects when it changed;
386 +- approved action rejects an unexpected existing target branch;
387 +- successful path is exactly blob -> tree -> commit -> branch ref -> durable `COMMITTED` result;
388 +- replayed approval performs zero second writes;
389 +- fresh approval for an already `COMMITTED` intent returns recorded SHA with zero provider writes;
390 +- if create-ref returns an ambiguous/409/422 error, orchestration reads the ref: same expected commit => mark success, different/missing => error;
391 +- `COMMITTING` retry with stored candidate SHA reconciles before any new branch ref creation;
392 +- audit contains workspace/intent/repo/path/digest/SHA metadata but never original/draft source or signed token.
393 +
394 +- [ ] **Step 2: Run RED**
395 +
396 +Run: `node --test test/github-workspace-approval.test.js test/github-workspace-integration.test.js`
397 +
398 +Expected: FAIL on codec, route and commit orchestration.
399 +
400 +- [ ] **Step 3: Add compact approval codec without regressing Actions approvals**
401 +
402 +Implement a dedicated workspace-intent compact encoding branch rather than expanding generic JSON. Reject malformed/non-8-char intent IDs. Re-run existing `test/approval*.test.js` together with workspace approval tests.
403 +
404 +- [ ] **Step 4: Implement commit orchestration**
405 +
406 +Algorithm:
407 +1. load immutable owner-scoped intent and call `beginCommit`;
408 +2. return recorded result immediately for `COMMITTED`;
409 +3. re-read base branch snapshot and require exact `baseHeadSha` before object creation;
410 +4. read target ref and fail if it exists unless it already points to the stored deterministic candidate commit;
411 +5. create content blob, tree and deterministic commit; persist candidate commit SHA before ref creation;
412 +6. create target branch ref;
413 +7. on provider ambiguity, re-read ref and accept only exact candidate SHA;
414 +8. persist `COMMITTED` result before returning Telegram success.
415 +
416 +No force update, default-branch update or retry with changed material is allowed.
417 +
418 +- [ ] **Step 5: Generalize approval UI/fallback and add CI handoff**
419 +
420 +Success view shows exact provider commit SHA + branch and buttons for `🧪 CI / Actions` and workspace view. Failure/stale views show explicit reason and never claim commit success.
421 +
422 +- [ ] **Step 6: Run all security, approval and integration tests**
423 +
424 +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`
425 +
426 +Expected: all tests PASS, 0 fail/skip/cancelled.
427 +
428 +- [ ] **Step 7: Record checkpoint and commit**
429 +
430 +Update `PROJECT_MEMORY.md` with RED/GREEN evidence and mark live GitHub commit as `NOT VERIFIED` until owner-device production smoke.
431 +
432 +Commit: `feat: add safe approval gated workspace commits`
433 +
434 +---
435 +
436 +### Task 7: Whole-Branch Verification, Deployment and Owner-Device Production Acceptance
437 +
438 +**Files:**
439 +- Modify: `PROJECT_MEMORY.md`
440 +- Modify: `README.md` only if user-facing workflow documentation is missing after implementation review.
441 +
442 +**Interfaces:**
443 +- Consumes all prior tasks.
444 +- Produces production-acceptance evidence; no new product interface should be invented in this task.
445 +
446 +- [ ] **Step 1: Run fresh full local/CI-equivalent verification**
447 +
448 +Run: `npm test`
449 +
450 +Expected: every discovered `test/*.test.js` passes; 0 fail/skip/cancelled.
451 +
452 +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.
453 +
454 +- [ ] **Step 2: Review exact branch diff against the spec and acceptance criteria**
455 +
456 +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.
457 +
458 +- [ ] **Step 3: Merge only a reviewed green head and verify exact post-merge CI**
459 +
460 +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.
461 +
462 +- [ ] **Step 4: Verify Cloudflare deploy and new Durable Object binding**
463 +
464 +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.
465 +
466 +- [ ] **Step 5: Owner-device pre-approval smoke on a safe branch-only edit**
467 +
468 +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 a commit message such as `test: verify nexa mobile editor`.
469 +
470 +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.
471 +
472 +- [ ] **Step 6: Owner confirms Safe Approval and verify one provider commit**
473 +
474 +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.
475 +
476 +- [ ] **Step 7: Verify replay and fresh-retry idempotency**
477 +
478 +Reusing the same approval callback must be rejected by `APPROVAL_REPLAY_GUARD`. Re-opening the already committed workspace and requesting a fresh confirmation for the unchanged intent must return the recorded commit SHA without a second commit/ref movement. Compare GitHub branch history before/after.
479 +
480 +- [ ] **Step 8: Verify Cloudflare runtime/audit agreement**
481 +
482 +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.
483 +
484 +- [ ] **Step 9: Close production acceptance in project memory**
485 +
486 +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`.
487 +
488 +Commit the checkpoint through the normal reviewed branch/PR flow; do not mutate production docs directly without CI.
489 +
490 +---
491 +
492 +## Execution Order and Stop Conditions
493 +
494 +1. Tasks 1-2 establish pure policy + durable state and may not call GitHub WRITE.
495 +2. Tasks 3-4 establish a complete mobile draft/diff flow with no provider mutation.
496 +3. Task 5 adds provider primitives but does not expose them to Telegram.
497 +4. Task 6 is the only task that connects those primitives to an approval-gated provider WRITE.
498 +5. Task 7 is the only production-acceptance gate.
499 +
500 +Stop and fail closed if any of these occur:
501 +- source/path/workspace ownership cannot be proven;
502 +- `WORKSPACE_STORE` is missing or unhealthy;
503 +- base HEAD changed;
504 +- target branch exists at a different SHA;
505 +- draft or commit message changed after intent sealing;
506 +- approval token is missing/expired/replayed/mismatched;
507 +- provider result cannot be reconciled to the exact expected commit/ref;
508 +- full source/draft content appears in audit logs;
509 +- exact deployed main SHA cannot be proven.