mustflow 2.39.1 → 2.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/cli/commands/run/executor.js +16 -0
  2. package/dist/cli/commands/run/process-tree.js +6 -3
  3. package/dist/cli/commands/tech.js +60 -4
  4. package/dist/cli/commands/verify.js +3 -1
  5. package/dist/cli/lib/git-changes.js +11 -1
  6. package/dist/cli/lib/i18n.js +1 -1
  7. package/dist/cli/lib/local-index/index.js +8 -4
  8. package/dist/cli/lib/local-index/populate.js +17 -3
  9. package/dist/cli/lib/local-index/search-read-model.js +9 -7
  10. package/dist/cli/lib/local-index/search-text.js +2 -2
  11. package/dist/cli/lib/local-index/workflow-documents.js +17 -2
  12. package/dist/cli/lib/mustflow-read.js +14 -2
  13. package/dist/cli/lib/npm-version-check.js +36 -0
  14. package/dist/cli/lib/repo-map.js +16 -3
  15. package/dist/cli/lib/templates.js +8 -7
  16. package/dist/cli/lib/validation/constants.js +1 -1
  17. package/dist/core/active-run-locks.js +78 -20
  18. package/dist/core/change-classification.js +4 -0
  19. package/dist/core/command-contract-rules.js +1 -1
  20. package/dist/core/command-contract-validation.js +1 -1
  21. package/dist/core/command-cwd.js +13 -2
  22. package/dist/core/command-effects.js +22 -4
  23. package/dist/core/command-env.js +8 -6
  24. package/dist/core/command-preconditions.js +28 -2
  25. package/dist/core/completion-verdict.js +1 -1
  26. package/dist/core/line-endings.js +8 -4
  27. package/dist/core/safe-filesystem.js +9 -1
  28. package/dist/core/source-anchor-validation.js +7 -1
  29. package/dist/core/source-anchors.js +8 -2
  30. package/dist/core/verification-scheduler.js +8 -2
  31. package/package.json +1 -1
  32. package/templates/default/i18n.toml +330 -1
  33. package/templates/default/locales/en/.mustflow/skills/INDEX.md +302 -5
  34. package/templates/default/locales/en/.mustflow/skills/agent-eval-integrity-review/SKILL.md +160 -0
  35. package/templates/default/locales/en/.mustflow/skills/agent-execution-control-review/SKILL.md +163 -0
  36. package/templates/default/locales/en/.mustflow/skills/ai-generated-code-hardening/SKILL.md +49 -13
  37. package/templates/default/locales/en/.mustflow/skills/api-access-control-review/SKILL.md +298 -0
  38. package/templates/default/locales/en/.mustflow/skills/api-misuse-resistance-review/SKILL.md +297 -0
  39. package/templates/default/locales/en/.mustflow/skills/api-request-performance-review/SKILL.md +189 -0
  40. package/templates/default/locales/en/.mustflow/skills/app-startup-performance-review/SKILL.md +309 -0
  41. package/templates/default/locales/en/.mustflow/skills/backend-log-evidence-review/SKILL.md +213 -0
  42. package/templates/default/locales/en/.mustflow/skills/business-rule-leakage-review/SKILL.md +295 -0
  43. package/templates/default/locales/en/.mustflow/skills/cache-integrity-review/SKILL.md +291 -0
  44. package/templates/default/locales/en/.mustflow/skills/change-blast-radius-review/SKILL.md +297 -0
  45. package/templates/default/locales/en/.mustflow/skills/client-bundle-pruning-review/SKILL.md +160 -0
  46. package/templates/default/locales/en/.mustflow/skills/cloud-cost-guardrail-review/SKILL.md +321 -0
  47. package/templates/default/locales/en/.mustflow/skills/concurrency-invariant-review/SKILL.md +193 -0
  48. package/templates/default/locales/en/.mustflow/skills/core-web-vitals-field-review/SKILL.md +161 -0
  49. package/templates/default/locales/en/.mustflow/skills/credit-ledger-integrity-review/SKILL.md +156 -0
  50. package/templates/default/locales/en/.mustflow/skills/database-json-modeling-review/SKILL.md +171 -0
  51. package/templates/default/locales/en/.mustflow/skills/database-lock-contention-review/SKILL.md +192 -0
  52. package/templates/default/locales/en/.mustflow/skills/database-migration-change/SKILL.md +76 -34
  53. package/templates/default/locales/en/.mustflow/skills/database-query-bottleneck-review/SKILL.md +194 -0
  54. package/templates/default/locales/en/.mustflow/skills/deletion-lifecycle-review/SKILL.md +171 -0
  55. package/templates/default/locales/en/.mustflow/skills/deployment-rollout-safety-review/SKILL.md +321 -0
  56. package/templates/default/locales/en/.mustflow/skills/desktop-auto-update-safety-review/SKILL.md +265 -0
  57. package/templates/default/locales/en/.mustflow/skills/desktop-background-process-stability-review/SKILL.md +318 -0
  58. package/templates/default/locales/en/.mustflow/skills/desktop-memory-footprint-review/SKILL.md +318 -0
  59. package/templates/default/locales/en/.mustflow/skills/error-message-integrity-review/SKILL.md +283 -0
  60. package/templates/default/locales/en/.mustflow/skills/failure-integrity-review/SKILL.md +193 -0
  61. package/templates/default/locales/en/.mustflow/skills/file-upload-security-review/SKILL.md +305 -0
  62. package/templates/default/locales/en/.mustflow/skills/frame-render-performance-review/SKILL.md +159 -0
  63. package/templates/default/locales/en/.mustflow/skills/frontend-accessibility-tree-review/SKILL.md +202 -0
  64. package/templates/default/locales/en/.mustflow/skills/frontend-localization-review/SKILL.md +202 -0
  65. package/templates/default/locales/en/.mustflow/skills/frontend-state-ownership-review/SKILL.md +183 -0
  66. package/templates/default/locales/en/.mustflow/skills/frontend-stress-layout-review/SKILL.md +193 -0
  67. package/templates/default/locales/en/.mustflow/skills/hot-path-performance-review/SKILL.md +159 -0
  68. package/templates/default/locales/en/.mustflow/skills/idempotency-integrity-review/SKILL.md +195 -0
  69. package/templates/default/locales/en/.mustflow/skills/image-delivery-performance-review/SKILL.md +161 -0
  70. package/templates/default/locales/en/.mustflow/skills/incident-triage-review/SKILL.md +185 -0
  71. package/templates/default/locales/en/.mustflow/skills/llm-hallucination-control-review/SKILL.md +155 -0
  72. package/templates/default/locales/en/.mustflow/skills/llm-response-latency-review/SKILL.md +155 -0
  73. package/templates/default/locales/en/.mustflow/skills/llm-service-ux-review/SKILL.md +2 -0
  74. package/templates/default/locales/en/.mustflow/skills/llm-token-cost-control-review/SKILL.md +155 -0
  75. package/templates/default/locales/en/.mustflow/skills/low-end-device-support-review/SKILL.md +340 -0
  76. package/templates/default/locales/en/.mustflow/skills/memory-lifetime-review/SKILL.md +169 -0
  77. package/templates/default/locales/en/.mustflow/skills/mobile-energy-efficiency-review/SKILL.md +329 -0
  78. package/templates/default/locales/en/.mustflow/skills/module-boundary-review/SKILL.md +278 -0
  79. package/templates/default/locales/en/.mustflow/skills/multi-agent-work-coordination/SKILL.md +1 -0
  80. package/templates/default/locales/en/.mustflow/skills/observability-debuggability-review/SKILL.md +208 -0
  81. package/templates/default/locales/en/.mustflow/skills/payment-integrity-review/SKILL.md +155 -0
  82. package/templates/default/locales/en/.mustflow/skills/prompt-contract-quality-review/SKILL.md +158 -0
  83. package/templates/default/locales/en/.mustflow/skills/quadratic-scan-review/SKILL.md +155 -0
  84. package/templates/default/locales/en/.mustflow/skills/queue-processing-integrity-review/SKILL.md +193 -0
  85. package/templates/default/locales/en/.mustflow/skills/race-condition-review/SKILL.md +188 -0
  86. package/templates/default/locales/en/.mustflow/skills/rate-limit-integrity-review/SKILL.md +344 -0
  87. package/templates/default/locales/en/.mustflow/skills/retry-policy-integrity-review/SKILL.md +195 -0
  88. package/templates/default/locales/en/.mustflow/skills/routes.toml +330 -0
  89. package/templates/default/locales/en/.mustflow/skills/security-flow-review/SKILL.md +279 -0
  90. package/templates/default/locales/en/.mustflow/skills/testability-boundary-review/SKILL.md +295 -0
  91. package/templates/default/locales/en/.mustflow/skills/transaction-boundary-integrity-review/SKILL.md +196 -0
  92. package/templates/default/locales/en/.mustflow/skills/type-state-modeling-review/SKILL.md +179 -0
  93. package/templates/default/locales/en/.mustflow/skills/web-render-performance-review/SKILL.md +164 -0
  94. package/templates/default/manifest.toml +386 -1
