Personal Telegram developer console for GitHub

feat: plugin foundation v1 (#14)

Introduce the Plugin Foundation v1 kernel with registry, action policy, redacted audit logging, policy-enforcing routing, and GitHub as the first plugin adapter. Preserve existing Telegram UX and route GitHub READ actions through resolve -> policy -> execute.

davoodmehraban89 committed Oct 3, 2026 at 01:47 UTC 9d95a18659cead269ffa98af08d6bbf041c6135f
15 files changed +988 -292
PROJECT_MEMORY.md
+105 -46
@@ -17,14 +17,19 @@
17
18 ## Architecture
19 - `src/index.js` — Cloudflare Worker HTTP boundary; webhook secret, owner authorization, required Telegram transport checks and redacted runtime diagnostics.
20 -- `src/bot.js` — Telegram update/callback router; callback acknowledgement is best-effort and cannot block menu rendering.
20 +- `src/bot.js` — Telegram update/callback coordinator; constructs the plugin kernel, keeps callback acknowledgement best-effort, routes GitHub operations through policy, and retains compatibility paths for non-GitHub menus.
21 +- `src/core/plugin-registry.js` — validates plugin/action manifests and rejects duplicate IDs or invalid risk values.
22 +- `src/core/action-policy.js` — central `READ` / `WRITE` / `DESTRUCTIVE` policy evaluation.
23 +- `src/core/audit.js` — best-effort structured action audit with recursive secret redaction.
24 +- `src/core/router.js` — policy-enforcing plugin router using the security-critical `resolve -> policy -> execute` flow.
25 +- `src/plugins/github/manifest.js` — GitHub plugin capability/action declarations.
26 +- `src/plugins/github/plugin.js` — GitHub plugin adapter around existing `GitHubService` and `MenuManager` behavior.
27 - `src/telegram.js` — Telegram Bot API client; explicit error propagation, fail-closed token handling and Cloudflare-safe default `fetch` invocation.
28 - `src/github.js` — authenticated GitHub REST reader; explicit errors, numeric repository-id resolution, tree/blob access.
29 - `src/menu.js` — hierarchical stateless inline menus, one-message editing, repository/file browser.
30 - `src/config.js` — non-secret static config.
31 - `.github/workflows/ci.yml` — Node 22 tests, official GitHub Actions v7 releases and non-zero test-discovery guard.
32 - `.github/workflows/deploy.yml` — production Cloudflare Worker deploy after successful CI on `main`; deploys the exact verified commit.
27 -- `test/` — security, Worker, navigation, menu, GitHub and Telegram regression coverage.
33 - `wrangler.jsonc` — Worker configuration; `keep_vars: true`, workers.dev enabled and observability enabled.
34
35 ## Runtime Configuration
@@ -49,6 +54,10 @@ GitHub Actions deployment secrets:
54 - Runtime diagnostic logs redact Telegram, webhook and GitHub secrets.
55 - Temporary setup/diagnostic exposure is disabled in source/tests.
56 - Operational UI does not invent SLA, latency or external health claims.
57 +- Plugin manifests must declare action risk as `READ`, `WRITE`, or `DESTRUCTIVE`.
58 +- Undeclared/unknown plugin actions are denied.
59 +- `WRITE` and `DESTRUCTIVE` plugin actions are not executed before an approval flow exists.
60 +- Plugin route resolvers must be side-effect-free; provider/view work is deferred to `execute()` after policy evaluation.
61
62 ## Telegram UX / GitHub Reader
63 - `/start` creates the initial menu message.
@@ -74,73 +83,115 @@ Audit scope covered the full recursive repository tree, including workflows, Wor
83
84 ### Root cause
85 - Telegram requests were reaching the production Worker, so webhook registration, secret header and owner gate were not the blocker.
77 -- Production observability showed `POST /telegram/webhook` returning HTTP 400 with:
78 - `Telegram API sendMessage network failure: Illegal invocation: function called with incorrect this reference`.
79 -- Root defect was in `src/telegram.js`: the platform-global `fetch` had been stored directly as an instance property and later called as `this.fetchFn(...)`, which supplied `TelegramClient` as the receiver. Cloudflare Workers rejects that receiver binding.
86 +- Production observability showed `POST /telegram/webhook` returning HTTP 400 with `Telegram API sendMessage network failure: Illegal invocation: function called with incorrect this reference`.
87 +- Root defect was in `src/telegram.js`: the platform-global `fetch` had been stored directly as an instance property and later called with the wrong receiver.
88 - Node unit tests had previously missed this platform-specific semantic difference.
89
90 ### PR #11 — redacted runtime diagnostics
83 -- Added regression-first diagnostics without exposing secrets.
84 -- RED commit: `079f9b7977e1120d1bcdbbcd75d91e6a322e5a49`.
85 -- Implementation commit: `2851c7045141aaeff501564d4a6bf8f22e333754`.
86 -- PR CI run `37064293599` = 30/30 pass.
87 -- Squash-merged to `main` at `cfd7a0b4803b13c76646b71666e7e0c66e023c99`.
91 +- RED commit `079f9b7977e1120d1bcdbbcd75d91e6a322e5a49`.
92 +- Implementation commit `2851c7045141aaeff501564d4a6bf8f22e333754`.
93 +- PR CI `37064293599` = 30/30 pass.
94 +- Squash merge `cfd7a0b4803b13c76646b71666e7e0c66e023c99`.
95 - Post-merge CI `37064405261` and deploy `37064436885` succeeded.
96
97 ### PR #12 — Cloudflare fetch receiver fix
91 -- Added a regression test that reproduces Cloudflare-style illegal receiver invocation.
92 -- RED commit: `99cf3468f820eb06390b7001c1d1eb5e5fb4ebbd`.
93 -- Fix commit: `c487727c968e4f00aecf0985a38b152f58e3b9b4`.
94 -- Fix: default transport now uses `(...args) => fetch(...args)` instead of storing bare platform `fetch`.
98 +- RED commit `99cf3468f820eb06390b7001c1d1eb5e5fb4ebbd`.
99 +- Fix commit `c487727c968e4f00aecf0985a38b152f58e3b9b4`.
100 +- Default transport now uses `(...args) => fetch(...args)` instead of storing bare platform `fetch`.
101 - PR CI `37064953868` = 31/31 pass.
96 -- Squash-merged to `main` at `bd01d8ede44331f50e1115d569095fb12246331d`.
102 +- Squash merge `bd01d8ede44331f50e1115d569095fb12246331d`.
103 - Post-merge CI `37065054623` and deploy `37065141745` succeeded.
98 -- Cloudflare telemetry after this deploy showed current-version Telegram webhook requests returning HTTP 200; the `Illegal invocation` errors existed only on the older Worker version.
104 +- Cloudflare telemetry showed current-version Telegram webhook requests returning HTTP 200; `Illegal invocation` existed only on the older Worker version.
105
106 ### PR #13 — callback resilience + documentation alignment
101 -- Added regression coverage requiring menu editing to continue even if `answerCallbackQuery` is stale/fails.
102 -- RED commit: `13daeb442d6a2e1189a5cec2148aab9c2ea7c338`.
103 -- Callback fix commit: `28e2e6b619c646796600048a34616138fbbc207c`.
104 -- README alignment commit: `67b04e04214e334a88aea0ecdc4598bc5fbd027c`.
107 +- RED commit `13daeb442d6a2e1189a5cec2148aab9c2ea7c338`.
108 +- Callback fix commit `28e2e6b619c646796600048a34616138fbbc207c`.
109 +- README alignment commit `67b04e04214e334a88aea0ecdc4598bc5fbd027c`.
110 - PR CI `37065725004` = 32/32 pass.
106 -- Squash-merged to `main` at `6c90cbb8384c9591ba89367b48e4ce7e785ce72f`.
107 -- Post-merge CI `37065832210` succeeded.
108 -- Post-merge deploy `37065860268` succeeded.
109 -- Cloudflare latest deployment after PR #13: `13a5abdc-92a0-415f-b30b-ab422ae8b8ce`, version `812c52f7-f0b3-48bf-917c-151f4618dabd`, 100% traffic.
110 -- Live Telegram webhook on this exact Worker version returned HTTP 200 with Worker outcome `ok`.
111 -- Observability query found no new `telegram_webhook_error` on fixed/current versions; retained error events were from the old pre-fix version only.
111 +- Squash merge `6c90cbb8384c9591ba89367b48e4ce7e785ce72f`.
112 +- Post-merge CI `37065832210` and deploy `37065860268` succeeded.
113 +- Cloudflare deployment `13a5abdc-92a0-415f-b30b-ab422ae8b8ce`, version `812c52f7-f0b3-48bf-917c-151f4618dabd`, served 100% traffic.
114 +- Live Telegram webhook on that Worker version returned HTTP 200 / outcome `ok`.
115 +
116 +## Plugin Foundation v1 — Implementation Checkpoint 2026-10-03
117 +
118 +### Approved design and plan
119 +- Design: `docs/superpowers/specs/2026-10-03-nexa-plugin-foundation-design.md`.
120 +- Design commit on `main`: `adabadefd74de656b20d112c325be4defcbf2103`.
121 +- Plan: `docs/superpowers/plans/2026-10-03-nexa-plugin-foundation.md`.
122 +- Initial plan commit on `main`: `5f9a1991dbc3a1e79f5c04dfbe591c4d35e74a97`.
123 +- Feature branch: `feat/plugin-foundation-v1`.
124 +- PR: `#14`.
125 +
126 +### Architecture implemented on PR #14
127 +- Plugin Registry with manifest/action validation.
128 +- Central Action Policy with owner READ allow and WRITE/DESTRUCTIVE approval-required decisions.
129 +- Recursive-redaction Audit Logger.
130 +- Plugin Router enforcing `resolve -> policy -> execute`.
131 +- GitHub manifest and plugin adapter.
132 +- `/repos` and GitHub callbacks migrated through the plugin kernel.
133 +- `/start`, `/status`, tools/settings/security and other non-GitHub menu flows remain compatibility routes in Foundation v1.
134 +
135 +### Security-critical design correction during implementation
136 +The initial plan described a handler returning an already-produced view/result. TDD review identified that this could allow provider/view work before policy. The implemented contract is safer: route resolution returns `{ actionId, execute }`; resolution must be side-effect-free, policy is evaluated next, and only then may `execute()` run. Tests prove denied, undeclared, WRITE and DESTRUCTIVE actions do not call `execute()`.
137 +
138 +### TDD evidence
139 +- Registry RED `2460b0854f6dbd99a80cfb9561850fdd23f1ac0e` / CI `37069219176`; GREEN `3f644caef41a9136cb5f0a78b0c66798238a257d` / CI `37069339637`.
140 +- Policy RED `77efe66f008fcb417b0b66f22b186885d3fecdd3` / CI `37069430240`; GREEN `cbdba6b1b70342d6325d229cec1725c05862a537` / CI `37069629741`.
141 +- Audit RED `a6f9735185f7a0ce45fe744b9a13b1fa3d885681` / CI `37069736330`; GREEN `92dfcba318f5199e6c9e54da5fbba91a15122ca3` / CI `37069824796`.
142 +- Router RED `4e3fca87139310c24c3c83a5181fc638f887882d` / CI `37069955642`; GREEN `00fcd1041e2f8074dc34727635395896eace0cba` / CI `37070015843`.
143 +- GitHub adapter RED `ae6829729779c2f656e99958a379c805eb1bebc4` / CI `37070181121`; GREEN adapter head `c9aed93bc1a3bd8ac047a3639722633bcd9c624e` / CI `37070481981`.
144 +- Bot migration RED `f1ee926320dc918d0d0c8b21d60710077a9d119b` / CI `37070633843`; GREEN integration `d628a4ed0b07dfa4c748b6161515565b1eef3073` / CI `37070778956`.
145 +- CI `37070778956` inspected in full: 12 test files discovered; 52 tests, 52 pass, 0 fail, 0 skipped/cancelled/todo.
146 +
147 +### Current verification state
148 +VERIFIED on PR merge result:
149 +- Plugin registry validation.
150 +- READ/WRITE/DESTRUCTIVE policy semantics.
151 +- Recursive audit redaction and non-breaking sink failure.
152 +- Undeclared and approval-required actions do not execute provider code.
153 +- GitHub callback/command ownership mapping.
154 +- Existing `/start`, same-message navigation, stale callback handling, security gates, GitHub fail-closed behavior and Cloudflare fetch-receiver regression remain green.
155 +
156 +NOT YET VERIFIED for Foundation v1:
157 +- Final documentation-head PR CI after this checkpoint commit.
158 +- Merge of PR #14 to `main`.
159 +- Post-merge `main` CI.
160 +- Cloudflare deployment of the merged Foundation revision.
161 +- Production Telegram webhook telemetry on that new Worker version.
162 +- Owner-device visual/interactive smoke after Foundation deploy.
163
164 ## Current Work / Last Checkpoint
165 WHERE WE ARE:
115 -- Full repository audit completed.
116 -- The production `/start` failure root cause was identified, reproduced with a regression test, fixed, merged and deployed.
117 -- Main CI and Cloudflare deploy are green.
118 -- Latest production Worker receives Telegram webhook traffic successfully with HTTP 200.
119 -- Callback navigation was additionally hardened against stale callback acknowledgements.
120 -- README now matches the deployed stateless Worker architecture.
166 +- Foundation v1 implementation is on PR #14 and has passed the full automated suite on the pre-documentation head.
167 +- Final documentation alignment is being committed before merge.
168 +- Production is still the previously verified pre-Foundation version until PR #14 is merged and deploy succeeds.
169
170 WHAT REMAINS:
123 -1. Owner-device visual smoke: confirm the new main menu is visible after `/start`.
124 -2. Exercise `Repositories → repository → Files → folder → file preview → root → project → Commits/PR/Status → Back → Main` and confirm the same Telegram message is edited throughout.
125 -3. Optional non-owner smoke to confirm no private bot response.
171 +1. Verify final PR #14 CI after documentation changes.
172 +2. Mark PR ready and merge after green CI/scope review.
173 +3. Verify post-merge main CI and Cloudflare deploy.
174 +4. Verify current-version Telegram webhook telemetry.
175 +5. Record owner-device smoke for the Foundation build.
176
177 ## Acceptance Rules
128 -A checkpoint is complete only after:
129 -`IMPLEMENTED → VERIFIED → FIXED IF NEEDED → RE-VERIFIED`
178 +A checkpoint is complete only after `IMPLEMENTED -> VERIFIED -> FIXED IF NEEDED -> RE-VERIFIED`.
179 Minimum automated/runtime gates:
180 - Non-zero discovered test files.
181 - Security tests green.
182 - Navigation/bot/menu/index tests green.
134 -- GitHub fail-closed/data-trust tests green.
183 +- Plugin registry/policy/audit/router tests green.
184 +- GitHub plugin/fail-closed/data-trust tests green.
185 - Telegram missing-token/API-error and Cloudflare fetch-receiver regression tests green.
186 - Production deploy workflow green.
187 - Cloudflare telemetry must show successful production webhook behavior before runtime is called verified.
188
189 ## Known Gaps / Low-Priority Technical Debt
140 -- Owner-device visual/interactive smoke remains the final UI acceptance gate.
190 +- Post-Foundation owner-device visual/interactive smoke remains a final UI acceptance gate.
191 - `package.json` still has `"start": "node src/index.js"`, which is not a useful local Cloudflare Worker development command; it does not affect production deployment.
142 -- Extremely long path-based refresh callback data could theoretically approach Telegram's 64-byte callback-data limit; normal deep navigation uses SHA-based callbacks and is not affected by the incident fixed here.
192 +- Extremely long path-based refresh callback data could theoretically approach Telegram's 64-byte callback-data limit; normal deep navigation uses SHA-based callbacks.
193 - Persistent navigation/session storage is intentionally not required for the current stateless callback flow.
194 +- Foundation v1 establishes approval-required policy results but intentionally does not implement the Telegram confirmation UX; that belongs to the first write-capable plugin phase.
195
196 ## Project Boundaries
197 - Nexa Dev Bot is independent from Finora / Factor-easy and has no Supabase requirement in this project.
@@ -150,22 +201,30 @@ Minimum automated/runtime gates:
201 ## Important Paths
202 - `PROJECT_MEMORY.md`
203 - `README.md`
204 +- `docs/superpowers/specs/2026-10-03-nexa-plugin-foundation-design.md`
205 +- `docs/superpowers/plans/2026-10-03-nexa-plugin-foundation.md`
206 - `src/index.js`
207 - `src/bot.js`
208 +- `src/core/plugin-registry.js`
209 +- `src/core/action-policy.js`
210 +- `src/core/audit.js`
211 +- `src/core/router.js`
212 +- `src/plugins/github/manifest.js`
213 +- `src/plugins/github/plugin.js`
214 - `src/menu.js`
215 - `src/telegram.js`
216 - `src/github.js`
158 -- `src/config.js`
217 +- `test/plugin-registry.test.js`
218 +- `test/action-policy.test.js`
219 +- `test/audit.test.js`
220 +- `test/plugin-router.test.js`
221 +- `test/github-plugin.test.js`
222 - `test/security.test.js`
223 - `test/navigation.test.js`
224 - `test/bot.test.js`
162 -- `test/menu.test.js`
163 -- `test/index.test.js`
164 -- `test/github.test.js`
165 -- `test/telegram.test.js`
225 - `.github/workflows/ci.yml`
226 - `.github/workflows/deploy.yml`
227 - `wrangler.jsonc`
228
229 ## Next Executable Action
171 -Run `/start` on the owner Telegram account. If the main menu renders, complete the one-message navigation smoke and record the result here.
\ No newline at end of file
230 +Verify final PR #14 CI after documentation commits; if green, perform final scope/secret review, mark ready, merge, verify main CI/deploy, then verify production telemetry and owner-device smoke.
docs/superpowers/plans/2026-10-03-nexa-plugin-foundation.md
+76 -240
@@ -1,12 +1,10 @@
1 # Nexa Dev Bot Plugin Foundation v1 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.
3 +> **Execution method:** superpowers `executing-plans` + TDD, on branch `feat/plugin-foundation-v1` and PR #14.
4
5 **Goal:** Introduce a small plugin kernel with explicit action risk policy and redacted auditing, then route existing GitHub behavior through a GitHub plugin without changing Telegram UX.
6
7 -**Architecture:** Add focused core modules for registry, policy, audit, and routing. Wrap the existing `GitHubService`/`MenuManager` behavior in a GitHub plugin adapter so existing UI and transport remain stable while future integrations gain a common extension contract.
8 -
9 -**Tech Stack:** JavaScript ES modules, Node.js 22 test runner, Cloudflare Workers, Telegram Bot API, GitHub REST API.
7 +**Architecture:** Focused core modules provide registry, policy, audit, and routing. The existing `GitHubService` and `MenuManager` remain the provider/data/view implementation; the GitHub plugin is an adapter around those existing capabilities.
8
9 **Spec:** `docs/superpowers/specs/2026-10-03-nexa-plugin-foundation-design.md`
10
@@ -15,22 +13,25 @@
13 - Bot remains owner-only.
14 - No secret, token, authorization header, or private key may appear in audit output, repository files, or Telegram output.
15 - Existing callback navigation continues to edit the same Telegram message.
18 -- Callback payloads remain within Telegram's 64-byte limit.
16 - Missing credentials fail closed.
20 -- Every declared plugin action must pass central policy evaluation before execution.
21 -- `WRITE` and `DESTRUCTIVE` actions are not automatically executed in Foundation v1.
17 +- Every declared plugin action must pass central policy evaluation before provider/view execution.
18 +- `WRITE` and `DESTRUCTIVE` actions are never auto-executed in Foundation v1.
19 - Worker remains stateless.
23 -- No AI, Browser QA, Supabase, Sentry, Linear, Notion, Mini App, or full Cloudflare operator implementation in this phase.
20 +- AI, Browser QA, Supabase, Sentry, Linear, Notion, Mini App, and full Cloudflare operator integrations are out of scope.
21 +
22 +## Implemented Structure
23 +
24 +New core:
25 +- `src/core/plugin-registry.js`
26 +- `src/core/action-policy.js`
27 +- `src/core/audit.js`
28 +- `src/core/router.js`
29
25 -## File Structure
30 +GitHub plugin:
31 +- `src/plugins/github/manifest.js`
32 +- `src/plugins/github/plugin.js`
33
27 -New:
28 -- `src/core/plugin-registry.js` — validates and indexes plugin manifests/actions.
29 -- `src/core/action-policy.js` — evaluates `READ` / `WRITE` / `DESTRUCTIVE` actions.
30 -- `src/core/audit.js` — best-effort structured audit with secret redaction.
31 -- `src/core/router.js` — resolves commands/callbacks to one plugin and enforces policy before execution.
32 -- `src/plugins/github/manifest.js` — GitHub plugin manifest/action declarations.
33 -- `src/plugins/github/plugin.js` — adapter over current `GitHubService` and `MenuManager` GitHub routes.
34 +New tests:
35 - `test/plugin-registry.test.js`
36 - `test/action-policy.test.js`
37 - `test/audit.test.js`
@@ -38,247 +39,82 @@ New:
39 - `test/github-plugin.test.js`
40
41 Modified:
41 -- `src/bot.js` — construct registry/router, route GitHub command/callbacks through plugin kernel, retain compatibility paths for non-GitHub menus.
42 -- `PROJECT_MEMORY.md` — record request, implementation evidence, CI/deploy/runtime status.
43 -
44 -## Review Focus
45 -
46 -1. Duplicate plugin/action identifiers must fail fast instead of silently shadowing an existing route.
47 -2. Unknown risk values or undeclared actions must be denied and must never invoke plugin code.
48 -3. Audit serialization must redact secrets even when they occur inside nested error/message values.
49 -4. A plugin returning `null` must not consume a route; the router must continue/fall back deterministically without dispatching two plugins.
50 -5. Callback acknowledgement failure must still not block GitHub plugin rendering/editing after migration.
51 -
52 ----
53 -
54 -### Task 1: Plugin Registry
55 -
56 -**Files:**
57 -- Create: `src/core/plugin-registry.js`
58 -- Create: `test/plugin-registry.test.js`
59 -
60 -**Interfaces:**
61 -- Produces: `PluginRegistry`, constructor `new PluginRegistry(plugins = [])`
62 -- Produces: `registry.getPlugins()`, `registry.getAction(actionId)`, `registry.getPlugin(pluginId)`
63 -- Manifest actions use `{ [actionId]: { risk: 'READ'|'WRITE'|'DESTRUCTIVE' } }`
64 -
65 -- [ ] **Step 1: Write failing registry tests**
66 -
67 -Cover valid registration, duplicate plugin ID, duplicate action ID, invalid risk, and lookup behavior.
68 -
69 -- [ ] **Step 2: Run registry test and confirm RED**
70 -
71 -Run: `node --test test/plugin-registry.test.js`
72 -Expected: FAIL because `src/core/plugin-registry.js` does not exist.
73 -
74 -- [ ] **Step 3: Implement `PluginRegistry` minimally**
75 -
76 -Validate plugin `manifest.id`, `manifest.actions`, and allowed risk values. Store immutable lookup maps sufficient for later router/policy tasks.
77 -
78 -- [ ] **Step 4: Run registry test and confirm GREEN**
79 -
80 -Run: `node --test test/plugin-registry.test.js`
81 -Expected: PASS.
82 -
83 -- [ ] **Step 5: Commit**
84 -
85 -Commit message: `feat: add plugin registry`
86 -
87 -### Task 2: Action Policy and Redacted Audit
88 -
89 -**Files:**
90 -- Create: `src/core/action-policy.js`
91 -- Create: `src/core/audit.js`
92 -- Create: `test/action-policy.test.js`
93 -- Create: `test/audit.test.js`
94 -
95 -**Interfaces:**
96 -- Consumes: action descriptors returned by `PluginRegistry.getAction(actionId)`
97 -- Produces: `ActionPolicy.evaluate({ action, isOwner }) -> { allowed, requiresApproval, risk, reason }`
98 -- Produces: `AuditLogger` with `log(event)` and shared redaction over configured secret values
99 -
100 -- [ ] **Step 1: Write failing policy tests**
101 -
102 -Assert owner `READ` is allowed without approval; `WRITE` and `DESTRUCTIVE` require approval and are not auto-executed; non-owner and missing/unknown action are denied.
103 -
104 -- [ ] **Step 2: Run policy test and confirm RED**
105 -
106 -Run: `node --test test/action-policy.test.js`
107 -Expected: FAIL because module is missing.
108 -
109 -- [ ] **Step 3: Implement `ActionPolicy` minimally**
110 -
111 -Use exact risks `READ`, `WRITE`, `DESTRUCTIVE`; return deterministic reason strings and deny unknown/missing actions.
112 -
113 -- [ ] **Step 4: Write failing audit tests**
114 -
115 -Assert nested strings containing bot/webhook/GitHub secrets are emitted redacted and that logging exceptions do not escape to the caller.
116 -
117 -- [ ] **Step 5: Run audit test and confirm RED**
118 -
119 -Run: `node --test test/audit.test.js`
120 -Expected: FAIL because module is missing.
121 -
122 -- [ ] **Step 6: Implement `AuditLogger` minimally**
123 -
124 -Accept secret values at construction, recursively sanitize string values, then emit structured events through an injectable sink defaulting to `console.log`; sink failure is swallowed after best-effort safe error logging.
125 -
126 -- [ ] **Step 7: Run policy + audit tests and confirm GREEN**
127 -
128 -Run: `node --test test/action-policy.test.js test/audit.test.js`
129 -Expected: PASS.
130 -
131 -- [ ] **Step 8: Commit**
132 -
133 -Commit message: `feat: add action policy and redacted audit`
134 -
135 -### Task 3: Policy-Enforcing Plugin Router
136 -
137 -**Files:**
138 -- Create: `src/core/router.js`
139 -- Create: `test/plugin-router.test.js`
140 -
141 -**Interfaces:**
142 -- Consumes: `PluginRegistry`, `ActionPolicy`, `AuditLogger`
143 -- Produces: `PluginRouter.dispatchCommand(command, context)` and `PluginRouter.dispatchCallback(data, context)`
144 -- Plugin handler result shape: `null` for no ownership, otherwise `{ actionId, view }` or `{ actionId, result }`
145 -
146 -- [ ] **Step 1: Write failing router tests**
147 -
148 -Assert exactly one matching plugin handles a route; `null` continues; unknown route returns `null`; declared `READ` runs; undeclared/denied action never reaches execution; WRITE/DESTRUCTIVE produce an approval-required normalized result without executing provider code; audit attempt/result events are emitted.
149 -
150 -- [ ] **Step 2: Run router test and confirm RED**
151 -
152 -Run: `node --test test/plugin-router.test.js`
153 -Expected: FAIL because router module is missing.
154 -
155 -- [ ] **Step 3: Implement `PluginRouter` minimally**
156 -
157 -Resolve handlers in registry order, require the returned `actionId` to be declared by that plugin, evaluate policy, audit the decision, and only return/execute an already-produced read view when policy allows. For approval-required actions, return a normalized non-executed result.
158 -
159 -- [ ] **Step 4: Run router test and confirm GREEN**
160 -
161 -Run: `node --test test/plugin-router.test.js`
162 -Expected: PASS.
163 -
164 -- [ ] **Step 5: Commit**
165 -
166 -Commit message: `feat: add policy enforcing plugin router`
167 -
168 -### Task 4: GitHub Plugin Adapter
169 -
170 -**Files:**
171 -- Create: `src/plugins/github/manifest.js`
172 -- Create: `src/plugins/github/plugin.js`
173 -- Create: `test/github-plugin.test.js`
174 -
175 -**Interfaces:**
176 -- Consumes: existing `GitHubService` and `MenuManager`
177 -- Produces: `createGitHubPlugin({ github, menu })`
178 -- Manifest id: `github`
179 -- Commands: `/repos`
180 -- Callback ownership prefixes: `menu:repos`, `repo:`, `files:`, `tree:`, `blob:`, `pr:`, `commits:`, `status:`
181 -- All Foundation v1 GitHub actions are `READ`
182 -
183 -- [ ] **Step 1: Write failing GitHub plugin tests**
184 -
185 -Assert `/repos` and each GitHub callback family map to a declared READ action and preserve the exact existing view objects returned by `MenuManager`; unrelated commands/callbacks return `null`.
186 -
187 -- [ ] **Step 2: Run GitHub plugin test and confirm RED**
188 -
189 -Run: `node --test test/github-plugin.test.js`
190 -Expected: FAIL because plugin modules are missing.
191 -
192 -- [ ] **Step 3: Implement GitHub manifest and adapter minimally**
193 -
194 -Delegate rendering to current menu methods. Do not move GitHub API logic or rewrite menu copy.
195 -
196 -- [ ] **Step 4: Run GitHub plugin test and confirm GREEN**
197 -
198 -Run: `node --test test/github-plugin.test.js`
199 -Expected: PASS.
200 -
201 -- [ ] **Step 5: Commit**
202 -
203 -Commit message: `feat: add github plugin adapter`
204 -
205 -### Task 5: Integrate Kernel into NexaDevBot Without UX Regression
206 -
207 -**Files:**
208 -- Modify: `src/bot.js`
209 -- Modify: `test/bot.test.js`
210 -- Modify: `test/navigation.test.js`
211 -- Modify: `test/security.test.js` only if a new explicit policy assertion belongs there
212 -
213 -**Interfaces:**
214 -- Consumes: `PluginRegistry`, `ActionPolicy`, `AuditLogger`, `PluginRouter`, `createGitHubPlugin`
215 -- Preserves: public behavior of `NexaDevBot.handleUpdate`, `handleMessage`, `handleCallbackQuery`
216 -
217 -- [ ] **Step 1: Add failing migration regression tests**
218 -
219 -Assert `/repos` and GitHub callback paths are dispatched through the plugin router, existing `/start`, `/status`, tools/settings/security compatibility paths remain unchanged, callback edits remain in-place, and callback acknowledgement failure still cannot block render/edit.
220 -
221 -- [ ] **Step 2: Run focused migration tests and confirm RED**
222 -
223 -Run: `node --test test/bot.test.js test/navigation.test.js`
224 -Expected: at least the new plugin-routing assertions FAIL before integration.
225 -
226 -- [ ] **Step 3: Integrate kernel into `NexaDevBot`**
227 -
228 -Construct the GitHub plugin from the existing `github` and `menu` instances. Route `/repos` and GitHub callbacks through `PluginRouter`; keep `/start`, `/status`, and non-GitHub menu callbacks on existing compatibility paths for Foundation v1.
229 -
230 -- [ ] **Step 4: Run focused migration tests and confirm GREEN**
231 -
232 -Run: `node --test test/bot.test.js test/navigation.test.js`
233 -Expected: PASS.
234 -
235 -- [ ] **Step 5: Run complete suite**
236 -
237 -Run: `npm test`
238 -Expected: all existing and new tests PASS with zero failures/skips.
239 -
240 -- [ ] **Step 6: Commit**
42 +- `src/bot.js`
43 +- `test/bot.test.js`
44 +- `PROJECT_MEMORY.md`
45
242 -Commit message: `refactor: route github through plugin kernel`
46 +## Security-Critical Router Contract
47
244 -### Task 6: Documentation, PR, CI, Deploy, Runtime Verification
48 +The implemented contract is deliberately stricter than the initial draft:
49
246 -**Files:**
247 -- Modify: `PROJECT_MEMORY.md`
50 +```text
51 +resolve route -> identify declared action -> evaluate policy -> audit decision -> execute provider/view code
52 +```
53
249 -**Interfaces:**
250 -- Consumes: completed implementation and CI/deploy evidence
251 -- Produces: durable checkpoint with SHAs/run IDs and explicit NOT VERIFIED items
54 +A plugin resolver returns either `null` or:
55
253 -- [ ] **Step 1: Update `PROJECT_MEMORY.md`**
56 +```js
57 +{
58 + actionId: 'github.repos.list',
59 + execute: async () => view
60 +}
61 +```
62
255 -Record Foundation v1 architecture, files, test counts, PR/commit evidence, and deployment state. Do not mark owner-device smoke verified until observed.
63 +`resolveCommand()` and `resolveCallback()` must be side-effect-free. Network/provider/menu work belongs inside the deferred `execute()` function. This guarantees `WRITE`, `DESTRUCTIVE`, undeclared, and denied actions cannot run before policy evaluation.
64
257 -- [ ] **Step 2: Run full suite one final time on branch**
65 +## Task 1 — Plugin Registry
66
259 -Run: `npm test`
260 -Expected: PASS.
67 +- [x] RED test added: valid registration, duplicate plugin ID, duplicate action ID, invalid risk, lookup behavior.
68 +- [x] RED CI confirmed: commit `2460b0854f6dbd99a80cfb9561850fdd23f1ac0e`, run `37069219176` failed for the missing module.
69 +- [x] `PluginRegistry` implemented: commit `3f644caef41a9136cb5f0a78b0c66798238a257d`.
70 +- [x] GREEN CI: `37069339637`.
71
262 -- [ ] **Step 3: Open PR to `main` and verify CI**
72 +## Task 2 — Action Policy + Redacted Audit
73
264 -Expected: PR CI success; inspect logs for actual discovered test count and zero failures.
74 +- [x] Policy RED commit `77efe66f008fcb417b0b66f22b186885d3fecdd3`; run `37069430240` failed as expected.
75 +- [x] `ActionPolicy` implementation commit `cbdba6b1b70342d6325d229cec1725c05862a537`; GREEN run `37069629741`.
76 +- [x] Audit RED commit `a6f9735185f7a0ce45fe744b9a13b1fa3d885681`; run `37069736330` failed as expected.
77 +- [x] `AuditLogger` implementation commit `92dfcba318f5199e6c9e54da5fbba91a15122ca3`; GREEN run `37069824796`.
78 +- [x] Recursive redaction covers nested strings, arrays, and objects; sink failures cannot break user actions.
79
266 -- [ ] **Step 4: Review PR diff for secrets and scope drift**
80 +## Task 3 — Policy-Enforcing Plugin Router
81
268 -Expected: only Foundation v1 files; no tokens/secrets; no unrelated provider integrations.
82 +- [x] RED commit `4e3fca87139310c24c3c83a5181fc638f887882d`; run `37069955642` failed as expected.
83 +- [x] Router implementation commit `00fcd1041e2f8074dc34727635395896eace0cba`.
84 +- [x] GREEN CI `37070015843`.
85 +- [x] Tests prove undeclared actions never execute.
86 +- [x] Tests prove `WRITE` and `DESTRUCTIVE` actions return approval-required results and never invoke `execute()`.
87 +- [x] Audit attempt/result events are emitted around allowed READ execution.
88
270 -- [ ] **Step 5: Merge only after CI is green**
89 +## Task 4 — GitHub Plugin Adapter
90
272 -Expected: squash/merge commit on `main`.
91 +- [x] RED commit `ae6829729779c2f656e99958a379c805eb1bebc4`; run `37070181121` failed as expected.
92 +- [x] Manifest + adapter implementation completed; final adapter commit `c9aed93bc1a3bd8ac047a3639722633bcd9c624e`.
93 +- [x] GREEN CI `37070481981`.
94 +- [x] `/repos`, `menu:repos`, `repo:`, `files:`, `tree:`, `blob:`, `pr:`, `commits:`, `status:` map to declared GitHub READ actions.
95 +- [x] Non-GitHub commands/callbacks are not consumed by the plugin.
96
274 -- [ ] **Step 6: Verify post-merge `main` CI and deploy workflow**
97 +## Task 5 — NexaDevBot Integration Without UX Regression
98
276 -Expected: both success; Cloudflare latest deployment serves the exact merged revision at 100% traffic.
99 +- [x] Migration RED tests added in commit `f1ee926320dc918d0d0c8b21d60710077a9d119b`; run `37070633843` failed as expected before integration.
100 +- [x] `src/bot.js` integration commit `d628a4ed0b07dfa4c748b6161515565b1eef3073`.
101 +- [x] `/repos` and GitHub callbacks route through the plugin kernel.
102 +- [x] `/start`, `/status`, and non-GitHub menu routes keep compatibility behavior.
103 +- [x] Callback acknowledgement remains best-effort and cannot block rendering.
104 +- [x] Same-message callback editing remains covered.
105 +- [x] PR CI run `37070778956` passed the merge result with **12 test files, 52 tests, 52 pass, 0 fail, 0 skip**.
106
278 -- [ ] **Step 7: Verify production runtime telemetry**
107 +## Task 6 — Final Review, Merge, Deploy, Runtime Verification
108
280 -Expected: Telegram webhook events on current Worker version return HTTP 200 with outcome `ok`, with no new plugin-kernel-related runtime errors.
109 +- [x] Full PR diff reviewed for Foundation v1 scope; no provider expansion or secret value added.
110 +- [x] Fresh PR CI evidence inspected, including test discovery and full `npm test` output.
111 +- [ ] Final documentation commit PR CI green.
112 +- [ ] PR #14 marked ready and merged to `main`.
113 +- [ ] Post-merge `main` CI green.
114 +- [ ] Cloudflare deploy workflow green and latest Worker deployment verified at 100% traffic.
115 +- [ ] Production Telegram webhook telemetry on the new Worker version returns HTTP 200 / outcome `ok` with no new plugin-kernel error.
116 +- [ ] Owner-device post-Foundation smoke recorded as VERIFIED or NOT VERIFIED.
117
282 -- [ ] **Step 8: Record owner-device smoke as VERIFIED or NOT VERIFIED**
118 +## Definition of Done
119
284 -Minimum smoke: `/start -> Repositories -> project -> Files -> folder/file -> project -> PR/Commits/Status -> Back -> Main`, preserving one-message callback navigation.
120 +Foundation v1 is complete only when all Task 6 runtime/deploy gates above are satisfied. Until then, implementation may be code-complete but is not marked production-complete.
src/bot.js
+61 -6
@@ -1,6 +1,11 @@
1 import { TelegramClient } from './telegram.js';
2 import { GitHubService } from './github.js';
3 import { MenuManager } from './menu.js';
4 +import { PluginRegistry } from './core/plugin-registry.js';
5 +import { ActionPolicy } from './core/action-policy.js';
6 +import { AuditLogger } from './core/audit.js';
7 +import { PluginRouter } from './core/router.js';
8 +import { createGitHubPlugin } from './plugins/github/plugin.js';
9
10 export class NexaDevBot {
11 constructor(env = {}) {
@@ -8,10 +13,31 @@ export class NexaDevBot {
13 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
14 this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
15 this.menu = new MenuManager(this.github);
16 +
17 + this.githubPlugin = createGitHubPlugin({
18 + github: this.github,
19 + menu: this.menu
20 + });
21 + this.registry = new PluginRegistry([this.githubPlugin]);
22 + this.policy = new ActionPolicy();
23 + this.audit = new AuditLogger({
24 + secrets: [
25 + env.TELEGRAM_BOT_TOKEN,
26 + env.TELEGRAM_WEBHOOK_SECRET,
27 + env.GITHUB_TOKEN
28 + ]
29 + });
30 + this.router = new PluginRouter({
31 + registry: this.registry,
32 + policy: this.policy,
33 + audit: this.audit
34 + });
35 }
36
37 /**
14 - * Process incoming Telegram webhook update
38 + * Process incoming Telegram webhook update.
39 + * Owner authorization is enforced at the Worker boundary before this bot is
40 + * constructed, so routed actions use an owner-authorized internal context.
41 */
42 async handleUpdate(update) {
43 if (!update) return { ok: false, error: 'Empty update' };
@@ -50,8 +76,29 @@ export class NexaDevBot {
76 }
77
78 try {
53 - // Render requested view
54 - const view = await this.menu.renderByCallback(data);
79 + // GitHub callbacks pass through the plugin policy boundary. Non-GitHub
80 + // callbacks remain on the existing compatibility router in Foundation v1.
81 + const routed = await this.router.dispatchCallback(data, { isOwner: true });
82 + if (routed?.requiresApproval) {
83 + return {
84 + ok: false,
85 + approvalRequired: true,
86 + actionId: routed.actionId,
87 + risk: routed.risk,
88 + callbackAnswered
89 + };
90 + }
91 + if (routed?.denied) {
92 + return {
93 + ok: false,
94 + denied: true,
95 + actionId: routed.actionId,
96 + reason: routed.reason,
97 + callbackAnswered
98 + };
99 + }
100 +
101 + const view = routed || await this.menu.renderByCallback(data);
102
103 // Edit the existing message in-place to prevent chat flooding
104 const res = await this.telegram.editMessageText(
@@ -84,10 +131,18 @@ export class NexaDevBot {
131 return { ok: true, command: 'start', res };
132 }
133
87 - // Legacy or shortcut command: /repos
134 + // GitHub shortcut command routed through the plugin kernel.
135 if (text === '/repos') {
89 - const view = await this.menu.getReposListView();
90 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
136 + const routed = await this.router.dispatchCommand(text, { isOwner: true });
137 + if (routed?.requiresApproval || routed?.denied || !routed) {
138 + return {
139 + ok: false,
140 + command: 'repos',
141 + error: routed?.reason || 'GitHub repository route unavailable'
142 + };
143 + }
144 +
145 + const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
146 return { ok: true, command: 'repos', res };
147 }
148
src/core/action-policy.js new
+50
@@ -0,0 +1,50 @@
1 +const KNOWN_RISKS = new Set(['READ', 'WRITE', 'DESTRUCTIVE']);
2 +
3 +export class ActionPolicy {
4 + evaluate({ action, isOwner } = {}) {
5 + const risk = action?.risk || null;
6 +
7 + if (!isOwner) {
8 + return {
9 + allowed: false,
10 + requiresApproval: false,
11 + risk,
12 + reason: 'owner_required'
13 + };
14 + }
15 +
16 + if (!action || !KNOWN_RISKS.has(risk)) {
17 + return {
18 + allowed: false,
19 + requiresApproval: false,
20 + risk,
21 + reason: 'unknown_action'
22 + };
23 + }
24 +
25 + if (risk === 'READ') {
26 + return {
27 + allowed: true,
28 + requiresApproval: false,
29 + risk,
30 + reason: 'owner_read_allowed'
31 + };
32 + }
33 +
34 + if (risk === 'WRITE') {
35 + return {
36 + allowed: false,
37 + requiresApproval: true,
38 + risk,
39 + reason: 'owner_write_requires_approval'
40 + };
41 + }
42 +
43 + return {
44 + allowed: false,
45 + requiresApproval: true,
46 + risk,
47 + reason: 'owner_destructive_requires_approval'
48 + };
49 + }
50 +}
src/core/audit.js new
+35
@@ -0,0 +1,35 @@
1 +function redactString(value, secrets) {
2 + let result = value;
3 + for (const secret of secrets) {
4 + if (secret) result = result.split(secret).join('[REDACTED]');
5 + }
6 + return result;
7 +}
8 +
9 +function sanitize(value, secrets) {
10 + if (typeof value === 'string') return redactString(value, secrets);
11 + if (Array.isArray(value)) return value.map(item => sanitize(item, secrets));
12 + if (value && typeof value === 'object') {
13 + return Object.fromEntries(
14 + Object.entries(value).map(([key, nested]) => [key, sanitize(nested, secrets)])
15 + );
16 + }
17 + return value;
18 +}
19 +
20 +export class AuditLogger {
21 + constructor({ secrets = [], sink } = {}) {
22 + this.secrets = secrets.map(value => String(value || '')).filter(Boolean);
23 + this.sink = sink || (event => console.log('nexa_audit', JSON.stringify(event)));
24 + }
25 +
26 + log(event) {
27 + const sanitized = sanitize(event, this.secrets);
28 + try {
29 + this.sink(sanitized);
30 + } catch {
31 + // Audit is best-effort in Foundation v1 and must never break a user action.
32 + }
33 + return sanitized;
34 + }
35 +}
src/core/plugin-registry.js new
+56
@@ -0,0 +1,56 @@
1 +const ALLOWED_RISKS = new Set(['READ', 'WRITE', 'DESTRUCTIVE']);
2 +
3 +export class PluginRegistry {
4 + constructor(plugins = []) {
5 + this.plugins = [];
6 + this.pluginsById = new Map();
7 + this.actionsById = new Map();
8 +
9 + for (const plugin of plugins) {
10 + this.register(plugin);
11 + }
12 + }
13 +
14 + register(plugin) {
15 + const pluginId = plugin?.manifest?.id;
16 + if (!pluginId) {
17 + throw new Error('Plugin manifest id is required');
18 + }
19 + if (this.pluginsById.has(pluginId)) {
20 + throw new Error(`Duplicate plugin id: ${pluginId}`);
21 + }
22 +
23 + const actions = plugin.manifest.actions || {};
24 + for (const [actionId, descriptor] of Object.entries(actions)) {
25 + if (this.actionsById.has(actionId)) {
26 + throw new Error(`Duplicate action id: ${actionId}`);
27 + }
28 + if (!ALLOWED_RISKS.has(descriptor?.risk)) {
29 + throw new Error(`Invalid action risk for ${actionId}: ${descriptor?.risk}`);
30 + }
31 + }
32 +
33 + this.plugins.push(plugin);
34 + this.pluginsById.set(pluginId, plugin);
35 +
36 + for (const [actionId, descriptor] of Object.entries(actions)) {
37 + this.actionsById.set(actionId, Object.freeze({
38 + pluginId,
39 + actionId,
40 + risk: descriptor.risk
41 + }));
42 + }
43 + }
44 +
45 + getPlugins() {
46 + return [...this.plugins];
47 + }
48 +
49 + getPlugin(pluginId) {
50 + return this.pluginsById.get(pluginId) || null;
51 + }
52 +
53 + getAction(actionId) {
54 + return this.actionsById.get(actionId) || null;
55 + }
56 +}
src/core/router.js new
+89
@@ -0,0 +1,89 @@
1 +export class PluginRouter {
2 + constructor({ registry, policy, audit } = {}) {
3 + if (!registry) throw new Error('PluginRouter registry is required');
4 + if (!policy) throw new Error('PluginRouter policy is required');
5 + if (!audit) throw new Error('PluginRouter audit logger is required');
6 +
7 + this.registry = registry;
8 + this.policy = policy;
9 + this.audit = audit;
10 + }
11 +
12 + async dispatchCommand(command, context = {}) {
13 + return this.#dispatch('resolveCommand', command, context);
14 + }
15 +
16 + async dispatchCallback(data, context = {}) {
17 + return this.#dispatch('resolveCallback', data, context);
18 + }
19 +
20 + async #dispatch(resolverName, input, context) {
21 + for (const plugin of this.registry.getPlugins()) {
22 + const resolver = plugin?.[resolverName];
23 + if (typeof resolver !== 'function') continue;
24 +
25 + const route = await resolver.call(plugin, input, context);
26 + if (!route) continue;
27 +
28 + const pluginId = plugin.manifest.id;
29 + const actionId = route.actionId;
30 + const registeredAction = this.registry.getAction(actionId);
31 + const action = registeredAction?.pluginId === pluginId ? registeredAction : null;
32 + const decision = this.policy.evaluate({
33 + action,
34 + isOwner: context.isOwner === true
35 + });
36 +
37 + this.audit.log({
38 + event: 'action_attempt',
39 + pluginId,
40 + actionId,
41 + risk: decision.risk,
42 + outcome: decision.allowed
43 + ? 'allowed'
44 + : (decision.requiresApproval ? 'approval_required' : 'denied'),
45 + reason: decision.reason
46 + });
47 +
48 + if (!decision.allowed) {
49 + return {
50 + ok: false,
51 + pluginId,
52 + actionId,
53 + risk: decision.risk,
54 + requiresApproval: decision.requiresApproval,
55 + denied: !decision.requiresApproval,
56 + reason: decision.reason
57 + };
58 + }
59 +
60 + if (typeof route.execute !== 'function') {
61 + throw new Error(`Plugin route execute function is required for ${actionId}`);
62 + }
63 +
64 + try {
65 + const result = await route.execute();
66 + this.audit.log({
67 + event: 'action_result',
68 + pluginId,
69 + actionId,
70 + risk: decision.risk,
71 + outcome: 'success'
72 + });
73 + return result;
74 + } catch (error) {
75 + this.audit.log({
76 + event: 'action_result',
77 + pluginId,
78 + actionId,
79 + risk: decision.risk,
80 + outcome: 'error',
81 + error: error?.message || 'Unknown plugin error'
82 + });
83 + throw error;
84 + }
85 + }
86 +
87 + return null;
88 + }
89 +}
src/plugins/github/manifest.js new
+16
@@ -0,0 +1,16 @@
1 +export const githubPluginManifest = Object.freeze({
2 + id: 'github',
3 + name: 'GitHub',
4 + version: 1,
5 + commands: Object.freeze(['/repos']),
6 + actions: Object.freeze({
7 + 'github.repos.list': Object.freeze({ risk: 'READ' }),
8 + 'github.repo.detail': Object.freeze({ risk: 'READ' }),
9 + 'github.files.list': Object.freeze({ risk: 'READ' }),
10 + 'github.tree.read': Object.freeze({ risk: 'READ' }),
11 + 'github.blob.read': Object.freeze({ risk: 'READ' }),
12 + 'github.pr.list': Object.freeze({ risk: 'READ' }),
13 + 'github.commits.list': Object.freeze({ risk: 'READ' }),
14 + 'github.status.read': Object.freeze({ risk: 'READ' })
15 + })
16 +});
src/plugins/github/plugin.js new
+49
@@ -0,0 +1,49 @@
1 +import { githubPluginManifest } from './manifest.js';
2 +
3 +const CALLBACK_ACTIONS = Object.freeze([
4 + ['repo:', 'github.repo.detail'],
5 + ['files:', 'github.files.list'],
6 + ['tree:', 'github.tree.read'],
7 + ['blob:', 'github.blob.read'],
8 + ['pr:', 'github.pr.list'],
9 + ['commits:', 'github.commits.list'],
10 + ['status:', 'github.status.read']
11 +]);
12 +
13 +function resolveCallbackAction(data) {
14 + const value = String(data || '');
15 + if (value === 'menu:repos') return 'github.repos.list';
16 +
17 + for (const [prefix, actionId] of CALLBACK_ACTIONS) {
18 + if (value.startsWith(prefix)) return actionId;
19 + }
20 +
21 + return null;
22 +}
23 +
24 +export function createGitHubPlugin({ github, menu } = {}) {
25 + if (!github) throw new Error('GitHub plugin requires github service');
26 + if (!menu) throw new Error('GitHub plugin requires menu manager');
27 +
28 + return {
29 + manifest: githubPluginManifest,
30 +
31 + resolveCommand(command) {
32 + if (command !== '/repos') return null;
33 + return {
34 + actionId: 'github.repos.list',
35 + execute: () => menu.getReposListView()
36 + };
37 + },
38 +
39 + resolveCallback(data) {
40 + const actionId = resolveCallbackAction(data);
41 + if (!actionId) return null;
42 +
43 + return {
44 + actionId,
45 + execute: () => menu.renderByCallback(data)
46 + };
47 + }
48 + };
49 +}
test/action-policy.test.js new
+39
@@ -0,0 +1,39 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { ActionPolicy } from '../src/core/action-policy.js';
4 +
5 +const action = risk => ({ pluginId: 'x', actionId: `x.${risk.toLowerCase()}`, risk });
6 +
7 +test('ActionPolicy allows owner READ without approval', () => {
8 + const policy = new ActionPolicy();
9 + assert.deepEqual(policy.evaluate({ action: action('READ'), isOwner: true }), {
10 + allowed: true,
11 + requiresApproval: false,
12 + risk: 'READ',
13 + reason: 'owner_read_allowed'
14 + });
15 +});
16 +
17 +test('ActionPolicy requires approval for WRITE and DESTRUCTIVE actions', () => {
18 + const policy = new ActionPolicy();
19 + for (const risk of ['WRITE', 'DESTRUCTIVE']) {
20 + assert.deepEqual(policy.evaluate({ action: action(risk), isOwner: true }), {
21 + allowed: false,
22 + requiresApproval: true,
23 + risk,
24 + reason: risk === 'WRITE' ? 'owner_write_requires_approval' : 'owner_destructive_requires_approval'
25 + });
26 + }
27 +});
28 +
29 +test('ActionPolicy denies non-owner, missing and unknown actions', () => {
30 + const policy = new ActionPolicy();
31 + assert.deepEqual(policy.evaluate({ action: action('READ'), isOwner: false }), {
32 + allowed: false,
33 + requiresApproval: false,
34 + risk: 'READ',
35 + reason: 'owner_required'
36 + });
37 + assert.equal(policy.evaluate({ action: null, isOwner: true }).allowed, false);
38 + assert.equal(policy.evaluate({ action: { risk: 'UNKNOWN' }, isOwner: true }).allowed, false);
39 +});
test/audit.test.js new
+39
@@ -0,0 +1,39 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { AuditLogger } from '../src/core/audit.js';
4 +
5 +test('AuditLogger redacts configured secrets recursively', () => {
6 + const events = [];
7 + const logger = new AuditLogger({
8 + secrets: ['bot-secret', 'github-secret'],
9 + sink: event => events.push(event)
10 + });
11 +
12 + logger.log({
13 + event: 'action_error',
14 + message: 'token bot-secret failed',
15 + nested: {
16 + detail: 'github-secret present',
17 + values: ['safe', 'bot-secret']
18 + }
19 + });
20 +
21 + assert.deepEqual(events, [{
22 + event: 'action_error',
23 + message: 'token [REDACTED] failed',
24 + nested: {
25 + detail: '[REDACTED] present',
26 + values: ['safe', '[REDACTED]']
27 + }
28 + }]);
29 +});
30 +
31 +test('AuditLogger sink failures never escape to the caller', () => {
32 + const logger = new AuditLogger({
33 + sink: () => {
34 + throw new Error('log sink failed');
35 + }
36 + });
37 +
38 + assert.doesNotThrow(() => logger.log({ event: 'action_attempt' }));
39 +});
test/bot.test.js
+72
@@ -65,6 +65,40 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
65 assert.ok(sentMessages[0].replyMarkup.inline_keyboard);
66 });
67
68 + it('/repos is dispatched through the plugin router', async () => {
69 + const sentMessages = [];
70 + const bot = makeBot();
71 + const routedView = {
72 + text: 'routed repositories',
73 + reply_markup: { inline_keyboard: [] }
74 + };
75 + let dispatchCount = 0;
76 +
77 + bot.menu.getReposListView = async () => {
78 + throw new Error('direct repository path must not be used');
79 + };
80 + bot.router.dispatchCommand = async (command, context) => {
81 + dispatchCount += 1;
82 + assert.equal(command, '/repos');
83 + assert.equal(context.isOwner, true);
84 + return routedView;
85 + };
86 + bot.telegram.sendMessage = async (chatId, text, replyMarkup) => {
87 + sentMessages.push({ chatId, text, replyMarkup });
88 + return { ok: true };
89 + };
90 +
91 + const res = await bot.handleUpdate({
92 + message: { message_id: 101, chat: { id: 123456 }, text: '/repos' }
93 + });
94 +
95 + assert.equal(res.ok, true);
96 + assert.equal(res.command, 'repos');
97 + assert.equal(dispatchCount, 1);
98 + assert.equal(sentMessages.length, 1);
99 + assert.equal(sentMessages[0].text, 'routed repositories');
100 + });
101 +
102 it('callback answers Telegram and edits the existing message in place', async () => {
103 const answeredCallbacks = [];
104 const editedMessages = [];
@@ -101,6 +135,44 @@ describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
135 assert.match(editedMessages[0].text, /فهرست مخزن‌ها/);
136 });
137
138 + it('github callbacks are dispatched through the plugin router before editing', async () => {
139 + const bot = makeBot();
140 + const edits = [];
141 + let dispatchCount = 0;
142 +
143 + bot.telegram.answerCallbackQuery = async () => ({ ok: true });
144 + bot.menu.renderByCallback = async () => {
145 + throw new Error('direct github callback path must not be used');
146 + };
147 + bot.router.dispatchCallback = async (data, context) => {
148 + dispatchCount += 1;
149 + assert.equal(data, 'repo:Factor-easy');
150 + assert.equal(context.isOwner, true);
151 + return {
152 + text: 'routed project',
153 + reply_markup: { inline_keyboard: [] }
154 + };
155 + };
156 + bot.telegram.editMessageText = async (chatId, messageId, text, replyMarkup) => {
157 + edits.push({ chatId, messageId, text, replyMarkup });
158 + return { ok: true };
159 + };
160 +
161 + const res = await bot.handleUpdate({
162 + callback_query: {
163 + id: 'cb_route',
164 + data: 'repo:Factor-easy',
165 + message: { message_id: 501, chat: { id: 123456 } }
166 + }
167 + });
168 +
169 + assert.equal(res.ok, true);
170 + assert.equal(res.edited, true);
171 + assert.equal(dispatchCount, 1);
172 + assert.equal(edits.length, 1);
173 + assert.equal(edits[0].text, 'routed project');
174 + });
175 +
176 it('callback navigation still edits when answerCallbackQuery fails', async () => {
177 const editedMessages = [];
178 const bot = makeBot();
test/github-plugin.test.js new
+90
@@ -0,0 +1,90 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { PluginRegistry } from '../src/core/plugin-registry.js';
4 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5 +
6 +function makeMenu() {
7 + const calls = [];
8 + const reposView = { text: 'repos', reply_markup: { inline_keyboard: [] } };
9 + return {
10 + calls,
11 + reposView,
12 + async getReposListView() {
13 + calls.push('/repos');
14 + return reposView;
15 + },
16 + async renderByCallback(data) {
17 + calls.push(data);
18 + return { text: data, reply_markup: { inline_keyboard: [] } };
19 + }
20 + };
21 +}
22 +
23 +test('GitHub plugin manifest registers all Foundation v1 actions as READ', () => {
24 + const menu = makeMenu();
25 + const plugin = createGitHubPlugin({ github: {}, menu });
26 + const registry = new PluginRegistry([plugin]);
27 +
28 + const expected = [
29 + 'github.repos.list',
30 + 'github.repo.detail',
31 + 'github.files.list',
32 + 'github.tree.read',
33 + 'github.blob.read',
34 + 'github.pr.list',
35 + 'github.commits.list',
36 + 'github.status.read'
37 + ];
38 +
39 + for (const actionId of expected) {
40 + assert.equal(registry.getAction(actionId)?.risk, 'READ');
41 + }
42 +});
43 +
44 +test('GitHub plugin resolves /repos without executing the menu before policy', async () => {
45 + const menu = makeMenu();
46 + const plugin = createGitHubPlugin({ github: {}, menu });
47 +
48 + const route = plugin.resolveCommand('/repos');
49 +
50 + assert.equal(route.actionId, 'github.repos.list');
51 + assert.deepEqual(menu.calls, []);
52 + assert.equal(await route.execute(), menu.reposView);
53 + assert.deepEqual(menu.calls, ['/repos']);
54 + assert.equal(plugin.resolveCommand('/status'), null);
55 +});
56 +
57 +test('GitHub plugin maps existing GitHub callback families to declared actions', async () => {
58 + const menu = makeMenu();
59 + const plugin = createGitHubPlugin({ github: {}, menu });
60 + const cases = [
61 + ['menu:repos', 'github.repos.list'],
62 + ['repo:123', 'github.repo.detail'],
63 + ['files:123', 'github.files.list'],
64 + ['tree:123:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'github.tree.read'],
65 + ['blob:123:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'github.blob.read'],
66 + ['pr:123', 'github.pr.list'],
67 + ['commits:123', 'github.commits.list'],
68 + ['status:123', 'github.status.read']
69 + ];
70 +
71 + for (const [callbackData, actionId] of cases) {
72 + const route = plugin.resolveCallback(callbackData);
73 + assert.equal(route.actionId, actionId);
74 + const before = menu.calls.length;
75 + const view = await route.execute();
76 + assert.equal(menu.calls.length, before + 1);
77 + assert.equal(menu.calls.at(-1), callbackData);
78 + assert.equal(view.text, callbackData);
79 + }
80 +});
81 +
82 +test('GitHub plugin does not consume unrelated commands or callbacks', () => {
83 + const plugin = createGitHubPlugin({ github: {}, menu: makeMenu() });
84 +
85 + assert.equal(plugin.resolveCommand('/start'), null);
86 + assert.equal(plugin.resolveCallback('menu:main'), null);
87 + assert.equal(plugin.resolveCallback('menu:status'), null);
88 + assert.equal(plugin.resolveCallback('menu:tools'), null);
89 + assert.equal(plugin.resolveCallback('tool:ping'), null);
90 +});
test/plugin-registry.test.js new
+49
@@ -0,0 +1,49 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { PluginRegistry } from '../src/core/plugin-registry.js';
4 +
5 +const plugin = (id, actions = {}) => ({
6 + manifest: { id, name: id, version: 1, actions }
7 +});
8 +
9 +test('PluginRegistry registers valid plugins and exposes lookups', () => {
10 + const github = plugin('github', {
11 + 'github.repos.list': { risk: 'READ' }
12 + });
13 +
14 + const registry = new PluginRegistry([github]);
15 +
16 + assert.deepEqual(registry.getPlugins(), [github]);
17 + assert.equal(registry.getPlugin('github'), github);
18 + assert.deepEqual(registry.getAction('github.repos.list'), {
19 + pluginId: 'github',
20 + actionId: 'github.repos.list',
21 + risk: 'READ'
22 + });
23 +});
24 +
25 +test('PluginRegistry rejects duplicate plugin ids', () => {
26 + assert.throws(
27 + () => new PluginRegistry([plugin('github'), plugin('github')]),
28 + /duplicate plugin id/i
29 + );
30 +});
31 +
32 +test('PluginRegistry rejects duplicate action ids across plugins', () => {
33 + assert.throws(
34 + () => new PluginRegistry([
35 + plugin('github', { 'shared.read': { risk: 'READ' } }),
36 + plugin('cloudflare', { 'shared.read': { risk: 'READ' } })
37 + ]),
38 + /duplicate action id/i
39 + );
40 +});
41 +
42 +test('PluginRegistry rejects unknown action risk levels', () => {
43 + assert.throws(
44 + () => new PluginRegistry([
45 + plugin('github', { 'github.repos.list': { risk: 'SUPERUSER' } })
46 + ]),
47 + /invalid action risk/i
48 + );
49 +});
test/plugin-router.test.js new
+162
@@ -0,0 +1,162 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { PluginRegistry } from '../src/core/plugin-registry.js';
4 +import { ActionPolicy } from '../src/core/action-policy.js';
5 +import { PluginRouter } from '../src/core/router.js';
6 +
7 +function auditCollector() {
8 + const events = [];
9 + return { events, logger: { log: event => events.push(event) } };
10 +}
11 +
12 +test('PluginRouter dispatches the first matching READ command after policy evaluation', async () => {
13 + let executed = 0;
14 + const first = {
15 + manifest: { id: 'first', actions: {} },
16 + resolveCommand: () => null
17 + };
18 + const second = {
19 + manifest: {
20 + id: 'second',
21 + actions: { 'second.read': { risk: 'READ' } }
22 + },
23 + resolveCommand: command => command === '/go'
24 + ? {
25 + actionId: 'second.read',
26 + execute: async () => {
27 + executed += 1;
28 + return { view: 'ok' };
29 + }
30 + }
31 + : null
32 + };
33 + const third = {
34 + manifest: {
35 + id: 'third',
36 + actions: { 'third.read': { risk: 'READ' } }
37 + },
38 + resolveCommand: () => ({
39 + actionId: 'third.read',
40 + execute: async () => {
41 + throw new Error('must not run');
42 + }
43 + })
44 + };
45 + const audit = auditCollector();
46 + const router = new PluginRouter({
47 + registry: new PluginRegistry([first, second, third]),
48 + policy: new ActionPolicy(),
49 + audit: audit.logger
50 + });
51 +
52 + const result = await router.dispatchCommand('/go', { isOwner: true });
53 +
54 + assert.deepEqual(result, { view: 'ok' });
55 + assert.equal(executed, 1);
56 + assert.equal(audit.events[0].event, 'action_attempt');
57 + assert.equal(audit.events[0].outcome, 'allowed');
58 + assert.equal(audit.events[1].event, 'action_result');
59 + assert.equal(audit.events[1].outcome, 'success');
60 +});
61 +
62 +test('PluginRouter dispatches callbacks through the same policy boundary', async () => {
63 + let executed = 0;
64 + const plugin = {
65 + manifest: {
66 + id: 'sample',
67 + actions: { 'sample.callback.read': { risk: 'READ' } }
68 + },
69 + resolveCallback: data => data === 'sample:1'
70 + ? {
71 + actionId: 'sample.callback.read',
72 + execute: async () => {
73 + executed += 1;
74 + return { callback: 'ok' };
75 + }
76 + }
77 + : null
78 + };
79 + const router = new PluginRouter({
80 + registry: new PluginRegistry([plugin]),
81 + policy: new ActionPolicy(),
82 + audit: { log() {} }
83 + });
84 +
85 + assert.deepEqual(
86 + await router.dispatchCallback('sample:1', { isOwner: true }),
87 + { callback: 'ok' }
88 + );
89 + assert.equal(executed, 1);
90 +});
91 +
92 +test('PluginRouter returns null when no plugin owns the route', async () => {
93 + const plugin = {
94 + manifest: { id: 'sample', actions: {} },
95 + resolveCommand: () => null,
96 + resolveCallback: () => null
97 + };
98 + const router = new PluginRouter({
99 + registry: new PluginRegistry([plugin]),
100 + policy: new ActionPolicy(),
101 + audit: { log() {} }
102 + });
103 +
104 + assert.equal(await router.dispatchCommand('/unknown', { isOwner: true }), null);
105 + assert.equal(await router.dispatchCallback('unknown', { isOwner: true }), null);
106 +});
107 +
108 +test('PluginRouter denies undeclared actions without executing plugin code', async () => {
109 + let executed = 0;
110 + const plugin = {
111 + manifest: { id: 'sample', actions: {} },
112 + resolveCommand: () => ({
113 + actionId: 'sample.missing',
114 + execute: async () => {
115 + executed += 1;
116 + }
117 + })
118 + };
119 + const router = new PluginRouter({
120 + registry: new PluginRegistry([plugin]),
121 + policy: new ActionPolicy(),
122 + audit: { log() {} }
123 + });
124 +
125 + const result = await router.dispatchCommand('/go', { isOwner: true });
126 +
127 + assert.equal(result.denied, true);
128 + assert.equal(result.requiresApproval, false);
129 + assert.equal(result.reason, 'unknown_action');
130 + assert.equal(executed, 0);
131 +});
132 +
133 +test('PluginRouter never executes WRITE or DESTRUCTIVE actions before approval', async () => {
134 + for (const risk of ['WRITE', 'DESTRUCTIVE']) {
135 + let executed = 0;
136 + const actionId = `sample.${risk.toLowerCase()}`;
137 + const plugin = {
138 + manifest: {
139 + id: 'sample',
140 + actions: { [actionId]: { risk } }
141 + },
142 + resolveCommand: () => ({
143 + actionId,
144 + execute: async () => {
145 + executed += 1;
146 + }
147 + })
148 + };
149 + const router = new PluginRouter({
150 + registry: new PluginRegistry([plugin]),
151 + policy: new ActionPolicy(),
152 + audit: { log() {} }
153 + });
154 +
155 + const result = await router.dispatchCommand('/danger', { isOwner: true });
156 +
157 + assert.equal(result.requiresApproval, true);
158 + assert.equal(result.denied, false);
159 + assert.equal(result.risk, risk);
160 + assert.equal(executed, 0);
161 + }
162 +});