mustflow 2.18.21 → 2.21.2

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 (46) hide show
  1. package/dist/cli/commands/classify.js +2 -3
  2. package/dist/cli/commands/doctor.js +46 -6
  3. package/dist/cli/commands/run/output.js +1 -1
  4. package/dist/cli/commands/run/receipt.js +1 -0
  5. package/dist/cli/commands/run.js +3 -1
  6. package/dist/cli/commands/verify.js +15 -10
  7. package/dist/cli/i18n/en.js +1 -0
  8. package/dist/cli/i18n/es.js +1 -0
  9. package/dist/cli/i18n/fr.js +1 -0
  10. package/dist/cli/i18n/hi.js +1 -0
  11. package/dist/cli/i18n/ko.js +1 -0
  12. package/dist/cli/i18n/zh.js +1 -0
  13. package/dist/cli/lib/filesystem.js +3 -96
  14. package/dist/cli/lib/local-index/index.js +4 -4
  15. package/dist/cli/lib/repo-map.js +3 -2
  16. package/dist/cli/lib/run-plan.js +8 -4
  17. package/dist/core/check-issues.js +1 -1
  18. package/dist/core/command-contract-validation.js +24 -10
  19. package/dist/core/command-effects.js +3 -4
  20. package/dist/core/command-output-limits.js +2 -1
  21. package/dist/core/line-endings.js +12 -4
  22. package/dist/core/repeated-failure.js +3 -3
  23. package/dist/core/run-performance-history.js +4 -4
  24. package/dist/core/run-profile.js +2 -3
  25. package/dist/core/run-receipt.js +11 -3
  26. package/dist/core/run-write-drift.js +67 -15
  27. package/dist/core/safe-filesystem.js +158 -0
  28. package/package.json +1 -1
  29. package/schemas/commands.schema.json +1 -0
  30. package/schemas/doctor-report.schema.json +23 -1
  31. package/schemas/run-receipt.schema.json +6 -2
  32. package/templates/default/i18n.toml +13 -13
  33. package/templates/default/locales/en/.mustflow/skills/INDEX.md +13 -13
  34. package/templates/default/locales/en/.mustflow/skills/adapter-boundary/SKILL.md +72 -4
  35. package/templates/default/locales/en/.mustflow/skills/command-contract-authoring/SKILL.md +16 -10
  36. package/templates/default/locales/en/.mustflow/skills/command-pattern/SKILL.md +64 -7
  37. package/templates/default/locales/en/.mustflow/skills/database-change-safety/SKILL.md +249 -16
  38. package/templates/default/locales/en/.mustflow/skills/dependency-reality-check/SKILL.md +37 -7
  39. package/templates/default/locales/en/.mustflow/skills/migration-safety-check/SKILL.md +74 -10
  40. package/templates/default/locales/en/.mustflow/skills/performance-budget-check/SKILL.md +132 -5
  41. package/templates/default/locales/en/.mustflow/skills/pure-core-imperative-shell/SKILL.md +12 -5
  42. package/templates/default/locales/en/.mustflow/skills/result-option/SKILL.md +4 -2
  43. package/templates/default/locales/en/.mustflow/skills/security-privacy-review/SKILL.md +112 -29
  44. package/templates/default/locales/en/.mustflow/skills/state-machine-pattern/SKILL.md +17 -4
  45. package/templates/default/locales/en/.mustflow/skills/structure-discovery-gate/SKILL.md +193 -2
  46. package/templates/default/manifest.toml +1 -1
@@ -2,11 +2,11 @@
2
2
  mustflow_doc: skill.dependency-reality-check
3
3
  locale: en
4
4
  canonical: true
5
- revision: 3
5
+ revision: 6
6
6
  lifecycle: mustflow-owned
7
7
  authority: procedure
8
8
  name: dependency-reality-check
9
- description: Apply this skill when a task assumes, adds, removes, imports, invokes, installs, audits, or documents a package, runtime, tool, command, service, or platform capability, especially for AI-suggested dependencies or supply-chain-sensitive changes.
9
+ description: Apply this skill when a task assumes, adds, removes, imports, invokes, installs, audits, or documents a package, runtime, framework, tool, command, service, platform capability, supported-version policy, security patch path, ecosystem maturity claim, maintainer-risk assumption, runtime portability claim, edge or serverless compatibility claim, critical-path dependency choice, or experimental technology placement, especially for AI-suggested dependencies, core backend stack choices, or supply-chain-sensitive changes.
10
10
  metadata:
11
11
  mustflow_schema: "1"
12
12
  mustflow_kind: procedure
@@ -34,6 +34,12 @@ Prevent code, docs, tests, and final reports from assuming unavailable packages,
34
34
  - An AI-generated patch, assistant suggestion, copied snippet, or generated docs introduce a package name that could be hallucinated, misspelled, abandoned, lookalike, or unnecessary.
35
35
  - A change adds package-manager scripts, package lifecycle hooks, build downloads, binary installers, lockfile changes, audit suppression, vulnerability scanner output, or CI dependency gates.
36
36
  - A solution relies on a package manager, binary, environment variable, browser API, operating-system command, hosted service, or optional integration.
37
+ - A dependency or platform is proposed for authentication, payment, database, migrations, authorization, cryptography, deployment, queueing, file storage, email, or another survival path where failure can stop the product.
38
+ - A small, experimental, single-maintainer, fast-moving, or platform-specific dependency is proposed and the task needs to decide whether it belongs in a differentiating feature or a core operating path.
39
+ - A language runtime or web framework choice needs to prove supported or LTS version policy, end-of-life avoidance, security advisory response, dependency lock behavior, smoke-test coverage, deployment path, and rollback path.
40
+ - A JavaScript or TypeScript runtime claim treats Node, Bun, Deno, serverless functions, edge runtime, Web-standard adapters, or Node compatibility modes as interchangeable without checking which APIs, packages, native modules, filesystem access, connection reuse, or platform features the code actually uses.
41
+ - A framework feature such as server actions, route handlers, edge middleware, framework cache, ORM relation helpers, or hosted platform storage is proposed for core business logic rather than for delivery, persistence, or infrastructure glue.
42
+ - Documentation or design claims that a technology has enough ecosystem support, production use, migration path, failure examples, security response, or maintainer coverage.
37
43
  - A generated instruction tells another agent or user to run a tool that may not be declared in the repository.
38
44
  - A failure may be caused by a missing install, mismatched version, unsupported runtime, or unavailable command.
39
45
 
@@ -51,6 +57,10 @@ Prevent code, docs, tests, and final reports from assuming unavailable packages,
51
57
  - Package, lock, config, import, script, command-intent, or documentation files that declare or reference it.
52
58
  - The minimum version, capability, or availability claim if one is required.
53
59
  - Registry name, package scope, lockfile entry, provenance or maintainer expectation, install script risk, and whether the dependency is runtime, development, fixture-only, transitive, or optional.
60
+ - Dependency role criticality: decorative utility, product-experience feature, operational support, or survival path such as identity, money, durable data, permissions, security, migrations, deployment, queues, or file ownership.
61
+ - Runtime and framework patchability: supported-version or LTS expectation, end-of-life status, security advisory channel, update cadence, dependency-lock behavior, deployment artifact, smoke-test surface, rollback route, and whether the choice is experimental, regulated, or core-path-facing.
62
+ - Runtime compatibility boundary: whether code imports Node-specific APIs, Bun or Deno globals, edge-only APIs, native modules, filesystem access, framework request objects, environment reads, ORM clients, or platform storage and queue objects outside delivery or infrastructure layers.
63
+ - Ecosystem and maintainer context when available from approved tooling or existing metadata: maintainer count, organization or foundation backing, release history, issue handling, security policy, migration docs, failure cases, license clarity, tests, alternatives, and hiring or support availability.
54
64
  - Vulnerability, license, audit, lifecycle-script, binary-download, package-age, maintainer-change, and fork-or-replacement context when those details are available from approved repository tooling or existing metadata.
55
65
  - Relevant command-intent contract entries for build, package, test, or documentation verification.
56
66
 
@@ -81,16 +91,33 @@ Prevent code, docs, tests, and final reports from assuming unavailable packages,
81
91
  6. If absent, prefer an existing local alternative. Add a new dependency only when it is necessary, within the task scope, and reflected in the package metadata and lockfile policy.
