mustflow 2.39.1 → 2.58.0

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 (92) 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/verify.js +3 -1
  4. package/dist/cli/lib/git-changes.js +11 -1
  5. package/dist/cli/lib/i18n.js +1 -1
  6. package/dist/cli/lib/local-index/index.js +8 -4
  7. package/dist/cli/lib/local-index/populate.js +17 -3
  8. package/dist/cli/lib/local-index/search-read-model.js +9 -7
  9. package/dist/cli/lib/local-index/search-text.js +2 -2
  10. package/dist/cli/lib/local-index/workflow-documents.js +17 -2
  11. package/dist/cli/lib/mustflow-read.js +14 -2
  12. package/dist/cli/lib/repo-map.js +16 -3
  13. package/dist/cli/lib/templates.js +8 -7
  14. package/dist/cli/lib/validation/constants.js +1 -1
  15. package/dist/core/active-run-locks.js +78 -20
  16. package/dist/core/change-classification.js +4 -0
  17. package/dist/core/command-contract-rules.js +1 -1
  18. package/dist/core/command-contract-validation.js +1 -1
  19. package/dist/core/command-cwd.js +13 -2
  20. package/dist/core/command-effects.js +22 -4
  21. package/dist/core/command-env.js +8 -6
  22. package/dist/core/command-preconditions.js +28 -2
  23. package/dist/core/completion-verdict.js +1 -1
  24. package/dist/core/line-endings.js +8 -4
  25. package/dist/core/safe-filesystem.js +9 -1
  26. package/dist/core/source-anchor-validation.js +7 -1
  27. package/dist/core/source-anchors.js +8 -2
  28. package/dist/core/verification-scheduler.js +8 -2
  29. package/package.json +1 -1
  30. package/templates/default/i18n.toml +330 -1
  31. package/templates/default/locales/en/.mustflow/skills/INDEX.md +302 -5
  32. package/templates/default/locales/en/.mustflow/skills/agent-eval-integrity-review/SKILL.md +160 -0
  33. package/templates/default/locales/en/.mustflow/skills/agent-execution-control-review/SKILL.md +163 -0
  34. package/templates/default/locales/en/.mustflow/skills/ai-generated-code-hardening/SKILL.md +49 -13
  35. package/templates/default/locales/en/.mustflow/skills/api-access-control-review/SKILL.md +298 -0
  36. package/templates/default/locales/en/.mustflow/skills/api-misuse-resistance-review/SKILL.md +297 -0
  37. package/templates/default/locales/en/.mustflow/skills/api-request-performance-review/SKILL.md +189 -0
  38. package/templates/default/locales/en/.mustflow/skills/app-startup-performance-review/SKILL.md +309 -0
  39. package/templates/default/locales/en/.mustflow/skills/backend-log-evidence-review/SKILL.md +213 -0
  40. package/templates/default/locales/en/.mustflow/skills/business-rule-leakage-review/SKILL.md +295 -0
  41. package/templates/default/locales/en/.mustflow/skills/cache-integrity-review/SKILL.md +291 -0
  42. package/templates/default/locales/en/.mustflow/skills/change-blast-radius-review/SKILL.md +297 -0
  43. package/templates/default/locales/en/.mustflow/skills/client-bundle-pruning-review/SKILL.md +160 -0
  44. package/templates/default/locales/en/.mustflow/skills/cloud-cost-guardrail-review/SKILL.md +321 -0
  45. package/templates/default/locales/en/.mustflow/skills/concurrency-invariant-review/SKILL.md +193 -0
  46. package/templates/default/locales/en/.mustflow/skills/core-web-vitals-field-review/SKILL.md +161 -0
  47. package/templates/default/locales/en/.mustflow/skills/credit-ledger-integrity-review/SKILL.md +156 -0
  48. package/templates/default/locales/en/.mustflow/skills/database-json-modeling-review/SKILL.md +171 -0
  49. package/templates/default/locales/en/.mustflow/skills/database-lock-contention-review/SKILL.md +192 -0
  50. package/templates/default/locales/en/.mustflow/skills/database-migration-change/SKILL.md +76 -34
  51. package/templates/default/locales/en/.mustflow/skills/database-query-bottleneck-review/SKILL.md +194 -0
  52. package/templates/default/locales/en/.mustflow/skills/deletion-lifecycle-review/SKILL.md +171 -0
  53. package/templates/default/locales/en/.mustflow/skills/deployment-rollout-safety-review/SKILL.md +321 -0
  54. package/templates/default/locales/en/.mustflow/skills/desktop-auto-update-safety-review/SKILL.md +265 -0
  55. package/templates/default/locales/en/.mustflow/skills/desktop-background-process-stability-review/SKILL.md +318 -0
  56. package/templates/default/locales/en/.mustflow/skills/desktop-memory-footprint-review/SKILL.md +318 -0
  57. package/templates/default/locales/en/.mustflow/skills/error-message-integrity-review/SKILL.md +283 -0
  58. package/templates/default/locales/en/.mustflow/skills/failure-integrity-review/SKILL.md +193 -0
  59. package/templates/default/locales/en/.mustflow/skills/file-upload-security-review/SKILL.md +305 -0
  60. package/templates/default/locales/en/.mustflow/skills/frame-render-performance-review/SKILL.md +159 -0
  61. package/templates/default/locales/en/.mustflow/skills/frontend-accessibility-tree-review/SKILL.md +202 -0
  62. package/templates/default/locales/en/.mustflow/skills/frontend-localization-review/SKILL.md +202 -0
  63. package/templates/default/locales/en/.mustflow/skills/frontend-state-ownership-review/SKILL.md +183 -0
  64. package/templates/default/locales/en/.mustflow/skills/frontend-stress-layout-review/SKILL.md +193 -0
  65. package/templates/default/locales/en/.mustflow/skills/hot-path-performance-review/SKILL.md +159 -0
  66. package/templates/default/locales/en/.mustflow/skills/idempotency-integrity-review/SKILL.md +195 -0
  67. package/templates/default/locales/en/.mustflow/skills/image-delivery-performance-review/SKILL.md +161 -0
  68. package/templates/default/locales/en/.mustflow/skills/incident-triage-review/SKILL.md +185 -0
  69. package/templates/default/locales/en/.mustflow/skills/llm-hallucination-control-review/SKILL.md +155 -0
  70. package/templates/default/locales/en/.mustflow/skills/llm-response-latency-review/SKILL.md +155 -0
  71. package/templates/default/locales/en/.mustflow/skills/llm-service-ux-review/SKILL.md +2 -0
  72. package/templates/default/locales/en/.mustflow/skills/llm-token-cost-control-review/SKILL.md +155 -0
  73. package/templates/default/locales/en/.mustflow/skills/low-end-device-support-review/SKILL.md +340 -0
  74. package/templates/default/locales/en/.mustflow/skills/memory-lifetime-review/SKILL.md +169 -0
  75. package/templates/default/locales/en/.mustflow/skills/mobile-energy-efficiency-review/SKILL.md +329 -0
  76. package/templates/default/locales/en/.mustflow/skills/module-boundary-review/SKILL.md +278 -0
  77. package/templates/default/locales/en/.mustflow/skills/multi-agent-work-coordination/SKILL.md +1 -0
  78. package/templates/default/locales/en/.mustflow/skills/observability-debuggability-review/SKILL.md +208 -0
  79. package/templates/default/locales/en/.mustflow/skills/payment-integrity-review/SKILL.md +155 -0
  80. package/templates/default/locales/en/.mustflow/skills/prompt-contract-quality-review/SKILL.md +158 -0
  81. package/templates/default/locales/en/.mustflow/skills/quadratic-scan-review/SKILL.md +155 -0
  82. package/templates/default/locales/en/.mustflow/skills/queue-processing-integrity-review/SKILL.md +193 -0
  83. package/templates/default/locales/en/.mustflow/skills/race-condition-review/SKILL.md +188 -0
  84. package/templates/default/locales/en/.mustflow/skills/rate-limit-integrity-review/SKILL.md +344 -0
  85. package/templates/default/locales/en/.mustflow/skills/retry-policy-integrity-review/SKILL.md +195 -0
  86. package/templates/default/locales/en/.mustflow/skills/routes.toml +330 -0
  87. package/templates/default/locales/en/.mustflow/skills/security-flow-review/SKILL.md +279 -0
  88. package/templates/default/locales/en/.mustflow/skills/testability-boundary-review/SKILL.md +295 -0
  89. package/templates/default/locales/en/.mustflow/skills/transaction-boundary-integrity-review/SKILL.md +196 -0
  90. package/templates/default/locales/en/.mustflow/skills/type-state-modeling-review/SKILL.md +179 -0
  91. package/templates/default/locales/en/.mustflow/skills/web-render-performance-review/SKILL.md +164 -0
  92. package/templates/default/manifest.toml +386 -1
