Personal Telegram developer console for GitHub
docs: control plane completion design and CP2-CP7 plans (#42)
* docs: design control plane completion phases 2-7 * docs: add 2026-10-05-cp2-multifile-workspace implementation plan * docs: add 2026-10-05-cp3-github-write implementation plan * docs: add 2026-10-05-cp4-cloudflare-ops implementation plan * docs: add 2026-10-05-cp5-cicd-control-plane implementation plan * docs: add 2026-10-05-cp6-incident-manager implementation plan * docs: add 2026-10-05-cp7-automation-engine implementation plan * test(workspace): define multi-file policy contract * feat(workspace): add bounded multi-file policy and aggregate diff
davoodmehraban89 committed
Oct 5, 2026 at 05:48 UTC
d339f7f08ad99a414c5ad433c0182506375e25b8
9 files changed
+541
-1
docs/superpowers/plans/2026-10-05-cp2-multifile-workspace.md
new
+96
@@ -0,0 +1,96 @@
1
+# CP2 Multi-file Repository Workspace Implementation Plan
2
+
3
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+**Goal:** Extend the existing branch-only Workspace to atomically edit a bounded set of text files.
6
+
7
+**Architecture:** Version the durable Workspace schema, represent files as an ordered bounded collection, seal immutable multi-file Ready intents, and reuse the existing Git Data commit path to create one tree/commit on `nexa/edit-*`. Preserve single-file compatibility and fail closed on stale base/material.
8
+
9
+**Tech Stack:** Node.js ESM, Cloudflare Workers/Durable Objects, Telegram Bot API, GitHub Git Data API, node:test.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
12
+
13
+## Global Constraints
14
+- Never mutate `main` directly.
15
+- Owner-only; WRITE requires Safe Approval and durable replay protection.
16
+- Per-file existing text/binary/sensitive/LFS policy remains authoritative.
17
+- Callback data <=64 UTF-8 bytes; Telegram text <=4096 chars.
18
+- No draft/source content in audit metadata.
19
+
20
+## Review Focus
21
+- Existing single-file records migrate/read without corruption.
22
+- Duplicate/renamed paths cannot create ambiguous tree entries.
23
+- Aggregate payload limit fails explicitly before persistence.
24
+- Base SHA changes invalidate sealed intent.
25
+- Retry after provider partial failure is idempotent.
26
+
27
+---
28
+
29
+### Task 1: Versioned multi-file Workspace model
30
+**Files:**
31
+- Modify: `src/durable/workspace-store.js`
32
+- Modify: `src/core/workspace-store.js`
33
+- Test: `test/workspace-store.test.js`
34
+- Test: `test/workspace-store-file-input.test.js`
35
+
36
+**Interfaces:**
37
+- Consumes: existing owner-scoped workspace ID and single-file records.
38
+- Produces: `files[]` records with path/baseSha/baseText/draftText and schemaVersion.
39
+
40
+- [ ] Write failing tests for legacy-read migration, add/update/remove file, duplicate path rejection and aggregate bound.
41
+- [ ] Run targeted tests and confirm RED.
42
+- [ ] Implement minimal versioned storage and migration.
43
+- [ ] Run targeted tests and confirm GREEN.
44
+- [ ] Commit.
45
+
46
+### Task 2: Multi-file policy, diff and immutable Ready intent
47
+**Files:**
48
+- Modify: `src/core/workspace-policy.js`
49
+- Modify: `src/plugins/github/workspace.js`
50
+- Test: `test/workspace-policy.test.js`
51
+- Test: `test/workspace-editor-v2.test.js`
52
+
53
+**Interfaces:**
54
+- Consumes: versioned workspace files.
55
+- Produces: aggregate diff summary and immutable intent containing ordered file descriptors.
56
+
57
+- [ ] Add RED tests for per-file policy, aggregate diff, unchanged workspace, stale material/base and intent reuse.
58
+- [ ] Implement bounded aggregate validation/diff and intent sealing.
59
+- [ ] Run targeted tests GREEN and commit.
60
+
61
+### Task 3: Atomic multi-file Git tree commit
62
+**Files:**
63
+- Modify: `src/plugins/github/workspace-commit.js`
64
+- Modify: `src/github.js`
65
+- Test: `test/workspace-approved-recovery.test.js`
66
+- Test: `test/workspace-recovery-validation.test.js`
67
+
68
+**Interfaces:**
69
+- Consumes: approved immutable multi-file intent.
70
+- Produces: exactly one branch commit/tree on `nexa/edit-<workspaceId>`.
71
+
72
+- [ ] Add RED tests for one atomic tree, stale base rejection, partial-failure retry and reconciliation.
73
+- [ ] Implement minimal multi-blob/tree orchestration reusing current Git Data primitives.
74
+- [ ] Run targeted tests GREEN and commit.
75
+
76
+### Task 4: Telegram/Mini App multi-file UX and recovery
77
+**Files:**
78
+- Modify: `src/workspace-editor.js`
79
+- Modify: `src/plugins/github/plugin.js`
80
+- Modify: `src/bot.js`
81
+- Test: `test/telegram-menu-e2e.test.js`
82
+- Test: `test/workspace-editor-worker.test.js`
83
+
84
+**Interfaces:**
85
+- Consumes: workspace file collection and aggregate diff.
86
+- Produces: bounded add/select/remove/diff/ready/recovery views.
87
+
88
+- [ ] Add RED navigation/callback-limit/recovery tests.
89
+- [ ] Implement views without embedding raw long paths in callback data.
90
+- [ ] Run targeted tests GREEN and commit.
91
+
92
+### Task 5: CP2 release gate
93
+- [ ] Run full `npm test`; expect zero failures/skips caused by CP2.
94
+- [ ] Review diff for direct-main mutation, sensitive logging and callback overflow.
95
+- [ ] Update README/Guide/PROJECT_MEMORY for multi-file behavior.
96
+- [ ] PR, CI, Preview, locked-head merge, post-merge CI, exact-SHA deploy and production smoke.
docs/superpowers/plans/2026-10-05-cp3-github-write.md
new
+53
@@ -0,0 +1,53 @@
1
+# CP3 GitHub Advanced WRITE Completion Implementation Plan
2
+
3
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+**Goal:** Complete high-value GitHub WRITE controls without weakening Safe Approval.
6
+
7
+**Architecture:** Extend the existing GitHub provider/plugin with workflow dispatch and job rerun only where supported. Every mutation is declared in the manifest, centrally policy-checked, target-bound in approval input, replay-safe and provider-error explicit.
8
+
9
+**Tech Stack:** Node.js ESM, GitHub REST API, Telegram, Durable replay guard, node:test.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
12
+
13
+## Global Constraints
14
+- No provider mutation before approval.
15
+- Keep existing rerun-failed, cancel and exact-head PR merge semantics unchanged.
16
+- WRITE/DESTRUCTIVE risk comes from manifest/policy, never hard-coded UI assumptions.
17
+- Callback <=64 UTF-8 bytes.
18
+
19
+## Review Focus
20
+- Unsupported workflow/job states never show misleading buttons.
21
+- Approval token binds immutable repo/action/target.
22
+- Replay/expiry/owner mismatch fails closed.
23
+- 403/404/409 provider errors remain visible.
24
+- Retried callbacks do not duplicate mutation.
25
+
26
+---
27
+
28
+### Task 1: Provider methods
29
+**Files:** `src/github.js`, `test/github-advanced-read.test.js`, new `test/github-advanced-write-completion.test.js`
30
+
31
+- [ ] RED tests for workflow dispatch and job rerun request method/path/body/validation.
32
+- [ ] Implement `dispatchWorkflow(repoRef, workflowId, {ref, inputs})` and `rerunJob(repoRef, jobId)`.
33
+- [ ] GREEN targeted tests and commit.
34
+
35
+### Task 2: Manifest, routes and eligibility
36
+**Files:** `src/plugins/github/manifest.js`, `src/plugins/github/plugin.js`, `test/telegram-menu-e2e.test.js`
37
+
38
+- [ ] RED tests for declared risk, eligible buttons, callback bounds and no provider call before policy.
39
+- [ ] Implement routes/views; classify mutation risk per spec.
40
+- [ ] GREEN and commit.
41
+
42
+### Task 3: Approval binding and execution
43
+**Files:** `src/core/approval.js`, `src/bot.js`, tests for approval/security.
44
+
45
+- [ ] RED tests for repo/action/target binding, replay, expiry and owner mismatch.
46
+- [ ] Extend compact codec only if callback budget requires it; preserve old codecs.
47
+- [ ] GREEN and commit.
48
+
49
+### Task 4: CP3 release gate
50
+- [ ] Full `npm test`.
51
+- [ ] Security/diff review.
52
+- [ ] Update docs/memory.
53
+- [ ] PR -> CI -> locked-head merge -> main CI -> deploy -> owner/runtime smoke.
docs/superpowers/plans/2026-10-05-cp4-cloudflare-ops.md
new
+52
@@ -0,0 +1,52 @@
1
+# CP4 Cloudflare Ops Completion 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:** Turn the Cloudflare READ foundation into a safe operational plugin with verified rollback/redeploy.
6
+
7
+**Architecture:** Keep Cloudflare API mechanics in the existing service, expose source-backed bounded views in the plugin, and route rollback/redeploy through central DESTRUCTIVE approval bound to an exact known version/deployment. Secret values are never read into UI/audit.
8
+
9
+**Tech Stack:** Cloudflare Workers REST API, Node.js ESM, Telegram, Safe Approval, node:test.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
12
+
13
+## Global Constraints
14
+- Production/Preview must be visibly distinguished.
15
+- Never expose secret values; bindings show name/type only.
16
+- Deployment-changing actions are DESTRUCTIVE.
17
+- Post-action verification must independently re-read active deployment/version.
18
+
19
+## Review Focus
20
+- Unknown version cannot be targeted.
21
+- Traffic split must be shown accurately rather than assumed 100%.
22
+- Provider API failure cannot produce success text.
23
+- Preview state never verifies Production.
24
+- Runtime error summaries redact query/token/source material.
25
+
26
+---
27
+
28
+### Task 1: Complete Cloudflare READ service
29
+**Files:** `src/plugins/cloudflare/service.js`, tests under `test/cloudflare*.test.js`
30
+
31
+- [ ] RED tests for deployments, versions, binding metadata, observability and bounded runtime error summaries.
32
+- [ ] Implement only documented API reads and redaction.
33
+- [ ] GREEN and commit.
34
+
35
+### Task 2: Ops views and navigation
36
+**Files:** `src/plugins/cloudflare/plugin.js`, `src/plugins/cloudflare/manifest.js`, `src/cloudflare-menu.js`, `src/ops-menu.js`
37
+
38
+- [ ] RED source-backed/recovery/callback-limit tests.
39
+- [ ] Implement deployments/versions/bindings/health/errors drill-down.
40
+- [ ] GREEN and commit.
41
+
42
+### Task 3: Exact-target rollback/redeploy approval
43
+**Files:** service/plugin/manifest, `src/core/approval.js`, `src/bot.js`
44
+
45
+- [ ] RED tests for DESTRUCTIVE classification, exact version binding, stale/unknown version, replay and no pre-approval mutation.
46
+- [ ] Implement provider deployment mutation and approval route.
47
+- [ ] GREEN and commit.
48
+
49
+### Task 4: Independent verification
50
+- [ ] RED/GREEN tests requiring post-mutation re-read to match target version/traffic.
51
+- [ ] Full `npm test`, docs, PR, CI, merge, deploy.
52
+- [ ] Verify active version/deployment/bindings directly through Cloudflare API.
docs/superpowers/plans/2026-10-05-cp5-cicd-control-plane.md
new
+49
@@ -0,0 +1,49 @@
1
+# CP5 CI/CD Control Plane 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:** Correlate exact-commit GitHub CI/deploy evidence with active Cloudflare runtime state in one owner-only control plane.
6
+
7
+**Architecture:** Add a pure correlation layer that consumes existing GitHub and Cloudflare adapters and emits explicit pending/failed/success/mismatch states. UI actions delegate to CP3/CP4 routes; the correlator never mutates providers.
8
+
9
+**Tech Stack:** Node.js ESM, GitHub Actions API, Cloudflare service, Telegram, node:test.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
12
+
13
+## Global Constraints
14
+- Exact SHA correlation is mandatory.
15
+- A green CI run alone is not deployment success.
16
+- No invented timing/SLA.
17
+- Correlator is READ-only.
18
+
19
+## Review Focus
20
+- CI success + wrong active version => mismatch.
21
+- Deploy pending => pending, not success.
22
+- Multiple deployments/traffic splits are represented.
23
+- Missing provider evidence is unknown, not failure/success.
24
+- Stale workflow runs are not mistaken for current SHA.
25
+
26
+---
27
+
28
+### Task 1: Correlation model
29
+**Files:** create `src/core/cicd-control-plane.js`, create `test/cicd-control-plane.test.js`
30
+
31
+- [ ] RED table tests for pending/failed/success/mismatch/unknown.
32
+- [ ] Implement pure `correlateDeliveryState(input)`.
33
+- [ ] GREEN and commit.
34
+
35
+### Task 2: Provider aggregation
36
+**Files:** `src/ops-menu.js`, GitHub/Cloudflare plugins as needed, new integration test.
37
+
38
+- [ ] RED tests for exact-SHA reads and no mutation.
39
+- [ ] Implement owner-only aggregate loader.
40
+- [ ] GREEN and commit.
41
+
42
+### Task 3: Telegram view
43
+- [ ] RED tests for drill-down, recovery and callback limits.
44
+- [ ] Implement state view with links/actions delegating to CP3/CP4.
45
+- [ ] GREEN and commit.
46
+
47
+### Task 4: CP5 release gate
48
+- [ ] Full test, diff review, docs/memory.
49
+- [ ] PR/CI/merge/deploy and production evidence showing exact SHA correlation.
docs/superpowers/plans/2026-10-05-cp6-incident-manager.md
new
+53
@@ -0,0 +1,53 @@
1
+# CP6 Monitoring & Incident Manager 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:** Persist, deduplicate and resolve source-backed operational incidents without leaking sensitive data.
6
+
7
+**Architecture:** Add a dedicated Durable Object incident store, a pure fingerprint/redaction layer, and an owner-only incident plugin/view fed by CP5/Cloudflare/GitHub failure evidence. Remediation links delegate to existing approved actions.
8
+
9
+**Tech Stack:** Cloudflare Durable Objects, Node.js ESM, Telegram, node:test.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
12
+
13
+## Global Constraints
14
+- Dedicated binding/class; never reuse approval/workspace storage.
15
+- Persist only redacted summaries and stable evidence references.
16
+- No automatic mutation during incident creation.
17
+- Public status remains minimal.
18
+
19
+## Review Focus
20
+- Duplicate event updates existing incident.
21
+- Different repo/SHA/provider failures do not collide.
22
+- Token/source/query material is redacted.
23
+- Provider outage is representable without fake root cause.
24
+- Resolve/reopen transitions are deterministic.
25
+
26
+---
27
+
28
+### Task 1: Incident domain and redaction
29
+**Files:** create `src/core/incidents.js`, create `test/incidents.test.js`
30
+
31
+- [ ] RED tests for fingerprint, severity, redact, dedupe semantics.
32
+- [ ] Implement pure domain helpers.
33
+- [ ] GREEN and commit.
34
+
35
+### Task 2: Durable incident store
36
+**Files:** create `src/durable/incident-store.js`, create `src/core/incident-store.js`, modify `src/index.js`/Wrangler config, tests.
37
+
38
+- [ ] RED CRUD/dedupe/resolve/reopen/owner-scope tests.
39
+- [ ] Implement versioned DO API.
40
+- [ ] GREEN and commit.
41
+
42
+### Task 3: Evidence ingestion and Telegram UI
43
+**Files:** `src/ops-menu.js`, plugin registry/menu files, integration tests.
44
+
45
+- [ ] RED tests for failed CI/deploy/runtime evidence ingestion and recovery.
46
+- [ ] Implement owner-only list/detail/resolve views; remediation delegates to CP3/CP4.
47
+- [ ] GREEN and commit.
48
+
49
+### Task 4: CP6 release gate
50
+- [ ] Full test and migration/binding review.
51
+- [ ] Docs/memory.
52
+- [ ] PR/CI/Preview DO isolation/merge/deploy.
53
+- [ ] Production verification of binding and dedupe behavior with non-destructive evidence.
docs/superpowers/plans/2026-10-05-cp7-automation-engine.md
new
+61
@@ -0,0 +1,61 @@
1
+# CP7 Automation Engine 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:** Add durable resumable developer workflows that pause safely at WRITE/DESTRUCTIVE steps.
6
+
7
+**Architecture:** Use a dedicated Durable Object store for versioned workflow state machines. READ steps execute through existing adapters; mutation steps emit approval intents and pause. Resume validates the matching one-time approval and idempotency key before execution. Initial recipes compose existing CP3–CP6 capabilities only.
8
+
9
+**Tech Stack:** Cloudflare Durable Objects, Node.js ESM, existing Plugin/Policy/Approval layer, Telegram, node:test.
10
+
11
+**Spec:** docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
12
+
13
+## Global Constraints
14
+- No new provider bypass path.
15
+- Every mutation remains centrally policy checked and approval bound.
16
+- Durable checkpoints before/after side effects.
17
+- Idempotency prevents duplicate provider mutations.
18
+- Cancellation/terminal failure are explicit and recoverable.
19
+
20
+## Review Focus
21
+- Worker restart between steps resumes correctly.
22
+- Approval replay cannot advance workflow twice.
23
+- Crash after provider success before checkpoint reconciles safely.
24
+- Cancelled workflow never resumes mutation.
25
+- Versioned recipe/state migration fails explicitly when unsupported.
26
+
27
+---
28
+
29
+### Task 1: State machine core
30
+**Files:** create `src/core/automation.js`, create `test/automation.test.js`
31
+
32
+- [ ] RED tests for step transitions, pause, resume, cancel, fail and idempotency.
33
+- [ ] Implement pure state transition engine.
34
+- [ ] GREEN and commit.
35
+
36
+### Task 2: Durable automation store
37
+**Files:** create `src/durable/automation-store.js`, create `src/core/automation-store.js`, modify Worker exports/config, tests.
38
+
39
+- [ ] RED persistence/resume/version/owner-scope tests.
40
+- [ ] Implement versioned DO API.
41
+- [ ] GREEN and commit.
42
+
43
+### Task 3: Policy-aware executor
44
+**Files:** create `src/core/automation-runner.js`, modify `src/bot.js`/router, tests.
45
+
46
+- [ ] RED tests: READ auto-run; WRITE/DESTRUCTIVE pause; exact matching approval resumes; replay/expiry/cancel fail closed.
47
+- [ ] Implement runner using existing plugin actions and approval service.
48
+- [ ] GREEN and commit.
49
+
50
+### Task 4: Initial bounded recipes and UI
51
+**Files:** create `src/plugins/automation/manifest.js`, `src/plugins/automation/plugin.js`, menu/registry/guide, tests.
52
+
53
+- [ ] RED tests for recipe: diagnose failed CI -> propose existing recovery action -> approval -> execute -> verify; plus cancellation/retry.
54
+- [ ] Implement only recipes composed of existing capabilities.
55
+- [ ] GREEN and commit.
56
+
57
+### Task 5: CP7 release gate
58
+- [ ] Full `npm test`; whole-branch security review.
59
+- [ ] Docs/Guide/PROJECT_MEMORY.
60
+- [ ] PR/CI/Preview binding verification/locked-head merge/main CI/deploy.
61
+- [ ] Production smoke proving durable resume and approval pause without destructive test mutation.
docs/superpowers/specs/2026-10-05-control-plane-completion-design.md
new
+56
@@ -0,0 +1,56 @@
1
+# Nexa Dev Bot — Control Plane Completion Design (Roadmap 2–7)
2
+
3
+## Intent
4
+Complete the next six roadmap capabilities without weakening the existing owner-only, Safe Approval, durable replay, branch-only Workspace, public `/status`, or Production/Preview isolation boundaries.
5
+
6
+## Delivery decomposition
7
+This architectural program is delivered as six independently reviewable subprojects in dependency order. Each subproject must ship working, tested software before the next relies on it.
8
+
9
+### CP2 — Multi-file Repository Workspace
10
+Extend the existing durable Workspace from one editable file to a bounded set of text files. A Workspace records repository/base SHA plus per-file base SHA, path and draft material. Diff and Ready intent cover the complete immutable file set. Commit remains a single atomic Git tree/commit on a `nexa/edit-*` branch; `main` is never directly mutated. Any base/material change invalidates Ready intent. Sensitive/binary/LFS/oversize policies apply per file and to an aggregate bounded payload.
11
+
12
+Acceptance: add/remove/replace draft files, aggregate diff, immutable Ready intent, stale-base rejection, one Safe Approval, one atomic branch commit, idempotent retry/reconciliation, recovery UI, and regression coverage proving no direct-main write.
13
+
14
+### CP3 — GitHub Advanced WRITE completion
15
+Keep GitHub mutation behind the central action policy. Add only high-value Actions controls not already present: workflow dispatch and job rerun where the provider supports them. Existing rerun-failed, cancel and exact-head PR merge remain unchanged. Approval targets bind repository + immutable operation target; provider permission failures are explicit and never reported as success.
16
+
17
+Acceptance: source-backed eligibility, DESTRUCTIVE/WRITE classification as appropriate, compact approval callback under Telegram limits, durable replay rejection, provider mutation only after approval, and exact provider-error feedback.
18
+
19
+### CP4 — Cloudflare Ops Plugin completion
20
+Extend the existing Cloudflare READ foundation into a first-class plugin. READ surfaces current Worker deployments/versions, traffic, bindings by name/type only, observability state and recent safe runtime error summaries. Mutations are intentionally limited to redeploy/rollback to a known version; they require Safe Approval, exact target version/deployment binding and post-action runtime verification. Secret values are never returned or audited.
21
+
22
+Acceptance: Production/Preview distinction, source-backed READ, fail-closed mutation, rollback/redeploy approval, exact target verification, and independent post-action version/traffic/binding verification.
23
+
24
+### CP5 — CI/CD Control Plane
25
+Compose GitHub Actions and Cloudflare deployment state into one owner-only view. The view correlates repository, exact commit SHA, CI run/jobs, deploy workflow and active Cloudflare version. It diagnoses mismatches rather than declaring success from a single green run. Actions delegate to CP3/CP4 policy-protected operations rather than bypassing them.
26
+
27
+Acceptance: exact-SHA correlation, clear pending/failed/success/mismatch states, drill-down and recovery, no invented SLA/latency, and deploy acceptance only when GitHub and Cloudflare evidence agree.
28
+
29
+### CP6 — Monitoring & Incident Manager
30
+Create durable incident records only from source-backed failures: failed CI/deploy, Cloudflare runtime/provider failure, or explicit health degradation. Incidents have deterministic fingerprints for deduplication, severity, evidence references, status and investigation notes. Sensitive logs/source are redacted before persistence. Owner notifications are informative; remediation actions route through existing policy/approval paths.
31
+
32
+Acceptance: create/dedupe/update/resolve incidents, evidence redaction, provider-outage handling, recovery navigation and tests for repeated events and false-success prevention.
33
+
34
+### CP7 — Automation Engine
35
+Add a durable, resumable orchestration layer for bounded developer workflows. An automation is a versioned state machine with idempotency key, step status, attempts and durable checkpoints. READ steps may run automatically; WRITE/DESTRUCTIVE steps pause for Safe Approval and resume only with a matching one-time approval. Retries never duplicate provider mutation; terminal failure is explicit. Initial recipes are deliberately limited to existing capabilities (for example diagnose failed CI, prepare recovery action, wait for approval, execute, verify).
36
+
37
+Acceptance: durable resume after Worker restart, idempotent retry, approval pause/resume, cancellation, terminal failure, audit-safe event trail, and no direct Production bypass.
38
+
39
+## Shared architecture
40
+- Telegram remains the owner control surface; Mini App is used only where richer Workspace editing is needed.
41
+- Plugin manifests declare actions and risk; central policy remains authoritative.
42
+- `ApprovalReplayGuard` remains the one-time approval boundary and fails closed for mutations.
43
+- `WorkspaceStore` may be extended with versioned multi-file schema; migration must preserve existing single-file drafts or fail explicitly without data corruption.
44
+- Automation/incident durable state uses dedicated Durable Object classes/bindings rather than mixing unrelated state into approval replay.
45
+- Provider adapters contain API mechanics; orchestration never embeds secrets or bypasses adapters.
46
+- Public `GET /status` stays minimal health-only. Operational diagnostics remain owner-only in Telegram.
47
+- Production and Preview Durable Object namespaces remain isolated.
48
+
49
+## Security and risk
50
+All provider mutations must be target-bound, expiry-bound, owner-bound and replay-safe. Cloudflare rollback/redeploy and any operation changing deployed code are DESTRUCTIVE. GitHub workflow dispatch/rerun are WRITE unless the concrete action is later shown to have destructive semantics. Logs, source code bodies, drafts, tokens, signed approvals and secret values are excluded from incident/audit persistence.
51
+
52
+## Verification strategy
53
+Every subproject follows RED → GREEN → relevant tests → full `npm test` → diff/security review → PR CI → Preview where applicable → locked-head merge → post-merge main CI → exact-SHA deploy → independent Cloudflare runtime verification. A subproject is not complete on documentation or mocks alone.
54
+
55
+## Non-goals for this program
56
+AI Copilot, Browser QA as a new subsystem, broad third-party plugin marketplace and general multi-project tenancy remain later roadmap items. CP2–CP7 must leave extension points but must not implement those later phases opportunistically.
src/core/workspace-policy.js
+63
-1
@@ -1,11 +1,15 @@
1
const MAX_CHARS = 20000;
2
const MAX_BYTES = 65536;
3
const MAX_COMMIT_MESSAGE = 120;
4
+const MAX_WORKSPACE_FILES = 8;
5
+const MAX_WORKSPACE_BYTES = 131072;
6
const SAFE_HANDLE = /^[A-Za-z0-9_-]{10}$/;
7
8
export const WORKSPACE_EDITOR_LIMITS = Object.freeze({
9
maxChars: MAX_CHARS,
8
- maxBytes: MAX_BYTES
10
+ maxBytes: MAX_BYTES,
11
+ maxFiles: MAX_WORKSPACE_FILES,
12
+ maxAggregateBytes: MAX_WORKSPACE_BYTES
13
});
14
15
const encoder = new TextEncoder();
@@ -131,3 +135,61 @@ export function buildUnifiedDiff({ path, before, after, maxChars = 2600 } = {})
135
truncated: true
136
};
137
}
138
+
139
+
140
+export function validateWorkspaceFiles(files = []) {
141
+ if (!Array.isArray(files) || files.length === 0) throw new Error('Workspace files are required');
142
+ if (files.length > MAX_WORKSPACE_FILES) throw new Error(`Workspace is limited to ${MAX_WORKSPACE_FILES} files`);
143
+ const seen = new Set();
144
+ let totalBytes = 0;
145
+ const normalized = files.map(source => {
146
+ const path = String(source?.path || '').replaceAll('\\', '/');
147
+ if (!path) throw new Error('Workspace file path is required');
148
+ if (seen.has(path)) throw new Error(`Duplicate workspace path: ${path}`);
149
+ seen.add(path);
150
+ const original = validateEditableFile({ path, text: source?.originalText ?? '' });
151
+ if (!original.editable) throw new Error(original.reason);
152
+ const draft = validateEditableFile({ path, text: source?.draftText ?? source?.originalText ?? '' });
153
+ if (!draft.editable) throw new Error(draft.reason);
154
+ totalBytes += Math.max(original.byteLength, draft.byteLength);
155
+ return { ...source, path, originalText: original.text, draftText: draft.text };
156
+ });
157
+ if (totalBytes > MAX_WORKSPACE_BYTES) {
158
+ throw new Error('Workspace aggregate text is limited to 131,072 UTF-8 bytes');
159
+ }
160
+ return { valid: true, files: normalized, totalBytes };
161
+}
162
+
163
+export function buildWorkspaceDiff({ files = [], maxChars = 3000 } = {}) {
164
+ const validated = validateWorkspaceFiles(files);
165
+ const changed = [];
166
+ let additions = 0;
167
+ let deletions = 0;
168
+ for (const file of validated.files) {
169
+ if (file.originalText === file.draftText) continue;
170
+ const diff = buildUnifiedDiff({ path: file.path, before: file.originalText, after: file.draftText, maxChars: 10000 });
171
+ additions += diff.additions;
172
+ deletions += diff.deletions;
173
+ changed.push(diff.text);
174
+ }
175
+ const raw = changed.join('\n\n');
176
+ const limit = Math.max(32, Math.min(10000, Number(maxChars) || 3000));
177
+ const marker = '\n…';
178
+ const truncated = raw.length > limit;
179
+ const text = truncated ? `${raw.slice(0, Math.max(0, limit - marker.length))}${marker}` : raw;
180
+ return { text, additions, deletions, filesChanged: changed.length, truncated };
181
+}
182
+
183
+export async function digestWorkspaceFiles(files = []) {
184
+ const validated = validateWorkspaceFiles(files);
185
+ const canonical = validated.files
186
+ .map(file => ({
187
+ path: file.path,
188
+ blobSha: String(file.blobSha || ''),
189
+ originalDigest: String(file.originalDigest || ''),
190
+ draftText: file.draftText,
191
+ draftDigest: String(file.draftDigest || '')
192
+ }))
193
+ .sort((a, b) => a.path.localeCompare(b.path));
194
+ return digestText(JSON.stringify(canonical));
195
+}
test/workspace-multifile.test.js
new
+58
@@ -0,0 +1,58 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { validateWorkspaceFiles, buildWorkspaceDiff, digestWorkspaceFiles } from '../src/core/workspace-policy.js';
4
+
5
+const file = (path, originalText, draftText = originalText) => ({
6
+ path,
7
+ blobSha: 'a'.repeat(40),
8
+ originalText,
9
+ originalDigest: 'b'.repeat(64),
10
+ draftText,
11
+ draftDigest: 'c'.repeat(64)
12
+});
13
+
14
+test('multi-file workspace policy accepts a bounded unique file set', () => {
15
+ const result = validateWorkspaceFiles([
16
+ file('README.md', 'before\n', 'after\n'),
17
+ file('src/app.js', 'export const a = 1;\n', 'export const a = 2;\n')
18
+ ]);
19
+ assert.equal(result.valid, true);
20
+ assert.equal(result.files.length, 2);
21
+ assert.ok(result.totalBytes > 0);
22
+});
23
+
24
+test('multi-file workspace rejects duplicate and sensitive paths and aggregate overflow', () => {
25
+ assert.throws(() => validateWorkspaceFiles([file('a.txt', 'x'), file('a.txt', 'y')]), /duplicate/i);
26
+ assert.throws(() => validateWorkspaceFiles([file('.env', 'x')]), /sensitive/i);
27
+ assert.throws(() => validateWorkspaceFiles([
28
+ file('a.txt', 'a'.repeat(65536)),
29
+ file('b.txt', 'b'.repeat(65536)),
30
+ file('c.txt', 'c')
31
+ ]), /aggregate|131,072|131072/i);
32
+});
33
+
34
+test('aggregate diff preserves per-file identity and exact total counts', () => {
35
+ const diff = buildWorkspaceDiff({
36
+ files: [
37
+ file('a.txt', 'one\ntwo\n', 'one\nTWO\n'),
38
+ file('b.txt', 'x\n', 'x\ny\n')
39
+ ],
40
+ maxChars: 2600
41
+ });
42
+ assert.equal(diff.filesChanged, 2);
43
+ assert.equal(diff.additions, 3);
44
+ assert.equal(diff.deletions, 1);
45
+ assert.match(diff.text, /a\/a\.txt/);
46
+ assert.match(diff.text, /a\/b\.txt/);
47
+});
48
+
49
+test('workspace material digest is order-independent but changes with material', async () => {
50
+ const a = file('a.txt', 'x', 'y');
51
+ const b = file('b.txt', 'm', 'n');
52
+ const first = await digestWorkspaceFiles([a, b]);
53
+ const reordered = await digestWorkspaceFiles([b, a]);
54
+ const changed = await digestWorkspaceFiles([a, { ...b, draftText: 'changed' }]);
55
+ assert.match(first, /^[a-f0-9]{64}$/);
56
+ assert.equal(first, reordered);
57
+ assert.notEqual(first, changed);
58
+});