82
92
  7. Treat package scripts and lifecycle hooks as executable code. Review `preinstall`, `install`, `postinstall`, `prepare`, build-time downloads, generated binaries, and shell-spawning scripts before accepting them.
83
93
  8. Check supply-chain-sensitive metadata when available through approved tooling or existing files: package scope, maintainer or organization expectation, package age, maintainer changes, install scripts, binary downloads, transitive dependency impact, license constraints, and fixture-only versus runtime use.
84
- 9. For vulnerability or audit output, separate runtime dependencies from fixture-only or intentionally vulnerable samples. Do not weaken audit gates, delete lockfiles, or add broad suppressions without a repository-owned reason.
85
- 10. For new dependencies, prefer pinned or lockfile-backed versions according to project policy. Avoid widening ranges or removing lockfiles to satisfy generated code.
86
- 11. Do not introduce new package-manager wrappers, vulnerability scanners, registry queries, or install commands inside this skill. Use configured command intents or report the missing verification surface.
87
- 12. Keep all dependency-facing surfaces aligned: package metadata, lockfiles when intentionally updated, command contract, docs, tests, and installation notes.
88
- 13. Run the narrowest configured verification that proves the dependency path used by the change.
94
+ 9. Classify the dependency by product criticality.
95
+ - Decorative or utility dependencies can be small when they are pure, replaceable, locked, and easy to remove.
96
+ - Product-experience dependencies such as charts, editors, calendars, or drag-and-drop should be wrapped or localized when they can spread through the UI.
97
+ - Operational dependencies such as logs, queues, caches, search, file processing, and email need maturity, observability, failure handling, and a replacement path.
98
+ - Survival-path dependencies such as authentication, payment, database access, migrations, authorization, cryptography, deployment, and security should avoid fragile single-maintainer or experimental choices unless the project explicitly accepts the risk.
99
+ 10. Place new or experimental technology intentionally. Prefer proven, boring dependencies for the survival path; reserve experimental technology for differentiating product areas such as UX, AI workflow, search experience, visualization, or internal tooling, and keep it isolated enough to replace.
100
+ - For runtime and framework choices, judge the stack by whether security patches can be applied, tested, deployed, and rolled back quickly. Do not treat performance benchmarks or developer excitement as a substitute for a supported-version policy and a working patch circuit.
101
+ - Keep experimental runtimes and fast-moving frameworks away from authentication, payment, authorization, database, migration, cryptography, and security-critical deployment paths unless the project explicitly accepts the risk and has a rollback plan.
102
+ 11. For runtime portability claims, inspect dependency leakage by layer before accepting the claim.
103
+ - Core and application code should not depend on Node-only APIs, Bun or Deno globals, edge-only globals, framework request objects, ORM clients, environment variables, or platform-specific queue and storage clients.
104
+ - Delivery and infrastructure layers may use runtime or framework capabilities, but the choice should be visible as an adapter decision rather than scattered through use cases.
105
+ - Treat Web-standard frameworks or adapters as a portability aid, not as proof that domain code is portable if provider SDKs, ORM clients, filesystem calls, or platform bindings still leak inward.
106
+ 12. Evaluate ecosystem maturity when the task depends on it: production examples, searchable error solutions, migration notes, security-response history, version stability, plugin ecosystem, older issue answers, support availability, and whether the direction is likely to hold over the next release cycles.
107
+ 13. For small libraries, accept them only when they are small in role as well as code: simple, understandable, peripheral, safe to fork or reimplement, and not directly touching secrets, personal data, money, permissions, migrations, durable state, or security.
108
+ 14. For vulnerability or audit output, separate runtime dependencies from fixture-only or intentionally vulnerable samples. Do not weaken audit gates, delete lockfiles, or add broad suppressions without a repository-owned reason.
109
+ 15. For new dependencies, prefer pinned or lockfile-backed versions according to project policy. Avoid widening ranges or removing lockfiles to satisfy generated code.
110
+ 16. Do not introduce new package-manager wrappers, vulnerability scanners, registry queries, or install commands inside this skill. Use configured command intents or report the missing verification surface.
111
+ 17. Keep all dependency-facing surfaces aligned: package metadata, lockfiles when intentionally updated, command contract, docs, tests, and installation notes.
112
+ 18. Run the narrowest configured verification that proves the dependency path used by the change.
89
113
 
90
114
  <!-- mustflow-section: postconditions -->
91
115
  ## Postconditions
92
116
 
93
117
  - Every dependency or tool claim is backed by a repository declaration, configured command, host boundary, or explicit unverified-risk note.
118
+ - Critical-path dependency choices identify role criticality, maintainer concentration, ecosystem maturity, replacement path, and whether the dependency belongs in a survival path or a differentiating feature.
119
+ - Runtime and framework choices identify supported-version policy, end-of-life exposure, security patch path, smoke-test surface, deployment and rollback route, and whether experimental choices are isolated from survival paths.
120
+ - Runtime portability claims identify which APIs are confined to delivery or infrastructure and which would force core or application code to change when moving between Node, Bun, Deno, serverless functions, or edge runtime.
94
121
  - New dependency requirements are reflected in the appropriate metadata and public documentation.
95
122
  - The final report states whether the dependency was existing, added, optional, unavailable, or intentionally not verified.
96
123
 
@@ -122,6 +149,9 @@ Use a narrower configured test, package, or docs intent when it better proves th
122
149
 
123
150
  - Dependency or capability checked
124
151
  - Repository declaration or absence
152
+ - Role criticality, ecosystem maturity, maintainer-risk, and replacement-path boundary when relevant
153
+ - Supported-version, patchability, smoke-test, rollback, and experimental-placement boundary when relevant
154
+ - Runtime portability, framework feature leakage, and layer-containment boundary when relevant
125
155
  - Surfaces synchronized
126
156
  - Command intents run
127
157
  - Skipped dependency checks and reasons
@@ -2,11 +2,11 @@
2
2
  mustflow_doc: skill.migration-safety-check
3
3
  locale: en
4
4
  canonical: true
5
- revision: 1
5
+ revision: 8
6
6
  lifecycle: mustflow-owned
7
7
  authority: procedure
8
8
  name: migration-safety-check
9
- description: Apply this skill when code, data, schema, configuration, file layout, template, or generated-state migrations are planned, edited, documented, or reported.
9
+ description: Apply this skill when code, data, schema, configuration, file layout, template, content frontmatter, file-to-database, SQLite-to-PostgreSQL, local-disk-to-object-storage, tenant-boundary, URL, slug, content lifecycle, asset path or variant, claim or fact extraction, global-ready time money locale or currency backfills, API projection compatibility, public identifier changes, provider id mappings, event-schema changes, search index or ranking migration, queue message or retry-policy migration, log or analytics migration, observability identifier continuity, deployment-state reproduction, generated-state, backup or restore proof, expand-migrate-contract deployment, destructive schema rollback, semantic export, import, platform exit, or cache migrations are planned, edited, documented, or reported.
10
10
  metadata:
11
11
  mustflow_schema: "1"
12
12
  mustflow_kind: procedure
@@ -32,6 +32,16 @@ Keep migrations reversible, scoped, and verified before they affect data, schema
32
32
 
33
33
  - A change moves, renames, deletes, transforms, backfills, or rewrites files, data, schemas, configuration, template state, generated state, or persisted metadata.
34
34
  - A task mentions migration, upgrade, conversion, import, export, reindexing, backfill, cleanup, lock refresh, or baseline regeneration.
