Personal Telegram developer console for GitHub

feat: add safe repository workspace editor (#21)

Owner-scoped branch-first repository workspace with durable drafts, safe approval, idempotent Git Data commits, diff review and production-safety guards.

davoodmehraban89 committed Oct 3, 2026 at 13:51 UTC 5bbd943891189609dd85d40fd02fcb065bbe5c58
26 files changed +4062 -357
.superpowers/sdd/repository-workspace-editor/progress.md new
+33
@@ -0,0 +1,33 @@
1 +# SDD ledger — plan: docs/superpowers/plans/2026-10-03-repository-workspace-editor.md
2 +
3 +Execution mode: Native / inline (no subagent tool available).
4 +Spec approved by owner on 2026-10-03.
5 +Pre-flight: Task 1 policy outputs feed Tasks 2/4/6; names and limits match plan/spec.
6 +Pre-flight: Task 2 workspace-store outputs feed Tasks 3/4/6; owner-scoped IDs, TTLs and intent states match consumers.
7 +Pre-flight: Task 3 provider-read/controller outputs feed Task 4 and Task 6; callbacks remain short handles, legacy callbacks preserved.
8 +Pre-flight: Task 4 sealed intent fields match Task 6 approval/orchestration inputs.
9 +Pre-flight: Task 5 Git Data primitives match Task 6 orchestration signatures.
10 +Pre-flight: Task 6 production behavior is consumed by Task 7 acceptance flow.
11 +
12 +Task 1 ruling: the plan asked for a Unicode string under 3,000 characters but over 12,000 UTF-8 bytes; this is impossible because one Unicode code point encodes to at most 4 UTF-8 bytes. The implementation tests the 3,000/12,000 exact multibyte boundary and the byte ceiling independently via provider-reported byteLength.
13 +Task 1 RED: CI #183 / run 37111334419, 105 tests total, 99 pass / 6 expected failures.
14 +Task 1 GREEN: CI #185 / run 37111432295 → 105/105 pass, 0 fail/skip/cancelled.
15 +
16 +Task 2 RED: CI #187 / run 37111557951, 113 tests total, 105 pass / 8 expected failures.
17 +Task 2 compatibility finding: CI #191 / run 37111806380 had 112/113 pass; an old assertion incorrectly required the Durable Object binding list to contain only ApprovalReplayGuard. The assertion was narrowed to presence, not exclusivity.
18 +Task 2 GREEN: CI #192 / run 37111858230 → 113/113 pass, 0 fail/skip/cancelled. WORKSPACE_STORE production binding/runtime remains NOT VERIFIED until deployment.
19 +
20 +Task 3 GREEN: CI #200 / run 37112677199, job 111173499300 → 121/121 pass, 0 fail/skip/cancelled. Path-safe short-ref browser, file eligibility, pinned draft creation and legacy browser compatibility verified in CI.
21 +
22 +Task 4 RED: CI #201 / run 37113613413, job 111176071940 → 126 total, 121 pass / 5 expected failures for pending message routing and draft/message/diff/ready flows.
23 +Task 4 GREEN: CI #207 / run 37114230736, job 111177792978 → 127/127 pass, 0 fail/skip/cancelled.
24 +
25 +Task 5 RED: CI #209 / run 37114394075, job 111178254379 → 132 total, 127 pass / 5 expected failures for Git Data primitives.
26 +Task 5 GREEN: CI #210 / run 37114509763, job 111178575800 → 132/132 pass, 0 fail/skip/cancelled. Live GitHub mutation remains NOT VERIFIED.
27 +
28 +Task 6 GREEN before final review: CI #219 / run 37115479051, job 111181371564 → 141/141 pass, 0 fail/skip/cancelled. Compact workspace approval, pre-approval zero-write boundary, stale-base/target-ref protection, deterministic blob→tree→commit→ref orchestration, COMMITTING/COMMITTED reconciliation, replay rejection and safe audit metadata are covered.
29 +
30 +Task 7 review finding: approved workspace provider error text was interpolated into Telegram HTML without escaping. RED CI #220 / run 37115793196, job 111182246421 → 142 total, 141 pass / exactly 1 expected failure on the new regression test.
31 +Task 7 review hardening GREEN: CI #221 / run 37115965768, job 111182732367 → 31 test files, 142/142 pass, 0 fail/skip/cancelled. Provider error text is now HTML escaped before Telegram rendering.
32 +
33 +Whole-branch production acceptance is not complete yet. Remaining gates: fresh CI after durable checkpoint, exact reviewed-head merge, post-merge main CI, Cloudflare deploy/binding verification, then owner-device pre-approval and approved branch-only commit smoke. No live Repository Workspace provider commit has been executed yet.
PROJECT_MEMORY.md
+113 -40
@@ -21,6 +21,7 @@
21 - Plugin Registry + central Action Policy + Audit Logger + Plugin Router in `src/core/`.
22 - HMAC approval tokens in `src/core/approval.js`.
23 - Durable Object replay guard via `APPROVAL_REPLAY_GUARD` / `ApprovalReplayGuard`.
24 +- Owner-scoped Repository Workspace storage via `WORKSPACE_STORE` / `WorkspaceStore` on the implementation branch; production deployment is still NOT VERIFIED.
25 - GitHub plugin in `src/plugins/github/`; provider adapter in `src/github.js`.
26 - Exact-commit CI/deploy workflows under `.github/workflows/`.
27
@@ -30,7 +31,7 @@
31 - Approval is owner/action/risk/target/expiry-bound and one-time consumed through Durable Object storage.
32 - Provider mutation never executes before policy approval.
33 - Provider errors are explicit; no fabricated success or fallback data.
33 -- Secrets and signed approval callback tokens must not appear in logs/docs.
34 +- Secrets, source/draft text and signed approval callback tokens must not appear in logs/docs.
35 - Telegram callback data and rendered provider text must remain bounded.
36
37 ## Production-Accepted Foundation
@@ -79,7 +80,6 @@ Conclusion:
80 - Post-merge CI #172 / run `37102293956` succeeded on that exact SHA with 22 test files and 97/97 tests passing, 0 fail/skip/cancelled.
81 - Deploy #108 / run `37102308006` succeeded from that exact SHA.
82 - Active Cloudflare production version after deploy: `bc23d9e5-1490-429c-9369-4e751f173df5` at 100% traffic.
82 -- Cloudflare Observability issue summary after deploy showed 0 active issues and 0 active occurrences.
83
84 ### TDD evidence
85 - Provider RED CI #156 / run `37100585034`: 87 tests total, 82 pass / 5 expected failures for missing Advanced provider readers.
@@ -103,51 +103,124 @@ Conclusion:
103 - New READ callbacks resolve without provider calls before central policy evaluation; callback lengths are regression-tested against Telegram limits.
104 - READ provider failures visibly update Telegram instead of appearing silent.
105
106 -### Owner-device production smoke findings
107 -- Owner exercised the new Advanced READ menu on Telegram after production deploy; most tested paths rendered and navigated as expected.
108 -- `Issues` failed live with GitHub `403 Resource not accessible by personal access token`.
109 -- Cloudflare production audit confirmed `github.issues.list` passed central READ policy and then failed only at the GitHub provider boundary with that 403.
110 -- Root cause: the existing fine-grained PAT does not currently grant Repository permissions -> Issues -> Read. Existing visible permissions include Metadata Read plus Actions/Code/Pull requests Read and Write.
111 -- `Releases` did not fail: a direct GitHub releases read returned an empty list `[]`, proving this repository currently has no GitHub Releases. The old Telegram empty-state wording was merely ambiguous.
106 +## GitHub Advanced READ Production Acceptance — PR #20
107 +- Live owner-device smoke found two gaps: Issues returned GitHub 403 due missing `Issues: Read`, while Releases successfully returned an empty source-backed list.
108 +- PR #20 `fix: clarify Issues permission and empty Releases state` merged to `main` at `7c0df4c8616c6859a2dfc4c35b0e22d6e47215bc`.
109 +- Post-merge CI #177 / run `37106715317` completed successfully on that exact SHA with 23 test files and 99/99 tests passing, 0 fail/skip/cancelled.
110 +- Deploy #113 / run `37106727515` completed successfully after checking out that exact SHA.
111 +- Active Cloudflare production version after deploy: `5741faa0-720f-48d5-9e76-64726a5f5167` at 100% traffic.
112 +- Owner updated the existing fine-grained PAT to add only Repository permissions -> Issues -> Read-only; token value was not rotated/stored/logged.
113 +- Owner-device Telegram smoke after that permission change showed Issues no longer returns 403 and Releases renders the explicit no-published-release state.
114 +- Cloudflare production telemetry on version `5741faa0-720f-48d5-9e76-64726a5f5167` recorded `github.issues.list` with `outcome=success` and `github.releases.list` with `outcome=success` for the owner-device interactions.
115
113 -## Current Work — PR #20 Live-Smoke Findings Hardening
114 -- Branch: `fix/issues-permission-release-empty-ux`.
115 -- Draft PR #20: `fix: clarify Issues permission and empty Releases state`.
116 -- Scope is UI/error-guidance only; no new provider mutation is added.
117 -- Issues 403 feedback now tells the owner the exact least-privilege setting required: Fine-grained token -> Repository permissions -> Issues -> Read.
118 -- Empty Releases view now explicitly says that no GitHub Release is published for the repository instead of presenting an ambiguous not-found message.
119 -
120 -### TDD evidence
121 -- RED CI #173 / run `37106220231`: 23 test files, 99 tests total, 97 pass / exactly 2 expected failures for the live Issues-permission guidance and empty Releases wording.
122 -- GREEN CI #175 / run `37106470008` at implementation head `d779c746dd4c0dadb652f9d2375ba7765ff5803b`: 23 test files, 99/99 pass, 0 fail/skip/cancelled.
123 -- A fresh final CI is still required after this memory checkpoint because this documentation commit moves the PR head.
116 +Conclusion:
117 +- GitHub Advanced READ production acceptance: VERIFIED.
118 +- Issues least-privilege provider authorization: VERIFIED.
119 +- Releases source-backed empty state: VERIFIED.
120 +- Telegram owner-device/runtime evidence: VERIFIED.
121 +
122 +## Repository Workspace / Code Editor Phase 1 — PR #21 IN PROGRESS
123 +- Design spec: `docs/superpowers/specs/2026-10-03-repository-workspace-editor-design.md`.
124 +- Implementation plan: `docs/superpowers/plans/2026-10-03-repository-workspace-editor.md`.
125 +- Implementation branch: `spec/repository-workspace-editor`.
126 +- PR #21 targets `main` and contains the complete Phase-1 implementation pending merge/deploy/owner-device acceptance.
127 +- Phase 1 remains branch-first only: no direct default-branch mutation, no force update, no automatic merge/rebase/conflict resolution.
128 +
129 +### Locked implementation constraints
130 +- Owner-scoped short navigation refs; raw long paths never appear in callback data.
131 +- Editable Phase-1 text ceiling: 3,000 Unicode code points and 12,000 UTF-8 bytes; overflow is rejected, never silently truncated.
132 +- Sensitive/private-key-like paths, binary-like content and Git LFS pointers are not editable.
133 +- Navigation/workspace handles are 10 URL-safe chars; commit-intent IDs are exactly 8 URL-safe chars.
134 +- Target branch is `nexa/edit-<workspaceId>`.
135 +- Draft/source content is never placed in callback data or audit metadata.
136 +- Repeated Ready on unchanged material reuses the existing immutable intent.
137 +- Provider Git commit creation remains NOT VERIFIED live until owner-device production acceptance passes.
138 +
139 +### Task 1 — Workspace policy/diff primitives: COMPLETE
140 +- `src/core/workspace-policy.js` implements editable-file policy, commit-message normalization, target-branch normalization, SHA-256 digests and bounded unified diff with exact full-content counts.
141 +- RED evidence was captured before implementation.
142 +- GREEN checkpoint CI #185 completed with 105/105 passing at that task head.
143 +
144 +### Task 2 — Durable owner-scoped Workspace Store: COMPLETE
145 +- Added `WORKSPACE_STORE` / `WorkspaceStore` client + Durable Object state machine.
146 +- Owner isolation, navigation/workspace expiry, one-shot pending input, READY invalidation/reuse, COMMITTING/COMMITTED state and cancellation are covered by tests.
147 +- GREEN checkpoint CI #192 completed with 113/113 passing at that task head.
148 +- Production deployment of the new binding/class: NOT VERIFIED.
149 +
150 +### Task 3 — Path-safe repository browser/editor entry: COMPLETE
151 +- Workspace file navigation uses short Durable refs after policy; legacy tree/blob/path-bearing callbacks remain compatible.
152 +- Eligible file preview exposes Edit; sensitive/LFS/oversized files remain readable with edit disabled.
153 +- `wedit` pins current default-branch HEAD/tree and exact file/blob/content before creating a durable local draft.
154 +- Archived repositories cannot create editable drafts.
155 +- GREEN checkpoint CI #200 / run `37112677199`, job `111173499300`: 121/121 pass, 0 fail/skip/cancelled.
156 +
157 +### Task 4 — Telegram Draft Input, Diff and Sealed Intent UX: COMPLETE
158 +- RED CI #201 / run `37113613413`, job `111176071940`: 126 tests total, 121 pass / 5 expected failures for missing message routing and `wtext`/`wmsg`/`wdiff`/`wready` behavior.
159 +- Added policy-routed `dispatchMessage`; source text is not audit metadata.
160 +- Bot preserves `/start`/`/menu`/`/repos`/`/status` precedence, then owner pending workspace text is routed with the exact untrimmed message body.
161 +- Pending draft/message input is one-shot; rejected draft input does not mutate the prior draft.
162 +- Diff is HTML escaped and bounded while additions/deletions are computed over complete content.
163 +- READY requires changed content + normalized commit message, binds stable digests/base/path/branch/timestamp, reuses unchanged intent and emits only short `wscommit:<repoId>:<intentId>` callback data.
164 +- GREEN CI #207 / run `37114230736`, job `111177792978`: 27 test files, 127/127 pass, 0 fail/skip/cancelled.
165 +
166 +### Task 5 — GitHub Git Data commit primitives: COMPLETE
167 +- RED CI #209 / run `37114394075`, job `111178254379`: 132 tests total, 127 pass / 5 expected failures for missing Git Data primitives.
168 +- `requestJson` supports opt-in `allowNotFound`; only HTTP 404 may return `null`, while 403/409/422 and other provider errors remain explicit.
169 +- Added `getGitRef`, `createGitBlob`, multi-file-capable `createGitTree`, deterministic `createGitCommit`, and create-only `createGitBranchRef`.
170 +- Branch paths containing `/` are safely encoded for ref reads; every provider/object SHA is full 40-hex validated.
171 +- Commit author/committer identity and timestamp are deterministic, making ambiguous Git object creation retries material-stable.
172 +- Phase 1 intentionally exposes no update-ref/force-ref primitive.
173 +- GREEN CI #210 / run `37114509763`, job `111178575800`: 28 test files, 132/132 pass, 0 fail/skip/cancelled.
174 +- These Git Data writes are verified only against mocked provider contracts; live GitHub branch commit remains NOT VERIFIED.
175 +
176 +### Task 6 — Safe Approval + idempotent branch commit orchestration: COMPLETE IN CI
177 +- Workspace commit approval uses a compact owner/action/risk/repo/8-char-intent-bound HMAC token; full Telegram `approve:` callback is regression-tested within the 64-byte limit.
178 +- `wscommit` returns approval metadata before execution; pre-approval route evaluation performs zero GitHub Git Data writes.
179 +- Approved orchestration revalidates immutable workspace material, exact base HEAD and target-branch absence before object creation.
180 +- Commit flow is blob -> tree -> deterministic commit -> persist candidate SHA -> create-only branch ref -> durable `COMMITTED` result.
181 +- `COMMITTING` and already `COMMITTED` retries reconcile idempotently; ambiguous create-ref failures are accepted only if the target ref resolves to the exact recorded candidate SHA.
182 +- Audit metadata is allowlisted and excludes source/draft text and signed token material.
183 +- Existing workflow-run Safe Approval behavior and replay protection remain covered.
184 +- GREEN CI #219 / run `37115479051`, job `111181371564`: 30 test files, 141/141 pass, 0 fail/skip/cancelled.
185 +- Live Repository Workspace provider mutation remains NOT VERIFIED.
186 +
187 +### Task 7 — Whole-branch review/hardening: IN PROGRESS
188 +- Review found one visible-error gap: approved workspace provider error text was inserted into Telegram HTML without escaping.
189 +- RED CI #220 / run `37115793196`, job `111182246421`: 31 test files, 142 tests total, 141 pass / exactly 1 expected failure on that regression.
190 +- Fix escapes provider error text before Telegram rendering.
191 +- GREEN CI #221 / run `37115965768`, job `111182732367`: 31 test files, 142/142 pass, 0 fail/skip/cancelled.
192 +- Secret-pattern review found no actual PAT/Telegram secret in the PR diff; occurrences of `ghp_` / `github_pat_` are only the documented scan-pattern names. `approve:` occurrences are expected callback construction/parsing and explicit negative audit tests, not logged live tokens.
193 +- A fresh CI is still required after this durable checkpoint because the documentation commits move the PR head.
194
195 ### Not yet production-accepted
126 -- PR #20 is not merged/deployed at this checkpoint.
127 -- Exact post-merge `main` CI and Cloudflare deployment for PR #20 are NOT VERIFIED.
128 -- Issues live success remains NOT VERIFIED until the owner adds only `Issues: Read` to the existing fine-grained token and repeats the Telegram Issues read.
129 -- Releases source-backed empty state is verified at the GitHub API boundary, but the revised Telegram wording is NOT VERIFIED on the owner device until PR #20 is deployed.
196 +- PR #21 is not yet merged/deployed at this checkpoint.
197 +- Exact post-merge `main` CI: NOT VERIFIED.
198 +- Production `WORKSPACE_STORE` / `WorkspaceStore` binding/runtime: NOT VERIFIED.
199 +- Live owner-device browse/edit/diff/READY pre-approval smoke: NOT VERIFIED.
200 +- Live proof of zero provider WRITE before workspace approval: NOT VERIFIED for this new action.
201 +- Live approved branch-only GitHub commit and exact provider SHA feedback: NOT VERIFIED.
202 +- Main/default branch remaining unchanged after the branch-only commit: NOT VERIFIED live.
203
204 ## Next Executable Actions
132 -1. Run fresh final PR #20 CI after this checkpoint; review the exact diff and secret patterns.
133 -2. Mark PR #20 ready and squash-merge only the exact reviewed green head.
134 -3. Verify exact post-merge `main` CI, deploy, active Cloudflare version and production runtime/telemetry.
135 -4. Owner adds only `Repository permissions -> Issues -> Read` to the existing fine-grained GitHub token; do not regenerate or rotate the token unnecessarily.
136 -5. Owner repeats Telegram `Issues` and `Releases`; verify production audit records provider success for both reads.
137 -6. Close GitHub Advanced READ production acceptance only after that owner-device/runtime verification.
138 -7. Then implement remaining GitHub Advanced WRITE items only where operationally useful and always through Safe Approval, followed by Cloudflare Ops.
205 +1. Run fresh CI on the final checkpoint head and review exact PR #21 diff/metadata.
206 +2. Mark PR #21 ready and merge only that reviewed green head.
207 +3. Verify exact post-merge `main` CI, deploy SHA, active Cloudflare version and both Durable Object bindings/classes.
208 +4. Perform owner-device production smoke up to the Approval screen; verify no target branch/provider WRITE exists before confirmation.
209 +5. Owner confirms the fresh Safe Approval; verify the new `nexa/edit-*` branch, exact commit SHA, main unchanged, Cloudflare audit success and Telegram success feedback.
210 +6. Do not call Repository Workspace Phase 1 production-accepted until Telegram, GitHub and Cloudflare runtime evidence agree.
211
212 ## Remaining Roadmap
141 -1. Finish GitHub Advanced production acceptance; add workflow dispatch/specific-job rerun only if operationally useful and always via Safe Approval.
142 -2. Cloudflare Ops plugin: deployments, versions, bindings, health, telemetry/runtime errors and approval-gated rollback/deploy operations.
143 -3. CI/CD Control Plane and release acceptance orchestration.
144 -4. Monitoring + Incident Manager.
145 -5. Automation Engine with resumable/idempotent approval-aware workflows.
146 -6. AI Copilot with no direct production mutation.
147 -7. Browser QA real production smoke.
148 -8. Telegram Mini App backed by real APIs.
149 -9. Plugin ecosystem and multi-project control plane.
150 -10. Final hardening, recovery drills, docs and versioning.
213 +1. Repository Workspace / Code Editor Phase 1 production acceptance, then multi-file expansion.
214 +2. Remaining useful GitHub Advanced WRITE actions, always through Safe Approval.
215 +3. Cloudflare Ops plugin: deployments, versions, bindings, health, telemetry/runtime errors and approval-gated rollback/deploy operations.
216 +4. CI/CD Control Plane and release acceptance orchestration.
217 +5. Monitoring + Incident Manager.
218 +6. Automation Engine with resumable/idempotent approval-aware workflows.
219 +7. AI Copilot with no direct production mutation.
220 +8. Browser QA real production smoke.
221 +9. Telegram Mini App backed by the same workspace/control-plane APIs.
222 +10. Plugin ecosystem and multi-project control plane.
223 +11. Final hardening, recovery drills, docs and versioning.
224
225 ## Project Boundaries
226 - Nexa Dev Bot is independent from Finora / Factor-easy unless an explicit adapter is added.
docs/superpowers/plans/2026-10-03-repository-workspace-editor.md new
+512
@@ -0,0 +1,512 @@
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.
docs/superpowers/specs/2026-10-03-repository-workspace-editor-design.md new
+383
@@ -0,0 +1,383 @@
1 +# Repository Workspace / Code Editor Design
2 +
3 +Date: 2026-10-03
4 +Status: Proposed for implementation after owner review
5 +Owner intent: let the repository owner browse a repository from Telegram, open a text file, edit it safely, inspect the exact diff, and commit the change back to GitHub. The architecture must support multi-file workspaces later without weakening approval, audit, branch, or conflict-safety rules.
6 +
7 +## 1. Goals
8 +
9 +The feature must let the owner:
10 +
11 +1. Select any repository already visible through Nexa.
12 +2. Browse to a text file and open a bounded preview.
13 +3. Start an edit workspace without writing anything to GitHub.
14 +4. Change file content or a bounded line range.
15 +5. Review a source-backed before/after diff.
16 +6. Provide a commit message.
17 +7. Commit only after Safe Approval.
18 +8. Receive the resulting commit SHA and continue into CI / Actions monitoring.
19 +9. Later edit multiple files in one workspace and commit them atomically.
20 +
21 +The central product goal is to make Nexa a real mobile developer control plane, not only a repository viewer.
22 +
23 +## 2. Delivery Strategy
24 +
25 +### Phase 1 — Safe single-file workspace
26 +
27 +Ship one-file editing first, but build the data model and commit engine so multi-file workspaces do not require a redesign.
28 +
29 +Phase 1 supports:
30 +- owner-only text-file editing;
31 +- branch-first commits;
32 +- bounded file preview and editing payloads;
33 +- exact diff before approval;
34 +- conflict detection against the original base HEAD;
35 +- Safe Approval before the GitHub mutation;
36 +- idempotent commit intent tracking;
37 +- commit SHA feedback and CI handoff.
38 +
39 +Phase 1 does not support:
40 +- binary files;
41 +- Git LFS objects;
42 +- automatic merge/conflict resolution;
43 +- arbitrary shell execution;
44 +- direct commits to `main`;
45 +- editing likely-secret/private-key files;
46 +- multi-user collaboration.
47 +
48 +### Phase 2 — Multi-file workspace
49 +
50 +Reuse the same workspace and commit engine to stage several changed files and create one atomic tree/commit.
51 +
52 +### Phase 3 — Rich editor surface
53 +
54 +A Telegram Mini App can later use the same workspace API for larger files, syntax-aware editing, multi-file tabs, search and richer diff presentation. The Telegram chat UI remains the safe control and approval surface.
55 +
56 +## 3. User Flow
57 +
58 +### Open and edit
59 +
60 +`/start -> Repositories -> <repo> -> Files -> <file> -> Edit`
61 +
62 +The file view shows:
63 +- path;
64 +- branch/ref;
65 +- blob SHA;
66 +- file size;
67 +- bounded text preview;
68 +- `Edit` only when the file passes editable-file policy.
69 +
70 +Pressing `Edit` creates a local Nexa workspace. This is not a GitHub WRITE.
71 +
72 +### Draft
73 +
74 +The workspace records:
75 +- owner id;
76 +- repository id/full name;
77 +- base branch;
78 +- base HEAD SHA;
79 +- source path;
80 +- source blob SHA;
81 +- original content digest;
82 +- draft content/digest;
83 +- commit message/digest when supplied;
84 +- target branch when supplied/generated;
85 +- created/updated timestamps;
86 +- expiration time;
87 +- workspace state.
88 +
89 +The owner submits replacement text or a bounded line-range edit. Nexa validates size, UTF-8 encoding, source path, workspace ownership and configured input bounds before accepting it. Commit messages and branch names are normalized and bounded; branch names must satisfy Git ref safety rules.
90 +
91 +### Review
92 +
93 +Nexa renders a bounded unified diff and summary:
94 +- repository;
95 +- base branch;
96 +- planned target branch;
97 +- file path;
98 +- additions/deletions;
99 +- original blob/base HEAD;
100 +- proposed content digest;
101 +- commit message.
102 +
103 +No provider mutation happens during preview.
104 +
105 +### Commit
106 +
107 +The default path is:
108 +
109 +`draft -> review diff -> Safe Approval -> Git Data commit flow -> target branch ref -> return SHA -> monitor CI`
110 +
111 +The approval target binds at least:
112 +- repository;
113 +- workspace id / commit-intent id;
114 +- base HEAD SHA;
115 +- target branch;
116 +- changed path(s);
117 +- proposed content/tree digest;
118 +- commit message digest;
119 +- action id;
120 +- owner;
121 +- expiry.
122 +
123 +If anything material changes after approval is issued, Nexa must require a new approval.
124 +
125 +## 4. Branch Policy
126 +
127 +### Default: branch-first
128 +
129 +Phase 1 never commits directly to `main`.
130 +
131 +Nexa generates or accepts a safe branch name such as:
132 +
133 +`nexa/edit-<short-workspace-id>`
134 +
135 +The final approved composite action creates Git objects and then the target branch ref. This keeps drafts local and avoids a visible provider branch write before final confirmation.
136 +
137 +### Direct-main future mode
138 +
139 +Direct commits to the default branch are deferred. If added later they must be explicitly enabled, clearly marked high-risk, respect branch protection/rulesets, and use a stronger confirmation UX. Nexa must never bypass GitHub protection rules.
140 +
141 +## 5. Commit Engine
142 +
143 +The implementation should use GitHub Git Data primitives rather than designing around one-file Contents API behavior:
144 +
145 +1. Read and pin the base HEAD commit/tree.
146 +2. After approval is consumed, re-check staleness/conflicts.
147 +3. Create blob(s) for staged content.
148 +4. Create a new tree from the pinned base tree.
149 +5. Create one commit pointing to that tree.
150 +6. Create or fast-forward the approved target branch ref.
151 +7. Persist the provider result into the workspace before returning success to Telegram.
152 +
153 +All GitHub Git Data writes (blob/tree/commit/ref) occur only after Safe Approval has been successfully consumed. Provider object creation is considered part of the approved composite WRITE even if a later ref update fails.
154 +
155 +This is slightly more work for the first single-file version, but it gives the correct atomic file-set foundation for Phase 2 multi-file commits.
156 +
157 +No branch ref may be moved if the repository state no longer matches the conflict checks described below.
158 +
159 +## 6. Conflict and Staleness Safety
160 +
161 +A workspace is optimistic-concurrency controlled.
162 +
163 +Before final mutation Nexa re-reads the relevant branch state.
164 +
165 +Rules:
166 +- If the base branch HEAD no longer matches the workspace base HEAD, the commit is blocked as stale before GitHub object creation.
167 +- Nexa does not silently rebase, merge or overwrite.
168 +- The owner is shown the conflict/staleness reason and can refresh the workspace from the new base.
169 +- If a target branch already exists unexpectedly or moved since approval, the action fails closed.
170 +- A provider 409/422 or protection error is surfaced to Telegram and audited; success is never fabricated.
171 +
172 +## 7. Idempotency and Ambiguous Provider Outcomes
173 +
174 +Approval replay protection alone is not enough. A provider call can succeed while the Telegram response fails, and the owner may then try again with a fresh approval.
175 +
176 +Each ready-to-commit workspace therefore gets a stable commit-intent digest derived from repository, base SHA, target branch, path(s), content/tree digest and commit-message digest.
177 +
178 +Workspace state transitions are monotonic, for example:
179 +
180 +`DRAFT -> READY -> COMMITTING -> COMMITTED | FAILED | STALE`
181 +
182 +Rules:
183 +- once `COMMITTED`, the workspace returns the recorded commit SHA and must not create another commit for the same intent;
184 +- the resulting commit SHA/target ref are persisted before Nexa reports success to Telegram;
185 +- if the provider result is ambiguous (timeout/network failure after a possible ref update), Nexa reconciles the target branch/ref against the expected commit intent before permitting a retry;
186 +- a fresh approval cannot bypass an already-committed workspace intent;
187 +- changing draft content, branch or commit message creates a new intent and invalidates any prior pending approval.
188 +
189 +This protects against duplicate commits even when the first successful provider result was not visible to the owner.
190 +
191 +## 8. Workspace Storage
192 +
193 +Draft content must not be stored in Telegram callback data or process memory.
194 +
195 +Use a dedicated owner-scoped durable workspace store, preferably a separate Durable Object namespace/class such as `WORKSPACE_STORE` / `WorkspaceStore`.
196 +
197 +Properties:
198 +- workspace id is random and non-secret;
199 +- every operation checks owner identity;
200 +- data is scoped by owner + workspace id;
201 +- TTL cleanup removes abandoned drafts;
202 +- committed result metadata is retained long enough to support idempotent retry/reconciliation;
203 +- no GitHub token, Telegram token or signing secret is stored in the workspace;
204 +- audit logs store metadata/digests, not full sensitive file contents;
205 +- draft state is never treated as a provider commit.
206 +
207 +The existing `APPROVAL_REPLAY_GUARD` remains dedicated to one-time approval consumption.
208 +
209 +## 9. Editable File Policy
210 +
211 +Phase 1 accepts UTF-8 text only.
212 +
213 +Reject or disable edit for:
214 +- binary/non-UTF-8 content;
215 +- files above the configured edit-size ceiling;
216 +- Git LFS pointers when unsafe to edit as normal text;
217 +- probable private-key/credential files such as common `.pem`, `id_rsa`, and committed environment-secret patterns;
218 +- generated files identified by explicit project policy when available.
219 +
220 +Reads may remain available where already allowed, but the editor should fail closed for risky write targets.
221 +
222 +All rendered file content and diff text must be HTML-escaped and bounded for Telegram. Editable input must never be silently truncated.
223 +
224 +## 10. Telegram UX
225 +
226 +New controls should fit naturally into the existing GitHub plugin:
227 +
228 +File view:
229 +- `✏️ Edit`
230 +- existing navigation/back controls
231 +
232 +Workspace view:
233 +- path + base ref
234 +- draft status
235 +- `📝 تغییر متن`
236 +- `🔍 مشاهده Diff`
237 +- `💬 پیام Commit`
238 +- `✅ آماده Commit`
239 +- `🗑 لغو Draft`
240 +
241 +Ready-to-commit view:
242 +- exact change summary;
243 +- bounded diff;
244 +- target branch;
245 +- commit message;
246 +- `✅ تأیید و Commit` through Safe Approval;
247 +- cancel/back.
248 +
249 +After commit:
250 +- resulting SHA;
251 +- branch;
252 +- `🧪 CI / Actions`;
253 +- optional later `Create PR` action, separately approval-gated.
254 +
255 +For content too large to edit comfortably in chat, Phase 1 explains the limit rather than truncating editable input silently. The richer Mini App editor is the planned expansion path.
256 +
257 +## 11. Action Model and Risk
258 +
259 +New actions should be explicit in the GitHub plugin manifest.
260 +
261 +READ examples:
262 +- `github.workspace.view`
263 +- `github.workspace.diff`
264 +
265 +Local/draft actions do not call GitHub and remain owner-only.
266 +
267 +Provider WRITE examples:
268 +- `github.workspace.commit_branch`
269 +- later `github.pr.create_from_workspace`
270 +
271 +Every provider WRITE must pass through the existing Action Policy, HMAC approval, durable replay guard and audit lifecycle.
272 +
273 +The GitHub Git Data write sequence must not begin until approval is successfully consumed.
274 +
275 +## 12. Audit Requirements
276 +
277 +Audit events must let us reconstruct the control-plane decision without leaking source contents.
278 +
279 +Record metadata such as:
280 +- workspace id;
281 +- commit-intent digest;
282 +- repo id;
283 +- base SHA;
284 +- target branch;
285 +- paths changed;
286 +- count of files;
287 +- additions/deletions when available;
288 +- proposed tree/content digest;
289 +- action/policy/approval outcome;
290 +- resulting commit SHA on success;
291 +- reconciliation outcome after ambiguous provider failures;
292 +- provider error category on failure.
293 +
294 +Do not log:
295 +- full file contents;
296 +- tokens/secrets;
297 +- signed approval callback tokens.
298 +
299 +## 13. Testing Strategy
300 +
301 +Implementation must be TDD and include:
302 +
303 +### Unit / provider
304 +- editable-file validation;
305 +- workspace owner isolation;
306 +- TTL/stale workspace behavior;
307 +- text/diff bounds and escaping;
308 +- branch/commit-message validation and bounds;
309 +- blob/tree/commit/ref request construction;
310 +- multi-file-capable tree construction even if UI initially stages one file;
311 +- GitHub error propagation.
312 +
313 +### Policy / security
314 +- no GitHub WRITE before approval;
315 +- approval target binds repo/workspace/base/branch/path/content digest;
316 +- replay rejected;
317 +- expired approval rejected;
318 +- stale base HEAD blocks mutation before object creation;
319 +- unexpected target-branch movement blocks mutation;
320 +- non-owner cannot read or mutate workspace;
321 +- sensitive-file policy fails closed.
322 +
323 +### Idempotency
324 +- committed workspace returns recorded SHA on retry without another provider write;
325 +- fresh approval cannot duplicate an already-committed intent;
326 +- ambiguous provider timeout reconciles expected target ref before retry;
327 +- content/branch/message change invalidates prior approval and produces a new intent.
328 +
329 +### Integration
330 +- create draft -> edit -> diff -> approve -> branch commit;
331 +- provider failure visibly updates Telegram;
332 +- successful commit persists exact SHA before Telegram success feedback;
333 +- successful commit returns exact SHA and CI navigation.
334 +
335 +### Production acceptance
336 +CI alone is insufficient. Acceptance requires an owner-device smoke on a safe test file/branch proving:
337 +1. draft creation does not change GitHub;
338 +2. diff matches the proposed edit;
339 +3. no GitHub write occurs before approval;
340 +4. confirmation creates exactly one commit on the intended branch;
341 +5. replay does not create a second commit;
342 +6. re-opening/retrying a committed workspace returns the same SHA without a duplicate commit;
343 +7. GitHub and Cloudflare audit/runtime evidence agree on the same operation.
344 +
345 +## 14. Acceptance Criteria
346 +
347 +Phase 1 is complete only when all are true:
348 +
349 +- owner can open an eligible text file from Telegram;
350 +- owner can create/edit a durable draft;
351 +- exact bounded diff is visible before commit;
352 +- `main` is not directly mutated;
353 +- stale-base conflicts fail closed;
354 +- final GitHub mutation is Safe-Approval gated and one-time;
355 +- a committed workspace is idempotent across Telegram/network retries;
356 +- resulting commit SHA/branch are shown from provider evidence;
357 +- CI handoff is available;
358 +- audit does not expose full draft/source contents or secrets;
359 +- automated tests pass;
360 +- exact production deployment is verified;
361 +- owner-device production smoke passes.
362 +
363 +## 15. Roadmap Placement
364 +
365 +Updated order:
366 +
367 +1. GitHub Advanced READ production acceptance — completed.
368 +2. Repository Workspace / Code Editor — this design.
369 +3. Remaining useful GitHub Advanced WRITE operations (for example workflow dispatch or specific-job rerun) through Safe Approval.
370 +4. Cloudflare Ops plugin.
371 +5. CI/CD Control Plane and release acceptance orchestration.
372 +6. Monitoring + Incident Manager.
373 +7. Automation Engine.
374 +8. AI Copilot with no direct production mutation.
375 +9. Browser QA.
376 +10. Telegram Mini App using the same workspace/control-plane APIs.
377 +11. Plugin ecosystem, multi-project control plane and final hardening.
378 +
379 +## 16. Key Architecture Decision
380 +
381 +The editor is not a special bypass around GitHub controls. It is a first-class GitHub WRITE workflow built on the same policy, approval, replay-protection and audit boundary already proven in production.
382 +
383 +The initial UI is deliberately small, but the underlying durable workspace + idempotent Git Data commit model is designed for later multi-file atomic commits and a richer editor without changing the security contract.
src/bot.js
+99 -209
@@ -5,27 +5,36 @@ import { PluginRegistry } from './core/plugin-registry.js';
5 import { ActionPolicy } from './core/action-policy.js';
6 import { ApprovalService } from './core/approval.js';
7 import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
8 +import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
9 import { AuditLogger } from './core/audit.js';
10 import { PluginRouter } from './core/router.js';
11 import { createGitHubPlugin } from './plugins/github/plugin.js';
12
13 +const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
14 +const escapeHtml = value => String(value ?? '')
15 + .replaceAll('&', '&amp;')
16 + .replaceAll('<', '&lt;')
17 + .replaceAll('>', '&gt;')
18 + .replaceAll('"', '&quot;');
19 +
20 function approvalSourceCallback(payload = {}) {
21 const repoId = payload.input?.repoId;
14 - const runId = payload.input?.runId;
15 - if (!Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(runId))) {
16 - throw new Error('Approval input is invalid');
17 - }
22 + if (!Number.isSafeInteger(Number(repoId))) throw new Error('Approval input is invalid');
23
19 - if (payload.actionId === 'github.workflow.run.rerun_failed') {
20 - return `rerun:${repoId}:${runId}`;
21 - }
22 - if (payload.actionId === 'github.workflow.run.cancel') {
23 - return `cancelrun:${repoId}:${runId}`;
24 + if (payload.actionId === 'github.workspace.commit_branch') {
25 + const intentId = String(payload.input?.intentId || '');
26 + if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval input is invalid');
27 + return `wscommit:${repoId}:${intentId}`;
28 }
29 +
30 + const runId = payload.input?.runId;
31 + if (!Number.isSafeInteger(Number(runId))) throw new Error('Approval input is invalid');
32 + if (payload.actionId === 'github.workflow.run.rerun_failed') return `rerun:${repoId}:${runId}`;
33 + if (payload.actionId === 'github.workflow.run.cancel') return `cancelrun:${repoId}:${runId}`;
34 throw new Error('Approval action is not supported');
35 }
36
28 -function approvalView({ label, token, repoId, runId }) {
37 +function approvalView({ label, token, cancelCallback = 'menu:main' }) {
38 return {
39 text:
40 `⚠️ <b>تأیید عملیات لازم است</b>
@@ -37,7 +46,7 @@ function approvalView({ label, token, repoId, runId }) {
46 reply_markup: {
47 inline_keyboard: [
48 [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
40 - [{ text: '↩️ انصراف', callback_data: `run:${repoId}:${runId}` }]
49 + [{ text: '↩️ انصراف', callback_data: cancelCallback }]
50 ]
51 }
52 };
@@ -55,6 +64,7 @@ function approvalRejectedView(message, error) {
64 let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
65 if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
66 if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
67 + const backText = fallback.startsWith('run:') ? '↩️ بازگشت به Run' : '↩️ بازگشت';
68
69 return {
70 text:
@@ -62,12 +72,8 @@ function approvalRejectedView(message, error) {
72 ➖➖➖➖➖➖➖➖➖➖
73 ${detail}
74
65 -برای ادامه به صفحهٔ Run برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
66 - reply_markup: {
67 - inline_keyboard: [
68 - [{ text: '↩️ بازگشت به Run', callback_data: fallback }]
69 - ]
70 - }
75 +برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
76 + reply_markup: { inline_keyboard: [[{ text: backText, callback_data: fallback }]] }
77 };
78 }
79
@@ -76,14 +82,19 @@ function approvedActionFailedView(payload, error) {
82 const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
83 const repoId = payload?.input?.repoId;
84 const runId = payload?.input?.runId;
79 - const fallback = Number.isSafeInteger(Number(repoId)) && Number.isSafeInteger(Number(runId))
80 - ? `run:${repoId}:${runId}`
81 - : 'menu:main';
82 -
83 - const detail = permissionDenied
84 - ? 'تأیید شما معتبر بود، اما GitHub درخواست را با خطای 403 رد کرد. دسترسی توکن فعلی برای GitHub Actions WRITE کافی نیست.'
85 - : 'تأیید شما معتبر بود، اما GitHub عملیات را موفق اعلام نکرد. وضعیت Run را بررسی کنید.';
86 -
85 + const workspaceAction = payload?.actionId === 'github.workspace.commit_branch';
86 + const fallback = workspaceAction && Number.isSafeInteger(Number(repoId))
87 + ? `repo:${repoId}`
88 + : Number.isSafeInteger(Number(repoId)) && Number.isSafeInteger(Number(runId))
89 + ? `run:${repoId}:${runId}`
90 + : 'menu:main';
91 + const detail = workspaceAction
92 + ? permissionDenied
93 + ? 'تأیید شما معتبر بود، اما GitHub درخواست Commit شاخه را با خطای 403 رد کرد. دسترسی Contents WRITE توکن فعلی را بررسی کنید.'
94 + : `تأیید شما معتبر بود، اما Commit شاخه انجام نشد: ${escapeHtml(reason)}`
95 + : permissionDenied
96 + ? 'تأیید شما معتبر بود، اما GitHub درخواست را با خطای 403 رد کرد. دسترسی توکن فعلی برای GitHub Actions WRITE کافی نیست.'
97 + : 'تأیید شما معتبر بود، اما GitHub عملیات را موفق اعلام نکرد. وضعیت Run را بررسی کنید.';
98 return {
99 text:
100 `⚠️ <b>اجرای عملیات در GitHub ناموفق بود</b>
@@ -91,11 +102,7 @@ function approvedActionFailedView(payload, error) {
102 ${detail}
103
104 این تأیید یک‌بار مصرف شده و با همان دکمه دوباره اجرا نمی‌شود.`,
94 - reply_markup: {
95 - inline_keyboard: [
96 - [{ text: '↩️ بازگشت به Run', callback_data: fallback }]
97 - ]
98 - }
105 + reply_markup: { inline_keyboard: [[{ text: workspaceAction ? '↩️ بازگشت به پروژه' : '↩️ بازگشت به Run', callback_data: fallback }]] }
106 };
107 }
108
@@ -110,7 +117,6 @@ function callbackReadFailedView(data, error) {
117 ? 'GitHub درخواست Issues را با خطای 403 رد کرد. در Fine-grained token، مجوز Repository permissions → Issues را روی Read قرار دهید.'
118 : 'GitHub این درخواست خواندنی را با خطای 403 رد کرد. مجوز Read مربوط به این بخش در توکن فعلی کافی نیست.'
119 : 'دریافت اطلاعات از سرویس با خطا مواجه شد. هیچ تغییری انجام نشد.';
113 -
120 return {
121 text:
122 `⚠️ <b>دریافت اطلاعات با خطا مواجه شد</b>
@@ -118,11 +124,7 @@ function callbackReadFailedView(data, error) {
124 ${detail}
125
126 این خطا هیچ عملیات تغییردهنده‌ای اجرا نکرد.`,
121 - reply_markup: {
122 - inline_keyboard: [
123 - [{ text: repoMatch ? '↩️ بازگشت به پروژه' : '↩️ منوی اصلی', callback_data: fallback }]
124 - ]
125 - }
127 + reply_markup: { inline_keyboard: [[{ text: repoMatch ? '↩️ بازگشت به پروژه' : '↩️ منوی اصلی', callback_data: fallback }]] }
128 };
129 }
130
@@ -132,33 +134,23 @@ export class NexaDevBot {
134 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
135 this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
136 this.menu = new MenuManager(this.github);
135 - this.replayStore = new DurableApprovalReplayStore({
136 - namespace: env.APPROVAL_REPLAY_GUARD
137 - });
137 + this.replayStore = new DurableApprovalReplayStore({ namespace: env.APPROVAL_REPLAY_GUARD });
138 + this.workspaceStore = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
139 this.approvals = new ApprovalService({
140 secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
141 replayStore: this.replayStore
142 });
142 -
143 this.githubPlugin = createGitHubPlugin({
144 github: this.github,
145 - menu: this.menu
145 + menu: this.menu,
146 + workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
147 });
148 this.registry = new PluginRegistry([this.githubPlugin]);
149 this.policy = new ActionPolicy();
150 this.audit = new AuditLogger({
150 - secrets: [
151 - env.TELEGRAM_BOT_TOKEN,
152 - env.TELEGRAM_WEBHOOK_SECRET,
153 - env.GITHUB_TOKEN,
154 - env.APPROVAL_SIGNING_SECRET
155 - ]
156 - });
157 - this.router = new PluginRouter({
158 - registry: this.registry,
159 - policy: this.policy,
160 - audit: this.audit
151 + secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.APPROVAL_SIGNING_SECRET]
152 });
153 + this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
154 }
155
156 async handleUpdate(update) {
@@ -177,15 +169,8 @@ export class NexaDevBot {
169 const ownerId = query.from?.id;
170
171 let callbackAnswered = true;
180 - try {
181 - await this.telegram.answerCallbackQuery(callbackId);
182 - } catch {
183 - callbackAnswered = false;
184 - }
185 -
186 - if (!chatId || !messageId) {
187 - return { ok: false, error: 'Missing message context for callback', callbackAnswered };
188 - }
172 + try { await this.telegram.answerCallbackQuery(callbackId); } catch { callbackAnswered = false; }
173 + if (!chatId || !messageId) return { ok: false, error: 'Missing message context for callback', callbackAnswered };
174
175 try {
176 if (data.startsWith('approve:')) {
@@ -193,102 +178,52 @@ export class NexaDevBot {
178 const token = data.slice('approve:'.length);
179 let payload;
180 try {
196 - payload = await this.approvals.consume(token, {
197 - ownerId: String(ownerId),
198 - pluginId: 'github',
199 - risk: 'WRITE'
200 - });
181 + payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', risk: 'WRITE' });
182 } catch (error) {
202 - this.audit.log({
203 - event: 'approval_rejected',
204 - pluginId: 'github',
205 - risk: 'WRITE',
206 - outcome: 'rejected',
207 - error: error?.message || 'Approval rejected'
208 - });
183 + this.audit.log({ event: 'approval_rejected', pluginId: 'github', risk: 'WRITE', outcome: 'rejected', error: error?.message || 'Approval rejected' });
184 const view = approvalRejectedView(message, error);
210 - const res = await this.telegram.editMessageText(
211 - chatId,
212 - messageId,
213 - view.text,
214 - view.reply_markup
215 - );
216 - return {
217 - ok: false,
218 - approvalRejected: true,
219 - error: error?.message || 'Approval rejected',
220 - callbackAnswered,
221 - edited: true,
222 - res
223 - };
185 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
186 + return { ok: false, approvalRejected: true, error: error?.message || 'Approval rejected', callbackAnswered, edited: true, res };
187 }
188
226 - this.audit.log({
227 - event: 'approval_verified',
228 - pluginId: payload.pluginId,
229 - actionId: payload.actionId,
230 - risk: payload.risk,
231 - outcome: 'verified'
232 - });
233 -
189 + this.audit.log({ event: 'approval_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, outcome: 'verified' });
190 const sourceCallback = approvalSourceCallback(payload);
191 let routed;
192 try {
193 routed = await this.router.dispatchCallback(sourceCallback, {
194 isOwner: true,
195 + ownerId: String(ownerId),
196 approved: true
197 });
241 - if (!routed || routed.requiresApproval || routed.denied) {
242 - throw new Error('Approved action could not be dispatched');
243 - }
198 + if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved action could not be dispatched');
199 } catch (error) {
200 const view = approvedActionFailedView(payload, error);
246 - const res = await this.telegram.editMessageText(
247 - chatId,
248 - messageId,
249 - view.text,
250 - view.reply_markup
251 - );
252 - return {
253 - ok: false,
254 - approved: true,
255 - providerError: true,
256 - actionId: payload.actionId,
257 - error: error?.message || 'GitHub operation failed',
258 - callbackAnswered,
259 - edited: true,
260 - res
261 - };
201 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
202 + return { ok: false, approved: true, providerError: true, actionId: payload.actionId, error: error?.message || 'GitHub operation failed', callbackAnswered, edited: true, res };
203 }
204
264 - const res = await this.telegram.editMessageText(
265 - chatId,
266 - messageId,
267 - routed.text,
268 - routed.reply_markup
269 - );
270 - return {
271 - ok: true,
272 - approved: true,
273 - actionId: payload.actionId,
274 - callbackAnswered,
275 - edited: true,
276 - res
277 - };
205 + const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
206 + return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
207 }
208
280 - const routed = await this.router.dispatchCallback(data, { isOwner: true });
209 + const routed = await this.router.dispatchCallback(data, {
210 + isOwner: true,
211 + ownerId: ownerId === undefined || ownerId === null ? '' : String(ownerId)
212 + });
213 if (routed?.requiresApproval) {
214 const approval = routed.approval;
215 const repoId = approval?.input?.repoId;
216 + if (!approval || !Number.isSafeInteger(Number(repoId))) throw new Error('Approval metadata is missing');
217 + const workspaceApproval = routed.actionId === 'github.workspace.commit_branch';
218 const runId = approval?.input?.runId;
285 - if (!approval || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(runId))) {
219 + const intentId = String(approval?.input?.intentId || '');
220 + if (workspaceApproval) {
221 + if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval metadata is missing');
222 + } else if (!Number.isSafeInteger(Number(runId))) {
223 throw new Error('Approval metadata is missing');
224 }
225 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
289 - if (!this.approvals.isReplayProtected()) {
290 - throw new Error('Durable approval replay protection is not configured');
291 - }
226 + if (!this.approvals.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
227
228 const token = await this.approvals.issue({
229 pluginId: routed.pluginId,
@@ -297,90 +232,36 @@ export class NexaDevBot {
232 ownerId: String(ownerId),
233 input: approval.input
234 });
300 - this.audit.log({
301 - event: 'approval_issued',
302 - pluginId: routed.pluginId,
303 - actionId: routed.actionId,
304 - risk: routed.risk,
305 - outcome: 'pending'
306 - });
307 -
308 - const view = approvalView({
309 - label: approval.label || routed.actionId,
310 - token,
311 - repoId,
312 - runId
313 - });
314 - const res = await this.telegram.editMessageText(
315 - chatId,
316 - messageId,
317 - view.text,
318 - view.reply_markup
319 - );
320 - return {
321 - ok: true,
322 - approvalRequired: true,
323 - actionId: routed.actionId,
324 - risk: routed.risk,
325 - callbackAnswered,
326 - edited: true,
327 - res
328 - };
329 - }
330 - if (routed?.denied) {
331 - return {
332 - ok: false,
333 - denied: true,
334 - actionId: routed.actionId,
335 - reason: routed.reason,
336 - callbackAnswered
337 - };
235 + this.audit.log({ event: 'approval_issued', pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, outcome: 'pending' });
236 + const cancelCallback = approval.cancelCallback || (Number.isSafeInteger(Number(runId)) ? `run:${repoId}:${runId}` : `repo:${repoId}`);
237 + const view = approvalView({ label: approval.label || routed.actionId, token, cancelCallback });
238 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
239 + return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
240 }
241 + if (routed?.denied) return { ok: false, denied: true, actionId: routed.actionId, reason: routed.reason, callbackAnswered };
242
243 const view = routed || await this.menu.renderByCallback(data);
341 - const res = await this.telegram.editMessageText(
342 - chatId,
343 - messageId,
344 - view.text,
345 - view.reply_markup
346 - );
347 -
244 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
245 return { ok: true, edited: true, callbackAnswered, res };
246 } catch (err) {
350 - if (err.message && err.message.includes('message is not modified')) {
351 - return { ok: true, unmodified: true, callbackAnswered };
352 - }
353 -
247 + if (err.message && err.message.includes('message is not modified')) return { ok: true, unmodified: true, callbackAnswered };
248 if (!data.startsWith('approve:')) {
249 try {
250 const view = callbackReadFailedView(data, err);
357 - const res = await this.telegram.editMessageText(
358 - chatId,
359 - messageId,
360 - view.text,
361 - view.reply_markup
362 - );
363 - return {
364 - ok: false,
365 - error: err.message,
366 - providerError: true,
367 - callbackAnswered,
368 - edited: true,
369 - res
370 - };
251 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
252 + return { ok: false, error: err.message, providerError: true, callbackAnswered, edited: true, res };
253 } catch {
254 // Preserve the original provider/navigation error when feedback delivery also fails.
255 }
256 }
375 -
257 return { ok: false, error: err.message, callbackAnswered };
258 }
259 }
260
261 async handleMessage(message) {
262 const chatId = message.chat?.id;
382 - const text = (message.text || '').trim();
383 -
263 + const rawText = typeof message.text === 'string' ? message.text : '';
264 + const text = rawText.trim();
265 if (!chatId) return { ok: false, error: 'Missing chat_id' };
266
267 if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
@@ -392,13 +273,8 @@ export class NexaDevBot {
273 if (text === '/repos') {
274 const routed = await this.router.dispatchCommand(text, { isOwner: true });
275 if (routed?.requiresApproval || routed?.denied || !routed) {
395 - return {
396 - ok: false,
397 - command: 'repos',
398 - error: routed?.reason || 'GitHub repository route unavailable'
399 - };
276 + return { ok: false, command: 'repos', error: routed?.reason || 'GitHub repository route unavailable' };
277 }
401 -
278 const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
279 return { ok: true, command: 'repos', res };
280 }
@@ -409,13 +285,27 @@ export class NexaDevBot {
285 return { ok: true, command: 'status', res };
286 }
287
412 - const defaultText = `💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:`;
288 + const ownerId = message.from?.id;
289 + if (ownerId !== undefined && ownerId !== null && this.workspaceStore.isConfigured()) {
290 + const pending = await this.workspaceStore.getPendingInput({ ownerId: String(ownerId) });
291 + if (pending) {
292 + const routed = await this.router.dispatchMessage(
293 + { pending, text: rawText },
294 + { isOwner: true, ownerId: String(ownerId) }
295 + );
296 + if (routed?.requiresApproval || routed?.denied || !routed) {
297 + return { ok: false, error: routed?.reason || 'Workspace input route unavailable' };
298 + }
299 + const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
300 + return { ok: true, workspaceInput: true, res };
301 + }
302 + }
303 +
304 + const defaultText = '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
305 const view = {
306 text: defaultText,
307 reply_markup: {
416 - inline_keyboard: [
417 - [{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]
418 - ]
308 + inline_keyboard: [[{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]]
309 }
310 };
311 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
src/core/approval.js
+36 -11
@@ -1,16 +1,25 @@
1 const encoder = new TextEncoder();
2 const SIGNING_DOMAIN = 'nexa-approval-v1';
3 +const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
4
5 const DEFAULT_CODECS = new Map([
6 ['github.workflow.run.rerun_failed', {
7 code: 'r',
8 pluginId: 'github',
8 - risk: 'WRITE'
9 + risk: 'WRITE',
10 + target: 'run'
11 }],
12 ['github.workflow.run.cancel', {
13 code: 'c',
14 pluginId: 'github',
13 - risk: 'WRITE'
15 + risk: 'WRITE',
16 + target: 'run'
17 + }],
18 + ['github.workspace.commit_branch', {
19 + code: 'e',
20 + pluginId: 'github',
21 + risk: 'WRITE',
22 + target: 'intent'
23 }]
24 ]);
25
@@ -161,19 +170,29 @@ export class ApprovalService {
170 #encodeBody(payload) {
171 const codec = compactCodecFor(payload.actionId);
172 const repoId = payload.input?.repoId;
164 - const runId = payload.input?.runId;
173 if (
174 codec &&
175 codec.pluginId === payload.pluginId &&
176 codec.risk === payload.risk &&
169 - Number.isSafeInteger(Number(repoId)) &&
170 - Number.isSafeInteger(Number(runId))
177 + Number.isSafeInteger(Number(repoId))
178 ) {
179 + let target;
180 + if (codec.target === 'run') {
181 + const runId = payload.input?.runId;
182 + if (!Number.isSafeInteger(Number(runId))) return `j.${textToBase64Url(JSON.stringify(payload))}`;
183 + target = toBase36Int(runId);
184 + } else if (codec.target === 'intent') {
185 + const intentId = String(payload.input?.intentId || '');
186 + if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Invalid approval intent ID');
187 + target = intentId;
188 + } else {
189 + return `j.${textToBase64Url(JSON.stringify(payload))}`;
190 + }
191 return [
192 '1',
193 codec.code,
194 toBase36Int(repoId),
176 - toBase36Int(runId),
195 + target,
196 toBase36Int(payload.expiresAt),
197 payload.nonce
198 ].join('.');
@@ -196,20 +215,26 @@ export class ApprovalService {
215
216 const parts = body.split('.');
217 if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload');
199 - const [, code, repoPart, runPart, expiryPart, nonce] = parts;
218 + const [, code, repoPart, targetPart, expiryPart, nonce] = parts;
219 const codec = compactCodecByCode(code);
220 if (!codec) throw new Error('Invalid approval action');
221 const expiresAt = fromBase36Int(expiryPart);
222 + const input = { repoId: fromBase36Int(repoPart) };
223 + if (codec.target === 'run') {
224 + input.runId = fromBase36Int(targetPart);
225 + } else if (codec.target === 'intent') {
226 + if (!INTENT_ID_PATTERN.test(targetPart)) throw new Error('Invalid approval intent ID');
227 + input.intentId = targetPart;
228 + } else {
229 + throw new Error('Invalid approval target');
230 + }
231 return {
232 v: 1,
233 pluginId: codec.pluginId,
234 actionId: codec.actionId,
235 risk: codec.risk,
236 ownerId,
209 - input: {
210 - repoId: fromBase36Int(repoPart),
211 - runId: fromBase36Int(runPart)
212 - },
237 + input,
238 issuedAt: expiresAt - this.ttlMs,
239 expiresAt,
240 nonce
src/core/router.js
+51 -4
@@ -1,3 +1,41 @@
1 +const AUDIT_METADATA_KEYS = Object.freeze(new Set([
2 + 'repoId',
3 + 'workspaceId',
4 + 'intentId',
5 + 'path',
6 + 'contentDigest',
7 + 'commitMessageDigest',
8 + 'baseHeadSha',
9 + 'targetBranch',
10 + 'commitSha',
11 + 'branch',
12 + 'idempotent'
13 +]));
14 +
15 +function sanitizeAuditMetadata(value) {
16 + if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
17 + const safe = {};
18 + for (const [key, raw] of Object.entries(value)) {
19 + if (!AUDIT_METADATA_KEYS.has(key)) continue;
20 + if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
21 + safe[key] = raw;
22 + continue;
23 + }
24 + if (typeof raw === 'boolean') {
25 + safe[key] = raw;
26 + continue;
27 + }
28 + if (typeof raw === 'string') safe[key] = raw.slice(0, 240);
29 + }
30 + return safe;
31 +}
32 +
33 +function withoutAuditMetadata(result) {
34 + if (!result || typeof result !== 'object' || Array.isArray(result) || !Object.hasOwn(result, 'audit')) return result;
35 + const { audit, ...publicResult } = result;
36 + return publicResult;
37 +}
38 +
39 export class PluginRouter {
40 constructor({ registry, policy, audit } = {}) {
41 if (!registry) throw new Error('PluginRouter registry is required');
@@ -17,6 +55,10 @@ export class PluginRouter {
55 return this.#dispatch('resolveCallback', data, context);
56 }
57
58 + async dispatchMessage(payload, context = {}) {
59 + return this.#dispatch('resolveMessage', payload, context);
60 + }
61 +
62 async #dispatch(resolverName, input, context) {
63 for (const plugin of this.registry.getPlugins()) {
64 const resolver = plugin?.[resolverName];
@@ -34,6 +76,7 @@ export class PluginRouter {
76 isOwner: context.isOwner === true,
77 approved: context.approved === true
78 });
79 + const routeAudit = sanitizeAuditMetadata(route.audit);
80
81 this.audit.log({
82 event: 'action_attempt',
@@ -43,7 +86,8 @@ export class PluginRouter {
86 outcome: decision.allowed
87 ? 'allowed'
88 : (decision.requiresApproval ? 'approval_required' : 'denied'),
46 - reason: decision.reason
89 + reason: decision.reason,
90 + ...routeAudit
91 });
92
93 if (!decision.allowed) {
@@ -70,9 +114,11 @@ export class PluginRouter {
114 pluginId,
115 actionId,
116 risk: decision.risk,
73 - outcome: 'success'
117 + outcome: 'success',
118 + ...routeAudit,
119 + ...sanitizeAuditMetadata(result?.audit)
120 });
75 - return result;
121 + return withoutAuditMetadata(result);
122 } catch (error) {
123 this.audit.log({
124 event: 'action_result',
@@ -80,7 +126,8 @@ export class PluginRouter {
126 actionId,
127 risk: decision.risk,
128 outcome: 'error',
83 - error: error?.message || 'Unknown plugin error'
129 + error: error?.message || 'Unknown plugin error',
130 + ...routeAudit
131 });
132 throw error;
133 }
src/core/workspace-policy.js new
+128
@@ -0,0 +1,128 @@
1 +const MAX_CHARS = 3000;
2 +const MAX_BYTES = 12000;
3 +const MAX_COMMIT_MESSAGE = 120;
4 +const SAFE_HANDLE = /^[A-Za-z0-9_-]{10}$/;
5 +
6 +const encoder = new TextEncoder();
7 +
8 +const sensitivePath = value => {
9 + const path = String(value || '').replaceAll('\\', '/').toLowerCase();
10 + const name = path.split('/').pop() || '';
11 + if (name === '.env' || name.startsWith('.env.')) return true;
12 + if (name === 'id_rsa' || name === 'id_ed25519') return true;
13 + if (/\.(pem|key|p12|pfx)$/i.test(name)) return true;
14 + if (name === 'credentials.json') return true;
15 + if (/^service-account.*\.json$/i.test(name)) return true;
16 + return false;
17 +};
18 +
19 +const codePointLength = value => Array.from(value).length;
20 +
21 +export function validateEditableFile({ path, text, byteLength } = {}) {
22 + const source = String(text ?? '');
23 + const charLength = codePointLength(source);
24 + const computedBytes = encoder.encode(source).byteLength;
25 + const providerBytes = Number(byteLength);
26 + const effectiveBytes = Number.isFinite(providerBytes) && providerBytes >= 0
27 + ? Math.max(computedBytes, providerBytes)
28 + : computedBytes;
29 +
30 + let reason = '';
31 + if (sensitivePath(path)) reason = 'Sensitive file path is not editable.';
32 + else if (source.includes('\0')) reason = 'Binary-like content is not editable.';
33 + else if (/^version https:\/\/git-lfs\.github\.com\/spec\/v1(?:\r?\n|$)/.test(source)) reason = 'Git LFS pointer files are not editable.';
34 + else if (charLength > MAX_CHARS) reason = 'Editable text is limited to 3,000 Unicode characters.';
35 + else if (effectiveBytes > MAX_BYTES) reason = 'Editable text is limited to 12,000 UTF-8 bytes.';
36 +
37 + return {
38 + editable: reason === '',
39 + reason,
40 + text: source,
41 + charLength,
42 + byteLength: effectiveBytes
43 + };
44 +}
45 +
46 +export function normalizeCommitMessage(value) {
47 + const normalized = String(value ?? '').trim().replace(/\s+/g, ' ');
48 + if (!normalized) throw new Error('Commit message is required');
49 + if (codePointLength(normalized) > MAX_COMMIT_MESSAGE) {
50 + throw new Error('Commit message must be 120 characters or fewer');
51 + }
52 + return normalized;
53 +}
54 +
55 +export function makeTargetBranch(workspaceId) {
56 + const id = String(workspaceId ?? '');
57 + if (!SAFE_HANDLE.test(id)) throw new Error('Workspace ID must be a 10-character URL-safe handle');
58 + return `nexa/edit-${id}`;
59 +}
60 +
61 +export async function digestText(value) {
62 + const digest = await crypto.subtle.digest('SHA-256', encoder.encode(String(value ?? '')));
63 + return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
64 +}
65 +
66 +function linesOf(value) {
67 + return String(value ?? '').split('\n');
68 +}
69 +
70 +function diffOperations(beforeLines, afterLines) {
71 + const rows = beforeLines.length + 1;
72 + const cols = afterLines.length + 1;
73 + const table = new Uint16Array(rows * cols);
74 + const at = (i, j) => i * cols + j;
75 +
76 + for (let i = beforeLines.length - 1; i >= 0; i -= 1) {
77 + for (let j = afterLines.length - 1; j >= 0; j -= 1) {
78 + table[at(i, j)] = beforeLines[i] === afterLines[j]
79 + ? table[at(i + 1, j + 1)] + 1
80 + : Math.max(table[at(i + 1, j)], table[at(i, j + 1)]);
81 + }
82 + }
83 +
84 + const operations = [];
85 + let i = 0;
86 + let j = 0;
87 + while (i < beforeLines.length || j < afterLines.length) {
88 + if (i < beforeLines.length && j < afterLines.length && beforeLines[i] === afterLines[j]) {
89 + operations.push({ kind: ' ', line: beforeLines[i] });
90 + i += 1;
91 + j += 1;
92 + continue;
93 + }
94 + if (j < afterLines.length && (i >= beforeLines.length || table[at(i, j + 1)] >= table[at(i + 1, j)])) {
95 + operations.push({ kind: '+', line: afterLines[j] });
96 + j += 1;
97 + continue;
98 + }
99 + operations.push({ kind: '-', line: beforeLines[i] });
100 + i += 1;
101 + }
102 + return operations;
103 +}
104 +
105 +export function buildUnifiedDiff({ path, before, after, maxChars = 2600 } = {}) {
106 + const safePath = String(path || 'file').replace(/[\r\n]/g, '');
107 + const operations = diffOperations(linesOf(before), linesOf(after));
108 + const additions = operations.reduce((count, op) => count + (op.kind === '+' ? 1 : 0), 0);
109 + const deletions = operations.reduce((count, op) => count + (op.kind === '-' ? 1 : 0), 0);
110 + const raw = [
111 + `--- a/${safePath}`,
112 + `+++ b/${safePath}`,
113 + '@@',
114 + ...operations.map(op => `${op.kind}${op.line}`)
115 + ].join('\n');
116 +
117 + const limit = Math.max(32, Math.min(10000, Number(maxChars) || 2600));
118 + if (raw.length <= limit) {
119 + return { text: raw, additions, deletions, truncated: false };
120 + }
121 + const marker = '\n…';
122 + return {
123 + text: `${raw.slice(0, Math.max(0, limit - marker.length))}${marker}`,
124 + additions,
125 + deletions,
126 + truncated: true
127 + };
128 +}
src/core/workspace-store.js new
+102
@@ -0,0 +1,102 @@
1 +const jsonRequest = (url, body) => new Request(url, {
2 + method: 'POST',
3 + headers: { 'content-type': 'application/json' },
4 + body: JSON.stringify(body)
5 +});
6 +
7 +export class DurableWorkspaceStoreClient {
8 + constructor({ namespace = null, now = () => Date.now() } = {}) {
9 + this.namespace = namespace;
10 + this.now = now;
11 + }
12 +
13 + isConfigured() {
14 + return Boolean(
15 + this.namespace &&
16 + typeof this.namespace.idFromName === 'function' &&
17 + typeof this.namespace.get === 'function'
18 + );
19 + }
20 +
21 + async #call(ownerId, operation, payload = {}) {
22 + if (!this.isConfigured()) throw new Error('Durable workspace store is not configured');
23 + const owner = String(ownerId ?? '');
24 + if (!owner) throw new Error('Workspace owner is required');
25 + const id = this.namespace.idFromName(owner);
26 + const stub = this.namespace.get(id);
27 + const response = await stub.fetch(jsonRequest(`https://workspace-store/${operation}`, {
28 + ...payload,
29 + now: Number(this.now())
30 + }));
31 + let body = null;
32 + try { body = await response.json(); } catch { body = null; }
33 + if (!response.ok) {
34 + throw new Error(body?.error || `Durable workspace store failed (${response.status})`);
35 + }
36 + return body?.result ?? null;
37 + }
38 +
39 + createNavigationRefs({ ownerId, refs, ttlMs = 900_000 } = {}) {
40 + return this.#call(ownerId, 'refs/create', { refs, ttlMs });
41 + }
42 +
43 + resolveNavigationRef({ ownerId, refId } = {}) {
44 + return this.#call(ownerId, 'refs/get', { refId });
45 + }
46 +
47 + createWorkspace({ ownerId, ...workspace } = {}) {
48 + return this.#call(ownerId, 'workspace/create', workspace);
49 + }
50 +
51 + getWorkspace({ ownerId, workspaceId } = {}) {
52 + return this.#call(ownerId, 'workspace/get', { workspaceId });
53 + }
54 +
55 + updateDraft({ ownerId, workspaceId, text, digest } = {}) {
56 + return this.#call(ownerId, 'workspace/draft', { workspaceId, text, digest });
57 + }
58 +
59 + setPendingInput({ ownerId, workspaceId, mode } = {}) {
60 + return this.#call(ownerId, 'pending/set', { workspaceId, mode });
61 + }
62 +
63 + getPendingInput({ ownerId } = {}) {
64 + return this.#call(ownerId, 'pending/get');
65 + }
66 +
67 + consumePendingInput({ ownerId, workspaceId, mode } = {}) {
68 + return this.#call(ownerId, 'pending/consume', { workspaceId, mode });
69 + }
70 +
71 + setCommitMessage({ ownerId, workspaceId, message, digest } = {}) {
72 + return this.#call(ownerId, 'workspace/message', { workspaceId, message, digest });
73 + }
74 +
75 + sealIntent({ ownerId, workspaceId, intent } = {}) {
76 + return this.#call(ownerId, 'intent/seal', { workspaceId, intent });
77 + }
78 +
79 + getIntent({ ownerId, intentId } = {}) {
80 + return this.#call(ownerId, 'intent/get', { intentId });
81 + }
82 +
83 + beginCommit({ ownerId, intentId } = {}) {
84 + return this.#call(ownerId, 'intent/begin', { intentId });
85 + }
86 +
87 + setCandidateCommit({ ownerId, intentId, commitSha } = {}) {
88 + return this.#call(ownerId, 'intent/candidate', { intentId, commitSha });
89 + }
90 +
91 + completeCommit({ ownerId, intentId, commitSha, branch } = {}) {
92 + return this.#call(ownerId, 'intent/complete', { intentId, commitSha, branch });
93 + }
94 +
95 + markStale({ ownerId, intentId, reason } = {}) {
96 + return this.#call(ownerId, 'intent/stale', { intentId, reason });
97 + }
98 +
99 + cancelWorkspace({ ownerId, workspaceId } = {}) {
100 + return this.#call(ownerId, 'workspace/cancel', { workspaceId });
101 + }
102 +}
src/durable/workspace-store.js new
+352
@@ -0,0 +1,352 @@
1 +const json = (payload, status = 200) => Response.json(payload, { status });
2 +const HANDLE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
3 +const WORKSPACE_TTL_MS = 30 * 60_000;
4 +const REF_TTL_MS = 15 * 60_000;
5 +const COMMITTED_RETENTION_MS = 24 * 60 * 60_000;
6 +
7 +function randomHandle(length) {
8 + const bytes = new Uint8Array(length);
9 + crypto.getRandomValues(bytes);
10 + let out = '';
11 + for (const byte of bytes) out += HANDLE_ALPHABET[byte & 63];
12 + return out;
13 +}
14 +
15 +function finiteNow(value) {
16 + const parsed = Number(value);
17 + return Number.isFinite(parsed) ? parsed : Date.now();
18 +}
19 +
20 +function positiveTtl(value, fallback) {
21 + const parsed = Number(value);
22 + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
23 +}
24 +
25 +function expired(record, now) {
26 + return Boolean(record && Number.isFinite(Number(record.expiresAt)) && Number(record.expiresAt) < now);
27 +}
28 +
29 +export class WorkspaceStore {
30 + constructor(state) {
31 + this.state = state;
32 + }
33 +
34 + async fetch(request) {
35 + const url = new URL(request.url);
36 + if (request.method !== 'POST') return new Response('Not Found', { status: 404 });
37 +
38 + let payload;
39 + try { payload = await request.json(); } catch { return json({ error: 'Invalid workspace payload' }, 400); }
40 + const now = finiteNow(payload?.now);
41 +
42 + try {
43 + switch (url.pathname) {
44 + case '/refs/create': return json({ result: await this.#createRefs(payload, now) });
45 + case '/refs/get': return json({ result: await this.#getExpiring(`ref:${String(payload.refId || '')}`, now) });
46 + case '/workspace/create': return json({ result: await this.#createWorkspace(payload, now) });
47 + case '/workspace/get': return json({ result: await this.#getExpiring(`ws:${String(payload.workspaceId || '')}`, now) });
48 + case '/workspace/draft': return json({ result: await this.#updateDraft(payload, now) });
49 + case '/workspace/message': return json({ result: await this.#setCommitMessage(payload, now) });
50 + case '/workspace/cancel': return json({ result: await this.#cancelWorkspace(payload) });
51 + case '/pending/set': return json({ result: await this.#setPending(payload, now) });
52 + case '/pending/get': return json({ result: await this.#getPending(now) });
53 + case '/pending/consume': return json({ result: await this.#consumePending(payload, now) });
54 + case '/intent/seal': return json({ result: await this.#sealIntent(payload, now) });
55 + case '/intent/get': return json({ result: await this.#getExpiring(`intent:${String(payload.intentId || '')}`, now) });
56 + case '/intent/begin': return json({ result: await this.#beginCommit(payload, now) });
57 + case '/intent/candidate': return json({ result: await this.#setCandidate(payload, now) });
58 + case '/intent/complete': return json({ result: await this.#completeCommit(payload, now) });
59 + case '/intent/stale': return json({ result: await this.#markStale(payload, now) });
60 + default: return new Response('Not Found', { status: 404 });
61 + }
62 + } catch (error) {
63 + return json({ error: String(error?.message || 'Workspace store operation failed') }, 400);
64 + }
65 + }
66 +
67 + async #schedule(expiresAt) {
68 + const expiry = Number(expiresAt);
69 + if (!Number.isFinite(expiry)) return;
70 + const current = Number(await this.state.storage.get('__next_alarm'));
71 + if (!Number.isFinite(current) || expiry < current) {
72 + await this.state.storage.put('__next_alarm', expiry);
73 + await this.state.storage.setAlarm(expiry);
74 + }
75 + }
76 +
77 + async #getExpiring(key, now) {
78 + if (!key || key.endsWith(':')) return null;
79 + const record = await this.state.storage.get(key);
80 + if (!record) return null;
81 + if (expired(record, now)) {
82 + await this.state.storage.delete(key);
83 + return null;
84 + }
85 + return record;
86 + }
87 +
88 + async #createRefs(payload, now) {
89 + if (!Array.isArray(payload.refs)) throw new Error('Navigation refs are required');
90 + const ttlMs = positiveTtl(payload.ttlMs, REF_TTL_MS);
91 + const expiresAt = now + ttlMs;
92 + const output = [];
93 + for (const source of payload.refs) {
94 + const refId = randomHandle(10);
95 + const record = {
96 + repoId: source?.repoId,
97 + path: String(source?.path || ''),
98 + type: source?.type === 'dir' ? 'dir' : 'file',
99 + sha: String(source?.sha || ''),
100 + expiresAt
101 + };
102 + await this.state.storage.put(`ref:${refId}`, record);
103 + output.push({ refId });
104 + }
105 + await this.#schedule(expiresAt);
106 + return output;
107 + }
108 +
109 + async #createWorkspace(payload, now) {
110 + const id = randomHandle(10);
111 + const expiresAt = Number.isFinite(Number(payload.expiresAt)) ? Number(payload.expiresAt) : now + WORKSPACE_TTL_MS;
112 + if (expiresAt <= now) throw new Error('Workspace expiry must be in the future');
113 + const workspace = {
114 + id,
115 + repoId: payload.repoId,
116 + repoFullName: String(payload.repoFullName || ''),
117 + baseBranch: String(payload.baseBranch || ''),
118 + baseHeadSha: String(payload.baseHeadSha || ''),
119 + baseTreeSha: String(payload.baseTreeSha || ''),
120 + path: String(payload.path || ''),
121 + blobSha: String(payload.blobSha || ''),
122 + originalText: String(payload.originalText ?? ''),
123 + originalDigest: String(payload.originalDigest || ''),
124 + draftText: String(payload.originalText ?? ''),
125 + draftDigest: String(payload.originalDigest || ''),
126 + commitMessage: '',
127 + commitMessageDigest: '',
128 + currentIntentId: null,
129 + state: 'DRAFT',
130 + createdAt: now,
131 + updatedAt: now,
132 + expiresAt
133 + };
134 + await this.state.storage.put(`ws:${id}`, workspace);
135 + await this.#schedule(expiresAt);
136 + return workspace;
137 + }
138 +
139 + async #requireWorkspace(workspaceId, now) {
140 + const workspace = await this.#getExpiring(`ws:${String(workspaceId || '')}`, now);
141 + if (!workspace) throw new Error('Workspace not found or expired');
142 + return workspace;
143 + }
144 +
145 + async #updateDraft(payload, now) {
146 + const workspace = await this.#requireWorkspace(payload.workspaceId, now);
147 + const digest = String(payload.digest || '');
148 + if (!digest) throw new Error('Draft digest is required');
149 + const changed = digest !== workspace.draftDigest;
150 + const updated = {
151 + ...workspace,
152 + draftText: String(payload.text ?? ''),
153 + draftDigest: digest,
154 + updatedAt: now,
155 + ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
156 + };
157 + await this.state.storage.put(`ws:${workspace.id}`, updated);
158 + return updated;
159 + }
160 +
161 + async #setCommitMessage(payload, now) {
162 + const workspace = await this.#requireWorkspace(payload.workspaceId, now);
163 + const digest = String(payload.digest || '');
164 + if (!digest) throw new Error('Commit message digest is required');
165 + const changed = digest !== workspace.commitMessageDigest;
166 + const updated = {
167 + ...workspace,
168 + commitMessage: String(payload.message || ''),
169 + commitMessageDigest: digest,
170 + updatedAt: now,
171 + ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
172 + };
173 + await this.state.storage.put(`ws:${workspace.id}`, updated);
174 + return updated;
175 + }
176 +
177 + async #setPending(payload, now) {
178 + const workspace = await this.#requireWorkspace(payload.workspaceId, now);
179 + const mode = String(payload.mode || '');
180 + if (!['draft', 'commit_message'].includes(mode)) throw new Error('Pending input mode is invalid');
181 + const pending = { workspaceId: workspace.id, mode, expiresAt: workspace.expiresAt };
182 + await this.state.storage.put('pending', pending);
183 + await this.#schedule(pending.expiresAt);
184 + return pending;
185 + }
186 +
187 + async #getPending(now) {
188 + const pending = await this.state.storage.get('pending');
189 + if (!pending) return null;
190 + if (expired(pending, now)) {
191 + await this.state.storage.delete('pending');
192 + return null;
193 + }
194 + const workspace = await this.#getExpiring(`ws:${pending.workspaceId}`, now);
195 + if (!workspace) {
196 + await this.state.storage.delete('pending');
197 + return null;
198 + }
199 + return { workspaceId: pending.workspaceId, mode: pending.mode };
200 + }
201 +
202 + async #consumePending(payload, now) {
203 + return this.state.storage.transaction(async txn => {
204 + const pending = await txn.get('pending');
205 + if (!pending || expired(pending, now)) {
206 + if (pending) await txn.delete('pending');
207 + return false;
208 + }
209 + if (pending.workspaceId !== String(payload.workspaceId || '') || pending.mode !== String(payload.mode || '')) return false;
210 + await txn.delete('pending');
211 + return true;
212 + });
213 + }
214 +
215 + async #sealIntent(payload, now) {
216 + const workspace = await this.#requireWorkspace(payload.workspaceId, now);
217 + const proposed = payload.intent && typeof payload.intent === 'object' ? payload.intent : null;
218 + if (!proposed?.intentDigest) throw new Error('Commit intent digest is required');
219 +
220 + if (workspace.currentIntentId) {
221 + const existing = await this.#getExpiring(`intent:${workspace.currentIntentId}`, now);
222 + if (existing?.intentDigest === proposed.intentDigest) return existing;
223 + }
224 +
225 + const id = randomHandle(8);
226 + const intent = {
227 + ...proposed,
228 + id,
229 + workspaceId: workspace.id,
230 + state: 'READY',
231 + candidateCommitSha: null,
232 + commitSha: null,
233 + branch: null,
234 + createdAt: now,
235 + updatedAt: now,
236 + expiresAt: workspace.expiresAt
237 + };
238 + await this.state.storage.put(`intent:${id}`, intent);
239 + await this.state.storage.put(`ws:${workspace.id}`, {
240 + ...workspace,
241 + currentIntentId: id,
242 + state: 'READY',
243 + updatedAt: now
244 + });
245 + await this.#schedule(intent.expiresAt);
246 + return intent;
247 + }
248 +
249 + async #beginCommit(payload, now) {
250 + const key = `intent:${String(payload.intentId || '')}`;
251 + return this.state.storage.transaction(async txn => {
252 + const intent = await txn.get(key);
253 + if (!intent || expired(intent, now)) throw new Error('Commit intent not found or expired');
254 + if (intent.state === 'COMMITTED') return { disposition: 'committed', intent };
255 + if (intent.state === 'COMMITTING') return { disposition: 'resume', intent };
256 + if (intent.state !== 'READY') throw new Error(`Commit intent is ${intent.state || 'invalid'}`);
257 + const updated = { ...intent, state: 'COMMITTING', updatedAt: now };
258 + await txn.put(key, updated);
259 + return { disposition: 'start', intent: updated };
260 + });
261 + }
262 +
263 + async #setCandidate(payload, now) {
264 + const key = `intent:${String(payload.intentId || '')}`;
265 + return this.state.storage.transaction(async txn => {
266 + const intent = await txn.get(key);
267 + if (!intent || expired(intent, now)) throw new Error('Commit intent not found or expired');
268 + if (intent.state === 'COMMITTED') return intent;
269 + if (intent.state !== 'COMMITTING') throw new Error('Commit intent is not committing');
270 + const updated = { ...intent, candidateCommitSha: String(payload.commitSha || ''), updatedAt: now };
271 + await txn.put(key, updated);
272 + return updated;
273 + });
274 + }
275 +
276 + async #completeCommit(payload, now) {
277 + const key = `intent:${String(payload.intentId || '')}`;
278 + const retainedUntil = now + COMMITTED_RETENTION_MS;
279 + const completed = await this.state.storage.transaction(async txn => {
280 + const intent = await txn.get(key);
281 + if (!intent) throw new Error('Commit intent not found');
282 + if (intent.state === 'COMMITTED') return intent;
283 + if (intent.state !== 'COMMITTING') throw new Error('Commit intent is not committing');
284 + const updated = {
285 + ...intent,
286 + state: 'COMMITTED',
287 + commitSha: String(payload.commitSha || ''),
288 + branch: String(payload.branch || ''),
289 + updatedAt: now,
290 + expiresAt: retainedUntil
291 + };
292 + await txn.put(key, updated);
293 + const workspaceKey = `ws:${intent.workspaceId}`;
294 + const workspace = await txn.get(workspaceKey);
295 + if (workspace) {
296 + await txn.put(workspaceKey, {
297 + ...workspace,
298 + state: 'COMMITTED',
299 + currentIntentId: intent.id,
300 + commitSha: updated.commitSha,
301 + branch: updated.branch,
302 + updatedAt: now,
303 + expiresAt: retainedUntil
304 + });
305 + }
306 + return updated;
307 + });
308 + await this.#schedule(retainedUntil);
309 + return completed;
310 + }
311 +
312 + async #markStale(payload, now) {
313 + const key = `intent:${String(payload.intentId || '')}`;
314 + return this.state.storage.transaction(async txn => {
315 + const intent = await txn.get(key);
316 + if (!intent) throw new Error('Commit intent not found');
317 + if (intent.state === 'COMMITTED') return intent;
318 + const updated = { ...intent, state: 'STALE', staleReason: String(payload.reason || 'stale'), updatedAt: now };
319 + await txn.put(key, updated);
320 + return updated;
321 + });
322 + }
323 +
324 + async #cancelWorkspace(payload) {
325 + const workspaceId = String(payload.workspaceId || '');
326 + if (!workspaceId) throw new Error('Workspace ID is required');
327 + await this.state.storage.transaction(async txn => {
328 + await txn.delete(`ws:${workspaceId}`);
329 + const pending = await txn.get('pending');
330 + if (pending?.workspaceId === workspaceId) await txn.delete('pending');
331 + });
332 + return { cancelled: true };
333 + }
334 +
335 + async alarm() {
336 + const now = Date.now();
337 + const entries = await this.state.storage.list();
338 + let next = Infinity;
339 + for (const [key, value] of entries) {
340 + if (key === '__next_alarm') continue;
341 + const expiry = Number(value?.expiresAt);
342 + if (!Number.isFinite(expiry)) continue;
343 + if (expiry <= now) await this.state.storage.delete(key);
344 + else next = Math.min(next, expiry);
345 + }
346 + await this.state.storage.delete('__next_alarm');
347 + if (Number.isFinite(next)) {
348 + await this.state.storage.put('__next_alarm', next);
349 + await this.state.storage.setAlarm(next);
350 + }
351 + }
352 +}
src/github.js
+125 -4
@@ -13,6 +13,29 @@ const fullSha = (value, label = 'Git commit') => {
13 if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`);
14 return text;
15 };
16 +const gitBranch = value => {
17 + const branch = String(value || '');
18 + if (!branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('\0')) {
19 + throw new Error('Invalid Git branch');
20 + }
21 + return branch;
22 +};
23 +const encodedBranch = value => gitBranch(value).split('/').map(encodeURIComponent).join('/');
24 +const encodedPath = value => String(value || '').split('/').filter(Boolean).map(encodeURIComponent).join('/');
25 +const decodeBase64Utf8 = value => {
26 + let binary;
27 + try {
28 + binary = atob(String(value || '').replace(/\s/g, ''));
29 + } catch {
30 + throw new Error('GitHub file content is not valid base64');
31 + }
32 + const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
33 + try {
34 + return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
35 + } catch {
36 + throw new Error('GitHub file content is not valid UTF-8 text');
37 + }
38 +};
39
40 export class GitHubService {
41 constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
@@ -35,7 +58,7 @@ export class GitHubService {
58 };
59 }
60
38 - async requestJson(url, label, { method = 'GET', body, allowEmpty = false } = {}) {
61 + async requestJson(url, label, { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}) {
62 const headers = this.getHeaders();
63 const options = { method, headers };
64 if (body !== undefined) {
@@ -49,6 +72,7 @@ export class GitHubService {
72 try { parsed = JSON.parse(raw); } catch { parsed = null; }
73 }
74 if (!res.ok) {
75 + if (allowNotFound && res.status === 404) return null;
76 const providerMessage = parsed?.message || raw.slice(0, 240);
77 const detail = providerMessage ? ` ${providerMessage}` : '';
78 throw new Error(`${label} failed: ${res.status}${detail}`);
@@ -192,14 +216,111 @@ export class GitHubService {
216 return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' }));
217 }
218
195 - async listFiles(repoRef, path = '') {
219 + async listFiles(repoRef, path = '', { ref } = {}) {
220 const { apiBase } = await this.getRepositoryContext(repoRef);
197 - const suffix = path ? `/contents/${path.split('/').map(encodeURIComponent).join('/')}` : '/contents';
198 - const data = await this.requestJson(`${apiBase}${suffix}`, 'GitHub contents');
221 + const suffix = path ? `/contents/${encodedPath(path)}` : '/contents';
222 + const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : '';
223 + const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents');
224 if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing');
225 return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
226 }
227
228 + async getGitRef(repoRef, branch, { allowMissing = false } = {}) {
229 + const branchName = gitBranch(branch);
230 + const { apiBase } = await this.getRepositoryContext(repoRef);
231 + const data = await this.requestJson(
232 + `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
233 + 'GitHub branch ref',
234 + { allowNotFound: allowMissing }
235 + );
236 + if (data === null) return null;
237 + return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') };
238 + }
239 +
240 + async getBranchSnapshot(repoRef, branch) {
241 + const branchName = gitBranch(branch);
242 + const { apiBase } = await this.getRepositoryContext(repoRef);
243 + const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref');
244 + const headSha = fullSha(ref?.object?.sha, 'Git branch head');
245 + const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit');
246 + const treeSha = fullSha(commit?.tree?.sha, 'Git tree');
247 + return { branch: branchName, headSha, treeSha };
248 + }
249 +
250 + async getFileAtRef(repoRef, path, ref) {
251 + const filePath = String(path || '');
252 + if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path');
253 + const commitRef = fullSha(ref);
254 + const { apiBase } = await this.getRepositoryContext(repoRef);
255 + const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file');
256 + if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file');
257 + if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported');
258 + const content = decodeBase64Utf8(data.content || '');
259 + return {
260 + path: data.path || filePath,
261 + sha: String(data.sha || ''),
262 + size: Number(data.size) || 0,
263 + encoding: 'utf-8',
264 + content
265 + };
266 + }
267 +
268 + async createGitBlob(repoRef, text) {
269 + const { apiBase } = await this.getRepositoryContext(repoRef);
270 + const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', {
271 + method: 'POST',
272 + body: { content: String(text ?? ''), encoding: 'utf-8' }
273 + });
274 + return { sha: fullSha(data?.sha, 'Git blob') };
275 + }
276 +
277 + async createGitTree(repoRef, { baseTreeSha, entries } = {}) {
278 + const base = fullSha(baseTreeSha, 'Git base tree');
279 + if (!Array.isArray(entries)) throw new Error('Git tree entries are required');
280 + const tree = entries.map(entry => {
281 + const path = String(entry?.path || '');
282 + if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path');
283 + if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry');
284 + return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') };
285 + });
286 + const { apiBase } = await this.getRepositoryContext(repoRef);
287 + const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', {
288 + method: 'POST',
289 + body: { base_tree: base, tree }
290 + });
291 + return { sha: fullSha(data?.sha, 'Git tree') };
292 + }
293 +
294 + async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) {
295 + const commitMessage = String(message || '');
296 + if (!commitMessage) throw new Error('Git commit message is required');
297 + const tree = fullSha(treeSha, 'Git tree');
298 + const parent = fullSha(parentSha, 'Git parent commit');
299 + const date = new Date(String(timestamp || ''));
300 + if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp');
301 + const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) };
302 + const { apiBase } = await this.getRepositoryContext(repoRef);
303 + const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', {
304 + method: 'POST',
305 + body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity }
306 + });
307 + return { sha: fullSha(data?.sha, 'Git commit') };
308 + }
309 +
310 + async createGitBranchRef(repoRef, { branch, sha } = {}) {
311 + const branchName = gitBranch(branch);
312 + const commitSha = fullSha(sha, 'Git commit');
313 + const { apiBase } = await this.getRepositoryContext(repoRef);
314 + const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', {
315 + method: 'POST',
316 + body: { ref: `refs/heads/${branchName}`, sha: commitSha }
317 + });
318 + return {
319 + ref: String(data?.ref || `refs/heads/${branchName}`),
320 + sha: fullSha(data?.object?.sha || commitSha, 'Git commit')
321 + };
322 + }
323 +
324 async listTree(repoRef, sha) {
325 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA');
326 const { apiBase } = await this.getRepositoryContext(repoRef);
src/index.js
+1
@@ -1,5 +1,6 @@
1 import { NexaDevBot } from './bot.js';
2 export { ApprovalReplayGuard } from './durable/approval-replay-guard.js';
3 +export { WorkspaceStore } from './durable/workspace-store.js';
4
5 const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
6 status,
src/plugins/github/manifest.js
+10 -1
@@ -1,7 +1,7 @@
1 export const githubPluginManifest = Object.freeze({
2 id: 'github',
3 name: 'GitHub',
4 - version: 3,
4 + version: 6,
5 commands: Object.freeze(['/repos']),
6 actions: Object.freeze({
7 'github.repos.list': Object.freeze({ risk: 'READ' }),
@@ -26,6 +26,15 @@ export const githubPluginManifest = Object.freeze({
26 'github.pr.checks.list': Object.freeze({ risk: 'READ' }),
27 'github.issues.list': Object.freeze({ risk: 'READ' }),
28 'github.releases.list': Object.freeze({ risk: 'READ' }),
29 + 'github.workspace.navigate': Object.freeze({ risk: 'READ' }),
30 + 'github.workspace.create': Object.freeze({ risk: 'READ' }),
31 + 'github.workspace.view': Object.freeze({ risk: 'READ' }),
32 + 'github.workspace.input.prepare': Object.freeze({ risk: 'READ' }),
33 + 'github.workspace.input.apply': Object.freeze({ risk: 'READ' }),
34 + 'github.workspace.diff': Object.freeze({ risk: 'READ' }),
35 + 'github.workspace.ready': Object.freeze({ risk: 'READ' }),
36 + 'github.workspace.cancel': Object.freeze({ risk: 'READ' }),
37 + 'github.workspace.commit_branch': Object.freeze({ risk: 'WRITE' }),
38 'github.workflow.run.rerun_failed': Object.freeze({ risk: 'WRITE' }),
39 'github.workflow.run.cancel': Object.freeze({ risk: 'WRITE' })
40 })
src/plugins/github/plugin.js
+31 -84
@@ -1,4 +1,5 @@
1 import { githubPluginManifest } from './manifest.js';
2 +import { createWorkspaceController } from './workspace.js';
3
4 const CALLBACK_ACTIONS = Object.freeze([
5 ['files:', 'github.files.list'],
@@ -163,12 +164,8 @@ async function workflowRunView(github, repoId, runId) {
164 { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
165 ]
166 ];
166 - if (run.conclusion === 'failure') {
167 - rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
168 - }
169 - if (run.status === 'in_progress' || run.status === 'queued') {
170 - rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
171 - }
167 + if (run.conclusion === 'failure') rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
168 + if (run.status === 'in_progress' || run.status === 'queued') rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
169 rows.push([
170 { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
171 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
@@ -198,10 +195,7 @@ async function workflowJobsView(github, repoId, runId) {
195 text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
196 reply_markup: {
197 inline_keyboard: [
201 - ...jobs.slice(0, 20).map(job => [{
202 - text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`,
203 - callback_data: `job:${repoId}:${job.id}`
204 - }]),
198 + ...jobs.slice(0, 20).map(job => [{ text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`, callback_data: `job:${repoId}:${job.id}` }]),
199 [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
200 ]
201 }
@@ -245,32 +239,22 @@ async function workflowArtifactsView(github, repoId, runId, page = 1) {
239 const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
240 return {
241 text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
248 - reply_markup: {
249 - inline_keyboard: [
250 - ...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10),
251 - [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
252 - ]
253 - }
242 + reply_markup: { inline_keyboard: [...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10), [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]] }
243 };
244 }
245
246 async function branchesView(github, repoId, page = 1) {
258 - const [repo, branches] = await Promise.all([
259 - github.getRepository(repoId),
260 - github.listBranches(repoId, { perPage: 20, page })
261 - ]);
247 + const [repo, branches] = await Promise.all([github.getRepository(repoId), github.listBranches(repoId, { perPage: 20, page })]);
248 const body = branches.length
249 ? branches.slice(0, 20).map(branch => `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`).join('\n\n')
250 : '<i>Branchی یافت نشد.</i>';
251 return {
252 text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
267 - reply_markup: {
268 - inline_keyboard: [
269 - ...branches.slice(0, 20).filter(branch => /^[a-f0-9]{40}$/i.test(String(branch.sha))).map(branch => [{ text: `↔️ ${short(branch.name, 42)}`, callback_data: `compare:${repoId}:${branch.sha}` }]),
270 - ...listPagination('branches', repoId, page, branches.length, 20),
271 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
272 - ]
273 - }
253 + reply_markup: { inline_keyboard: [
254 + ...branches.slice(0, 20).filter(branch => /^[a-f0-9]{40}$/i.test(String(branch.sha))).map(branch => [{ text: `↔️ ${short(branch.name, 42)}`, callback_data: `compare:${repoId}:${branch.sha}` }]),
255 + ...listPagination('branches', repoId, page, branches.length, 20),
256 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
257 + ] }
258 };
259 }
260
@@ -290,13 +274,11 @@ async function pullRequestsView(github, repoId, page = 1) {
274 : '<i>Pull Requestی یافت نشد.</i>';
275 return {
276 text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
293 - reply_markup: {
294 - inline_keyboard: [
295 - ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
296 - ...listPagination('prs', repoId, page, prs.length, 10),
297 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
298 - ]
299 - }
277 + reply_markup: { inline_keyboard: [
278 + ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
279 + ...listPagination('prs', repoId, page, prs.length, 10),
280 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
281 + ] }
282 };
283 }
284
@@ -305,15 +287,7 @@ async function pullRequestDetailView(github, repoId, prNumber) {
287 const body = escapeHtml(short(pr.body || '', 600));
288 return {
289 text: `🔎 <b>PR #${pr.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(pr.title)}</b>\n${pr.merged ? '🟣 merged' : `${stateIcon(pr.state)} ${escapeHtml(pr.state)}`} · ${escapeHtml(pr.author)}\n<code>${escapeHtml(pr.head || '-')}</code> → <code>${escapeHtml(pr.base || '-')}</code>\n+${pr.additions}/-${pr.deletions} · ${pr.changedFiles} files\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
308 - reply_markup: {
309 - inline_keyboard: [
310 - [
311 - { text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` },
312 - { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }
313 - ],
314 - [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]
315 - ]
316 - }
290 + reply_markup: { inline_keyboard: [[{ text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` }, { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }], [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]] }
291 };
292 }
293
@@ -325,12 +299,7 @@ async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
299 }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
300 return {
301 text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
328 - reply_markup: {
329 - inline_keyboard: [
330 - ...pairPagination('prfiles', repoId, prNumber, page, files.length, 8),
331 - [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
332 - ]
333 - }
302 + reply_markup: { inline_keyboard: [...pairPagination('prfiles', repoId, prNumber, page, files.length, 8), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
303 };
304 }
305
@@ -342,32 +311,19 @@ async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
311 : '<i>Checkی یافت نشد.</i>';
312 return {
313 text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
345 - reply_markup: {
346 - inline_keyboard: [
347 - ...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20),
348 - [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
349 - ]
350 - }
314 + reply_markup: { inline_keyboard: [...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
315 };
316 }
317
318 async function issuesView(github, repoId, page = 1) {
355 - const [repo, issuePage] = await Promise.all([
356 - github.getRepository(repoId),
357 - github.listIssuesPage(repoId, { page })
358 - ]);
319 + const [repo, issuePage] = await Promise.all([github.getRepository(repoId), github.listIssuesPage(repoId, { page })]);
320 const issues = issuePage.items || [];
321 const body = issues.length
322 ? issues.slice(0, 20).map(issue => `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`).join('\n\n')
323 : '<i>Issueی یافت نشد.</i>';
324 return {
325 text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
365 - reply_markup: {
366 - inline_keyboard: [
367 - ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
368 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
369 - ]
370 - }
326 + reply_markup: { inline_keyboard: [...explicitPagination('issues', repoId, page, !!issuePage.hasMore), [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
327 };
328 }
329
@@ -393,52 +349,36 @@ function workflowActionResultView(repoId, runId, action) {
349 function resolveReadCallback(data) {
350 const value = String(data || '');
351 if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
396 -
352 const repoId = numericSingle(value, 'repo');
353 if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
399 -
354 const runs = workflowRunsPage(value);
355 if (runs) return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
402 -
356 const run = numericPair(value, 'run');
357 if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
405 -
358 const jobs = numericPair(value, 'jobs');
359 if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
408 -
360 const job = numericPair(value, 'job');
361 if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
411 -
362 const joblog = numericPair(value, 'joblog');
363 if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
414 -
364 const artifacts = pagedPair(value, 'artifacts');
365 if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
417 -
366 const branches = pagedSingle(value, 'branches');
367 if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
420 -
368 const compare = compareRef(value);
369 if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
423 -
370 const prs = pagedSingle(value, 'prs');
371 if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
426 -
372 const prdetail = numericPair(value, 'prdetail');
373 if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
429 -
374 const prfiles = numericTriple(value, 'prfiles');
375 if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
432 -
376 const prchecks = numericTriple(value, 'prchecks');
377 if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
435 -
378 const issues = pagedSingle(value, 'issues');
379 if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
438 -
380 const releases = pagedSingle(value, 'releases');
381 if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
441 -
382 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
383 if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
384 }
@@ -471,9 +411,10 @@ function resolveWriteCallback(data) {
411 return null;
412 }
413
474 -export function createGitHubPlugin({ github, menu } = {}) {
414 +export function createGitHubPlugin({ github, menu, workspaces } = {}) {
415 if (!github) throw new Error('GitHub plugin requires github service');
416 if (!menu) throw new Error('GitHub plugin requires menu manager');
417 + const workspaceController = workspaces ? createWorkspaceController({ github, workspaces }) : null;
418
419 return {
420 manifest: githubPluginManifest,
@@ -483,13 +424,19 @@ export function createGitHubPlugin({ github, menu } = {}) {
424 return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
425 },
426
486 - resolveCallback(data) {
427 + resolveMessage(payload, context = {}) {
428 + return workspaceController?.resolveMessage(payload, context) || null;
429 + },
430 +
431 + resolveCallback(data, context = {}) {
432 const write = resolveWriteCallback(data);
433 if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
434
435 + const workspaceRoute = workspaceController?.resolveCallback(data, context);
436 + if (workspaceRoute) return workspaceRoute;
437 +
438 const read = resolveReadCallback(data);
439 if (!read) return null;
492 -
440 return {
441 actionId: read.actionId,
442 execute: async () => {
src/plugins/github/workspace-commit.js new
+156
@@ -0,0 +1,156 @@
1 +const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
2 +const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
3 +
4 +function assertOwner(ownerId) {
5 + const owner = String(ownerId ?? '');
6 + if (!owner) throw new Error('Workspace owner is required');
7 + return owner;
8 +}
9 +
10 +function assertRepoId(repoId) {
11 + const value = Number(repoId);
12 + if (!Number.isSafeInteger(value) || value < 1) throw new Error('Workspace repository ID is invalid');
13 + return value;
14 +}
15 +
16 +function assertIntentId(intentId) {
17 + const value = String(intentId || '');
18 + if (!INTENT_ID_PATTERN.test(value)) throw new Error('Workspace intent ID is invalid');
19 + return value;
20 +}
21 +
22 +function assertSha(value, label) {
23 + const sha = String(value || '');
24 + if (!FULL_SHA_PATTERN.test(sha)) throw new Error(`${label} SHA is invalid`);
25 + return sha;
26 +}
27 +
28 +function committedResult(intent, idempotent = true) {
29 + return {
30 + commitSha: assertSha(intent?.commitSha, 'Committed'),
31 + branch: String(intent?.branch || intent?.targetBranch || ''),
32 + idempotent
33 + };
34 +}
35 +
36 +function materialMismatch(intent, workspace, repoId, intentId) {
37 + return (
38 + Number(intent?.repoId) !== repoId ||
39 + Number(workspace?.repoId) !== repoId ||
40 + String(workspace?.id || '') !== String(intent?.workspaceId || '') ||
41 + String(workspace?.currentIntentId || '') !== intentId ||
42 + String(workspace?.baseBranch || '') !== String(intent?.baseBranch || '') ||
43 + String(workspace?.baseHeadSha || '') !== String(intent?.baseHeadSha || '') ||
44 + String(workspace?.baseTreeSha || '') !== String(intent?.baseTreeSha || '') ||
45 + String(workspace?.path || '') !== String(intent?.path || '') ||
46 + String(workspace?.blobSha || '') !== String(intent?.sourceBlobSha || '') ||
47 + String(workspace?.draftDigest || '') !== String(intent?.contentDigest || '') ||
48 + String(workspace?.commitMessageDigest || '') !== String(intent?.commitMessageDigest || '')
49 + );
50 +}
51 +
52 +async function markStaleThenThrow(workspaces, ownerId, intentId, reason) {
53 + try {
54 + await workspaces.markStale({ ownerId, intentId, reason });
55 + } catch {
56 + // The original safety failure remains authoritative.
57 + }
58 + throw new Error(reason);
59 +}
60 +
61 +async function reconcileCandidate({ github, workspaces, ownerId, repoId, intent, intentId }) {
62 + const candidate = assertSha(intent.candidateCommitSha, 'Candidate commit');
63 + const branch = String(intent.targetBranch || '');
64 + const existing = await github.getGitRef(repoId, branch, { allowMissing: true });
65 + if (existing?.sha === candidate) {
66 + await workspaces.completeCommit({ ownerId, intentId, commitSha: candidate, branch });
67 + return { commitSha: candidate, branch, idempotent: true };
68 + }
69 + if (existing) {
70 + throw new Error('Target branch exists at an unexpected commit');
71 + }
72 +
73 + const snapshot = await github.getBranchSnapshot(repoId, intent.baseBranch);
74 + if (snapshot.headSha !== intent.baseHeadSha) {
75 + return markStaleThenThrow(workspaces, ownerId, intentId, 'Base branch changed; commit intent is stale');
76 + }
77 +
78 + try {
79 + await github.createGitBranchRef(repoId, { branch, sha: candidate });
80 + } catch (error) {
81 + const observed = await github.getGitRef(repoId, branch, { allowMissing: true });
82 + if (observed?.sha !== candidate) {
83 + throw new Error(`Unable to reconcile candidate branch after provider error: ${error?.message || 'unknown error'}`);
84 + }
85 + }
86 + await workspaces.completeCommit({ ownerId, intentId, commitSha: candidate, branch });
87 + return { commitSha: candidate, branch, idempotent: true };
88 +}
89 +
90 +export async function commitWorkspaceIntent({ github, workspaces, ownerId, repoId, intentId } = {}) {
91 + if (!github) throw new Error('Workspace commit requires GitHub service');
92 + if (!workspaces) throw new Error('Workspace commit requires durable workspace store');
93 + const owner = assertOwner(ownerId);
94 + const repositoryId = assertRepoId(repoId);
95 + const id = assertIntentId(intentId);
96 +
97 + let intent = await workspaces.getIntent({ ownerId: owner, intentId: id });
98 + if (!intent) throw new Error('Commit intent not found or expired');
99 + if (Number(intent.repoId) !== repositoryId) throw new Error('Commit intent repository mismatch');
100 + if (intent.state === 'COMMITTED') return committedResult(intent, true);
101 +
102 + const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId: intent.workspaceId });
103 + if (!workspace || materialMismatch(intent, workspace, repositoryId, id)) {
104 + return markStaleThenThrow(workspaces, owner, id, 'Workspace material changed; commit intent is stale');
105 + }
106 +
107 + const begun = await workspaces.beginCommit({ ownerId: owner, intentId: id });
108 + intent = begun?.intent;
109 + if (!intent) throw new Error('Commit intent could not begin');
110 + if (begun.disposition === 'committed' || intent.state === 'COMMITTED') return committedResult(intent, true);
111 +
112 + if (intent.candidateCommitSha) {
113 + return reconcileCandidate({ github, workspaces, ownerId: owner, repoId: repositoryId, intent, intentId: id });
114 + }
115 +
116 + const snapshot = await github.getBranchSnapshot(repositoryId, intent.baseBranch);
117 + if (snapshot.headSha !== intent.baseHeadSha) {
118 + return markStaleThenThrow(workspaces, owner, id, 'Base branch changed; commit intent is stale');
119 + }
120 +
121 + const existing = await github.getGitRef(repositoryId, intent.targetBranch, { allowMissing: true });
122 + if (existing) throw new Error('Target branch already exists unexpectedly');
123 +
124 + const blob = await github.createGitBlob(repositoryId, workspace.draftText);
125 + const tree = await github.createGitTree(repositoryId, {
126 + baseTreeSha: intent.baseTreeSha,
127 + entries: [{ path: intent.path, mode: '100644', type: 'blob', sha: blob.sha }]
128 + });
129 + const commit = await github.createGitCommit(repositoryId, {
130 + message: workspace.commitMessage,
131 + treeSha: tree.sha,
132 + parentSha: intent.baseHeadSha,
133 + timestamp: intent.commitTimestamp
134 + });
135 + const commitSha = assertSha(commit.sha, 'Candidate commit');
136 + await workspaces.setCandidateCommit({ ownerId: owner, intentId: id, commitSha });
137 +
138 + let idempotent = false;
139 + try {
140 + await github.createGitBranchRef(repositoryId, { branch: intent.targetBranch, sha: commitSha });
141 + } catch (error) {
142 + const observed = await github.getGitRef(repositoryId, intent.targetBranch, { allowMissing: true });
143 + if (observed?.sha !== commitSha) {
144 + throw new Error(`Unable to reconcile target branch after provider error: ${error?.message || 'unknown error'}`);
145 + }
146 + idempotent = true;
147 + }
148 +
149 + await workspaces.completeCommit({
150 + ownerId: owner,
151 + intentId: id,
152 + commitSha,
153 + branch: intent.targetBranch
154 + });
155 + return { commitSha, branch: intent.targetBranch, idempotent };
156 +}
src/plugins/github/workspace.js new
+386
@@ -0,0 +1,386 @@
1 +import {
2 + buildUnifiedDiff,
3 + digestText,
4 + makeTargetBranch,
5 + normalizeCommitMessage,
6 + validateEditableFile
7 +} from '../../core/workspace-policy.js';
8 +import { commitWorkspaceIntent } from './workspace-commit.js';
9 +
10 +export { commitWorkspaceIntent } from './workspace-commit.js';
11 +
12 +const HANDLE_10 = '[A-Za-z0-9_-]{10}';
13 +const INTENT_8 = '[A-Za-z0-9_-]{8}';
14 +const escapeHtml = value => String(value ?? '')
15 + .replaceAll('&', '&amp;')
16 + .replaceAll('<', '&lt;')
17 + .replaceAll('>', '&gt;')
18 + .replaceAll('"', '&quot;');
19 +const short = (value, max = 70) => {
20 + const text = String(value ?? '');
21 + return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22 +};
23 +
24 +const ownerFrom = context => {
25 + const ownerId = String(context?.ownerId ?? '');
26 + if (!ownerId) throw new Error('Workspace owner is required');
27 + return ownerId;
28 +};
29 +
30 +function parseCallback(data) {
31 + const value = String(data || '');
32 + let match = value.match(/^(?:files):(\d+)$/);
33 + if (match) return { actionId: 'github.files.list', kind: 'root', repoId: Number(match[1]) };
34 + match = value.match(new RegExp(`^wnav:(${HANDLE_10})$`));
35 + if (match) return { actionId: 'github.workspace.navigate', kind: 'navigate', refId: match[1] };
36 + match = value.match(new RegExp(`^wedit:(${HANDLE_10})$`));
37 + if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
38 + match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
39 + if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
40 + match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
41 + if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft' };
42 + match = value.match(new RegExp(`^wmsg:(${HANDLE_10})$`));
43 + if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'commit_message' };
44 + match = value.match(new RegExp(`^wdiff:(${HANDLE_10})$`));
45 + if (match) return { actionId: 'github.workspace.diff', kind: 'diff', workspaceId: match[1] };
46 + match = value.match(new RegExp(`^wready:(${HANDLE_10})$`));
47 + if (match) return { actionId: 'github.workspace.ready', kind: 'ready', workspaceId: match[1] };
48 + match = value.match(new RegExp(`^wcancel:(${HANDLE_10})$`));
49 + if (match) return { actionId: 'github.workspace.cancel', kind: 'cancel', workspaceId: match[1] };
50 + match = value.match(new RegExp(`^wscommit:(\\d+):(${INTENT_8})$`));
51 + if (match) return {
52 + actionId: 'github.workspace.commit_branch',
53 + kind: 'commit',
54 + repoId: Number(match[1]),
55 + intentId: match[2]
56 + };
57 + return null;
58 +}
59 +
60 +function workspaceButtons(workspace) {
61 + return [
62 + [
63 + { text: '📝 متن Draft', callback_data: `wtext:${workspace.id}` },
64 + { text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }
65 + ],
66 + [
67 + { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
68 + { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
69 + ],
70 + [
71 + { text: '🗑 لغو Draft', callback_data: `wcancel:${workspace.id}` },
72 + { text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }
73 + ]
74 + ];
75 +}
76 +
77 +function workspaceCommitResultView(repoId, intent, result) {
78 + const rows = [
79 + [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]
80 + ];
81 + if (intent?.workspaceId) {
82 + rows.push([{ text: '📝 Workspace', callback_data: `ws:${intent.workspaceId}` }]);
83 + }
84 + rows.push([{ text: '📦 پروژه', callback_data: `repo:${repoId}` }]);
85 + return {
86 + text: `✅ <b>Commit روی branch جدید ایجاد شد</b>\nBranch: <code>${escapeHtml(result.branch)}</code>\nSHA: <code>${escapeHtml(result.commitSha)}</code>${result.idempotent ? '\nوضعیت: <b>reconciled / idempotent</b>' : ''}\n\nشاخهٔ پیش‌فرض تغییر نکرده است.`,
87 + reply_markup: { inline_keyboard: rows }
88 + };
89 +}
90 +
91 +export function createWorkspaceController({ github, workspaces } = {}) {
92 + if (!github) throw new Error('Workspace controller requires GitHub service');
93 + if (!workspaces) throw new Error('Workspace controller requires durable workspace store');
94 +
95 + const requireWorkspace = async (workspaceId, ownerId) => {
96 + const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
97 + if (!workspace) throw new Error('Workspace not found or expired');
98 + return workspace;
99 + };
100 +
101 + const renderDirectory = async (repoId, path, ownerId) => {
102 + const [repo, items] = await Promise.all([
103 + github.getRepository(repoId),
104 + github.listFiles(repoId, path)
105 + ]);
106 + const visible = items.slice(0, 30);
107 + const handles = await workspaces.createNavigationRefs({
108 + ownerId,
109 + refs: visible.map(item => ({ repoId, path: item.path, type: item.type, sha: item.sha }))
110 + });
111 + const body = visible.length
112 + ? visible.map(item => `${item.type === 'dir' ? '📁' : '📄'} <code>${escapeHtml(short(item.name, 100))}</code>${item.type === 'file' && item.size ? ` (${Number(item.size).toLocaleString()} B)` : ''}`).join('\n')
113 + : '<i>این پوشه خالی است.</i>';
114 + const rows = visible.map((item, index) => [{
115 + text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
116 + callback_data: `wnav:${handles[index].refId}`
117 + }]);
118 + rows.push([
119 + { text: '🔄 بروزرسانی', callback_data: `files:${repoId}` },
120 + { text: '📦 پروژه', callback_data: `repo:${repoId}` }
121 + ]);
122 + return {
123 + text: `📂 <b>فایل‌های ${escapeHtml(repo.name)}</b>\n${path ? `مسیر: <code>${escapeHtml(path)}</code>\n` : ''}➖➖➖➖➖➖➖➖➖➖\n${body}`,
124 + reply_markup: { inline_keyboard: rows }
125 + };
126 + };
127 +
128 + const getPinnedFile = async ref => {
129 + const repo = await github.getRepository(ref.repoId);
130 + const snapshot = await github.getBranchSnapshot(ref.repoId, repo.defaultBranch);
131 + const file = await github.getFileAtRef(ref.repoId, ref.path, snapshot.headSha);
132 + return { repo, snapshot, file };
133 + };
134 +
135 + const renderFile = async (refId, ownerId) => {
136 + const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
137 + if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
138 + const { repo, snapshot, file } = await getPinnedFile(ref);
139 + const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
140 + const preview = file.content.length > 2600 ? `${file.content.slice(0, 2600)}\n…` : file.content;
141 + const reason = repo.archived
142 + ? 'این مخزن آرشیوشده است و ویرایش فایل در آن غیرفعال است.'
143 + : policy.reason;
144 + const rows = [];
145 + if (!repo.archived && policy.editable) rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
146 + rows.push([{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }, { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }]);
147 + return {
148 + text: `📄 <b>پیش‌نمایش فایل — ${escapeHtml(repo.name)}</b>\nمسیر: <code>${escapeHtml(file.path)}</code>\nRef: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n${reason ? `⚠️ ${escapeHtml(reason)}\n` : ''}➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(preview)}</pre>`,
149 + reply_markup: { inline_keyboard: rows }
150 + };
151 + };
152 +
153 + const createDraft = async (refId, ownerId) => {
154 + const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
155 + if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
156 + const { repo, snapshot, file } = await getPinnedFile(ref);
157 + if (repo.archived) throw new Error('Archived repository is not editable');
158 + const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
159 + if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
160 + const originalDigest = await digestText(file.content);
161 + const workspace = await workspaces.createWorkspace({
162 + ownerId,
163 + repoId: Number(ref.repoId),
164 + repoFullName: repo.fullName,
165 + baseBranch: repo.defaultBranch,
166 + baseHeadSha: snapshot.headSha,
167 + baseTreeSha: snapshot.treeSha,
168 + path: file.path,
169 + blobSha: file.sha,
170 + originalText: file.content,
171 + originalDigest
172 + });
173 + return {
174 + text: `📝 <b>Draft ساخته شد</b>\nمخزن: <code>${escapeHtml(repo.fullName)}</code>\nفایل: <code>${escapeHtml(file.path)}</code>\nBase: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
175 + reply_markup: { inline_keyboard: [[{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }], [{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }]] }
176 + };
177 + };
178 +
179 + const renderWorkspace = async (workspaceId, ownerId) => {
180 + const workspace = await requireWorkspace(workspaceId, ownerId);
181 + const changed = workspace.draftText !== workspace.originalText;
182 + const commitMessage = workspace.commitMessage
183 + ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>`
184 + : '<i>ثبت نشده</i>';
185 + return {
186 + 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تا قبل از تأیید نهایی، هیچ تغییری در GitHub انجام نمی‌شود.`,
187 + reply_markup: { inline_keyboard: workspaceButtons(workspace) }
188 + };
189 + };
190 +
191 + const prepareInput = async (workspaceId, mode, ownerId) => {
192 + const workspace = await requireWorkspace(workspaceId, ownerId);
193 + await workspaces.setPendingInput({ ownerId, workspaceId, mode });
194 + const draftMode = mode === 'draft';
195 + return {
196 + text: draftMode
197 + ? `📝 <b>متن جدید Draft را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nکل محتوای فایل جایگزین می‌شود. سقف: 3,000 کاراکتر Unicode و 12,000 بایت UTF-8. پیام بعدی فقط یک‌بار مصرف می‌شود.`
198 + : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
199 + reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
200 + };
201 + };
202 +
203 + const applyPendingInput = async ({ pending, text }, ownerId) => {
204 + const workspaceId = String(pending?.workspaceId || '');
205 + const mode = String(pending?.mode || '');
206 + if (!new RegExp(`^${HANDLE_10}$`).test(workspaceId) || !['draft', 'commit_message'].includes(mode)) {
207 + throw new Error('Pending workspace input is invalid');
208 + }
209 +
210 + const consumed = await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
211 + if (!consumed) throw new Error('Pending workspace input was already consumed or expired');
212 + const workspace = await requireWorkspace(workspaceId, ownerId);
213 +
214 + if (mode === 'draft') {
215 + const policy = validateEditableFile({ path: workspace.path, text });
216 + if (!policy.editable) {
217 + return {
218 + text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'متن ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «متن Draft» را بزنید.`,
219 + reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
220 + };
221 + }
222 + const digest = await digestText(policy.text);
223 + const updated = await workspaces.updateDraft({ ownerId, workspaceId, text: policy.text, digest });
224 + return {
225 + text: `✅ <b>Draft محلی ذخیره شد</b>\nفایل: <code>${escapeHtml(updated.path)}</code>\nکاراکتر: <b>${policy.charLength}</b> · بایت UTF-8: <b>${policy.byteLength}</b>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
226 + reply_markup: { inline_keyboard: workspaceButtons(updated) }
227 + };
228 + }
229 +
230 + let message;
231 + try {
232 + message = normalizeCommitMessage(text);
233 + } catch (error) {
234 + return {
235 + text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
236 + reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
237 + };
238 + }
239 + const digest = await digestText(message);
240 + const updated = await workspaces.setCommitMessage({ ownerId, workspaceId, message, digest });
241 + return {
242 + text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
243 + reply_markup: { inline_keyboard: workspaceButtons(updated) }
244 + };
245 + };
246 +
247 + const renderDiff = async (workspaceId, ownerId) => {
248 + const workspace = await requireWorkspace(workspaceId, ownerId);
249 + const diff = buildUnifiedDiff({
250 + path: workspace.path,
251 + before: workspace.originalText,
252 + after: workspace.draftText,
253 + maxChars: 2400
254 + });
255 + const truncation = diff.truncated ? '\n⚠️ نمایش Diff کوتاه شده؛ شمارش‌ها بر اساس محتوای کامل هستند.' : '';
256 + return {
257 + text: `🔍 <b>Diff محلی</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n+${diff.additions} / -${diff.deletions}${truncation}\n➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(diff.text)}</pre>`,
258 + reply_markup: { inline_keyboard: [[{ text: '📝 Draft', callback_data: `ws:${workspace.id}` }, { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }]] }
259 + };
260 + };
261 +
262 + const sealReadyIntent = async (workspaceId, ownerId) => {
263 + const workspace = await requireWorkspace(workspaceId, ownerId);
264 + if (workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
265 + const commitMessage = normalizeCommitMessage(workspace.commitMessage);
266 + const contentDigest = await digestText(workspace.draftText);
267 + const commitMessageDigest = await digestText(commitMessage);
268 + const targetBranch = makeTargetBranch(workspace.id);
269 + const createdAt = Number(workspace.createdAt);
270 + const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
271 + const material = {
272 + repoId: Number(workspace.repoId),
273 + workspaceId: workspace.id,
274 + baseBranch: workspace.baseBranch,
275 + baseHeadSha: workspace.baseHeadSha,
276 + baseTreeSha: workspace.baseTreeSha,
277 + path: workspace.path,
278 + sourceBlobSha: workspace.blobSha,
279 + contentDigest,
280 + commitMessageDigest,
281 + targetBranch,
282 + commitTimestamp
283 + };
284 + const intentDigest = await digestText(JSON.stringify(material));
285 + const intent = await workspaces.sealIntent({
286 + ownerId,
287 + workspaceId,
288 + intent: { ...material, intentDigest }
289 + });
290 + if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id)) throw new Error('Commit intent ID is invalid');
291 + return {
292 + text: `✅ <b>آمادهٔ تأیید Commit</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nBranch: <code>${escapeHtml(targetBranch)}</code>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha).slice(0, 10))}</code>\n\nمرحلهٔ بعد فقط درخواست تأیید امن را می‌سازد؛ تا تأیید معتبر مصرف نشود GitHub WRITE اجرا نمی‌شود.`,
293 + reply_markup: {
294 + inline_keyboard: [
295 + [{ text: '✅ تأیید و Commit', callback_data: `wscommit:${workspace.repoId}:${intent.id}` }],
296 + [{ text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` }, { text: '📝 Draft', callback_data: `ws:${workspace.id}` }]
297 + ]
298 + }
299 + };
300 + };
301 +
302 + const cancelDraft = async (workspaceId, ownerId) => {
303 + const workspace = await requireWorkspace(workspaceId, ownerId);
304 + await workspaces.cancelWorkspace({ ownerId, workspaceId });
305 + return {
306 + text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
307 + reply_markup: { inline_keyboard: [[{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]] }
308 + };
309 + };
310 +
311 + return {
312 + resolveCallback(data, context = {}) {
313 + const parsed = parseCallback(data);
314 + if (!parsed) return null;
315 +
316 + if (parsed.kind === 'commit') {
317 + return {
318 + actionId: parsed.actionId,
319 + approval: {
320 + input: { repoId: parsed.repoId, intentId: parsed.intentId },
321 + label: 'Commit روی branch جدید',
322 + cancelCallback: `repo:${parsed.repoId}`
323 + },
324 + audit: { repoId: parsed.repoId, intentId: parsed.intentId },
325 + execute: async () => {
326 + const ownerId = ownerFrom(context);
327 + const result = await commitWorkspaceIntent({
328 + github,
329 + workspaces,
330 + ownerId,
331 + repoId: parsed.repoId,
332 + intentId: parsed.intentId
333 + });
334 + const intent = await workspaces.getIntent({ ownerId, intentId: parsed.intentId });
335 + const view = workspaceCommitResultView(parsed.repoId, intent, result);
336 + return {
337 + ...view,
338 + audit: {
339 + repoId: parsed.repoId,
340 + intentId: parsed.intentId,
341 + workspaceId: intent?.workspaceId,
342 + path: intent?.path,
343 + contentDigest: intent?.contentDigest,
344 + commitMessageDigest: intent?.commitMessageDigest,
345 + baseHeadSha: intent?.baseHeadSha,
346 + targetBranch: intent?.targetBranch,
347 + commitSha: result.commitSha,
348 + branch: result.branch,
349 + idempotent: result.idempotent
350 + }
351 + };
352 + }
353 + };
354 + }
355 +
356 + return {
357 + actionId: parsed.actionId,
358 + execute: async () => {
359 + const ownerId = ownerFrom(context);
360 + if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
361 + if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
362 + if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
363 + if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
364 + if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
365 + if (parsed.kind === 'ready') return sealReadyIntent(parsed.workspaceId, ownerId);
366 + if (parsed.kind === 'cancel') return cancelDraft(parsed.workspaceId, ownerId);
367 + const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
368 + if (!ref) throw new Error('Workspace navigation reference is missing or expired');
369 + return ref.type === 'dir'
370 + ? renderDirectory(ref.repoId, ref.path, ownerId)
371 + : renderFile(parsed.refId, ownerId);
372 + }
373 + };
374 + },
375 +
376 + resolveMessage(payload, context = {}) {
377 + const pending = payload?.pending;
378 + if (!pending || !['draft', 'commit_message'].includes(String(pending.mode || ''))) return null;
379 + if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || ''))) return null;
380 + return {
381 + actionId: 'github.workspace.input.apply',
382 + execute: async () => applyPendingInput({ pending, text: String(payload?.text ?? '') }, ownerFrom(context))
383 + };
384 + }
385 + };
386 +}
test/durable-replay.test.js
+3 -4
@@ -120,10 +120,9 @@ test('Worker exports ApprovalReplayGuard and Wrangler declares SQLite durable bi
120
121 const configText = await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8');
122 const config = JSON.parse(configText);
123 - assert.deepEqual(config.durable_objects?.bindings, [{
124 - name: 'APPROVAL_REPLAY_GUARD',
125 - class_name: 'ApprovalReplayGuard'
126 - }]);
123 + assert.ok(config.durable_objects?.bindings?.some(binding =>
124 + binding.name === 'APPROVAL_REPLAY_GUARD' && binding.class_name === 'ApprovalReplayGuard'
125 + ));
126 assert.deepEqual(config.exports?.ApprovalReplayGuard, {
127 type: 'durable-object',
128 storage: 'sqlite'
test/github-workspace-approval.test.js new
+342
@@ -0,0 +1,342 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { ApprovalService } from '../src/core/approval.js';
4 +import { PluginRegistry } from '../src/core/plugin-registry.js';
5 +import { ActionPolicy } from '../src/core/action-policy.js';
6 +import { AuditLogger } from '../src/core/audit.js';
7 +import { PluginRouter } from '../src/core/router.js';
8 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
9 +import * as workspaceModule from '../src/plugins/github/workspace.js';
10 +
11 +const OWNER = '42';
12 +const REPO_ID = 123;
13 +const WORKSPACE_ID = 'W123456789';
14 +const INTENT_ID = 'Ab12_cdE';
15 +const BASE_HEAD = 'a'.repeat(40);
16 +const BASE_TREE = 'b'.repeat(40);
17 +const SOURCE_BLOB = 'c'.repeat(40);
18 +const CONTENT_BLOB = 'd'.repeat(40);
19 +const NEW_TREE = 'e'.repeat(40);
20 +const COMMIT_SHA = 'f'.repeat(40);
21 +const TARGET_BRANCH = `nexa/edit-${WORKSPACE_ID}`;
22 +const TIMESTAMP = '2026-10-03T09:00:00.000Z';
23 +const CONTENT_DIGEST = '1'.repeat(64);
24 +const MESSAGE_DIGEST = '2'.repeat(64);
25 +
26 +function replayStore() {
27 + const seen = new Set();
28 + return {
29 + async consume({ ownerId, nonce }) {
30 + const key = `${ownerId}:${nonce}`;
31 + if (seen.has(key)) return false;
32 + seen.add(key);
33 + return true;
34 + }
35 + };
36 +}
37 +
38 +function makeIntent(overrides = {}) {
39 + return {
40 + id: INTENT_ID,
41 + workspaceId: WORKSPACE_ID,
42 + repoId: REPO_ID,
43 + baseBranch: 'main',
44 + baseHeadSha: BASE_HEAD,
45 + baseTreeSha: BASE_TREE,
46 + path: 'src/app.js',
47 + sourceBlobSha: SOURCE_BLOB,
48 + contentDigest: CONTENT_DIGEST,
49 + commitMessageDigest: MESSAGE_DIGEST,
50 + targetBranch: TARGET_BRANCH,
51 + commitTimestamp: TIMESTAMP,
52 + intentDigest: '3'.repeat(64),
53 + state: 'READY',
54 + candidateCommitSha: null,
55 + commitSha: null,
56 + branch: null,
57 + ...overrides
58 + };
59 +}
60 +
61 +function makeWorkspace(overrides = {}) {
62 + return {
63 + id: WORKSPACE_ID,
64 + repoId: REPO_ID,
65 + currentIntentId: INTENT_ID,
66 + state: 'READY',
67 + baseBranch: 'main',
68 + baseHeadSha: BASE_HEAD,
69 + baseTreeSha: BASE_TREE,
70 + path: 'src/app.js',
71 + blobSha: SOURCE_BLOB,
72 + originalText: 'before\n',
73 + draftText: 'after\n',
74 + draftDigest: CONTENT_DIGEST,
75 + commitMessage: 'edit app',
76 + commitMessageDigest: MESSAGE_DIGEST,
77 + ...overrides
78 + };
79 +}
80 +
81 +function makeWorkspaces({ intent = makeIntent(), workspace = makeWorkspace(), disposition = 'start' } = {}) {
82 + const calls = [];
83 + let mutableIntent = structuredClone(intent);
84 + return {
85 + calls,
86 + async getIntent({ ownerId, intentId }) {
87 + calls.push(['getIntent', ownerId, intentId]);
88 + return ownerId === OWNER && intentId === mutableIntent.id ? structuredClone(mutableIntent) : null;
89 + },
90 + async getWorkspace({ ownerId, workspaceId }) {
91 + calls.push(['getWorkspace', ownerId, workspaceId]);
92 + return ownerId === OWNER && workspaceId === workspace.id ? structuredClone(workspace) : null;
93 + },
94 + async beginCommit({ ownerId, intentId }) {
95 + calls.push(['beginCommit', ownerId, intentId]);
96 + if (mutableIntent.state === 'COMMITTED') return { disposition: 'committed', intent: structuredClone(mutableIntent) };
97 + if (mutableIntent.state === 'COMMITTING') return { disposition: 'resume', intent: structuredClone(mutableIntent) };
98 + mutableIntent = { ...mutableIntent, state: 'COMMITTING' };
99 + return { disposition, intent: structuredClone(mutableIntent) };
100 + },
101 + async setCandidateCommit({ ownerId, intentId, commitSha }) {
102 + calls.push(['setCandidateCommit', ownerId, intentId, commitSha]);
103 + mutableIntent = { ...mutableIntent, candidateCommitSha: commitSha, state: 'COMMITTING' };
104 + return structuredClone(mutableIntent);
105 + },
106 + async completeCommit({ ownerId, intentId, commitSha, branch }) {
107 + calls.push(['completeCommit', ownerId, intentId, commitSha, branch]);
108 + mutableIntent = { ...mutableIntent, commitSha, branch, state: 'COMMITTED' };
109 + return structuredClone(mutableIntent);
110 + },
111 + async markStale({ ownerId, intentId, reason }) {
112 + calls.push(['markStale', ownerId, intentId, reason]);
113 + mutableIntent = { ...mutableIntent, state: 'STALE', staleReason: reason };
114 + return structuredClone(mutableIntent);
115 + }
116 + };
117 +}
118 +
119 +function makeGitHub({ baseHead = BASE_HEAD, existingRef = null, createRefError = null } = {}) {
120 + const calls = [];
121 + return {
122 + calls,
123 + async getBranchSnapshot(repoId, branch) {
124 + calls.push(['getBranchSnapshot', repoId, branch]);
125 + return { branch, headSha: baseHead, treeSha: BASE_TREE };
126 + },
127 + async getGitRef(repoId, branch, options) {
128 + calls.push(['getGitRef', repoId, branch, options]);
129 + return existingRef ? structuredClone(existingRef) : null;
130 + },
131 + async createGitBlob(repoId, text) {
132 + calls.push(['createGitBlob', repoId, text]);
133 + return { sha: CONTENT_BLOB };
134 + },
135 + async createGitTree(repoId, input) {
136 + calls.push(['createGitTree', repoId, structuredClone(input)]);
137 + return { sha: NEW_TREE };
138 + },
139 + async createGitCommit(repoId, input) {
140 + calls.push(['createGitCommit', repoId, structuredClone(input)]);
141 + return { sha: COMMIT_SHA };
142 + },
143 + async createGitBranchRef(repoId, input) {
144 + calls.push(['createGitBranchRef', repoId, structuredClone(input)]);
145 + if (createRefError) throw createRefError;
146 + return { ref: `refs/heads/${input.branch}`, sha: input.sha };
147 + }
148 + };
149 +}
150 +
151 +function minimalMenu() {
152 + return {
153 + async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
154 + async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
155 + };
156 +}
157 +
158 +test('workspace approval uses compact <=56 byte token and binds owner action risk repo and exact 8-char intent', async () => {
159 + let now = 1_700_000_000_000;
160 + const approvals = new ApprovalService({
161 + secret: 'workspace-secret',
162 + now: () => now,
163 + ttlMs: 120_000,
164 + replayStore: replayStore()
165 + });
166 + const token = await approvals.issue({
167 + pluginId: 'github',
168 + actionId: 'github.workspace.commit_branch',
169 + risk: 'WRITE',
170 + ownerId: OWNER,
171 + input: { repoId: REPO_ID, intentId: INTENT_ID }
172 + });
173 + assert.ok(new TextEncoder().encode(token).byteLength <= 56);
174 + assert.ok(new TextEncoder().encode(`approve:${token}`).byteLength <= 64);
175 + const payload = await approvals.consume(token, {
176 + ownerId: OWNER,
177 + pluginId: 'github',
178 + actionId: 'github.workspace.commit_branch',
179 + risk: 'WRITE'
180 + });
181 + assert.deepEqual(payload.input, { repoId: REPO_ID, intentId: INTENT_ID });
182 + await assert.rejects(() => approvals.consume(token, { ownerId: OWNER }), /already used/i);
183 +
184 + const second = await approvals.issue({
185 + pluginId: 'github', actionId: 'github.workspace.commit_branch', risk: 'WRITE', ownerId: OWNER,
186 + input: { repoId: REPO_ID, intentId: INTENT_ID }
187 + });
188 + now += 121_000;
189 + await assert.rejects(() => approvals.verify(second, { ownerId: OWNER }), /expired/i);
190 + await assert.rejects(() => approvals.issue({
191 + pluginId: 'github', actionId: 'github.workspace.commit_branch', risk: 'WRITE', ownerId: OWNER,
192 + input: { repoId: REPO_ID, intentId: 'too-short' }
193 + }), /intent/i);
194 +});
195 +
196 +test('wscommit resolves to WRITE approval metadata before execution and performs zero GitHub or workspace calls pre-approval', async () => {
197 + const github = makeGitHub();
198 + const workspaces = makeWorkspaces();
199 + const plugin = createGitHubPlugin({ github, menu: minimalMenu(), workspaces });
200 + const router = new PluginRouter({
201 + registry: new PluginRegistry([plugin]),
202 + policy: new ActionPolicy(),
203 + audit: new AuditLogger({ sink: () => {} })
204 + });
205 + const result = await router.dispatchCallback(`wscommit:${REPO_ID}:${INTENT_ID}`, { isOwner: true, ownerId: OWNER });
206 + assert.equal(result.requiresApproval, true);
207 + assert.equal(result.actionId, 'github.workspace.commit_branch');
208 + assert.deepEqual(result.approval.input, { repoId: REPO_ID, intentId: INTENT_ID });
209 + assert.equal(result.approval.cancelCallback, `repo:${REPO_ID}`);
210 + assert.deepEqual(github.calls, []);
211 + assert.deepEqual(workspaces.calls, []);
212 +});
213 +
214 +test('approved orchestration fails closed on changed workspace material or stale base before any Git object creation', async () => {
215 + assert.equal(typeof workspaceModule.commitWorkspaceIntent, 'function');
216 +
217 + const changedWorkspaces = makeWorkspaces({ workspace: makeWorkspace({ currentIntentId: null, draftDigest: '9'.repeat(64) }) });
218 + const changedGitHub = makeGitHub();
219 + await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
220 + github: changedGitHub, workspaces: changedWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
221 + }), /intent|material|changed|stale/i);
222 + assert.equal(changedGitHub.calls.some(call => call[0].startsWith('createGit')), false);
223 +
224 + const staleWorkspaces = makeWorkspaces();
225 + const staleGitHub = makeGitHub({ baseHead: '9'.repeat(40) });
226 + await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
227 + github: staleGitHub, workspaces: staleWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
228 + }), /base|stale|changed/i);
229 + assert.equal(staleGitHub.calls.some(call => call[0].startsWith('createGit')), false);
230 + assert.ok(staleWorkspaces.calls.some(call => call[0] === 'markStale'));
231 +});
232 +
233 +test('approved orchestration rejects an unexpected existing target branch without creating Git objects', async () => {
234 + const workspaces = makeWorkspaces();
235 + const github = makeGitHub({ existingRef: { branch: TARGET_BRANCH, sha: '8'.repeat(40) } });
236 + await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
237 + github, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
238 + }), /already exists|target branch|unexpected/i);
239 + assert.equal(github.calls.some(call => call[0].startsWith('createGit')), false);
240 +});
241 +
242 +test('successful approved orchestration is blob -> tree -> commit -> durable candidate -> create ref -> durable COMMITTED', async () => {
243 + const workspaces = makeWorkspaces();
244 + const github = makeGitHub();
245 + const result = await workspaceModule.commitWorkspaceIntent({ github, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID });
246 + assert.deepEqual(result, { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: false });
247 + assert.deepEqual(github.calls.map(call => call[0]), [
248 + 'getBranchSnapshot', 'getGitRef', 'createGitBlob', 'createGitTree', 'createGitCommit', 'createGitBranchRef'
249 + ]);
250 + const blobCall = github.calls.find(call => call[0] === 'createGitBlob');
251 + assert.equal(blobCall[2], 'after\n');
252 + const treeCall = github.calls.find(call => call[0] === 'createGitTree');
253 + assert.deepEqual(treeCall[2], {
254 + baseTreeSha: BASE_TREE,
255 + entries: [{ path: 'src/app.js', mode: '100644', type: 'blob', sha: CONTENT_BLOB }]
256 + });
257 + const commitCall = github.calls.find(call => call[0] === 'createGitCommit');
258 + assert.deepEqual(commitCall[2], {
259 + message: 'edit app', treeSha: NEW_TREE, parentSha: BASE_HEAD, timestamp: TIMESTAMP
260 + });
261 + assert.ok(workspaces.calls.some(call => call[0] === 'setCandidateCommit' && call[3] === COMMIT_SHA));
262 + assert.ok(workspaces.calls.some(call => call[0] === 'completeCommit' && call[3] === COMMIT_SHA && call[4] === TARGET_BRANCH));
263 +});
264 +
265 +test('COMMITTED and COMMITTING retries reconcile idempotently without a second provider write', async () => {
266 + const committedIntent = makeIntent({ state: 'COMMITTED', commitSha: COMMIT_SHA, branch: TARGET_BRANCH });
267 + const committedWorkspaces = makeWorkspaces({ intent: committedIntent });
268 + const committedGitHub = makeGitHub();
269 + assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
270 + github: committedGitHub, workspaces: committedWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
271 + }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
272 + assert.deepEqual(committedGitHub.calls, []);
273 +
274 + const resumingIntent = makeIntent({ state: 'COMMITTING', candidateCommitSha: COMMIT_SHA });
275 + const resumingWorkspaces = makeWorkspaces({ intent: resumingIntent });
276 + const resumingGitHub = makeGitHub({ existingRef: { branch: TARGET_BRANCH, sha: COMMIT_SHA } });
277 + assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
278 + github: resumingGitHub, workspaces: resumingWorkspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
279 + }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
280 + assert.deepEqual(resumingGitHub.calls.map(call => call[0]), ['getGitRef']);
281 + assert.ok(resumingWorkspaces.calls.some(call => call[0] === 'completeCommit'));
282 +});
283 +
284 +test('ambiguous create-ref error reconciles only the exact candidate SHA and rejects different or missing refs', async () => {
285 + const ambiguous = new Error('GitHub create branch ref failed: 422 Reference already exists');
286 + const sequenceGitHub = makeGitHub({ createRefError: ambiguous });
287 + let refReads = 0;
288 + sequenceGitHub.getGitRef = async (repoId, branch, options) => {
289 + sequenceGitHub.calls.push(['getGitRef', repoId, branch, options]);
290 + refReads += 1;
291 + return refReads === 1 ? null : { branch, sha: COMMIT_SHA };
292 + };
293 + const workspaces = makeWorkspaces();
294 + assert.deepEqual(await workspaceModule.commitWorkspaceIntent({
295 + github: sequenceGitHub, workspaces, ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
296 + }), { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true });
297 +
298 + for (const ref of [null, { branch: TARGET_BRANCH, sha: '7'.repeat(40) }]) {
299 + const github = makeGitHub({ createRefError: ambiguous });
300 + let reads = 0;
301 + github.getGitRef = async (repoId, branch, options) => {
302 + github.calls.push(['getGitRef', repoId, branch, options]);
303 + reads += 1;
304 + return reads === 1 ? null : ref;
305 + };
306 + await assert.rejects(() => workspaceModule.commitWorkspaceIntent({
307 + github, workspaces: makeWorkspaces(), ownerId: OWNER, repoId: REPO_ID, intentId: INTENT_ID
308 + }), /422|reconcile|branch|candidate/i);
309 + }
310 +});
311 +
312 +test('router audit merges only allowlisted workspace metadata and never source draft text or signed token material', async () => {
313 + const events = [];
314 + const plugin = {
315 + manifest: { id: 'safe', name: 'safe', version: 1, commands: [], actions: { 'safe.write': { risk: 'WRITE' } } },
316 + resolveCallback() {
317 + return {
318 + actionId: 'safe.write',
319 + audit: {
320 + repoId: REPO_ID,
321 + workspaceId: WORKSPACE_ID,
322 + intentId: INTENT_ID,
323 + path: 'src/app.js',
324 + contentDigest: CONTENT_DIGEST,
325 + commitSha: COMMIT_SHA,
326 + draftText: 'DO NOT LOG THIS',
327 + token: 'approve:DO_NOT_LOG'
328 + },
329 + execute: async () => ({ text: 'ok' })
330 + };
331 + }
332 + };
333 + const router = new PluginRouter({
334 + registry: new PluginRegistry([plugin]), policy: new ActionPolicy(),
335 + audit: new AuditLogger({ sink: event => events.push(event) })
336 + });
337 + await router.dispatchCallback('x', { isOwner: true, approved: true });
338 + const serialized = JSON.stringify(events);
339 + assert.match(serialized, /src\/app\.js/);
340 + assert.match(serialized, new RegExp(INTENT_ID));
341 + assert.doesNotMatch(serialized, /DO NOT LOG THIS|DO_NOT_LOG|draftText|token/);
342 +});
test/github-workspace-bot-approval.test.js new
+97
@@ -0,0 +1,97 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { NexaDevBot } from '../src/bot.js';
4 +import { ApprovalService } from '../src/core/approval.js';
5 +
6 +const OWNER = 42;
7 +const REPO_ID = 123;
8 +const INTENT_ID = 'Ab12_cdE';
9 +
10 +function oneShotReplayStore() {
11 + const seen = new Set();
12 + return {
13 + async consume({ ownerId, nonce }) {
14 + const key = `${ownerId}:${nonce}`;
15 + if (seen.has(key)) return false;
16 + seen.add(key);
17 + return true;
18 + }
19 + };
20 +}
21 +
22 +function buttons(markup) {
23 + return markup?.inline_keyboard?.flat() || [];
24 +}
25 +
26 +test('bot workspace commit approval uses repository cancel fallback, executes only after approval and rejects replay', async () => {
27 + const bot = new NexaDevBot({ TELEGRAM_WEBHOOK_SECRET: 'workspace-test-secret' });
28 + bot.approvals = new ApprovalService({
29 + secret: 'workspace-test-secret',
30 + replayStore: oneShotReplayStore()
31 + });
32 +
33 + const routeCalls = [];
34 + bot.router = {
35 + async dispatchCallback(data, context) {
36 + routeCalls.push({ data, context: structuredClone(context) });
37 + if (data !== `wscommit:${REPO_ID}:${INTENT_ID}`) return null;
38 + if (context.approved === true) {
39 + return {
40 + text: '✅ committed',
41 + reply_markup: { inline_keyboard: [[{ text: 'project', callback_data: `repo:${REPO_ID}` }]] }
42 + };
43 + }
44 + return {
45 + ok: false,
46 + pluginId: 'github',
47 + actionId: 'github.workspace.commit_branch',
48 + risk: 'WRITE',
49 + requiresApproval: true,
50 + denied: false,
51 + approval: {
52 + input: { repoId: REPO_ID, intentId: INTENT_ID },
53 + label: 'Commit روی branch جدید',
54 + cancelCallback: `repo:${REPO_ID}`
55 + }
56 + };
57 + }
58 + };
59 +
60 + const edits = [];
61 + bot.telegram = {
62 + async answerCallbackQuery() { return { ok: true }; },
63 + async editMessageText(chatId, messageId, text, replyMarkup) {
64 + edits.push({ chatId, messageId, text, replyMarkup });
65 + return { ok: true };
66 + }
67 + };
68 +
69 + const baseQuery = {
70 + id: 'cb-1',
71 + from: { id: OWNER },
72 + message: { chat: { id: 7 }, message_id: 9 }
73 + };
74 + const prepare = await bot.handleCallbackQuery({ ...baseQuery, data: `wscommit:${REPO_ID}:${INTENT_ID}` });
75 + assert.equal(prepare.approvalRequired, true);
76 + assert.equal(routeCalls.length, 1);
77 + assert.notEqual(routeCalls[0].context.approved, true);
78 +
79 + const approvalButtons = buttons(edits.at(-1).replyMarkup);
80 + const confirm = approvalButtons.find(button => button.callback_data?.startsWith('approve:'));
81 + const cancel = approvalButtons.find(button => button.text.includes('انصراف'));
82 + assert.ok(confirm);
83 + assert.equal(cancel.callback_data, `repo:${REPO_ID}`);
84 + assert.ok(new TextEncoder().encode(confirm.callback_data).byteLength <= 64);
85 +
86 + const approved = await bot.handleCallbackQuery({ ...baseQuery, id: 'cb-2', data: confirm.callback_data });
87 + assert.equal(approved.approved, true);
88 + assert.equal(routeCalls.length, 2);
89 + assert.equal(routeCalls[1].data, `wscommit:${REPO_ID}:${INTENT_ID}`);
90 + assert.deepEqual(routeCalls[1].context, { isOwner: true, ownerId: String(OWNER), approved: true });
91 + assert.match(edits.at(-1).text, /committed/);
92 +
93 + const replay = await bot.handleCallbackQuery({ ...baseQuery, id: 'cb-3', data: confirm.callback_data });
94 + assert.equal(replay.approvalRejected, true);
95 + assert.match(replay.error, /already used/i);
96 + assert.equal(routeCalls.length, 2);
97 +});
test/github-workspace-integration.test.js new
+258
@@ -0,0 +1,258 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { NexaDevBot } from '../src/bot.js';
4 +import { PluginRouter } from '../src/core/router.js';
5 +import { PluginRegistry } from '../src/core/plugin-registry.js';
6 +import { ActionPolicy } from '../src/core/action-policy.js';
7 +import { AuditLogger } from '../src/core/audit.js';
8 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
9 +import { digestText } from '../src/core/workspace-policy.js';
10 +
11 +const OWNER = '42';
12 +const WORKSPACE_ID = 'W000000001';
13 +
14 +function flatten(view) {
15 + return view?.reply_markup?.inline_keyboard?.flat() || [];
16 +}
17 +
18 +function makeMenu() {
19 + return {
20 + async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
21 + async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
22 + };
23 +}
24 +
25 +function makeGitHub() {
26 + const calls = [];
27 + return {
28 + calls,
29 + async getRepository(repoId) {
30 + calls.push(['getRepository', Number(repoId)]);
31 + return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived: false };
32 + }
33 + };
34 +}
35 +
36 +function makeWorkspaces() {
37 + const calls = [];
38 + let pending = null;
39 + let intentCounter = 0;
40 + const intents = new Map();
41 + const workspace = {
42 + id: WORKSPACE_ID,
43 + repoId: 123,
44 + repoFullName: 'davood/demo',
45 + baseBranch: 'main',
46 + baseHeadSha: 'a'.repeat(40),
47 + baseTreeSha: 'b'.repeat(40),
48 + path: 'src/app.js',
49 + blobSha: 'c'.repeat(40),
50 + originalText: 'before\n',
51 + originalDigest: '0'.repeat(64),
52 + draftText: 'before\n',
53 + draftDigest: '0'.repeat(64),
54 + commitMessage: '',
55 + commitMessageDigest: '',
56 + currentIntentId: null,
57 + state: 'DRAFT'
58 + };
59 +
60 + return {
61 + calls,
62 + workspace,
63 + intents,
64 + async getWorkspace({ ownerId, workspaceId }) {
65 + calls.push(['getWorkspace', ownerId, workspaceId]);
66 + return ownerId === OWNER && workspaceId === WORKSPACE_ID ? structuredClone(workspace) : null;
67 + },
68 + async setPendingInput({ ownerId, workspaceId, mode }) {
69 + calls.push(['setPendingInput', ownerId, workspaceId, mode]);
70 + pending = { workspaceId, mode };
71 + return structuredClone(pending);
72 + },
73 + async getPendingInput({ ownerId }) {
74 + calls.push(['getPendingInput', ownerId]);
75 + return ownerId === OWNER && pending ? structuredClone(pending) : null;
76 + },
77 + async consumePendingInput({ ownerId, workspaceId, mode }) {
78 + calls.push(['consumePendingInput', ownerId, workspaceId, mode]);
79 + if (ownerId !== OWNER || !pending || pending.workspaceId !== workspaceId || pending.mode !== mode) return false;
80 + pending = null;
81 + return true;
82 + },
83 + async updateDraft({ ownerId, workspaceId, text, digest }) {
84 + calls.push(['updateDraft', ownerId, workspaceId, text, digest]);
85 + workspace.draftText = text;
86 + workspace.draftDigest = digest;
87 + workspace.currentIntentId = null;
88 + workspace.state = 'DRAFT';
89 + return structuredClone(workspace);
90 + },
91 + async setCommitMessage({ ownerId, workspaceId, message, digest }) {
92 + calls.push(['setCommitMessage', ownerId, workspaceId, message, digest]);
93 + workspace.commitMessage = message;
94 + workspace.commitMessageDigest = digest;
95 + workspace.currentIntentId = null;
96 + workspace.state = 'DRAFT';
97 + return structuredClone(workspace);
98 + },
99 + async sealIntent({ ownerId, workspaceId, intent }) {
100 + calls.push(['sealIntent', ownerId, workspaceId, structuredClone(intent)]);
101 + if (workspace.currentIntentId) {
102 + const existing = intents.get(workspace.currentIntentId);
103 + if (existing?.intentDigest === intent.intentDigest) return structuredClone(existing);
104 + }
105 + intentCounter += 1;
106 + const id = `I${String(intentCounter).padStart(7, '0')}`;
107 + const sealed = { ...structuredClone(intent), id, workspaceId, state: 'READY' };
108 + intents.set(id, sealed);
109 + workspace.currentIntentId = id;
110 + workspace.state = 'READY';
111 + return structuredClone(sealed);
112 + }
113 + };
114 +}
115 +
116 +function makePlugin() {
117 + const github = makeGitHub();
118 + const workspaces = makeWorkspaces();
119 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
120 + return { github, workspaces, plugin };
121 +}
122 +
123 +test('PluginRouter dispatchMessage applies the same policy boundary without auditing source text', async () => {
124 + const auditEvents = [];
125 + const plugin = {
126 + manifest: { id: 'demo', name: 'Demo', version: 1, commands: [], actions: { 'demo.message': { risk: 'READ' } } },
127 + resolveMessage(payload) {
128 + if (!payload?.pending) return null;
129 + return { actionId: 'demo.message', execute: async () => ({ text: 'accepted' }) };
130 + }
131 + };
132 + const router = new PluginRouter({
133 + registry: new PluginRegistry([plugin]),
134 + policy: new ActionPolicy(),
135 + audit: new AuditLogger({ sink: event => auditEvents.push(event) })
136 + });
137 + const result = await router.dispatchMessage({ pending: { mode: 'draft' }, text: 'TOP SECRET SOURCE' }, { isOwner: true, ownerId: OWNER });
138 + assert.equal(result.text, 'accepted');
139 + assert.equal(JSON.stringify(auditEvents).includes('TOP SECRET SOURCE'), false);
140 +});
141 +
142 +test('draft input is prepared without GitHub calls and the next owner text is consumed exactly once', async () => {
143 + const { github, workspaces, plugin } = makePlugin();
144 + const prepare = plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER });
145 + assert.equal(prepare.actionId, 'github.workspace.input.prepare');
146 + assert.deepEqual(github.calls, []);
147 + const prompt = await prepare.execute();
148 + assert.match(prompt.text, /3,000|3000/);
149 + assert.deepEqual(github.calls, []);
150 +
151 + const pending = await workspaces.getPendingInput({ ownerId: OWNER });
152 + assert.deepEqual(pending, { workspaceId: WORKSPACE_ID, mode: 'draft' });
153 + const route = plugin.resolveMessage({ pending, text: 'after <tag>\n' }, { ownerId: OWNER });
154 + assert.equal(route.actionId, 'github.workspace.input.apply');
155 + const view = await route.execute();
156 + assert.match(view.text, /ذخیره|Draft|پیش.?نویس/i);
157 + assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
158 + assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
159 +
160 + const late = plugin.resolveMessage({ pending: await workspaces.getPendingInput({ ownerId: OWNER }), text: 'late mutation' }, { ownerId: OWNER });
161 + assert.equal(late, null);
162 + assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
163 + assert.deepEqual(github.calls, []);
164 +});
165 +
166 +test('oversized multibyte draft input is visibly rejected without mutating the old draft', async () => {
167 + const { workspaces, plugin } = makePlugin();
168 + await plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
169 + const before = workspaces.workspace.draftText;
170 + const pending = await workspaces.getPendingInput({ ownerId: OWNER });
171 + const route = plugin.resolveMessage({ pending, text: '😀'.repeat(3001) }, { ownerId: OWNER });
172 + const view = await route.execute();
173 + assert.match(view.text, /12,000|12000|3,000|3000|مجاز|حد/i);
174 + assert.equal(workspaces.workspace.draftText, before);
175 + assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
176 +});
177 +
178 +test('commit message input normalizes text and diff renders escaped bounded exact counts without GitHub mutation', async () => {
179 + const { github, workspaces, plugin } = makePlugin();
180 + await plugin.resolveCallback(`wmsg:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
181 + const pending = await workspaces.getPendingInput({ ownerId: OWNER });
182 + await plugin.resolveMessage({ pending, text: ' chore: update workspace ' }, { ownerId: OWNER }).execute();
183 + assert.equal(workspaces.workspace.commitMessage, 'chore: update workspace');
184 +
185 + workspaces.workspace.draftText = 'after <script>\n';
186 + workspaces.workspace.draftDigest = await digestText(workspaces.workspace.draftText);
187 + const diffRoute = plugin.resolveCallback(`wdiff:${WORKSPACE_ID}`, { ownerId: OWNER });
188 + assert.equal(diffRoute.actionId, 'github.workspace.diff');
189 + const diffView = await diffRoute.execute();
190 + assert.match(diffView.text, /\+1/);
191 + assert.match(diffView.text, /-1/);
192 + assert.doesNotMatch(diffView.text, /<script>/);
193 + assert.match(diffView.text, /&lt;script&gt;/);
194 + assert.deepEqual(github.calls, []);
195 +});
196 +
197 +test('READY rejects no-change, reuses identical material and mints a new intent after material change', async () => {
198 + const { github, workspaces, plugin } = makePlugin();
199 + workspaces.workspace.commitMessage = 'edit app';
200 + workspaces.workspace.commitMessageDigest = await digestText('edit app');
201 +
202 + const noChange = plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER });
203 + await assert.rejects(() => noChange.execute(), /change|تغییر|بدون/i);
204 +
205 + workspaces.workspace.draftText = 'after\n';
206 + workspaces.workspace.draftDigest = await digestText('after\n');
207 + const ready1 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
208 + const commit1 = flatten(ready1).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
209 + assert.match(commit1, /^wscommit:123:[A-Za-z0-9_-]{8}$/);
210 + assert.ok(new TextEncoder().encode(commit1).byteLength <= 64);
211 +
212 + const ready2 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
213 + const commit2 = flatten(ready2).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
214 + assert.equal(commit2, commit1);
215 +
216 + workspaces.workspace.draftText = 'after again\n';
217 + workspaces.workspace.draftDigest = await digestText('after again\n');
218 + workspaces.workspace.currentIntentId = null;
219 + workspaces.workspace.state = 'DRAFT';
220 + const ready3 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
221 + const commit3 = flatten(ready3).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
222 + assert.notEqual(commit3, commit1);
223 + assert.deepEqual(github.calls, []);
224 +});
225 +
226 +test('bot preserves command precedence and routes raw pending workspace text exactly once', async () => {
227 + const bot = new NexaDevBot({});
228 + const calls = [];
229 + bot.telegram = {
230 + async sendMessage(chatId, text, replyMarkup) {
231 + calls.push(['sendMessage', chatId, text, replyMarkup]);
232 + return { ok: true };
233 + }
234 + };
235 + bot.workspaceStore = {
236 + isConfigured: () => true,
237 + async getPendingInput({ ownerId }) {
238 + calls.push(['getPendingInput', ownerId]);
239 + return { workspaceId: WORKSPACE_ID, mode: 'draft' };
240 + }
241 + };
242 + bot.router = {
243 + async dispatchMessage(payload, context) {
244 + calls.push(['dispatchMessage', structuredClone(payload), structuredClone(context)]);
245 + return { text: 'workspace accepted', reply_markup: { inline_keyboard: [] } };
246 + }
247 + };
248 +
249 + await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: '/status' });
250 + assert.equal(calls.some(call => call[0] === 'getPendingInput'), false);
251 + assert.equal(calls.some(call => call[0] === 'dispatchMessage'), false);
252 +
253 + calls.length = 0;
254 + await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: ' exact draft text \n' });
255 + const dispatch = calls.find(call => call[0] === 'dispatchMessage');
256 + assert.equal(dispatch[1].text, ' exact draft text \n');
257 + assert.deepEqual(dispatch[2], { isOwner: true, ownerId: OWNER });
258 +});
test/github-workspace-provider-error-ui.test.js new
+46
@@ -0,0 +1,46 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { NexaDevBot } from '../src/bot.js';
4 +import { ApprovalService } from '../src/core/approval.js';
5 +
6 +function replayStore() {
7 + return { async consume() { return true; } };
8 +}
9 +
10 +test('workspace approved provider errors are HTML-escaped before Telegram rendering', async () => {
11 + const bot = new NexaDevBot({ TELEGRAM_WEBHOOK_SECRET: 'test-secret' });
12 + bot.approvals = new ApprovalService({ secret: 'test-secret', replayStore: replayStore() });
13 + bot.router = {
14 + async dispatchCallback(data, context) {
15 + if (context?.approved === true) throw new Error('GitHub provider <bad>& response');
16 + return null;
17 + }
18 + };
19 + const edits = [];
20 + bot.telegram = {
21 + async answerCallbackQuery() { return { ok: true }; },
22 + async editMessageText(chatId, messageId, text, replyMarkup) {
23 + edits.push({ chatId, messageId, text, replyMarkup });
24 + return { ok: true };
25 + }
26 + };
27 +
28 + const token = await bot.approvals.issue({
29 + pluginId: 'github',
30 + actionId: 'github.workspace.commit_branch',
31 + risk: 'WRITE',
32 + ownerId: '42',
33 + input: { repoId: 123, intentId: 'Ab12_cdE' }
34 + });
35 + const result = await bot.handleCallbackQuery({
36 + id: 'cb',
37 + from: { id: 42 },
38 + data: `approve:${token}`,
39 + message: { chat: { id: 7 }, message_id: 9 }
40 + });
41 +
42 + assert.equal(result.providerError, true);
43 + assert.equal(edits.length, 1);
44 + assert.match(edits[0].text, /GitHub provider &lt;bad&gt;&amp; response/);
45 + assert.doesNotMatch(edits[0].text, /<bad>/);
46 +});
test/github-workspace-provider.test.js new
+203
@@ -0,0 +1,203 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GitHubService } from '../src/github.js';
4 +
5 +const REPO = 123;
6 +const HEAD = 'a'.repeat(40);
7 +const TREE = 'b'.repeat(40);
8 +const BLOB1 = 'c'.repeat(40);
9 +const BLOB2 = 'd'.repeat(40);
10 +const COMMIT = 'e'.repeat(40);
11 +const TIMESTAMP = '2026-10-03T09:00:00.000Z';
12 +
13 +function jsonBody(options = {}) {
14 + return options.body ? JSON.parse(options.body) : null;
15 +}
16 +
17 +function withFetch(handler, run) {
18 + const original = globalThis.fetch;
19 + globalThis.fetch = handler;
20 + return Promise.resolve()
21 + .then(run)
22 + .finally(() => { globalThis.fetch = original; });
23 +}
24 +
25 +function repoResponse(url) {
26 + if (String(url).endsWith('/repositories/123')) {
27 + return Response.json({ id: REPO, name: 'demo', full_name: 'davood/demo', default_branch: 'main' });
28 + }
29 + return null;
30 +}
31 +
32 +test('getGitRef encodes slash branch names and only 404 may become an allowed missing ref', async () => {
33 + const seen = [];
34 + await withFetch(async (url, options = {}) => {
35 + const repo = repoResponse(url);
36 + if (repo) return repo;
37 + seen.push([String(url), options.method || 'GET']);
38 + if (String(url).endsWith('/git/ref/heads/feature/mobile')) {
39 + return Response.json({ ref: 'refs/heads/feature/mobile', object: { type: 'commit', sha: HEAD } });
40 + }
41 + return new Response(JSON.stringify({ message: 'Not Found' }), { status: 404, headers: { 'content-type': 'application/json' } });
42 + }, async () => {
43 + const github = new GitHubService('token', 'davood');
44 + assert.deepEqual(await github.getGitRef(REPO, 'feature/mobile'), { branch: 'feature/mobile', sha: HEAD });
45 + assert.equal(await github.getGitRef(REPO, 'missing/branch', { allowMissing: true }), null);
46 + await assert.rejects(() => github.getGitRef(REPO, 'missing/branch'), /404/);
47 + });
48 + assert.ok(seen.some(([url, method]) => url.endsWith('/git/ref/heads/feature/mobile') && method === 'GET'));
49 +});
50 +
51 +test('getGitRef still propagates non-404 provider errors and validates returned full SHA', async () => {
52 + await withFetch(async (url) => {
53 + const repo = repoResponse(url);
54 + if (repo) return repo;
55 + return new Response(JSON.stringify({ message: 'Forbidden' }), { status: 403, headers: { 'content-type': 'application/json' } });
56 + }, async () => {
57 + const github = new GitHubService('token', 'davood');
58 + await assert.rejects(() => github.getGitRef(REPO, 'main', { allowMissing: true }), /403 Forbidden/);
59 + });
60 +
61 + await withFetch(async (url) => {
62 + const repo = repoResponse(url);
63 + if (repo) return repo;
64 + return Response.json({ ref: 'refs/heads/main', object: { sha: 'short' } });
65 + }, async () => {
66 + const github = new GitHubService('token', 'davood');
67 + await assert.rejects(() => github.getGitRef(REPO, 'main'), /SHA/);
68 + });
69 +});
70 +
71 +test('Git Data primitives send exact blob tree commit and branch-ref requests', async () => {
72 + const requests = [];
73 + await withFetch(async (url, options = {}) => {
74 + const repo = repoResponse(url);
75 + if (repo) return repo;
76 + requests.push({ url: String(url), method: options.method || 'GET', body: jsonBody(options) });
77 + const value = String(url);
78 + if (value.endsWith('/git/blobs')) return Response.json({ sha: BLOB1 }, { status: 201 });
79 + if (value.endsWith('/git/trees')) return Response.json({ sha: TREE }, { status: 201 });
80 + if (value.endsWith('/git/commits')) return Response.json({ sha: COMMIT }, { status: 201 });
81 + if (value.endsWith('/git/refs')) return Response.json({ ref: 'refs/heads/nexa/edit-W123456789', object: { sha: COMMIT } }, { status: 201 });
82 + return new Response('unexpected', { status: 500 });
83 + }, async () => {
84 + const github = new GitHubService('token', 'davood');
85 + assert.deepEqual(await github.createGitBlob(REPO, 'hello\n'), { sha: BLOB1 });
86 + assert.deepEqual(await github.createGitTree(REPO, {
87 + baseTreeSha: HEAD,
88 + entries: [
89 + { path: 'src/app.js', mode: '100644', type: 'blob', sha: BLOB1 },
90 + { path: 'src/other.js', mode: '100644', type: 'blob', sha: BLOB2 }
91 + ]
92 + }), { sha: TREE });
93 + assert.deepEqual(await github.createGitCommit(REPO, {
94 + message: 'edit app', treeSha: TREE, parentSha: HEAD, timestamp: TIMESTAMP
95 + }), { sha: COMMIT });
96 + assert.deepEqual(await github.createGitBranchRef(REPO, {
97 + branch: 'nexa/edit-W123456789', sha: COMMIT
98 + }), { ref: 'refs/heads/nexa/edit-W123456789', sha: COMMIT });
99 + });
100 +
101 + assert.deepEqual(requests, [
102 + {
103 + url: 'https://api.github.com/repos/davood/demo/git/blobs',
104 + method: 'POST',
105 + body: { content: 'hello\n', encoding: 'utf-8' }
106 + },
107 + {
108 + url: 'https://api.github.com/repos/davood/demo/git/trees',
109 + method: 'POST',
110 + body: {
111 + base_tree: HEAD,
112 + tree: [
113 + { path: 'src/app.js', mode: '100644', type: 'blob', sha: BLOB1 },
114 + { path: 'src/other.js', mode: '100644', type: 'blob', sha: BLOB2 }
115 + ]
116 + }
117 + },
118 + {
119 + url: 'https://api.github.com/repos/davood/demo/git/commits',
120 + method: 'POST',
121 + body: {
122 + message: 'edit app',
123 + tree: TREE,
124 + parents: [HEAD],
125 + author: { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: TIMESTAMP },
126 + committer: { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: TIMESTAMP }
127 + }
128 + },
129 + {
130 + url: 'https://api.github.com/repos/davood/demo/git/refs',
131 + method: 'POST',
132 + body: { ref: 'refs/heads/nexa/edit-W123456789', sha: COMMIT }
133 + }
134 + ]);
135 +});
136 +
137 +test('Git Data primitives validate all full SHAs and preserve deterministic retry bodies', async () => {
138 + const commitBodies = [];
139 + await withFetch(async (url, options = {}) => {
140 + const repo = repoResponse(url);
141 + if (repo) return repo;
142 + if (String(url).endsWith('/git/commits')) {
143 + commitBodies.push(jsonBody(options));
144 + return Response.json({ sha: COMMIT }, { status: 201 });
145 + }
146 + return Response.json({ sha: TREE }, { status: 201 });
147 + }, async () => {
148 + const github = new GitHubService('token', 'davood');
149 + await assert.rejects(() => github.createGitTree(REPO, { baseTreeSha: 'short', entries: [] }), /SHA/);
150 + await assert.rejects(() => github.createGitTree(REPO, {
151 + baseTreeSha: TREE,
152 + entries: [{ path: 'a.js', mode: '100644', type: 'blob', sha: 'short' }]
153 + }), /SHA/);
154 + await assert.rejects(() => github.createGitCommit(REPO, { message: 'x', treeSha: 'short', parentSha: HEAD, timestamp: TIMESTAMP }), /SHA/);
155 + await assert.rejects(() => github.createGitCommit(REPO, { message: 'x', treeSha: TREE, parentSha: 'short', timestamp: TIMESTAMP }), /SHA/);
156 + await assert.rejects(() => github.createGitBranchRef(REPO, { branch: 'nexa/edit-W123456789', sha: 'short' }), /SHA/);
157 +
158 + const input = { message: 'same material', treeSha: TREE, parentSha: HEAD, timestamp: TIMESTAMP };
159 + await github.createGitCommit(REPO, input);
160 + await github.createGitCommit(REPO, input);
161 + });
162 + assert.equal(commitBodies.length, 2);
163 + assert.deepEqual(commitBodies[0], commitBodies[1]);
164 +});
165 +
166 +test('provider 409 and 422 remain explicit and an existing different target ref never triggers an update or force endpoint', async () => {
167 + for (const status of [409, 422]) {
168 + await withFetch(async (url, options = {}) => {
169 + const repo = repoResponse(url);
170 + if (repo) return repo;
171 + return new Response(JSON.stringify({ message: 'Reference conflict' }), {
172 + status,
173 + headers: { 'content-type': 'application/json' }
174 + });
175 + }, async () => {
176 + const github = new GitHubService('token', 'davood');
177 + await assert.rejects(
178 + () => github.createGitBranchRef(REPO, { branch: 'nexa/edit-W123456789', sha: COMMIT }),
179 + new RegExp(String(status))
180 + );
181 + });
182 + }
183 +
184 + const calls = [];
185 + await withFetch(async (url, options = {}) => {
186 + const repo = repoResponse(url);
187 + if (repo) return repo;
188 + calls.push({ url: String(url), method: options.method || 'GET' });
189 + if (String(url).endsWith('/git/ref/heads/nexa/edit-W123456789')) {
190 + return Response.json({ object: { sha: HEAD } });
191 + }
192 + return new Response('unexpected', { status: 500 });
193 + }, async () => {
194 + const github = new GitHubService('token', 'davood');
195 + const existing = await github.getGitRef(REPO, 'nexa/edit-W123456789', { allowMissing: true });
196 + assert.deepEqual(existing, { branch: 'nexa/edit-W123456789', sha: HEAD });
197 + assert.notEqual(existing.sha, COMMIT);
198 + });
199 + assert.deepEqual(calls, [{
200 + url: 'https://api.github.com/repos/davood/demo/git/ref/heads/nexa/edit-W123456789',
201 + method: 'GET'
202 + }]);
203 +});
test/github-workspace-ui.test.js new
+265
@@ -0,0 +1,265 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GitHubService } from '../src/github.js';
4 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5 +
6 +function makeMenu() {
7 + const calls = [];
8 + return {
9 + calls,
10 + async getReposListView() { calls.push('/repos'); return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
11 + async renderByCallback(data) { calls.push(data); return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
12 + };
13 +}
14 +
15 +function makeWorkspaces() {
16 + const calls = [];
17 + const refs = new Map();
18 + const workspaces = new Map();
19 + let refCounter = 0;
20 + return {
21 + calls,
22 + refs,
23 + workspaces,
24 + async createNavigationRefs({ ownerId, refs: input }) {
25 + calls.push(['createNavigationRefs', ownerId, structuredClone(input)]);
26 + return input.map(ref => {
27 + refCounter += 1;
28 + const refId = `R${String(refCounter).padStart(9, '0')}`;
29 + refs.set(`${ownerId}:${refId}`, structuredClone(ref));
30 + return { refId };
31 + });
32 + },
33 + async resolveNavigationRef({ ownerId, refId }) {
34 + calls.push(['resolveNavigationRef', ownerId, refId]);
35 + return refs.get(`${ownerId}:${refId}`) || null;
36 + },
37 + async createWorkspace(payload) {
38 + calls.push(['createWorkspace', payload.ownerId, payload.path, payload.baseHeadSha]);
39 + const workspace = { id: 'W000000001', state: 'DRAFT', draftText: payload.originalText, ...payload };
40 + workspaces.set(`${payload.ownerId}:${workspace.id}`, workspace);
41 + return workspace;
42 + },
43 + async getWorkspace({ ownerId, workspaceId }) {
44 + calls.push(['getWorkspace', ownerId, workspaceId]);
45 + return workspaces.get(`${ownerId}:${workspaceId}`) || null;
46 + }
47 + };
48 +}
49 +
50 +function makeGitHub({ archived = false, fileText = 'export const ok = true;\n', filePath = 'src/deep/really-long-file-name-for-mobile-editor.js' } = {}) {
51 + const calls = [];
52 + const headSha = 'a'.repeat(40);
53 + const treeSha = 'b'.repeat(40);
54 + const blobSha = 'c'.repeat(40);
55 + return {
56 + calls,
57 + headSha,
58 + treeSha,
59 + blobSha,
60 + async getRepository(repoId) {
61 + calls.push(['getRepository', Number(repoId)]);
62 + return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived };
63 + },
64 + async listFiles(repoId, path = '', options = {}) {
65 + calls.push(['listFiles', Number(repoId), path, options.ref || null]);
66 + if (path === 'src/deep') {
67 + return [{ name: 'nested.js', path: 'src/deep/nested.js', type: 'file', size: 20, sha: 'd'.repeat(40) }];
68 + }
69 + return [
70 + { name: 'deep', path: 'src/deep', type: 'dir', size: 0, sha: 'e'.repeat(40) },
71 + { name: 'really-long-file-name-for-mobile-editor.js', path: filePath, type: 'file', size: new TextEncoder().encode(fileText).byteLength, sha: blobSha }
72 + ];
73 + },
74 + async getBranchSnapshot(repoId, branch) {
75 + calls.push(['getBranchSnapshot', Number(repoId), branch]);
76 + return { branch, headSha, treeSha };
77 + },
78 + async getFileAtRef(repoId, path, ref) {
79 + calls.push(['getFileAtRef', Number(repoId), path, ref]);
80 + return {
81 + path,
82 + sha: path === filePath ? blobSha : 'd'.repeat(40),
83 + size: new TextEncoder().encode(fileText).byteLength,
84 + encoding: 'utf-8',
85 + content: fileText
86 + };
87 + }
88 + };
89 +}
90 +
91 +function flatten(view) {
92 + return view.reply_markup?.inline_keyboard?.flat() || [];
93 +}
94 +
95 +test('exact files callback resolves side-effect-free then renders path-safe short navigation refs', async () => {
96 + const github = makeGitHub();
97 + const workspaces = makeWorkspaces();
98 + const menu = makeMenu();
99 + const plugin = createGitHubPlugin({ github, menu, workspaces });
100 +
101 + const route = plugin.resolveCallback('files:123', { ownerId: '42' });
102 + assert.equal(route.actionId, 'github.files.list');
103 + assert.deepEqual(github.calls, []);
104 + assert.deepEqual(workspaces.calls, []);
105 +
106 + const view = await route.execute();
107 + const buttons = flatten(view).filter(button => button.callback_data?.startsWith('wnav:'));
108 + assert.equal(buttons.length, 2);
109 + for (const button of buttons) {
110 + assert.match(button.callback_data, /^wnav:[A-Za-z0-9_-]{10}$/);
111 + assert.ok(new TextEncoder().encode(button.callback_data).byteLength <= 64);
112 + assert.doesNotMatch(button.callback_data, /src|really-long|\.js/);
113 + }
114 + assert.equal(menu.calls.length, 0);
115 +});
116 +
117 +test('nested directory resolves through short ref and preserves the full server-side path', async () => {
118 + const github = makeGitHub();
119 + const workspaces = makeWorkspaces();
120 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
121 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
122 + const dirCallback = flatten(root).find(button => button.text?.includes('deep'))?.callback_data;
123 + assert.match(dirCallback, /^wnav:/);
124 +
125 + github.calls.length = 0;
126 + workspaces.calls.length = 0;
127 + const route = plugin.resolveCallback(dirCallback, { ownerId: '42' });
128 + assert.equal(route.actionId, 'github.workspace.navigate');
129 + assert.deepEqual(github.calls, []);
130 + assert.deepEqual(workspaces.calls, []);
131 + const nested = await route.execute();
132 + assert.ok(flatten(nested).some(button => /^wnav:/.test(button.callback_data || '')));
133 + assert.ok(github.calls.some(call => call[0] === 'listFiles' && call[2] === 'src/deep'));
134 +});
135 +
136 +test('eligible file preview shows Edit while risky or oversized content stays readable with explicit disabled reason', async () => {
137 + for (const fixture of [
138 + { path: 'src/app.js', text: 'console.log(1);\n', editable: true },
139 + { path: '.env.production', text: 'NOT_A_REAL_SECRET=value\n', editable: false, reason: /sensitive/i },
140 + { path: 'large.txt', text: 'x'.repeat(3001), editable: false, reason: /3,000|3000/ },
141 + { path: 'asset.txt', text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 9\n', editable: false, reason: /LFS/i }
142 + ]) {
143 + const github = makeGitHub({ fileText: fixture.text, filePath: fixture.path });
144 + const workspaces = makeWorkspaces();
145 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
146 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
147 + const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
148 + const view = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
149 + assert.match(view.text, /پیش.?نمایش|فایل/i);
150 + const edit = flatten(view).find(button => button.callback_data?.startsWith('wedit:'));
151 + if (fixture.editable) {
152 + assert.ok(edit, fixture.path);
153 + } else {
154 + assert.equal(edit, undefined, fixture.path);
155 + assert.match(view.text, fixture.reason);
156 + }
157 + }
158 +});
159 +
160 +test('wedit pins default-branch snapshot and exact file before creating a durable draft', async () => {
161 + const github = makeGitHub({ filePath: 'src/app.js', fileText: 'before\n' });
162 + const workspaces = makeWorkspaces();
163 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
164 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
165 + const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
166 + const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
167 + const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
168 +
169 + github.calls.length = 0;
170 + workspaces.calls.length = 0;
171 + const route = plugin.resolveCallback(editCallback, { ownerId: '42' });
172 + assert.equal(route.actionId, 'github.workspace.create');
173 + assert.deepEqual(github.calls, []);
174 + assert.deepEqual(workspaces.calls, []);
175 + const draftView = await route.execute();
176 +
177 + const snapshotIndex = github.calls.findIndex(call => call[0] === 'getBranchSnapshot');
178 + const fileIndex = github.calls.findIndex(call => call[0] === 'getFileAtRef');
179 + const createCall = workspaces.calls.find(call => call[0] === 'createWorkspace');
180 + assert.ok(snapshotIndex >= 0 && fileIndex > snapshotIndex);
181 + assert.deepEqual(github.calls[fileIndex].slice(2), ['src/app.js', github.headSha]);
182 + assert.deepEqual(createCall, ['createWorkspace', '42', 'src/app.js', github.headSha]);
183 + assert.match(draftView.text, /Draft|پیش.?نویس/i);
184 + assert.ok(flatten(draftView).some(button => button.callback_data === 'ws:W000000001'));
185 +});
186 +
187 +test('archived repository cannot create an editable workspace', async () => {
188 + const github = makeGitHub({ archived: true, filePath: 'src/app.js' });
189 + const workspaces = makeWorkspaces();
190 + const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
191 + const root = await plugin.resolveCallback('files:123', { ownerId: '42' }).execute();
192 + const fileCallback = flatten(root).find(button => button.callback_data?.startsWith('wnav:') && !button.text?.includes('deep'))?.callback_data;
193 + const fileView = await plugin.resolveCallback(fileCallback, { ownerId: '42' }).execute();
194 + const editCallback = flatten(fileView).find(button => button.callback_data?.startsWith('wedit:'))?.callback_data;
195 + assert.equal(editCallback, undefined);
196 + assert.match(fileView.text, /archiv|آرشیو/i);
197 + assert.equal(workspaces.calls.some(call => call[0] === 'createWorkspace'), false);
198 +});
199 +
200 +test('legacy tree blob and path-bearing files callbacks remain on MenuManager path', async () => {
201 + const github = makeGitHub();
202 + const workspaces = makeWorkspaces();
203 + const menu = makeMenu();
204 + const plugin = createGitHubPlugin({ github, menu, workspaces });
205 +
206 + for (const callback of [
207 + `tree:123:${'a'.repeat(40)}`,
208 + `blob:123:${'b'.repeat(40)}`,
209 + 'files:123:src/deep'
210 + ]) {
211 + const route = plugin.resolveCallback(callback, { ownerId: '42' });
212 + const view = await route.execute();
213 + assert.equal(view.text, `legacy:${callback}`);
214 + }
215 +});
216 +
217 +test('workspace READ actions are declared and all short callback families fit Telegram limit', () => {
218 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu(), workspaces: makeWorkspaces() });
219 + for (const actionId of [
220 + 'github.workspace.navigate',
221 + 'github.workspace.create',
222 + 'github.workspace.view',
223 + 'github.workspace.input.prepare',
224 + 'github.workspace.diff',
225 + 'github.workspace.ready',
226 + 'github.workspace.cancel'
227 + ]) {
228 + assert.equal(plugin.manifest.actions[actionId]?.risk, 'READ', actionId);
229 + }
230 + for (const callback of [
231 + 'wnav:R123456789', 'wedit:R123456789', 'ws:W123456789', 'wtext:W123456789',
232 + 'wmsg:W123456789', 'wdiff:W123456789', 'wready:W123456789', 'wcancel:W123456789'
233 + ]) {
234 + assert.ok(new TextEncoder().encode(callback).byteLength <= 64, callback);
235 + }
236 +});
237 +
238 +test('GitHubService reads pinned branch snapshot and UTF-8 file at full SHA', async () => {
239 + const originalFetch = globalThis.fetch;
240 + const seen = [];
241 + const headSha = 'a'.repeat(40);
242 + const treeSha = 'b'.repeat(40);
243 + const blobSha = 'c'.repeat(40);
244 + globalThis.fetch = async (url, options = {}) => {
245 + seen.push([String(url), options.method || 'GET']);
246 + const value = String(url);
247 + if (value.endsWith('/repositories/123')) return Response.json({ id: 123, name: 'demo', full_name: 'davood/demo', default_branch: 'main' });
248 + if (value.endsWith('/repos/davood/demo/git/ref/heads/main')) return Response.json({ object: { sha: headSha } });
249 + if (value.endsWith(`/repos/davood/demo/git/commits/${headSha}`)) return Response.json({ sha: headSha, tree: { sha: treeSha } });
250 + if (value.endsWith(`/repos/davood/demo/contents/src/app.js?ref=${headSha}`)) {
251 + return Response.json({ type: 'file', path: 'src/app.js', sha: blobSha, size: 6, encoding: 'base64', content: btoa('hello\n') });
252 + }
253 + return new Response('unexpected', { status: 500 });
254 + };
255 + try {
256 + const github = new GitHubService('token', 'davood');
257 + assert.deepEqual(await github.getBranchSnapshot(123, 'main'), { branch: 'main', headSha, treeSha });
258 + assert.deepEqual(await github.getFileAtRef(123, 'src/app.js', headSha), {
259 + path: 'src/app.js', sha: blobSha, size: 6, encoding: 'utf-8', content: 'hello\n'
260 + });
261 + assert.ok(seen.some(([url]) => url.endsWith(`/contents/src/app.js?ref=${headSha}`)));
262 + } finally {
263 + globalThis.fetch = originalFetch;
264 + }
265 +});
test/workspace-policy.test.js new
+115
@@ -0,0 +1,115 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +
4 +let policy = {};
5 +try {
6 + policy = await import('../src/core/workspace-policy.js');
7 +} catch {
8 + policy = {};
9 +}
10 +
11 +const requireFn = name => {
12 + assert.equal(typeof policy[name], 'function', `${name} must be implemented`);
13 + return policy[name];
14 +};
15 +
16 +test('editable file policy accepts bounded UTF-8 text', () => {
17 + const validateEditableFile = requireFn('validateEditableFile');
18 + const result = validateEditableFile({ path: 'src/app.js', text: 'export const ok = true;\n' });
19 + assert.deepEqual(result, {
20 + editable: true,
21 + reason: '',
22 + text: 'export const ok = true;\n',
23 + charLength: 24,
24 + byteLength: 24
25 + });
26 +});
27 +
28 +test('editable file policy rejects sensitive paths binary markers LFS and both size ceilings', () => {
29 + const validateEditableFile = requireFn('validateEditableFile');
30 + for (const path of ['.env', '.env.production', 'keys/id_rsa', 'id_ed25519', 'tls/cert.pem', 'tls/private.key', 'a.p12', 'a.pfx', 'credentials.json', 'service-account-prod.json']) {
31 + const result = validateEditableFile({ path, text: 'safe-looking text' });
32 + assert.equal(result.editable, false, path);
33 + assert.match(result.reason, /sensitive/i);
34 + }
35 +
36 + const binary = validateEditableFile({ path: 'data.txt', text: 'abc\0def' });
37 + assert.equal(binary.editable, false);
38 + assert.match(binary.reason, /binary/i);
39 +
40 + const lfs = validateEditableFile({ path: 'asset.txt', text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 123\n' });
41 + assert.equal(lfs.editable, false);
42 + assert.match(lfs.reason, /LFS/i);
43 +
44 + const tooManyChars = validateEditableFile({ path: 'large.txt', text: 'a'.repeat(3001) });
45 + assert.equal(tooManyChars.editable, false);
46 + assert.match(tooManyChars.reason, /3,000|3000/);
47 +
48 + const explicitTooManyBytes = validateEditableFile({ path: 'large.txt', text: 'ok', byteLength: 12001 });
49 + assert.equal(explicitTooManyBytes.editable, false);
50 + assert.match(explicitTooManyBytes.reason, /12,000|12000/);
51 +});
52 +
53 +test('editable file policy enforces multibyte UTF-8 byte boundary independently from character boundary', () => {
54 + const validateEditableFile = requireFn('validateEditableFile');
55 + const exact = '😀'.repeat(3000);
56 + const exactResult = validateEditableFile({ path: 'emoji.txt', text: exact });
57 + assert.equal(exactResult.charLength, 3000);
58 + assert.equal(exactResult.byteLength, 12000);
59 + assert.equal(exactResult.editable, true);
60 +
61 + const over = `${exact}a`;
62 + const overResult = validateEditableFile({ path: 'emoji.txt', text: over });
63 + assert.equal(overResult.charLength, 3001);
64 + assert.equal(overResult.byteLength, 12001);
65 + assert.equal(overResult.editable, false);
66 +});
67 +
68 +test('commit message and target branch normalization fail closed on empty or unsafe values', () => {
69 + const normalizeCommitMessage = requireFn('normalizeCommitMessage');
70 + const makeTargetBranch = requireFn('makeTargetBranch');
71 +
72 + assert.equal(normalizeCommitMessage(' test: verify mobile editor '), 'test: verify mobile editor');
73 + assert.throws(() => normalizeCommitMessage(' '), /commit message/i);
74 + assert.throws(() => normalizeCommitMessage('x'.repeat(121)), /120/);
75 +
76 + assert.equal(makeTargetBranch('Ab3_-xYz09'), 'nexa/edit-Ab3_-xYz09');
77 + assert.throws(() => makeTargetBranch('../bad'), /workspace/i);
78 + assert.throws(() => makeTargetBranch('short'), /workspace/i);
79 +});
80 +
81 +test('unified diff reports exact additions deletions and marks bounded truncation without changing counts', () => {
82 + const buildUnifiedDiff = requireFn('buildUnifiedDiff');
83 + const before = 'alpha\nbeta\ngamma\n';
84 + const after = 'alpha\nBETA\ngamma\ndelta\n';
85 + const full = buildUnifiedDiff({ path: 'src/app.js', before, after, maxChars: 2600 });
86 + assert.equal(full.additions, 2);
87 + assert.equal(full.deletions, 1);
88 + assert.equal(full.truncated, false);
89 + assert.match(full.text, /--- a\/src\/app\.js/);
90 + assert.match(full.text, /\+\+\+ b\/src\/app\.js/);
91 + assert.match(full.text, /-beta/);
92 + assert.match(full.text, /\+BETA/);
93 + assert.match(full.text, /\+delta/);
94 +
95 + const bounded = buildUnifiedDiff({
96 + path: 'src/app.js',
97 + before: Array.from({ length: 250 }, (_, i) => `old-${i}`).join('\n'),
98 + after: Array.from({ length: 250 }, (_, i) => `new-${i}`).join('\n'),
99 + maxChars: 120
100 + });
101 + assert.equal(bounded.additions, 250);
102 + assert.equal(bounded.deletions, 250);
103 + assert.equal(bounded.truncated, true);
104 + assert.ok(bounded.text.length <= 120);
105 +});
106 +
107 +test('digestText is stable for identical content and changes with content', async () => {
108 + const digestText = requireFn('digestText');
109 + const first = await digestText('hello');
110 + const second = await digestText('hello');
111 + const changed = await digestText('hello!');
112 + assert.match(first, /^[a-f0-9]{64}$/);
113 + assert.equal(first, second);
114 + assert.notEqual(first, changed);
115 +});
test/workspace-store.test.js new
+207
@@ -0,0 +1,207 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFile } from 'node:fs/promises';
4 +
5 +let clientModule = {};
6 +let durableModule = {};
7 +let indexModule = {};
8 +try { clientModule = await import('../src/core/workspace-store.js'); } catch {}
9 +try { durableModule = await import('../src/durable/workspace-store.js'); } catch {}
10 +try { indexModule = await import('../src/index.js'); } catch {}
11 +
12 +const requireExport = (mod, name) => {
13 + assert.equal(typeof mod[name], 'function', `${name} must be implemented`);
14 + return mod[name];
15 +};
16 +
17 +function makeState() {
18 + const data = new Map();
19 + let alarm = null;
20 + const api = {
21 + async get(key) { return data.get(key); },
22 + async put(key, value) { data.set(key, structuredClone(value)); },
23 + async delete(key) { return data.delete(key); },
24 + async list() { return new Map(data); }
25 + };
26 + return {
27 + data,
28 + get alarm() { return alarm; },
29 + storage: {
30 + ...api,
31 + async transaction(fn) { return fn(api); },
32 + async setAlarm(value) { alarm = value; },
33 + async deleteAll() { data.clear(); alarm = null; }
34 + }
35 + };
36 +}
37 +
38 +function makeNamespace(StoreClass, states = new Map()) {
39 + return {
40 + states,
41 + idFromName(name) { return String(name); },
42 + get(id) {
43 + if (!states.has(id)) states.set(id, makeState());
44 + const state = states.get(id);
45 + const instance = new StoreClass(state);
46 + return { fetch: request => instance.fetch(request) };
47 + }
48 + };
49 +}
50 +
51 +function baseWorkspace(now = 1_000) {
52 + return {
53 + repoId: 123,
54 + repoFullName: 'davoodmehraban89/nexa-dev-bot',
55 + baseBranch: 'main',
56 + baseHeadSha: 'a'.repeat(40),
57 + baseTreeSha: 'b'.repeat(40),
58 + path: 'README.md',
59 + blobSha: 'c'.repeat(40),
60 + originalText: 'before\n',
61 + originalDigest: 'd'.repeat(64),
62 + expiresAt: now + 30 * 60_000
63 + };
64 +}
65 +
66 +function baseIntent(workspace, overrides = {}) {
67 + return {
68 + repoId: workspace.repoId,
69 + workspaceId: workspace.id,
70 + baseBranch: workspace.baseBranch,
71 + baseHeadSha: workspace.baseHeadSha,
72 + baseTreeSha: workspace.baseTreeSha,
73 + path: workspace.path,
74 + sourceBlobSha: workspace.blobSha,
75 + contentDigest: '1'.repeat(64),
76 + commitMessageDigest: '2'.repeat(64),
77 + targetBranch: `nexa/edit-${workspace.id}`,
78 + commitTimestamp: '2026-10-03T08:00:00.000Z',
79 + intentDigest: '3'.repeat(64),
80 + ...overrides
81 + };
82 +}
83 +
84 +test('DurableWorkspaceStoreClient fails closed without WORKSPACE_STORE', async () => {
85 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
86 + const client = new Client();
87 + assert.equal(client.isConfigured(), false);
88 + await assert.rejects(() => client.getWorkspace({ ownerId: 'owner', workspaceId: 'Ab3_-xYz09' }), /not configured/i);
89 +});
90 +
91 +test('workspace store isolates refs and workspaces by owner', async () => {
92 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
93 + const Store = requireExport(durableModule, 'WorkspaceStore');
94 + const namespace = makeNamespace(Store);
95 + const client = new Client({ namespace, now: () => 1_000 });
96 +
97 + const [ref] = await client.createNavigationRefs({ ownerId: 'A', refs: [{ repoId: 123, path: 'src/app.js', type: 'file', sha: 'a'.repeat(40) }] });
98 + assert.match(ref.refId, /^[A-Za-z0-9_-]{10}$/);
99 + assert.equal((await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId })).path, 'src/app.js');
100 + assert.equal(await client.resolveNavigationRef({ ownerId: 'B', refId: ref.refId }), null);
101 +
102 + const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
103 + assert.match(workspace.id, /^[A-Za-z0-9_-]{10}$/);
104 + assert.equal((await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id })).path, 'README.md');
105 + assert.equal(await client.getWorkspace({ ownerId: 'B', workspaceId: workspace.id }), null);
106 +});
107 +
108 +test('expired refs and workspaces read as missing and schedule cleanup', async () => {
109 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
110 + const Store = requireExport(durableModule, 'WorkspaceStore');
111 + let now = 1_000;
112 + const namespace = makeNamespace(Store);
113 + const client = new Client({ namespace, now: () => now });
114 +
115 + const [ref] = await client.createNavigationRefs({ ownerId: 'A', refs: [{ repoId: 1, path: 'a.txt', type: 'file', sha: 'a'.repeat(40) }], ttlMs: 50 });
116 + const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace(now), expiresAt: now + 50 });
117 + now = 1_051;
118 +
119 + assert.equal(await client.resolveNavigationRef({ ownerId: 'A', refId: ref.refId }), null);
120 + assert.equal(await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }), null);
121 + assert.ok(namespace.states.get('A').alarm !== null);
122 +});
123 +
124 +test('pending workspace input is owner scoped and consumed exactly once', async () => {
125 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
126 + const Store = requireExport(durableModule, 'WorkspaceStore');
127 + const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
128 + const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
129 +
130 + await client.setPendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'draft' });
131 + assert.deepEqual(await client.getPendingInput({ ownerId: 'A' }), { workspaceId: workspace.id, mode: 'draft' });
132 + assert.equal(await client.getPendingInput({ ownerId: 'B' }), null);
133 + assert.equal(await client.consumePendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'draft' }), true);
134 + assert.equal(await client.consumePendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'draft' }), false);
135 +});
136 +
137 +test('material draft or message changes invalidate READY intent while identical values reuse it', async () => {
138 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
139 + const Store = requireExport(durableModule, 'WorkspaceStore');
140 + const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
141 + let workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
142 + workspace = await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'after\n', digest: '1'.repeat(64) });
143 + workspace = await client.setCommitMessage({ ownerId: 'A', workspaceId: workspace.id, message: 'test: edit', digest: '2'.repeat(64) });
144 +
145 + const first = await client.sealIntent({ ownerId: 'A', workspaceId: workspace.id, intent: baseIntent(workspace) });
146 + assert.match(first.id, /^[A-Za-z0-9_-]{8}$/);
147 + const same = await client.sealIntent({ ownerId: 'A', workspaceId: workspace.id, intent: baseIntent(workspace) });
148 + assert.equal(same.id, first.id);
149 +
150 + await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'after\n', digest: '1'.repeat(64) });
151 + assert.equal((await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id })).currentIntentId, first.id);
152 +
153 + await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'changed\n', digest: '9'.repeat(64) });
154 + const changed = await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id });
155 + assert.equal(changed.currentIntentId, null);
156 + assert.equal(changed.state, 'DRAFT');
157 + assert.equal((await client.getIntent({ ownerId: 'A', intentId: first.id })).intentDigest, first.intentDigest);
158 +});
159 +
160 +test('sealed intent is immutable and beginCommit is atomic through COMMITTED result', async () => {
161 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
162 + const Store = requireExport(durableModule, 'WorkspaceStore');
163 + const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
164 + let workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
165 + workspace = await client.updateDraft({ ownerId: 'A', workspaceId: workspace.id, text: 'after\n', digest: '1'.repeat(64) });
166 + workspace = await client.setCommitMessage({ ownerId: 'A', workspaceId: workspace.id, message: 'test: edit', digest: '2'.repeat(64) });
167 + const intent = await client.sealIntent({ ownerId: 'A', workspaceId: workspace.id, intent: baseIntent(workspace) });
168 +
169 + const start = await client.beginCommit({ ownerId: 'A', intentId: intent.id });
170 + assert.equal(start.disposition, 'start');
171 + const resume = await client.beginCommit({ ownerId: 'A', intentId: intent.id });
172 + assert.equal(resume.disposition, 'resume');
173 +
174 + await client.setCandidateCommit({ ownerId: 'A', intentId: intent.id, commitSha: 'e'.repeat(40) });
175 + const completed = await client.completeCommit({ ownerId: 'A', intentId: intent.id, commitSha: 'e'.repeat(40), branch: intent.targetBranch });
176 + assert.equal(completed.state, 'COMMITTED');
177 + assert.equal(completed.commitSha, 'e'.repeat(40));
178 + assert.equal(completed.branch, intent.targetBranch);
179 +
180 + const again = await client.beginCommit({ ownerId: 'A', intentId: intent.id });
181 + assert.equal(again.disposition, 'committed');
182 + assert.equal(again.intent.commitSha, 'e'.repeat(40));
183 +
184 + const stored = await client.getIntent({ ownerId: 'A', intentId: intent.id });
185 + assert.equal(stored.intentDigest, intent.intentDigest);
186 + assert.equal(stored.contentDigest, intent.contentDigest);
187 +});
188 +
189 +test('cancelWorkspace removes draft and matching pending input', async () => {
190 + const Client = requireExport(clientModule, 'DurableWorkspaceStoreClient');
191 + const Store = requireExport(durableModule, 'WorkspaceStore');
192 + const client = new Client({ namespace: makeNamespace(Store), now: () => 1_000 });
193 + const workspace = await client.createWorkspace({ ownerId: 'A', ...baseWorkspace() });
194 + await client.setPendingInput({ ownerId: 'A', workspaceId: workspace.id, mode: 'commit_message' });
195 + await client.cancelWorkspace({ ownerId: 'A', workspaceId: workspace.id });
196 + assert.equal(await client.getWorkspace({ ownerId: 'A', workspaceId: workspace.id }), null);
197 + assert.equal(await client.getPendingInput({ ownerId: 'A' }), null);
198 +});
199 +
200 +test('Worker exports WorkspaceStore and Wrangler declares SQLite durable binding without legacy migrations', async () => {
201 + const Store = requireExport(durableModule, 'WorkspaceStore');
202 + assert.equal(indexModule.WorkspaceStore, Store);
203 + const config = JSON.parse(await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8'));
204 + assert.ok(config.durable_objects?.bindings?.some(binding => binding.name === 'WORKSPACE_STORE' && binding.class_name === 'WorkspaceStore'));
205 + assert.deepEqual(config.exports?.WorkspaceStore, { type: 'durable-object', storage: 'sqlite' });
206 + assert.equal('migrations' in config, false);
207 +});
wrangler.jsonc
+8
@@ -13,6 +13,10 @@
13 {
14 "name": "APPROVAL_REPLAY_GUARD",
15 "class_name": "ApprovalReplayGuard"
16 + },
17 + {
18 + "name": "WORKSPACE_STORE",
19 + "class_name": "WorkspaceStore"
20 }
21 ]
22 },
@@ -20,6 +24,10 @@
24 "ApprovalReplayGuard": {
25 "type": "durable-object",
26 "storage": "sqlite"
27 + },
28 + "WorkspaceStore": {
29 + "type": "durable-object",
30 + "storage": "sqlite"
31 }
32 }
33 }