@davoodmehraban89 / Factor-easy / commits / c35b7dc
Fork 0

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

feat: reconcile journal graphs without losing pending edits

JVK committed Nov 11, 2026 at 07:54 UTC c35b7dc7f7a8b51fd471ec2f4f0f84734a149818
21 files changed +898 -19
.github/workflows/quality.yml
+1 -1
@@ -26,7 +26,7 @@ jobs:
26 - name: Purchase correction server-mode guards
27 run: node scripts/wp1-purchase-correction-guard-test.mjs
28 - name: Versioned sync compatibility and pending-edit protection
29 - run: node --test scripts/wp1-client-capability-test.mjs
29 + run: node --test scripts/wp1-client-capability-test.mjs scripts/wp1-graph-reconcile-test.mjs
30 - name: JavaScript syntax
31 run: node scripts/syntax-check.mjs
32 - name: Generated Pages public regression (standalone suite)
PROJECT_STATE.md
+7
@@ -337,3 +337,10 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
337 ### 2026-11-11 — Targeted journal reconciliation continuation
338 - Owner continuation resumes MANUAL_RPC_NEXT step2; integrate main6f457ff first so login/bootstrap/navigation repairs remain present. Merge retains both continuity histories, all browser specs and versioned synchronization. Baseline43client protocol tests PASS.
339 - Implement/test targeted graph refresh under the existing sync lock, complete graph validation, captured tenant/company/form identity, rejection on affected dirty/changed data, and atomic data/revision snapshot updates. Preserve unrelated edits/timers. No manual mutation adapter activation or production SQL.
340 +
341 +### 2026-11-11 — Targeted graph reconciliation verified candidate
342 +- Implemented MANUAL_RPC_NEXT step2 in shared sync: capture hydrated tenant/generation/company/form/edit revision and affected graph; bounded shared-lock queue/read; validate complete graph/links/revisions/status/collisions; atomically replace only affected rows and snapshot entries, retain unrelated objects/edits/deletions/timers. Effective reversal status remains separate display metadata. No existing manual mutation handler activated.
343 +- Independent client reviewer reproduced two Important races: stale full hydration overwrote a newer graph; a pre-failure queued save was revived after an uncertain write. Both have observed assertion RED→GREEN. Publication now advances generation; preservePending failure drops only pre-failure queued intent, preserving a later explicit save. No post-fix rereview or independent SQL approval claimed.
344 +- Final88Node (45new+43existing),250full-browser (5.5m),11generatedPages (7.9s),55static/server/release commands PASS. Tightened negative cases assert exact error codes; final45cases all fail on actual e57e046 baseline. One earlier final browser run was interrupted at192/250 across the session gap; excluded and rerun completely. Evidence/hashes: docs/wp1/evidence/graph-reconciliation/result.json. Process-only fontconfig workaround remains outside git.
345 +- Remote ab7fea4 baseline allCI SUCCESS: Quality42948390999,Security42948391034,WP142948391112. Publish this new candidate and verify its exact-head runs separately; no production migration, mode activation or financial data change. PR195 stays draft, stacked onPR194.
346 +- Next: explicit manual form RPC adapter and truthful mutation/retry states (steps3–4); atomic linked correction, entity dimensions/account rules, purchase/source coverage, schema parity/shadow, independent SQL review, real nonproduction JWT acceptance andG1package still required. WP1 and later phases remain incomplete. Main6f457ff public UI releases unchanged; actual owner-account acceptance still pending secure saved profile.
docs/EXECUTION_STATUS.md
+10 -9
@@ -1,11 +1,12 @@
1 -# وضعیت جاری — ۲۰۲۶/۱۱/۰۴
1 +# وضعیت جاری — ۲۰۲۶/۱۱/۱۱
2
3 هدف جاری: تکمیل WP1 با ثبت مالی معتبر سمت سرور و حفاظت ویرایش‌های ذخیره‌نشده. مالک ادامه همه WPها را مجاز کرده؛ گیت هر مرحله و G1–G5 برقرار است. [نقشه راه جاری](ROADMAP_CURRENT.md) و [وضعیت دقیق WP1](wp1/STATUS_FA.md) مرجع فعلی‌اند.
4
5 - انجام‌شده: WP0 و CI آن؛ اتصال امن کلاینت در56818d8 و تمام CI آن؛ ۲۲۲ آزمون مرورگر،۴۳ آزمون Node،۸ آزمون Pages و۵۵ فرمان کنترل موفق.
6 -- اصلاح‌های جدید: حفظ ابعاد برگشت سند و کنترل تاریخ/نوع سند دستی؛ زنجیرهٔ۱۴تغییر در تمام آزمون‌های مالی شامل۱۰۰۰رویداد،هم‌زمانی و DOWN/UP موفق است. نسخهٔ خالی نیز پس از بازتولید چهار نقص در عملیات سند اصلاح شد و۱۶آزمون منفی و چرخهٔ اختصاصی آن موفق‌اند؛ آزمون کامل محلی زنجیرهٔ۱۵تغییر شامل۱۶فایل SQL،۱۰۰۰رویداد،هم‌زمانی و DOWN/UP موفق است؛ CI کامیت4149d50 نیز کامل و موفق است. مسیر خواندن جدید CI جداگانه لازم دارد.
7 -- پیش‌نیاز جدید: خواندن یکپارچهٔ سند با کنترل کامل دسترسی،۱۰۰۳رکورد و دو اتصال آزمایش شد؛ زنجیرهٔ۱۶تغییر DOWN/UP موفق است. کارایی واقعی و CI نهایی جداگانه بررسی می‌شوند.
8 -- باقی‌مانده: ادغام پاسخ خواندن یکپارچه و مسیرRPC سند دستی، اصلاح/ابطال تراکنشی خرید،قرارداد ابعاد و پوشش منابع،حل تعارض،تطبیق ساختار واقعی،shadowکامل،پذیرش واقعی،بکاپ/بازیابی و بستهG1. بازبینی مستقل SQL، ممیزی همهٔ دکمه‌ها و ورود روی اینترنت مالک هنوز پذیرش نهایی ندارند. نصب عملیاتی انجام نشده است.
6 +- اصلاح‌های جدید: حفظ ابعاد برگشت سند و کنترل تاریخ/نوع سند دستی؛ زنجیرهٔ۱۴تغییر در تمام آزمون‌های مالی شامل۱۰۰۰رویداد،هم‌زمانی و DOWN/UP موفق است. نسخهٔ خالی نیز پس از بازتولید چهار نقص در عملیات سند اصلاح شد و۱۶آزمون منفی و چرخهٔ اختصاصی آن موفق‌اند؛ آزمون کامل محلی زنجیرهٔ۱۵تغییر شامل۱۶فایل SQL،۱۰۰۰رویداد،هم‌زمانی و DOWN/UP موفق است؛ CI کامیت4149d50 نیز کامل و موفق است. CI مسیر خواندن جدید در61092e4 نیز کامل و موفق است.
7 +- پیش‌نیاز جدید: خواندن یکپارچهٔ سند با کنترل کامل دسترسی،۱۰۰۳رکورد و دو اتصال آزمایش شد؛ زنجیرهٔ۱۶تغییر DOWN/UP موفق است. CI61092e4 موفق است؛ کارایی و پذیرش واقعی همچنان باز است.
8 +- کاندیدای جدید: ادغام هدفمند پاسخ سند با حفظ ویرایش‌ها؛۸۸آزمونNode،۲۵۰آزمون مرورگر،۱۱آزمونPages و۵۵فرمان کنترل موفق. دو ایراد هم‌زمانی بازبینی مستقل نیز با آزمون قبل/بعد اصلاح شدند. [شواهد](wp1/evidence/graph-reconciliation/result.json).
9 +- باقی‌مانده: اتصال مسیرRPC سند دستی به ادغام پاسخ، اصلاح/ابطال تراکنشی خرید،قرارداد ابعاد و پوشش منابع،حل تعارض،تطبیق ساختار واقعی،shadowکامل،پذیرش واقعی،بکاپ/بازیابی و بستهG1. بازبینی مستقل SQL، ممیزی همهٔ دکمه‌ها و ورود روی اینترنت مالک هنوز پذیرش نهایی ندارند. نصب عملیاتی انجام نشده است.
10
11 ## سوابق پیشین (وضعیت‌های تاریخ‌دار)
12
@@ -13,7 +14,7 @@
14
15 # وضعیت اجرای فینورا
16
16 -آخرین به‌روزرسانی: ۲۰۲۶-۱۱-۱۰. مرجع تاریخچه و اختیار اجرا: [PROJECT_STATE](../PROJECT_STATE.md).
17 +آخرین به‌روزرسانی: ۲۰۲۶-۱۱-۱۱. مرجع تاریخچه و اختیار اجرا: [PROJECT_STATE](../PROJECT_STATE.md).
18
19 ## هدف جاری
20
@@ -22,11 +23,11 @@
23 |کار|وضعیت|شواهد / اقدام بعدی|
24 |---|---|---|
25 |ورود با دکمه‌های غیرفعال|منتشر؛ ۱۰/۱۰ فایل عمومی تطبیق داده شد و کلیک بررسی اتصال سالم است|[گزارش رخداد](LOGIN_BOOTSTRAP_INCIDENT_2026-11-10.md)؛ مرجع وضعیت انتشار و بازخوانی سایت: [PR196](https://github.com/davoodmehraban89/Factor-easy/pull/196)؛ پذیرش حساب و اینترنت مالک هنوز تأیید نشده|
25 -|جابه‌جایی ماژول‌ها و دسترسی‌ها کنار خروج|پیاده‌سازی و بررسی؛ انتخابگر در نوار بالا، دسترسی در تنظیمات|۹/۹ source و ۹/۹ Pages؛ [گزارش](NAVIGATION_UTILITIES_2026-11-10.md) و مرجع CI/انتشار [PR197](https://github.com/davoodmehraban89/Factor-easy/pull/197)|
26 -|WP1 سخت‌سازی مالی|کاندیدای جداگانه؛ روی سایت فعال نشده|PR195، نسخه61092e4: Quality41957583573 / Security41957583565 / WP141957583675 موفق؛ اتصال امن کلاینت و گیت‌های انتشار باقی است|
26 +|جابه‌جایی ماژول‌ها و دسترسی‌ها کنار خروج|منتشر و تطبیق۱۰/۱۰فایل عمومی؛ انتخابگر در نوار بالا، دسترسی در تنظیمات|۹/۹ source و ۹/۹ Pages؛ [گزارش](NAVIGATION_UTILITIES_2026-11-10.md) و مرجع CI/انتشار [PR197](https://github.com/davoodmehraban89/Factor-easy/pull/197)|
27 +|WP1 سخت‌سازی مالی|کاندیدای جداگانه؛ روی سایت فعال نشده|PR195، نسخه61092e4: Quality41957583573 / Security41957583565 / WP141957583675 موفق؛ ادغام پاسخ کاندیدا و آزموده است؛ آداپتور دستی و گیت‌های انتشار باقی است|
28 |تفکیک نوع سند خرید/فروش|منتشر در PR191؛ آزمون‌های مجدد در مجموعهٔ ۲۲۰ موفق|فروش: فروش/پیش‌فاکتور/صورت‌وضعیت؛ خرید: خرید؛ اسناد قبلی حفظ می‌شوند|
28 -|سازمان، درخواست‌ها و مدیریت اعضا|مسیرها در PR191 منتشر شدند؛ جایگذاری جدید در PR197|پنجرهٔ مدیریت در خطای خواندن هنوز نیازمند PR193 است؛ نشر آن با جایگذاری منو یکی نیست|
29 -|خطاهای دریافت حساب و بارگذاری پنل کاربران|پیاده‌سازی یکپارچه و آزمون کامل موفق؛ انتشار در PR193 پیگیری می‌شود|۲۳۶/۲۳۶ مرورگر کامل، ۲۲/۲۲ Pages، ۵۱ بررسی ایستا/سرور؛ [مرجع انتشار](https://github.com/davoodmehraban89/Factor-easy/pull/193)|
29 +|سازمان، درخواست‌ها و مدیریت اعضا|مسیرها در PR191 منتشر شدند؛ جایگذاری جدید در PR197|پنجرهٔ مدیریت با خطای روشن و تلاش مجدد درPR193 منتشر شد؛ پذیرش واقعی نقش‌ها باز است|
30 +|خطاهای دریافت حساب و بارگذاری پنل کاربران|منتشر و تطبیق۱۰/۱۰فایل عمومی؛ آزمون عمومی تازه موفق|۲۳۶/۲۳۶ مرورگر کامل، ۲۲/۲۲ Pages، ۵۱ بررسی ایستا/سرور؛ [مرجع انتشار](https://github.com/davoodmehraban89/Factor-easy/pull/193)|
31 |اصلاح شرکت|منتشر؛ بازکردن/انصراف واقعی قبول|ذخیرهٔ تغییر شرکت در حساب واقعی از این پذیرش نتیجه نمی‌شود|
32 |تعیین رمز مدیر کل|منتشر؛ تست مصنوعی موفق|آزمون واقعی پنجره با نقش مدیر کل و حساب کنترل‌شده باقی است|
33 |منوهای فازA|منتشر؛۲۰۳تست نسخهٔ مربوط موفق|پذیرش همهٔ نقش‌ها و داده‌ها جداست|
docs/ROADMAP_CURRENT.md
+1 -1
@@ -25,4 +25,4 @@
25
26 ## پیگیری اصلاحات فوری رابط کاربر — ۱۰ نوامبر
27
28 -ورود و جایگذاری منوها در PR196 وPR197 جدا از تغییرات مالی منتشر و با۱۰/۱۰فایل عمومی و مرورگر تازه تأیید شدند. PR193 با۲۳۶آزمون موفق محلی وGitHub،۲۲آزمونPages و۵۱بررسی ایستا/سرور منتشر شده و تطبیق۱۰/۱۰فایل عمومی و مرورگر تازه برای آن نیز موفق است؛ شواهد کامل در همانPR ثبت شده‌اند. این اصلاح‌ها WP2 را کامل نمی‌کنند. نشست واقعی مالک برای پذیرش داخل حساب منتظر ذخیرهٔ امن است؛ اطلاعات ورود در مخزن قرار نمی‌گیرد. ادامهٔ WP1 از بند۲ برنامه MANUAL_RPC_NEXT است: ادغام هدفمند و امن پاسخ سند، سپس آداپتور فرم دستی.
28 +ورود و جایگذاری منوها در PR196 وPR197 جدا از تغییرات مالی منتشر و با۱۰/۱۰فایل عمومی و مرورگر تازه تأیید شدند. PR193 با۲۳۶آزمون موفق محلی وGitHub،۲۲آزمونPages و۵۱بررسی ایستا/سرور منتشر شده و تطبیق۱۰/۱۰فایل عمومی و مرورگر تازه برای آن نیز موفق است؛ شواهد کامل در همانPR ثبت شده‌اند. این اصلاح‌ها WP2 را کامل نمی‌کنند. نشست واقعی مالک برای پذیرش داخل حساب منتظر ذخیرهٔ امن است؛ اطلاعات ورود در مخزن قرار نمی‌گیرد. بند۲ برنامه MANUAL_RPC_NEXT اکنون پیاده‌سازی کاندیدا و۸۸آزمون موفق دارد؛ دو ایراد بازبینی مستقل اصلاح شدند و ۲۵۰آزمون مرورگر،۱۱آزمونPages و۵۵فرمان کنترل نهایی موفق‌اند؛ CI نسخهٔ منتشرشده جداگانه پیگیری می‌شود. سپس آداپتور فرم دستی و مدیریت نتیجهٔ نامطمئن در بندهای۳و۴ ادامه می‌یابد.
docs/wp1/CLIENT_SYNC_CONTRACT.md
+10
@@ -21,3 +21,13 @@ Independent review identified and reproduced two scheduling/tenant races. Both w
21 A final identity-refresh status regression is also covered: with no queued save, stale write completion changes a still-pending same-tenant badge from saving to unconfirmed, without accepting the stale ACK or clearing a newer save timer.
22
23 Final local checkpoint2026-11-04:43Node,222full-browser,8generatedPages and55quality commands PASS. C8 fixture now waits for actual organization/startup readiness before injecting synthetic authority;30repeated cases PASS. [Hashes and evidence](evidence/client-sync/result.json). Exact client head56818d8 subsequently passed Quality41758729100,Security41758729122 andWP1proof41758729204. Later SQL changes require their own exact-head CI.
24 +
25 +## Targeted journal graph reconciliation (candidate, 2026-11-11)
26 +
27 +`finoraCaptureJournalRefresh(voucherId, readViewContext)` captures a hydrated user/organization/generation, the affected local records plus their snapshots/revisions, and a live view identity. The accessor must return `{companyId, formId, editRevision}`: `formId` is unique per form opening, and `editRevision` advances for every relevant input change. The future manual adapter must capture before asynchronous work, not after it. Affected unsaved edits refuse refresh; unrelated dirty rows are allowed. No existing manual handler calls this API yet.
28 +
29 +`await finoraRefreshJournalGraph(capture)` queues behind the normal sync lock (20-second bound), validates the capture after acquiring it, calls only `finora_journal_read_graph` (20-second bound), revalidates the capture and validates the entire reply before publishing. Null/missing header, invalid tenant/company/links/revisions/status, stale revision and ID collision refuse publication. Normal saves cannot overlap the read/publication. A late response after timeout cannot publish. Only the three affected journal arrays and corresponding snapshot entries change; unrelated row references, pending deletions and save timers survive. Deleted children are removed only after a valid complete graph is received. A null graph is never interpreted as confirmed deletion.
30 +
31 +Return value `{voucherId, effectiveStatus}` is display metadata. Stored original status remains intact. Refresh does not clear the form, authorize a write, mark a mutation successful, or use a full `pullAll`/snapshot replacement. A read-only member can refresh visible records; the RPC remains the authority for visibility. The planned mutation adapter still needs its own operation serialization, intent/retry policy and truthful confirmed-write/failed-refresh state; do not infer those from this read-only API.
32 +
33 +A successful targeted publication advances the snapshot generation. Full reads already in flight cannot overwrite it, and older queued graph captures must be recaptured explicitly. A preserve-pending write failure discards save intent queued before that failure; a genuinely new explicit save during the following graph read still resumes. These two ordering regressions were independently reproduced before their fixes.
docs/wp1/GRAPH_RECONCILIATION_LEDGER.md new
+35
@@ -0,0 +1,35 @@
1 +# Targeted graph reconciliation execution ledger
2 +
3 +Plan: MANUAL_RPC_NEXT.md step2. Base: e57e046 (main6f457ff integrated).
4 +Spec: owner-prompts/FINORA_HARDENING_MASTER_2026-11-02_REV2.txt; CLIENT_SYNC_CONTRACT.md.
5 +
6 +Task1 is complete at61092e4 with verified Quality/Security/WP1 CI. Task2 is in progress. Tasks3–6 remain pending; this increment does not activate manual server mutations.
7 +
8 +Pre-flight interfaces:
9 +- Graph RPC returns organization_id/voucher_id/effective_status/records; client must validate all rows, separate revisions, relationships and status before publication.
10 +- Existing sync uses syncRunning, syncAgain, syncTimer, hydrated tenant/generation and two snapshot maps. Targeted refresh must share that lock and preserve unrelated object identity and pending work.
11 +- Future manual adapter needs a capture made before asynchronous work: voucher ID plus live company/form/edit-revision accessor. A changed form must invalidate refresh even if datastore has not changed.
12 +
13 +Ruling: use this tracked ledger and explicit task brief instead of unavailable local skill helper scripts — same baseline, RED/GREEN and evidence contract; cost if wrong is bookkeeping drift, not a runtime behavior change.
14 +Ruling: integrate the three already released UI repairs before client work — avoids testing an obsolete login/navigation baseline; cost is broader integration verification, covered by the full canonical browser suite.
15 +
16 +## Step2 brief
17 +
18 +Implement capture + refresh API in sync.js. Require a hydrated organization, valid voucher identity and live view context {companyId, formId, editRevision}; reject affected unsaved edits initially and after each await. Queue a refresh behind active sync using the same lock; serialize multiple refreshes, with bounded queue wait. Normal sync requested while refreshing resumes on release. Reject malformed/null/error graph, colliding unrelated IDs and decreasing revisions. Prepare new arrays/maps without mutation, then publish affected records and snapshots together without awaiting; retain all unrelated references and timers. Return effective status as metadata only. Do not mutate the stored voucher status, clear a form or display mutation success. Missing graph is not proof of deletion and never deletes local data.
19 +
20 +Behavior tests: clean targeted merge/removal, unrelated dirty data/timers/references, initial and in-flight graph edits, same-user organization change, hydration generation, company/form/revision changes, normal sync on both sides of lock, concurrent refresh, queue/request timeout and late replies, errors/null/invalid rows/versions/links/status, colliding unrelated IDs, new graph, read-only refresh and no mutation RPC. Baseline43 protocol tests PASS after integration. Expected final: all new tests, existing protocol tests, canonical static and browser checks pass. No production activation.
21 +
22 +## Verification and independent review
23 +
24 +- Initial38cases ran against missing API:12failed, while26negative cases accepted the missing-function rejection too broadly. After tightening expected error codes, all45final cases fail against the actual e57e046 baseline source (0pass/45fail), and all45pass against the implementation. Existing43protocol cases also pass. Four extra cases verify complete1003records, canonical JSON equality, queued view change and unhydrated tenant;85/85 passed. One test initially assumed array order rather than voucher identity; corrected lookup to the explicit voucher ID (no behavior assertion removed).
25 +- Independent reviewer /root/graph_reconciliation_review read the increment and integration, independently passed85 tests and reproduced two Important races. No Critical or Minor findings. This is client/integration review, not independent SQL approval.
26 +- Final fix1: older full hydration could overwrite a successful targeted publication; added reverse-order regression (RED: missing expected rejection), then advance sync generation on targeted publication. Older queued captures also reject conservatively and require a fresh capture.
27 +- Final fix2: pre-failure syncAgain could be revived by graph completion after an uncertain writer; added regression (RED: unexpected retry timer), then clear that stale intent at preservePending failure. Added positive case ensuring a new explicit save during the following graph read still resumes.88/88Node now pass;55final static/server/release commands pass. Complete final browser verification remains in progress.
28 +- Final: Ruling: SQL correctness, actual Auth/JWT/PostgREST, production/schema/performance and manual steps3–6 are not established by this client review — retain existing gates and remaining tasks; cost if misinterpreted is premature release, prevented by draft PR and no activation.
29 +- Final: Ruling: coordinator owns full browser/static evidence rather than attributing it to reviewer — results and exact commands are recorded separately; cost if omitted is incomplete verification, so no acceptance is claimed until those runs finish.
30 +
31 +- Final canonical source/browser run:250/250PASS (5.5m). An earlier final run was interrupted at192/250 across the session gap and is not counted. The preceding249case integration run passed but is not the final-fix acceptance; the complete250case run above is the final source/browser evidence. Generated Pages11/11PASS (7.9s).
32 +- Remote documentation baseline ab7fea4 subsequently verified allSUCCESS: Quality42948390999,Security42948391034,WP142948391112. These do not substitute for CI on the forthcoming implementation commit.
33 +
34 +Task2: implementation complete locally (base e57e046; final code/test hashes in evidence/graph-reconciliation/result.json). Tests: node --test scripts/wp1-client-capability-test.mjs scripts/wp1-graph-reconcile-test.mjs →88/88; canonical quality workflow browser command→250/250; same sync spec on generatedPages→11/11;54quality commands+release safety→55/55. Published exact-head CI remains a separate gate.
35 +Next task: MANUAL_RPC_NEXT steps3–4, explicit manual form adapter and truthful mutation/retry outcomes. Capture expected revision when opening edits; preserve form identity and account binding through each await, including the snapshot generation advanced by this refresh. Do not globally replace synchronous engine callers. Delete requires an explicit confirmed-deletion reconciliation contract; null read is not deletion proof. No production enablement before remaining contracts/gates.
docs/wp1/MANUAL_RPC_NEXT.md
+1 -1
@@ -1,6 +1,6 @@
1 # Next WP1 increment: manual journal server workflow
2
3 -Status: source-backed implementation plan. The read prerequisite now has an isolated candidate in JOURNAL_GRAPH_READ.md; client adapter/merge and remaining items are not implemented or accepted. Depends on the integrated ledger guards and versioned sync; remains in draft PR195. No production activation.
3 +Status: source-backed implementation plan. The read prerequisite now has an isolated candidate in JOURNAL_GRAPH_READ.md; targeted client merge is implemented as a candidate (see GRAPH_RECONCILIATION_LEDGER.md); manual adapter and remaining items are not implemented or accepted. Depends on the integrated ledger guards and versioned sync; remains in draft PR195. No production activation.
4
5 ## Problem and invariant
6
docs/wp1/STATUS_FA.md
+1 -1
@@ -21,7 +21,7 @@
21 - کامیت `4149d50` (زنجیرهٔ۱۵تغییر) در [Quality41921247467](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41921247467)، [Security41921247463](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41921247463) و [WP1 proof41921247407](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41921247407) موفق است؛ آزمون۱۰۰۰رویداد،هم‌زمانی و تمام چرخه‌ها کامل شده‌اند. نتیجهٔ نسخهٔ خواندن جدید در بند بعد ثبت شده است.
22 - [خواندن یکپارچهٔ سند](JOURNAL_GRAPH_READ.md) آمادهٔ بررسی است: آزمون۱۰۰۳رکورد، جداسازی سازمان‌ها، عضو فقط‌خواندنی/تعلیق‌شده، ردیف و برگشت محرمانه و خطاهای اتصال ردیف موفق‌اند. آزمایش دو اتصال، نسخهٔ یکپارچهٔ قبل و بعد از ثبت هم‌زمان را تأیید می‌کند. چرخهٔ اختصاصی و برگشت/نصب مجدد هر۱۶تغییر موفق‌اند. ۱۶ فایل SQL به‌جز آزمون۱۰۰۰رویداد و رقابت ثبت نیز روی این زنجیره موفق‌اند؛ CI دقیق کامیت61092e4810b6e0b9ab66bd7ecffbd557bea71eda در Quality41957583573،Security41957583565 وWP1 proof41957583675 کامل و موفق است؛ شامل زنجیرهٔ۱۶تغییر،۱۰۰۰رویداد،هم‌زمانی و چرخه‌های برگشت/نصب. کارایی محیط واقعی و بازبینی مستقل هنوز تأیید نشده‌اند.
23
24 -این اصلاح‌های SQL بازبینی ریشه‌ای و آزمون دارند؛ بازبینی مستقل متخصص SQL هنوز انجام نشده است. هدف بعدی، اتصال خواندن یکپارچه به فرم دستی و ادغام پاسخ بدون از دست‌رفتن ویرایش‌های دیگر است؛ [ترتیب اجرا و معیار پذیرش](MANUAL_RPC_NEXT.md).
24 +این اصلاح‌های SQL بازبینی ریشه‌ای و آزمون دارند؛ بازبینی مستقل متخصص SQL هنوز انجام نشده است. ادغام هدفمند پاسخ سند اکنون کاندیدای پیاده‌سازی دارد: حفظ ویرایش‌های نامرتبط، کنترل تغییر شرکت/فرم و نسخه و صف مشترک ذخیره؛۸۸آزمون Node موفق‌اند. دو ایراد هم‌زمانی در بازبینی مستقل بازتولید و با آزمون قبل/بعد اصلاح شدند؛ ۲۵۰آزمون کامل مرورگر،۱۱آزمون خروجیPages و۵۵فرمان کنترل نهایی نیز موفق‌اند. CI کامیت جدید جداگانه بررسی می‌شود. [گزارش اجرا](GRAPH_RECONCILIATION_LEDGER.md). هدف بعدی، اتصال فرم دستی به این مسیر و مدیریت نتیجهٔ نامطمئن است؛ [ترتیب اجرا و معیار پذیرش](MANUAL_RPC_NEXT.md).
25
26 ## باقی‌مانده برای پایان WP1
27
docs/wp1/evidence/graph-reconciliation/baseline-red-summary.txt new
+8
@@ -0,0 +1,8 @@
1 +Baseline source: e57e046:js/sync.js
2 +Command: FINORA_SYNC_SOURCE=<baseline source> node --test scripts/wp1-graph-reconcile-test.mjs
3 +ℹ tests 45
4 +ℹ pass 0
5 +ℹ fail 45
6 +
7 +All45cases fail because the required capture/refresh API is absent on the baseline.
8 +The two independent race regressions have separate assertion failures in review-races-red.log.
docs/wp1/evidence/graph-reconciliation/browser-summary.txt new
+4
@@ -0,0 +1,4 @@
1 +[248/250] scripts/wp1-client-sync.spec.js:92:47 › journal graph merge preserves unrelated unsaved edits in real runtime
2 +[249/250] scripts/wp1-client-sync.spec.js:92:47 › journal graph form-changed preserves unrelated unsaved edits in real runtime
3 +[250/250] scripts/wp1-client-sync.spec.js:114:1 › organization hydration begun before graph refresh cannot overwrite its newer revision
4 + 250 passed (5.5m)
docs/wp1/evidence/graph-reconciliation/node-green.log new
+96
@@ -0,0 +1,96 @@
1 +✔ confirmed absent server uses legacy columns and legacy sync (13.541328ms)
2 +✔ present capability loads versions and uses versioned sync acknowledgement (5.571946ms)
3 +✔ transport probe errors preserve pending edits without a legacy write (4.41725ms)
4 +✔ partial server with no row version fails before write (5.252983ms)
5 +✔ account switch during probe cannot send old edits (4.510609ms)
6 +✔ old-organization write acknowledgement cannot overwrite new snapshot (2.730183ms)
7 +✔ incomplete upsert acknowledgement cannot mark pending changes saved (3.095577ms)
8 +✔ incomplete delete acknowledgement cannot erase snapshot (4.341366ms)
9 +✔ missing V2 write RPC never silently downgrades to legacy write (5.028077ms)
10 +✔ new server capability requires fresh versions without discarding pending edits (4.139376ms)
11 +✔ organization wrapper uses same capability and versioned protocol (5.573953ms)
12 +✔ late read cannot publish across identity switch (org wrapper false) (4.20993ms)
13 +✔ CAS conflict preserves edits without reload or retry (org wrapper false) (4.816247ms)
14 +✔ late read cannot publish across identity switch (org wrapper true) (2.932365ms)
15 +✔ CAS conflict preserves edits without reload or retry (org wrapper true) (3.081492ms)
16 +✔ malformed acknowledgement stays pending: {"upserts":[{"collection":"companies","id":"C","version":5},{"collection":"companies","id":"C","version":5}],"deletes":[]} (3.113386ms)
17 +✔ malformed acknowledgement stays pending: {"upserts":[{"collection":"companies","id":"C","version":4}],"deletes":[]} (2.526197ms)
18 +✔ malformed acknowledgement stays pending: {"upserts":[{"collection":"companies","id":"C","version":"5"}],"deletes":[]} (3.94373ms)
19 +✔ malformed acknowledgement stays pending: {"upserts":[{"collection":"companies","id":"other","version":5}],"deletes":[]} (3.175646ms)
20 +✔ malformed acknowledgement stays pending: {"upserts":[{"collection":"companies","id":"C","version":5}],"deletes":[{"collection":"companies","id":"C"}]} (2.653399ms)
21 +✔ malformed acknowledgement stays pending: null (2.367667ms)
22 +✔ positive version evidence prevents falling back when probe disappears (3.973502ms)
23 +✔ new record uses version zero and deletion acknowledges exact identity (2.42686ms)
24 +✔ edits made during write stay pending and use returned version on next batch (2.607389ms)
25 +✔ malformed guard mode cannot authorize a write (2.422764ms)
26 +✔ invalid persisted revision cannot downgrade to legacy: null (2.201767ms)
27 +✔ invalid persisted revision cannot downgrade to legacy: 0 (1.71071ms)
28 +✔ invalid persisted revision cannot downgrade to legacy: -1 (3.062024ms)
29 +✔ invalid persisted revision cannot downgrade to legacy: 1.5 (2.133919ms)
30 +✔ invalid persisted revision cannot downgrade to legacy: 4 (2.306558ms)
31 +✔ invalid persisted revision cannot downgrade to legacy: 9007199254740992 (2.375187ms)
32 +✔ late acknowledgement after same-tenant refresh cannot replace fresh revisions (3.523652ms)
33 +✔ nested edits during capability probe cannot mutate the captured write payload (7.821865ms)
34 +✔ stalled probe has a bounded failure and no late success (22.399711ms)
35 +✔ stalled write has a bounded failure and no late success (4.907375ms)
36 +✔ duplicate pending identifiers fail before any write (3.285494ms)
37 +✔ queued save resumes after stale tenant request releases sync lock (5.880716ms)
38 +✔ queued save resumes after stale identity request releases sync lock (5.858253ms)
39 +✔ same-context CAS rejection does not automatically retry queued edits (5.668289ms)
40 +✔ same user cannot dispatch old-organization edits while new organization is loading (12.6967ms)
41 +✔ direct same-user organization change cannot write before its own snapshot (3.237494ms)
42 +✔ identity refresh without queued save marks unconfirmed edits instead of endless saving (3.84042ms)
43 +✔ stale identity status preserves a newer save timer that has not fired (4.990848ms)
44 +✔ targeted refresh replaces only its graph and acknowledges versions without syncing display status (9.074353ms)
45 +✔ unrelated dirty objects, deletion, pending state and save timer survive graph publication (2.965857ms)
46 +✔ initial dirty graph rejects without network: datastore.journalVouchers[0].description='local' (2.673261ms)
47 +✔ initial dirty graph rejects without network: datastore.journalLines=[] (1.408444ms)
48 +✔ initial dirty graph rejects without network: datastore.journalLines[0].voucherId='OTHER' (1.946917ms)
49 +✔ initial dirty graph rejects without network: datastore.journalLineDimensions[0].journalLineId='bad' (1.501588ms)
50 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.run("datastore.journalLines[0].debit=101") (1.826218ms)
51 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.run("datastore.journalLines.push({id:'NEW',ownerUserId:'U',companyId:'C',voucherId:'V',debit:20})") (2.096934ms)
52 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.setView({companyId:'C2'}) (2.180484ms)
53 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.setView({formId:'F2'}) (2.836252ms)
54 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.setView({editRevision:1}) (2.200071ms)
55 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>{f.c.currentUser.organizationId='OTHER';} (1.674388ms)
56 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>{f.c.currentUser={id:'U',organizationId:'O'};} (1.794554ms)
57 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.c.pullAll() (2.058651ms)
58 +✔ malformed or unauthorized graph preserves all arrays and snapshots: null (2.058334ms)
59 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong tenant (1.565698ms)
60 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong voucher (2.706967ms)
61 +✔ malformed or unauthorized graph preserves all arrays and snapshots: no header (2.422187ms)
62 +✔ malformed or unauthorized graph preserves all arrays and snapshots: duplicate (1.622971ms)
63 +✔ malformed or unauthorized graph preserves all arrays and snapshots: foreign collection (1.768658ms)
64 +✔ malformed or unauthorized graph preserves all arrays and snapshots: unsafe version (2.56306ms)
65 +✔ malformed or unauthorized graph preserves all arrays and snapshots: regressed version (2.063792ms)
66 +✔ malformed or unauthorized graph preserves all arrays and snapshots: same revision altered payload (2.129483ms)
67 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong company (3.102482ms)
68 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong parent (1.649032ms)
69 +✔ malformed or unauthorized graph preserves all arrays and snapshots: bad ID (1.574859ms)
70 +✔ malformed or unauthorized graph preserves all arrays and snapshots: mismatched data ID (1.611112ms)
71 +✔ malformed or unauthorized graph preserves all arrays and snapshots: invalid status (1.541151ms)
72 +✔ malformed or unauthorized graph preserves all arrays and snapshots: draft reversed status (1.80053ms)
73 +✔ malformed or unauthorized graph preserves all arrays and snapshots: orphan dimension (1.888797ms)
74 +✔ malformed or unauthorized graph preserves all arrays and snapshots: collision (2.843819ms)
75 +✔ malformed or unauthorized graph preserves all arrays and snapshots: error (1.345027ms)
76 +✔ normal sync waits for refresh and sends only unrelated dirty records (14.999578ms)
77 +✔ refresh queues behind an existing normal save (4.857874ms)
78 +✔ second captured refresh rejects after first graph changes, without a second request (6.564661ms)
79 +✔ request timeout releases lock and a late graph cannot publish (5.943746ms)
80 +✔ queued refresh timeout does not steal active writer lock (12.349816ms)
81 +✔ read-only user can refresh a new visible graph without a write (4.162315ms)
82 +✔ valid same-revision JSON with different key order remains clean (3.876639ms)
83 +✔ complete graph above normal page size retains all lines and linked dimensions (40.871593ms)
84 +✔ context changed while queued rejects before sending graph request (6.737854ms)
85 +✔ unhydrated same-user tenant cannot capture old graph (6.5512ms)
86 +✔ failed writer drops pre-failure queued retry even when a graph refresh follows (12.772055ms)
87 +✔ a new explicit save queued during graph read still resumes after earlier writer failure (2.011435ms)
88 +✔ older same-tenant full read cannot overwrite a newer targeted graph publication (2.251527ms)
89 +ℹ tests 88
90 +ℹ suites 0
91 +ℹ pass 88
92 +ℹ fail 0
93 +ℹ cancelled 0
94 +ℹ skipped 0
95 +ℹ todo 0
96 +ℹ duration_ms 680.738284
docs/wp1/evidence/graph-reconciliation/pages-summary.txt new
+4
@@ -0,0 +1,4 @@
1 +[9/11] scripts/wp1-client-sync.spec.js:92:47 › journal graph merge preserves unrelated unsaved edits in real runtime
2 +[10/11] scripts/wp1-client-sync.spec.js:92:47 › journal graph form-changed preserves unrelated unsaved edits in real runtime
3 +[11/11] scripts/wp1-client-sync.spec.js:114:1 › organization hydration begun before graph refresh cannot overwrite its newer revision
4 + 11 passed (7.9s)
docs/wp1/evidence/graph-reconciliation/result.json new
+47
@@ -0,0 +1,47 @@
1 +{
2 + "date": "2026-11-11",
3 + "base": "e57e046",
4 + "scope": "MANUAL_RPC_NEXT step2 candidate only; no production activation",
5 + "baseline": {
6 + "source": "e57e046:js/sync.js",
7 + "pass": 0,
8 + "fail": 45
9 + },
10 + "review_regressions_red": {
11 + "pass": 43,
12 + "fail": 2
13 + },
14 + "final_node": {
15 + "pass": 88,
16 + "fail": 0
17 + },
18 + "full_browser": {
19 + "pass": 250,
20 + "fail": 0,
21 + "duration": "5.5m"
22 + },
23 + "generated_pages": {
24 + "pass": 11,
25 + "fail": 0,
26 + "duration": "7.9s"
27 + },
28 + "static_server_release_commands": {
29 + "pass": 55,
30 + "fail": 0
31 + },
32 + "independent_review": "Two Important client races reproduced; both fixed with RED/GREEN and full verification. No independent SQL approval or post-fix rereview claimed.",
33 + "limitations": [
34 + "Synthetic network boundaries, not real Auth/JWT/PostgREST",
35 + "No financial production migration or activation",
36 + "Manual mutation adapter and remaining WP1 gates pending"
37 + ],
38 + "sha256": {
39 + "js/sync.js": "3465b829d8f1fe39010d099033e22420707b3a8086efe9b8e45d9bd1788ec8ef",
40 + "js/organization-rbac.js": "8c677a689c9923ea03335d51f9e72aaba8779ca234c1eba2e2bdbae1fe16fee6",
41 + "js/bootstrap.js": "bc23063bb8550fb5648e9324ab71539e0b9c0d8548b21a1373a831310c94ce66",
42 + "index.html": "0752d83982a23729cb40e439268734821e5788d1b7f83d059b25f01741d0b652",
43 + "scripts/wp1-graph-reconcile-test.mjs": "d7f2f7f79d6742bb6ce8cb9557940d159a45d8616d91e1cd5cb25a8894720104",
44 + "scripts/wp1-client-sync.spec.js": "b217992c289841dc6f9754ac55ef51667e41a5d66c08bcf49f5c779591141b60",
45 + ".github/workflows/quality.yml": "17655978b647e2ec7845efb4ba8c5b0a922aeedf436bfd0df5c766cee442e02d"
46 + }
47 +}
docs/wp1/evidence/graph-reconciliation/review-races-red.log new
+86
@@ -0,0 +1,86 @@
1 +✔ targeted refresh replaces only its graph and acknowledges versions without syncing display status (11.131223ms)
2 +✔ unrelated dirty objects, deletion, pending state and save timer survive graph publication (2.540014ms)
3 +✔ initial dirty graph rejects without network: datastore.journalVouchers[0].description='local' (2.979948ms)
4 +✔ initial dirty graph rejects without network: datastore.journalLines=[] (2.435382ms)
5 +✔ initial dirty graph rejects without network: datastore.journalLines[0].voucherId='OTHER' (1.736705ms)
6 +✔ initial dirty graph rejects without network: datastore.journalLineDimensions[0].journalLineId='bad' (3.5196ms)
7 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.run("datastore.journalLines[0].debit=101") (2.585552ms)
8 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.run("datastore.journalLines.push({id:'NEW',ownerUserId:'U',companyId:'C',voucherId:'V',debit:20})") (2.157909ms)
9 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.setView({companyId:'C2'}) (2.892254ms)
10 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.setView({formId:'F2'}) (5.786137ms)
11 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.setView({editRevision:1}) (3.710598ms)
12 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>{f.c.currentUser.organizationId='OTHER';} (1.938847ms)
13 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>{f.c.currentUser={id:'U',organizationId:'O'};} (1.535501ms)
14 +✔ in-flight local/view/account/snapshot change rejects atomic publication #f=>f.c.pullAll() (2.592206ms)
15 +✔ malformed or unauthorized graph preserves all arrays and snapshots: null (2.633586ms)
16 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong tenant (3.429468ms)
17 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong voucher (2.768656ms)
18 +✔ malformed or unauthorized graph preserves all arrays and snapshots: no header (3.101318ms)
19 +✔ malformed or unauthorized graph preserves all arrays and snapshots: duplicate (1.82723ms)
20 +✔ malformed or unauthorized graph preserves all arrays and snapshots: foreign collection (1.747037ms)
21 +✔ malformed or unauthorized graph preserves all arrays and snapshots: unsafe version (1.774437ms)
22 +✔ malformed or unauthorized graph preserves all arrays and snapshots: regressed version (2.120605ms)
23 +✔ malformed or unauthorized graph preserves all arrays and snapshots: same revision altered payload (2.047641ms)
24 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong company (1.57455ms)
25 +✔ malformed or unauthorized graph preserves all arrays and snapshots: wrong parent (2.509505ms)
26 +✔ malformed or unauthorized graph preserves all arrays and snapshots: bad ID (1.529343ms)
27 +✔ malformed or unauthorized graph preserves all arrays and snapshots: mismatched data ID (1.598755ms)
28 +✔ malformed or unauthorized graph preserves all arrays and snapshots: invalid status (2.292858ms)
29 +✔ malformed or unauthorized graph preserves all arrays and snapshots: draft reversed status (4.946887ms)
30 +✔ malformed or unauthorized graph preserves all arrays and snapshots: orphan dimension (2.429958ms)
31 +✔ malformed or unauthorized graph preserves all arrays and snapshots: collision (1.742755ms)
32 +✔ malformed or unauthorized graph preserves all arrays and snapshots: error (4.777361ms)
33 +✔ normal sync waits for refresh and sends only unrelated dirty records (15.331653ms)
34 +✔ refresh queues behind an existing normal save (5.558163ms)
35 +✔ second captured refresh rejects after first graph changes, without a second request (3.74137ms)
36 +✔ request timeout releases lock and a late graph cannot publish (2.862428ms)
37 +✔ queued refresh timeout does not steal active writer lock (2.957039ms)
38 +✔ read-only user can refresh a new visible graph without a write (2.321164ms)
39 +✔ valid same-revision JSON with different key order remains clean (2.49846ms)
40 +✔ complete graph above normal page size retains all lines and linked dimensions (19.324015ms)
41 +✔ context changed while queued rejects before sending graph request (8.065094ms)
42 +✔ unhydrated same-user tenant cannot capture old graph (2.283201ms)
43 +✖ failed writer drops pre-failure queued retry even when a graph refresh follows (4.826822ms)
44 +✔ a new explicit save queued during graph read still resumes after earlier writer failure (8.048777ms)
45 +✖ older same-tenant full read cannot overwrite a newer targeted graph publication (2.072151ms)
46 +ℹ tests 45
47 +ℹ suites 0
48 +ℹ pass 43
49 +ℹ fail 2
50 +ℹ cancelled 0
51 +ℹ skipped 0
52 +ℹ todo 0
53 +ℹ duration_ms 269.312717
54 +
55 +✖ failing tests:
56 +
57 +test at scripts/wp1-graph-reconcile-test.mjs:158:1
58 +✖ failed writer drops pre-failure queued retry even when a graph refresh follows (4.826822ms)
59 + AssertionError [ERR_ASSERTION]: An uncertain write cannot gain a retry timer from the read-only graph operation
60 +
61 + 1 !== 0
62 +
63 + at TestContext.<anonymous> (file:///workspace/Factor-easy-wp1/scripts/wp1-graph-reconcile-test.mjs:163:9)
64 + at async Test.run (node:internal/test_runner/test:1389:7)
65 + at async Test.processPendingSubtests (node:internal/test_runner/test:960:7) {
66 + generatedMessage: false,
67 + code: 'ERR_ASSERTION',
68 + actual: 1,
69 + expected: 0,
70 + operator: 'strictEqual',
71 + diff: 'simple'
72 + }
73 +
74 +test at scripts/wp1-graph-reconcile-test.mjs:173:1
75 +✖ older same-tenant full read cannot overwrite a newer targeted graph publication (2.072151ms)
76 + AssertionError [ERR_ASSERTION]: Missing expected rejection.
77 + at async TestContext.<anonymous> (file:///workspace/Factor-easy-wp1/scripts/wp1-graph-reconcile-test.mjs:177:34)
78 + at async Test.run (node:internal/test_runner/test:1389:7)
79 + at async Test.processPendingSubtests (node:internal/test_runner/test:960:7) {
80 + generatedMessage: false,
81 + code: 'ERR_ASSERTION',
82 + actual: undefined,
83 + expected: { code: 'FINORA_SYNC_CONTEXT_CHANGED' },
84 + operator: 'rejects',
85 + diff: 'simple'
86 + }
docs/wp1/evidence/graph-reconciliation/static-results.json new
+222
@@ -0,0 +1,222 @@
1 +[
2 + {
3 + "command": "node scripts/migration-manifest-check.mjs",
4 + "exit": 0
5 + },
6 + {
7 + "command": "node scripts/migration-manifest-test.mjs",
8 + "exit": 0
9 + },
10 + {
11 + "command": "node scripts/wp1-purchase-correction-guard-test.mjs",
12 + "exit": 0
13 + },
14 + {
15 + "command": "node --test scripts/wp1-client-capability-test.mjs scripts/wp1-graph-reconcile-test.mjs",
16 + "exit": 0
17 + },
18 + {
19 + "command": "node scripts/syntax-check.mjs",
20 + "exit": 0
21 + },
22 + {
23 + "command": "node scripts/public-qa-regression-check.mjs",
24 + "exit": 0
25 + },
26 + {
27 + "command": "python3 scripts/finora_local_backup_test.py -v",
28 + "exit": 0
29 + },
30 + {
31 + "command": "node scripts/quality-check.mjs",
32 + "exit": 0
33 + },
34 + {
35 + "command": "node scripts/finance-integrity-audit-test.mjs",
36 + "exit": 0
37 + },
38 + {
39 + "command": "node scripts/stripe-sandbox-readonly-test.mjs",
40 + "exit": 0
41 + },
42 + {
43 + "command": "node scripts/stripe-edge-sandbox-test.mjs",
44 + "exit": 0
45 + },
46 + {
47 + "command": "node scripts/kavenegar-otp-preflight-test.mjs",
48 + "exit": 0
49 + },
50 + {
51 + "command": "node scripts/commercial-rnd-check.mjs",
52 + "exit": 0
53 + },
54 + {
55 + "command": "node scripts/ux-hardening-r2-check.mjs",
56 + "exit": 0
57 + },
58 + {
59 + "command": "node scripts/accounting-product-guidance-check.mjs",
60 + "exit": 0
61 + },
62 + {
63 + "command": "node scripts/phase2-check.mjs",
64 + "exit": 0
65 + },
66 + {
67 + "command": "node scripts/chart-completeness-check.mjs",
68 + "exit": 0
69 + },
70 + {
71 + "command": "node scripts/phase3-check.mjs",
72 + "exit": 0
73 + },
74 + {
75 + "command": "node scripts/phase3-behavior-check.mjs",
76 + "exit": 0
77 + },
78 + {
79 + "command": "node scripts/accounting-p0-check.mjs",
80 + "exit": 0
81 + },
82 + {
83 + "command": "node scripts/phase4-behavior-check.mjs",
84 + "exit": 0
85 + },
86 + {
87 + "command": "node scripts/phase5-behavior-check.mjs",
88 + "exit": 0
89 + },
90 + {
91 + "command": "node scripts/enterprise-behavior-check.mjs",
92 + "exit": 0
93 + },
94 + {
95 + "command": "node scripts/phase6-behavior-check.mjs",
96 + "exit": 0
97 + },
98 + {
99 + "command": "node scripts/golden-accounting-core-check.mjs",
100 + "exit": 0
101 + },
102 + {
103 + "command": "node scripts/platform-office-check.mjs",
104 + "exit": 0
105 + },
106 + {
107 + "command": "node scripts/slice-b-rbac-check.mjs",
108 + "exit": 0
109 + },
110 + {
111 + "command": "node scripts/enterprise-license-check.mjs",
112 + "exit": 0
113 + },
114 + {
115 + "command": "node scripts/enterprise-role-check.mjs",
116 + "exit": 0
117 + },
118 + {
119 + "command": "node scripts/enterprise-invitation-check.mjs",
120 + "exit": 0
121 + },
122 + {
123 + "command": "node scripts/enterprise-org-ux-check.mjs",
124 + "exit": 0
125 + },
126 + {
127 + "command": "node scripts/identity-wave5a-check.mjs",
128 + "exit": 0
129 + },
130 + {
131 + "command": "node scripts/identity-wave5b-check.mjs",
132 + "exit": 0
133 + },
134 + {
135 + "command": "node scripts/identity-wave5c-check.mjs",
136 + "exit": 0
137 + },
138 + {
139 + "command": "node scripts/branding-login-check.mjs",
140 + "exit": 0
141 + },
142 + {
143 + "command": "node scripts/login-connectivity-check.mjs",
144 + "exit": 0
145 + },
146 + {
147 + "command": "node scripts/office-slice-c1-check.mjs",
148 + "exit": 0
149 + },
150 + {
151 + "command": "node scripts/office-slice-c2-check.mjs",
152 + "exit": 0
153 + },
154 + {
155 + "command": "node scripts/office-slice-c3-check.mjs",
156 + "exit": 0
157 + },
158 + {
159 + "command": "node scripts/office-slice-c4-check.mjs",
160 + "exit": 0
161 + },
162 + {
163 + "command": "node scripts/office-slice-c5-check.mjs",
164 + "exit": 0
165 + },
166 + {
167 + "command": "node scripts/office-slice-c6-check.mjs",
168 + "exit": 0
169 + },
170 + {
171 + "command": "node scripts/office-slice-c7-check.mjs",
172 + "exit": 0
173 + },
174 + {
175 + "command": "node scripts/office-slice-c8-check.mjs",
176 + "exit": 0
177 + },
178 + {
179 + "command": "node scripts/request-workflow-d1-check.mjs",
180 + "exit": 0
181 + },
182 + {
183 + "command": "node scripts/request-workflow-d1-transition-check.mjs",
184 + "exit": 0
185 + },
186 + {
187 + "command": "node scripts/request-workflow-d1-security-check.mjs",
188 + "exit": 0
189 + },
190 + {
191 + "command": "node scripts/request-workflow-d2-check.mjs",
192 + "exit": 0
193 + },
194 + {
195 + "command": "node scripts/request-workflow-d3b-check.mjs",
196 + "exit": 0
197 + },
198 + {
199 + "command": "node scripts/request-workflow-d3c-check.mjs",
200 + "exit": 0
201 + },
202 + {
203 + "command": "node scripts/request-workflow-d4a-check.mjs",
204 + "exit": 0
205 + },
206 + {
207 + "command": "node scripts/posting-idempotency-check.mjs",
208 + "exit": 0
209 + },
210 + {
211 + "command": "node scripts/admin-provisioning-contract.mjs",
212 + "exit": 0
213 + },
214 + {
215 + "command": "node --test scripts/admin-recovery-handler.spec.mjs",
216 + "exit": 0
217 + },
218 + {
219 + "command": "node scripts/release-safety-check.mjs",
220 + "exit": 0
221 + }
222 +]
\ No newline at end of file
index.html
+2 -2
@@ -937,7 +937,7 @@ body{background:#f6f9fc}
937 <script src="js/password-recovery.js?v=20261026-recovery-cancel-v2"></script>
938 <script src="js/core.js?v=20261110-account-read-v3"></script>
939 <script src="js/admin.js?v=20261028-central-password-reset-v1"></script>
940 -<script src="js/sync.js?v=20261103-versioned-sync-v1"></script>
940 +<script src="js/sync.js?v=20261111-journal-graph-v1"></script>
941 <script src="js/ui.js?v=20261031-workspace-recovery-v1"></script>
942 <script src="js/invoices.js?v=20261031-workspace-recovery-v1"></script>
943 <script src="js/print.js?v=20261012-clean-invoice-print-v1"></script>
@@ -948,7 +948,7 @@ body{background:#f6f9fc}
948 <script src="js/companies.js?v=20261028-company-edit-v1"></script>
949 <script src="js/backup.js?v=20260928-data-v3"></script>
950 <script src="js/words.js"></script>
951 -<script src="js/bootstrap.js?v=20261110-account-read-v3"></script>
951 +<script src="js/bootstrap.js?v=20261111-journal-graph-v1"></script>
952
953 <style>
954 .form-control, textarea, select { direction: rtl; }
js/bootstrap.js
+1 -1
@@ -3,7 +3,7 @@
3 // browsers may download in parallel but preserve script execution/dependencies.
4 // Auth starts only once all extensions have finished loading or failed.
5 const FINORA_EXTENSION_SCRIPTS=[
6 - "js/organization-rbac.js?v=20261110-organization-read-v2",
6 + "js/organization-rbac.js?v=20261111-versioned-graph-v1",
7 "js/organization-invitations.js?v=20261110-organization-read-v2",
8 "js/organization-enterprise-ux.js?v=20261110-organization-read-v2",
9 "js/platform-modules.js?v=20261031-workspace-recovery-v1",
js/sync.js
+142 -2
@@ -114,6 +114,144 @@ async function finoraWriteSyncBatch(up,del,c){
114 }
115 let syncTimer=null,syncRunning=false,syncAgain=false,syncPending=false,syncFailCount=0;
116
117 +// Journal refresh uses the same lock as normal saves. A waiter owns the lock
118 +// before it resumes; queued/late responses cannot publish into another context.
119 +const finoraGraphWaiters=[];
120 +function finoraReleaseSyncLock(){
121 + syncRunning=false;
122 + const next=finoraGraphWaiters.shift();
123 + if(next){syncRunning=true;next();}
124 +}
125 +function finoraAcquireGraphLock(){
126 + if(!syncRunning){syncRunning=true;return Promise.resolve();}
127 + return new Promise((resolve,reject)=>{
128 + let timer;
129 + const ready=()=>{clearTimeout(timer);resolve();};
130 + finoraGraphWaiters.push(ready);
131 + timer=setTimeout(()=>{
132 + const index=finoraGraphWaiters.indexOf(ready);
133 + if(index<0)return;
134 + finoraGraphWaiters.splice(index,1);reject(finoraSyncIssue('FINORA_GRAPH_BUSY'));
135 + },20000);
136 + });
137 +}
138 +const finoraJournalCollections=['journalVouchers','journalLines','journalLineDimensions'];
139 +function finoraJournalLocalState(voucherId){
140 + const rows=new Map(),snapRows=new Map();
141 + for(const coll of finoraJournalCollections){
142 + for(const row of datastore[coll]||[]){
143 + const key=coll+'|'+row.id;
144 + if(rows.has(key))throw finoraSyncIssue('FINORA_GRAPH_LOCAL_CHANGED');
145 + rows.set(key,{coll,row});
146 + }
147 + for(const [key,value] of syncSnap){
148 + if(key.startsWith(coll+'|'))snapRows.set(key,{coll,row:JSON.parse(value)});
149 + }
150 + }
151 + // Include old links as well as current ones: moving/deleting a local child
152 + // must not remove it from the dirty graph check.
153 + const all=[...rows.values(),...snapRows.values()];
154 + const lines=new Set(all.filter(x=>x.coll==='journalLines'&&x.row.voucherId===voucherId).map(x=>x.row.id));
155 + const keys=new Set(['journalVouchers|'+voucherId]);
156 + for(const [key,{coll,row}] of [...rows,...snapRows]){
157 + if((coll==='journalLines'&&row.voucherId===voucherId)||
158 + (coll==='journalLineDimensions'&&(row.voucherId===voucherId||lines.has(row.journalLineId))))keys.add(key);
159 + }
160 + const state=[...keys].sort().map(key=>{
161 + const item=rows.get(key)?.row;
162 + return [key,item?JSON.stringify(stripOwner(item)):null,item?.ownerUserId||null,syncSnap.get(key)??null,versionSnap.get(key)??null];
163 + });
164 + return {keys,rows,state,fingerprint:JSON.stringify(state)};
165 +}
166 +function finoraReadGraphView(readViewContext){
167 + const v=typeof readViewContext==='function'?readViewContext():null;
168 + if(!v||typeof v.companyId!=='string'||!ID_RE.test(v.companyId)||typeof v.formId!=='string'||!v.formId||!Number.isSafeInteger(v.editRevision)||v.editRevision<0)throw finoraSyncIssue('FINORA_GRAPH_VIEW_CHANGED');
169 + return {companyId:v.companyId,formId:v.formId,editRevision:v.editRevision};
170 +}
171 +function finoraCaptureJournalRefresh(voucherId,readViewContext){
172 + const context=finoraSyncContext();finoraAssertSyncSnapshot(context);
173 + if(!context.uid||!context.org||typeof voucherId!=='string'||!ID_RE.test(voucherId))throw finoraSyncIssue('FINORA_GRAPH_CONTEXT_REQUIRED');
174 + const view=finoraReadGraphView(readViewContext),local=finoraJournalLocalState(voucherId);
175 + for(const [,data,owner,snapshot,version] of local.state){
176 + if(data!==snapshot||(data!==null&&(owner!==context.uid||!finoraValidVersion(version))))throw finoraSyncIssue('FINORA_GRAPH_LOCAL_CHANGED');
177 + }
178 + const header=local.rows.get('journalVouchers|'+voucherId)?.row;
179 + if(header&&header.companyId!==view.companyId)throw finoraSyncIssue('FINORA_GRAPH_VIEW_CHANGED');
180 + return {context,voucherId,view,readViewContext,fingerprint:local.fingerprint};
181 +}
182 +function finoraAssertJournalRefresh(capture){
183 + finoraAssertSyncSnapshot(capture.context);
184 + if(JSON.stringify(finoraReadGraphView(capture.readViewContext))!==JSON.stringify(capture.view))throw finoraSyncIssue('FINORA_GRAPH_VIEW_CHANGED');
185 + const local=finoraJournalLocalState(capture.voucherId);
186 + if(local.fingerprint!==capture.fingerprint)throw finoraSyncIssue('FINORA_GRAPH_LOCAL_CHANGED');
187 + return local;
188 +}
189 +function finoraPrepareJournalGraph(graph,capture,local){
190 + const invalid=()=>{throw finoraSyncIssue('FINORA_GRAPH_INVALID');};
191 + if(!graph||graph.organization_id!==capture.context.org||graph.voucher_id!==capture.voucherId||!Array.isArray(graph.records))invalid();
192 + const staged=new Map();
193 + for(const record of graph.records){
194 + if(!record||!finoraJournalCollections.includes(record.collection)||typeof record.id!=='string'||!ID_RE.test(record.id)||!finoraValidVersion(record.version))invalid();
195 + const data=record.data,key=record.collection+'|'+record.id;
196 + if(!data||typeof data!=='object'||Array.isArray(data)||data.companyId!==capture.view.companyId||
197 + (data.id!==undefined&&data.id!==record.id)||Object.prototype.hasOwnProperty.call(data,'ownerUserId')||staged.has(key))invalid();
198 + if(record.collection==='journalVouchers'?record.id!==capture.voucherId:data.voucherId!==capture.voucherId)invalid();
199 + if(!local.keys.has(key)&&(local.rows.has(key)||syncSnap.has(key)||versionSnap.has(key)))invalid();
200 + const obj=JSON.parse(JSON.stringify(data));obj.id=record.id;
201 + const serialized=JSON.stringify(obj),oldVersion=versionSnap.get(key);
202 + if(oldVersion!==undefined&&(record.version<oldVersion||
203 + (record.version===oldVersion&&!finoraSameJournalData(obj,JSON.parse(syncSnap.get(key))))))invalid();
204 + staged.set(key,{collection:record.collection,data:{...obj,ownerUserId:capture.context.uid},serialized,version:record.version});
205 + }
206 + const header=staged.get('journalVouchers|'+capture.voucherId)?.data;
207 + if(!header||!['draft','posted','reversed'].includes(header.status))invalid();
208 + const statuses=header.status==='posted'&&header.sourceType!=='reversal'?['posted','partially_reversed','reversed']:[header.status];
209 + if(!statuses.includes(graph.effective_status))invalid();
210 + for(const row of staged.values()){
211 + if(row.collection==='journalLineDimensions'&&!staged.has('journalLines|'+row.data.journalLineId))invalid();
212 + }
213 + const arrays={};
214 + for(const coll of finoraJournalCollections){
215 + arrays[coll]=(datastore[coll]||[]).filter(row=>!local.keys.has(coll+'|'+row.id));
216 + for(const row of staged.values())if(row.collection===coll)arrays[coll].push(row.data);
217 + }
218 + return {staged,arrays};
219 +}
220 +function finoraSameJournalData(a,b){
221 + // JSON object key order is not part of the PostgREST record value.
222 + if(a===b)return true;
223 + if(!a||!b||typeof a!=='object'||typeof b!=='object'||Array.isArray(a)!==Array.isArray(b))return false;
224 + const keys=Object.keys(a);
225 + return keys.length===Object.keys(b).length&&keys.every(k=>Object.prototype.hasOwnProperty.call(b,k)&&finoraSameJournalData(a[k],b[k]));
226 +}
227 +async function finoraRefreshJournalGraph(capture){
228 + finoraAssertJournalRefresh(capture);
229 + await finoraAcquireGraphLock();
230 + try{
231 + finoraAssertJournalRefresh(capture);
232 + let response;
233 + try{response=await finoraBoundedSyncRequest(sb.rpc('finora_journal_read_graph',{
234 + p_organization_id:capture.context.org,p_voucher_id:capture.voucherId
235 + }),'FINORA_GRAPH_READ_TIMEOUT');}
236 + catch(error){throw finoraSyncIssue('FINORA_GRAPH_READ_UNAVAILABLE');}
237 + const local=finoraAssertJournalRefresh(capture);
238 + if(!response||response.error!==null)throw finoraSyncIssue('FINORA_GRAPH_READ_UNAVAILABLE');
239 + const prepared=finoraPrepareJournalGraph(response.data,capture,local);
240 + // No await or callbacks after validation: publish this graph and its ACKs
241 + // together. Unrelated arrays/objects, dirty snapshots and timer survive.
242 + for(const coll of finoraJournalCollections)datastore[coll]=prepared.arrays[coll];
243 + for(const key of local.keys){syncSnap.delete(key);versionSnap.delete(key);}
244 + for(const [key,row] of prepared.staged){syncSnap.set(key,row.serialized);versionSnap.set(key,row.version);}
245 + finoraVersionedTenants.add(finoraTenantKey(capture.context));
246 + // Invalidate full reads already in flight: they contain an older graph.
247 + finoraSyncGeneration++;
248 + return {voucherId:capture.voucherId,effectiveStatus:response.data.effective_status};
249 + }finally{
250 + finoraReleaseSyncLock();
251 + if(syncAgain&&!syncRunning){syncAgain=false;scheduleSync(0);}
252 + }
253 +}
254 +
255 function keyOfRecord(coll,item){return coll==='settings'?'main':String(item&&item.id!=null?item.id:'');}
256 function stripOwner(item){const c=Object.assign({},item);delete c.ownerUserId;return c;}
257 function setSyncBadge(state){
@@ -192,7 +330,7 @@ async function runSync(){
330 await handleSyncError(err);
331 }
332 }finally{
195 - syncRunning=false;
333 + finoraReleaseSyncLock();
334 // A newer account/snapshot may have queued its save behind this request.
335 // Release that work only after the stale request relinquishes the lock;
336 // same-context uncertain/conflicting writes must not gain an automatic retry.
@@ -206,7 +344,9 @@ async function runSync(){
344 }
345 async function handleSyncError(err){
346 if(err?.finoraPreservePending||err?.code==='40001'){
209 - clearTimeout(syncTimer);syncPending=true;syncFailCount=0;setSyncBadge('conflict');
347 + // A request queued before this uncertain outcome is not a new retry intent.
348 + // Explicit saves arriving after this point may queue normally.
349 + clearTimeout(syncTimer);syncAgain=false;syncPending=true;syncFailCount=0;setSyncBadge('conflict');
350 const conflict=err.code==='FINORA_SYNC_VERSION_CONFLICT'||err.code==='40001';
351 alert(conflict?'این اطلاعات هم‌زمان تغییر کرده است؛ ویرایش شما حفظ شد ولی ذخیره نشد. پیش از بارگذاری مجدد، تغییرات را برای مقایسه نگه دارید.':'ذخیره روی سرور تأیید نشد؛ ویرایش شما در این صفحه حفظ شده است. پیش از خروج یا بارگذاری مجدد، تغییرات را نگه دارید و اتصال و وضعیت ذخیره را بررسی کنید.');
352 return;
scripts/login-connectivity-check.mjs
+1 -1
@@ -9,7 +9,7 @@ assert(html.includes('id="auth-connectivity-result" aria-live="polite"'),'Diagno
9 assert(html.includes('js/login-connectivity.js?v=20261110-login-bootstrap-v6'),'Missing versioned script');
10 assert(html.includes('js/core.js?v=20261110-account-read-v3'),'Production login controls must use new cache version');
11 assert(html.indexOf('<script src="js/login-connectivity.js?v=20261110-login-bootstrap-v6"')<html.indexOf('<script src="js/core.js?v=20261110-account-read-v3"'),'Connectivity handler script must execute before core (not just preload)');
12 -assert(html.includes('js/bootstrap.js?v=20261110-account-read-v3'),'Parallel bootstrap must also be cache-busted');
12 +assert(html.includes('js/bootstrap.js?v=20261111-journal-graph-v1'),'Parallel bootstrap must also be cache-busted');
13 assert(html.includes('id="auth-login-button"')&&html.includes('id="auth-login-status"'),'Login control requires real readiness/progress feedback');
14 assert(core.includes('window.FinoraAppAssetsReady'),'Authenticated workspace must remain gated until all module scripts settle');
15 assert(core.includes('window.FinoraOrganizationContextReady')&&core.includes('organizationAccount'),'Profile and license lookup must wait for the organization account adapter');
scripts/wp1-client-sync.spec.js
+39
@@ -88,3 +88,42 @@ test('identity refresh during a save ends with an unconfirmed badge and retained
88 await expect(page.locator('#sync-badge')).toContainText('ذخیره تأیید نشد');
89 expect(await page.evaluate(()=>({pending:syncPending,name:datastore.companies[0].name,version:versionSnap.get('companies|QA_CO')}))).toEqual({pending:true,name:'not acknowledged',version:4});
90 });
91 +
92 +for(const outcome of ['merge','form-changed'])test(`journal graph ${outcome} preserves unrelated unsaved edits in real runtime`,async({page})=>{
93 + await fixture(page);
94 + const result=await page.evaluate(async outcome=>{
95 + __syncQA.rows.push({collection:'journalVouchers',id:'V',version:2,data:{id:'V',companyId:'QA_CO',status:'draft',description:'old'}});
96 + await pullAll();
97 + datastore.companies[0].name='unsaved';syncPending=true;scheduleSync(60000);
98 + const timer=syncTimer,company=datastore.companies[0];
99 + const view={companyId:'QA_CO',formId:'F',editRevision:0};
100 + const captured=finoraCaptureJournalRefresh('V',()=>view);
101 + sb.rpc=async(name,args)=>{
102 + __syncQA.calls.push({name,args});
103 + if(outcome==='form-changed')view.editRevision++;
104 + return {error:null,data:{organization_id:'QA_ORG',voucher_id:'V',effective_status:'partially_reversed',records:[{collection:'journalVouchers',id:'V',version:3,data:{id:'V',companyId:'QA_CO',status:'posted',description:'server'}}]}};
105 + };
106 + let status=null,error=null;
107 + try{status=(await finoraRefreshJournalGraph(captured)).effectiveStatus;}catch(e){error=e.code;}
108 + const response={status,error,description:datastore.journalVouchers.find(x=>x.id==='V').description,pending:syncPending,preserved:datastore.companies[0]===company&&syncTimer===timer,dirty:computeDiff().up.map(x=>x.key),rpc:__syncQA.calls.map(x=>x.name)};
109 + clearTimeout(syncTimer);return response;
110 + },outcome);
111 + expect(result).toEqual({status:outcome==='merge'?'partially_reversed':null,error:outcome==='merge'?null:'FINORA_GRAPH_VIEW_CHANGED',description:outcome==='merge'?'server':'old',pending:true,preserved:true,dirty:['companies|QA_CO'],rpc:['finora_journal_read_graph']});
112 +});
113 +
114 +test('organization hydration begun before graph refresh cannot overwrite its newer revision',async({page})=>{
115 + await fixture(page);
116 + const result=await page.evaluate(async()=>{
117 + __syncQA.rows.push({collection:'journalVouchers',id:'V',version:2,data:{id:'V',companyId:'QA_CO',status:'draft',description:'old'}});
118 + await pullAll();
119 + const original=sb.from;let release;
120 + const gate=new Promise(resolve=>release=resolve);
121 + sb.from=()=>{const q=original();q.range=async()=>{const data=JSON.parse(JSON.stringify(__syncQA.rows));await gate;return {error:null,data};};return q;};
122 + const pending=pullAll().then(()=>null,e=>e.code);
123 + sb.rpc=async()=>({error:null,data:{organization_id:'QA_ORG',voucher_id:'V',effective_status:'posted',records:[{collection:'journalVouchers',id:'V',version:3,data:{id:'V',companyId:'QA_CO',status:'posted',description:'new'}}]}});
124 + await finoraRefreshJournalGraph(finoraCaptureJournalRefresh('V',()=>({companyId:'QA_CO',formId:'F',editRevision:0})));
125 + release();const error=await pending;
126 + return {error,version:versionSnap.get('journalVouchers|V'),description:datastore.journalVouchers.find(x=>x.id==='V').description};
127 + });
128 + expect(result).toEqual({error:'FINORA_SYNC_CONTEXT_CHANGED',version:3,description:'new'});
129 +});
scripts/wp1-graph-reconcile-test.mjs new
+180
@@ -0,0 +1,180 @@
1 +import fs from 'node:fs';
2 +import vm from 'node:vm';
3 +import assert from 'node:assert/strict';
4 +import test from 'node:test';
5 +
6 +// Real synchronization code; only the network, clock and page boundary are simulated.
7 +// Removing targeted publication or the context/dirty guards must break these tests.
8 +function fixture(){
9 + const rows=[
10 + {collection:'companies',id:'C',version:4,data:{id:'C',name:'company'}},
11 + {collection:'journalVouchers',id:'V',version:2,data:{id:'V',companyId:'C',status:'draft',description:'old'}},
12 + {collection:'journalLines',id:'L',version:2,data:{id:'L',companyId:'C',voucherId:'V',debit:100,credit:0}},
13 + {collection:'journalLineDimensions',id:'D',version:2,data:{id:'D',companyId:'C',voucherId:'V',journalLineId:'L',dimensionValueId:'X'}},
14 + {collection:'journalVouchers',id:'OTHER',version:1,data:{id:'OTHER',companyId:'C',status:'draft'}}
15 + ];
16 + const graph={organization_id:'O',voucher_id:'V',effective_status:'posted',records:[
17 + {collection:'journalVouchers',id:'V',version:3,data:{id:'V',companyId:'C',status:'posted',description:'server'}},
18 + {collection:'journalLines',id:'L2',version:1,data:{id:'L2',companyId:'C',voucherId:'V',debit:200,credit:0}}
19 + ]};
20 + let view={companyId:'C',formId:'F',editRevision:0},nextTimer=0;
21 + const timers=new Map(),calls=[];
22 + const state={rows,graph,hook:null,error:null};
23 + const c={console:{error(){},warn(){}},Map,Set,JSON,Promise,Number,String,Array,Date,Math,
24 + setTimeout(fn,ms){const id=++nextTimer;timers.set(id,{fn,ms});return id;},clearTimeout(id){timers.delete(id);},
25 + currentUser:{id:'U',organizationId:'O'},COLLS:['companies','journalVouchers','journalLines','journalLineDimensions'],ID_RE:/^[A-Za-z0-9_-]+$/,
26 + document:{getElementById:()=>null,addEventListener(){}},canWrite:()=>true,requireWrite:()=>true,refreshAllSurfaces(){},alert(){},finoraAbortableRead:async p=>p};
27 + c.window=c;c.addEventListener=()=>{};
28 + c.sb={from(){const q={select(){return q;},order(){return q;},range:async()=>({error:null,data:structuredClone(state.rows)})};return q;},
29 + async rpc(name,args){calls.push({name,args});if(state.hook)await state.hook(name,args);
30 + if(name==='finora_journal_read_graph')return {error:state.error,data:structuredClone(state.graph)};
31 + if(name==='finora_journal_get_guard_mode')return {error:null,data:'audit'};
32 + return {error:null,data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:args.p_deletes}};
33 + }};
34 + vm.createContext(c);vm.runInContext(fs.readFileSync(process.env.FINORA_SYNC_SOURCE||'js/sync.js','utf8'),c);
35 + const run=s=>vm.runInContext(s,c),capture=(id='V')=>c.finoraCaptureJournalRefresh(id,()=>view);
36 + return {c,state,calls,timers,run,capture,setView:v=>{view={...view,...v};},snapshot:()=>run('JSON.stringify({datastore,snap:[...syncSnap],versions:[...versionSnap]})')};
37 +}
38 +const tick=()=>new Promise(r=>setImmediate(r));
39 +function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}
40 +async function prepared(){const f=fixture();await f.c.pullAll();return f;}
41 +async function refresh(f){return f.c.finoraRefreshJournalGraph(f.capture());}
42 +
43 +test('targeted refresh replaces only its graph and acknowledges versions without syncing display status',async()=>{
44 + const f=await prepared();f.state.graph.effective_status='partially_reversed';
45 + const result=await refresh(f);
46 + assert.equal(result.effectiveStatus,'partially_reversed');
47 + assert.equal(f.run("datastore.journalVouchers.find(r=>r.id==='V').status"),'posted');
48 + assert.equal(f.run('datastore.journalLines[0].id'),'L2');
49 + assert.equal(f.run('datastore.journalLineDimensions.length'),0);
50 + assert.equal(f.run("versionSnap.get('journalVouchers|V')"),3);
51 + assert.equal(f.run("syncSnap.has('journalLines|L')"),false);
52 + assert.equal(f.run("versionSnap.has('journalLineDimensions|D')"),false);
53 + assert.equal(f.run('computeDiff().up.length+computeDiff().del.length'),0);
54 + assert.deepEqual(f.calls.map(x=>x.name),['finora_journal_read_graph']);
55 +});
56 +test('unrelated dirty objects, deletion, pending state and save timer survive graph publication',async()=>{
57 + const f=await prepared();f.run("datastore.companies[0].name='unsaved';datastore.journalVouchers=datastore.journalVouchers.filter(r=>r.id!=='OTHER');saveDatastore();globalThis.keepCompany=datastore.companies;globalThis.keepObject=datastore.companies[0];globalThis.keepTimer=syncTimer");
58 + await refresh(f);
59 + assert.equal(f.run('datastore.companies===keepCompany&&datastore.companies[0]===keepObject&&syncTimer===keepTimer&&syncPending'),true);
60 + assert.equal(f.run('computeDiff().up[0].payload.name'),'unsaved');
61 + assert.equal(f.run('computeDiff().del[0]'),'journalVouchers|OTHER');
62 + assert.equal(f.timers.get(f.run('syncTimer')).ms,300);
63 +});
64 +for(const edit of ["datastore.journalVouchers[0].description='local'","datastore.journalLines=[]","datastore.journalLines[0].voucherId='OTHER'","datastore.journalLineDimensions[0].journalLineId='bad'"]){
65 + test('initial dirty graph rejects without network: '+edit,async()=>{
66 + const f=await prepared();f.run(edit);const before=f.snapshot();
67 + await assert.rejects(async()=>refresh(f),{code:'FINORA_GRAPH_LOCAL_CHANGED'});
68 + assert.equal(f.snapshot(),before);assert.equal(f.calls.length,0);
69 + });
70 +}
71 +for(const [code,change] of [
72 + ['FINORA_GRAPH_LOCAL_CHANGED',f=>f.run("datastore.journalLines[0].debit=101")],
73 + ['FINORA_GRAPH_LOCAL_CHANGED',f=>f.run("datastore.journalLines.push({id:'NEW',ownerUserId:'U',companyId:'C',voucherId:'V',debit:20})")],
74 + ['FINORA_GRAPH_VIEW_CHANGED',f=>f.setView({companyId:'C2'})],['FINORA_GRAPH_VIEW_CHANGED',f=>f.setView({formId:'F2'})],['FINORA_GRAPH_VIEW_CHANGED',f=>f.setView({editRevision:1})],
75 + ['FINORA_SYNC_CONTEXT_CHANGED',f=>{f.c.currentUser.organizationId='OTHER';}],['FINORA_SYNC_CONTEXT_CHANGED',f=>{f.c.currentUser={id:'U',organizationId:'O'};}],
76 + ['FINORA_SYNC_CONTEXT_CHANGED',f=>f.c.pullAll()]
77 +])test('in-flight local/view/account/snapshot change rejects atomic publication #'+change.toString(),async()=>{
78 + const f=await prepared();f.state.hook=async name=>{if(name==='finora_journal_read_graph')await change(f);};
79 + const p=refresh(f);await assert.rejects(p,{code});assert.notEqual(f.run("datastore.journalVouchers.find(r=>r.id==='V').description"),'server');
80 + assert.equal(f.run('syncRunning'),false);
81 +});
82 +for(const [name,mutate] of [
83 + ['null',f=>f.state.graph=null],['wrong tenant',f=>f.state.graph.organization_id='OTHER'],
84 + ['wrong voucher',f=>f.state.graph.voucher_id='OTHER'],['no header',f=>f.state.graph.records.shift()],
85 + ['duplicate',f=>f.state.graph.records.push(f.state.graph.records[0])],
86 + ['foreign collection',f=>f.state.graph.records[1].collection='companies'],
87 + ['unsafe version',f=>f.state.graph.records[0].version=Number.MAX_SAFE_INTEGER],
88 + ['regressed version',f=>f.state.graph.records[0].version=1],
89 + ['same revision altered payload',f=>f.state.graph.records[0].version=2],
90 + ['wrong company',f=>f.state.graph.records[1].data.companyId='C2'],
91 + ['wrong parent',f=>f.state.graph.records[1].data.voucherId='OTHER'],
92 + ['bad ID',f=>f.state.graph.records[1].id='bad|id'],
93 + ['mismatched data ID',f=>f.state.graph.records[1].data.id='bad'],
94 + ['invalid status',f=>f.state.graph.effective_status='success'],
95 + ['draft reversed status',f=>{f.state.graph.records[0].data.status='draft';f.state.graph.effective_status='reversed';}],
96 + ['orphan dimension',f=>f.state.graph.records.push({collection:'journalLineDimensions',id:'D2',version:1,data:{id:'D2',companyId:'C',voucherId:'V',journalLineId:'missing'}})],
97 + ['collision',f=>{f.state.graph.records[1].id='COLLIDE';f.state.graph.records[1].data.id='COLLIDE';f.run("datastore.journalLines.push({id:'COLLIDE',ownerUserId:'U',companyId:'C',voucherId:'OTHER'})");}],
98 + ['error',f=>f.state.error={code:'42501',message:'private server details'}]
99 +])test('malformed or unauthorized graph preserves all arrays and snapshots: '+name,async()=>{
100 + const f=await prepared();mutate(f);const before=f.snapshot();
101 + await assert.rejects(refresh(f),{code:name==='error'?'FINORA_GRAPH_READ_UNAVAILABLE':'FINORA_GRAPH_INVALID'});assert.equal(f.snapshot(),before);assert.equal(f.run('syncRunning'),false);
102 +});
103 +test('normal sync waits for refresh and sends only unrelated dirty records',async()=>{
104 + const f=await prepared(),gate=deferred();f.state.hook=name=>name==='finora_journal_read_graph'?gate.promise:undefined;
105 + const p=refresh(f);await tick();f.run("datastore.companies[0].name='pending'");await f.c.runSync();
106 + assert.deepEqual(f.calls.map(x=>x.name),['finora_journal_read_graph']);
107 + gate.resolve();await p;const timer=f.timers.get(f.run('syncTimer'));assert.equal(timer.ms,0);await timer.fn();
108 + const write=f.calls.find(x=>x.name==='finora_sync_records_v2');assert.equal(write.args.p_upserts.length,1);assert.equal(write.args.p_upserts[0].collection,'companies');
109 +});
110 +test('refresh queues behind an existing normal save',async()=>{
111 + const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");
112 + f.state.hook=name=>name==='finora_sync_records_v2'?gate.promise:undefined;
113 + const sync=f.c.runSync();await tick();const graph=refresh(f);await tick();
114 + assert.equal(f.calls.some(x=>x.name==='finora_journal_read_graph'),false);
115 + gate.resolve();await sync;await graph;assert.equal(f.run("datastore.journalVouchers.find(r=>r.id==='V').description"),'server');
116 +});
117 +test('second captured refresh rejects after first graph changes, without a second request',async()=>{
118 + const f=await prepared(),gate=deferred();f.state.hook=()=>gate.promise;
119 + const a=refresh(f);await tick();const b=refresh(f);const reject=assert.rejects(b,{code:'FINORA_SYNC_CONTEXT_CHANGED'});
120 + gate.resolve();await a;await reject;assert.equal(f.calls.length,1);
121 +});
122 +test('request timeout releases lock and a late graph cannot publish',async()=>{
123 + const f=await prepared(),gate=deferred();f.state.hook=()=>gate.promise;const before=f.snapshot();
124 + const p=refresh(f);const rejection=assert.rejects(p,{code:'FINORA_GRAPH_READ_UNAVAILABLE'});await tick();
125 + for(const t of [...f.timers.values()])if(t.ms===20000)t.fn();await rejection;
126 + gate.resolve();await tick();assert.equal(f.snapshot(),before);assert.equal(f.run('syncRunning'),false);
127 +});
128 +test('queued refresh timeout does not steal active writer lock',async()=>{
129 + const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");f.state.hook=name=>name==='finora_sync_records_v2'?gate.promise:undefined;
130 + const sync=f.c.runSync();await tick();const p=refresh(f);const rejection=assert.rejects(p,{code:'FINORA_GRAPH_BUSY'});await tick();
131 + const last=[...f.timers.values()].at(-1);last.fn();await rejection;
132 + assert.equal(f.run('syncRunning'),true);gate.resolve();await sync;assert.equal(f.calls.some(x=>x.name==='finora_journal_read_graph'),false);
133 +});
134 +test('read-only user can refresh a new visible graph without a write',async()=>{
135 + const f=await prepared();f.c.canWrite=()=>false;f.state.graph.voucher_id='NEW';f.state.graph.records=f.state.graph.records.slice(0,1);f.state.graph.records[0].id='NEW';f.state.graph.records[0].data.id='NEW';
136 + await f.c.finoraRefreshJournalGraph(f.capture('NEW'));assert.equal(f.run('datastore.journalVouchers.length'),3);assert.equal(f.calls.length,1);
137 +});
138 +test('valid same-revision JSON with different key order remains clean',async()=>{
139 + const f=await prepared();f.state.graph.effective_status='draft';f.state.graph.records=structuredClone(f.state.rows.filter(r=>r.id!=='C'&&r.id!=='OTHER'));
140 + f.state.graph.records[0].data={description:'old',status:'draft',companyId:'C',id:'V'};
141 + await refresh(f);assert.equal(f.run('computeDiff().up.length+computeDiff().del.length'),0);
142 +});
143 +test('complete graph above normal page size retains all lines and linked dimensions',async()=>{
144 + const f=await prepared();f.state.graph.records=f.state.graph.records.slice(0,1);
145 + for(let n=0;n<1001;n++)f.state.graph.records.push({collection:'journalLines',id:'N'+n,version:1,data:{companyId:'C',voucherId:'V',debit:n+1,credit:0}});
146 + f.state.graph.records.push({collection:'journalLineDimensions',id:'D2',version:1,data:{companyId:'C',voucherId:'V',journalLineId:'N1000'}});
147 + await refresh(f);assert.equal(f.run('datastore.journalLines.length'),1001);assert.equal(f.run("versionSnap.get('journalLines|N1000')"),1);assert.equal(f.run('datastore.journalLineDimensions[0].journalLineId'),'N1000');assert.equal(f.run('computeDiff().up.length+computeDiff().del.length'),0);
148 +});
149 +test('context changed while queued rejects before sending graph request',async()=>{
150 + const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");f.state.hook=name=>name==='finora_sync_records_v2'?gate.promise:undefined;
151 + const sync=f.c.runSync();await tick();const graph=refresh(f);const rejected=assert.rejects(graph,{code:'FINORA_GRAPH_VIEW_CHANGED'});f.setView({editRevision:1});gate.resolve();await sync;await rejected;
152 + assert.equal(f.calls.some(x=>x.name==='finora_journal_read_graph'),false);assert.equal(f.run('syncRunning'),false);
153 +});
154 +test('unhydrated same-user tenant cannot capture old graph',async()=>{
155 + const f=await prepared();f.c.currentUser.organizationId='OTHER';const before=f.snapshot();await assert.rejects(async()=>refresh(f),{code:'FINORA_SYNC_SNAPSHOT_REQUIRED'});assert.equal(f.snapshot(),before);assert.equal(f.calls.length,0);
156 +});
157 +
158 +test('failed writer drops pre-failure queued retry even when a graph refresh follows',async()=>{
159 + const f=await prepared(),gate=deferred();f.run("datastore.companies[0].name='pending'");
160 + let writes=0;f.state.hook=async name=>{if(name==='finora_sync_records_v2'){writes++;await gate.promise;throw new Error('transport lost');}};
161 + const sync=f.c.runSync();await tick();await f.c.runSync();const graph=refresh(f);await tick();
162 + gate.resolve();await sync;await graph;
163 + assert.equal(f.timers.size,0,'An uncertain write cannot gain a retry timer from the read-only graph operation');
164 + assert.equal(writes,1);assert.equal(f.run('syncPending'),true);assert.equal(f.run('computeDiff().up[0].payload.name'),'pending');
165 +});
166 +test('a new explicit save queued during graph read still resumes after earlier writer failure',async()=>{
167 + const f=await prepared(),writeGate=deferred(),readGate=deferred();f.run("datastore.companies[0].name='pending'");
168 + f.state.hook=async name=>{if(name==='finora_sync_records_v2'){await writeGate.promise;throw new Error('transport lost');}if(name==='finora_journal_read_graph')await readGate.promise;};
169 + const sync=f.c.runSync();await tick();const graph=refresh(f);writeGate.resolve();await sync;await tick();
170 + await f.c.runSync();readGate.resolve();await graph;
171 + assert.equal(f.timers.get(f.run('syncTimer')).ms,0);
172 +});
173 +test('older same-tenant full read cannot overwrite a newer targeted graph publication',async()=>{
174 + const f=await prepared(),gate=deferred();const original=f.c.sb.from;
175 + f.c.sb.from=()=>{const q=original();q.range=async()=>{const old=structuredClone(f.state.rows);await gate.promise;return {error:null,data:old};};return q;};
176 + const pull=f.c.pullAll();const rejected=assert.rejects(pull,{code:'FINORA_SYNC_CONTEXT_CHANGED'});
177 + await refresh(f);gate.resolve();await rejected;
178 + assert.equal(f.run("versionSnap.get('journalVouchers|V')"),3);
179 + assert.equal(f.run("datastore.journalVouchers.find(r=>r.id==='V').description"),'server');
180 +});