35
+ - Content moves between inline code, Markdown/MDX files, CMS documents, database rows, generated indexes, site-specific overrides, central facts, redirects, or reusable content blocks.
36
+ - Existing content must gain lifecycle states, redirects, topic aliases, relationship records, asset metadata, immutable originals, variants, claim or fact references, comparison methodology records, affiliate link records, or exportable ownership metadata.
37
+ - Existing APIs, mobile clients, integrations, analytics events, cache keys, public identifiers, read models, generated indexes, or reporting tables must survive a schema or storage shape change.
38
+ - Existing product state must survive leaving a CMS, hosted database, authentication provider, payment provider, file store, analytics tool, observability backend, deployment platform, or closed automation tool.
39
+ - Existing search quality, search ranking policy, search documents, synonyms, query logs, click logs, queue messages, retry policy, dead-letter history, product events, audit events, billing events, job events, or operator troubleshooting records must survive leaving a search engine, queue, log backend, analytics SaaS, or dashboard-driven automation.
40
+ - Existing request ids, trace ids, job ids, webhook ids, event ids, user ids, organization ids, or provider id mappings must survive a log, trace, metrics, event, job, webhook, export, or import migration.
41
+ - Existing local SQLite files, local upload directories, object-storage keys, public file URLs, tenant or workspace fields, server-side authorization scope, or API response shapes must survive a persistence or deployment change.
42
+ - Existing timestamp, date-only, timezone, currency, price, exchange-rate, tax, locale, country, account-default, user-preference, or AI-pricing fields must be split, backfilled, snapshotted, or made globally safe.
43
+ - A migration touches destructive schema changes such as dropping columns, changing column types, setting `NOT NULL`, adding constraints, creating large indexes, rewriting many rows, or claiming that a `down` migration makes rollback safe.
44
+ - Documentation or final reports claim that backup, restore, cache rebuild, index rebuild, or analytics migration is safe, tested, repeatable, or complete.
35
45
  - Documentation or final reports claim that a migration is safe, complete, reversible, idempotent, or already applied.
36
46
  - A change could make older installed projects, existing lock files, generated files, caches, or user-edited documents incompatible.
37
47
 
@@ -47,6 +57,17 @@ Keep migrations reversible, scoped, and verified before they affect data, schema
47
57
 
48
58
  - The source state, target state, and the files or data that would change.
49
59
  - The owner of the migration surface: code, schema, template, lock file, generated state, cache, package, or docs.
60
+ - Content identity, slug, URL, frontmatter schema, relationship, fact, source, search index, sitemap, analytics, and cache dependency expectations when content or site migrations are involved.
61
+ - Lifecycle state mapping, asset path mapping, original versus variant ownership, topic or tag merge history, policy or fact extraction, comparison methodology backfill, affiliate link classification, export shape, and deletion or anonymization expectations when those surfaces are involved.
62
+ - API response compatibility, public id mapping, client version support, analytics event versioning, cache key versioning, search index rebuild, reporting aggregate rebuild, and projection backfill expectations when those surfaces are involved.
63
+ - Database engine mapping, local file path mapping, object-storage key mapping, tenant or workspace ownership mapping, private download URL behavior, and API response mapper compatibility when those surfaces are involved.
64
+ - Restore-test evidence or restore gap, including database, files, secrets or environment configuration, migration history, external service settings, queue or job state, and cache storage when the migration depends on recovery guarantees.
65
+ - Export/import reconstruction evidence or gap, including relationships, permissions, files, versions, event history, audit history, automation rules, external integration mappings, provider id mappings, schemas, and whether imported data can rebuild a working service elsewhere.
66
+ - Search, queue, log, and analytics reconstruction evidence or gap, including search document structure, ranking or boost policy, representative query expectations, queue message envelope and schema versions, idempotency keys, retry and dead-letter rules, internal event list, retention windows, and raw event export or replay paths.
67
+ - Deployment-state migration evidence or gap, including environment variable schema, secret names, DNS records, domains, SSL assumptions, redirects, cron schedules, runtime versions, build commands, regions, storage, queues, worker settings, observability routing, and rollback behavior.
68
+ - Rollback type expected: schema rollback, data rollback, application rollback, operational restore, forward corrective migration, or explicit no-rollback boundary.
69
+ - Deployment compatibility rule: whether old application code can run on the new schema, whether new application code can run while old fields remain, and when destructive cleanup is safe.
70
+ - Operational safety limits for live databases: rehearsal dataset, expected lock time, statement timeout, lock timeout, batch size, restart marker, validation query, and point-in-time restore availability when applicable.
50
71
  - Idempotency, rollback, backup, dry-run, compatibility, and failure behavior expectations.
51
72
  - Relevant command-intent contract entries for status, diff, docs, release, build, or mustflow validation.
52
73
 
@@ -69,19 +90,58 @@ Keep migrations reversible, scoped, and verified before they affect data, schema
69
90
  ## Procedure
70
91
 
71
92
  1. Identify the migration surface and classify it as code, schema, data, configuration, template, generated state, cache, package metadata, or documentation.
93
+ For content systems, also classify whether it touches inline page content, body files, frontmatter, lifecycle states, slug history, redirects, taxonomy, assets, facts, claims, sources, site exposure, search index, feeds, sitemaps, analytics events, exports, or public API projections.
72
94
  2. Record the source state, target state, expected affected paths, and whether the change must support old and new states during transition.