@@ -0,0 +1,193 @@
1
+ ---
2
+ mustflow_doc: skill.concurrency-invariant-review
3
+ locale: en
4
+ canonical: true
5
+ revision: 1
6
+ lifecycle: mustflow-owned
7
+ authority: procedure
8
+ name: concurrency-invariant-review
9
+ description: Apply this skill when code is created, changed, reviewed, or reported and concurrency correctness depends on whether invariants still hold after time order changes, including shared ownership, hidden writes in getters or lazy initialization, check-then-act, read-modify-write, lock identity, lock order, lock scope, condition variables, lost notifications, atomics mixed with ordinary state, CAS ABA, double-checked locking, object publication, fake immutability, concurrent collection iteration, cache stampede, application-only uniqueness, transaction isolation, distributed lock leases, idempotency keys, queue duplicate delivery, state-machine transitions, scheduler overlap, shutdown drain, lock or semaphore release, thread-local leakage, async await interleavings, and deterministic concurrency tests.
10
+ metadata:
11
+ mustflow_schema: "1"
12
+ mustflow_kind: procedure
13
+ pack_id: mustflow.core
14
+ skill_id: mustflow.core.concurrency-invariant-review
15
+ command_intents:
16
+ - changes_status
17
+ - changes_diff_summary
18
+ - lint
19
+ - build
20
+ - test_related
21
+ - test
22
+ - docs_validate_fast
23
+ - test_release
24
+ - mustflow_check
25
+ ---
26
+
27
+ # Concurrency Invariant Review
28
+
29
+ <!-- mustflow-section: purpose -->
30
+ ## Purpose
31
+
32
+ Review concurrency by changing the time order in your head and checking whether the invariant still holds.
33
+
34
+ The review question is not "is the code correct in this order?" The stronger question is "if execution A pauses here, execution B changes the shared world, and A resumes, does the system still tell the truth?" Use this skill for concurrency design and primitive discipline. Use `race-condition-review` for a focused stale-read or check-then-act path.
35
+
36
+ <!-- mustflow-section: use-when -->
37
+ ## Use When
38
+
39
+ - Code is created, changed, reviewed, or reported and more than one request, thread, async task, worker, callback, scheduler, queue consumer, process, or service instance can touch the same value, object, cache key, queue item, database row, file, socket, session, lock, or lifecycle flag.
40
+ - A review needs to establish the owner of shared state and the invariant that must survive different time orders.
41
+ - Code claims to be safe because it has a lock, atomic, transaction, concurrent collection, distributed lock, idempotency key, queue, scheduler, shutdown flag, or concurrency test.
42
+ - Code uses condition variables, wait/notify, semaphores, read-write locks, atomics, CAS, double-checked locking, thread-local context, lazy initialization, cache fills, object pools, reusable buffers, or mutable shared DTOs.
43
+ - A failure, retry, timeout, cancellation, shutdown, duplicate queue delivery, scheduler overlap, or async `await` can run concurrently with the normal path.
44
+
45
+ <!-- mustflow-section: do-not-use-when -->
46
+ ## Do Not Use When
47
+
48
+ - The task only changes local immutable values inside one call stack and no shared owner, durable store, callback, async yield, queue, timer, or lifecycle boundary exists.
49
+ - The concern is one concrete stale read, check-then-act, read-modify-write, close/send race, or database uniqueness race; use `race-condition-review` first and this skill only if primitive discipline or ownership is also unclear.
50
+ - The task is only memory retention, listener cleanup, timer cleanup, or native resource lifetime; use `memory-lifetime-review` first unless cleanup can race with concurrent work.
51
+ - The task is only backend retries, queues, idempotency, outbox, health, cache, or external-call deadlines; use `backend-reliability-change` first and this skill only for concurrent ownership and invariant timing.
52
+ - The task is only error handling truthfulness; use `failure-integrity-review` first.
53
+
54
+ <!-- mustflow-section: required-inputs -->
55
+ ## Required Inputs
56
+
57
+ - Shared state inventory: variables, objects, caches, queues, database rows, files, sessions, singleton services, static fields, Redis keys, global settings, thread-local context, and external side effects.
58
+ - Ownership rule: who owns each shared state item, whether ownership is single-writer, lock-protected, transaction-protected, atomic-only, message-serialized, immutable, or undefined.
59
+ - Invariant: the business or data fact that must remain true across multiple fields, rows, messages, callbacks, operations, or lifecycle states.
60
+ - Time-order points: `await`, I/O, DB calls, callbacks, event listeners, plugin hooks, logging, metrics, lock release, condition wait, notify, retry, timeout, queue ack, scheduler tick, cancellation, shutdown, close, send, and publication.
61
+ - Synchronization evidence: exact lock identity, lock order, condition predicate, atomic memory-ordering story, transaction isolation, row lock, unique constraint, fencing token, idempotency record, queue dedupe, or deterministic test harness.
62
+ - Runtime and deployment shape: single thread, worker pool, process pool, multi-instance service, distributed cache, database, queue, scheduler, coroutine runtime, or reactive runtime.
63
+
64
+ <!-- mustflow-section: preconditions -->
65
+ ## Preconditions
66
+
67
+ - The task matches the Use When conditions and does not match the Do Not Use When exclusions.
68
+ - Higher-priority instructions and `.mustflow/config/commands.toml` have been checked for the current scope.
69
+ - Required inputs are available, or missing owner, invariant, lock identity, isolation, queue, scheduler, or test evidence can be reported without guessing.
70
+ - Existing local patterns for locks, atomics, transactions, state machines, queues, idempotency, cancellation, shutdown, and deterministic tests have been searched before adding new primitives.
71
+
72
+ <!-- mustflow-section: allowed-edits -->
73
+ ## Allowed Edits
74
+
75
+ - Add or tighten ownership boundaries, immutable snapshots, single-writer serialization, scoped locks, lock ordering, condition predicates, atomic conditional writes, transactions, row locks, unique constraints, idempotency records, fencing tokens, state-transition guards, queue dedupe, shutdown drains, and deterministic concurrency tests tied to the reviewed invariant.
76
+ - Move callbacks, plugin hooks, event listeners, HTTP calls, database calls, logging, metrics, JSON conversion, compression, image processing, or other external code outside locks when the invariant allows it.
77
+ - Replace fake safety such as comments, `Thread.sleep`, best-effort retries, app-only duplicate checks, process-local locks for multi-instance data, or log-order reasoning with durable or deterministic evidence.
78
+ - Do not invent raw stress-test, load-test, thread-sanitizer, profiler, server, watcher, or database commands outside configured command intents.
79
+
80
+ <!-- mustflow-section: procedure -->
81
+ ## Procedure
82
+
83
+ 1. Color every shared value.
84
+ - Include referenced objects, singleton services, static fields, DI-managed services, caches, queues, database rows, files, sessions, Redis keys, global config, sockets, and thread-local context.
85
+ - Treat "read-only" helpers as suspicious until getters, `find`, `load`, `resolve`, `toString`, `hashCode`, memoization, lazy init, counters, and connection refresh paths are checked for hidden writes.
86
+ 2. Name the owner and the invariant.
87
+ - If a value has one owner, preserve that ownership.
88
+ - If several flows own it, require a lock, transaction, atomic operation, message serialization, immutable snapshot, durable constraint, or state-machine transition.
89
+ - If the owner cannot be named, report that the concurrency surface is not reviewable yet.
90
+ 3. Build a time-order table.
91
+ - Pick two executions, A and B.
92
+ - Pause A after each shared read, condition check, lock release, `await`, I/O, callback, notify, queue ack, scheduler tick, cancellation check, or state publication.
93
+ - Let B mutate or observe the same state, then resume A and check the invariant.
94
+ 4. Catch check-then-act and read-modify-write.
95
+ - Treat `if (!exists) create`, `if (balance >= amount) withdraw`, `if (map.get(k) == null) put`, `if (!closed) send`, `count++`, `x = x + 1`, `size()` then `add()`, and version read then update as unsafe until the whole operation is atomic.
96
+ - Use atomic conditional update, compare-and-swap, row lock, unique constraint, transaction isolation, or one correctly scoped lock.
97
+ 5. Verify lock identity and lock scope.
98
+ - A lock helps only when every read and write of the protected invariant uses the same lock or an explicitly ordered lock set.
99
+ - A one-line lock can still be too narrow when `orders` plus `total`, status plus timestamp, queue plus offset, or cache plus index must change together.
100
+ - A wide lock can turn a performance bug into an outage when it holds while doing network, DB, disk, compression, JSON parsing, image processing, logging, metrics, callbacks, or plugin code.
101
+ 6. Build the lock-order table.
102
+ - Record nested acquisition order such as `account lock -> ledger lock -> notification lock`.
103
+ - Reject paths that acquire the same pair in reverse order unless the runtime and lock type make that impossible.
104
+ - Check reentrant callbacks and external code called under a lock for hidden reacquisition.
105
+ 7. Check condition variables and notifications by state, not signal.
106
+ - A condition variable wait should be inside a loop that rechecks the predicate.
107
+ - The loop must tolerate spurious wakeup, another waiter consuming the work first, and notifications that arrive before this worker starts waiting.
108
+ - `notify` and state changes should happen under the same synchronization boundary.
109
+ - A lost notification is possible when code trusts the signal instead of a persistent state predicate.
110
+ 8. Check atomics, memory visibility, and CAS.
111
+ - Atomics protect one value, not the surrounding object graph.
112
+ - Do not mix `AtomicBoolean closed` with ordinary `socket`, `buffer`, or `currentUser` state unless another boundary protects the combined invariant.
113
+ - CAS on stacks, queues, free lists, and state machines needs an ABA story such as version, stamp, generation, or immutable node identity.
114
+ - Double-checked locking needs a language-specific memory model and publication guarantee.
115
+ 9. Check object publication and immutability.
116
+ - Constructors should not publish `this` to event buses, global maps, callbacks, threads, or async work before construction completes.
117
+ - `final`, `readonly`, or `const` is not enough when the object contains mutable arrays, lists, maps, buffers, or handles.
118
+ - Share immutable snapshots or freeze the reachable state when lock-free sharing is intended.
119
+ 10. Check collections, caches, and lazy loading.
120
+ - Iteration while another flow can add or remove needs a lock, snapshot, copy-on-write, version check, or verified concurrent collection semantics.
121
+ - A concurrent collection makes single methods safe; it does not make multi-method business rules safe.
122
+ - Cache `get-or-load` should collapse same-key misses, avoid partially initialized values, and define stale-read and delete/recreate behavior.
123
+ 11. Check database and distributed boundaries.
124
+ - Application locks do not protect multi-instance uniqueness; unique facts belong in a durable constraint or single-writer authority.
125
+ - Review isolation level, `SELECT` then `UPDATE`, row locks, optimistic version columns, phantom reads, lost updates, and conditional writes.
126
+ - Distributed locks are leases. Check expiry, process pauses, network delay, clock skew, and fencing tokens before trusting external side effects.
127
+ 12. Check duplicate execution and state transitions.
128
+ - Retries and timeouts can mean "completed but response lost", not "did not happen".
129
+ - Queue consumers should assume at-least-once delivery, late ack, redelivery, and concurrent same-resource work.
130
+ - Status fields need allowed transitions when payment, cancellation, shipping, deletion, processing, or closure can happen at the same time.
131
+ 13. Check time-based ownership.
132
+ - `if (now - lastRun > interval) run()` can let several executions pass together.
133
+ - Cron, scheduler, timer, and lease-based work should acquire execution ownership atomically and tolerate clock skew where relevant.
134
+ - Old timers should not update new state after ownership changes.
135
+ 14. Check shutdown, cancellation, and resource release.
136
+ - Shutdown should define stop-accepting, drain, cancel, flush, close, and in-flight side-effect ownership.
137
+ - `closed = true` is not enough if futures, workers, sockets, buffers, queues, or async continuations keep running.
138
+ - Mutexes, semaphores, read-write locks, connection checkouts, rate-limit tokens, and permits must release on every exception path.
139
+ 15. Check thread-local and async context.
140
+ - Thread-local context is hidden global state in thread pools.
141
+ - Clear request, tenant, auth, transaction, and locale context before the thread is reused.
142
+ - Async, coroutine, virtual-thread, and reactive runtimes can break assumptions that thread-local state follows logical work.
143
+ - Treat every `await` as a point where the world can change before the continuation resumes.
144
+ 16. Check concurrency tests as evidence, not decoration.
145
+ - `Thread.sleep(100)` is not deterministic proof.
146
+ - Prefer barriers, latches, fake schedulers, deterministic executors, controlled promises, transactional fixtures, version assertions, queue dedupe fixtures, and explicit interleaving tests.
147
+ - Use stress or repeated tests only as supplementary evidence when deterministic ordering is unavailable.
148
+
149
+ <!-- mustflow-section: postconditions -->
150
+ ## Postconditions
151
+
152
+ - Shared state, owners, invariants, and time-order points are named or missing evidence is reported.
153
+ - Locks, atomics, conditions, transactions, distributed leases, queues, schedulers, shutdown, thread-local context, async yields, collections, caches, and tests are checked where relevant.
154
+ - The chosen fix or recommendation preserves the whole invariant, not just one field or one method call.
155
+ - Deterministic evidence covers the highest-risk interleaving when the repository has a configured way to exercise it.
156
+
157
+ <!-- mustflow-section: verification -->
158
+ ## Verification
159
+
160
+ Use configured oneshot command intents when available:
161
+
162
+ - `changes_status`
163
+ - `changes_diff_summary`
164
+ - `lint`
165
+ - `build`
166
+ - `test_related`
167
+ - `test`
168
+ - `docs_validate_fast`
169
+ - `test_release`
170
+ - `mustflow_check`
171
+
172
+ Prefer the narrowest configured test, build, docs, release, or mustflow intent that proves the changed concurrency invariant. Report skipped manual diagnostics such as stress tests, load tests, thread sanitizers, database isolation harnesses, scheduler fuzzers, and live multi-instance checks when no configured intent exists.
173
+
174
+ <!-- mustflow-section: failure-handling -->
175
+ ## Failure Handling
176
+
177
+ - If a configured command fails, preserve the failing intent, output tail, and invariant under test before editing again.
178
+ - If the owner or invariant cannot be named, stop the concurrency claim and report the missing design fact.
179
+ - If a process-local lock cannot protect multi-instance data, report the missing durable boundary instead of pretending the lock solves it.
180
+ - If deterministic proof is unavailable, state the remaining manual evidence gap and complete the configured checks that are available.
181
+
182
+ <!-- mustflow-section: output-format -->
183
+ ## Output Format
184
+
185
+ - Shared state inventory and owner decision
186
+ - Invariant and time-order table reviewed
187
+ - Check-then-act and read-modify-write findings
188
+ - Lock identity, lock scope, lock order, condition variable, atomics, memory visibility, CAS ABA, publication, immutability, collections, cache, database, distributed lock, idempotency, queue duplicate, state transition, scheduler, shutdown, resource release, thread-local, async `await`, and test-evidence checks where relevant
189
+ - Concurrency fixes made or recommended
190
+ - Tests or verification evidence
191
+ - Command intents run
192
+ - Skipped concurrency diagnostics and reasons
193
+ - Remaining concurrency-invariant risk
@@ -0,0 +1,161 @@
1
+ ---
2
+ mustflow_doc: skill.core-web-vitals-field-review
3
+ locale: en
4
+ canonical: true
5
+ revision: 1
6
+ lifecycle: mustflow-owned
7
+ authority: procedure
8
+ name: core-web-vitals-field-review
9
+ description: Apply this skill when Core Web Vitals, real-user web performance, CrUX, Search Console page experience, Lighthouse-versus-field discrepancies, RUM instrumentation, web-vitals reporting, LCP, INP, CLS, TTFB, LCP subparts, interaction latency, LoAF, long tasks, bfcache, speculation rules, third-party scripts, tag managers, ads, web fonts, responsive hero media, layout shifts, or deployment performance regressions need review from field data rather than a one-off lab score.
10
+ metadata:
11
+ mustflow_schema: "1"
12
+ mustflow_kind: procedure
13
+ pack_id: mustflow.core
14
+ skill_id: mustflow.core.core-web-vitals-field-review
15
+ command_intents:
16
+ - changes_status
17
+ - changes_diff_summary
18
+ - lint
19
+ - build
20
+ - test_related
21
+ - test
22
+ - docs_validate_fast
23
+ - test_release
24
+ - mustflow_check
25
+ ---
26
+
27
+ # Core Web Vitals Field Review
28
+
29
+ <!-- mustflow-section: purpose -->
30
+ ## Purpose
31
+
32
+ Review Core Web Vitals as a field-data operating contract, not as a Lighthouse trophy.
33
+
34
+ The review question is: "Will real users at the 75th percentile on mobile and desktop separately pass LCP, INP, and CLS after this change, and do we have enough attribution to know why not?" Lab tools can reproduce and debug, but Core Web Vitals pass/fail is a real-user distribution problem.
35
+
36
+ <!-- mustflow-section: use-when -->
37
+ ## Use When
38
+
39
+ - Code, docs, tests, reports, dashboards, budgets, or final claims mention Core Web Vitals, page experience, CrUX, Search Console, RUM, Lighthouse, PageSpeed Insights, LCP, INP, CLS, FID replacement, TTFB, first-view performance, interaction responsiveness, layout stability, or web-performance regression.
40
+ - A web route, landing page, ecommerce page, dashboard, app shell, SSR/RSC/SPA route, hero media, client bundle, hydration boundary, third-party script, tag manager, ad slot, font, image, iframe, route prefetch, bfcache, or speculation rules change may affect real-user LCP, INP, or CLS.
41
+ - A lab score looks good but Search Console, CrUX, RUM, or production users report poor Web Vitals.
42
+ - The work needs to decide whether to use `web-render-performance-review`, `image-delivery-performance-review`, `frame-render-performance-review`, `client-bundle-pruning-review`, or `performance-budget-check` next.
43
+
44
+ <!-- mustflow-section: do-not-use-when -->
45
+ ## Do Not Use When
46
+
47
+ - The task is only first-render resource discovery, critical CSS, LCP media delivery, TTFB, or cache delivery with no field-data or Core Web Vitals pass/fail claim; use `web-render-performance-review`.
48
+ - The task is only image delivery, responsive image markup, image CDN behavior, or image safety; use `image-delivery-performance-review`.
49
+ - The task is only frame jank, scroll performance, layout thrash, animation smoothness, or interaction rendering cost; use `frame-render-performance-review`.
50
+ - The task is only bundle size, tree shaking, initial JS, or shared vendor weight; use `client-bundle-pruning-review`.
51
+ - The task requires collecting new production RUM, opening Search Console, running Lighthouse, starting a browser, launching a dev server, or querying analytics, but no user-provided evidence or configured one-shot intent exists. Report the measurement gap instead of inventing raw browser or service workflows.
52
+
53
+ <!-- mustflow-section: required-inputs -->
54
+ ## Required Inputs
55
+
56
+ - Metric contract: current official thresholds when they matter, target percentile, mobile versus desktop split, page or route grouping, route templates, release window, and whether the claim is field, lab, or static risk.
57
+ - Field evidence ledger: RUM events, CrUX, Search Console, PageSpeed field data, navigation type, URL, route, device class, connection type, viewport, memory, country or region when safe, and sampling or privacy policy.
58
+ - LCP ledger: candidate element, viewport, TTFB, resource load delay, resource load duration, element render delay, discovery path, priority, image candidate size, font or text candidate, render-blocking CSS, JavaScript blockage, and cache status.
59
+ - INP ledger: interaction target, interaction type, input delay, processing duration, presentation delay, main-thread queue, hydration, render cascade, long tasks, Long Animation Frames, third-party work, worker boundary, and affected route state.
60
+ - CLS ledger: shift source, session window, images and media geometry, ad or embed slots, banners, toasts, personalization, skeleton contracts, font fallback metrics, animations, and user-input exception boundary.
61
+ - Lab and diagnostics ledger: Lighthouse, WebPageTest, DevTools trace, Performance panel, LoAF entries, long tasks, Server-Timing, bundle output, resource waterfall, bfcache diagnostics, speculation-rules evidence, or missing evidence.
62
+ - Relevant command-intent contract entries for build, tests, docs, release checks, and mustflow validation.
63
+
64
+ <!-- mustflow-section: preconditions -->
65
+ ## Preconditions
66
+
67
+ - The task matches the Use When conditions and does not match the Do Not Use When exclusions.
68
+ - Higher-priority instructions and `.mustflow/config/commands.toml` have been checked for the current scope.
69
+ - Required inputs are available from current files, diffs, docs, provided reports, configured outputs, or the missing evidence can be reported honestly.
70
+ - Current thresholds, browser support, and API status are verified against official sources before adding durable docs, hard-coded gates, or public claims that depend on them.
71
+ - If the fix changes HTML, CSS, images, scripts, bundles, framework boundaries, cache headers, or third-party loading, also use the matching narrower skill.
72
+
73
+ <!-- mustflow-section: allowed-edits -->
74
+ ## Allowed Edits
75
+
76
+ - Add or adjust RUM instrumentation, metric payload fields, route grouping, privacy-safe attribution, p75 reporting, metric budgets, field-versus-lab wording, LCP candidate annotations, Server-Timing, resource timing hooks, LoAF or long-task capture, bfcache diagnostics, and focused tests when local patterns support them.
77
+ - Adjust LCP resource discovery, hero loading, responsive images, critical CSS, fonts, server HTML streaming, hydration boundaries, main-thread scheduling, worker offload, third-party script gates, ad or embed reservation, skeleton geometry, content visibility, route prefetch, and speculation rules only when the repository owns that surface and the matching narrower skill supports the change.
78
+ - Do not add unbounded analytics payloads, personal data, raw selectors that expose private content, production-only service calls, third-party tags, new analytics vendors, new browser harnesses, or speculative preload/prerender behavior without product and command-contract support.
79
+ - Do not claim a Core Web Vitals improvement from a Lighthouse score alone when field data is absent.
80
+
81
+ <!-- mustflow-section: procedure -->
82
+ ## Procedure
83
+
84
+ 1. Anchor the pass/fail contract. As of 2026-06-14, the official "good" Core Web Vitals targets are LCP at or below 2.5 seconds, INP at or below 200 milliseconds, and CLS at or below 0.1, evaluated at the 75th percentile. Re-verify official thresholds before durable public docs or hard-coded policy.
85
+ 2. Split mobile and desktop. Do not average them together. A desktop p75 pass can hide a mobile failure, and field tools classify experiences by user distributions, not developer machines.
86
+ 3. Treat INP as current, FID as legacy. INP replaced FID as a Core Web Vital on 2024-03-12; keep FID only when reviewing legacy dashboards or old historical baselines.
87
+ 4. Classify evidence before conclusions.
88
+ - Field evidence: RUM, CrUX, Search Console, PageSpeed field data, or production telemetry.
89
+ - Lab evidence: Lighthouse, WebPageTest, DevTools traces, local throttled runs, or synthetic monitoring.
90
+ - Static risk: code or config shape without measurement.
91
+ - Manual-only or missing: evidence that cannot be collected through configured intents or user-provided artifacts.
92
+ 5. Prefer RUM first for operating decisions. Capture metric `rating`, route, URL template, navigation type, metric element or target when safe, load state, viewport class, device memory, effective connection type, and release version when local privacy policy allows it.
93
+ 6. Report percentiles, not averages. Track p75 for pass/fail and p90 or p95 for tail diagnosis; averages hide the slow devices and bad networks that usually decide field status.
94
+ 7. Explain Lighthouse-versus-field gaps. A clean lab score can still fail field data because CrUX and RUM include real devices, real networks, cache states, third-party drift, bfcache behavior, route mix, and 28-day rolling windows.
95
+ 8. Break LCP into subparts: TTFB, resource load delay, resource load duration, and element render delay. Do not call an image "optimized" until discovery, download, and render delay are each accounted for.
96
+ 9. Keep LCP resource discovery early. Lazy LCP images, CSS background heroes without preload, late client-rendered heroes, wrong `sizes`, font-blocked text candidates, and render-blocking CSS belong in `web-render-performance-review` or `image-delivery-performance-review`.
97
+ 10. Treat `fetchpriority` and preload as different levers. Preload helps discovery; `fetchpriority` changes priority after discovery. Too many high-priority resources create priority inflation.
98
+ 11. Use SSR, streaming, static shells, and dynamic holes to lower first-view waits. If TTFB is high, check origin work, cache status, Server-Timing, query counts, API fan-out, and personalization before polishing image bytes.
99
+ 12. Debug INP as a whole-page responsiveness problem. A short click handler can still have poor INP when hydration, analytics, JSON parsing, React render cascades, layout, ads, or previous tasks block the main thread.
100
+ 13. Split long tasks and heavy work. Chunk work with explicit yielding where supported, move DOM-free parsing or compute to workers, defer noncritical hydration, use transitions or deferred rendering for expensive UI updates, and route detailed frame work to `frame-render-performance-review`.
101
+ 14. Instrument Long Animation Frames when available and useful. LoAF can attribute slow UI frames to scripts and rendering work; treat browser support and privacy constraints as part of the evidence ledger.
102
+ 15. Review third-party scripts as performance debt. Tag managers, ads, heatmaps, chat widgets, A/B tests, and analytics can execute on the main thread even when loaded asynchronously. Gate them by route, consent, idle time, user intent, or budget.
103
+ 16. Review GTM and marketing tags like client bundle changes. New tags can invalidate bundle savings; record third-party time or LoAF attribution when available.
104
+ 17. Debug CLS as a space contract. Images need dimensions, but ads, cookie bars, app banners, toast stacks, recommendation modules, personalization blocks, skeletons, font swaps, and embeds often cause the real shifts.
105
+ 18. Match skeletons to final geometry. A skeleton that changes height when content arrives is a layout-shift generator, not a fix.
106
+ 19. Animate with layout safety. Prefer transform and opacity; layout-affecting animations can hurt rendering and, when not tied to recent user input, contribute to CLS.
107
+ 20. Preserve bfcache eligibility. Avoid unnecessary `unload` handlers, synchronous page-exit work, and lifecycle patterns that block instant back or forward navigation.
108
+ 21. Use speculation rules only for safe next pages. Prefetch or prerender can help predictable navigation, but do not prerender pages with side effects, payment, inventory mutation, personalized secrets, or unsafe GET behavior.
109
+ 22. Set multidimensional budgets. Track JS, CSS, image bytes, third-party time, main-thread blocking, hydration, LCP resource delay, p75 INP, CLS, and route-level budgets instead of one bundle-size number.
110
+ 23. Turn performance into release monitoring. Compare pre-change and post-deploy p75 by route, device class, and navigation type; field regressions often appear after content, campaign, tag, or upload changes rather than code alone.
111
+ 24. Label output honestly. If only static review was possible, recommend RUM or lab follow-up without claiming measured Core Web Vitals improvement.
112
+
113
+ <!-- mustflow-section: postconditions -->
114
+ ## Postconditions
115
+
116
+ - Core Web Vitals target, percentile, mobile and desktop split, route grouping, and evidence level are explicit.
117
+ - LCP, INP, and CLS risks are mapped to concrete causes or to missing evidence.
118
+ - Lighthouse-only claims, stale FID dashboards, averaged metrics, hidden mobile failures, uninstrumented RUM, lazy LCP media, main-thread interaction blockage, third-party drift, layout-shift space gaps, bfcache blockers, unsafe prerendering, and budget blind spots are fixed or reported.
119
+ - Privacy, accessibility, security, cache safety, authorization, and user control remain intact or are reported as tradeoffs.
120
+
121
+ <!-- mustflow-section: verification -->
122
+ ## Verification
123
+
124
+ Use configured oneshot command intents when available:
125
+
126
+ - `changes_status`
127
+ - `changes_diff_summary`
128
+ - `lint`
129
+ - `build`
130
+ - `test_related`
131
+ - `test`
132
+ - `docs_validate_fast`
133
+ - `test_release`
134
+ - `mustflow_check`
135
+
136
+ Use the narrowest configured test, build, docs, release, or mustflow intent that covers the changed route, instrumentation, template, or reporting contract. Use browser, Lighthouse, Search Console, CrUX, RUM, analytics, WebPageTest, DevTools, tag-manager, CDN, or production telemetry workflows only when they are configured one-shot intents or explicitly provided or approved by the user.
137
+
138
+ <!-- mustflow-section: failure-handling -->
139
+ ## Failure Handling
140
+
141
+ - If current thresholds, browser support, or API status are stale or unverified, report the freshness gap before changing durable docs or policy.
142
+ - If field data is missing, do not backfill the gap with Lighthouse certainty. Mark the result as static or lab-only.
143
+ - If RUM attribution would collect personal data, raw selectors, URLs with secrets, or sensitive text, reduce or hash the payload according to project privacy policy before instrumentation.
144
+ - If the fix needs unconfigured production access, service credentials, browser traces, dev servers, or analytics dashboards, stop at the manual boundary and report the skipped measurement.
145
+ - If a configured test or build fails, preserve the failing intent and output tail, then fix only the Core Web Vitals, instrumentation, route, or template contract exercised by the failure.
146
+
147
+ <!-- mustflow-section: output-format -->
148
+ ## Output Format
149
+
150
+ - Core Web Vitals surface reviewed
151
+ - Evidence level: field, lab, configured-test evidence, static risk, manual-only, missing, or not applicable
152
+ - Threshold and percentile contract
153
+ - Mobile and desktop split
154
+ - LCP subpart ledger
155
+ - INP interaction and main-thread ledger
156
+ - CLS space-contract ledger
157
+ - Third-party, bfcache, speculation, budget, and release-monitoring notes where relevant
158
+ - Fixes or recommendations
159
+ - Command intents run
160
+ - Skipped field, browser, analytics, or lab measurements and reasons
161
+ - Remaining Core Web Vitals field risk
@@ -0,0 +1,156 @@
1
+ ---
2
+ mustflow_doc: skill.credit-ledger-integrity-review
3
+ locale: en
4
+ canonical: true
5
+ revision: 1
6
+ lifecycle: mustflow-owned
7
+ authority: procedure
8
+ name: credit-ledger-integrity-review
9
+ description: Apply this skill when credits, points, wallet balances, reward points, prepaid credits, usage credits, bonus credits, loyalty points, stored-value balances, balance deductions, accruals, refunds, reversals, expirations, reservations, captures, releases, admin adjustments, ledger tables, balance caches, reconciliation jobs, settlement reports, or credit-related tests need review for ledger integrity, idempotency, atomic balance changes, concurrency, ordering, ownership, amount precision, policy snapshots, expiry lots, failure recovery, audit evidence, or reconciliation risk.
10
+ metadata:
11
+ mustflow_schema: "1"
12
+ mustflow_kind: procedure
13
+ pack_id: mustflow.core
14
+ skill_id: mustflow.core.credit-ledger-integrity-review
15
+ command_intents:
16
+ - changes_status
17
+ - changes_diff_summary
18
+ - lint
19
+ - build
20
+ - test_related
21
+ - test
22
+ - test_audit
23
+ - docs_validate_fast
24
+ - test_release
25
+ - mustflow_check
26
+ ---
27
+
28
+ # Credit Ledger Integrity Review
29
+
30
+ <!-- mustflow-section: purpose -->
31
+ ## Purpose
32
+
33
+ Review credit, point, and wallet balance code as an accounting ledger, not a balance subtraction. The core question is whether every balance-changing event has a durable cause, happens once, preserves non-negative and unit invariants under concurrency, can be reversed or reconciled after failure, and leaves enough evidence for support, audit, and settlement.
34
+
35
+ <!-- mustflow-section: use-when -->
36
+ ## Use When
37
+
38
+ - Credit, point, wallet, reward, prepaid, usage, bonus, loyalty, stored-value, quota-like paid credit, or internal money-equivalent balance logic is created, changed, reviewed, or reported.
39
+ - Balance deduction, accrual, refund, reversal, expiration, reservation, capture, release, adjustment, transfer, coupon-backed credit, item purchase, game purchase, subscription credit, or order credit logic can change a user or tenant balance.
40
+ - Code touches ledger tables, balance columns, balance caches, idempotency keys, source IDs, conditional updates, locks, transactions, queue consumers, expiry batches, reconciliation jobs, settlement reports, or admin tools for credits or points.
41
+ - Tests need to prove duplicate requests, concurrent deductions, partial refunds, expiration races, failure injection, cache or replica staleness, or ledger-vs-balance reconciliation.
42
+
43
+ <!-- mustflow-section: do-not-use-when -->
44
+ ## Do Not Use When
45
+
46
+ - The task only reviews payment-provider calls, checkout redirects, card payments, provider webhooks, authorization, capture, settlement, or chargebacks; use `payment-integrity-review`.
47
+ - The task only reviews general business-rule placement without a balance, ledger, wallet, credit, point, or reconciliation surface; use `business-rule-leakage-review`.
48
+ - The task only designs a generic lifecycle state machine with no ledger, amount, idempotency, balance, reservation, expiry, or reconciliation risk; use `state-machine-pattern`.
49
+ - The task only reviews cache correctness for a non-balance value; use `cache-integrity-review`.
50
+ - The task requires production balance corrections, real refunds, data migrations, or direct database repair without explicit user approval and configured command support.
51
+
52
+ <!-- mustflow-section: required-inputs -->
53
+ ## Required Inputs
54
+
55
+ - Balance surface ledger: balance columns, wallet rows, account rows, point buckets, credit lots, cached balances, read models, and derived totals.
56
+ - Ledger-entry ledger: every earn, grant, charge, deduct, reserve, capture, release, expire, refund, reverse, adjust, transfer, settlement, and correction entry.
57
+ - Source identity ledger: order ID, payment ID, usage ID, subscription ID, coupon ID, item ID, event ID, request ID, idempotency key, admin action ID, and source type.
58
+ - Atomicity ledger: transaction boundaries, conditional updates, row locks, optimistic versions, uniqueness constraints, affected-row checks, and retry policy.
59
+ - Amount and unit ledger: integer unit or decimal representation, maximum amount, rounding rules, conversion rates, bonus rules, policy version, product price snapshot, and campaign snapshot.
60
+ - Ownership ledger: user, tenant, wallet, account, team, family, organization, operator, source object, and current actor checks.
61
+ - Expiry and lot ledger: FIFO, LIFO, earliest-expiry-first, bucket allocation, expiry batch, lot-level consumption, partial use, partial refund, and lot restoration behavior.
62
+ - Reservation ledger: reserved, captured, released, failed, expired, cancelled, partially refunded, and reversed states, plus the owner of each transition.
63
+ - Queue and cache ledger: producer events, consumer idempotency, partitioning, outbox or inbox records, read-replica routing, cache invalidation, and balance display semantics.
64
+ - Audit and reconciliation ledger: logs, metrics, support IDs, before/after values, daily balance-vs-ledger checks, settlement reports, and manual adjustment evidence.
65
+
66
+ <!-- mustflow-section: preconditions -->
67
+ ## Preconditions
68
+
69
+ - The credit or point surface is identifiable from the current diff, target files, tests, docs, or user request.
70
+ - Required ledgers can be collected from repository evidence or reported as missing without guessing.
71
+ - Command execution remains governed by `.mustflow/config/commands.toml`; this skill does not authorize production balance changes, real refunds, migrations, or raw commands.
72
+
73
+ <!-- mustflow-section: allowed-edits -->
74
+ ## Allowed Edits
75
+
76
+ - Tighten ledger-entry models, source identifiers, idempotency comparison, conditional balance updates, database constraints, transaction boundaries, row-lock targets, optimistic-lock retry classification, amount validation, rounding policy, non-negative invariants, refund and reversal modeling, partial-use handling, expiry lot allocation, reservation/capture/release transitions, queue idempotency and ordering, cache invalidation, replica-read routing, admin adjustment audit trails, reconciliation checks, evidence logs, focused concurrency and failure tests, and directly synchronized docs or templates.
77
+ - Do not replace a focused balance-integrity fix with a broad wallet rewrite unless current code cannot preserve ledger correctness with a smaller boundary.
78
+ - Do not add real user balance data, production correction scripts, live settlement actions, or secret-bearing provider payloads.
79
+
80
+ <!-- mustflow-section: procedure -->
81
+ ## Procedure
82
+
83
+ 1. Treat balance as a derived fact. Prefer append-only ledger entries plus a maintained or checked balance over a lone mutable `balance` column. Flag any path where a balance can change without a durable cause record.
84
+ 2. Require an external source key. Every balance-changing request needs a stable source identity such as order ID, payment ID, usage ID, event ID, subscription ID, coupon ID, admin action ID, or idempotency key.
85
+ 3. Compare idempotency payloads. If a duplicate key appears, verify the existing entry has the same user, tenant, wallet, source, amount, unit, product, policy version, and state before returning success.
86
+ 4. Make insufficient-balance checks atomic. Reject read-then-update subtraction. Look for conditional updates, row locks, serializable ledger insertion, or equivalent storage-level protection that checks availability and changes balance as one fact.
87
+ 5. Verify affected rows. Conditional deductions must check that exactly the intended row changed. Zero affected rows should become an explicit insufficient-balance, stale-version, or conflict result.
88
+ 6. Follow the transaction boundary. Deduction, ledger insert, order creation, coupon state, reservation, capture, refund, and event publication must not commit as unrelated fragments unless compensation and reconciliation are explicit.
89
+ 7. Lock the contested resource. A lock on an order row does not protect a wallet balance. Check whether the wallet, balance row, credit lot, or unique ledger key is the actual contention point.
90
+ 8. Classify optimistic-lock retries. Retry only the same logical request after technical conflict. Do not turn separate user clicks, duplicated business requests, or stale client retries into multiple successful deductions by accident.
91
+ 9. Use exact amount units. Credits and points should use integer smallest units or decimal types with explicit scale. Reject float, double, locale-formatted strings, and rounded-late arithmetic.
92
+ 10. Centralize rounding policy. Identify where fractional bonuses, exchange rates, discounts, and refunds round. The service path, batch path, admin path, and report path must use the same policy and policy version.
93
+ 11. Validate amount shape at every entrypoint. Reject negative, zero when invalid, fractional when invalid, too-large, wrong-unit, wrong-currency, overflow-prone, or client-trusted amounts before they reach balance mutation code.
94
+ 12. Add database-level invariants where possible. Look for `CHECK (balance >= 0)`, conditional updates, uniqueness constraints, ledger sum checks, or equivalent persistence guards instead of app-only promises.
95
+ 13. Enforce unique ledger identity. Use database uniqueness for combinations such as user, wallet, source type, source ID, operation type, and reversal target where duplicates would double-spend or double-refund.
96
+ 14. Model refunds as reversals. Refunds, cancellations, and corrections should reference the original ledger entry or reservation, not call a generic balance increase with no causal link.
97
+ 15. Test partial use and partial refund. Exercise cases where only part of a balance, lot, coupon, order, or mixed payment is used or refunded. Full-cancel-only assumptions are not enough.
98
+ 16. Consume expiry lots deliberately. When credits expire, inspect FIFO, LIFO, earliest-expiry-first, or policy-specific lot allocation. Record lot-level consumption so later refund and audit can reconstruct the path.
99
+ 17. Race expiry and usage. Expiry batches must use the same ledger, lock, idempotency, and conditional update rules as user requests. Flag direct batch subtraction that bypasses wallet safeguards.
100
+ 18. Separate reservation from capture. Model reserved, captured, released, failed, expired, cancelled, and partially refunded states when credits are held before final purchase, fulfillment, or external payment completion.
101
+ 19. Draw allowed state transitions. Prevent arbitrary `status = REFUNDED`, `status = CAPTURED`, or `status = EXPIRED` writes. Each transition should have a guard, cause, effect, and idempotency rule.
102
+ 20. Preserve queue ordering or tolerate reordering. If deduction, cancellation, refund, or expiry events use a queue, prove user, wallet, or transaction-level ordering, or make each consumer robust to reordered events.
103
+ 21. Treat message redelivery as normal. Producers, queues, schedulers, and webhooks can duplicate events. Consumer-side ledger mutation must be idempotent with durable dedupe records.
104
+ 22. Do not decide deduction from cache. Balance caches and Redis totals are display or acceleration surfaces only. Final availability checks must happen in the authoritative store.
105
+ 23. Handle read-replica lag. After a deduction, API responses and next actions should not read stale replica balances in a way that invites duplicate clicks or false support claims.
106
+ 24. Route admin adjustments through the same ledger. Manual grants, penalties, refunds, corrections, and support actions need role checks, reason, source identity, before/after values, operator ID, approval evidence, and rollback or correction path.
107
+ 25. Bind actor to wallet ownership. Validate user, tenant, team, family, organization, wallet, and source object ownership. Do not trust request-body `user_id`, `wallet_id`, or `tenant_id` without actor-context checks.
108
+ 26. Snapshot price and policy inputs. Store product price, discount, exchange rate, bonus rule, campaign ID, policy version, and calculated result at transaction time. Do not recalculate old transactions from current product or policy tables.
109
+ 27. Inject failure at split points. Review or add tests for ledger insert followed by order failure, order creation followed by deduction failure, deduction success followed by timeout, refund success followed by event failure, and event publish failure after commit.
110
+ 28. Reconcile ledger and balance independently. Require scheduled or manual checks that compare current balance to ledger sums, lot sums, reservation sums, and settlement reports, then surface drift with enough identifiers to repair safely.
111
+ 29. Log evidence, not vibes. Balance-changing logs should include safe user, wallet, amount, before, after, source type, source ID, idempotency key, request ID, transaction ID, policy version, and operator ID when applicable.
112
+ 30. Test the nightmare paths. Include concurrent overdraw attempts, repeated submit clicks, duplicate idempotency key with changed amount, duplicate queue delivery, out-of-order cancellation and deduction, expiry batch racing usage, partial refund, cache stale display, replica stale read, admin adjustment, and reconciliation drift.
113
+
114
+ <!-- mustflow-section: postconditions -->
115
+ ## Postconditions
116
+
117
+ - The credit surface has balance, ledger-entry, source identity, atomicity, amount/unit, ownership, expiry/lot, reservation, queue/cache, audit, and reconciliation maps.
118
+ - Any mutable-balance-only path, missing source key, weak idempotency comparison, non-atomic deduction, wrong lock target, float amount, hidden rounding policy, missing DB invariant, duplicate ledger risk, generic refund, expiry race, cache-trusted deduction, stale replica read, unaudited admin adjustment, or missing reconciliation is fixed or reported with evidence.
119
+ - Tests or explicit verification cover the highest-risk concurrency, failure, duplicate, expiry, reservation, refund, cache, and reconciliation paths available in the current scope.
120
+
121
+ <!-- mustflow-section: verification -->
122
+ ## Verification
123
+
124
+ Use configured oneshot command intents when available:
125
+
126
+ - `changes_status`
127
+ - `changes_diff_summary`
128
+ - `lint`
129
+ - `build`
130
+ - `test_related`
131
+ - `test`
132
+ - `test_audit`
133
+ - `docs_validate_fast`
134
+ - `test_release`
135
+ - `mustflow_check`
136
+
137
+ Prefer focused tests for concurrent deductions, duplicate idempotency keys, affected-row checks, partial refunds, expiry races, queue redelivery, failure injection, admin adjustments, cache invalidation, replica reads, and ledger-vs-balance reconciliation. Use broader checks when credit integrity touches shared state machines, provider adapters, database migrations, template surfaces, or release output.
138
+
139
+ <!-- mustflow-section: failure-handling -->
140
+ ## Failure Handling
141
+
142
+ - If the source key, ledger entry, amount policy, transaction boundary, or ownership evidence is missing, report the missing ledger instead of approving the deduction path.
143
+ - If duplicate prevention relies only on frontend button disabling, in-memory flags, read-before-insert checks, or queue producer promises, report the missing durable idempotency gate.
144
+ - If balance drift is found, do not invent a correction. Report the drift evidence and the missing reconciliation or correction workflow.
145
+ - If concurrency behavior cannot be tested directly, use storage-level constraints, deterministic fake repositories, transaction fixtures, or explicit reasoning from current code, and report remaining live concurrency risk.
146
+ - If sensitive user or financial data appears in logs or test fixtures, redact it and summarize safely.
147
+
148
+ <!-- mustflow-section: output-format -->
149
+ ## Output Format
150
+
151
+ - Credit or wallet surface reviewed
152
+ - Balance, ledger-entry, source identity, atomicity, amount/unit, ownership, expiry/lot, reservation, queue/cache, audit, and reconciliation ledgers
153
+ - Findings or fixes for duplicate, concurrent, wrong-owner, wrong-amount, rounding, expiry, reservation, refund, cache, replica, failure-recovery, admin, and reconciliation risks
154
+ - Nightmare-path tests or evidence added, run, skipped, or still missing
155
+ - Command intents run
156
+ - Remaining credit-ledger integrity risk