سامانه صدور فاکتور و حسابداری

Record C8 design approval and testable implementation plan

davoodmehraban89 committed Oct 1, 2026 at 09:59 UTC dad2ab14d27046dde5feeb1c24d59c7f8481ffda
3 files changed +111 -4
PROJECT_STATE.md
+11 -3
@@ -12,7 +12,8 @@ Verify live GitHub + Supabase before acting; implement/test/fix/retest/commit/ve
12 ## Current change ledger
13 | Date | Request / decision | Status | Evidence / next action |
14 |---|---|---|---|
15 -| 2026-10-01 | Owner explicitly replied «بله تاییده» to additive C8 workflow schema/stages/rules, immutable transition history and related RLS; no data deletion or auth change. | **SENSITIVE SCOPE APPROVED / DESIGN REVIEW PENDING** | Design: `docs/superpowers/specs/2026-10-01-office-c8-workflow-design.md`. No product SQL or runtime implemented. Written-design review precedes implementation planning under the design workflow. |
15 +| 2026-10-01 | Owner replied «ادامه بده» to the C8 written design review request. | **DESIGN APPROVED / IMPLEMENTATION PLAN SAVED FOR REVIEW** | Plan: `docs/superpowers/plans/2026-10-01-office-c8-workflow.md`. Proposed subagent-driven execution; owner review/method confirmation pending. No C8 runtime or SQL implementation yet. |
16 +| 2026-10-01 | Owner explicitly replied «بله تاییده» to additive C8 workflow schema/stages/rules, immutable transition history and related RLS; no data deletion or auth change. | **SENSITIVE SCOPE + DESIGN APPROVED / PLAN REVIEW PENDING** | Design: `docs/superpowers/specs/2026-10-01-office-c8-workflow-design.md`. No product SQL or runtime implemented. Written-design review precedes implementation planning under the design workflow. |
17 | 2026-10-01 | Owner requested live main/CI/Supabase reconciliation, request recording before implementation, verified vertical slices, same-commit state updates, SQL migration archival, explicit approval before schema/RLS/auth/role/destructive changes; subsequently said «ادامه بده». | **AUDIT RECORDED / C8 SENSITIVE SCOPE NOW APPROVED** | Read AGENTS.md then this file in full. Audited main `63fd08f500f31b41877a50020ce023d6ec46f812`; reviewed actual Quality job logs, migration inventory and public RLS catalog. No product, database, auth or role change performed. Details below. |
18 | 2026-10-01 | Continue Office Slice C autonomously from the current checkpoint. | **IN PROGRESS** | C1-C7 are closed with evidence; C8 workflow policy is the next slice. |
19 | 2026-09-30 | Office Slice C4: tenant-safe registration repair + versioned correspondence templates + controlled draft application. | **IMPLEMENTED / PRODUCTION + ADVERSARIAL + REAL-DOM + SECURITY VERIFIED** | Production migrations `20260930202526_office_registration_tenant_repair`, `20260930202701_office_slice_c4_versioned_templates`; verified runtime/test head `481f9fed434f127eaa32ccf8d69c649e783b5cad`; Quality `36773156535` PASS including C4 + Real-DOM; Security `36773156559` CodeQL PASS; Pages `36773155535` PASS. Removed ambiguous legacy registration overload, bound registration to organization, added private append-only template versions, server provenance validation and template UI. Evidence: `docs/OFFICE_SLICE_C4_VERIFICATION.md`. |
@@ -38,7 +39,7 @@ Verify live GitHub + Supabase before acting; implement/test/fix/retest/commit/ve
39 - Read-only public catalog inspection: all 13 public ordinary/partitioned tables have RLS enabled and at least one policy; FORCE RLS is false. Enabled RLS alone does not prove effective tenant isolation. Fresh adversarial RLS execution and private/storage policy review remain NOT VERIFIED.
40 - Security advisor still reports 20 authenticated-callable SECURITY DEFINER warnings and disabled leaked-password protection. No security/auth setting was changed. Previous production-membership and performance claims below are historical and were not re-run in this audit.
41 - No feature is newly marked COMPLETED. Fresh local accounting tests, real-DOM smoke and persistent two-user production E2E: NOT VERIFIED this session. This change only reconciles documentation and records the owner request before implementation.
41 -- Approval boundary: owner approved additive C8 versioned workflow policy/stage/transition storage, immutable transition evidence and tenant-scoped RLS/RPC authorization on 2026-10-01; written design review is pending. No destructive data operations, commercial-role expansion or auth-provider changes are included in that proposed scope.
42 +- Approval boundary: owner approved additive C8 versioned workflow policy/stage/transition storage, immutable transition evidence and tenant-scoped RLS/RPC authorization on 2026-10-01; written design approved; implementation-plan review is pending. No destructive data operations, commercial-role expansion or auth-provider changes are included in that proposed scope.
43
44 ## Current production state — 2026-09-30 (historical checkpoint; live checks above)
45 - Supabase project `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`, **53 migrations through `20260930205919 office_c7_bind_ocr_source_attachment`**.
@@ -79,7 +80,7 @@ Posted accounting history is immutable and balanced; tenant isolation is enforce
80 Authenticated two-real-user production browser E2E with a persistent legitimate non-owner member; automatic external invitation email delivery; owner-approved accounting cutover; real Persian OCR; qualified digital signature; physical printer; live external adapters; GitHub Dependency graph; leaked-password protection; PostgreSQL 17.11 upgrade; CodeQL v4 migration.
81
82 ## Exact next executable work
82 -1. Review the written C8 design with the owner, then prepare and review its implementation plan. Sensitive C8 schema/RLS scope is approved; do not ask for the same scope permission again. Then implement Office Slice C8 as the next bounded internal-office vertical slice: mature correspondence workflow policy (configurable workflow stages, authorized transition rules and immutable transition evidence) without claiming external BPM/provider integration; preserve all C1-C7/accounting/Golden/ELI gates.
83 +1. Obtain review of the saved C8 implementation plan and confirm the execution method; the written design has been approved. Sensitive C8 schema/RLS scope is approved; do not ask for the same scope permission again. Then implement Office Slice C8 as the next bounded internal-office vertical slice: mature correspondence workflow policy (configurable workflow stages, authorized transition rules and immutable transition evidence) without claiming external BPM/provider integration; preserve all C1-C7/accounting/Golden/ELI gates.
84 2. Keep qualified digital signature and external delivery adapters explicitly outside verified scope until real providers are connected and tested.
85 3. Authenticated two-real-user production browser verification remains blocked until a legitimate persistent non-owner principal is intentionally available; do not fabricate or permanently cross-add one.
86 4. External invitation email delivery remains an adapter boundary; do not claim it until a real provider is connected and tested.
@@ -90,3 +91,10 @@ Authenticated two-real-user production browser E2E with a persistent legitimate
91 - Read-only Supabase recheck: 53 migrations, latest `20260930205919`, zero public ordinary/partitioned tables without RLS. No database write performed.
92 - Proposed design self-reviewed for scope, authorization, immutable evidence, concurrency, idempotency, expired-license read-only behavior and non-interference with C1/C5/accounting.
93 - C8 implementation, migrations, real-DOM, accounting rerun and database adversarial/concurrency tests: NOT VERIFIED / NOT RUN. This commit changes documentation only.
94 +
95 +## C8 implementation-plan checkpoint — 2026-10-01
96 +- Baseline main `53cd24eabdfed3bae162bbc217753824a8cfb3bb`; Quality `36824644380`, Security `36824644419`, Pages `36824643831` observed success. These are prior documentation-head statuses, not C8 verification.
97 +- Read actual runtime loader `js/bootstrap.js`, office modules and C7 tests; plan uses focused `js/office-workflow.js` and behavior-level DOM assertions instead of presence-only checks.
98 +- Read-only live database confirmed `records_pkey PRIMARY KEY (organization_id, collection, id)`; C8 FK plan binds the complete identity.
99 +- Plan self-reviewed for spec coverage, interface consistency and retry/tenant-switch/concurrency/malformed-input/HTML failure modes.
100 +- No product or database changes; fresh C8 accounting/DOM/database/concurrency tests NOT RUN / NOT VERIFIED. Next: owner plan review and execution choice, then implement without repeating the approved scope/design questions.
docs/superpowers/plans/2026-10-01-office-c8-workflow.md new
+99
@@ -0,0 +1,99 @@
1 +# Office C8 Workflow Implementation Plan
2 +
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox syntax for tracking.
4 +
5 +**Goal:** Deliver optional, tenant-safe versioned correspondence workflows with atomic authorized transitions and immutable evidence.
6 +**Architecture:** Add three private relational tables and checked private RPC implementations behind public invoker wrappers. Keep correspondence status, C5 approvals and accounting history independent. Add one focused browser module loaded after office-mature.js.
7 +**Tech Stack:** Existing browser JavaScript, PostgreSQL 17/Supabase, Node checks and Playwright Chromium.
8 +**Spec:** docs/superpowers/specs/2026-10-01-office-c8-workflow-design.md
9 +
10 +## Global Constraints
11 +- Policy: 2–20 stages, at most 60 edges, exactly one start, at least one terminal; all stages reachable from start and able to reach a terminal.
12 +- No terminal outgoing edge, duplicate stage/edge, self edge, user executable code or arbitrary conditions.
13 +- Edge capability is edit, refer or approve in office_automation; no role or auth-provider changes.
14 +- Immutable published policy/event history; one workflow per correspondence; pinned policy version.
15 +- Posted financial history, C1–C7, Golden and ELI gates remain intact.
16 +- C8 schema/RLS changes approved; deletion, destructive data operations and auth changes excluded.
17 +- Every durable commit includes PROJECT_STATE.md. Never infer feature completion from CI status alone.
18 +- Exact migration SQL must be archived under supabase/migrations before production application and reconciled to actual history afterwards.
19 +
20 +## Review Focus
21 +1. Lost HTTP response followed by retry must not duplicate events; revoked users must not retrieve prior results through retry.
22 +2. Organization switch while a request is pending must not render another organization's response.
23 +3. Two tabs transitioning the same letter must yield exactly one change for the expected revision.
24 +4. Unknown/null status or malformed JSON must fail closed, not behave as registered.
25 +5. Persian titles containing HTML/quotes must remain text, including historical event labels.
26 +These cases are assigned to tasks 1–3 below.
27 +
28 +## Files and interface decisions
29 +Create js/office-workflow.js; scripts/office-slice-c8-check.mjs; scripts/office-slice-c8.spec.js; supabase/tests/office_c8_workflow.sql; scripts/office-c8-concurrency.mjs; docs/OFFICE_SLICE_C8_VERIFICATION.md.
30 +Modify js/bootstrap.js (load after office-mature.js), js/office-mature.js only to provide a successful-open integration hook if needed, .github/workflows/quality.yml, and PROJECT_STATE.md.
31 +Generate the migration filename with the installed Supabase CLI's migration new command after checking --help; do not guess its timestamp. Use the suffix office_slice_c8_workflow_policy.
32 +Do not restructure office-mature.js or redesign the shell.
33 +
34 +### Task 1: Policy publication and catalog vertical slice
35 +**Owner:** database/runtime implementer; security reviewer examines grants and checks before production.
36 +**Interfaces:**
37 +- Definition JSON: {stages:[{id,label,start,terminal}],edges:[{id,from,to,label,capability}]}.
38 +- IDs match ^[A-Za-z][A-Za-z0-9_-]{0,63}$; labels 1–160 Unicode characters after trim; note at most 2000 characters; definition at most 64 KiB UTF-8. Reject unknown keys and non-boolean flags.
39 +- public.office_workflow_publish(p_organization_id uuid,p_policy_key text,p_title text,p_definition jsonb) returns integer server version.
40 +- public.office_workflow_catalog(p_organization_id uuid) returns JSON array of {policy_key,version,title,definition}; newest versions only, sorted policy_key.
41 +- Private implementations end in _impl, public wrappers SECURITY INVOKER. Publication requires active membership, write entitlement and office configure or owner; catalog requires active membership and read entitlement/capability.
42 +
43 +- [ ] Read existing authorization helpers, current C1 terminal statuses and table grants; run baseline accounting and DOM before edits. If baseline fails, diagnose separately before extending.
44 +- [ ] Write SQL behavioral assertions: accept valid two-stage graph; reject 1/21 stages, 61 edges, duplicate IDs/edges, unknown targets, terminal outgoing edge, unreachable/no-exit graph, missing boolean, unknown capability, null definition, invalid UTF-8-size bound; accept Persian labels within limit.
45 +- [ ] Run SQL tests against a local/disposable nonproduction database and record missing-function failure.
46 +- [ ] Generate migration; create private.office_workflow_policy_versions with composite organization/policy_key/version primary key, organization FK, definition, title, published_by and server time; enable RLS and deny direct client DML. Reject UPDATE/DELETE by trigger.
47 +- [ ] Implement validation with bounded graph traversal (visited set handles allowed nonterminal cycles). Serialize publication per organization/policy_key; allocate version server-side. All private entry points check auth independently.
48 +- [ ] Add browser policy editor/catalog in js/office-workflow.js using DOM creation/textContent and labeled inputs; load after office-mature.js in bootstrap. Expose officeWorkflowPolicies() and officeWorkflowPublish() within the office screen; controls reflect capability but server is authoritative.
49 +- [ ] Add actual Playwright clicks filling a two-stage policy, publishing through a mocked RPC and rendering returned version; reject malicious titles as HTML. Label this UI integration, not production E2E.
50 +- [ ] Execute SQL tests and node scripts/office-slice-c8-check.mjs; execute npx playwright test scripts/office-slice-c8.spec.js --reporter=line --workers=1 against localhost:4173. Require successful assertions, not merely function presence.
51 +- [ ] Review, update PROJECT_STATE.md with exact commands/results and commit task 1 together. Keep production UI gated until required RPCs are deployed.
52 +
53 +### Task 2: Attach/transition/read transactional vertical slice
54 +**Interfaces:**
55 +- office_workflow_attach(p_organization_id uuid,p_correspondence_id text,p_policy_key text,p_policy_version integer,p_request_id uuid) returns JSON {instance_id,stage_id,revision,event_id}.
56 +- office_workflow_transition(p_organization_id uuid,p_instance_id uuid,p_edge_id text,p_expected_revision bigint,p_request_id uuid,p_note text) returns same shape.
57 +- office_workflow_read(p_organization_id uuid,p_correspondence_id text,p_after_revision bigint,p_limit integer) returns JSON {instance,allowed_edges,events,next_after_revision}; limit 1–100, initial cursor -1; instance null when readable letter has no workflow.
58 +- All are public SECURITY INVOKER wrappers with private checked implementations.
59 +- SQLSTATE: 42501 denied/not visible; 22023 invalid input/state; 40001 stale revision; 23505 reused request key with different payload.
60 +- read.allowed_edges is server-authorized at observation time, not an authorization token.
61 +
62 +- [ ] Write failing SQL tests for attach revision 0 + one event, legal transfer revision 1, pinned policy, illegal edge, negative/null revision, anonymous/foreign tenant/unreadable/suspended/expired denial and read-only expired access.
63 +- [ ] Confirm public.records composite PK (organization_id,collection,id); create private.office_workflow_instances FK using collection fixed to correspondence, and policy composite FK. Unique organization/correspondence; revision >=0. Create private.office_workflow_events with unique instance/revision and organization/request_id; add indexed FKs, RLS, revoked client DML and immutable triggers.
64 +- [ ] Implement source-letter lock followed by instance lock consistently; verify active membership, read access, write entitlement and row-scoped required capability under lock. Allow only registered/in_circulation if those are confirmed canonical C1 states; explicitly reconcile any different live token with C1 before implementation. Unknown/draft/closed/archived status denied. Never modify source status, content or approval evidence.
65 +- [ ] Bind actor to auth.uid and timestamps to server; attachment and transition insert evidence + state atomically. Recheck current authorization before replaying a request result. Same actor/payload returns original result; mismatched actor or payload denied; store comparison payload including expected revision and note.
66 +- [ ] Implement read paging by revision, source visibility, and read entitlement. Deny direct private calls identically to wrapper calls. Protect instance policy and correspondence identity from mutation.
67 +- [ ] Add SQL tests for direct insert/actor spoofing, update/delete evidence/policy, pinned-version mutation, tenant FK, duplicate request replay after permission removal, and full transaction rollback.
68 +- [ ] Create scripts/office-c8-concurrency.mjs using two nonproduction PostgreSQL sessions and task-relevant configured credentials (no secrets in logs); race expected revision 0, assert exactly one success/one stale conflict and one event at revision 1. Do not claim this covered by sequential tests.
69 +- [ ] Run nonproduction SQL and concurrency tests with deterministic fixtures. No production user creation, membership/seat changes or permanent fixture insertion.
70 +- [ ] Review SQL authorization and race results, then commit with PROJECT_STATE.md. If no suitable database/credentials exist, mark BLOCKED/NOT VERIFIED and do not apply untested production DDL.
71 +
72 +### Task 3: Correspondence workflow UI vertical slice
73 +**Consumes:** task 2 RPC contracts and task 1 catalog.
74 +**Produces:** officeWorkflowOpen(correspondenceId), officeWorkflowAttach(), officeWorkflowTransition(edgeId), and a labeled workflow panel in #view-office.
75 +- [ ] Write failing Playwright tests for attachment, allowed-edge click, returned revision/history, double-click during pending request, stale-error refresh without auto-transition, denied writes, expired read-only state, and tenant switch during request.
76 +- [ ] Integrate via officeOpenRecord only after successful existing read-evidence check; prevent showing C8 against a stale/failed-open letter. Add a scoped data-correspondence-id hook if existing functions cannot reliably indicate success.
77 +- [ ] Render workflow stage separately from letter status. Exact notice: «مرحله گردش، جایگزین ثبت دبیرخانه یا تأیید داخلی نامه نیست.» History uses server actor/time/revision; textContent for untrusted content.
78 +- [ ] Retain request_id for retry of same intent, generate a new key for a new intent; disable controls while pending. On 40001 refresh and request explicit user action. Capture organization and request generation, discard late responses after navigation/tenant change.
79 +- [ ] Test real DOM behavior with mocked transport; additionally run real authenticated nonproduction integration when legitimate test identities are available. Distinguish results in evidence.
80 +- [ ] Run all prior Playwright specs and accounting checks; fix regressions, retest, update PROJECT_STATE.md and commit UI slice.
81 +
82 +### Task 4: Release verification and evidence
83 +**Files:** .github/workflows/quality.yml; docs/OFFICE_SLICE_C8_VERIFICATION.md; PROJECT_STATE.md; exact migration archive.
84 +- [ ] Add C8 Node and Playwright commands to existing Quality workflow without removing C1–C7/accounting/Golden/ELI steps.
85 +- [ ] Run every Node command listed in quality.yml and all existing DOM specs plus C8. Preserve test output with tested SHA. Inspect logs, not only run conclusion.
86 +- [ ] Before production apply, independently review private entry-point checks, grants, FK indexes, lock order, retry semantics and migration immutability. Resolve important defects and rerun tests.
87 +- [ ] Refresh live head/migrations/RLS; stop on unexpected drift. Apply only the approved additive migration after nonproduction tests pass. Keep exact SQL recoverable even if deployment or Git update fails.
88 +- [ ] Reconcile applied migration version/name/content to repository file in the same durable commit as state; never silently replay or repair history.
89 +- [ ] Run security/performance advisors, grant/RLS catalog checks and read-only deployment checks. Production transactional test writes need separately justified safe scope; never manufacture persistent users.
90 +- [ ] Verify head, CI job/test logs, Pages status and browser entry point. Record UI-mock/nonproduction/production evidence separately.
91 +- [ ] Mark COMPLETED only with actual C8 DOM and accounting invariant PASS, plus implemented acceptance criteria and disclosed external limits. Otherwise keep precise IN PROGRESS/BLOCKED and NOT VERIFIED entries.
92 +- [ ] Operational rollback is disable C8 UI/write entry points preserving data, never DROP or deletion; confirm rollback procedure before release.
93 +- [ ] Commit final evidence with PROJECT_STATE.md, reread remote head/files and report Persian <=15 lines including SHAs, run IDs, unverified items and next action.
94 +
95 +## Self-review / handoff
96 +Spec coverage: graph/versioning task 1; immutable transactional authorization task 2; Persian UI/accessibility task 3; regression/deployment/archival task 4.
97 +Five review-focus cases assigned: retry/permissions + two-tab concurrency task 2; tenant-switch and HTML task 3; malformed status/JSON tasks 1–2.
98 +No implementation/test execution is claimed by this plan.
99 +Recommended execution: subagent-driven with serialized owners (database, UI, independent QA/security), because a workflow authorization defect could cross a tenant boundary. Shared files and commits remain coordinator-owned. Owner reviews this plan and chooses/confirms execution before code changes.
docs/superpowers/specs/2026-10-01-office-c8-workflow-design.md
+1 -1
@@ -1,6 +1,6 @@
1 # طرح C8 — گردش کنترل‌شده مکاتبات
2 تاریخ: 2026-10-01
3 -وضعیت: پیش‌نویس برای بررسی مالک؛ مجوز تغییرات افزایشی schema/RLS دریافت شده، پیاده‌سازی نشده است.
3 +وضعیت: طرح با پیام «ادامه بده» مورخ 2026-10-01 تأیید شد؛ مجوز تغییرات افزایشی schema/RLS دریافت شده، پیاده‌سازی نشده است.
4
5 ## هدف و مرز
6 مدیر مجاز سازمان بتواند مراحل گردش یک نامه و انتقال‌های مجاز را تعریف کند؛ کاربر فقط انتقال مجاز فعلی را اجرا کند و سابقه قابل تغییر نباشد.