73
- 3. Check whether the migration is idempotent: a second run should either do nothing or report an already-applied state without extra diffs.
74
- 4. Check rollback or recovery expectations: backup, restore path, manual fallback, or explicit "not reversible" report.
75
- 5. Prefer dry-run or read-only inspection before apply behavior when a command or workflow exists for it.
76
- 6. Keep compatibility claims tied to fixtures, lock metadata, tests, generated output, or documented command results.
77
- 7. If the migration changes public docs, installed templates, package contents, or lock files, synchronize the related metadata and version surfaces.
78
- 8. Run the narrowest configured verification that proves the migrated surface and its metadata still agree.
95
+ - Prefer an expand, backfill, switch, and shrink sequence for live schema and API changes: add the new shape, support old and new reads or writes, migrate data, switch readers, then remove the old shape only after compatibility is proven.
96
+ - Treat rollback as more than `down` migration. Distinguish schema rollback, data rollback, app rollback, and operational restore. A `down` file does not recover deleted or overwritten data unless the original values were preserved.
97
+ - Prefer forward-only recovery for live systems: if a change fails after partial application, use a corrective migration or compatibility patch unless a tested restore path proves a rewind is safer.
98
+ - Delay destructive cleanup such as `DROP COLUMN`, type changes, `SET NOT NULL`, irreversible rewrites, and old-field removal until at least one compatible application version and validation window have proven the new shape.
99
+ - For large tables, separate schema expansion from data backfill. Make backfills restartable, bounded by batches, and validated with queries that count missing, malformed, duplicate, or conflicting rows.
100
+ - For globally safe data fixes, backfill time, money, locale, country, currency, and timezone from explicit evidence only. If a value was previously inferred, mark confidence or require review instead of silently treating inference as fact.
101
+ 3. Check identity preservation. Stable ids, content groups, entity ids, author ids, asset ids, and API ids should survive title, slug, file path, locale, category, site, or provider changes.
102
+ - If internal numeric ids are replaced or hidden by public ids, preserve mapping, redirects or aliases, audit references, API compatibility, and analytics continuity.
103
+ 4. Check whether the migration is idempotent: a second run should either do nothing or report an already-applied state without extra diffs.
104
+ 5. Check rollback or recovery expectations: backup, restore path, manual fallback, redirect fallback, old/new schema compatibility, or explicit "not reversible" report.
105
+ - Before risky live database work, require recent backup or point-in-time restore capability, rehearsal on production-like data when possible, expected lock behavior, statement and lock timeouts, and a documented stop condition.
106
+ 6. Prefer dry-run or read-only inspection before apply behavior when a command or workflow exists for it.
107
+ 7. For file-to-database or database-to-file content migration, verify that strict metadata is preserved or intentionally introduced: id, type, status, locale, slug, summary, author, created/updated actors, category, tags, related entities, SEO fields, canonical group, site exposure, and access level where relevant.
108
+ 8. For lifecycle migration, map old booleans or ad hoc flags into explicit states such as draft, scheduled, published, unlisted, private, archived, deprecated, redirected, gone, and soft-deleted without losing search, access, retention, or recovery semantics.
109
+ 9. For URL or slug migration, verify canonical targets, old-to-new redirects, duplicate handling, sitemap and canonical updates, analytics continuity, and cache invalidation.
110
+ 10. For asset migration, preserve immutable originals, introduce stable asset ids, avoid storage keys tied to mutable slugs, rebuild variants from originals, carry alt text, license, credit, dimensions, hash, focal point, and usage references, and report any missing metadata that cannot be inferred safely.
111
+ 11. For taxonomy or relationship migration, preserve tag aliases, merge history, topic-hub indexability, relationship type, direction, order, confidence, manual or automatic source, reason, and creator when those fields affect search, navigation, analytics, or SEO.
112
+ 12. For fact, claim, policy, comparison, or affiliate extraction, verify that changing facts move to typed entity, claim, source, methodology, result, or affiliate records with source, observed or effective dates, jurisdiction, risk tier, reviewer, relationship policy, and usage mappings while historical prose remains intentionally preserved or annotated.
113
+ 13. For export or platform-exit migration, verify that content, assets, redirects, tag merges, claim references, source references, revisions, and page dependencies can be exported or rebuilt without relying on the current CMS screen layout.
114
+ - Treat CSV-only export as insufficient for product-state migration when relationships, permissions, comments, files, history, automations, provider mappings, or audit trails define the service meaning.
115
+ - Preserve product-owned stable ids and map provider ids separately. Payment, authentication, CRM, storage, analytics, observability, and CMS ids should be replaceable without breaking internal references.
116
+ - Verify import or restore shape, not only download shape. If data cannot be loaded into another environment or self-hosted replacement, report the export as partial.
117
+ - Treat provider dashboards and no-code screens as migration inputs only when their hidden rules can be represented as data, configuration, code, or documented operator procedure. Manual refund, permission repair, file deletion, customer verification, and email automation habits need an owner before tool replacement.
118
+ - For search migration, rebuild the index from source records and compare representative queries or expected top results before claiming quality continuity. Search settings changed only through a hosted dashboard need a captured policy or change log.
119
+ - For queue migration, preserve a versioned message envelope, job type list, retry policy, timeout, dead-letter state, ordering requirement, idempotency key, and manual replay procedure. Do not claim queue replacement is safe from message transport alone.
120
+ - For log or analytics migration, separate raw historical events from dashboards. Keep event names, schema versions, request or trace ids, retention rules, and core billing, entitlement, file, security, job, search, and support events available outside the SaaS.
121
+ 14. For deployment-platform migration, verify that operating state is reproducible from code and docs rather than dashboard memory. Preserve or recreate environment variable schemas, secret names, domain and DNS records, redirects, SSL assumptions, cron jobs, build commands, runtime versions, regions, storage buckets, queues, worker settings, observability routing, deployment hooks, and rollback procedure.
122
+ 15. For observability migration, preserve request id, trace id, span id, user or anonymous id, tenant or organization id, command id, job run id, webhook event id, and event schema version continuity. Do not migrate logs or traces in a way that replaces internal ids with email, token, payment customer id, or other sensitive provider identifiers.
123
+ 16. For database-engine migration, such as SQLite to PostgreSQL, preserve schema constraints, transaction semantics, public ids, timestamps, JSON handling, unique indexes, idempotency keys, audit references, and backup or restore expectations. Check write-concurrency behavior, locking assumptions, and any code that depended on local file paths or process-local database access.
124
+ 17. For local-disk to object-storage migration, preserve stable asset ids, owner or workspace scope, original filenames as metadata, storage keys independent from mutable user input, visibility, status, checksums, variants, signed download behavior, and cleanup of stale local files or orphaned remote objects.
125
+ 18. For tenant-boundary migration, verify that every affected read, list, search, mutation, upload, download, admin operation, audit log, idempotency key, cache key, and analytics event maps to the correct workspace, organization, team, or account before enforcing the new scope.
126
+ 19. Keep compatibility claims tied to fixtures, lock metadata, tests, generated output, or documented command results.
127
+ 20. For API or projection migration, verify that database table splits, column renames, status remaps, relationship moves, storage-key changes, and internal identifier changes are absorbed by response mappers or versioned contracts before they break clients.
128
+ 21. For analytics or event migration, keep event names and schema versions explicit. Do not mix old and new event payload meanings under one unversioned JSON shape.
129
+ 22. For cache migration, version cache keys when response shape, visibility, filter normalization, ranking formula, or source-of-truth rules change. Define whether old keys can expire naturally or need an explicit purge.
130
+ 23. For backup or restore claims, require evidence from a clean-environment restore or report the missing drill. A backup file, snapshot setting, or managed-service checkbox is not enough to claim restore readiness.
131
+ 24. For AI usage or model-pricing migrations, preserve request identity, provider-call identity, feature key, pricing snapshot, retry grouping, cache-hit type, and historical cost units. Do not recalculate past AI costs from only the current provider price sheet.
132
+ 25. If the migration changes public docs, installed templates, package contents, or lock files, synchronize the related metadata and version surfaces.
133
+ 26. Run the narrowest configured verification that proves the migrated surface and its metadata still agree.
79
134
 
80
135
  <!-- mustflow-section: postconditions -->
81
136
  ## Postconditions
82
137
 
83
138
  - The migration surface, source state, target state, and compatibility boundary are named.
84
- - Idempotency, rollback, backup, dry-run, and verification status are either proven or explicitly left as remaining risk.
139
+ - Content identity, lifecycle, URL, slug, asset, metadata, taxonomy, relationship, claim, fact, search, cache, sitemap, export, and public API continuity are preserved or explicitly marked out of scope when relevant.
140
+ - Semantic export or import, provider id mappings, self-hosted or replacement restore shape, deployment-state reproduction, and observability identifier continuity are preserved or explicitly marked out of scope when relevant.
141
+ - Idempotency, rollback, backup, restore, dry-run, old/new compatibility, and verification status are either proven or explicitly left as remaining risk.
142
+ - Rollback claims distinguish schema, data, app, and operational recovery, and destructive changes are delayed or explicitly marked as requiring restore/manual recovery.
143
+ - API projections, public identifiers, analytics event versions, cache keys, read models, and generated indexes keep compatibility or carry an explicit migration risk.
144
+ - Database engine changes, local-disk to object-storage moves, tenant-boundary retrofits, and API response reshapes preserve compatibility or carry an explicit migration risk.
85
145
  - Final reports do not imply that a live or destructive migration ran unless configured evidence proves it.
86
146
 
87
147
  <!-- mustflow-section: verification -->
@@ -110,7 +170,11 @@ Use a narrower configured test, build, migration dry-run, or documentation inten
110
170
 
111
171
  - Migration surface reviewed
112
172
  - Source and target state
113
- - Idempotency and rollback status
173
+ - Identity, lifecycle, slug, URL, asset, metadata, taxonomy, relationship, claim, fact, index, cache, export, and redirect continuity where relevant
174
+ - API projection, public id, event schema, restore, and generated-state continuity where relevant
175
+ - Semantic export/import, provider-id mapping, deployment-state reproduction, observability identifier, and platform-exit continuity where relevant
176
+ - Search ranking, search quality set, queue message contract, dead-letter or replay procedure, log or analytics event ownership, and operator procedure continuity where relevant
177
+ - Idempotency, expand-migrate-contract compatibility, rollback type, backup, restore, rehearsal, timeout, backfill, and validation-query status
114
178
  - Compatibility or lock metadata updated
115
179
  - Command intents run
116
180
  - Skipped checks and reasons
@@ -2,11 +2,11 @@
2
2
  mustflow_doc: skill.performance-budget-check
3
3
  locale: en
4
4
  canonical: true
5
- revision: 1
5
+ revision: 12
6
6
  lifecycle: mustflow-owned
7
7
  authority: procedure
8
8
  name: performance-budget-check
9
- description: Apply this skill when performance budgets, bundle size, page weight, startup time, command duration, memory use, asset size, throughput, latency, benchmark output, or performance claims are planned, edited, reviewed, or reported.
9
+ description: Apply this skill when performance budgets, query-count budgets, N+1 risk, read/write workload shape, database concurrency pressure, app-server scaling, vertical versus horizontal scaling, process count, connection-pool pressure, read-model cost, operational database reporting load, analytics-query isolation, cache strategy, cache keys, cache invalidation, cache stampede, hot keys, stale fallback, ranking snapshots, search API cost, search index rebuild cost, search quality regression set, file upload bandwidth, external-dependency timeout cost, retry storms, worker queue starvation, provider rate limits, queue backlog or dead-letter growth, pricing-growth cost, vendor free-tier limits, value-pricing units, internal cost units, tenant usage limits, user-action fan-out, contribution margin, P50/P90/P99 heavy-user costs, AI usage cost budgets, AI gateway hard limits, provider budget guardrails, agent loop caps, model-call retries, token-cost tracking, bundle size, page weight, startup time, command duration, memory use, asset size, throughput, latency, benchmark output, or performance claims are planned, edited, reviewed, or reported.
10
10
  metadata:
11
11
  mustflow_schema: "1"
12
12
  mustflow_kind: procedure
@@ -34,6 +34,24 @@ Keep performance claims and budgets tied to declared thresholds, reproducible me
34
34
 
35
35
  - A task changes or reports performance budgets, bundle size, page weight, startup time, command duration, memory use, asset size, throughput, latency, search index size, build time, or benchmark output.