@@ -0,0 +1,155 @@
1
+ ---
2
+ mustflow_doc: skill.quadratic-scan-review
3
+ locale: en
4
+ canonical: true
5
+ revision: 1
6
+ lifecycle: mustflow-owned
7
+ authority: procedure
8
+ name: quadratic-scan-review
9
+ description: Apply this skill when code is created, changed, reviewed, or reported and the specific risk is hidden O(N^2) or pairwise work caused by repeated scans, membership checks, code joins, resolver fan-out, render-time lookup, repeated sorting, copying, string building, or helper functions that rescan growing collections.
10
+ metadata:
11
+ mustflow_schema: "1"
12
+ mustflow_kind: procedure
13
+ pack_id: mustflow.core
14
+ skill_id: mustflow.core.quadratic-scan-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
+ # Quadratic Scan Review
28
+
29
+ <!-- mustflow-section: purpose -->
30
+ ## Purpose
31
+
32
+ Find hidden O(N^2) work by tracing when one growing collection repeatedly scans, searches, sorts, copies, serializes, or fetches against another growing collection.
33
+
34
+ The review question is not "is there a loop inside a loop?" That catches only the obvious case. The stronger question is "does this path look at the same growing data from the beginning again for each item?"
35
+
36
+ <!-- mustflow-section: use-when -->
37
+ ## Use When
38
+
39
+ - Code is created, changed, reviewed, or reported and the risk is repeated `map`, `filter`, `find`, `some`, `includes`, `indexOf`, membership checks, list joins, group building, tree building, graph traversal, duplicate removal, overlap checks, sorting, cloning, string building, JSON comparison, ORM lazy loading, GraphQL resolver loading, or render-time lookup.
40
+ - A list, table, tree, graph, event log, permission list, tag list, relation list, selected item list, likes/bookmarks/read state, orders, comments, posts, users, rows, files, or queue messages can grow without a small hard cap.
41
+ - A helper called inside a loop or render path has a harmless name such as `isValid`, `getStatus`, `hasPermission`, `getCount`, `findOwner`, `renderRow`, or `resolveField` but may scan a full collection internally.
42
+ - A review or final report claims that an O(N^2)-looking path is fine because the current fixture is small, the code is functional, the list is sorted, the helper is simple, or the data is "only a few items."
43
+
44
+ <!-- mustflow-section: do-not-use-when -->
45
+ ## Do Not Use When
46
+
47
+ - The task is broader performance triage across I/O, locks, queues, retries, payloads, clients, caches, and observability; use `hot-path-performance-review`.
48
+ - The task is a measured performance budget, benchmark, profiling, latency, throughput, or p95/p99 optimization project; use `performance-budget-check`.
49
+ - The task only changes resource cleanup, retained references, or memory lifetime without repeated-scan complexity; use `memory-lifetime-review`.
50
+ - The only concern is a fixed-size lookup over a small, documented, hard-capped configuration list where the cap is enforced or clearly external to user data.
51
+
52
+ <!-- mustflow-section: required-inputs -->
53
+ ## Required Inputs
54
+
55
+ - Outer work: the loop, mapper, reducer, render, resolver, batch, import, export, queue consumer, tree builder, graph traversal, or helper call site that repeats.
56
+ - Inner work: the scan, membership check, lookup, sort, clone, string copy, JSON serialization, DB query, resolver call, or helper body run for each item.
57
+ - Data shape: which collections grow, whether they are user-generated or fixed configuration, maximum known size, duplicate behavior, order requirements, and key fields.
58
+ - Join or membership key: ID, composite key, normalized key, parent ID, foreign key, timestamp bucket, interval boundary, permission key, tag key, or object identity.
59
+ - Current semantic contract: order, duplicates, first or last winner, stable tie-breakers, missing records, authorization filtering, stale data, and partial failure.
60
+ - Evidence level: static review, fixture size, configured test, benchmark, profiler, query count, resolver count, render count, or missing measurement.
61
+ - Relevant command-intent contract entries for build, tests, docs, release checks, and mustflow validation.
62
+
63
+ <!-- mustflow-section: preconditions -->
64
+ ## Preconditions
65
+
66
+ - The task matches the Use When conditions and does not match the Do Not Use When exclusions.
67
+ - Higher-priority instructions and `.mustflow/config/commands.toml` have been checked for the current scope.
68
+ - Required inputs are available, or missing inputs can be reported without guessing.
69
+ - If the fix changes database query shape, indexes, pagination, or transaction behavior, also use the matching database skill.
70
+ - If the pattern appears in UI rendering or derived state, also use the matching UI or framework skill when UI behavior changes.
71
+ - If resolver, queue, cache, or backend operational behavior changes, also use `backend-reliability-change`.
72
+
73
+ <!-- mustflow-section: allowed-edits -->
74
+ ## Allowed Edits
75
+
76
+ - Replace repeated scans with `Set`, `Map`, lookup tables, grouping maps, parent-to-children maps, composite keys, sorted merge, single-pass aggregation, or database-side joins when semantics match.
77
+ - Move repeated lookup preparation out of loops, render functions, resolvers, and per-item helpers into a bounded pre-indexing step.
78
+ - Add small tests or fixtures that preserve order, duplicate handling, first or last winner behavior, missing IDs, and composite-key behavior when changing lookup structure.
79
+ - Add bounded static-review notes or complexity comments only when the code would otherwise look misleading.
80
+ - Do not add caches when an index built from already-loaded data is enough.
81
+ - Do not replace arrays with maps or sets when duplicates, order, stable tie-breakers, or small hard-capped lists make the array behavior intentional.
82
+
83
+ <!-- mustflow-section: procedure -->
84
+ ## Procedure
85
+
86
+ 1. Name the repeated path and multiply call count by inner scan length. Review the product `outer_count * inner_count`, not the apparent number of loops.
87
+ 2. Search for the obvious collection-combinator shapes: `map` plus `filter`, `map` plus `find`, `forEach` plus `includes`, `filter` plus `indexOf`, `reduce` plus spread, and chained `filter().map().sort()` inside a repeated path.
88
+ 3. Search for membership checks over arrays. `includes`, `indexOf`, `contains`, `find`, `some`, and list membership inside a loop usually want `Set.has` or `Map.has` unless the searched list is tiny and hard-capped.
89
+ 4. Search for code joins by ID. `posts.map(post => users.find(...))`, `users.map(user => orders.filter(...))`, permission lookups, likes, bookmarks, read state, tags, and relation lists usually need a `Map` or grouped `Map` keyed by ID or composite key.
90
+ 5. Check duplicate removal. `filter((x, i) => arr.indexOf(x) === i)` is O(N^2). Prefer `Set` for scalar values and `Map` keyed by stable identity for objects.
91
+ 6. Check sorted arrays. Sorting does not make `find` fast. If code repeatedly searches a sorted array, use a prebuilt map, binary search with a proven comparator, or a single sorted merge.
92
+ 7. Check repeated sorting. Sorting inside a per-item loop is usually worse than scanning once, keeping a top candidate, using a heap, or sorting once before the loop.
93
+ 8. Check copy-accumulation patterns. `reduce` with `[...acc, item]`, repeated object spread over a growing object, repeated string `+=`, and repeated concatenation can become quadratic copy work. Prefer push, builders, buffers, or one final copy at the boundary.
94
+ 9. Check JSON and serialization comparisons. Repeated `JSON.stringify` inside search, equality, sort, dedupe, or render logic multiplies object size by item count. Use explicit keys and precomputed normalized keys.
95
+ 10. Open helper bodies called from loops or render paths. Harmless helper names can hide full-list scans, database calls, resolver calls, serialization, sorting, or permission checks.
96
+ 11. Check ORM and lazy relations. A single visible loop can become one query per entity. Replace per-entity relation access with eager loading, joins, `WHERE id IN (...)`, batch loading, or DataLoader-style batching.
97
+ 12. Check GraphQL and nested resolvers. Parent-list resolvers plus per-field DB or API calls create hidden pairwise fan-out. Batch by parent IDs and preserve field-level authorization semantics.
98
+ 13. Check render-time lookup. `rows.map(row => columns.find(...))`, `items.map(item => selectedIds.includes(item.id))`, derived data recomputed on every render, and per-row helper scans should move to memoized sets or maps when inputs are large or stable.
99
+ 14. Check all-data-in-app joins. Fetching `allUsers`, `allOrders`, or `allLogs` and joining in application arrays is often a database join without an index. Push join, filter, sort, and pagination to the data store when the data store owns the index and semantics allow it.
100
+ 15. Check tree and graph construction. `nodes.map(node => nodes.filter(child => child.parentId === node.id))` should usually become `childrenByParentId` plus one assembly pass. `visited.includes(id)` in traversal should be a `Set`.
101
+ 16. Check event-log and time-window scans. Repeatedly scanning all previous events per event should usually become grouping, sorting once, and one pointer or rolling aggregate per key.
102
+ 17. Check interval overlap. All-pairs range checks are sometimes necessary, but overlap detection often only needs sorting by start and comparing adjacent or active intervals.
103
+ 18. Check incremental updates. Adding one item should not recompute a full ranking, group map, unread count, cart total, or dashboard aggregate unless the collection is fixed and tiny.
104
+ 19. Separate index from cache. A `Map` built from current input is an index. A cache stores results across calls or time. Use an index for repeated lookup over already-owned data before introducing cache invalidation.
105
+ 20. Require a hard cap for "small list" exceptions. Countries, enum options, or fixed config lists may stay arrays if the cap is real. User data, logs, orders, comments, permissions, tags, events, and uploaded rows need scalable lookup.
106
+ 21. Preserve behavior while changing shape. Before replacing scans with indexes, state how order, duplicates, first or last match, missing references, authorization filtering, and stable keys are preserved.
107
+ 22. Add growth evidence when feasible. If configured tests or fixtures can scale input size, prefer a small growth test that compares behavior at larger counts. If benchmarking is not configured, report complexity-only evidence instead of a speedup claim.
108
+
109
+ <!-- mustflow-section: postconditions -->
110
+ ## Postconditions
111
+
112
+ - Each suspected O(N^2) path has an outer count, inner count, and data-growth classification.
113
+ - Repeated membership checks, code joins, duplicate removal, tree building, resolver fan-out, render-time lookup, helper-hidden scans, repeated sort, copy accumulation, and JSON comparison are fixed or reported.
114
+ - Array-to-set or array-to-map changes preserve order, duplicates, missing records, first or last winner, authorization, and stable key behavior.
115
+ - Small-list exceptions have an explicit hard cap or are reported as residual risk.
116
+ - Performance claims are backed by configured evidence or labeled as static complexity risk.
117
+
118
+ <!-- mustflow-section: verification -->
119
+ ## Verification
120
+
121
+ Use configured oneshot command intents when available:
122
+
123
+ - `changes_status`
124
+ - `changes_diff_summary`
125
+ - `lint`
126
+ - `build`
127
+ - `test_related`
128
+ - `test`
129
+ - `docs_validate_fast`
130
+ - `test_release`
131
+ - `mustflow_check`
132
+
133
+ Use the narrowest configured test, build, docs, release, or mustflow intent that covers the changed data shape. Do not infer raw benchmark, profiler, database, browser, load-test, or package-manager commands.
134
+
135
+ <!-- mustflow-section: failure-handling -->
136
+ ## Failure Handling
137
+
138
+ - If a configured test or build fails, preserve the failing intent and output tail, then fix the behavior contract that changed with the lookup structure.
139
+ - If duplicate or order semantics are unknown, do not replace a scan with a map or set until the missing semantic decision is reported.
140
+ - If an all-pairs comparison is actually required by the domain, report why the O(N^2) shape is intentional and whether input size is bounded.
141
+ - If measurement requires unconfigured benchmark, profiler, production trace, database, browser, or load-test access, report it as manual evidence instead of running raw commands.
142
+
143
+ <!-- mustflow-section: output-format -->
144
+ ## Output Format
145
+
146
+ - Repeated path reviewed
147
+ - Outer count, inner count, and data-growth classification
148
+ - Hidden scan patterns found or ruled out
149
+ - Membership, join, dedupe, helper, ORM, resolver, render, tree, graph, event, interval, sort, copy, string, and JSON checks where relevant
150
+ - Index, grouping, sorted merge, database join, or intentional all-pairs decision
151
+ - Semantics preserved: order, duplicates, first or last winner, missing IDs, authorization, and stable keys
152
+ - Evidence level: configured test, static complexity risk, manual-only, missing, or not applicable
153
+ - Command intents run
154
+ - Skipped measurements and reasons
155
+ - Remaining quadratic-scan risk
@@ -0,0 +1,193 @@
1
+ ---
2
+ mustflow_doc: skill.queue-processing-integrity-review
3
+ locale: en
4
+ canonical: true
5
+ revision: 1
6
+ lifecycle: mustflow-owned
7
+ authority: procedure
8
+ name: queue-processing-integrity-review
9
+ description: Apply this skill when code is created, changed, reviewed, or reported and queue, stream, pub/sub, broker, worker, task, job, consumer, producer, webhook handoff, DLQ, retry, redelivery, visibility timeout, offset commit, message ack, nack, reject, delete, publisher confirm, prefetch, rebalance, FIFO group, deduplication, or worker-loss behavior can lose work, duplicate work, hide poison messages, reorder state, exhaust consumers, or falsely claim processing success.
10
+ metadata:
11
+ mustflow_schema: "1"
12
+ mustflow_kind: procedure
13
+ pack_id: mustflow.core
14
+ skill_id: mustflow.core.queue-processing-integrity-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
+ # Queue Processing Integrity Review
28
+
29
+ <!-- mustflow-section: purpose -->
30
+ ## Purpose
31
+
32
+ Review queue processing by starting at the success boundary, not at dashboard lag or the top of the handler.
33
+
34
+ The core question is not "is the worker running?" It is "when does this code declare the message finished, and what state or side effect can still be missing, duplicated, reordered, or invisible after that declaration?"
35
+
36
+ <!-- mustflow-section: use-when -->
37
+ ## Use When
38
+
39
+ - Code creates, changes, reviews, or reports queue consumers, producers, stream processors, task workers, pub/sub handlers, delayed jobs, schedulers, webhooks handed to queues, DLQ replayers, retry workers, or batch consumers.
40
+ - Code calls or configures message acknowledgement, negative acknowledgement, reject, delete, visibility timeout, offset commit, publisher confirm, prefetch, concurrency, rebalance listeners, FIFO message groups, deduplication IDs, task acknowledgements, worker-loss behavior, dead-letter routing, or poison-message handling.
41
+ - Kafka, RabbitMQ, SQS, Celery, BullMQ, Sidekiq, Redis streams, Pub/Sub, NATS, Kinesis, Azure queues, or local equivalents appear in the changed path.
42
+ - A review or final report claims queue work is processed, durable, at-least-once, exactly-once, idempotent, retry-safe, backpressured, ordered, dead-lettered, observable, or safe after worker crash.
43
+
44
+ <!-- mustflow-section: do-not-use-when -->
45
+ ## Do Not Use When
46
+
47
+ - The task is primarily duplicate business intent across HTTP retries, webhooks, schedulers, or batch replays; use `idempotency-integrity-review` first and this skill for queue-specific delivery boundaries.
48
+ - The task is primarily swallowed exceptions, false success, unsafe fallback, timeout honesty, cancellation, or public error shape; use `failure-integrity-review` first and this skill for message settlement behavior.
49
+ - The task is primarily transaction isolation, rollback, outbox, after-commit, or read-decision-write atomicity; use `transaction-boundary-integrity-review` first and this skill for broker settlement.
50
+ - The task is primarily database query speed, cache correctness, API latency, or generic hot-path performance with no broker, worker, or redelivery surface.
51
+ - The queue path is read-only telemetry where dropped or duplicate messages are explicitly acceptable and no state, audit, billing, permission, notification, or external side effect depends on it.
52
+
53
+ <!-- mustflow-section: required-inputs -->
54
+ ## Required Inputs
55
+
56
+ - Broker and delivery model: queue or stream type, at-least-once or at-most-once assumptions, message identity, partition or group key, ordering requirement, redelivery behavior, and retention or visibility rules.
57
+ - Success boundary: exact ack, delete, commit, confirm, mark-complete, task-ack, batch-commit, or checkpoint call and every fallible operation before and after it.
58
+ - Producer boundary: enqueue, publish, send, transaction commit, outbox write, publisher confirm, broker response, retry behavior, and what happens when DB commit and publish split.
59
+ - Consumer state ledger: DB writes, external calls, emails, payments, inventory, cache writes, file writes, queue publishes, metrics, logs, audit entries, idempotency records, inbox records, and outbox records.
60
+ - Failure and retry policy: transient versus permanent failure, poison message classification, retry budget, backoff, jitter, DLQ threshold, requeue behavior, visibility extension, stuck in-flight recovery, and manual replay policy.
61
+ - Concurrency and ordering evidence: consumer parallelism, batch size, prefetch, thread pool, async handler ownership, per-key ordering, FIFO group cardinality, rebalance behavior, partition revoke handling, and in-progress commit fences.
62
+ - Observability evidence: message id, correlation id, attempt, age or queue delay, processing time, ack or commit decision, retry-after, DLQ reason, poison classification, worker-loss signal, and reconciliation signal.
63
+ - Test evidence: ack-before-work tests, work-before-ack crash tests, duplicate redelivery tests, poison message tests, visibility timeout tests, offset commit tests, publisher failure tests, rebalance tests, DLQ replay tests, and configured command intents.
64
+
65
+ <!-- mustflow-section: preconditions -->
66
+ ## Preconditions
67
+
68
+ - The task matches the Use When conditions and does not match the Do Not Use When exclusions.
69
+ - Higher-priority instructions and `.mustflow/config/commands.toml` have been checked for the current scope.
70
+ - Required broker, success-boundary, producer-boundary, retry, ordering, and observability evidence is available, or the missing evidence can be reported without guessing.
71
+ - Existing local patterns for consumers, producers, inbox, outbox, idempotency, retry, DLQ, partition or group ordering, worker shutdown, and metrics have been searched before adding new shapes.
72
+ - If queue processing moves money, credits, permissions, inventory, personal data, customer notifications, or provider calls, also apply the relevant payment, credit, security, idempotency, transaction, failure, or business-rule skill.
73
+
74
+ <!-- mustflow-section: allowed-edits -->
75
+ ## Allowed Edits
76
+
77
+ - Move ack, delete, commit, or task acknowledgement after durable processing when the local broker contract requires it, and make redelivery safe with idempotent handlers or inbox records.
78
+ - Add or tighten publisher confirmation, outbox writes, inbox or applied-message records, unique message or event keys, conditional state transitions, DLQ routing, poison-message classification, retry budgets, visibility extension, bounded concurrency, prefetch limits, rebalance hooks, and shutdown drains.
79
+ - Separate transient failures from permanent payload failures so invalid messages do not loop forever and temporary outages do not vanish as successful work.
80
+ - Add focused tests for the changed settlement, redelivery, ordering, retry, DLQ, and producer-confirm boundary.
81
+ - Do not replace durable message integrity with dashboard lag checks, log-only errors, frontend disabling, memory-only dedupe, unlimited parallelism, infinite requeue, or broad catch-and-ack behavior.
82
+ - Do not introduce live broker, server, watcher, tunnel, load-test, or manual replay commands outside the configured command contract.
83
+
84
+ <!-- mustflow-section: procedure -->
85
+ ## Procedure
86
+
87
+ 1. Start at the settlement call.
88
+ - Search the changed path for `ack`, `nack`, `reject`, `deleteMessage`, `commitSync`, `commitAsync`, `commit`, `checkpoint`, `confirm`, `task ack`, `acks_late`, `autoAck`, `auto.commit`, `visibility`, `prefetch`, `maxReceiveCount`, `MessageGroupId`, `deduplication`, and local equivalents.
89
+ - Treat these terms as anchors, not automatic bugs.
90
+ 2. Build the message lifecycle.
91
+ - Name the producer, broker, consumer, business handler, durable writes, external side effects, retry path, DLQ path, replay path, and final operator-visible state.
92
+ - Mark which component owns "received", "started", "durably applied", "externally applied", "settled", "retried", "dead-lettered", and "reconciled".
93
+ 3. Reject ack-before-truth.
94
+ - Ack, delete, commit, or mark-complete before durable work can lose the message when the next line fails.
95
+ - A `finally` block that always acknowledges is usually a discard policy disguised as cleanup.
96
+ - A catch block that logs and returns normally can have the same effect if the framework auto-acks normal returns.
97
+ 4. Reject unbounded redelivery loops.
98
+ - Blind nack, reject, requeue, or retry on every failure can keep one poison message burning CPU, network, logs, and downstream systems.
99
+ - Require permanent-failure classification, retry count, backoff, jitter, DLQ threshold, and a reason that helps replay or discard safely.
100
+ 5. Check producer confirmation.
101
+ - A producer that only calls `send` or `publish` may not know the broker durably accepted the message.
102
+ - If local DB commit and queue publish are separate, require outbox, transactional publish support, reconciliation, or a reported split-brain risk.
103
+ 6. Review async handler ownership.
104
+ - If processing returns a promise, future, coroutine, goroutine, thread, or background task, settlement must wait for the actual work or explicitly record durable handoff.
105
+ - Fire-and-forget work after ack is message loss unless the handoff itself is durable and observable.
106
+ 7. Review batch settlement.
107
+ - Batch commit after mixed success can skip failed items.
108
+ - Per-item failure handling, partial commit boundaries, ordered stop-on-failure behavior, or replay-safe idempotency should be explicit.
109
+ - Check off-by-one semantics where a committed offset or checkpoint means the next message to read, not the last item processed.
110
+ 8. Review SQS-style visibility and delete behavior.
111
+ - Receiving a message is not finishing it; delete is the success boundary.
112
+ - Visibility timeout should cover high-percentile processing or be extended with a heartbeat while avoiding recovery delays that are too long.
113
+ - Check stale receipt handles, in-flight limits, DLQ redrive thresholds, and duplicate processing after timeout.
114
+ 9. Review RabbitMQ-style ack behavior.
115
+ - `autoAck` or equivalent automatic acknowledgement is a loss-prone default for important work.
116
+ - `multiple=true` or bulk ack can acknowledge earlier concurrent deliveries that have not finished.
117
+ - Ack should happen on the owning channel or equivalent delivery context.
118
+ - Prefetch should bound unacknowledged work instead of loading unlimited messages into consumer memory.
119
+ 10. Review Kafka-style offset behavior.
120
+ - Auto-commit can move the durable cursor ahead of handler completion.
121
+ - Manual commits should reflect only records actually processed.
122
+ - Long processing should respect poll intervals, pause or resume behavior, worker handoff, and rebalance revoke handling so ownership changes do not lose or duplicate in-flight records unexpectedly.
123
+ 11. Review Celery-style task acknowledgement.
124
+ - Default early acknowledgement can mark a task complete before work runs.
125
+ - Late acknowledgement helps only when tasks are idempotent and worker-loss behavior is configured for the desired redelivery semantics.
126
+ - Broad auto-retry over every exception can turn invalid payloads into poison-message loops.
127
+ 12. Review ordering and concurrency.
128
+ - FIFO groups, Kafka partitions, per-tenant locks, entity keys, and aggregate ordering should match the business ordering requirement.
129
+ - One global group can serialize the whole system; a unique group for every message can destroy per-entity ordering.
130
+ - Parallel consumers need idempotency and conditional state transitions for redelivery and out-of-order completion.
131
+ 13. Review side-effect ordering.
132
+ - Email, payment, entitlement, stock, file conversion, webhooks, provider calls, and downstream publishes should not be able to run twice without a durable operation key.
133
+ - If side effects happen before completion markers, crash recovery needs idempotency, provider lookup, reconciliation, or compensation.
134
+ 14. Review DLQ as a workflow, not a bucket.
135
+ - DLQ entries need reason, attempt count, original queue, message identity, safe payload summary, replay eligibility, and alerting or ownership.
136
+ - A DLQ consumer or replay tool can repeat the same bug if it lacks idempotency, ordering, and poison classification.
137
+ 15. Review backpressure and resource bounds.
138
+ - Unlimited `Promise.all`, unbounded goroutines, huge prefetch, large batch size, or worker pools detached from DB and HTTP pool limits can move the bottleneck from broker lag to consumer collapse.
139
+ - Bound concurrency by downstream capacity and message processing cost.
140
+ 16. Review shutdown, cancellation, and worker loss.
141
+ - A worker should stop receiving new work, finish or safely abandon in-progress work, and avoid acknowledging work that did not complete.
142
+ - Cancellation should not be swallowed as success.
143
+ 17. Review observability at decision points.
144
+ - Logs and metrics should record the decision: processed, acknowledged, committed, retried, delayed, dead-lettered, discarded, or unknown.
145
+ - Useful fields include message id, correlation id, attempt, queue delay, processing duration, ack or commit result, retry-after, DLQ reason, and safe business key.
146
+ - "Received message" alone is not incident evidence.
147
+ 18. Require replay-path evidence.
148
+ - Good tests or integration checks cover duplicate delivery, handler failure before settlement, settlement failure after durable commit, poison payload, delayed redelivery, visibility expiry, rebalance, worker crash, DLQ replay, and producer publish failure.
149
+ - If deterministic broker evidence is not configured, report static risk and missing manual or integration proof instead of approving the path.
150
+
151
+ <!-- mustflow-section: postconditions -->
152
+ ## Postconditions
153
+
154
+ - The producer acceptance boundary, consumer settlement boundary, durable state boundary, retry or DLQ policy, ordering guarantee, resource bounds, shutdown behavior, and replay story are explicit.
155
+ - Ack-before-work, catch-and-ack, finally-ack, auto-ack, stale receipt handle, premature offset commit, batch partial-failure skip, unbounded requeue, poison-message loops, unsafe visibility timeout, in-flight saturation, FIFO group misuse, worker-loss false success, producer publish split, side-effect duplication, and observability gaps are fixed or reported.
156
+ - Queue safety claims are backed by configured tests, broker or framework evidence matched to current code, schema or idempotency evidence, static review evidence, or labeled as manual-only or missing.
157
+
158
+ <!-- mustflow-section: verification -->
159
+ ## Verification
160
+
161
+ Use configured oneshot command intents when available:
162
+
163
+ - `changes_status`
164
+ - `changes_diff_summary`
165
+ - `lint`
166
+ - `build`
167
+ - `test_related`
168
+ - `test`
169
+ - `docs_validate_fast`
170
+ - `test_release`
171
+ - `mustflow_check`
172
+
173
+ Prefer the narrowest configured test, build, docs, release, or mustflow intent that covers the changed queue processing boundary and synchronized template surfaces. Do not infer raw broker commands, local servers, live queue workers, replay scripts, load tests, watchers, tunnels, or manual dashboards outside the command contract.
174
+
175
+ <!-- mustflow-section: failure-handling -->
176
+ ## Failure Handling
177
+
178
+ - If a configured command fails, preserve the failing intent, failing assertion or output tail, and the queue-processing invariant it exercised before editing again.
179
+ - If the success boundary cannot be found, report that the queue path is not reviewable for processing integrity yet.
180
+ - If the broker delivery semantics are unknown, report the missing broker contract instead of assuming exactly-once behavior.
181
+ - If safe repair requires schema migration, outbox, inbox, durable dedupe, broker configuration, DLQ operator workflow, visibility heartbeat, rebalance architecture, or integration replay harness outside the current scope, report the missing durable boundary.
182
+ - If deterministic broker proof is not configured, complete available verification and report the missing manual or integration evidence.
183
+
184
+ <!-- mustflow-section: output-format -->
185
+ ## Output Format
186
+
187
+ - Queue processing boundary reviewed
188
+ - Broker model, producer confirm, consumer settlement, durable state, side effects, retry or DLQ policy, visibility or offset or ack behavior, batch behavior, ordering, concurrency, shutdown, observability, and replay evidence findings
189
+ - Queue-processing fixes made or recommended
190
+ - Evidence level: configured-test evidence, schema or idempotency evidence, broker or framework evidence, static review risk, manual-only, missing, or not applicable
191
+ - Command intents run
192
+ - Skipped queue diagnostics and reasons
193
+ - Remaining queue-processing-integrity risk
@@ -0,0 +1,188 @@
1
+ ---
2
+ mustflow_doc: skill.race-condition-review
3
+ locale: en
4
+ canonical: true
5
+ revision: 1
6
+ lifecycle: mustflow-owned
7
+ authority: procedure
8
+ name: race-condition-review
9
+ description: Apply this skill when code is created, changed, reviewed, or reported and shared state can be observed across interleaving execution flows, including check-then-act, read-modify-write, stale reads after await or I/O, lock scope and order, tryLock, timeout or retry behavior, cache miss fill, lazy initialization, atomics and memory ordering, database transaction races, uniqueness, distributed locks, idempotency, atomic file creation, event or outbox ordering, queue duplicates, shutdown, cancellation, timers, close/send races, shared collections, object reuse, fake immutability, sleep-based race tests, log ordering, and state-machine transitions.
10
+ metadata:
11
+ mustflow_schema: "1"
12
+ mustflow_kind: procedure
13
+ pack_id: mustflow.core
14
+ skill_id: mustflow.core.race-condition-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
+ # Race Condition Review
28
+
29
+ <!-- mustflow-section: purpose -->
30
+ ## Purpose
31
+
32
+ Find race conditions by tracing which shared facts can become stale before code acts on them.
33
+
34
+ The review question is not "does this code use threads?" The stronger question is "does code read a shared value, keep a meaning in its head for more than one step, and then let another execution flow change that meaning before the action?" Race bugs appear in async servers, queues, database writes, caches, filesystems, timers, shutdown paths, and event streams even when the language runtime has a single event loop.
35
+
36
+ <!-- mustflow-section: use-when -->
37
+ ## Use When
38
+
39
+ - Code is created, changed, reviewed, or reported and shared state, durable state, cached state, process state, collection state, socket state, file state, queue state, or lifecycle state can be touched by more than one request, worker, callback, timer, retry, queue delivery, or async continuation.
40
+ - Code reads state and later acts on that read after `await`, I/O, a database call, callback invocation, event publish, lock release, timer scheduling, queue insertion, retry, cancellation, shutdown, or another function call.
41
+ - Code uses check-then-act, read-modify-write, `++`, `+=`, `push`, `append`, `map[key] = value`, `get` then `set`, lazy initialization, double-checked locking, cache miss fill, sequence generation, state status changes, close/send operations, or object pooling.
42
+ - Code adds or changes locks, mutexes, synchronized blocks, distributed locks, atomic values, compare-and-swap, transaction isolation, row locks, unique constraints, idempotency keys, outbox or inbox processing, retry policies, queue consumers, timers, cancellation, or shutdown behavior.
43
+ - A review or final report claims a path is race-free, atomic, thread-safe, event-loop-safe, idempotent, lock-protected, transaction-protected, retry-safe, or safe under concurrent requests.
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 with no shared owner, durable store, callback, async yield, queue, timer, lock, or lifecycle boundary.
49
+ - The task is only object retention or cleanup risk; use `memory-lifetime-review` first and this skill only if cleanup races, cancellation races, or close/send races also matter.
50
+ - The task is only expected failure, retry, idempotency, cache, queue, or outbox behavior in a backend surface; use `backend-reliability-change` first and this skill as the interleaving adjunct.
51
+ - The task is only lifecycle transition modeling; use `state-machine-pattern` first and this skill only when stale concurrent transitions or duplicate side effects matter.
52
+ - The only concern is query speed, allocation churn, or hot-path latency with no stale-read or shared-state interleaving risk.
53
+
54
+ <!-- mustflow-section: required-inputs -->
55
+ ## Required Inputs
56
+
57
+ - Shared state surface: variable, object, collection, cache, file, socket, stream, database row, table, queue, message, state field, lock, atomic, timer, cancellation token, shutdown flag, or external side effect.
58
+ - Invariant: the fact that must stay true across more than one line, field, row, message, event, callback, or operation.
59
+ - Interleaving points: `await`, I/O, database calls, callbacks, hooks, plugin calls, event publish, queue insert, lock release, timer scheduling, retry, cancellation, shutdown, close, send, and other function calls after a state read.
60
+ - Synchronization boundary: lock scope, atomic operation, compare-and-swap, transaction, row lock, unique constraint, conditional update, singleflight, idempotency record, outbox, or file atomic create/rename behavior.
61
+ - Ordering and duplication rules: event order, queue delivery semantics, duplicate messages, same-user or same-resource concurrency, retry replay, cancellation timing, timer overlap, and shutdown drain behavior.
62
+ - Evidence surface: existing tests, fixtures, schema constraints, command intents, logs, metrics, sequence numbers, request ids, transaction ids, versions, or manual-only concurrency evidence.
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 state, invariant, isolation, lock, idempotency, or ordering facts can be reported without guessing.
70
+ - Existing local patterns for locks, atomics, database transactions, state machines, idempotency, queues, outbox/inbox, cancellation, shutdown, tests, and logging have been searched before adding new primitives.
71
+ - If the race affects authorization, personal data, money, orders, external side effects, or audit records, also apply the relevant security, backend reliability, database, or API skill.
72
+
73
+ <!-- mustflow-section: allowed-edits -->
74
+ ## Allowed Edits
75
+
76
+ - Replace check-then-act and read-modify-write sequences with atomic create, atomic conditional update, compare-and-swap, row lock, unique constraint, idempotency guard, singleflight, or a correctly scoped lock when local style supports it.
77
+ - Narrow lock scope to protect the whole invariant and remove slow callbacks, hooks, events, network calls, logs, JSON conversion, or plugin execution from inside locks where possible.
78
+ - Add global lock order, state transition guards, outbox or inbox guards, duplicate-message handling, cancellation and close idempotence, timer ownership checks, iterator snapshot handling, snapshot iteration, copy-on-write, or object ownership boundaries tied to the task.
79
+ - Add focused tests, fixtures, schema constraints, or docs that prove the concurrency invariant when the repository has a configured way to exercise it.
80
+ - Do not replace a real atomicity requirement with `sleep`, arbitrary delay, best-effort retry, log ordering, comments, or a distributed lock that is not backed by a durable data invariant.
81
+
82
+ <!-- mustflow-section: procedure -->
83
+ ## Procedure
84
+
85
+ 1. Name the shared fact. State the exact value or invariant another execution flow could change: balance, status, cache entry, uniqueness, queue offset, file existence, socket state, collection membership, timer owner, shutdown flag, or object ownership.
86
+ 2. Build a stale-read ledger.
87
+ - For each shared state read, mark every later `await`, I/O, DB call, callback, event publish, queue insertion, lock release, timer, retry, cancellation, shutdown, close, send, or function call before the action.
88
+ - Ask whether the read is still true after each interleaving point. If the answer relies on hope, the path is not race-safe.
89
+ 3. Catch check-then-act.
90
+ - Treat patterns such as `if exists then create`, `if balance >= amount then withdraw`, `if status == pending then approve`, duplicate email checks, coupon redemption, order number generation, and filesystem `exists` then `open` as unsafe until proven atomic.
91
+ - Prefer atomic conditional updates, atomic create, insert with unique constraint, compare-and-swap, row locks, or file creation modes that fail when the target already exists.
92
+ 4. Catch read-modify-write.
93
+ - `++`, `+=`, `push`, `append`, `map[key] = value`, collection mutation, get-then-set, and counter updates are shared-state writes, not harmless syntax.
94
+ - Use atomic operations only when the invariant is one variable. If the invariant spans fields, rows, objects, or messages, use a transaction, lock, state machine, or conditional write that protects the whole fact.
95
+ 5. Do not trust a single event loop after `await`.
96
+ - In JavaScript, Python async, UI runtimes, and coroutine systems, a state read before `await` can be stale after the continuation resumes.
97
+ - Re-read, validate a version, hold the correct synchronization boundary, or move the decision into an atomic operation.
98
+ 6. Review lock scope by invariant, not by field.
99
+ - A lock around one setter does not protect a multi-field or multi-row rule if reads and writes outside the lock can observe intermediate state.
100
+ - Keep callbacks, hooks, events, plugin calls, external I/O, logging, JSON conversion, and long calculations outside locks unless the invariant truly requires them.
101
+ - Define and follow a global lock order when more than one lock can be acquired.
102
+ 7. Treat `tryLock`, timeout, and retry as risk multipliers.
103
+ - Check what partial state remains when lock acquisition fails, times out, or is retried.
104
+ - Verify rollback, idempotency, duplicate side-effect prevention, and retry budget. A retry can make a race rarer or louder, not correct.
105
+ 8. Review cache miss fill and lazy initialization.
106
+ - Multiple misses for the same key should not all rebuild, fetch, insert, or publish the same value unless duplication is harmless and bounded.
107
+ - Use singleflight, promise memoization with failure cleanup, once initialization, durable uniqueness, or explicit cache-authority rules.
108
+ - Double-checked locking needs a memory-ordering story in runtimes where construction visibility is not automatically safe.
109
+ 9. Review atomics and memory ordering.
110
+ - Atomics protect a specific operation on a specific value. They do not automatically make surrounding objects, arrays, maps, or multi-field invariants safe.
111
+ - Check acquire/release or stronger memory ordering where the language exposes it, and report missing expertise or evidence instead of guessing.
112
+ 10. Review database races.
113
+ - A database transaction does not erase a race by itself. Check isolation level, row locks, predicate locks, uniqueness, conditional updates, and whether `SELECT` then `UPDATE` can be invalidated before commit.
114
+ - Prefer `UPDATE ... WHERE status = ...`, insert-or-ignore/upsert with unique constraints, version columns, row locks, or serializable isolation when the invariant requires it.
115
+ - Application-level duplicate checks are advisory only; unique facts belong in the database or another durable single-writer authority.
116
+ 11. Review distributed locks as debt.
117
+ - Lock expiry, process pauses, network delay, clock skew, and split ownership can let two workers believe they own the same work.
118
+ - Keep data correct if the distributed lock breaks: unique constraints, idempotency keys, fencing tokens, conditional writes, or state transitions should still reject stale owners.
119
+ 12. Review event, queue, and outbox ordering.
120
+ - Publishing an event before or after a state change can split the world unless a durable outbox or equivalent boundary ties them together.
121
+ - Queue consumers should assume duplicates, reordering, delayed delivery, redelivery after timeout, and concurrent work for the same user or resource.
122
+ - Use inbox deduplication, per-aggregate ordering, conditional state transitions, or idempotent side effects where needed.
123
+ 13. Review filesystem races.
124
+ - `exists` then `open`, temp file name selection, cleanup by path, and replace-in-place can race.
125
+ - Prefer atomic create, safe temporary file APIs, same-directory temp files, fsync where durability matters, and atomic rename or replace semantics appropriate to the platform.
126
+ 14. Review shutdown, cancellation, timers, close, and send.
127
+ - Shutdown should define who stops accepting work, who drains, who cancels, and who owns in-flight side effects.
128
+ - Cancellation must be idempotent and safe when completion happens at the same time.
129
+ - Timers and schedulers need one current owner; old timers should not update new state.
130
+ - WebSocket, channel, stream, socket, queue, and emitter paths need a clear rule for close/send races and double close.
131
+ 15. Review shared collections and object reuse.
132
+ - Iteration over a collection that another flow can mutate needs a lock, snapshot, immutable copy, version check, or concurrent collection semantics.
133
+ - Object pooling, buffer reuse, mutable DTO reuse, and reused request contexts are unsafe if async work can still hold references.
134
+ - Fake immutable objects with mutable internals, getters, shared maps, or cached arrays should be treated as mutable shared state.
135
+ 16. Review tests and logs with suspicion.
136
+ - `sleep`-based race tests are usually probability tests. Prefer deterministic barriers, fake schedulers, controlled promises, version assertions, unique constraints, or repeated stress only as supplementary evidence.
137
+ - Logging can hide or change a race. Log order is not event order across threads, processes, async tasks, buffers, or machines.
138
+ - Use monotonic sequence numbers, request ids, transaction ids, version columns, or state transition logs when ordering is evidence.
139
+ 17. Escalate broad status fields into state-machine review.
140
+ - If values such as `pending`, `processing`, `done`, `failed`, `cancelled`, `closed`, or `deleted` drive behavior, draw allowed transitions and reject stale concurrent transitions.
141
+ - Use `state-machine-pattern` when the race fix needs a transition table, event union, transition log, retry reconciliation, or effect ordering.
142
+
143
+ <!-- mustflow-section: postconditions -->
144
+ ## Postconditions
145
+
146
+ - Shared state reads, interleaving points, and stale-read risks are identified or ruled out.
147
+ - Check-then-act and read-modify-write paths are atomic, guarded, constrained, or explicitly reported as residual risk.
148
+ - Locks protect whole invariants, have a clear ordering rule, and avoid slow or reentrant work where possible.
149
+ - Database, cache, queue, event, filesystem, cancellation, shutdown, timer, close/send, collection, and object-reuse races are checked where relevant.
150
+ - Tests or configured verification cover the highest-risk concurrency invariant when feasible.
151
+
152
+ <!-- mustflow-section: verification -->
153
+ ## Verification
154
+
155
+ Use configured oneshot command intents when available:
156
+
157
+ - `changes_status`
158
+ - `changes_diff_summary`
159
+ - `lint`
160
+ - `build`
161
+ - `test_related`
162
+ - `test`
163
+ - `docs_validate_fast`
164
+ - `test_release`
165
+ - `mustflow_check`
166
+
167
+ Prefer the narrowest configured test, build, docs, release, or mustflow intent that proves the changed concurrency invariant. Do not infer raw stress, load, database, queue, thread sanitizer, profiler, server, watcher, or sleep-loop commands outside the command contract.
168
+
169
+ <!-- mustflow-section: failure-handling -->
170
+ ## Failure Handling
171
+
172
+ - If a configured command fails, preserve the failing intent, failing assertion or output tail, and the shared-state invariant it exercised before editing again.
173
+ - If the invariant cannot be named, stop and report that the code is not reviewable for races yet.
174
+ - If a fix requires a schema constraint, isolation change, outbox, queue contract, state-machine transition, or idempotency store outside the current scope, report the missing durable boundary instead of adding a local lock that cannot enforce it.
175
+ - If deterministic race proof is not configured, report the missing manual evidence and complete the configured checks that are available.
176
+
177
+ <!-- mustflow-section: output-format -->
178
+ ## Output Format
179
+
180
+ - Shared state and invariant reviewed
181
+ - Interleaving points checked
182
+ - Check-then-act and read-modify-write findings
183
+ - Async stale-read, lock scope/order, tryLock/timeout/retry, cache/lazy init, atomic/memory ordering, database transaction, uniqueness, distributed lock, idempotency, filesystem, event/outbox, queue, shutdown, cancellation, timer, close/send, shared collection, object reuse, fake immutable, test, log, and state-machine checks where relevant
184
+ - Race fixes made or recommended
185
+ - Tests or verification evidence
186
+ - Command intents run
187
+ - Skipped concurrency diagnostics and reasons
188
+ - Remaining race-condition risk