36
36
  - A change adds heavier dependencies, generated assets, static pages, search indexes, startup work, file scanning, command fan-out, or repeated process spawning.
37
+ - A change introduces or reports caching, cache-control headers, cache keys, cache tags, purge rules, stale fallback, precomputed ranking, search-result caching, faceted-filter caching, CDN caching, or private versus shared cache behavior.
38
+ - A list, feed, search, admin table, dashboard, or API response introduces relation loading, ORM includes, lazy loading, per-row counts, viewer-specific flags, aggregate counters, or read models that can hide N+1 queries or unbounded query cost.
39
+ - A behavior analytics, dashboard, reporting, search ranking, event log, or experiment analysis path may scan operational tables, consume the same connection pool as user requests, or run grouped aggregates on high-growth data.
40
+ - A database or storage choice is justified by "read-heavy", "write-heavy", "SQLite is enough", "PostgreSQL is safer", "cache it", "direct upload", or "local file upload" performance assumptions.
41
+ - A performance issue is framed as "scale up", "add servers", "move to serverless", "move to edge", "add workers", or "use a larger instance" before CPU, database, external dependency, regional latency, and process-state bottlenecks are separated.
42
+ - App servers may be multiplied and could increase database connections, queue load, retry volume, cron duplication, cache pressure, or external API calls instead of improving throughput.
43
+ - A file upload, download, resize, conversion, object-storage, CDN, or app-server streaming path could consume request time, memory, bandwidth, or worker capacity.
44
+ - A cache, queue, search service, analytics store, AI provider, email service, or other auxiliary dependency might cause core user requests to wait, retry, stampede, or fail.
45
+ - HTTP requests perform AI, email, embedding, statistics, webhook follow-up, import, export, file conversion, or other slow work inline instead of accepting work and handing it to a bounded worker path.
46
+ - A retry policy, worker pool, or provider integration can create retry storms, rate-limit feedback loops, dead-letter buildup, or queue starvation across unrelated work.
47
+ - Search ranking, query behavior, search index rebuild, queue partitioning, job retry policy, dead-letter retention, log volume, or analytics event volume may affect latency, worker capacity, provider cost, storage cost, or operational visibility.
48
+ - AI, embedding, reranking, image, audio, or tool-call features can create provider cost, token cost, retry cost, cache savings, rate-limit pressure, free-plan abuse, or worker starvation that needs a budget, usage ledger, or limit.
49
+ - AI requests need a gateway-level cost stop before provider calls, including estimated-cost checks, hard budget decisions, model downgrade rules, request-size caps, token caps, tool-call caps, agent-step caps, timeout caps, or an emergency disable switch.
50
+ - A third-party tool, hosted platform, analytics service, observability vendor, automation provider, database, file store, email provider, authentication provider, or AI provider has a free tier, seat price, API-call price, event price, storage price, bandwidth price, workspace price, audit-log price, export price, or usage limit that can become a product margin or growth bottleneck.
51
+ - A pricing or plan design must compare the value unit users understand with the cost units the system consumes, such as seats, workspaces, requests, storage, bandwidth, AI tokens, search queries, image conversions, automation runs, events, realtime connections, or support.
52
+ - A user action can fan out into several internal jobs such as thumbnail generation, OCR, AI summary, embeddings, search indexing, notifications, logs, analytics events, or webhook calls.
53
+ - Free, unlimited, or generous plan limits touch high-cost surfaces such as AI calls, media conversion, file storage, download traffic, search, automation, webhooks, realtime connections, or log retention.
54
+ - A margin claim depends on average customers but could be dominated by heavy users, high-volume tenants, or P90/P99 usage.
37
55
  - A report claims that a path is faster, slower, lightweight, optimized, cached, parallelized, cheap, expensive, within budget, or over budget.
38
56
  - A failure or slowdown suggests that measurement scope, command selection, concurrency, caching, or generated output size needs review.
39
57
 
@@ -50,6 +68,23 @@ Keep performance claims and budgets tied to declared thresholds, reproducible me
50
68
  - The performance surface, such as command, page, asset, bundle, startup path, query, build, or generated output.
51
69
  - The budget source, if one exists: repository config, documented threshold, user-provided limit, benchmark baseline, package metadata, or current command result.
52
70
  - Measurement method, environment boundary, warm or cold run expectation, and whether the result is deterministic, sampled, local-only, or approximate.
71
+ - Cache layer, cache key source, cache version, TTL or freshness rule, invalidation trigger, stale fallback, private or no-store boundary, and rebuild source when a cache or precomputed read model is involved.
72
+ - Cache failure behavior, hot-key risk, stampede risk, TTL jitter or lock strategy, cache flush tolerance, and whether the cache is disposable or runtime storage.
73
+ - Expected query count, row count, relation loading shape, aggregate strategy, read-model owner, and whether the measurement can detect query growth when a database-backed read path is involved.
74
+ - Read/write workload profile, including repeated reads, freshness requirement, write bursts, same-row contention, index maintenance cost, ledger or audit write amplification, and whether a read projection can replace per-request calculation.
75
+ - Operational database versus analytics or reporting boundary, including read replica, precomputed aggregate, queue, event store, separate connection pool, or external analytics system when available.
76
+ - Timeout, retry, circuit-breaker, stale-response, feature-flag, and degraded-mode policy when an auxiliary dependency can affect the critical path.
77
+ - Worker and provider capacity boundary, including queue separation, concurrency limits, retry delay, backoff with jitter, circuit-breaker threshold, dead-letter behavior, and whether one provider can consume shared worker or database resources.
78
+ - Scaling boundary, including current process count, CPU and memory pressure, connection-pool limits, database maximum connections, serverless or edge timeout limits, worker concurrency, cron ownership, and whether adding app servers would increase pressure on the real bottleneck.
79
+ - Search capacity and quality boundary, including index rebuild time, partial reindex trigger, query log volume, ranking snapshot cost, representative query set, and whether relevance changes are measured or only observed anecdotally.
80
+ - Log and analytics volume boundary, including which events must be retained internally, which can be sampled or dropped, retention window, storage cost, and whether analysis scans are isolated from core user requests.
81
+ - AI cost boundary, including feature key, account or workspace scope, request count, input and output token limits, cached-input treatment, provider price snapshot, retry grouping, cache-hit type, model tier, plan limit, and whether failed or cancelled provider calls can still cost money.
82
+ - AI gateway boundary, including preflight estimated cost, hard limit decision, remaining budget, model downgrade, feature policy, provider budget role, maximum tool calls, maximum agent steps, maximum total tokens, timeout, and emergency kill switch.
83
+ - Vendor cost boundary, including whether cost grows by users, seats, workspaces, API calls, events, storage, bandwidth, active users, projects, advanced permissions, audit logs, exports, AI tokens, or support tier, and whether that growth follows the product's revenue model.
84
+ - Pricing and margin boundary, including the user-facing value unit, internal cost unit, included quota or credit pool, overuse policy, tenant-level limit, free-plan maximum loss, and customer contribution margin formula.
85
+ - Usage metering boundary, including workspace or organization id, user id, feature key, request type, input size, output size, processing time, external API usage, retries, failures, plan, and whether one user action can create multiple billable or cost-bearing internal operations.
86
+ - Heavy-user boundary, including P50, P90, and P99 customer cost, whether a few users can dominate provider or infrastructure bills, and which high-cost actions require hard limits instead of only reporting.
87
+ - Free-to-paid transition boundary, including which operationally required features are outside the free tier, what usage cliffs exist, and whether growth creates a gradual cost curve or a sudden platform migration or plan upgrade.
53
88
  - Relevant command-intent contract entries for status, diff, build, tests, docs, release, or mustflow validation.
54
89
 
55
90
  <!-- mustflow-section: preconditions -->
@@ -75,14 +110,96 @@ Keep performance claims and budgets tied to declared thresholds, reproducible me
75
110
  3. Check nearby code, docs, templates, tests, and command metadata for duplicated performance statements or stale thresholds.
76
111
  4. Classify the measurement as deterministic, sampled, local-only, externally dependent, or unmeasured.
77
112
  5. If the change adds dependencies, generated output, or repeated work, identify the likely cost path and whether an existing alternative is available.
78
- 6. Keep claims conservative: state the command, input scope, and whether caching, warm runs, parallelism, or generated files influenced the result.
79
- 7. If a budget is exceeded, report the affected surface, budget source, measured value or unavailable measurement, likely cause, and smallest follow-up.
80
- 8. Run the narrowest configured verification that proves the changed performance, package, docs, or mustflow surface.
113
+ 6. For database-backed lists, feeds, search, dashboards, or admin tables, define the intended query shape before accepting a performance claim.
114
+ - Count queries separately from returned rows when the local tooling supports it.
115
+ - Watch for per-row author, tag, attachment, permission, count, reaction, bookmark, or viewer-state lookups.
116
+ - Prefer joins for small required one-to-one data, batch queries for one-to-many data, aggregate or cached counters for counts, and read models or projections for complex feeds.
117
+ - Treat ORM lazy loading as a performance risk until the query count is bounded or measured.
118
+ - Treat repeated `GROUP BY`, `COUNT`, `SUM`, large date windows, free-form filtering, and dashboard scans on high-growth tables as reporting load. Prefer precomputed aggregates, read replicas, analytics stores, or bounded query windows over user-request database resources.
119
+ - Protect core user requests from analytics or reporting load with separate connection pools, read-only replicas, queued jobs, cached summaries, or explicit rate limits when the architecture has those tools.
120
+ 7. For read-heavy and write-heavy workload claims, check the ordering of mitigations before accepting the design.
121
+ - For read-heavy paths, first stabilize query patterns, then indexes, then precomputed read tables or projections, then caches, then replicas or separate search engines. Do not add cache first when invalidation is unclear.
122
+ - For write-heavy paths, account for index write cost, audit-log amplification, ledger writes, lock contention, hot counters, same-row balance or inventory updates, and retry or idempotency overhead.
123
+ - Treat current-value fields such as balances, counts, or rankings as derived when a ledger, event, or snapshot is the real evidence source.
124
+ 8. For caching work, classify the cache layer: browser, CDN, server response, query-result cache, search index, precomputed ranking or statistics, generated page, or generated API projection.
125
+ 9. Check whether the cache key comes from normalized input rather than raw URL order, casing, default values, arbitrary range values, or temporary UI state. Include a cache version when the response shape, filter logic, ranking formula, or visibility rule can change.
126
+ 10. Check invalidation before accepting a cache: name the source data, affected cache tags or dependencies, purge trigger, rebuild source, stale-response behavior, and whether failures degrade safely.
127
+ - Ask whether the cache can be flushed. If flushing only increases latency, report it as cache; if it destroys sessions, queues, locks, rate-limit state, user state, or permissions, report it as runtime storage and require a different durability budget.
128
+ - Check hot keys such as global home feeds, popular lists, pricing data, and common search terms. Report sharding, replication, request coalescing, local memoization, or CDN strategy when one key can receive disproportionate traffic.
129
+ - Check stampede behavior. Prefer TTL jitter, single-flight refresh, stale-while-revalidate, background refresh, or prewarming over letting simultaneous misses hit the origin together.
130
+ 11. For ranking, trending, search, and faceted-list APIs, prefer precomputed snapshots, generated indexes, or bounded caches over per-request full aggregation when traffic can spike.
131
+ 12. For file upload and download paths, identify whether the app server handles raw bytes or only issues signed object-storage URLs.
132
+ - Large uploads, image processing, document conversion, video conversion, and archive extraction should not monopolize request memory or bandwidth when they can be direct-to-storage or worker-driven.
133
+ - Treat app-local file serving as a scalability and failure-isolation risk once user files are a product feature, especially with multiple servers, redeploys, or CDN needs.
134
+ 13. Ensure admin, private, authenticated, or personalized responses use no shared cache. Require `no-store` or private-cache behavior where leaking data would be worse than serving slower responses.
135
+ 14. For external or auxiliary dependencies on a critical path, check timeout, retry, backoff, circuit-breaker, fallback, and feature-flag behavior. A slow AI, search, analytics, email, or statistics dependency should not consume the whole request budget unless the user-visible operation truly depends on it.
136
+ 15. For scaling choices, locate the bottleneck before accepting the mitigation.
137
+ - If CPU is the bottleneck, consider a larger instance, more processes, worker processes, or worker threads for CPU-heavy work before distributing state across many app hosts.
138
+ - If the database is the bottleneck, check query shape, indexes, slow queries, transaction length, connection pooling, and N+1 behavior before adding app servers that may exhaust connections faster.
139
+ - If an external API is the bottleneck, use queueing, timeout budgets, limited retries, circuit breakers, degraded behavior, and rate limits rather than letting user requests wait indefinitely.
140
+ - If regional latency is the bottleneck, consider edge or regional routing only for short, independent paths. Do not move database-write-heavy or dependency-heavy business logic to edge runtime only because the edge is faster for simple responses.
141
+ - Treat serverless and edge scaling as capacity tools with their own limits: cold starts, timeouts, connection reuse, provider compatibility, bundle size, and cost cliffs still need budgets.
142
+ 16. For worker and retry paths, check whether retryable work is bounded.
143
+ - Prefer accepting work quickly, persisting a job or outbox record, and returning a queued or processing status over making HTTP wait for slow external completion.
144
+ - Use backoff with jitter so many failing jobs or clients do not retry at the same time.
145
+ - Separate queues, worker pools, rate limits, or concurrency budgets when AI, email, analytics, embeddings, webhooks, billing, and imports have different urgency or failure policies.
146
+ - Report dead-letter growth, retry exhaustion, provider rate limits, and unknown provider outcomes as capacity and reliability risks, not just error-handling details.
147
+ - Check that queues with different urgency do not share an unbounded worker pool when one backlog can delay payments, entitlement grants, password resets, webhook processing, or other critical work.
148
+ - Treat manual replay and dead-letter review as operational capacity. A dead-letter queue that no one watches is a delayed outage, not a solved failure.
149
+ 17. For search and analytics volume, check whether derived systems can be rebuilt and observed without overwhelming the core path.
150
+ - Search indexes should be rebuildable from source records, and full or partial reindex cost should be bounded before relying on provider search as the only serving path.
151
+ - Search relevance claims should cite a representative query set, expected top results, or explicit unmeasured status instead of relying on a dashboard impression.
152
+ - Logs and analytics events should not grow without retention, sampling, aggregation, export, or cold-storage policy when storage, query, or SaaS event pricing can become the bottleneck.
153
+ 18. For AI cost and provider-usage budgets, treat cost as a first-class performance and product limit.
154
+ - Do not rely on provider dashboards as the only source for user, workspace, feature, model, cache, retry, or plan-level cost decisions.
155
+ - Prefer a single AI call boundary that records request-level usage before cost is summarized. Scattered direct SDK calls hide feature economics and retry amplification.
156
+ - Track user request id separately from provider call id so one user action with retries, fallbacks, embeddings, tool calls, or evaluations can be costed without being counted as multiple user actions.
157
+ - Store usage in integer cost units plus a pricing snapshot or version reference. Do not recompute historical costs from the current provider price sheet.
158
+ - Distinguish app response cache, provider prompt cache, embedding cache, and search-result cache. A cache hit that avoids a provider call is not the same as a discounted provider input.
159
+ - Apply preflight limits for plan, account, request length, model tier, monthly cost, request count, input tokens, and output tokens; record actual usage afterward and update rollups or limits.
160
+ - Treat provider console budgets, account-level spend caps, and rate-limit headers as secondary guardrails unless they are proven hard stops. Product-owned limits should block, downgrade, queue, or reject high-cost work before the provider call.
161
+ - For agentic or multi-call AI work, cap steps, tool calls, total tokens, total estimated cost, and total time. One visible user request can create many provider calls, so request-count limits alone are not enough.
162
+ - Keep budget decisions inspectable. Record allow, block, downgrade, or emergency-disable decisions with safe identifiers, estimated cost, remaining budget, selected model, and blocked reason.
163
+ - Include failed, timed-out, cancelled, and retried calls in the budget review when they may consume provider quota or money.
164
+ 19. For vendor pricing and free-tier claims, compare the tool's pricing unit with the product's revenue unit.
165
+ - Check whether the product earns by customer, workspace, seat, transaction, storage, content item, automation run, active user, or AI usage, then compare that with how the vendor charges.
166
+ - Treat user-seat, monthly-active-user, API-call, event, storage, bandwidth, workspace, project, advanced-permission, audit-log, export, and overage pricing as structural risk when the product can grow in a different direction.
167
+ - Identify operationally required features that are plan-gated, such as backups, audit logs, SSO, role management, webhooks, API limits, data export, retention, monitoring, or support. A generous free tier can still be risky when the paid cliff lands on a feature that is hard to replace later.
168
+ - Report pricing cliffs and unverified provider terms as margin risk rather than performance risk alone. "Cheap now" is not evidence that the tool remains cheap at the product's next scale.
169
+ 20. For pricing and internal metering claims, separate user-perceived value from system cost.
170
+ - Identify the value unit: seat, workspace, project, document, transaction, plan, or another unit customers can understand.
171
+ - Identify the cost units: storage, transfer, database usage, search, AI or external API calls, log or analytics volume, email or notification sends, automation runs, file conversions, queue work, payment fees, and support load.
172
+ - Prefer simple external plans plus internal limits for cost-bearing resources. A seat or workspace plan can include storage, AI credits, search quotas, automation runs, and shared tenant pools without exposing every raw request count to the customer.
173
+ - Treat "unlimited" as a claim that must have a natural human limit, fair-use policy, rate limit, abuse detection, or hard internal cap. Do not let unlimited AI, media conversion, storage, traffic, search, automation, realtime, webhook, or log retention become an unbounded liability.
174
+ - Model contribution margin as customer revenue minus customer variable cost. Report which variable costs are included and which are unmeasured.
175
+ - Compare P50, P90, and P99 users or tenants when possible. Averages can hide a small number of heavy users who destroy margin.
176
+ - Meter by workspace or organization as well as user when team usage is pooled. Seat-level credits may be sold, but shared tenant pools often better match real usage.
177
+ 21. For user-action fan-out, count internal work rather than only the visible request.
178
+ - Name the jobs triggered by one action, such as uploads, transforms, OCR, AI calls, embeddings, search indexing, notification sends, event writes, log writes, analytics exports, and webhook deliveries.
179
+ - Identify which fan-out work is synchronous, queued, retryable, deduplicated, rate-limited, or skipped under load.
180
+ - Treat hidden retries, failed calls, and duplicate worker execution as cost multipliers when they consume provider quota or infrastructure.
181
+ 22. Keep claims conservative: state the command, input scope, query-count boundary, cache boundary, worker boundary, search rebuild or quality boundary, log and analytics volume boundary, AI cost boundary, vendor cost boundary, pricing value/cost boundary, critical-path dependency boundary, and whether caching, warm runs, parallelism, stale responses, precomputed snapshots, generated files, queues, provider limits, pricing cliffs, user-action fan-out, or external services influenced the result.
182
+ 23. If a budget is exceeded, report the affected surface, budget source, measured value or unavailable measurement, likely cause, and smallest follow-up.
183
+ 24. Run the narrowest configured verification that proves the changed performance, package, docs, or mustflow surface.
81
184
 
82
185
  <!-- mustflow-section: postconditions -->
83
186
  ## Postconditions
84
187
 
85
188
  - Performance claims have a budget source, measurement method, or explicit unverified status.
189
+ - Database-backed read paths have an explicit query-count, row-count, relation-loading, or unmeasured-risk note when N+1 or aggregate cost is plausible.
190
+ - Read-heavy and write-heavy claims identify query patterns, indexes, projections, cache invalidation, write contention, audit or ledger amplification, and retry overhead before claiming a store or cache is sufficient.
191
+ - File upload and download paths identify app-server bandwidth, memory, conversion, object-storage, CDN, and worker boundaries when those costs are plausible.
192
+ - Cache behavior has an owner, key source, freshness rule, invalidation path, private/shared boundary, and rebuild or fallback story when cache is part of the claim.
193
+ - Analytics, dashboard, and reporting paths do not silently share unbounded operational query cost with core user requests, or the remaining risk is reported.
194
+ - Critical-path external dependencies have timeout, retry, fallback, feature-flag, or degraded-mode boundaries when performance or availability can affect core use.
195
+ - Vertical scaling, horizontal scaling, serverless, edge, worker, and process-count claims identify the actual bottleneck and the state, connection, cron, queue, or provider limits that could make the chosen scaling path worse.
196
+ - Worker queues, retry policies, provider rate limits, and dead-letter paths have capacity boundaries when auxiliary work can starve core flows.
197
+ - Search index rebuilds, search quality checks, log volume, analytics event volume, and queue dead-letter review have explicit measured or unmeasured status when they affect latency, cost, or operational visibility.
198
+ - AI usage and cost claims have request, provider-call, feature, model, cache, retry, pricing-snapshot, and plan-limit boundaries when model calls can affect cost or quota.
199
+ - AI gateway claims have preflight hard-limit, provider-budget, downgrade, agent-step, tool-call, timeout, and emergency-disable boundaries when autonomous or high-cost model work can affect margin.
200
+ - Vendor pricing, free-tier, plan-gated feature, and usage-growth claims are tied to the product's revenue unit or reported as unverified margin risk.
201
+ - Pricing claims separate customer-visible value units from internal cost units, and identify included limits, credit pools, overuse behavior, tenant-level controls, free-plan loss budget, and unverified margin risk.
202
+ - Usage-cost claims account for user-action fan-out, hidden retries, P50/P90/P99 heavy-user shape, and contribution margin when high-cost actions can dominate customer economics.
86
203
  - Thresholds and benchmark-facing docs, tests, package metadata, generated output notes, and command contracts are synchronized where they overlap.
87
204
  - Final reports separate measured evidence from estimates, local observations, and suggested follow-up work.
88
205
 
@@ -115,6 +232,16 @@ Use a narrower configured benchmark, asset, build, docs, or test intent when it
115
232
  - Performance surface reviewed
116
233
  - Budget source or missing budget
117
234
  - Measurement method and boundary
235
+ - Query-count, N+1, read-model, and aggregate-cost boundary when relevant
236
+ - Operational versus analytics query boundary when relevant
237
+ - Cache layer, key, freshness, invalidation, hot-key, stampede, flush-tolerance, and private/shared boundary when relevant
238
+ - Critical-path external dependency timeout, retry, fallback, worker, queue, rate-limit, and dead-letter boundary when relevant
239
+ - Scaling bottleneck, process-count, database-connection, serverless, edge, worker, and cron-ownership boundary when relevant
240
+ - Search rebuild, search quality, log volume, analytics retention, queue backlog, and dead-letter review boundary when relevant
241
+ - AI usage, token, provider-call, model-tier, retry-cost, cache-hit, pricing-snapshot, and plan-limit boundary when relevant
242
+ - AI gateway hard limit, provider budget guardrail, model downgrade, agent loop, tool-call, timeout, and emergency kill-switch boundary when relevant
243
+ - Vendor pricing unit, customer value unit, internal cost unit, tenant limit, free-tier cliff, plan-gated operations feature, contribution-margin, P50/P90/P99 heavy-user, and revenue-alignment boundary when relevant
244
+ - User-action fan-out, hidden retry, and internal work amplification when relevant
118
245
  - Thresholds, claims, or metadata synchronized
119
246
  - Command intents run
120
247
  - Skipped measurements and reasons
@@ -2,11 +2,11 @@
2
2
  mustflow_doc: skill.pure-core-imperative-shell
3
3
  locale: en
4
4
  canonical: true
5
- revision: 6
5
+ revision: 7
6
6
  lifecycle: mustflow-owned
7
7
  authority: procedure
8
8
  name: pure-core-imperative-shell
9
- description: Apply this skill when business decisions, validation, authorization, pricing, eligibility, state transitions, domain events, effect descriptions, or calculations are mixed with I/O such as databases, HTTP handlers, repositories, SDK calls, files, queues, logs, metrics, clocks, randomness, environment reads, payments, emails, or framework request/response objects.
9
+ description: Apply this skill when business decisions, validation, authorization, pricing, discounts, credits, permissions, eligibility, state transitions, domain events, effect descriptions, or calculations are mixed with I/O such as databases, ORM entities, HTTP handlers, repositories, SDK calls, files, queues, logs, metrics, clocks, randomness, environment reads, payments, emails, or framework request/response objects.
10
10
  metadata:
11
11
  mustflow_schema: "1"
12
12
  mustflow_kind: procedure
@@ -41,6 +41,7 @@ Core decides. Shell does.
41
41
  - Business rules are mixed with database access, HTTP handlers, repositories, external SDK calls, framework objects, logs, metrics, clocks, randomness, generated identifiers, environment reads, payments, emails, files, queues, or caches.
42
42
  - Code contains meaningful `if`, `switch`, pricing, permission, eligibility, expiration, quota, scoring, matching, validation, or state-transition logic and also performs side effects.
43
43
  - Several pricing, discount, permission, scoring, matching, recommendation, or provider-choice policies need to remain pure while being selected at runtime.
44
+ - ORM models, entity hooks, lifecycle hooks, decorators, lazy-loaded relations, or active-record methods contain pricing, permissions, discounts, credits, entitlement, subscription, point, or state-transition decisions.
44
45
  - Core tests require database mocks, HTTP mocks, SDK mocks, clock mocks, logger mocks, or framework request objects.
45
46
  - A handler, repository, adapter, worker, or event consumer hides business policy.
46
47
  - A state change must produce domain events or effect descriptions without executing those effects immediately.
@@ -64,6 +65,7 @@ Core decides. Shell does.
64
65
  - The business action, command, workflow, or state change being implemented or refactored.
65
66
  - The decision the domain must make and the facts needed to make it.
66
67
  - The current side effects, including persistence, external calls, messages, logs, metrics, generated identifiers, time, randomness, and environment reads.
68
+ - ORM-specific behavior involved in the current decision, such as relation includes, lazy loading, model methods, hooks, transactions, repository calls, and generated database row types.
67
69
  - Local patterns for result types, domain errors, events, effects, outbox messages, repositories, adapters, mappers, and tests.
68
70
  - Existing behavior evidence when refactoring code that already runs.
69
71
  - Relevant command-intent contract entries for verification.
@@ -97,7 +99,7 @@ Core decides. Shell does.
97
99
 
98
100
  1. Locate the mixed responsibility.
99
101
  - Decision signals: `if`, `switch`, status checks, role checks, amount calculations, eligibility checks, validation rules, state transitions, deadline rules, quota rules, and domain error choices.
100
- - Execution signals: `await`, database access, external SDK calls, HTTP clients, file access, logging, metrics, email sending, message publishing, cache access, `new Date()`, `Date.now()`, generated identifiers, randomness, and environment reads.
102
+ - Execution signals: `await`, database access, ORM relation access, active-record model methods, ORM hooks, external SDK calls, HTTP clients, file access, logging, metrics, email sending, message publishing, cache access, `new Date()`, `Date.now()`, generated identifiers, randomness, and environment reads.
101
103
  2. Name the pure decision.
102
104
  - Prefer verbs such as `decide`, `calculate`, `derive`, `validate`, `transition`, `classify`, `price`, `score`, `select`, `can`, `is`, or `has`.
103
105
  - Avoid naming the core after a route, ORM model, SDK method, provider, or transport operation.
@@ -137,6 +139,9 @@ Core decides. Shell does.
137
139
  - Map decisions to persistence commands after core returns.
138
140
  - Database constraints can protect integrity, but they must not be the only place where business policy exists.
139
141
  - Use optimistic locking, version checks, unique constraints, and transactions in the shell when stale decisions or duplicates are possible.
142
+ - Keep ORM syntax, eager-loading choices, lazy-loading behavior, model hooks, decorators, and generated entity types out of business rules. Treat the ORM as a persistence tool, not the owner of domain policy.
143
+ - Do not hide notifications, payments, credit grants, permission changes, audit writes, or other business effects in ORM create, update, or delete hooks.
144
+ - For complex reads, allow a query service, projection, or explicit SQL-style read model instead of forcing all screens through the write-domain model.
140
145
  10. Keep external side effects outside local transactions.
141
146
  - Do not hold a database transaction open while calling slow network services.
142
147
  - When local state and external messages must both be reliable, save state and outbox messages in one transaction, then publish after commit.
@@ -145,8 +150,9 @@ Core decides. Shell does.
145
150
  - If status, state, phase, step, or stage controls allowed actions, use `state-machine-pattern` to define the transition table, event names, guards, terminal states, effect descriptions, invalid transitions, and tests.
146
151
  - Keep the transition function pure and let the shell persist state, transition history, idempotency records, and outbox rows.
147
152
  12. Use strategies for interchangeable pure policies when needed.
148
- - If pricing, discount, scoring, ranking, matching, permission, recommendation, or provider-choice logic has several methods with one shared purpose, use `strategy-pattern`.
149
- - Keep strategy selection in a selector, resolver, or shell boundary and keep strategy execution behind a shared pure contract when possible.
153
+ - If pricing, discount, scoring, ranking, matching, permission, recommendation, or provider-choice logic has several methods with one shared purpose, use `strategy-pattern`.
154
+ - Keep strategy selection in a selector, resolver, or shell boundary and keep strategy execution behind a shared pure contract when possible.
155
+ - Return explainable policy results for pricing, discounts, credits, entitlements, and permissions, such as original amount, applied rules, rejected rules, final amount, tax, rounding, and reason codes, so UI, receipts, refunds, support, and analytics do not recalculate the rule independently.
150
156
  13. Use command structure for state-changing shell units when needed.
151
157
  - If one user or system intent needs explicit payload, context, authorization, transaction, idempotency, outbox, audit, retry, concurrency, or queue and worker reuse, use `command-pattern` to shape the shell execution unit.
152
158
  - Keep the pure core as the decision maker and the command handler as the orchestrator.
@@ -167,6 +173,7 @@ Core decides. Shell does.
167
173
  - Given the same input, the core returns the same output.
168
174
  - The core can run without a database, network, file system, queue, cache, server, framework, logger, clock, environment variables, random generator, or generated identifier service.
169
175
  - Business rules are visible in core functions, not hidden inside handlers, repositories, adapters, or database queries.
176
+ - Business rules are not hidden inside ORM models, relation loading, lifecycle hooks, decorators, or generated entity methods.
170
177
  - The shell owns all I/O, boundary mapping, persistence, transactions, retries, idempotency, logs, metrics, and side-effect execution.
171
178
  - Business rule tests do not require mocks.
172
179
 
@@ -2,11 +2,11 @@
2
2
  mustflow_doc: skill.result-option
3
3
  locale: en
4
4
  canonical: true
5
- revision: 2
5
+ revision: 3
6
6
  lifecycle: mustflow-owned
7
7
  authority: procedure
8
8
  name: result-option
9
- description: Apply this skill when expected failures, meaningful absence, null or undefined returns, thrown business errors, boolean success flags, raw string errors, repository lookups, validation, parsing, external adapter errors, or boundary error mapping need explicit Result and Option handling.
9
+ description: Apply this skill when expected failures, meaningful absence, null or undefined returns, thrown business errors, boolean success flags, raw string errors, repository lookups, validation, parsing, external adapter errors, API error response contracts, or boundary error mapping need explicit Result and Option handling.
10
10
  metadata:
11
11
  mustflow_schema: "1"
12
12
  mustflow_kind: procedure
@@ -44,6 +44,7 @@ Expected failure must be data. Meaningful absence must be data. Exceptions are o
44
44
  - A repository lookup can fail due to persistence and can also legitimately find no record.
45
45
  - External SDK, database, HTTP, payment, email, filesystem, or framework exceptions leak into business logic.
46
46
  - A controller, adapter, or command handler must convert typed failures into HTTP, UI, CLI, or queue responses.
47
+ - API responses need stable machine-readable error codes, safe messages, request identifiers, and details that do not expose raw causes, provider payloads, or sensitive data.
47
48
  - Tests need stable success, failure, and absence cases without relying on thrown exceptions.
48
49
 
49
50
  <!-- mustflow-section: do-not-use-when -->
@@ -127,6 +128,7 @@ Expected failure must be data. Meaningful absence must be data. Exceptions are o
127
128
  - Repositories that can fail and may not find data should return `Result<Option<T>, E>`.
128
129
  - Services may convert an `Option` into a domain error when the value is required.
129
130
  - Controllers, CLI handlers, queue consumers, and UI boundary code should convert `Result` into protocol responses.
131
+ - Public and integration APIs should expose a consistent error envelope with stable code, safe message, optional safe details, and request id when available; they should not leak internal `Result` names, stack traces, storage keys, SQL, provider responses, or sensitive raw causes.
130
132
  - Do not serialize internal `Result` or `Option` shapes as public API responses unless that is the explicit public contract.
131
133
  9. Log once at the outer boundary.
132
134
  - Do not log the same error at every layer.