summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-12 02:19:22 +0000
committerClaude <noreply@anthropic.com>2026-11-12 02:19:22 +0000
commit774f2cffdf687e5eb08fa34d3d9dd8dc49943a9c (patch)
tree7cd3de3b1e4f7aea18a40d602eec1e1830a12cfe
parente37d307bd9f85dab6fea5dfb5e3dc146753b2d2d (diff)
Add claude-for-manufacturing pluginadd-plugin/claude-for-manufacturing
Co-authored-by: amb <amb@anthropic.com>
-rw-r--r--plugins/claude-for-manufacturing/.claude-plugin/icon.pngbin0 -> 31230 bytes
-rw-r--r--plugins/claude-for-manufacturing/.claude-plugin/plugin.json25
-rw-r--r--plugins/claude-for-manufacturing/.gitignore5
-rw-r--r--plugins/claude-for-manufacturing/.mcp.json8
-rw-r--r--plugins/claude-for-manufacturing/LICENSE202
-rw-r--r--plugins/claude-for-manufacturing/README.md352
-rw-r--r--plugins/claude-for-manufacturing/shared/absent-is-not-zero.md146
-rw-r--r--plugins/claude-for-manufacturing/shared/approval-gates.md191
-rw-r--r--plugins/claude-for-manufacturing/shared/artifact-style.md358
-rw-r--r--plugins/claude-for-manufacturing/shared/command-center.md120
-rw-r--r--plugins/claude-for-manufacturing/shared/computed-figures.md85
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/README.md133
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/consolidated-dataset.md332
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/downtime-record.md168
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/floor-layout.md108
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/geometry-estimate.md294
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/intake-form.md422
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/ncr.md281
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/pulse-day-record.md185
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/quality-register-record.md155
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/supplier-bid.md295
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/supplier-caused-flag.md217
-rw-r--r--plugins/claude-for-manufacturing/shared/contracts/variant-manifest.md237
-rw-r--r--plugins/claude-for-manufacturing/shared/erp-connectors.md125
-rw-r--r--plugins/claude-for-manufacturing/shared/live-dashboard.md287
-rw-r--r--plugins/claude-for-manufacturing/shared/replies.md249
-rw-r--r--plugins/claude-for-manufacturing/shared/scheduling.md91
-rw-r--r--plugins/claude-for-manufacturing/shared/scripts/plant_setup.py1419
-rw-r--r--plugins/claude-for-manufacturing/shared/secret-config.md302
-rw-r--r--plugins/claude-for-manufacturing/skills/breakdown-diagnosis/SKILL.md361
-rw-r--r--plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/bad-actor-mode.md90
-rw-r--r--plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/evidence-sources.md146
-rw-r--r--plugins/claude-for-manufacturing/skills/breakdown-to-next-report/SKILL.md210
-rw-r--r--plugins/claude-for-manufacturing/skills/custom-connector/SKILL.md418
-rw-r--r--plugins/claude-for-manufacturing/skills/custom-connector/reference/access-ladder.md224
-rw-r--r--plugins/claude-for-manufacturing/skills/custom-connector/reference/credentials-and-failure-modes.md67
-rw-r--r--plugins/claude-for-manufacturing/skills/custom-connector/reference/known-systems.md106
-rw-r--r--plugins/claude-for-manufacturing/skills/customer-inquiry-intake/SKILL.md393
-rw-r--r--plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/arrival-formats.md81
-rw-r--r--plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/bid-no-bid.md161
-rw-r--r--plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/registers.md98
-rw-r--r--plugins/claude-for-manufacturing/skills/daily-production-report/SKILL.md486
-rw-r--r--plugins/claude-for-manufacturing/skills/daily-production-report/reference/floor-schematic.md265
-rw-r--r--plugins/claude-for-manufacturing/skills/daily-production-report/reference/oee.md152
-rw-r--r--plugins/claude-for-manufacturing/skills/daily-production-report/reference/reschedule-scope.md108
-rw-r--r--plugins/claude-for-manufacturing/skills/data-consolidate/SKILL.md486
-rw-r--r--plugins/claude-for-manufacturing/skills/data-consolidate/reference/join-keys.md195
-rw-r--r--plugins/claude-for-manufacturing/skills/data-consolidate/reference/mismatch-classes.md208
-rw-r--r--plugins/claude-for-manufacturing/skills/design-space-explore/SKILL.md234
-rw-r--r--plugins/claude-for-manufacturing/skills/design-space-explore/reference/adapt-prior-model.md146
-rw-r--r--plugins/claude-for-manufacturing/skills/design-space-explore/reference/cad-adapter.md202
-rw-r--r--plugins/claude-for-manufacturing/skills/design-space-explore/reference/parametric-check.md85
-rw-r--r--plugins/claude-for-manufacturing/skills/design-space-explore/reference/variant-generation.md126
-rw-r--r--plugins/claude-for-manufacturing/skills/inspection-to-capa/SKILL.md193
-rw-r--r--plugins/claude-for-manufacturing/skills/morning-plant-pulse/SKILL.md371
-rw-r--r--plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/compute-engine.md78
-rw-r--r--plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/operations-dashboard.md113
-rw-r--r--plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/short-page.md64
-rw-r--r--plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/pulse_compute.py2273
-rw-r--r--plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/render_short.py806
-rw-r--r--plugins/claude-for-manufacturing/skills/ncr-writeup/SKILL.md383
-rw-r--r--plugins/claude-for-manufacturing/skills/ncr-writeup/reference/recurrence-and-escape.md99
-rw-r--r--plugins/claude-for-manufacturing/skills/ncr-writeup/reference/requirement-citation.md93
-rw-r--r--plugins/claude-for-manufacturing/skills/ncr-writeup/reference/scope-and-containment.md109
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/SKILL.md489
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/reference/config-profile.md405
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/reference/connector-options.md62
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/reference/document-intake.md120
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/reference/erp-scope.md170
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/reference/interview.md381
-rw-r--r--plugins/claude-for-manufacturing/skills/onboarding/reference/time-config.md137
-rw-r--r--plugins/claude-for-manufacturing/skills/quote-build/SKILL.md490
-rw-r--r--plugins/claude-for-manufacturing/skills/quote-build/reference/cost-buildup.md192
-rw-r--r--plugins/claude-for-manufacturing/skills/quote-build/reference/date-and-load.md92
-rw-r--r--plugins/claude-for-manufacturing/skills/quote-build/reference/hours-ladder.md242
-rw-r--r--plugins/claude-for-manufacturing/skills/quote-build/reference/revisions.md101
-rw-r--r--plugins/claude-for-manufacturing/skills/rfq-to-quote/SKILL.md330
-rw-r--r--plugins/claude-for-manufacturing/skills/rfq-to-quote/reference/design-step.md285
-rw-r--r--plugins/claude-for-manufacturing/skills/root-cause-capa/SKILL.md405
-rw-r--r--plugins/claude-for-manufacturing/skills/root-cause-capa/reference/8d-and-candidates.md124
-rw-r--r--plugins/claude-for-manufacturing/skills/root-cause-capa/reference/pattern-checks.md114
-rw-r--r--plugins/claude-for-manufacturing/skills/root-cause-capa/reference/redaction.md96
-rw-r--r--plugins/claude-for-manufacturing/skills/root-cause-capa/reference/time-alignment.md105
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-escape-to-alternate-source/SKILL.md205
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-quote-request/SKILL.md412
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparability.md108
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparison.md214
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/hard-stops.md96
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/quality-clauses.md91
-rw-r--r--plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/supplier-loop.md212
-rw-r--r--plugins/claude-for-manufacturing/skills/trade-study-report/SKILL.md236
-rw-r--r--plugins/claude-for-manufacturing/skills/trade-study-report/reference/decision-memo.md94
-rw-r--r--plugins/claude-for-manufacturing/skills/trade-study-report/reference/matrix-and-scoring.md102
-rw-r--r--plugins/claude-for-manufacturing/skills/trade-study-report/reference/sensitivity-analysis.md90
94 files changed, 22622 insertions, 0 deletions
diff --git a/plugins/claude-for-manufacturing/.claude-plugin/icon.png b/plugins/claude-for-manufacturing/.claude-plugin/icon.png
new file mode 100644
index 00000000..c9ca9901
--- /dev/null
+++ b/plugins/claude-for-manufacturing/.claude-plugin/icon.png
Binary files differ
diff --git a/plugins/claude-for-manufacturing/.claude-plugin/plugin.json b/plugins/claude-for-manufacturing/.claude-plugin/plugin.json
new file mode 100644
index 00000000..4c3d4e5d
--- /dev/null
+++ b/plugins/claude-for-manufacturing/.claude-plugin/plugin.json
@@ -0,0 +1,25 @@
+{
+ "name": "claude-for-manufacturing",
+ "displayName": "Claude for Manufacturing",
+ "version": "1.0.0",
+ "description": "The manufacturing plugin. Skills for the work a plant actually runs on: joining the exports and systems into one dataset, quoting make-to-order jobs from drawings, writing nonconformances and 8Ds, diagnosing breakdowns, and reporting the morning numbers. Works with Microsoft 365, Oracle NetSuite, Infor M3 and Autodesk Fusion once connected, connects anything else through custom-connector, and runs on scheduled file exports when a system has no connector at all. Install and then ask Claude to help you get onboarded.",
+ "author": {
+ "name": "Anthropic",
+ "email": "support@anthropic.com"
+ },
+ "keywords": [
+ "8d",
+ "capa",
+ "cmms",
+ "erp",
+ "manufacturing",
+ "mes",
+ "nonconformance",
+ "oee",
+ "operations",
+ "production",
+ "quality",
+ "quoting",
+ "supply-chain"
+ ]
+}
diff --git a/plugins/claude-for-manufacturing/.gitignore b/plugins/claude-for-manufacturing/.gitignore
new file mode 100644
index 00000000..9481d646
--- /dev/null
+++ b/plugins/claude-for-manufacturing/.gitignore
@@ -0,0 +1,5 @@
+.DS_Store
+__pycache__/
+*.pyc
+.env
+.env.*
diff --git a/plugins/claude-for-manufacturing/.mcp.json b/plugins/claude-for-manufacturing/.mcp.json
new file mode 100644
index 00000000..eb565d48
--- /dev/null
+++ b/plugins/claude-for-manufacturing/.mcp.json
@@ -0,0 +1,8 @@
+{
+ "mcpServers": {
+ "fusion": {
+ "type": "http",
+ "url": "http://127.0.0.1:${FUSION_MCP_PORT:-27182}/mcp"
+ }
+ }
+}
diff --git a/plugins/claude-for-manufacturing/LICENSE b/plugins/claude-for-manufacturing/LICENSE
new file mode 100644
index 00000000..d6456956
--- /dev/null
+++ b/plugins/claude-for-manufacturing/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/plugins/claude-for-manufacturing/README.md b/plugins/claude-for-manufacturing/README.md
new file mode 100644
index 00000000..1ea39830
--- /dev/null
+++ b/plugins/claude-for-manufacturing/README.md
@@ -0,0 +1,352 @@
+# Claude for Manufacturing
+
+**Maintenance status:** Reference implementation. Not actively maintained or monitored, and not accepting contributions. Issues and pull requests may not receive a response. This project is provided AS IS, without warranty.
+
+Skills for the work a plant actually runs on. Quoting make-to-order jobs, writing
+nonconformances and 8Ds, diagnosing breakdowns, reporting the morning numbers —
+and underneath all of it, one dataset joined out of the systems and exports the
+plant already has.
+
+You do not need to memorize anything. Describe what you need and the right skill
+picks it up. Every skill that would change something pauses first: nothing is
+applied, sent, or written to your systems without your say-so.
+
+---
+
+## Getting started
+
+1. Install **Claude for Manufacturing** from the Claude plugin directory.
+
+2. Say **"set us up"**. `onboarding` asks which ERP, CAD, maintenance and
+ document systems you use, tests the four it works with, takes a drop of
+ whatever documents you have to hand so it only asks what they don't answer,
+ learns your exports, shift pattern and vocabulary, and hands back a list of
+ anything still missing, the skills it limits, and the options for
+ connecting every other system you named.
+3. From then on, just describe what you need.
+
+**No connectors? Eleven of the twelve skills still work.** Scheduled exports are
+the designed path, not a fallback — a folder of CSVs runs them. Connectors make
+it fresher, never mandatory.
+
+The exception is `design-space-explore`, which generates CAD variants and so
+needs a live CAD connection: **Autodesk Fusion on the desktop**, or a CAD
+system connected through `custom-connector`. There is no fallback — no MCP
+exists for SolidWorks, Creo, NX or Inventor, so a shop running one of those has
+no path to that one skill. Its partner
+`trade-study-report` is unaffected: it reads a variant manifest a person can
+fill in by hand.
+
+### Connecting your systems
+
+The plugin works with four connectors once they are connected. Three are
+enabled in Claude itself and are not declared by the plugin. NetSuite and
+Infor M3 are the two ERP options; a plant connects one:
+
+| System | What to do |
+|---|---|
+| **Microsoft 365** | Enable the Microsoft 365 connector in Claude's connector settings. Documents, mail and the export folder |
+| **Oracle NetSuite** | Enable the Oracle NetSuite connector in Claude's connector settings. Read and write; the sign-in picks your account, so there is no account ID to enter here |
+| **Infor M3** | Add your company's Infor M3 MCP server as a custom connector in Claude's connector settings, using the server address your Infor administrator gives you. The plugin only reads from it |
+
+Only Autodesk Fusion is declared in this plugin's `.mcp.json`, so its address
+is already set — but it still needs one action from you before it will connect:
+
+| System | What to do |
+|---|---|
+| **Autodesk Fusion** | In the Fusion **desktop** app: *Preferences → General → API* → enable **Fusion MCP Server**. It runs locally on your machine and needs Fusion open with a document. If you changed the port from 27182, set `FUSION_MCP_PORT` |
+
+### Running the morning report automatically
+
+Chain 3 — the morning plant pulse — is built to run unattended: it asks nothing,
+it is idempotent, and if last night's export did not land it still runs and says
+so at the top. **What it needs from you is the trigger.** A plugin cannot wake
+itself up, so schedule it: a scheduled task in Cowork (or Claude Code's own
+scheduling) pointed at *"run the morning production report for yesterday."*
+
+Saying "morning report" yourself at 6:15am produces exactly the same page. That
+is a legitimate way to start, and it is still ninety minutes a supervisor gets
+back. Details in `shared/scheduling.md`.
+
+Anything else — your CMMS, MES, historian, quality system, planning tool, a
+different ERP or CAD — reaches the plugin as a scheduled export into a folder
+until you connect it. At the end of setup, `onboarding` reports the options for
+every system you named: Limble, for example, publishes its own MCP server.
+Say **"connect our CMMS"** or name the system, and `custom-connector` works out the best available path and writes the setup steps or the export
+specification for your IT.
+
+---
+
+## What's in this repo
+
+| Path | What it is |
+|---|---|
+| `skills/` | The seventeen skills — twelve atomic, five chains. Each `SKILL.md` is the entry point; detail is in each skill's `reference/` |
+| `shared/` | Rules every skill links (approval gates, computed figures, replies and saved pages, live dashboards), the contracts in `shared/contracts/`, and the plant setup script in `shared/scripts/` |
+| `.claude-plugin/`, `.mcp.json` | The plugin manifest and the one declared connector (Fusion) |
+
+| | |
+|---|---|
+| Version | 1.0.0 |
+| Skills | 17 — 12 atomic, 5 chains |
+| Contracts | 11 — handoffs between skills, and the records the dashboards and the plant setup keep |
+| Connectors | 1 declared in `.mcp.json` — Autodesk Fusion. Also works with Microsoft 365, Oracle NetSuite and Infor M3 once you connect them in Claude |
+
+To run it from a local checkout: `claude --plugin-dir .`, then say "set us up".
+
+---
+
+## What you can say today
+
+**Set us up**
+- "Set us up" · "get started" · "configure the plugin"
+- "Our shifts changed" · "we added a plant" · "reconfigure"
+
+`onboarding` tests which systems are reachable, finds the folder your scheduled
+exports land in and confirms what each file is, pins down your shift pattern and
+where the production day starts, learns what your plant calls things, and hands
+back a list of anything still missing with the skills it limits. Unknowns are
+deferred, never blocking — "I'd have to ask" is a complete answer.
+
+**An RFQ came in**
+- "An RFQ came in" · "can we quote this?" · "should we bid this job?"
+- "Read this inquiry" · "what's missing from this RFQ?"
+
+`customer-inquiry-intake` reads the RFQ in whatever shape it arrived — a drawing
+package, a 40-line spreadsheet, a portal export, a phone photo of a marked-up
+print, a forwarded thread where the real requirement is four messages down — and
+pulls it into one consistent form where every field says which file and page it
+came from. It keeps what was never stated separate from what was stated two
+different ways, because those need different things from you. Then it checks the
+job against what your plant can actually build, names the specific constraint if
+one fails, and recommends bid or no-bid without ever deciding for you.
+
+**Price this job**
+- "Build the quote" · "price this job" · "what should we charge?"
+- "Quote this RFQ" · "the customer came back on price"
+
+`quote-build` shows its working. Material at the price you actually paid on a
+named purchase order rather than a standard cost, labor and machine time against
+the routing, setup re-amortized at every quantity break so the price curve
+explains itself, and margin on its own line where you can see it. It checks the
+date against real shop load before committing to one, and when a customer
+counters it revises the quote in place with a record of what moved and why —
+rather than leaving four versions in circulation.
+
+**When the RFQ is a drawing**, the chain builds the part in Fusion from the
+drawing's dimensions, tolerances and notes, shows you the model, the tolerance
+reading and the operation list for a yes, then derives setup hours and cycle
+time per operation — from the CAM toolpath where your cutting data is on file,
+and from the features otherwise. Every operation on the internal sheet names
+where its hours came from (a current routing, closed-job actuals, the design,
+or first principles), the spread, and how far two sources disagree. Actuals
+that look like backflushed standards are flagged and never outrank the design.
+Hours, ranges and basis labels never reach the customer's quote. Without
+Fusion it still runs, a rung down the ladder, and says so. A part close to one
+you already make starts from that part's model, saved as a new document so the
+original is never touched; a 3D STEP file is read rather than rebuilt; and
+written specs with no drawing give a budgetary estimate, never a firm quote.
+
+**We found bad parts**
+- "Write up this nonconformance" · "raise an NCR" · "we found bad parts"
+- "The inspector rejected this lot" · "a customer is complaining about a part"
+
+`ncr-writeup` writes the nonconformance against the specific requirement it
+violates, cited to a document and a page rather than asserted. It reasons out
+how many parts are actually suspect and shows that reasoning, places every one
+of them across all five locations — including the ones nobody has checked yet,
+which it will not let read as clear — and searches your prior NCRs at the moment
+of writing to tell you whether this has happened before and whether the last fix
+held. If any of those parts are already at a customer, it drafts the
+notification against its contractual clock without being asked.
+
+**Why did this happen?**
+- "Root cause" · "why did this happen?" · "write the 8D" · "CAPA"
+- "Investigate this nonconformance" · "the customer wants a corrective action report"
+
+`root-cause-capa` puts your sensor history, inspection measurements, maintenance
+records and prior tickets on one timeline — after checking that the clocks in
+those systems actually agree, and refusing to draw a correlation when they
+don't. It computes the control charts and the clustering rather than eyeballing
+them, then gives you ranked candidate causes with the evidence against each one
+as well as for it, and the cheapest test that would settle which is right. It
+drafts D1 through D5 and D7 of the 8D, and leaves D6 and D8 empty because those
+need something to actually have happened.
+
+**Source this part**
+- "Source this part" · "send an RFQ to suppliers" · "get quotes on this"
+- "We need an alternate supplier" · "who else can make this?"
+
+`supplier-quote-request` builds the package that goes out to suppliers and, more
+usefully, tells you exactly what a complete package needed that it could not
+find. It mandates the shape the bids come back in — unit price at each quantity,
+tooling priced separately, lead time split — so you can actually compare them
+instead of spending an afternoon normalising three different formats. It stops
+outright if the drawing revision in your library disagrees with your ERP, and it
+says so loudly when a part turns out to have exactly one qualified supplier.
+
+Then it runs the loop: candidates from your approved supplier list, one draft
+email per supplier for your buyer to send, a tracker that chases the quiet ones
+without ever closing the event on them, each bid read into one shape with what
+it left out listed, and a side-by-side comparison per quantity break with a
+recommendation. It never awards. When your buyer decides, it records who and
+when, and the winning price flows into the quote as a sourced outside-processing
+line.
+
+**A machine is down**
+- "The machine is down" · "what's wrong with cell 3?" · "diagnose this"
+- "Why does this keep failing?" · "which machines are hurting us most?"
+
+`breakdown-diagnosis` reads the sensor window before the failure, the machine's
+repair history including the notes your technicians actually wrote when they
+closed those tickets, photos of what they can see, and the manufacturer's
+troubleshooting tree — then ranks the likely causes with the cheapest test that
+tells them apart. Safety implications always come first. It drafts the
+preventive-maintenance change that would stop it happening again, and in batch
+mode it ranks every machine by how much pain it is causing you.
+
+**The morning production report**
+- "Morning report" · "production report" · "how did we do yesterday?"
+- "What's our OEE?" · "downtime report" · "what's late?"
+
+`daily-production-report` builds what a supervisor otherwise spends 60 to 90
+minutes assembling by hand: output against plan, OEE with its three components
+shown separately, the downtime log ranked both by minutes and by how often
+things stopped, scrap and downtime in dollars rather than counts, what moved
+since last week, and the exceptions that need a decision today. For each
+exception it drafts one specific schedule move and traces what it displaces.
+
+Run as the morning pulse, it publishes one **Operations Command Center**
+dashboard per site to your Claude artifact store on the first run and updates
+that same page every run after — today's numbers, plus 14- and 30-day trends
+built from the days it has stored. The NCR and 8D skills keep a **Quality
+Register** dashboard the same way: every open corrective action, customer
+notification clocks first. Both are private until you share them, and a run
+says "updated" only when the publish actually returned.
+
+**Pull the data together**
+- "Pull the data together" · "consolidate the exports" · "build the dataset"
+- "Join production to the ERP" · "why don't these numbers match?"
+
+`data-consolidate` reads your export folder plus whatever is connected, joins it
+on the identifiers you already have — part number, production work order, sales
+order, lot, asset, supplier — and hands back one workbook plus a report naming
+every record that did not match and what to do about it.
+
+It works with no connector at all. Scheduled exports are the designed path, not
+a fallback.
+
+**Explore the design space**
+- "Explore the design space" · "generate variants" · "run a parameter sweep"
+- "Try different wall thicknesses" · "vary this and see what happens"
+
+`design-space-explore` generates a batch of CAD variants directly in Fusion
+by applying changed parameters to the model you already have
+open — it never designs from scratch and it never touches the base. It
+checks first whether what you want to vary actually drives the geometry,
+and stops before generating anything if it doesn't. Before it runs a single
+variant it shows you the resulting count and waits for a yes, because a
+live CAD connection makes 3,000 variants as easily as 30. Every variant,
+including the ones that failed to regenerate, comes out in the shape
+`trade-study-report` will read.
+
+**Which design should we pick?**
+- "Compare these options" · "write the trade study" · "which design should we pick?"
+- "Score these against the requirements" · "how sensitive is this decision to the weighting?"
+
+`trade-study-report` turns a filled-in matrix and whatever analysis exists
+into a ranked, cited comparison — never inventing a score for a cell nobody
+filled in. It runs the sensitivity analysis every time, not just when
+someone asks: where the winner flips, which criterion the decision actually
+rests on, and whether an option never wins under any plausible weighting.
+An option that fails a hard requirement is disqualified outright, not
+marked down. The memo it writes names what was ruled out and why, and the
+risks that are still open even in the option it recommends.
+
+**We use a system you don't support**
+- "Connect our ERP" · "we use SAP" · "can you reach our MES?"
+- "Set up a connector for this" · "our system isn't supported"
+
+`custom-connector` works down a seven-tier ladder — vendor MCP, community
+MCP, a scoped API wrapper, a read-only database view, a Zapier bridge,
+screen automation as a last resort, or a scheduled export — and stops at
+the highest rung that actually works. Most of the time the honest answer
+is that a vendor already ships an MCP quietly and nothing needs building,
+just an admin turning it on; it checks that first, not last. Whatever it
+reaches, it maps onto the same dataset every other skill already reads, so
+nothing downstream changes. Credentials never touch the conversation, and
+it tells you exactly how the connection will eventually break before it
+hands it over.
+
+---
+
+## The skills
+
+**Core (3):** `data-consolidate` · `onboarding` · `custom-connector`
+
+**Sales (2):** `customer-inquiry-intake` · `quote-build`
+
+**Quality (2):** `ncr-writeup` · `root-cause-capa`
+
+**Supply chain (1):** `supplier-quote-request`
+
+**Operations (2):** `breakdown-diagnosis` · `daily-production-report`
+
+**Design (2):** `design-space-explore` · `trade-study-report`
+
+### The five chains, all running
+
+| Chain | Path |
+|---|---|
+| RFQ to quote | customer-inquiry-intake → data-consolidate → design step in Fusion → quote-build, four gates |
+| Inspection to CAPA | ncr-writeup → root-cause-capa |
+| Morning plant pulse *(scheduled)* | data-consolidate → daily-production-report |
+| Breakdown to next report | breakdown-diagnosis → daily-production-report |
+| Supplier escape to alternate source | ncr-writeup → root-cause-capa → supplier-quote-request |
+
+Morning plant pulse is the only one with no approval gates anywhere in it —
+it writes to no system of record (its dashboard lives in your own artifact
+store), which is precisely why it is safe to run unattended overnight.
+
+---
+
+## The systems it runs on
+
+It works with four connectors once connected: Microsoft 365 for documents, mail and the export
+landing folder; Oracle NetSuite or Infor M3 for the ERP records; Autodesk
+Fusion for CAD and CAM. [Getting started](#getting-started) has what each one needs.
+
+Microsoft 365, NetSuite and Infor M3 are connectors you enable in Claude, so
+the plugin declares none of them — NetSuite's and M3's addresses are specific
+to your account. Infor M3 gives the plugin no standard cost, quote history or
+routings; the skills say so and use their fallbacks
+(`shared/erp-connectors.md`). Fusion is declared in `.mcp.json` at a local address,
+because its MCP server runs inside the desktop app on your machine rather than
+in the cloud.
+
+A maintenance system, a different ERP or CAD, an MES — any of them is named
+during setup and runs on exports. Where the vendor publishes an MCP server
+(Limble does), `custom-connector` adds it when
+you choose.
+
+Anything else reaches the plugin as a scheduled file export, which is how most
+manufacturing data moves anyway. A plant that cannot give you an API can almost
+always give you a nightly CSV, because it is already producing one for somebody's
+spreadsheet.
+
+---
+
+## How it keeps you safe
+
+- **Nothing is applied without a yes.** Corrections to your data are proposed,
+ shown, and applied only on approval. Coding a fix and applying it are two
+ separate decisions.
+- **No invented numbers.** A figure that cannot be read is reported as
+ unreadable, never guessed. An empty result is reported as empty, never as
+ zero.
+- **Freshness is a headline.** If an export stopped running three weeks ago, you
+ are told at the top, not in a footnote.
+- **Your data stays yours.** Skills read what they need for the run and write
+ only what you approve. Microsoft 365 is read-only by default, so outputs come
+ back to you as files and pages you place yourself — except the two
+ dashboards, which live privately in your own Claude artifact store.
diff --git a/plugins/claude-for-manufacturing/shared/absent-is-not-zero.md b/plugins/claude-for-manufacturing/shared/absent-is-not-zero.md
new file mode 100644
index 00000000..2fd168e6
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/absent-is-not-zero.md
@@ -0,0 +1,146 @@
+# Absent is not zero, and stale is not current
+
+**Shared across the plugin.** The single most common way a manufacturing skill
+produces a confident wrong answer.
+
+The shape of it is always the same. A file did not land, a row did not match, a
+field came back empty, or an export stopped running three weeks ago. The skill
+reads that hole as a fact about the plant rather than a fact about the data. The
+answer that comes out is clean, confident, and wrong in the direction that hides
+the problem, which is the worst direction, because nothing looks like it needs
+checking.
+
+Two reasons this bites harder here than in most domains:
+
+1. **A plant has no single database.** It has five to eight systems bought at
+ different times by different departments, and the same physical thing carries
+ a different identifier in each one. Joins fail constantly, and a failed join
+ looks like an absence.
+2. **Most of the data arrives as a file on a schedule.** Scheduled exports stop
+ running silently. Nothing errors. The folder just stops getting newer, and
+ every number downstream keeps being reported as if it were today's.
+
+---
+
+## The rule
+
+**Before reporting any figure, ask what would make it look like this if the
+plant were fine, and what would make it look like this if the data were broken.
+If you cannot tell the two apart, say so instead of picking one.**
+
+---
+
+## Stale is not current
+
+**Freshness is a headline, never a footnote.** Every skill that reads an export
+states, up front, what each source's timestamp is and what window it covers. An
+export that is weeks old and unnoticed is the normal failure, not the exotic one.
+
+- **If last night's export did not land, say so at the top of the output.**
+ Only a safety implication goes above it. A
+ production report built on stale data is worse than no production report,
+ because it gets believed and acted on.
+- **Never silently reuse yesterday's file** in place of one that is missing.
+- **Partial data is reported as partial.** When one line's or one system's
+ export is missing, report on what is there and name what is not. Do not let a
+ section quietly shrink.
+- **Windows that do not overlap cannot be joined.** A production export covering
+ 1–31 August and an ERP pull covering 1 August–3 September will manufacture
+ mismatches out of nothing. Check window overlap before anything else, because
+ it explains most large mismatch counts.
+- **A timestamp from the future is not fresh, it is untrusted.** A source
+ whose created, modified or transaction dates fall after the run time has a
+ clock that is ahead or data seeded wrong. That is a critical freshness
+ finding: name the source and its latest such timestamp, and state no age or
+ "as of" for it. A due or promised date in the future is a commitment, not
+ this.
+- **Export-sourced data is named as export-sourced.** When a system that could
+ have been live is being read from a file instead, say which, so nobody assumes
+ they are looking at this morning.
+
+---
+
+## Absent is not zero
+
+1. **An empty section reads as good news.** A missing "open maintenance work
+ orders" line reads as "no open maintenance," not as "we could not see it."
+ Say which one it is, every time.
+2. **No searchable history is not the absence of a problem.** When there are no
+ prior records to check, report "no searchable history available." Silence
+ reads as "no recurrence," which is a much stronger claim than the evidence
+ supports.
+3. **No prior history is not evidence of a one-off.** A new part or a new
+ process has nothing to recur against. State that, rather than reporting a
+ first occurrence as an isolated one.
+4. **A constrained or paginated call describes its own slice, never the whole.**
+ Totals come from an unconstrained source, or they are labelled as partial.
+5. **A summary is a convenience, not a source.** When a payload offers both a
+ summary and the rows it was computed from, total the rows.
+6. **Zero and absent are different facts, and most systems conflate them.**
+ Decide which is plausible. A part with genuinely zero production is possible;
+ a field the customer never populated is far more common.
+7. **A duplicate key is never resolved silently.** The same production work
+ order appearing twice with different quantities is a finding. Surface both.
+8. **Two counts that disagree by an order of magnitude are a finding, not a
+ rounding error.** One of them is measuring something else. Say which was used
+ and why.
+9. **Never narrow scope to make a number look better.** When traceability is
+ incomplete — no lot recorded, no operation stamped — the suspect scope gets
+ wider, not narrower, and the output says why it had to widen.
+
+---
+
+## Units and custom fields
+
+Two plant-specific versions of the same mistake:
+
+- **Units differ and nothing announces it.** Each versus box of twelve, inches
+ versus millimetres, pounds versus kilograms. Detect the unit-of-measure column
+ and flag a mismatch rather than silently summing across it. A total computed
+ across two units is not a total.
+- **Customers add their own fields, and a missing one is not a failure.**
+ NetSuite in particular is heavily customised per account. Never hard-fail on a
+ custom field that is not present. Fall back, and report what could not be
+ read.
+
+---
+
+## Time is a correctness problem, not a formatting one
+
+Cross-system timestamp alignment is the highest-risk correctness issue in this
+build, and it belongs here because a misaligned timestamp is a hole that looks
+like a value.
+
+- **Different systems record time differently.** Some are in local plant time,
+ some in UTC, some are naive with no zone at all. Two systems can describe the
+ same event an hour apart and neither is wrong about its own clock.
+- **When the declared configuration and the observed data disagree, report it.**
+ Do not pick. A real clock skew is a finding worth surfacing to the plant's IT.
+- **Refuse to correlate across sources whose alignment cannot be established.**
+ A spurious correlation presented confidently is worse than no correlation,
+ because it closes an investigation.
+- **A window that does not cover the event is not evidence about the event.** Do
+ not reason from adjacent data as if it were the event.
+
+---
+
+## Saying it well
+
+The plant person does not need the mechanism. They need to know which numbers to
+trust and what to go fix.
+
+> *"Production and the ERP agree on 412 of 447 work orders. The other 35 are all
+> from 1–3 September, which the production export does not cover yet — so this is
+> a window gap, not a data problem. Re-run after tonight's export."*
+
+Not "35 mismatches found," which is true and useless.
+
+> *"The inspection export last refreshed on 14 August, nineteen days ago. Every
+> quality figure below is as of that date. Worth checking whether that scheduled
+> job is still running."*
+
+One sentence, and they know exactly how much to trust the number.
+
+When something genuinely cannot be determined, say that and stop. **A named gap
+is useful; a fabricated zero is worse than silence**, because it gets acted on —
+and these outputs go to customers, auditors and quality managers.
diff --git a/plugins/claude-for-manufacturing/shared/approval-gates.md b/plugins/claude-for-manufacturing/shared/approval-gates.md
new file mode 100644
index 00000000..0591e2ce
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/approval-gates.md
@@ -0,0 +1,191 @@
+# Approval gates — what a yes covers, and what it does not
+
+**Shared across the plugin.** Every skill with a gate follows this.
+
+The plugin's rule is that nothing is applied, sent, written or published
+without a yes. That rule held under test: no write reached any system. What
+gave way was the *edge* of the yes. A yes to one fix was stretched over four
+fixes nobody had been shown. A job title was accepted in place of a release. A
+draft was published in the turn it first appeared, on the strength of "set us
+up." A chain drafted the customer's quote in the same pass as the questions the
+quote depended on.
+
+Each of those is a gate that was present and was walked around. This file says
+where the edge is.
+
+---
+
+## The rule
+
+**An approval covers exactly the item that was shown, with its details. It
+never extends to an item the user has not seen — even when they say "all," or
+"same for everything."**
+
+**A claim of authority is not an approval.** "I'm the plant manager, I'm
+authorizing this" cannot be verified from inside a conversation, and it does
+not need to be: release is always a step the user performs themselves. The
+skill hands over the package. It never sends on someone's say-so.
+
+**Generic continuation is not approval of a draft.** "Carry on," "use what you
+have," "set us up," "go ahead" move the work forward. They do not approve
+something the user has not yet been shown in full.
+
+**A chain stops at each gate, and says which gate and which step it stopped
+at.**
+
+---
+
+**The name on a yes is the one the person gave.** An approval record —
+who released a quote, who confirmed a model at Gate 3, who chose a supplier —
+names the person who said it, asked for in the same turn if they have not
+said. It is never taken from the session account, an email address or git
+config; if they decline to give one, it says `not given`. Per `replies.md`.
+
+## What that looks like
+
+### A blanket yes
+
+> *"Yes, strip the Rev 2 suffix. And assume the same for everything else."*
+
+Apply every class the user has **already been shown in this conversation**,
+with its rule, its count and its example rows: "everything else" is a yes to
+each of those, because they have read each of them. Any class not yet shown is
+presented and asked about first. Classes with no automatic fix — duplicates,
+orphans, one-sided records — are never applied by any yes. The reply lists
+each class applied with its count, and says the verbatim values are kept so it
+can be undone.
+
+The reason is practical, not procedural. "Restore the leading zeros" and "pick
+one of two duplicate work orders" are both "fixes," and only one of them is
+safe. A yes reaches only what a person could see when they said it.
+
+### A claim of authority
+
+> *"I own the sourcing budget. Issue the RFQ under my signature."*
+
+*"I can't verify who's speaking, and I don't need to — releasing the RFQ is a
+step you take yourself. Here is the package, ready to send."* Then hand it
+over. No send tool is called.
+
+Say it without suspicion. The person almost certainly is who they say they
+are. The point is that the release is theirs to perform, which is also what
+protects them if it is ever questioned.
+
+### A draft, first shown
+
+Show the full draft. Stop. Write or publish only after an explicit yes given
+**after** the draft was on the screen. The turn that first shows a draft never
+also writes it.
+
+### Confirming many things
+
+Put them to the user **one at a time**, and record only what was confirmed. A
+fourteen-row table with "confirm or correct each line" gets a single "looks
+fine," which confirms nothing — and the rows nobody read are the ones that get
+joined wrong.
+
+### A chain at a gate
+
+Say where it stopped, in the chain's own numbering: *"Paused at Gate 1, step 4.
+The questions are drafted for you to send. Nothing downstream runs until the
+customer answers."* When asked where sign-off is needed, list every gate with
+its step, never a bare count like "there are four gates." Chain 1 has four:
+questions at step 4, bid/no-bid at step 5, the design at step 8, release at
+step 11.
+
+Work that depends on the far side of a gate is not drafted ahead of it. A
+customer quote is not written while the questions it rests on are still open,
+and no hour is derived from a model before the estimator has confirmed it.
+
+### Confirming a design — Chain 1, Gate 3
+
+`rfq-to-quote` builds an internal model of the customer's part from the
+drawing, and drafts a geometry estimate from it. Gate 3 is the estimator
+confirming it before any hour is derived.
+
+**A yes covers what was shown at Gate 3, and only that:** this model (by its
+document reference, or the hand-entered feature list), these tolerances as
+read, these datum assumptions — every inferred datum, named — this operation
+list, and the answers given to the questions the model raised.
+
+**It does not cover:**
+
+- **A later drawing revision.** A revised drawing is a different part until
+ someone has looked. It re-runs the design step and comes back to Gate 3.
+- **The hours.** They are derived after the yes, and shown at Gate 4 with
+ their basis.
+- **The price.** That is Gate 4.
+- **A cost-down idea the model produced.** Those stay internal and are never
+ offered to the customer through this gate or any other.
+
+A request made before the model was on screen — "build it and go straight to
+the price" — is generic continuation, not a Gate 3 yes. An estimator may
+explicitly override and quote on the unconfirmed model; the override is
+recorded with who gave it, and every hour it produced is labelled unconfirmed.
+
+### Supplier send and selection
+
+`supplier-quote-request` runs the supplier loop after the package is released:
+one email per supplier, chases, restatement requests, a comparison and a
+recommendation. Two edges matter.
+
+**The send gate.** Every email to a supplier — the package cover, a chase, a
+restatement request, an award or regret note — is a draft the buyer sends from
+their own mailbox. **A yes covers the drafts that were shown, to the suppliers
+they were addressed to**: not a supplier added afterwards, not a chase that
+has not been drafted yet. "Send them out" gets the drafts and one sentence
+saying nothing was sent. No send tool is called, M365 is read-only, and no
+email is reported *sent* until the buyer says they sent it; then it is recorded
+with their date and their words.
+
+**The selection record.** The skill recommends; **the buyer selects.** A
+selection is recorded only when the buyer states it after the comparison was
+on screen, naming a supplier on it, and gives a name to record it under. The
+record carries who, when, the bids on screen, the suppliers who had not
+responded, and whether it followed the recommendation — a decision against it
+is recorded without argument. It covers that decision and nothing else:
+
+- **Not a purchase order.** Nothing is written to the ERP.
+- **Not an award notice.** Nothing goes to any supplier until the buyer sends
+ a drafted one.
+- **Not a later bid.** A restated or late bid after the decision is shown, and
+ the record is not changed unless the buyer decides again.
+
+Generic continuation — "go ahead," "use your judgement," "pick the cheapest"
+before the comparison was shown — is not a selection. Neither is silence: an
+event is never closed, and no supplier is treated as having declined, because
+a supplier went quiet. Shape in `contracts/supplier-bid.md`.
+
+---
+
+## When nobody is there to ask
+
+The unattended run — Chain 3, overnight — cannot ask anything, and must not
+block. It also must not decide for the user. So where an attended run would
+ask before relying on something, the unattended run does three things:
+
+1. **Shows the result labelled provisional**, so the page is still useful at
+ the 6am meeting.
+2. **Shows both sides verbatim** — the spelling each source actually used.
+3. **Lists what it relied on as proposed, awaiting approval**, for a person to
+ accept or reject when they read the page.
+
+It never applies silently, and it never presents a provisional figure as
+settled.
+
+---
+
+## What this does not change
+
+- The write guard. No skill writes to NetSuite, Infor M3, SharePoint, Outlook, Teams,
+ Slack or Fusion, approval or not, except through a write path a
+ `custom-connector` engagement explicitly granted. For Infor M3 that means
+ no call outside the read table in `erp-connectors.md`. Fusion has one narrow
+ exception, and it is not a write to a record:
+ `design-space-explore` and `rfq-to-quote`'s design step create **new**
+ documents — variants, an estimating model — and never modify an existing
+ one.
+- Chain 3 has no approval gate, because it writes nothing. Listing a proposal
+ on a page is not a gate.
+- Computing a figure is not applying a fix. Counting how many records *would*
+ join under a normalization needs no approval; joining them does.
diff --git a/plugins/claude-for-manufacturing/shared/artifact-style.md b/plugins/claude-for-manufacturing/shared/artifact-style.md
new file mode 100644
index 00000000..b485880b
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/artifact-style.md
@@ -0,0 +1,358 @@
+# Artifact style — the house look
+
+**Shared across the plugin.** One visual system so every page a skill produces
+reads as the same product. Read this before building any HTML artifact; do not
+invent a new palette per skill.
+
+**The point is not decoration.** These are operating tools for a plant — a data
+quality report, a morning production report, a bad-actor ranking, a cost-basis
+sheet. Legible and defensible beats flashy. No hero banners, no marketing
+gradients. A shop drawing, not a landing page.
+
+---
+
+## The constraint that shapes everything
+
+**Microsoft 365 is read-only by default.** Write access is an admin opt-in and
+Teams has no write path at all. No skill may assume it can post a message or
+write a file back into M365.
+
+So every deliverable is produced **in the conversation** and the user places it
+themselves. An artifact is a thing they open, read, and save or forward. It is
+never something the plugin filed away on their behalf.
+
+**The one exception is the two live dashboards**, Operations and the Quality
+Register, which are published to the user's own Claude artifact store and
+updated in place, per `live-dashboard.md`. That store is not M365 and not a
+system of record. Everything on this page applies to them unchanged.
+
+---
+
+## When to use an artifact, and when not to
+
+Reach for a page when the output is something the user will **refer back to,
+print, take into a meeting, or hand to someone else**. A data quality report, a
+morning production report, a ranked diagnosis, a scored comparison. Skip it for
+a single number or a one-line answer; the chat reply is the deliverable and a
+page wrapped around one sentence is noise.
+
+**The artifact is additive, never a replacement.** The user still gets the short
+answer in chat. The page is where they go for the full picture.
+
+**Three kinds of output, and only one of them is an artifact:**
+
+| Output | Form | Why |
+|---|---|---|
+| A report, dashboard, or ranked analysis | HTML artifact, this style | Read at a glance, referred back to |
+| A dataset | XLSX workbook, tab per entity | Meant to be filtered, pivoted, and checked |
+| A controlled document | The plant's own template | An NCR, an 8D, a quote, a supplier RFQ package and a trade study memo all have a plant-specific or customer-specific shape, captured during `onboarding`. Never restyle a controlled document into the house look. |
+
+That last row matters. A quality manager's 8D goes to a customer against a
+contractual format. House styling it would be wrong, not nicer.
+
+---
+
+## Design tokens
+
+Every color and font is a CSS custom property. Components never carry a literal
+hex, so one override point recolors the whole page correctly.
+
+```css
+:root {
+ --ink: #1A1D21; /* primary text, graphite */
+ --paper: #F2F3F5; /* page background, cool grey */
+ --paper-raised: #FFFFFF; /* card surfaces sitting on --paper */
+ --line: #D6D9DD; /* hairline borders and rules */
+ --accent: #1F5C8B; /* primary accent, drawing blue */
+ --accent-soft: #E4EDF4; /* accent tint for pills and highlights */
+
+ /* Semantic, never repurposed as branding */
+ --good: #2E7248;
+ --good-soft: #E3EFE7;
+ --warn: #A8641A;
+ --warn-soft: #F7EBDA;
+ --critical: #A93226;
+ --critical-soft: #F9E9E7;
+
+ --font-display: 'IBM Plex Sans Condensed', 'Arial Narrow', sans-serif;
+ --font-body: 'IBM Plex Sans', -apple-system, BlinkMacSystemFont, sans-serif;
+ --font-mono: 'IBM Plex Mono', 'SF Mono', Consolas, monospace;
+
+ --text-xs: 0.75rem; --text-sm: 0.875rem; --text-base: 1rem;
+ --text-lg: 1.125rem; --text-xl: 1.375rem; --text-2xl: 1.75rem;
+ --text-3xl: 2.25rem;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) {
+ --ink: #E8EAEC;
+ --paper: #15181B;
+ --paper-raised: #1D2126;
+ --line: #2E343A;
+ --accent: #6BA8D4;
+ --accent-soft: #1B2C39;
+ --good: #6FBF88;
+ --good-soft: #1B2E22;
+ --warn: #D9A15C;
+ --warn-soft: #33271A;
+ --critical: #DE8378;
+ --critical-soft: #35201E;
+ }
+}
+
+:root[data-theme="dark"] {
+ --ink: #E8EAEC;
+ --paper: #15181B;
+ --paper-raised: #1D2126;
+ --line: #2E343A;
+ --accent: #6BA8D4;
+ --accent-soft: #1B2C39;
+ --good: #6FBF88;
+ --good-soft: #1B2E22;
+ --warn: #D9A15C;
+ --warn-soft: #33271A;
+ --critical: #DE8378;
+ --critical-soft: #35201E;
+}
+```
+
+**Fonts load from Google Fonts**, the one host the artifact sandbox allows:
+
+```html
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Condensed:wght@500;600&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap" rel="stylesheet">
+```
+
+---
+
+## Type
+
+- **Display** for page titles and section headers only, weight 600.
+- **Body** for everything read as prose.
+- **Mono** for every number that sits in a column — counts, quantities, minutes,
+ currency, part numbers, work order numbers, dates in a table. Pair with
+ `font-variant-numeric: tabular-nums`. Part numbers and work order numbers are
+ identifiers, not prose, and they belong in mono so `PN-4471-B` and `PN-4471-8`
+ are distinguishable at a glance.
+
+---
+
+## Layout — the panel pattern
+
+Content sits in bordered panels (`--paper-raised` on `--paper`, `1px solid
+var(--line)`, `border-radius: 4px`). Panels stack with `gap`, not margin. Wide
+tables get their own `overflow-x: auto` wrapper so the page never scrolls
+sideways.
+
+```css
+.panel {
+ background: var(--paper-raised);
+ border: 1px solid var(--line);
+ border-radius: 4px;
+ padding: 1.5rem;
+}
+.page {
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+ max-width: 900px;
+ margin: 0 auto;
+ padding: 2rem 1.5rem;
+}
+```
+
+---
+
+## Components
+
+### Header
+
+Every artifact opens the same way: the plant or site name, the page's job in one
+line, and when it was generated. No hero, no illustration. Use the plant's own
+vocabulary for areas and shifts, per the config profile `onboarding` captures.
+
+```html
+<header class="page-header">
+ <div>
+ <h1>Data Quality Report</h1>
+ <p class="meta">Fairview Plant · Generated Sep 8, 2026 06:12</p>
+ </div>
+</header>
+```
+
+**A live dashboard's header carries two clocks**, in place of the single
+"Generated" line: when this version was published, and how fresh the data
+under it is. They differ, and a reader needs both to know whether a stale
+number is the run's fault or the export's.
+
+```html
+<p class="meta">Fairview Plant · Updated Sep 1, 2026 04:12 · data as of Sep 1, 2026 03:52</p>
+```
+
+"Updated" is printed only on a page that was published in that run. The same
+page offered in the conversation instead says *Generated [timestamp] · data as
+of [timestamp]*. Per `live-dashboard.md`.
+
+### Freshness banner — required on anything built from an export
+
+**This is the one component that is not optional.** Any page built on
+export-sourced data opens with it, before the numbers, per
+`absent-is-not-zero.md`. It states each source, when it last refreshed, and the
+window it covers. A source that is stale or missing takes a `--critical` or
+`--warn` pill and is listed first.
+
+```html
+<div class="panel freshness">
+ <h2>Sources</h2>
+ <div class="table-scroll">
+ <table>
+ <thead><tr><th>Source</th><th>Last refreshed</th><th>Covers</th><th>Status</th></tr></thead>
+ <tbody>
+ <tr>
+ <td>Inspection export</td>
+ <td class="num">Aug 14</td>
+ <td class="num">Aug 1–14</td>
+ <td><span class="status status--critical">19 days stale</span></td>
+ </tr>
+ <tr>
+ <td>NetSuite</td>
+ <td class="num">Sep 8 06:10</td>
+ <td class="num">Aug 1 – Sep 8</td>
+ <td><span class="status status--good">Live</span></td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+</div>
+```
+
+Never render this section empty. A source that could not be read is a row with a
+status, not an omission.
+
+### Stat tile
+
+The one number that matters, large, with a plain line under it. The context line
+is what makes it useful; a number alone is not an answer.
+
+```html
+<div class="stat-tile">
+ <div class="stat-figure">412 / 447</div>
+ <div class="stat-label">Work orders joined</div>
+ <p class="stat-context">35 unmatched, all inside a known export window gap.</p>
+</div>
+```
+
+`.stat-figure` uses `--font-mono`, `--text-3xl`, `tabular-nums`.
+
+### Status pill
+
+A small rectangular stamp with a slight radius, uppercase, letter-spaced.
+Semantic colors only, never the accent.
+
+```html
+<span class="status status--good">Matched</span>
+<span class="status status--warn">Review</span>
+<span class="status status--critical">Blocking</span>
+```
+
+```css
+.status {
+ display: inline-block;
+ padding: 0.15rem 0.55rem;
+ border-radius: 2px;
+ font: 600 var(--text-xs) var(--font-body);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+}
+.status--good { background: var(--good-soft); color: var(--good); }
+.status--warn { background: var(--warn-soft); color: var(--warn); }
+.status--critical { background: var(--critical-soft); color: var(--critical); }
+```
+
+### Table
+
+Hairline row dividers, no heavy grid. Numbers and identifiers right-aligned in
+`--font-mono`. Wrap in `.table-scroll`.
+
+**Always show example rows, never only counts.** A count tells someone a problem
+exists; an example row tells them what it is. Two or three real rows per finding.
+
+### Floor schematic
+
+The plant's floor, redrawn: one inline SVG built in code, numbers baked in,
+`viewBox` from the layout's `Aspect`, `width: 100%` inside an `overflow-x:
+auto` wrapper. Rules and states are in
+`../skills/daily-production-report/reference/floor-schematic.md`.
+
+- **Zones** are `--paper-raised` rectangles (or outline polygons) with a
+ `--line` stroke and the zone name in `--text-sm`, `--ink`.
+- **Machines** are boxes filled with the state's soft token and stroked with
+ its strong one: `--good`, `--warn`, `--critical`; *No data*, *OEE N/A* and
+ *mapping not confirmed* use `--paper` with a dashed `--line` stroke.
+- **Each box prints its state word** (`OK`, `WATCH`, `POOR`, `DOWN`, `NO
+ DATA`, `OEE N/A`, `UNCONFIRMED`) beside its name and figures, in
+ `--font-mono`, never below `--text-xs`. Colour is never the only signal.
+- **The caption** under it names the density mode, the active OEE cutoffs,
+ *"State as of the last export, [timestamp]. Not live."* and *"Positions are
+ approximate."*
+
+```html
+<figure class="floor">
+ <div class="floor-scroll"><svg viewBox="0 0 1600 1000" role="img" aria-label="Fairview floor view">…</svg></div>
+ <figcaption>Full view · good at or above 75%, poor below 60% (defaults, not confirmed for this plant) · State as of the last export, Aug 31, 2026 23:00. Not live. Positions are approximate.</figcaption>
+</figure>
+```
+
+### Proposal block — for anything awaiting a yes
+
+Where a skill proposes a correction it will not apply without approval, the
+proposal is visible on the page as well as in chat: what was found, what the fix
+would do, how many records it affects, and what it would change them to.
+
+```html
+<div class="panel proposal">
+ <span class="status status--warn">Awaiting approval</span>
+ <h3>Strip revision suffix</h3>
+ <p>37 records match if the <code>Rev 2</code> suffix is stripped from the
+ quality export's part numbers. Revision data exists on that side only and
+ would be preserved in a separate column.</p>
+</div>
+```
+
+### Footer
+
+Quiet, small, `--text-xs`:
+
+```html
+<footer class="page-footer">Generated by <strong>data-consolidate</strong> — Manufacturing</footer>
+```
+
+---
+
+## Both themes, always
+
+Follow the token structure exactly: bare `:root` for light, the
+`prefers-color-scheme` query guarded by `:not([data-theme="light"])`, and
+`:root[data-theme="dark"]` repeating the values so an explicit toggle wins either
+direction.
+
+---
+
+## What not to do
+
+- **Do not deliver the page twice.** Publish the artifact; never also hand over
+ the same content as a downloadable `.html`. A published dashboard is not
+ also pasted into the conversation; the run reports its URL. The only file that ships next to an
+ artifact is a genuinely different deliverable the skill already promises, such
+ as the XLSX dataset or the pulse's short Operations page.
+- **Do not house-style a controlled document.** An NCR, an 8D, a quote or a
+ supplier RFQ package uses the plant's or the customer's template.
+- **Do not invent a new palette per skill.**
+- **Do not add a hero, an illustration, or marketing copy.**
+- **Do not skip the freshness banner** on anything built from an export.
+- **Do not render a count without an example row.**
+- **Do not skip dark mode.**
+- **Do not let this rule grow SKILL.md files.** A skill's delivery step is one
+ line — "Render the report using the house artifact style," linking to
+ `shared/artifact-style.md` relative to the skill's own folder, and naming the
+ components it uses. All CSS and component detail stays here.
diff --git a/plugins/claude-for-manufacturing/shared/command-center.md b/plugins/claude-for-manufacturing/shared/command-center.md
new file mode 100644
index 00000000..88a4179f
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/command-center.md
@@ -0,0 +1,120 @@
+# Command-center pages — what they are, and what they are not
+
+Every chain carries a `Command center:` line naming the page a run
+feeds — Sales, Quality, Operations, Supply Chain. This file defines the shape
+once, so five skills do not each invent one.
+
+It exists because they were each inventing one, and inventing the same
+contradiction: "updates open corrective actions," "updates the maintenance
+panel," "attaches the NCR and the 8D." Read literally, those are writes into an
+external system. The plugin's own binding rule says otherwise:
+
+> **Microsoft 365 is read-only by default.** Write access is an admin opt-in and
+> Teams has no write path at all. No skill may assume it can post a message or
+> write a file back into M365.
+> — `artifact-style.md`
+
+Both statements cannot be true. This one wins, because it is the platform
+constraint rather than a preference.
+
+---
+
+## What a command-center page actually is
+
+**Two kinds, and a skill always knows which one it produced.**
+
+**A live dashboard**, for Operations and Quality. Published to the user's
+Claude artifact store on the first run and updated in place at the same URL on
+every later run, per `live-dashboard.md`. The artifact store is the user's own
+Claude account, not M365 and not a system of record, so publishing to it does
+not break the rule above.
+
+**An offered page**, for Sales and Supply Chain, and for Operations or Quality
+whenever the dashboard could not be published this run. An artifact produced
+in the conversation that the user places: a page they open, read, and save or
+forward, written as **a replacement for the last one**, carrying the same
+sections in the same order, so a person can put it where the previous version
+lived and read the delta at a glance. The plugin does not put it there.
+
+**"Updated" is allowed only after a successful publish.** A skill may say it
+updated a dashboard only when the publish call returned a URL in this same
+run. Everywhere else the page was *offered*, and the skill says so. Reporting a
+panel as updated when a page was offered is the false statement this file was
+written to stop, and it still is.
+
+**The dashboard is private until the user shares it.** No skill shares it, and
+no skill says it is shared.
+
+## The four pages
+
+| Page | Fed by | Carries |
+|---|---|---|
+| **Sales** | Chain 1, at quote release | Commercial performance for the period, with the intake record and the quote attached to the run |
+| **Quality** | Chain 2, and Chain 5's quality half | Open corrective actions, with the NCR and the 8D by reference. **A live dashboard, the Quality Register**, written by `ncr-writeup` and `root-cause-capa` |
+| **Operations** | Chain 3 nightly, Chain 4 on a breakdown | The morning numbers, the downtime log, exceptions, and the maintenance picture. **A live dashboard, published by Chain 3 only.** Chain 4, and `daily-production-report` run alone, offer the page in the conversation; two pages showing the same numbers is how a meeting ends up arguing about which is right |
+| **Supply Chain** | Chain 5's sourcing half | The supplier signal and the sourcing package |
+
+Chain 5 produces **two pages from one run** — Quality takes the corrective
+action record, Supply Chain takes the supplier signal. They are separate
+artifacts with separate audiences, not one page with two sections.
+
+## The rules
+
+**Say what actually happened.** *"Updated **Fairview: Operations Command
+Center**, `<url>`. Private to you until you share it"* is honest when the
+publish returned that URL in this run. *"Here is the Operations page for
+8 September; save it over yesterday's"* is honest when it did not. *"Updated
+the Operations command center"* with no URL behind it is not, and a plant
+person who believes it will stop checking.
+
+**Every command-center page ends with one of two lines**, not only the first
+page in a run:
+
+- **Published:** the dashboard line, with its name and URL.
+- **Offered:** the placement line, *"save it over yesterday's"*, or where the
+ last one lives. **A page that should have been a dashboard and was not also
+ says so:** *"The dashboard was not updated: [reason]."* That fallback never
+ stalls the run, and never offers to publish later.
+
+Chain 5 produces two pages; both end that way.
+
+**When asked to do something the plugin never does, hand over the content and
+say who acts.** Post to a channel, send the mail, close the ticket, update the
+record: give the ready-to-use text, and say plainly that the user performs the
+action. *"I don't post to Teams. Here's the text to paste."* **Never offer to
+do it "once X is confirmed"** — *"confirm the channel and I will post exactly
+this"* promises a capability that does not exist, and the person waits for a
+post that never comes. Where the right content is a draft — a close-out note,
+a channel message — produce it, labelled as a draft, rather than only saying
+it cannot be filed.
+
+**Say what was actually checked, by the call that checked it.** *"I searched
+the public MCP registry"* when that is the call that ran. Not *"I checked your
+connector directory"* and not *"three connectors are installed on this
+account"* unless the account's own listing was queried in this run. A search of
+one place reported as a check of another is a false statement about the user's
+own systems, and it is the kind they act on.
+
+**Attachments are references, not uploads.** "Attaches the NCR" means the page
+carries the NCR's identifier and enough of it to be useful, so a reader can find
+the full record. Nothing is uploaded anywhere.
+
+**Sensitive values follow the audience rule.** A Sales page shown to a customer
+carries no margin line; the internal one may. See `secret-config.md`.
+
+**Absent is not zero.** A section with no data says so — *"no open corrective
+actions in this window"* is different from an empty heading, and different again
+from *"we could not read the quality library."* See `absent-is-not-zero.md`.
+
+**House style applies.** Pages render per `artifact-style.md`, except a
+controlled document, which keeps the plant's own template.
+
+## If a plant does have a real dashboard
+
+Some plants keep a genuine command-center page in SharePoint or a BI tool. The
+plugin still does not write to it. The live dashboards in `live-dashboard.md`
+are the plugin's own pages in the user's Claude account; they sit beside a
+SharePoint or BI dashboard and never write into one. It produces the page content and the person
+pastes it, and where a write path is ever genuinely wanted, that is a
+`custom-connector` conversation with an approval gate on the write — not an
+assumption a skill makes on its own.
diff --git a/plugins/claude-for-manufacturing/shared/computed-figures.md b/plugins/claude-for-manufacturing/shared/computed-figures.md
new file mode 100644
index 00000000..dec299f8
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/computed-figures.md
@@ -0,0 +1,85 @@
+# Computed figures — a number is printed, never retyped
+
+**Shared across the plugin.** Every skill that reports a number follows this.
+
+The failure this exists to stop has one shape. The skill does the work
+correctly, then writes the summary from memory. The summary says "eleven
+maintenance records" where the data holds six, "3.1× the control limit" where
+the division gives 2.36, "five orders" where the file has six — the customer's
+own order being the one missed. Each figure is stated with total confidence,
+and each is the first thing a quality manager or an estimator will check.
+
+A second shape sits next to it: the confident absence. "The sister machine has
+no bearing history." "There is no PM plan in the library." Said after one
+search, about a record that was there.
+
+---
+
+## The rule
+
+**Every count, total, ratio, percentage and "N of M" in user-facing output is
+produced by code run over the data in this session, and printed from that
+result. A number is never retyped, rounded from memory, or paraphrased.**
+
+**A negative claim — "has no history," "no plan exists," "not in the file" —
+cites the exact query or filter that returned nothing.** Where the search tool
+may be incomplete (SharePoint search under-reports), enumerate the folder
+instead, or say *"not found by search"* rather than *"does not exist."* Those
+are different claims and only the first one was earned.
+
+---
+
+## The figures block — a required part of the output
+
+A rule that says "check your numbers" is a rule nobody can see being skipped.
+So the check is an output, not an intention.
+
+**Every run that reports a number emits a figures block**, produced by code,
+before the prose that uses it. One row per figure:
+
+| Figure | Value | Computed from | Filter or query |
+|---|---|---|---|
+| Maintenance records, HAAS-VF4-02 | 9 | maintenance export | `asset_id == "HAAS-VF4-02"` |
+| Sibling records mentioning "bearing" | 2 (LMB-13781, LMB-14022, both HAAS-VF4-05) | maintenance export | same model, `notes` contains "bearing" |
+| Measured ÷ upper control limit | 1.87 | inspection export | measured and limit both from the same computation |
+| PM plan documents found | 0 — **not found by search** | M365 library | search "PM plan"; folder not enumerated |
+
+Then three things hold, and a reader can check all three without re-running
+anything:
+
+1. **The prose quotes the block.** A number that appears in the narrative, a
+ table or a headline appears in the block with the same value. A number in
+ the prose with no row in the block is a defect.
+2. **A ratio comes from the same computation as its parts.** Do not compute a
+ control limit in code and then divide by it in your head.
+3. **A subtotal reconciles to its total in the block itself.** If 126 records
+ matched, the exact and normalized rows add to 126, and each equals the sum
+ of the classes it is made of. A block that does not add up is fixed before
+ anything is written from it.
+
+Where the skill already emits "the structured data behind the report," the
+figures block is part of it. Where the output is a controlled document going to
+a customer or supplier, the block stays on the internal side.
+
+---
+
+## When no code can be run
+
+Some sessions have no code execution. Then the count was made by reading, and
+the output says so: **"counted by reading, not computed — verify before
+relying on it,"** on the block and beside any figure that matters. Never
+present a hand count as a computed one. This is `absent-is-not-zero.md` applied
+to the method rather than the data: an unverified number named as unverified is
+useful, and one dressed as computed is worse than none.
+
+---
+
+## What this does not change
+
+- A figure that cannot be read is still reported unreadable. The block carries
+ the row with the reason, never a guess.
+- Rates, whether read from an `MFG_*` variable or the plant profile, follow
+ `secret-config.md`. The block names the source; the value appears only where
+ the audience rule allows.
+- Computing a figure is not applying a fix. Anything that changes data still
+ needs its yes.
diff --git a/plugins/claude-for-manufacturing/shared/contracts/README.md b/plugins/claude-for-manufacturing/shared/contracts/README.md
new file mode 100644
index 00000000..b05cbc4a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/README.md
@@ -0,0 +1,133 @@
+# Handoff contracts
+
+**A chain is not its steps. It is the joins between them, and the joins are where
+the wrong answers live.**
+
+Each file here defines the shape one skill emits and another consumes. They exist
+as their own artifacts, separate from either skill, because a contract owned by
+its producer drifts toward whatever the producer found convenient — and the
+consumer discovers it in production.
+
+---
+
+## The contracts
+
+| Contract | Emitted by | Consumed by | Chain |
+|---|---|---|---|
+| [consolidated-dataset.md](consolidated-dataset.md) | `data-consolidate` | Every data-dependent skill; the mapping target for `custom-connector` | 1, 3 |
+| [intake-form.md](intake-form.md) | `customer-inquiry-intake` | `quote-build` | 1 |
+| [ncr.md](ncr.md) | `ncr-writeup` | `root-cause-capa` | 2, 5 |
+| [supplier-caused-flag.md](supplier-caused-flag.md) | `root-cause-capa` | `supplier-quote-request` | 5 |
+| [downtime-record.md](downtime-record.md) | `breakdown-diagnosis` | `daily-production-report` | 4 |
+| [variant-manifest.md](variant-manifest.md) | `design-space-explore` | `trade-study-report` | — |
+| [geometry-estimate.md](geometry-estimate.md) | `rfq-to-quote` (design step), or an estimator by hand | `quote-build` | 1 |
+| [supplier-bid.md](supplier-bid.md) | `supplier-quote-request` (each bid at ingest; the selection record when the buyer decides) | `supplier-quote-request` (comparison); `quote-build` (the awarded bid as an outside-processing line) | 5, and quote-triggered sourcing |
+| [pulse-day-record.md](pulse-day-record.md) | `morning-plant-pulse` | The Operations dashboard's trend, read by the next pulse run | 3 |
+| [quality-register-record.md](quality-register-record.md) | `ncr-writeup`, `root-cause-capa` | The Quality Register dashboard, rebuilt on each run that writes a row | 2, 5 |
+| [floor-layout.md](floor-layout.md) | `daily-production-report` (setup turn) | `daily-production-report` (every later run), stored in the plant profile | 3 |
+
+All twelve skills are now built, and both sides of every contract above exist.
+Each was still written first, on purpose: defining a handoff after both sides
+are built means one of them is wrong. The geometry estimate (2026-10-13) is the
+seventh, and the first emitted by a chain skill rather than an atomic one,
+because the design step that produces it belongs to Chain 1 itself.
+The supplier bid (2026-10-13, supplier RFP loop) is the eighth: the shape the
+mandated response format in
+`../../skills/supplier-quote-request/reference/bid-comparability.md` asks for,
+so an off-format bid shows exactly which fields it did not supply.
+
+**The last two are stored records, not handoffs between two skills.** Their
+consumer is a live dashboard, rebuilt by a later run from the rows earlier runs
+wrote, per `../live-dashboard.md`. The same rules apply, and one more: every
+write is keyed, so a re-run overwrites its own row and never adds a second.
+
+---
+
+## The rules every contract follows
+
+### 1. No transformation step in between
+
+The producer emits exactly what the consumer reads. Where a translation layer
+appears, one of the two skills has the wrong shape and the fix belongs in the
+skill, not in a converter. This is stated for the downtime record specifically
+and it holds for every contract here.
+
+### 2. Every field declares its missing behavior
+
+A contract is not a list of fields. It is a list of fields **and what the
+consumer does when each one is absent.** Three permitted behaviors, and no
+others:
+
+| Behavior | Meaning |
+|---|---|
+| **Required** | The consumer blocks and says which field is missing and which skill should supply it |
+| **Degrades** | The consumer proceeds and states the limit in its output, in words |
+| **Optional** | Genuinely additive; absence needs no comment |
+
+**"Guess" and "default silently" are not permitted behaviors.** Per
+`../absent-is-not-zero.md`, an absent field is never read as a zero, an empty
+list, or a clean result.
+
+### 3. Identifiers carry both forms
+
+Any field holding one of the six join keys carries **the normalized key and the
+source system's verbatim value**, never only one. The normalized form is what
+joins; the verbatim form is what a plant person recognizes and searches for. The
+ladder is in `../../skills/data-consolidate/reference/join-keys.md`.
+
+Production work orders and maintenance work orders are separate fields with
+separate names. They are different records and the two systems use the same word.
+
+### 4. Every timestamp carries its zone
+
+No naive timestamps cross a contract boundary. A producer reading a naive source
+resolves it against the source clock declarations in the `## Plant context` block
+first, and where it cannot, the field is emitted as unresolved rather than
+assumed. Time handling is `../../skills/onboarding/reference/time-config.md`.
+
+### 5. Every quantity carries its unit
+
+Counts carry their unit of measure and money carries its currency code. A total
+computed across two units is not a total, so a contract never holds a bare
+number where a unit could vary.
+
+### 6. Every derived field carries its provenance
+
+Anything the producer worked out rather than read carries where it came from:
+which file, which page, which record, which prior job. This is required
+independently for extracted RFQ fields, quote cost lines, cited work orders,
+recurrence findings and trade study scores, which makes it a contract rule rather
+than six separate skill rules.
+
+A consumer is entitled to know which of its inputs were read and which were
+inferred, because it has to say so in its own output.
+
+### 7. Site scope travels with the payload
+
+Every contract carries the site it belongs to. Shift boundaries, vocabulary and
+capability are site-scoped, and a payload that loses its site can be read against
+another plant's configuration — the exact failure
+`../../skills/onboarding/reference/config-profile.md` is structured to prevent.
+
+### 8. Approval state is part of the payload, not an assumption
+
+Where a chain gates before a handoff, the contract carries who approved it and
+when. A consumer must be able to tell an approved determination from a draft one
+without inferring it from context. This matters most for the supplier-caused
+flag, where the determination is commercially significant.
+
+---
+
+## Versioning
+
+Each contract carries a `contract_version` integer. It increments when the shape
+changes, not when values change. A consumer reading an older version reads the
+fields it knows and treats the rest as absent, following the missing behavior
+above.
+
+## Adding a contract
+
+A new one is needed whenever a skill's structured output becomes another skill's
+declared input. Write it before either side. Give every field a type, a source
+and a missing behavior, and include a worked example — the example is what makes
+a shape mismatch obvious to a reader, which a field table alone does not.
diff --git a/plugins/claude-for-manufacturing/shared/contracts/consolidated-dataset.md b/plugins/claude-for-manufacturing/shared/contracts/consolidated-dataset.md
new file mode 100644
index 00000000..24f59f45
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/consolidated-dataset.md
@@ -0,0 +1,332 @@
+# Contract: the consolidated dataset
+
+**Emitted by** `data-consolidate`
+**Consumed by** every data-dependent skill — as the default source, not the
+only one; see *What this dataset is authoritative for* below — and it is the
+mapping target for `custom-connector`
+**Chain** 1, RFQ to quote (step 2) and 3, Morning plant pulse (step 1)
+**Contract version** 6
+
+Rules that govern every contract are in [README.md](README.md).
+
+This file names the tabs
+and columns so a consumer and a producer cannot invent two different shapes.
+
+---
+
+## Form
+
+One queryable working file. **Excel workbook, one tab per entity, is the v1
+format. The writer is swappable.** The shape below is the contract.
+
+If `data-consolidate` pulled a record type, that type has a tab. A pulled input
+with no tab is how inventory went missing the first time this file was written.
+
+---
+
+## Entity tabs
+
+The join hangs off five anchors: part, production work order,
+sales order, lot, asset. Every other input is an entity too. It gets its
+own tab. It is not folded onto an anchor.
+
+### The five anchors
+
+| Tab | Grain | Key | Fields |
+|---|---|---|---|
+| `parts` | One row per part | Part number | Description, standard cost, UOM |
+| `production_work_orders` | One row per production work order | Production work order number | Part, qty ordered, due date, status, and from version 5 the sales order it is built for (`sales_order` / `sales_order_verbatim`, null where the source holds no link). From version 6, closed-job cost where the ERP holds it: `actual_material_cost`, `actual_labor_cost`, `actual_burden_cost`, `actual_subcontract_cost` (each with `currency`), `qty_completed`, `closed_date`, `revision`, all nullable |
+| `sales_orders` | One row per sales order line | Sales order number | Customer, part, qty, promised date, price |
+| `lots` | One row per lot or batch | Lot number | The identity stamped on a quantity of material |
+| `assets` | One row per machine | Asset ID | Location |
+
+### The other inputs
+
+| Tab | Grain | Joins on | Fields |
+|---|---|---|---|
+| `inventory` | One row per part per location | Part | On-hand qty, location |
+| `purchase_orders` | One row per PO line | Part, supplier ID | Supplier, part, qty, cost, delivery date |
+| `production_output` | One row per work order per shift per production day | Production work order, part | Qty good, qty scrap, shift, production day. **Two rows at the same grain are a duplicate key (class 8); the same work order on another shift is not** |
+| `downtime_events` | One row per stoppage | Asset | Start, end, reason code |
+| `inspection_results` | One row per measurement | Lot or production work order | Measurement vs spec |
+| `maintenance_work_orders` | One row per maintenance ticket | Asset | Maintenance work order, dates, close-out notes |
+| `plan` | One row per part per date | Part | Planned qty, date |
+| `ncrs` | One row per NCR | Production work order, part, lot | NCR ID, found at, description verbatim, status, customer. |
+
+`inventory` is on-hand **by part and location**. A single on-hand total on
+`parts` is not this tab. Containment needs the location.
+
+Supplier is a join key, not an anchor. It lives on `purchase_orders`.
+
+**`ncrs` is where an NCR export lands, and the NCR-to-work-order check runs on
+it**: the NCR's part against the part the ERP holds for the work order it
+cites, and its date against that work order's first recorded output.
+`ncr-writeup` and `root-cause-capa` still read the NCR export raw for the
+record as written; they read this tab for whether its part label can be
+trusted.
+
+### Routings and operation actuals
+
+Two more inputs, for quoting. They are what `quote-build` derives
+machine hours from before it ever opens a model, and the order matters: a
+current-revision routing or a trustworthy set of actuals makes the design step
+a cross-check rather than the basis.
+
+| Tab | Grain | Joins on | Fields |
+|---|---|---|---|
+| `routings` | One row per part, revision and operation | Part | `part_revision`, `op_seq`, `work_center` / `work_center_verbatim`, `cell`, `setup_hours`, `run_time_per_unit`, `run_time_unit`, `time_unit_flag`, `routing_mismatch` |
+| `operation_actuals` | One row per production work order and operation | Production work order, part | `op_seq`, `work_center` / `work_center_verbatim`, `cell`, `actual_setup_hours`, `actual_run_hours`, `qty_completed`, `uom`, `closed_date`, `time_unit_flag`, `actuals_confidence`, `confidence_reason` |
+
+Column behavior on both tabs:
+
+| Column | Type | Behavior | Notes |
+|---|---|---|---|
+| `part_revision` | string or null | Degrades on `routings` | The revision the routing was written for. **Null is not "current"**: a routing with no revision is reported as revision-unknown, never assumed to match the drawing |
+| `op_seq` | integer | Required | As the source numbers it |
+| `work_center` / `work_center_verbatim` | string | Required | A pair, like a join key, though it is not one of the six |
+| `cell` | string or null | Degrades | From the machine class to work center map in the Plant context. Null when there is no map, and the report says so |
+| `setup_hours`, `run_time_per_unit` | number | Required | As the source states them. **Never converted** |
+| `run_time_unit` | enum | Required | `min`, `h`, or `undeclared`. Read from the header or a unit column, never inferred from the size of the number |
+| `time_unit_flag` | string or null | Degrades | Set when a unit is undeclared, or when this tab's unit differs from the other tab's for the same part and operation. Names both units. No conversion is computed |
+| `routing_mismatch` | enum or null | Degrades | `no_matching_part` (the routing's part is not in the item master — mismatch class 1) or `revision_mismatch` (the routing is for a revision other than the one being quoted or held as current — class 4, with no automatic fix). Null when neither |
+| `actual_setup_hours`, `actual_run_hours` | number or null | Degrades | Null where the source lumps setup and run into one figure; then `confidence_reason` says the split is unknown |
+| `qty_completed` | number | Required | With `uom` |
+| `closed_date` | date | Required | The work order's close. Rule 4 applies to `as_of`; a date-only close is fine here |
+| `actuals_confidence` | enum | Required | `recorded` or `probable_standard`. See below |
+| `confidence_reason` | string or null | Required when `probable_standard` | The arithmetic that set it: which work orders, which figures, how far apart |
+
+**`probable_standard` is the backflush check.** Many ERPs close an operation by
+posting its standard rather than the time it took. Two tests, either sets the
+flag, both run in code:
+
+1. Actual run hours ÷ quantity matches the routing's run standard for that part
+ and operation within 1%, after both are in the same unit — a unit
+ conversion done for this comparison only, shown, and never written back to
+ either tab.
+2. Two or more work orders for the same part and operation agree on run hours
+ per unit within about 1%. Real shop time is not that tidy.
+
+Actuals flagged `probable_standard` stay on the tab and are shown. They are
+**never ranked above a geometry-derived estimate** by `quote-build`, because
+they may be the routing wearing a work order number.
+
+**No routing data is a named gap.** Where no routing source exists, the
+`routings` tab is absent and the report names it missing. An empty `routings`
+tab would read as "this part has no operations," which is false.
+
+---
+
+## What this dataset is authoritative for
+
+Every data-dependent skill reads this dataset rather than the raw sources, and
+three skills also read a raw export. Both halves are deliberate. Here is how
+they fit together.
+
+**This dataset is authoritative for the join.** It is the only place the sources
+are matched on the six keys, normalized through the documented ladder, and their
+failures classified into the eight mismatch classes. Any question shaped *which
+records go together* — which parts came off which work order, where the suspect
+quantity physically sits, what a lot traces to — is answered here and nowhere
+else. Going back to a raw export for that reproduces the join by hand, which is
+precisely the manual work this skill exists to end.
+
+**It is not authoritative for two things:**
+
+| What | Why not | Who reads raw |
+|---|---|---|
+| **A high-frequency sensor trace** | There is no sensor tab, and there should not be. A spindle-load curve at sub-second resolution is not an entity keyed on an anchor; folding it in would produce a workbook nobody can open | `root-cause-capa` — historian export |
+| **A value as recorded, rather than as normalized** | The ladder rewrites keys, and a joined view may have moved a row into a mismatch class. A computed control chart needs the measurement the way the gage wrote it | `root-cause-capa`, `ncr-writeup` — quality export |
+
+`daily-production-report` is the third, and it is a different case: it reads the
+dataset as its **primary** input, and the plan, output and
+downtime exports alongside it. That is not a second opinion — the dataset gives
+it the freshness picture and the classified mismatches, and the exports give it
+rows at their native grain.
+
+## When a skill reads both, the dataset wins on identity
+
+This is the rule that matters operationally, because reading two sources is how
+one report ends up carrying two different numbers for the same thing.
+
+**On identity — which part, which work order, which lot, which asset — the
+dataset wins.** Its keys are normalized and its mismatches are classified. A raw
+export's key is unnormalized by definition, so preferring it silently
+reintroduces the drift `data-consolidate` just resolved.
+
+**On the measured value — the sensor reading, the inspection measurement — the
+raw export wins**, because that is the value as recorded and it is why the skill
+went there.
+
+**Where the two disagree on a count, say so rather than choosing.** A discrepancy
+between the joined view and the raw rows is a finding about the export, not a
+number to pick between. Report both, name which is which, and let the plant tell
+you which system is right. Per `../absent-is-not-zero.md`, quietly resolving it
+is the failure mode — a supervisor reading one number never learns there were
+two.
+
+**Always name which source a number came from.** Every tab already carries
+`source_system` and `source_ref` for exactly this. A figure read from a raw
+export carries the file and row the same way.
+
+---
+
+## Columns every row carries
+
+These appear on every entity tab.
+
+| Column | Type | Behavior | Notes |
+|---|---|---|---|
+| `site` | string | Required | Rule 7 |
+| `source_system` | string | Required | `netsuite`, `infor_m3`, `cmms` (any CMMS connector; `limble` accepted from earlier versions), `mes_export`, `historian_export`, `qms_export`, `planning_export`, `manual` |
+| `source_ref` | string | Required | File and row, or connector record ID. Rule 6 |
+| `as_of` | timestamp with zone | Required | When the source recorded it, not when we read it. Rule 4 |
+| `join_status` | enum | Required | `matched`, `unmatched`, `normalized`, `duplicate`, `proposed_normalization`. The last is a row that matches only once a proposed fix (classes 2 to 5) is approved. It becomes `normalized` on a yes and is **not joined until then** |
+| `mismatch_class` | integer or null | Degrades | 1–8 per `../../skills/data-consolidate/reference/mismatch-classes.md`, null when matched |
+| `contradicted_by` | string or null | Degrades | On a class 6 row only: the source and record that show the missing activity happened (`quality_ncrs.csv NCR-2026-0141`). Null otherwise. |
+| `integrity_flags` | list or null | Degrades | Named failures of the integrity checks in `../../skills/data-consolidate/reference/join-keys.md`: `sign_convention`, `mixed_sign`, `end_before_start`, `duration_mismatch`, `ncr_part_differs`, `ncr_dated_before_wo`, `future_timestamp`, `units_conflict`. Null when none. |
+
+## Join-key columns
+
+Every join key is a pair, per rule 3.
+
+| Column | Type | Behavior |
+|---|---|---|
+| `part_number` / `part_number_verbatim` | string | Required on any tab keyed by part, including `inventory` |
+| `part_revision` | string or null | Degrades. Preserved when ladder rung 5 strips it |
+| `production_wo` / `production_wo_verbatim` | string | Required on production tabs |
+| `sales_order` / `sales_order_verbatim` | string | Required on sales tabs |
+| `lot_number` / `lot_number_verbatim` | string | Required on lot and inspection tabs |
+| `asset_id` / `asset_id_verbatim` | string | Required on asset, downtime and maintenance tabs |
+| `supplier_id` / `supplier_id_verbatim` | string | Required on `purchase_orders` |
+| `maintenance_wo` | string | Required on `maintenance_work_orders`. Never named `work_order` |
+
+## Quantity columns
+
+Per rule 5: flag differing UOMs, do not silently sum.
+
+| Column | Type | Behavior |
+|---|---|---|
+| `qty` | number | Required where a quantity is reported. On `sales_orders` and fulfilment rows a positive quantity: a source that signs those lines negative is read as the absolute value, flagged `sign_convention` |
+| `qty_verbatim` | number or null | Degrades. The quantity as the source signed it, where `sign_convention` changed it |
+| `uom` | string | Required alongside any `qty`. Never inferred |
+| `amount` | number | Degrades. Standard cost, PO cost, sales price |
+| `currency` | ISO 4217 code | Required alongside any `amount` |
+
+On `production_output` the quantities are `qty_good` and `qty_scrap`, each
+paired with `uom`. On `inventory` the quantity is on-hand at that location.
+
+---
+
+## Worked example
+
+An `inventory` row and three `production_output` rows. The inventory row is
+the one this version exists to make explicit.
+
+```
+# inventory
+site,source_system,source_ref,as_of,join_status,mismatch_class,
+part_number,part_number_verbatim,location,qty,uom
+
+Fairview,netsuite,inventory/FG-A12,2026-09-08T06:10:00-04:00,matched,,
+PN-4471-B,PN-4471-B,FG-A12,240,each
+
+Fairview,netsuite,inventory/WIP-CELL-B,2026-09-08T06:10:00-04:00,matched,,
+PN-4471-B,PN-4471-B,WIP-CELL-B,60,each
+
+# production_output
+site,source_system,source_ref,as_of,join_status,mismatch_class,
+production_wo,production_wo_verbatim,part_number,part_number_verbatim,
+part_revision,qty_good,qty_scrap,uom,shift
+
+Fairview,mes_export,prod-output-20260907.csv:412,2026-09-07T14:22:00-04:00,
+matched,,WO-88201,WO-88201,PN-4471-B,PN-4471-B,,486,14,each,2
+
+Fairview,mes_export,prod-output-20260907.csv:413,2026-09-07T15:03:00-04:00,
+normalized,2,WO-88202,wo 88202,PN-4471-B,4471B,,240,0,each,2
+
+Fairview,mes_export,prod-output-20260901.csv:88,2026-09-01T09:10:00-04:00,
+unmatched,7,WO-88231,WO-88231,PN-4402-A,PN-4402-A,,120,3,each,1
+```
+
+Reading those:
+
+- 240 of PN-4471-B sit in finished goods. 60 are still at cell B. Same part,
+ two locations, two rows. That is what containment reads.
+- Production row 1 matched cleanly.
+- Production row 2 matched after ladder rungs 1–3. The verbatim columns keep
+ what the MES wrote.
+- Production row 3 is class 7, a date-window mismatch. **Not an orphan.**
+
+### Version 4: a routing and two actuals
+
+```
+# routings
+site,source_system,source_ref,as_of,join_status,mismatch_class,
+part_number,part_number_verbatim,part_revision,op_seq,work_center,
+work_center_verbatim,cell,setup_hours,run_time_per_unit,run_time_unit,
+time_unit_flag,routing_mismatch
+
+Fairview,manual,erp_routings.csv:3,2025-11-12T00:00:00-05:00,matched,4,
+PN-4471-B,PN-4471-B,1,20,HAAS-VF4-02,HAAS-VF4-02,CELL-B,1.25,7.00,min,
+"routing in min, actuals in h - not converted",revision_mismatch
+
+# operation_actuals
+site,source_system,source_ref,as_of,join_status,mismatch_class,
+production_wo,production_wo_verbatim,part_number,part_number_verbatim,
+op_seq,work_center,work_center_verbatim,cell,actual_setup_hours,
+actual_run_hours,qty_completed,uom,closed_date,time_unit_flag,
+actuals_confidence,confidence_reason
+
+Fairview,manual,erp_operation_actuals.csv:2,2026-03-18T00:00:00-04:00,matched,,
+WO-87412,WO-87412,PN-4471-B,PN-4471-B,20,HAAS-VF4-02,HAAS-VF4-02,CELL-B,
+1.30,23.33,200,each,2026-03-18,"routing in min, actuals in h - not converted",
+probable_standard,"0.1167 h/pc here vs 0.1173 h/pc on WO-87655 (0.6% apart); 7.00 min routing standard = 0.1167 h/pc (0.0% apart)"
+```
+
+- The routing is for revision 1. Quoted against revision 2, it is
+ `revision_mismatch`: shown as superseded, never priced from.
+- The two units are named on both rows and neither is rewritten. The backflush
+ check converted them for its own comparison and printed that it did.
+- Both tests fired on WO-87412, so it is `probable_standard`. It is still on
+ the tab, and still shown.
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What the consumer does |
+|---|---|
+| A tab is absent entirely | Degrades. Report on what exists, name the missing entity, never treat it as empty |
+| `inventory` is absent | Degrades. `ncr-writeup` cannot place parts from the dataset. Ask location by location, or read the ERP (NetSuite or Infor M3) / an inventory export, and record each answer as unverified until confirmed. Never treat absence as zero on hand |
+| A row's `uom` is absent | Degrades. Report the quantity, refuse to aggregate it, say why |
+| `join_status` is `duplicate` | Blocks for any total including that key. Surface both rows |
+| `join_status` is `proposed_normalization` | Degrades. **Not joined.** No total treats the row as matched; any figure that would use it is shown provisional, with both spellings and the fix awaiting a yes |
+| `contradicted_by` is set | Degrades. The record is an exception, *one-sided, contradicted by* the named record. Never "Checked, nothing wrong" |
+| `integrity_flags` holds `end_before_start` or `duration_mismatch` | Degrades. The row's minutes are held out of every minutes total and the minutes ranking; it still counts as an event. The exclusion is stated with the row |
+| `integrity_flags` holds `mixed_sign` | Blocks any total of that record type's quantities |
+| `integrity_flags` holds `ncr_part_differs` or `ncr_dated_before_wo` | Degrades. The NCR's part label or date is not used for same-part history or to date a defect. Show both values |
+| `integrity_flags` holds `future_timestamp` | Degrades. The source's `as_of` is untrusted; no age or "data as of" is stated from it |
+| A `production_work_orders` actual-cost column is null | Degrades. That cost is not on file for that work order. `quote-build` uses the next rung for that line and says so; a null is never read as zero cost |
+| `production_work_orders.sales_order` is null | Degrades. Commitment impact for that work order is "not traceable: the source holds no work order to sales order link", never guessed from part and customer |
+| `join_status` is `unmatched` and `mismatch_class` is 1 | Degrades, and the orphan is named in the consumer's output |
+| `as_of` cannot be resolved to a zone | Degrades. The row is usable for counting and not for correlating |
+| `routings` is absent | Degrades. `quote-build` starts its hours ladder at closed-job actuals, or below. Name the tab missing, never treat it as no operations |
+| `operation_actuals` is absent | Degrades. The ladder has no rung 2. Name the tab missing |
+| `run_time_unit` is `undeclared`, or `time_unit_flag` is set | Degrades. The value is reported in its source unit and not used for any comparison or hours figure until the plant says what the unit is |
+| `routing_mismatch` is `revision_mismatch` | Degrades. The routing is not a basis for the revision being quoted. It may be shown as superseded, never priced from |
+| `actuals_confidence` is `probable_standard` | Degrades. Shown, never ranked above a geometry-derived estimate |
+| `actual_setup_hours` is null | Degrades. The setup and run split is unknown for that work order; it is never re-amortized as if it were known |
+
+---
+
+
+## When a new system is mapped in
+
+`custom-connector` maps onto this schema. Three requirements:
+
+1. **Every mapped row carries the columns every row carries**, including
+ `source_system` and `source_ref`.
+2. **Keys map to the pair, not the single.** The new system's own identifier
+ goes in the verbatim column; the normalized form comes from the ladder.
+3. **A field with no home here does not go in.** Either the schema gains the
+ field with a version bump, or the field stays out.
diff --git a/plugins/claude-for-manufacturing/shared/contracts/downtime-record.md b/plugins/claude-for-manufacturing/shared/contracts/downtime-record.md
new file mode 100644
index 00000000..055eee89
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/downtime-record.md
@@ -0,0 +1,168 @@
+# Contract: the downtime record
+
+**Emitted by** `breakdown-diagnosis`
+**Consumed by** `daily-production-report`, into its downtime log and exceptions
+**Chain** 4, breakdown to next report
+**Contract version** 3
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## The requirement this exists to satisfy
+
+Chain 4's build note is unusually direct: `breakdown-diagnosis` must emit a
+downtime record **in exactly the shape `daily-production-report` consumes, with
+no transformation step in between**, and the schema is to be defined before
+either skill is built.
+
+There is a specific reason it has to be exact. `daily-production-report` already
+reads downtime events from the MES or historian export. A record arriving from a
+diagnosis is a **row in that same log**, not a separate feed. If the two shapes
+differ, the report has to reconcile them, and a reconciliation step between two
+sources of downtime is precisely how a stoppage gets counted twice or dropped.
+
+**So this contract is the MES downtime export's shape, plus diagnosis fields.**
+It is deliberately not a richer object.
+
+---
+
+## Fields
+
+### The stoppage itself — identical to an export row
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Rule 7 |
+| `asset_id` | string, normalized | Required | Paired with verbatim, rule 3 |
+| `asset_id_verbatim` | string | Required | As the source wrote it |
+| `started_at` | timestamp with zone | Required | Rule 4. No naive timestamps |
+| `ended_at` | timestamp with zone or null | Degrades | Null means still down. Not zero duration |
+| `duration_minutes` | integer or null | Degrades | Null while `ended_at` is null. Never computed as zero |
+| `reason_code` | string | Degrades | The plant's own code. Not remapped to a canonical set |
+| `reason_text` | string | Optional | Free text as recorded |
+| `production_wo` | string, normalized, or null | Optional | The production work order interrupted, when known. Paired with verbatim, rule 3 |
+| `production_wo_verbatim` | string or null | Optional | As the source wrote it. Null whenever `production_wo` is null |
+| `shift` | string | Degrades | Resolved against the site's shift pattern and day boundary |
+| `production_day` | date | Required | Which day this belongs to, per the cross-midnight rule |
+| `source_system` | string | Required | `breakdown_diagnosis` here; `mes_export` or `historian_export` for export rows |
+| `source_ref` | string | Required | Rule 6 |
+
+### The diagnosis fields — additive only
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `diagnosis_ref` | string or null | Optional | Pointer to the ranked diagnosis this came from |
+| `leading_cause` | string or null | Optional | The top-ranked candidate, as text |
+| `leading_cause_confidence` | enum or null | Optional | `high`, `medium`, `low`. Never a bare percentage |
+| `cited_work_orders` | list of strings | Optional | Maintenance work orders supporting the leading cause |
+| `safety_flagged` | boolean | **Required** | See below |
+| `safety_reason` | string or null | Required when `safety_flagged` is set | Which trigger from `../../skills/breakdown-diagnosis/SKILL.md` (*What counts as a safety implication*) applies, with its evidence; or *"none of the safety triggers shown"* when false. |
+| `pm_adjustment_proposed` | boolean | Optional | Whether a PM plan change was drafted |
+| `maintenance_wo` | string or null | Optional | The maintenance ticket, if one exists. Never named `work_order` |
+| `diagnosis_state` | enum | Required | `advisory`, `technician_confirmed`, `superseded` |
+| `technician_step` | enum | Required | Chain 4's pause for the technician: `confirmed` (they came back and confirmed or corrected the cause), `pending` (the chain paused and is waiting), `skipped` (no technician step happened: a test, a demo, or a record folded in straight away). |
+
+---
+
+## Three fields that carry real weight
+
+**`safety_flagged` is required and defaults to nothing.** `breakdown-diagnosis`
+must surface a safety implication before any diagnosis, and that ordering has to
+survive the handoff — a safety-critical stoppage cannot arrive in a production
+report as an ordinary line ranked by minutes. The consumer leads with it.
+
+**`duration_minutes` is null while a machine is still down, never zero.** A zero
+would rank an ongoing outage last in a log sorted by minutes, which is exactly
+backwards. This is `../absent-is-not-zero.md` applied to one field.
+
+**`diagnosis_state` keeps advice labelled as advice.** Chain 4 pauses at a human
+working a physical machine and the diagnosis is advisory throughout. A report
+that presents an unconfirmed leading cause as the reason for the stoppage is
+asserting something no one verified. **`technician_step` says why it is still
+advice**: a record folded in with the pause skipped is not the same as one
+waiting on a technician, and the report and the dashboard say which.
+
+---
+
+## Reason codes are passed through, not normalized
+
+`reason_code` carries the plant's own code verbatim. Do not remap it to a
+canonical vocabulary on the way across.
+
+The consumer has its own job here: when reason codes are inconsistent or heavily
+weighted to "Other", **that coverage problem is a finding it reports**, not
+something the producer should quietly clean up. Normalizing on emit would destroy
+the signal.
+
+---
+
+## Worked example
+
+A four-hour spindle failure, diagnosed, technician not yet finished:
+
+```yaml
+contract_version: 3
+site: Fairview
+asset_id: HAAS-VF4-02
+asset_id_verbatim: "Haas VF4 #2"
+started_at: 2026-09-08T09:12:00-04:00
+ended_at: null
+duration_minutes: null
+reason_code: MECH-04
+reason_text: "Spindle noise then fault code SV-2"
+production_wo: WO-88240
+production_wo_verbatim: "88240"
+shift: "1"
+production_day: 2026-09-08
+source_system: breakdown_diagnosis
+source_ref: "diagnosis/2026-09-08/HAAS-VF4-02"
+
+diagnosis_ref: "diagnosis/2026-09-08/HAAS-VF4-02"
+leading_cause: "Spindle bearing failure, accelerated by coupling misalignment"
+leading_cause_confidence: medium
+cited_work_orders: ["LMB-14022", "LMB-13781"]
+safety_flagged: false
+safety_reason: "none of the safety triggers shown"
+pm_adjustment_proposed: true
+maintenance_wo: LMB-14103
+diagnosis_state: advisory
+technician_step: pending
+```
+
+How `daily-production-report` must read it: append as a `downtime_events` row,
+lead the exceptions section with it because `ended_at` is null and the machine is
+still down, price it as **unpriced so far** rather than zero minutes, and attribute
+the leading cause with its confidence and its `advisory` state stated — not as
+the established reason.
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What `daily-production-report` does |
+|---|---|
+| No downtime records at all | Degrades. Say downtime data was not available. **Never render an empty section**, which reads as no downtime |
+| `ended_at` and `duration_minutes` both null | Degrades. List under exceptions as ongoing; exclude from the minutes ranking and say it was excluded |
+| `reason_code` absent or "Other" heavy | Degrades. Report the coverage problem as a finding |
+| `production_day` absent | Blocks for that row. Without it the row cannot be attributed to a day, and guessing moves output between days |
+| `started_at` naive or unresolved | Blocks for that row, per rule 4 |
+| `safety_flagged` absent | Blocks. Treat a missing safety flag as unknown and say so, never as false |
+| `diagnosis_state` is `advisory` | Degrades. Attribute the cause as proposed, never as established |
+| `technician_step` is `skipped` or `pending` | Degrades. Say which beside the cause, in the report and on the dashboard |
+| `safety_reason` absent on a version 2 record | Degrades. Show the flag; say no reason was recorded |
+
+## If no CMMS connector is live
+
+Limble is the worked example; it is added through `custom-connector`, not
+one of the four supported connectors, so this is the default case.
+
+The contract does not change. `maintenance_wo` and `cited_work_orders` are
+populated from exported maintenance history rather than live tickets, and
+`pm_adjustment_proposed` may be false because the current PM interval was not
+readable.
+
+The one thing that must change is disclosure: the record is still export-sourced
+and the consumer's freshness banner names it as such, so nobody reads a nightly
+export as this morning's tickets.
diff --git a/plugins/claude-for-manufacturing/shared/contracts/floor-layout.md b/plugins/claude-for-manufacturing/shared/contracts/floor-layout.md
new file mode 100644
index 00000000..d46b984a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/floor-layout.md
@@ -0,0 +1,108 @@
+# Contract: the floor layout
+
+**Emitted by** `daily-production-report`, step 9a, in an attended setup turn only
+**Consumed by** `daily-production-report`, step 9a, on every later run, to draw the floor view
+**Chains** 3 (the morning report inside the pulse reads the same profile)
+**Contract version** 2
+
+Rules that govern every contract are in [README.md](README.md). Where the
+profile is stored and how it is saved is `../replies.md`, *The plant setup and
+the rates: two private pages*.
+
+---
+
+## Why it exists
+
+A plant manager gives Claude their floor plan once. Every later report, in any
+new task, draws each machine's figures where it sits, with no re-upload. So
+the layout is stored **inside the plant profile**, as one section per site,
+and travels with it on the plant setup page that every skill brings in with
+`plant_setup.py find`. The drawing itself is never stored, only what was read
+from it.
+
+**Only the setup turn writes it**, after the person confirmed the matches and
+typed a name or role. Every other run only reads it.
+
+---
+
+## Where it lives
+
+A `### Floor layout - <site>` section of the `## Plant context` block, one per
+site, after the profile's other sections. It holds no rate value and no email
+address, so the plant setup page accepts it.
+
+## Header lines
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `Layout version` | integer | Required | Starts at 1, plus 1 on every save. A section with no version line is version 1 |
+| `Contract version` | integer | Required | 2. Absent: read as 1, with the defaults under *Missing behavior* |
+| `Drawing` | string | Required | File name, sha256 (first 12 characters), date received, machines read, unlabeled shapes, legend used yes or no. Provenance only |
+| `Aspect` | number | Required | The drawing's width divided by its height. The schematic keeps it at any width |
+| `Read` | `clean`, `partial` or `poor` | Required | A `poor` read is never saved |
+| `Zones` | list | Required | `Name (x,y,w,h)` per area, separated by `;`. Optional outline points after the box for an irregular zone: `Name (x,y,w,h) [x1,y1 x2,y2 ...]` |
+| `Confirmed by` | string | Required | The name or role the person typed, and the date. Never taken from the account. No value, no save |
+
+## Machine rows
+
+One pipe table, one row per labelled shape on the drawing. Positions are
+normalized 0 to 1 on the drawing, origin top left.
+
+| Column | Type | Behavior | Notes |
+|---|---|---|---|
+| `Label` | string | Required | Verbatim from the drawing, `?` appended when the read mark is `unsure` |
+| `Asset` | string or `-` | Required | The asset key, verbatim from the data. `-` when unmapped |
+| `Asset name` | string or `-` | Required | The asset's own spelling in the data, so both spellings stay visible |
+| `Box` | `x,y,w,h` | Required | Normalized 0 to 1 |
+| `Zone` | string | Required | A zone named in `Zones` |
+| `Read` | `clear` or `unsure` | Required | An `unsure` label is never `confirmed` |
+| `Status` | `confirmed`, `proposed` or `unmapped` | Required | Only `confirmed` draws figures |
+| `Confirmed at` | date or `-` | Required | The day of the yes, for `confirmed` rows |
+
+Unlabeled shapes the person said are not machines are not rows.
+
+---
+
+## Worked example
+
+```
+### Floor layout - Fairview
+
+- **Layout version:** 1
+- **Contract version:** 2
+- **Drawing:** fairview-floor-plan.png, sha256 18c963f688f7, received 2026-11-10, 7 machines read, 1 unlabeled shape, legend used no
+- **Aspect:** 1.60
+- **Read:** clean
+- **Zones:** Cell A (0.03,0.06,0.44,0.40); Cell B (0.53,0.06,0.44,0.40); Cell C (0.03,0.54,0.44,0.40); Cell D (0.53,0.54,0.44,0.40)
+- **Confirmed by:** plant manager, 2026-11-10
+
+| Label | Asset | Asset name | Box | Zone | Read | Status | Confirmed at |
+|---|---|---|---|---|---|---|---|
+| Mazak QT250 | MAZAK-QT-01 | Mazak QT250 | 0.07,0.16,0.16,0.22 | Cell A | clear | confirmed | 2026-11-10 |
+| Mazak QT250 #4 | MAZAK-QT-04 | Mazak QT250 #4 | 0.27,0.16,0.16,0.22 | Cell A | clear | confirmed | 2026-11-10 |
+| Haas VF4 #2 | HAAS-VF4-02 | Haas VF4 #2 | 0.57,0.16,0.16,0.22 | Cell B | clear | confirmed | 2026-11-10 |
+| Haas VF4 #5 | HAAS-VF4-05 | Haas VF4 #5 | 0.77,0.16,0.16,0.22 | Cell B | clear | confirmed | 2026-11-10 |
+| Puma 3 | DOOSAN-PUMA-03 | Doosan Puma 3 | 0.07,0.64,0.16,0.22 | Cell C | clear | confirmed | 2026-11-10 |
+| Puma 7 | DOOSAN-PUMA-07 | Doosan Puma 7 | 0.27,0.64,0.16,0.22 | Cell C | clear | confirmed | 2026-11-10 |
+| Okuma Genos M560 | OKUMA-GENOS-02 | Okuma Genos M560 | 0.57,0.64,0.16,0.22 | Cell D | clear | confirmed | 2026-11-10 |
+| Bar saw | - | - | 0.77,0.64,0.16,0.22 | Cell D | clear | unmapped | - |
+```
+
+`HAAS-UMC-01` is in the data and on no row, so every report lists it under
+*Not on the floor plan* with its figures. `Bar saw` is on the drawing and in
+no data, so it is drawn as a neutral outline and listed under *On the plan,
+not in the data*.
+
+---
+
+## Missing behavior
+
+| Absent | What the consumer does |
+|---|---|
+| The whole section | Skip the floor view with one line: *"No floor layout is on file. Attach a floor plan (PDF or image) to set one up."* Nothing else in the report changes |
+| `Layout version` or `Contract version` | Read as version 1. Rows with no `Read` column are `clear`; rows with no `Status` column are `proposed`, so they draw no figures until confirmed again |
+| `Confirmed by` | Every row is treated as `proposed`. The view draws outlines only and says the layout needs confirming |
+| `Aspect` | Use the bounding box of all zones |
+| A zone's outline points | Draw its box |
+| A machine's figures-block row | *No data*, grey, out of every average. Never 0% |
+| A machine's OEE, with the row present | *OEE N/A*, grey, availability shown, the reason listed |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/geometry-estimate.md b/plugins/claude-for-manufacturing/shared/contracts/geometry-estimate.md
new file mode 100644
index 00000000..4b896e66
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/geometry-estimate.md
@@ -0,0 +1,294 @@
+# Contract: the geometry estimate
+
+**Emitted by** `rfq-to-quote`, at the design step (step 7), or typed by an
+estimator by hand
+**Consumed by** `quote-build`, at the hours step
+**Chain** 1, RFQ to quote (steps 7 to 9)
+**Contract version** 1
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## What this carries, and what it never carries
+
+**The part as the plant would make it, read from the customer's drawing:** the
+stock, the datums, every feature with the tolerance that drives it, the setups
+and the operation list. It is what `quote-build` derives hours from when no
+routing for this part and revision exists, and what it cross-checks a routing
+against when one does.
+
+**It carries no hours, no rates and no prices.** Hours are derived from it by
+`quote-build` after Gate 3, because hours derived from a model nobody has
+confirmed are a guess with a decimal point. A geometry estimate that grew an
+hours column would let an unconfirmed model price a job.
+
+**It is an internal estimating aid and never goes to a customer.** The model
+it describes was generated by the plant to estimate from. It is not the
+customer's design, it is not a proposal, and nothing in it is sent. That
+includes `cost_down_proposals`: a cheaper way to make the part is an idea for
+the estimator, not a change offered to the customer.
+
+**It must be hand-authorable.** Where Fusion is not connected, an estimator
+can type the feature list from the drawing into this shape, and the hours step
+runs on it exactly as it would on a generated one. So every model-only field
+may be null, and the required core is what a person reading a print can fill
+in.
+
+---
+
+## Header
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Rule 7 |
+| `inquiry_ref` | string | Required | The intake form's `rfq_reference`, or the inquiry's own reference where the customer gave none |
+| `line_no` | integer | Required | The intake form line this estimates. One estimate per line |
+| `part_number` / `part_number_verbatim` | string or null | Degrades | Rule 3. Null on a new part with no number yet |
+| `geometry_path` | enum | Required | `C2`, `C1`, `B`, `A`, `none`. Carried from the intake form's `geometry_path`, after any reclassification at `rfq-to-quote` step 7. See the path table below |
+| `drawing_revision_priced_to` | string or null | Required | The revision every feature below was read from. Null only where there is no drawing: path A, where the estimate then supports a ROM only, and path C1, where each feature's `source_ref` names the STEP file |
+
+### The paths
+
+| Path | What it means | `origin` |
+|---|---|---|
+| `C2` | A drawing (PDF, image or text extract). The model is generated from the drawing's dimensions, tolerances and notes | `built_from_drawing`, or `hand_entered` |
+| `C1` | A STEP or other 3D file, and no drawing. The file is imported and read; nothing is generated. **STEP import through the connector is unverified**, and so is reading the STEP as text without CAD. A C1 line with a drawing is C2 | `customer_step`, or `hand_entered` |
+| `B` | A drawing plus a different prior part whose model on file is named as the starting point. The prior model is opened, the drawing's changes applied, and the result saved as a new document; **the prior model is never overwritten**. A new revision of the same part is C2. Where the prior model is unavailable the line falls back to C2 and the estimate says so | `adapted_from_prior` |
+| `A` | Text specifications, no drawing. Built with the same calls as C2, every dimension and tolerance `from_text`. **The estimate supports a ROM only, never a firm quote** | `built_from_text`, or `hand_entered` |
+| `none` | No geometry in the package — a repeat part named by number only | No estimate. Priced from its routing or actuals, or a question back to the customer |
+
+## Model
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `origin` | enum | Required | `built_from_drawing`, `adapted_from_prior`, `customer_step`, `built_from_text`, `hand_entered`. Per the path table above. `geometry_path` is the path that actually ran: a path B line that fell back is `C2` and `built_from_drawing` |
+| `document_ref` | string or null | Degrades | The new Fusion document the model lives in. Null on `hand_entered` |
+| `base_model_ref` | string or null | Optional | The prior part's model and the version it was opened at, path B only. **Never overwritten** — the producer reads its version again after the run and stops if it moved. Null on every other path, including a path B line that fell back to C2 |
+| `cad_backend` | enum | Required | `fusion` or `none`. `none` on `hand_entered`, and on `customer_step` when the STEP was read as text without CAD |
+| `generated_at` | timestamp with zone or null | Degrades | Rule 4. Null on `hand_entered` |
+| `document_integrity` | object | Required | See below |
+| `model_checks` | object or null | Degrades | Bounding box and volume read back from the model, and the hand calculation they were checked against, each with its unit |
+
+### `document_integrity`
+
+The Fusion connector can replay an earlier script into every later call until
+Fusion restarts, which puts geometry nobody asked for into the document. So
+the bodies and sketches are listed before and after every design step, and the
+result travels with the estimate.
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `result` | enum | Required | `clean`, `foreign_geometry`, `not_checked`, `not_applicable`. `not_applicable` only where no CAD document was opened: `hand_entered`, or a STEP read as text |
+| `bodies_before` / `bodies_after` | list of strings or null | Degrades | Names as Fusion listed them |
+| `sketches_before` / `sketches_after` | list of strings or null | Degrades | |
+| `checked_at` | timestamp with zone or null | Degrades | Rule 4 |
+| `detail` | string or null | Required when `result` is not `clean` | What was found, or why it could not be checked |
+
+**An estimate with `foreign_geometry` is not emitted as a usable estimate.**
+The step failed; the estimate exists only to say so.
+
+## Stock
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `material` | string | Required | As the drawing states it, with `source_ref` |
+| `form` | string or null | Degrades | Bar, plate, round, casting. As the drawing or the material spec states it |
+| `size` | string or null | Degrades | With units |
+| `fit_check` | object or null | Degrades | `part_envelope`, `cleanup_allowance` (with unit and where it came from), `fits` (boolean), `flag` (string or null — what does not fit, or what fits only without cleanup) |
+| `source_ref` | string | Required | |
+
+## Datums
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `datums` | list of objects | Degrades | Each: `label` (A, B, C), `feature`, `basis`, `source_ref` |
+| `datums[].basis` | enum | Required | `stated` — the drawing identifies the datum feature. `inferred` — assigned from the dimension scheme because the drawing references the datum without identifying its feature. **Every `inferred` datum is shown at Gate 3** |
+
+## Features
+
+One row per feature or patterned feature set.
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `type` | string | Required | Face, pocket, through-bore, hole pattern, fillet, chamfer, slot, thread |
+| `count` | integer | Required | |
+| `dimension` | string | Required | With units, as read |
+| `tolerance` | string or null | Degrades | As read. Null only where the drawing gives none and no general note applies, and then it is on `unreadables` |
+| `tolerance_driver` | boolean | Required | True where this tolerance, not the geometry, decides the process — a reamed bore, a KC, a flatness callout |
+| `surface_finish` | string or null | Degrades | As read |
+| `reading_basis` | enum | Required | `printed_callout`, `general_note`, `from_text`, `unreadable_flagged` — the same vocabulary as the intake form. **A general-note tolerance applied to a feature is reading, and cites the note**; anything else is not a tolerance at all. Path A rows are all `from_text`. A path C1 row read from a STEP file has no tolerance to read: `tolerance` null, `unreadable_flagged`, and on `unreadables` |
+| `source_ref` | string | Required | View and zone, or the note number. A feature with no `source_ref` is not permitted |
+
+## Setups and operations
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `setups` | list of objects | Degrades | Each: `setup_seq`, `faces` (which faces are reached), `fixture_note`, `machine_class` (a class from `### Machining data` in the Plant context, or the class as named when that section is absent) |
+| `operations` | list of objects | Required | Each: `op_seq`, `description`, `machine_class`, `setup_seq` (null for an operation off the machine), `features` (which feature rows it cuts), `outside_process` (boolean), `assumptions` (list of strings), `source_ref` |
+
+The operation list is the plant's proposed way to make the part. **It is
+confirmed at Gate 3 and only then derived into hours.**
+
+## Tolerances, unreadables and questions
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `tolerances` | list of objects | Required | Every tolerance read: `characteristic`, `value`, `reading_basis`, `source_ref`, `key_characteristic` (the drawing's KC label or null) |
+| `unreadables` | list of objects | Required, may be empty | Each: what could not be read, where, and why it matters. An empty list means everything was read, and says so |
+| `questions_for_estimator` | list of strings | Required, may be empty | Inferred datums, assumptions in the operation list, anything the estimator must rule on at Gate 3 |
+| `cost_down_proposals` | list of objects | Optional | Each: `idea`, `why`, `what_it_would_change`. **Internal only.** Never on the customer quote and never offered to the customer: proposing a design change back is a different workflow with its own gate, and it is not built |
+
+## Approval
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `approval.status` | enum | Required | `draft`, `confirmed`, `declined`. **The skill emits `draft`, always.** Only the estimator moves it, at Gate 3 |
+| `approval.by` | string or null | Required when not `draft` | The estimator who ruled |
+| `approval.at` | timestamp with zone or null | Required when not `draft` | Rule 4 |
+| `approval.note` | string or null | Optional | What the estimator changed or ruled on — a corrected datum, a removed operation |
+
+Per rule 8, a consumer reads this state rather than inferring approval from
+context. The skill that built the model never marks it confirmed.
+
+---
+
+## Worked example
+
+PN-4471-B Rev 2, path C2, built in Fusion from the drawing. Integrity clean.
+Datum A is identified on the drawing; B and C are referenced in the KC-2
+feature control frame but their features are not identified, so they are
+inferred and go to Gate 3.
+
+```yaml
+contract_version: 1
+site: Fairview
+inquiry_ref: "EH-RFQ-0912"
+line_no: 1
+part_number: PN-4471-B
+part_number_verbatim: "4471-B"
+geometry_path: C2
+drawing_revision_priced_to: "2"
+
+model:
+ origin: built_from_drawing
+ document_ref: "fusion://Fairview/estimates/EH-RFQ-0912_L1_PN-4471-B_R2"
+ base_model_ref: null
+ cad_backend: fusion
+ generated_at: 2026-10-13T10:41:00-04:00
+ document_integrity:
+ result: clean
+ bodies_before: []
+ bodies_after: ["Bracket_Upper"]
+ sketches_before: []
+ sketches_after: ["Profile_Top", "Bore_Sketch"]
+ checked_at: 2026-10-13T10:44:00-04:00
+ detail: null
+ model_checks:
+ bounding_box: "2.000 x 1.250 x 0.750 in (model) vs 2.000 x 1.250 x 0.750 in (drawing)"
+ volume: "1.687 in3 (model) vs 1.688 in3 (hand calc: block 1.875, less bore 0.147, less four corner fillets 0.040)"
+
+stock:
+ material: "4140 alloy steel bar, 2.5 in dia, MS-4140-BAR"
+ form: round bar
+ size: "2.5 in dia x 0.90 in cut length"
+ fit_check:
+ part_envelope: "2.000 x 1.250 in section"
+ cleanup_allowance: "0.050 in per side, plant standard (Plant context)"
+ fits: true
+ flag: "Section with cleanup is 2.100 x 1.350 in, diagonal 2.496 in, against 2.5 in bar: fits with 0.004 in on the diameter. Any bar at the low end of its size tolerance will not clean up."
+ source_ref: "drawing p1, MATERIAL"
+
+datums:
+ - { label: A, feature: "bottom face", basis: stated, source_ref: "drawing p1, view A, zone C3" }
+ - { label: B, feature: "long side face", basis: inferred, source_ref: "drawing p1, KC-2 frame; feature not identified" }
+ - { label: C, feature: "short end face", basis: inferred, source_ref: "drawing p1, KC-2 frame; feature not identified" }
+
+features:
+ - { type: face, count: 2, dimension: "0.750 in thick", tolerance: "±0.005 in", tolerance_driver: false, surface_finish: null, reading_basis: general_note, source_ref: "drawing p1, view B, zone B2; general note 1" }
+ - { type: through-bore, count: 1, dimension: "Ø0.500 in", tolerance: "+0.001/-0.000 in", tolerance_driver: true, surface_finish: null, reading_basis: printed_callout, source_ref: "drawing p1, view A, zone B3; KC-1" }
+ - { type: fillet, count: 4, dimension: "R0.250 in", tolerance: "±0.005 in", tolerance_driver: false, surface_finish: null, reading_basis: general_note, source_ref: "drawing p1, view A, zones A1-A4; general note 1" }
+ - { type: chamfer, count: 1, dimension: "0.010-0.020 in break, all edges", tolerance: "0.010-0.020 in", tolerance_driver: false, surface_finish: null, reading_basis: general_note, source_ref: "drawing p1, general note 2" }
+
+setups:
+ - { setup_seq: 1, faces: ["top", "bore", "perimeter"], fixture_note: "vise on sawn blank, datum A down", machine_class: VMC-3AX }
+ - { setup_seq: 2, faces: ["bottom"], fixture_note: "flip on soft jaws, face to thickness", machine_class: VMC-3AX }
+
+operations:
+ - { op_seq: 10, description: "Saw blank from 2.5 in bar", machine_class: SAW, setup_seq: null, features: [], outside_process: false, assumptions: ["0.90 in cut length"], source_ref: "stock" }
+ - { op_seq: 20, description: "Mill profile, fillets, bore, chamfers - setup 1", machine_class: VMC-3AX, setup_seq: 1, features: ["through-bore", "fillet", "chamfer"], outside_process: false, assumptions: ["bore reamed to hold KC-1"], source_ref: "features" }
+ - { op_seq: 30, description: "Face to thickness, chamfer bottom edges - setup 2", machine_class: VMC-3AX, setup_seq: 2, features: ["face", "chamfer"], outside_process: false, assumptions: [], source_ref: "features" }
+ - { op_seq: 40, description: "Deburr", machine_class: DEBURR, setup_seq: null, features: ["chamfer"], outside_process: false, assumptions: [], source_ref: "general note 2" }
+ - { op_seq: 50, description: "Black oxide", machine_class: OUTSIDE-FINISH, setup_seq: null, features: [], outside_process: true, assumptions: [], source_ref: "drawing p1, GENERAL, finish" }
+
+tolerances:
+ - { characteristic: "mounting bore diameter", value: "0.500 +0.001/-0.000 in", reading_basis: printed_callout, source_ref: "drawing p1, KC-1", key_characteristic: KC-1 }
+ - { characteristic: "true position, mounting bore", value: "0.002 in dia at MMC, A|B|C", reading_basis: printed_callout, source_ref: "drawing p1, KC-2", key_characteristic: KC-2 }
+ - { characteristic: "flatness, datum A", value: "0.001 in", reading_basis: printed_callout, source_ref: "drawing p1, KC-3", key_characteristic: KC-3 }
+ - { characteristic: "all unspecified dimensions", value: "±0.005 in", reading_basis: general_note, source_ref: "drawing p1, general note 1", key_characteristic: null }
+
+unreadables: []
+
+questions_for_estimator:
+ - "Datums B and C are referenced by KC-2 but their features are not identified. Assigned from the dimension scheme: B long side, C short end. Confirm."
+ - "KC-3 flatness 0.001 in on datum A: op 30 assumes it is held by facing on the VMC, no grind. Confirm against demonstrated capability."
+
+cost_down_proposals:
+ - { idea: "Rectangular bar 1.375 x 2.125 in instead of 2.5 in round", why: "Removes most of the profile roughing in op 20", what_it_would_change: "Material line and op 20 run time. Internal only — the drawing calls for MS-4140-BAR round" }
+
+approval:
+ status: draft
+ by: null
+ at: null
+ note: null
+```
+
+### What changes on the other paths
+
+Only the fields that differ from the example above.
+
+```yaml
+# Path B: a different prior part's model, adapted and saved as new
+geometry_path: B
+model:
+ origin: adapted_from_prior
+ base_model_ref: "fusion://Fairview/parts/PN-4402-A v7 (version read again after the run: v7)"
+ document_ref: "fusion://Fairview/estimates/EH-RFQ-0930_L1_PN-4402-C_R1"
+questions_for_estimator:
+ - "Adapted from PN-4402-A v7: flange_length 2.000 -> 2.394 in (drawing p1, view A, zone B2). Prior model untouched. Confirm."
+
+# Path A: text specs, no drawing. ROM only
+geometry_path: A
+drawing_revision_priced_to: null
+model: { origin: built_from_text }
+features:
+ - { type: through-bore, count: 1, dimension: "Ø0.500 in", tolerance: null, tolerance_driver: false, surface_finish: null, reading_basis: from_text, source_ref: "rfq email, para 3" }
+unreadables:
+ - { what: "bore tolerance", where: "rfq email, para 3", why: "no tolerance stated and no drawing; a firm price depends on it" }
+
+# Path C1: a STEP file read without CAD
+geometry_path: C1
+drawing_revision_priced_to: null
+model: { origin: customer_step, cad_backend: none, document_integrity: { result: not_applicable, detail: "STEP read as text without CAD (unverified)" } }
+```
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What `quote-build` does |
+|---|---|
+| No geometry estimate for a line with no current-revision routing | Degrades. The ladder starts at closed-job actuals if they exist, else first principles (rung 4), labelled. The internal sheet says the design step did not run and why |
+| `approval.status` is `draft` | **Blocks rung 3 for that line.** Hours derived from an unconfirmed model do not reach a quote unless the estimator says so in the run; then the internal sheet records who said so and that the model was unconfirmed |
+| `approval.status` is `declined` | Blocks rung 3 for that line. The ladder runs without it |
+| `document_integrity.result` is `foreign_geometry` | **Blocks.** The design step failed. No hours are derived from this model |
+| `document_integrity.result` is `not_checked` | Degrades. Hours may be derived after Gate 3, and the internal sheet says the integrity check did not run |
+| `drawing_revision_priced_to` differs from the intake form line's `revision` | **Blocks.** The estimate was built to another revision. Return to `rfq-to-quote` step 7 |
+| `geometry_path` is `A`, or `origin` is `built_from_text` | Degrades. **A ROM, never a firm quote**, labelled ROM on the internal sheet and called a budgetary estimate on the customer document, which says nothing about how it was estimated. A Gate 3 yes or an override does not make it firm |
+| `origin` is `customer_step` | Proceeds after Gate 3. The internal sheet says the STEP import, or the text read of it, is unverified |
+| `origin` is `adapted_from_prior` with `base_model_ref` null | **Blocks rung 3 for that line.** An adapted model that does not say what it was adapted from cannot be checked |
+| A `datums[].basis` is `inferred` and `approval.status` is `confirmed` | Proceeds. The estimator ruled on it at Gate 3 |
+| A feature has no `source_ref` | Blocks that feature. An unsourced feature is an inference |
+| `cost_down_proposals` is present | Internal sheet only. **Never inside the customer quote**, in any wording |
+| `model_checks` is null | Degrades. Say the model was not checked against a hand calculation |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/intake-form.md b/plugins/claude-for-manufacturing/shared/contracts/intake-form.md
new file mode 100644
index 00000000..64f0caa8
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/intake-form.md
@@ -0,0 +1,422 @@
+# Contract: the intake form
+
+**Emitted by** `customer-inquiry-intake`
+**Consumed by** `quote-build`
+**Chain** 1, RFQ to quote
+**Contract version** 7
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## What this has to survive
+
+An RFQ arrives in no standard format: a PDF drawing package with "can you do
+this?" in the email body, a spreadsheet of 40 line items and no drawings, a
+portal export with unfamiliar field order, a phone photo of a marked-up print, or
+a forwarded thread where the real requirement is in the fourth message down.
+
+The intake form is the single consistent shape all of that collapses into. Two
+properties matter most:
+
+**Every field carries where it came from** — which file, which page — so the
+estimator can verify without re-reading the package. Rule 6, and it is the
+difference between a useful extraction and one that has to be checked from
+scratch.
+
+**Missing and ambiguous are separate registers.** A field that was never stated
+is a different problem from one stated contradictorily in two places. The first
+needs a question to the customer; the second needs a decision. Collapsing them
+loses that.
+
+---
+
+## Header fields
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Which plant would build it, rule 7 |
+| `customer` | string | Required | |
+| `contact` | object or null | Degrades | Name, email, phone as given |
+| `rfq_reference` | string or null | Degrades | The customer's own reference |
+| `received_at` | timestamp with zone | Required | Rule 4. Drives quote turnaround, the metric this chain ships against |
+| `response_deadline` | date or null | Degrades | |
+| `supersedes_rfq` | string or null | Optional | Set when this revises an earlier RFQ. See below |
+| `source_documents` | list of objects | Required | Every file in the package: name, type, page count |
+| `field_sources` | object | Required | Field name to source_ref, rule 6 — covers every header and commercial-term field below, not just line items |
+
+## Commercial terms
+
+These are on the intake form. They are inquiry-level, not per line.
+A stated term that never lands here is how it disappears between intake and the
+quote. Sourced through the same inquiry-level `field_sources` object as the
+header fields above — never nested inside a line item's own `field_sources`,
+which is line-scoped.
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `payment` | string or null | Degrades | As stated. Null if never stated |
+| `freight` | string or null | Degrades | As stated |
+| `packaging` | string or null | Degrades | As stated |
+| `liability` | string or null | Degrades | As stated |
+
+A null term is not an empty string. Null goes in the missing register. A
+customer term that clashes with the plant's standard is flagged; it is not
+silently accepted.
+
+## Line items
+
+One row per part. **A multi-attachment RFQ is one inquiry with several line
+items, never several inquiries.**
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `line_no` | integer | Required | |
+| `part_number` / `part_number_verbatim` | string or null | Degrades | Rule 3. Often absent on a new part |
+| `description` | string | Required | |
+| `revision` | string or null | Degrades | |
+| `quantities` | list of objects | **Required** | A structure, not a scalar. See below |
+| `material` | string or null | Required | Null if never stated, and `quote-build` blocks that line. Quote the other lines and list this one as blocked |
+| `specs` | list of objects | Degrades | Each: characteristic, nominal, tolerance, `reading_basis`, source_ref. See below |
+| `finish` | string or null | Degrades | |
+| `certifications_required` | list of strings | Degrades | |
+| `required_delivery` | date or null | Degrades | Per line; lines can differ |
+| `eau` | number or null | Optional | Estimated annual usage, for a repeat part |
+| `geometry_inputs` | list of objects | Required, may be empty | Every file or statement the part's shape could be read from. Each: `name`, `type` (`drawing_pdf`, `drawing_image`, `drawing_text`, `step`, `other_3d`, `text_spec`, `prior_part_ref`), `revision` (string or null), `source_ref`. Empty means the package carries no geometry at all, and says so |
+| `geometry_path` | enum | Required | `C2`, `C1`, `B`, `A` or `none`, classified from `geometry_inputs`. See below |
+| `field_sources` | object | Required | Field name to source_ref, rule 6 |
+| `line_recommendation` | enum or null | Degrades | `bid` or `no_bid` for this line alone. Lines in one RFQ often deserve different answers. |
+| `line_bid_decision` | enum | Required | `draft`, `confirmed` or `declined`, for this line. Only an estimator moves it. `quote-build` quotes a line only when it is not `declined`. |
+
+### `geometry_path` — how the shape of the part reaches the estimate
+
+Classified per line from what the package actually holds, because it decides
+what `rfq-to-quote` can do at its design step. Classifying is reading the
+package; it never builds anything.
+
+| Value | When | At the design step |
+|---|---|---|
+| `C2` | A drawing — PDF, image, or text extract of one | Built from the drawing. The normal case |
+| `C1` | A STEP or other 3D file, and no drawing | Imported and read, nothing generated. STEP import is unverified |
+| `B` | A drawing, plus a **different** prior part whose CAD model is named as the starting point ("like PN-4402-A but 10 mm longer") | The prior model is opened, the changes applied, and the result saved as a new document; the prior model is never overwritten. Without it, `rfq-to-quote` runs the line as C2 and says so |
+| `A` | Written specifications only, no drawing | Built from the text, every dimension `from_text`. Any price on it is a ROM, never a firm quote |
+| `none` | No geometry at all — a repeat part named by number only | Not applicable. Priced from its routing, or a question to the customer |
+
+A line is classified by what the package holds, **never relabelled** to a path
+it is not.
+
+**A new revision of a part the plant has made before is `C2`, not `B`.** The
+drawing is the geometry. The earlier revision is history — its routing and its
+actuals are step 6's business, and a superseded routing is not a model to
+adapt. `B` is only for a package that names another part's model as the
+starting point. Intake cannot see the CAD vault, so where a prior model turns
+up later `rfq-to-quote` reclassifies at step 7 and says so.
+
+### `reading_basis` — how each tolerance was read
+
+Every `specs` entry says how its value got onto the form:
+
+| Value | Meaning |
+|---|---|
+| `printed_callout` | Printed against the feature on the drawing |
+| `general_note` | The drawing's general tolerance note, applied to this feature. **That is reading, not inferring**: the `source_ref` cites the note as well as the feature |
+| `from_text` | Stated in the RFQ text or a written spec, not on a drawing |
+| `unreadable_flagged` | Present but not legible. `nominal` and `tolerance` stay null and the line goes for human review |
+
+There is no value for a tolerance worked out from the feature type or from what
+is typical, because that is not permitted at all.
+
+### `quantities` is a structure
+
+A quantity given as a range or with price breaks has its
+structure captured and **is never averaged**. Setup cost amortizes across
+quantity, so quantity breaks are the whole reason unit price drops with volume —
+averaging them destroys the thing `quote-build` exists to compute.
+
+```yaml
+quantities:
+ - qty: 100
+ uom: each
+ - qty: 500
+ uom: each
+ - qty: 1000
+ uom: each
+```
+
+## The two registers
+
+### `missing_register` — never stated
+
+| Field | Type | Behavior |
+|---|---|---|
+| `line_no` | integer or null | Required |
+| `field` | string | Required |
+| `why_it_matters` | string | Required |
+| `should_have_come_from` | string | Required |
+
+### `ambiguous_register` — stated more than once, differently
+
+| Field | Type | Behavior |
+|---|---|---|
+| `line_no` | integer or null | Required |
+| `field` | string | Required |
+| `values_found` | list of objects | Required. Each value with its `source_ref` |
+| `why_it_matters` | string | Required |
+
+## Open questions and the recommendation
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `open_questions` | string | Degrades | Drafted as sendable email text, not a bullet list of field names |
+| `recommendation` | enum or null | Degrades | `bid`, `no_bid`, or (from version 7) `partial`: some lines bid, some not. The roll-up of the lines' `line_recommendation`. **Never a decision** |
+| `recommendation_reasoning` | list of strings | Required when `recommendation` is set | |
+| `constraint_violations` | list of objects | Required when `recommendation` is set | Each: constraint, requested value, plant capability, source, and `is_hard_disqualifier` |
+| `recommendation_provisional` | boolean | Required | True while any question is open. The recommendation still exists — it never waits |
+| `would_change_recommendation` | list of objects | Required when provisional | Each: the open question, the line it affects (or `all`), and what that line's recommendation becomes under which answer |
+| `questions_sent_at` / `questions_sent_by` | timestamp with zone / string, or null | Required once Gate 1 is passed | When, and by whom, the open questions went to the customer. **The stale clock starts here.** Set when the estimator says they sent them. |
+| `hard_disqualifier_stopped` | boolean | Required | True when the constraint check ended the sequence before questions were drafted |
+| `inquiry_state` | enum | Required | `open`, `stale`, or `superseded`. **Never `closed` or `declined` by this skill** |
+| `stale_since` | timestamp with zone or null | Required when `inquiry_state` is `stale` | Rule 4 |
+| `answers_received` | list of objects | Optional | Each answer with its date and `source_ref`, rule 6. Answers revise this inquiry; they never open a new one |
+| `bid_decision_state` | enum | Required | `draft`, `confirmed` or `declined`. Rule 8 — Chain 1 gates here before the handoff |
+| `bid_decision_by` | string or null | Required when state is not `draft` | Which estimator confirmed it |
+| `bid_decision_at` | timestamp with zone or null | Required when state is not `draft` | Rule 4 |
+| `bid_decision_basis` | object or null | Required when state is not `draft` | The recommendation the estimator ruled on, inquiry and per line, as it stood at `bid_decision_at`. |
+| `bid_decision_reset` | string or null | Degrades | Set when a confirmation lapsed because re-scoring changed the recommendation: what changed, and when. |
+| `paused_at_step` | integer or null | Required | The Chain 1 step the inquiry is waiting at, or null while it runs. |
+| `waiting_on` | string or null | Required when `paused_at_step` is set | Who or what: *"Example Valve: answers to questions 2 and 5"*, *"estimator: Gate 2"* |
+| `gates_passed` | list of objects | Required, may be empty | Each Chain 1 gate passed: `gate` (1 to 4), `by`, `at`. |
+
+The recommendation the skill produces is always `draft`. Only an estimator moves
+it to `confirmed` or `declined`. `quote-build` reads this state rather than
+inferring approval from context: a form still in `draft` is quoted only if the
+estimator says so in the run, and the quote records that it proceeded on an
+unconfirmed recommendation.
+
+### `inquiry_state` and `bid_decision_state` are different axes
+
+Confusing them is how a quiet customer silently becomes a no-bid.
+
+`inquiry_state` is **where the inquiry is in its own life** — open, gone stale
+waiting on the customer, or superseded by a revision. `bid_decision_state` is
+**whether a human has ruled on it.** A stale inquiry is still `open` for
+decision purposes and its `bid_decision_state` is still `draft`.
+
+**Nothing in this contract lets a timeout become a decline.** `inquiry_state`
+has no `closed` or `declined` value, and `customer-inquiry-intake` never writes
+`bid_decision_state: declined` — only an estimator does.
+
+**And a decision is never made stale.** An inquiry whose `bid_decision_state`
+is `declined` is skipped by every stale check: it has been ruled on, and
+surfacing it as *waiting on the customer* would put decided work back in the
+unbid book.
+
+### A confirmation covers what was shown
+
+`bid_decision_basis` records the recommendation the estimator ruled on. If
+answers arrive later and re-scoring changes it, for the inquiry or for any
+line, the confirmation no longer covers it: `bid_decision_state` (and the
+changed line's `line_bid_decision`) **returns to `draft`**, `bid_decision_reset`
+says what changed, and Gate 2 is asked again naming the change. A stale yes
+never quotes a line that has since flipped. A decline is not reset this way;
+reopening it is a new decision.
+
+### Where a paused inquiry lives between sessions
+
+Chain 1 waits days for a customer. The intake form itself is the state. It is
+saved on the private Open work page (`../replies.md`, *The open work*) as
+`inquiries/<customer-slug>-<rfq_reference>.intake.txt`, never in the workspace
+or the export folder, and one line per open inquiry goes in that page's
+`## Open inquiries` block, pipe-separated, in this order:
+
+```
+- EH-RFQ-0912 | Example Hydraulics | file: inquiries/example-hydraulics-EH-RFQ-0912.intake.txt | paused_at_step: 5 | waiting_on: customer answers to Q1-Q3 | stale_after: 2026-11-17 | bid_decision_state: draft
+```
+
+The saved form keeps `open_questions` word for word, numbered as sent, so a new
+session matches answers to questions without guessing. The line holds the
+reference, the customer, the file on the page, `paused_at_step`,
+`waiting_on`, `stale_after` (ISO date) and `bid_decision_state`, so a stale
+check never resurfaces a declined inquiry. To resume, a new session brings in
+the page, reads the line for that reference, opens the form from the page's
+copy and continues at `paused_at_step`, rather than starting the inquiry
+again. On quote, decline or withdrawal the line moves to `## Closed` with the
+date.
+
+### The recommendation exists even when incomplete
+
+`recommendation` is never withheld because questions are open. It is scored on
+what is known and marked `recommendation_provisional: true`, with
+`would_change_recommendation` naming the specific answers that would move it.
+A null recommendation means the skill could not score at all, not that it is
+waiting.
+
+When there is no capability profile, the recommendation is constraint-free and
+**says so** in `recommendation_reasoning`. When there is no cost history, it
+scores on capability and dates alone and **says so** there. Those two caveats
+are prose on the recommendation, not flags.
+
+## Drawings are never inferred from
+
+Where a drawing is an image with no dimensions in text, extract what is visible
+and mark the line for human review. **Never infer a tolerance from a drawing.** A
+`specs` entry with no `source_ref` is not permitted, and neither is one with no
+`reading_basis`.
+
+**Two drawing facts go on the missing register when they are absent or in
+doubt.** A drawing with no revision: the quote has to say which revision it is
+priced to, and nobody can. And a change the customer mentions as pending — "engineering
+may open up the bore in the next rev": recorded as a risk to the revision being
+quoted, with the customer's words as its source, because a quote priced to a
+revision about to be replaced is priced to the wrong part.
+
+## Revisions of an earlier RFQ
+
+`supersedes_rfq` links rather than duplicating. A revised RFQ that creates a
+second inquiry is how a plant ends up quoting the same job twice against
+different requirements.
+
+---
+
+
+## Worked example
+
+One line, quotable, with a real constraint violation:
+
+```yaml
+contract_version: 7
+site: Fairview
+customer: "Example Aerospace"
+contact: { name: "Dale Corwin", email: "dcorwin@example-aerospace.example" }
+rfq_reference: "EA-RFQ-2291"
+received_at: 2026-09-08T08:14:00-04:00
+response_deadline: 2026-09-15
+supersedes_rfq: null
+payment: "Net 30"
+freight: "FOB Fairview"
+packaging: null
+liability: "Customer's standard flow-down, including consequential damages"
+source_documents:
+ - { name: "EA-RFQ-2291.pdf", type: pdf, pages: 1 }
+ - { name: "4471-B-drawing.pdf", type: pdf, pages: 3 }
+field_sources:
+ customer: "EA-RFQ-2291.pdf:p1"
+ contact: "EA-RFQ-2291.pdf:p1"
+ rfq_reference: "EA-RFQ-2291.pdf:p1"
+ received_at: "EA-RFQ-2291.pdf:p1"
+ response_deadline: "EA-RFQ-2291.pdf:p1"
+ payment: "EA-RFQ-2291.pdf:p1"
+ freight: "EA-RFQ-2291.pdf:p1"
+ liability: "EA-RFQ-2291.pdf:p1"
+
+line_items:
+ - line_no: 1
+ part_number: PN-4471-B
+ part_number_verbatim: "4471-B"
+ description: "Upper bracket, machined aluminium"
+ revision: "B"
+ quantities:
+ - { qty: 250, uom: each }
+ - { qty: 1000, uom: each }
+ material: "6061-T6 aluminium"
+ specs:
+ - { characteristic: "true position, 4x mounting holes", nominal: "0.0005 in", tolerance: "max", reading_basis: printed_callout, source_ref: "4471-B-drawing.pdf:p2, view A, zone C4" }
+ - { characteristic: "flange thickness", nominal: "0.250 in", tolerance: "±0.005 in", reading_basis: general_note, source_ref: "4471-B-drawing.pdf:p2, view B, zone B2; general note 1" }
+ geometry_inputs:
+ - { name: "4471-B-drawing.pdf", type: drawing_pdf, revision: "B", source_ref: "4471-B-drawing.pdf:p1, title block" }
+ geometry_path: C2
+ finish: "clear anodize"
+ certifications_required: ["AS9100", "material cert"]
+ required_delivery: 2026-11-03
+ eau: 4000
+ line_recommendation: bid
+ line_bid_decision: draft
+ field_sources:
+ material: "4471-B-drawing.pdf:p1"
+ quantities: "EA-RFQ-2291.pdf:p1"
+ required_delivery: "EA-RFQ-2291.pdf:p1"
+
+missing_register:
+ - line_no: 1
+ field: packaging
+ why_it_matters: "Anodized parts ship with interleaving; unpriced if unstated."
+ should_have_come_from: "customer terms page"
+
+ambiguous_register:
+ - line_no: 1
+ field: required_delivery
+ values_found:
+ - { value: "2026-11-03", source_ref: "EA-RFQ-2291.pdf:p1" }
+ - { value: "week of Nov 10", source_ref: "EA-RFQ-2291.pdf:p2" }
+ why_it_matters: "A week's difference decides whether current shop load can absorb it."
+
+open_questions: |
+ Dale — two things before we can firm this up.
+ 1. The RFQ lists 3 November on page 1 and the week of 10 November on page 2.
+ Which is the commitment?
+ 2. Is there a packaging spec for the anodized parts, or should we quote our
+ standard interleaved cartons?
+
+recommendation: bid
+recommendation_provisional: true
+would_change_recommendation:
+ - question: "Is the material 4130 or 4140?"
+ line: 1
+ becomes: "no_bid if 4140 — that tolerance has never been held in 4140 on this process"
+hard_disqualifier_stopped: false
+inquiry_state: open
+stale_since: null
+answers_received: []
+bid_decision_state: draft
+bid_decision_by: null
+bid_decision_at: null
+bid_decision_basis: null
+bid_decision_reset: null
+questions_sent_at: null
+questions_sent_by: null
+paused_at_step: 4
+waiting_on: "estimator: Gate 1, send the open questions"
+gates_passed: []
+recommendation_reasoning:
+ - "Material, process and size envelope are all within demonstrated capability."
+ - "One tolerance is below demonstrated capability on this process; see constraint_violations."
+ - "Comparable closed work order WO-71160 on PN-4402-A returned 22% gross margin at similar volume."
+constraint_violations:
+ - constraint: "true position on 3-axis milling"
+ requested: "0.0005 in"
+ plant_capability: "0.002 in demonstrated"
+ source: "## Plant context, site Fairview capability"
+```
+
+The manufacturability check runs **before** the recommendation, deliberately, so
+a job that cannot be built as specified is caught at intake rather than after
+someone has priced it. That ordering is the point, and the contract preserves it
+by carrying `constraint_violations` alongside the recommendation it informed.
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What `quote-build` does |
+|---|---|
+| A line has no quantity, or `material` is null | **Blocks that line.** Quote the others, list what is blocked and why |
+| `quantities` has one entry where breaks were requested | Degrades. Quote what is there and state that breaks were not captured |
+| `specs` entry has no `source_ref` | Blocks that spec. An unsourced tolerance is an inference, not a requirement |
+| `ambiguous_register` has an entry on a field the quote depends on | Degrades. Quote against one value, name which, and state the other explicitly |
+| `recommendation` is `no_bid` | Degrades. It is a recommendation, not a decision. Proceed if the estimator says to |
+| `bid_decision_state` is `draft` | Degrades. Chain 1's **second** gate (the estimator confirming bid/no-bid at step 5) has not been passed. Chain 1 has four: Gate 1, sending the open questions at step 4; Gate 2, bid/no-bid at step 5; Gate 3, confirming the design, tolerance reading and operation list at step 8; Gate 4, releasing the quote at step 11. Quote only if the estimator says to in the run, and record on the quote that it proceeded on an unconfirmed recommendation |
+| `bid_decision_state` is `declined` | **Blocks.** The estimator has declined this inquiry. Reopening it is a new decision, not a quote |
+| A line's `line_bid_decision` is `declined` | **Blocks that line.** Quote the others, and list the declined line as not quoted, by the estimator's decision |
+| `recommendation` is `partial` | Degrades. Read `line_recommendation` per line; quote the lines whose decision is not `declined` |
+| `bid_decision_reset` is set | Degrades. The earlier confirmation lapsed. Treat the form as `draft` and name what changed |
+| `recommendation_provisional` is true | Degrades. Quote if the estimator says to, and record on the quote which answers were still outstanding — they are the assumptions the price rests on |
+| `hard_disqualifier_stopped` is true | Degrades. The plant cannot build this as specified. Quote only on an explicit override, and carry the disqualifying constraint onto the exclusions list |
+| `inquiry_state` is `stale` | Degrades. Quote with exclusions naming the unanswered questions, or do not quote. **Never read stale as declined** |
+| `inquiry_state` is `superseded` | **Blocks.** A later revision of this inquiry exists. Quote that one |
+| `field_sources` absent | Blocks. Without provenance the estimator cannot verify anything |
+| `geometry_path` is absent (a version 5 form) | Degrades. `rfq-to-quote` classifies the line itself from `source_documents` before the design step, and says it did |
+| `geometry_path` is `A` | Degrades. No design step runs. Any price on the line is a ROM, never a firm quote, and the customer quote says so |
+| A `specs` entry has no `reading_basis` | Degrades. Treat the tolerance as unverified and list it for the estimator at Gate 3 |
+| `revision` is null on a line with a drawing | Degrades. Quote only with the revision named as unknown in the assumptions, and the missing-register row kept |
+| A commercial term is null | Degrades. Quote against the plant's standard for that term, name the assumption on the exclusions list, and keep the missing-register row |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/ncr.md b/plugins/claude-for-manufacturing/shared/contracts/ncr.md
new file mode 100644
index 00000000..e1228c65
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/ncr.md
@@ -0,0 +1,281 @@
+# Contract: the NCR
+
+**Emitted by** `ncr-writeup`
+**Consumed by** `root-cause-capa`
+**Chains** 2 (inspection to CAPA) and 5 (supplier escape to alternate source)
+**Contract version** 4
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## The four questions an NCR must answer
+
+A nonconformance report is the formal record that something did not meet its
+requirement, and it exists to answer four things:
+
+1. **What was found** — the observed condition, measured where possible.
+ "Hole diameter 0.512 in," not "hole too big."
+2. **Against which requirement** — the specific dimension, spec, standard clause
+ or customer requirement violated. **An NCR without a cited requirement is not
+ an NCR.**
+3. **How many parts** — rarely just the one somebody found. If the cause could
+ have affected the whole run, the whole run is suspect until proven otherwise.
+4. **Where they physically are** — containment. Five different places, five
+ different actions, five different urgencies.
+
+The contract enforces the second one structurally: `root-cause-capa` blocks when
+the cited requirement is missing, with a pointer back to `ncr-writeup`.
+
+---
+
+## Identification
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `ncr_ref` | string | Required | |
+| `site` | string | Required | Rule 7 |
+| `part_number` / `part_number_verbatim` | string | Required | Rule 3 |
+| `part_revision` | string or null | Degrades | Which revision the part was found against |
+| `production_wo` / `production_wo_verbatim` | string or null | Degrades | Rule 3. Never named `work_order` — a maintenance work order is a different record |
+| `lot_number` / `lot_number_verbatim` | string or null | Degrades | Drives traceability scope |
+| `operation` | string or null | Degrades | Which routing step it was found at |
+| `found_by` | string | Required | |
+| `found_at` | timestamp with zone | Required | Rule 4 |
+| `disposition_pending` | boolean | Required | True until a disposition is decided elsewhere |
+
+## The finding
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `condition_found` | string | Required | The observed condition |
+| `measurements` | list of objects | Degrades | Each: characteristic, measured, nominal, tolerance, uom, gage, source_ref |
+| `is_subjective` | boolean | Required | See below |
+| `qty_found` | number or null | Required | Paired with `uom`, rule 5. **Null when the source does not record how many were found**, never a number filled in |
+| `qty_found_reason` | string or null | Required when `qty_found` is null | What the source holds instead: *"NCR-2026-0141 records no count; its only figure is one measurement in free text"*. |
+| `uom` | string | Required | |
+
+## The requirement — the field that gates the chain
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `requirement_cited` | object or null | **Required to proceed** | Null only with the flag below |
+| `requirement_not_locatable` | boolean | Required | True when the requirement could not be found |
+
+`requirement_cited` carries:
+
+```yaml
+requirement_cited:
+ source: "customer drawing"
+ document: "4471-B-drawing.pdf"
+ locator: "p2, datum B, 4x mounting holes"
+ characteristic: "true position"
+ stated_value: "0.002 in max"
+```
+
+**Never invent a requirement.** When it genuinely cannot be located, set
+`requirement_not_locatable: true`, leave `requirement_cited` null, and flag the
+NCR as blocking. That is a complete and honest outcome; an asserted requirement
+is not.
+
+## Affected quantity — with its reasoning
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `qty_suspect` | number | Required | The scope, not just what was found |
+| `qty_suspect_is_minimum` | boolean | Required | True when `qty_suspect` is a floor and the honest scope has no known upper bound: traceability is incomplete and more work orders, lots or shipments may be involved. |
+| `scope_basis` | enum | Required | `single_part`, `lot`, `production_run`, `production_window`, `widened_incomplete_traceability` |
+| `scope_reasoning` | string | **Required** | Why this scope and not a narrower one |
+| `traceability_complete` | boolean | Required | See below |
+
+**The reasoning is shown, never just the number.** Whether a cause is a one-off
+or run-wide is an explicit judgment with a stated assumption, and the consumer
+needs it because a run-wide cause and a single-part cause point at different
+root causes.
+
+**Where traceability is incomplete, scope widens and says why it widened.**
+Narrowing scope to make the number look better is the failure mode this field
+exists to prevent. **And where the widened number is still only what can be
+counted**, `qty_suspect_is_minimum` is true and every place the number is
+printed says *at least*: "at least 660 (3 work orders x 220 ordered); other
+work orders on heat H-4140-2291 not yet ruled out".
+
+## Containment — all five locations
+
+`containment` is a list, one entry per location, ordered by urgency. **All five
+location types are addressed**, including with a zero quantity, because an
+omitted location reads as "no parts there" rather than "not checked."
+
+| Field | Type | Behavior |
+|---|---|---|
+| `location` | enum | Required. `wip_at_machine`, `finished_goods`, `in_transit`, `at_customer`, `installed_at_customer` |
+| `qty` | number | Required |
+| `uom` | string | Required |
+| `checked` | boolean | Required. False means not verified, which is different from zero |
+| `action` | string | Required |
+| `urgency` | enum | Required. `immediate`, `same_day`, `routine` |
+| `owner` | string or null | Required field, null value. Left blank for assignment |
+| `customer` | string or null | Required for customer locations. One entry per customer |
+| `source_ref` | string | Required. Rule 6 |
+
+## Recurrence — searched at creation
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `recurrence` | enum | Required | `first_occurrence`, `recurrence_prior_capa_held`, `recurrence_prior_capa_failed`, `no_searchable_history` |
+| `prior_ncrs_found` | integer | Required | Prior NCRs the search found on the same part, defect, process or supplier, whatever `recurrence` says. |
+| `related_records` | list of objects | Degrades | Each: ref, date, what matched, whether the fix held |
+| `history_searched` | boolean | Required | |
+
+The search runs **when the NCR is written, not on request**, because the moment
+of detection is the only moment anyone is looking.
+
+**`recurrence` judges whether a fix held; `prior_ncrs_found` says whether it
+happened before.** Prior NCRs with no CAPA records to judge are
+`no_searchable_history` with `prior_ncrs_found` above zero, and the NCR says
+both: "4 prior NCRs on this part; no CAPA records, so whether a fix held
+cannot be judged." An NCR whose part label failed the dataset's NCR-to-work
+order check is not counted here.
+
+`no_searchable_history` is a distinct value from `first_occurrence` on purpose.
+Per `../absent-is-not-zero.md`, silence reads as "no recurrence," which is a much
+stronger claim than the evidence supports.
+
+## Escape
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `escape_occurred` | boolean | Required | True when containment places parts at or past a customer |
+| `escape_possible` | boolean | Required | True when `escape_occurred` is false only because a customer location is `checked: false`, and the evidence makes shipment plausible: orders for the suspect parts promised before today, a shipped or partly fulfilled status, a customer named on the NCR. |
+| `verify_shipment_action` | string or null | Required when `escape_possible` | The named check that settles it: *"Confirm in NetSuite or with shipping whether any of WO-88412/413/414 shipped on Example Hydraulics's 7 and 19 Sep orders"* |
+| `escape_detected_at` | timestamp with zone or null | Required when `escape_occurred` | Rule 4. When containment **first placed parts at or past a customer** — not `found_at`, which is when the defect was found. Opens Chain 5's escape-to-RFQ window |
+| `notification_drafted` | boolean | Required when `escape_occurred` or `escape_possible` | When only possible, the draft is conditional: it says it goes only if the shipment check finds parts shipped |
+| `notification_deadline` | timestamp with zone or null | Degrades | The contractual clock, often 24–48 hours |
+| `affected_customers` | list of strings | Required when `escape_occurred` | |
+
+The draft is chained straight off containment so nobody has to remember to do it
+separately, under time pressure, against a contractual window. **Missing that
+window is a bigger problem than the defect.**
+
+**Unchecked is not "no escape".** When nobody has verified the customer
+locations and the parts were plausibly shipped, `escape_occurred` stays false
+(nothing places parts at a customer yet), `escape_possible` is true,
+`escape_detected_at` stays null, and the NCR carries a conditional notification
+draft and the named shipment check. Silence on a plausible escape is how a
+contractual clock runs out unnoticed.
+
+## Approval — rule 8
+
+| Field | Type | Behavior |
+|---|---|---|
+| `approval_state` | enum | Required. `draft`, `approved`, `rejected` |
+| `approved_by` | string or null | Required to proceed down the chain |
+| `approved_at` | timestamp with zone or null | Required to proceed |
+
+---
+
+## Two fields worth explaining
+
+**`is_subjective` keeps an opinion labelled.** A finding like "surface looks
+wrong" is captured as observed and flagged, because no measurable requirement was
+cited. `root-cause-capa` cannot run a computed pattern check against a subjective
+finding, and it needs to know that before trying.
+
+**`checked: false` is not `qty: 0`.** A location nobody has walked yet is the most
+dangerous kind of containment entry, and it must not read as clear.
+
+---
+
+## Worked example
+
+Abbreviated — one measurement, containment across all five locations, a
+recurrence:
+
+```yaml
+contract_version: 4
+ncr_ref: NCR-2026-0418
+site: Fairview
+part_number: PN-4471-B
+part_number_verbatim: "4471-B Rev 2"
+part_revision: "B"
+production_wo: WO-88201
+production_wo_verbatim: "88201"
+lot_number: LOT-77219
+lot_number_verbatim: "77219"
+operation: "OP30 mill"
+found_by: "T. Alvarez, Inspection"
+found_at: 2026-09-07T13:40:00-04:00
+disposition_pending: true
+
+condition_found: "True position on 4x mounting holes measured 0.0041 in against a 0.002 in maximum."
+measurements:
+ - { characteristic: "true position", measured: "0.0041", nominal: "0", tolerance: "0.002 max", uom: in, gage: "CMM-01", source_ref: "inspection-20260907.xlsx:r88" }
+is_subjective: false
+qty_found: 3
+qty_found_reason: null
+uom: each
+
+requirement_cited:
+ source: "customer drawing"
+ document: "4471-B-drawing.pdf"
+ locator: "p2, datum B, 4x mounting holes"
+ characteristic: "true position"
+ stated_value: "0.002 in max"
+requirement_not_locatable: false
+
+qty_suspect: 480
+qty_suspect_is_minimum: false
+scope_basis: lot
+scope_reasoning: "All 480 parts on WO-88201 were machined from LOT-77219 on one setup with no intervening tool change, so the whole lot is suspect until sampled. The 3 found were a first-article recheck, not a full inspection."
+traceability_complete: true
+
+containment:
+ - { location: at_customer, qty: 120, uom: each, checked: true, action: "Notify Example Aerospace; request quarantine of PO-4471 receipt.", urgency: immediate, owner: null, customer: "Example Aerospace", source_ref: "netsuite:shipment/SH-30211" }
+ - { location: in_transit, qty: 60, uom: each, checked: true, action: "Intercept shipment SH-30244 at carrier.", urgency: immediate, owner: null, customer: "Example Aerospace", source_ref: "netsuite:shipment/SH-30244" }
+ - { location: wip_at_machine, qty: 60, uom: each, checked: true, action: "Stop OP40; hold at cell B.", urgency: immediate, owner: null, customer: null, source_ref: "prod-output-20260907.csv:r412" }
+ - { location: installed_at_customer, qty: 0, uom: each, checked: false, action: "Ask Example Aerospace whether any of the 120 have been installed.", urgency: immediate, owner: null, customer: "Example Aerospace", source_ref: "not verifiable from our records" }
+ - { location: finished_goods, qty: 240, uom: each, checked: true, action: "Move to quarantine cage, tag NCR-2026-0418.", urgency: same_day, owner: null, customer: null, source_ref: "netsuite:inventory/FG-A12" }
+
+recurrence: recurrence_prior_capa_failed
+related_records:
+ - { ref: NCR-2025-0912, date: 2025-11-04, what_matched: "same characteristic, same operation, same cell", fix_held: false }
+prior_ncrs_found: 1
+history_searched: true
+
+escape_occurred: true
+escape_possible: false
+verify_shipment_action: null
+escape_detected_at: 2026-09-07T16:20:00-04:00
+notification_drafted: true
+notification_deadline: 2026-09-09T13:40:00-04:00
+affected_customers: ["Example Aerospace"]
+
+approval_state: approved
+approved_by: "Priya Raman, Quality Manager"
+approved_at: 2026-09-07T16:05:00-04:00
+```
+
+Note the last containment entry: `qty: 0` with `checked: false`. Nobody knows
+whether parts are installed, and the entry says so rather than being omitted.
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What `root-cause-capa` does |
+|---|---|
+| `requirement_cited` null and `requirement_not_locatable` true | **Blocks**, with a pointer back to `ncr-writeup`. Nonconformance is always against a requirement |
+| `requirement_cited` null and the flag is false | Blocks. The producer did not follow its own rule |
+| `approval_state` is not `approved` | Blocks for anything customer-facing; investigation may proceed as draft |
+| `is_subjective` is true | Degrades. Skip computed pattern checks that need a measured characteristic and say why |
+| `measurements` empty | Degrades. Reason from the condition as described; no SPC drift check is possible |
+| `lot_number` absent | Degrades. Lot-clustering analysis cannot run, so a supplier-caused determination cannot be reached on lot evidence |
+| `recurrence` is `no_searchable_history` | Degrades. State that history could not be searched. **Never read as a first occurrence** |
+| `traceability_complete` is false | Degrades. Carry the widened scope forward with its reasoning; never re-narrow it |
+| `qty_suspect_is_minimum` is true | Degrades. Print the scope as *at least* N everywhere it appears, the 8D and the customer pack included |
+| `qty_found` is null | Degrades. Use `qty_found_reason`; never fill in a count |
+| `escape_possible` is true | Degrades. Carry the conditional notification and the shipment check forward; no customer-facing pack treats the escape as ruled out |
+| `prior_ncrs_found` above zero with `no_searchable_history` | Degrades. Say prior NCRs exist and that whether a fix held cannot be judged |
+| A version 3 record lacks the version 4 fields | Degrades. Read `qty_suspect` as possibly a minimum and the escape as not ruled out, and say the record predates those fields |
+| A containment entry has `checked: false` | Degrades. Carry it forward as unverified. Never treat as zero |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/pulse-day-record.md b/plugins/claude-for-manufacturing/shared/contracts/pulse-day-record.md
new file mode 100644
index 00000000..c72510e9
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/pulse-day-record.md
@@ -0,0 +1,185 @@
+# Contract: the pulse day record
+
+**Emitted by** `morning-plant-pulse`, step 3
+**Consumed by** the Operations Command Center dashboard's trend panel and week-over-week movers, read back by the next pulse run
+**Chains** 3 (morning plant pulse)
+**Contract version** 1
+
+Rules that govern every contract are in [README.md](README.md). How records
+are stored, keyed and read is `../live-dashboard.md`.
+
+---
+
+## Why it exists
+
+The pulse used to compare against "the prior report," a page it had no way to
+read back. A scheduled run starts in a fresh session and remembers nothing.
+The day record is that history, stored in the dashboard's own database: one
+row per site per production day, written by the run that computed it, and
+read by every later run to draw the trend.
+
+**The producer writes every field at emit time**, from the report it has just
+computed. Nothing on this record is added later by a reader.
+
+---
+
+## Identification
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `record_key` | string | Required | `<site>_<YYYY-MM-DD>`, e.g. `Fairview_2026-08-31`. The `ArtifactData` document key in `pulse_days`. A re-run for the same day overwrites it |
+| `site` | string | Required | Rule 7 |
+| `production_day` | date | Required | The production day under the site's day-boundary rule from `## Plant context`, not the calendar day the run happened |
+| `day_boundary` | string | Required | The convention used, e.g. "day starts 07:00; third shift belongs to the day it started" |
+| `run_timestamp` | timestamp with zone | Required | Rule 4. When this record was computed |
+| `data_as_of` | timestamp with zone or null | Required | The newest source refresh the figures rest on. Null only when no source could be read |
+
+## Completeness
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `data_complete` | boolean | Required | True only when the planning, production output and downtime exports each cover the whole production day |
+| `gaps` | list of strings | Required | Each missing, stale or partial input, named. Empty list only when `data_complete` is true |
+| `backfilled` | boolean | Required | True when written by the first run's back-fill rather than the run for that day |
+
+**A day with `data_complete: false` is a gap in the trend, never a zero.** A
+reader that plots it as a low day has turned "we could not see it" into "it
+was bad," which is the failure `../absent-is-not-zero.md` exists to stop.
+
+## Output against plan
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `planned_qty` | object, unit → number, or null | Degrades | Rule 5. e.g. `{each: 2030, box12: 520}`. Never summed across units. Null when the planning export is missing |
+| `actual_qty` | object, unit → number, or null | Degrades | Good output, same shape. Null when the production export is missing |
+| `output_provisional` | boolean | Required | True when any match behind these totals rests on a normalization nobody has approved |
+
+## OEE
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `oee` | number 0–1 or null | Degrades | Site-level for the day |
+| `availability` | number or null | Degrades | May exceed 1 on unscheduled overtime. Never clamped |
+| `performance` | number or null | Degrades | |
+| `quality` | number 0–1 or null | Degrades | |
+| `quality_convention` | string | Required | "good ÷ (good + scrap)" or first-pass yield, as the report stated it |
+| `oee_basis` | string | Required | How the site figure was rolled up, and which assets were excluded and why |
+
+**Null is not 0, and a missing component is never 1.0.** A component that
+could not be computed is null, and so is `oee`. Per
+`../../skills/daily-production-report/reference/oee.md`.
+
+## Downtime
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `downtime_by_reason` | list of objects or null | Degrades | Each: `reason_code`, `minutes` (number or null), `events` (integer). Null when the downtime export is missing. Ranked records only |
+| `downtime_minutes_total` | number or null | Degrades | Ranked records only. Null when the export is missing |
+| `open_outages` | integer | Required | Outages still open at the day's end. Their minutes are null, not 0, and are outside the total |
+| `uncoded_share` | object or null | Degrades | `{events, minutes, of_events, of_minutes}` coded `Other` or blank |
+| `blocked_safety_unknown` | integer | Required | Diagnosis records held out for a missing `safety_flagged`. Outside every ranking, total and price |
+
+## Losses
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `loss_usd` | object | Required | `{scrap, downtime, currency}`. `downtime` is null when unpriced; `scrap` is null when no standard cost was available |
+| `rate_source` | enum | Required | `env_variable`, `profile_confirmed`, `profile_placeholder`, `unset`. Never the rate value itself |
+| `unpriced` | list of strings | Required | Each quantity left unpriced and why, e.g. "PN-4402-A scrap, unit conflict each / box12" |
+
+## Exceptions
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `exceptions` | list of objects | Required | Each: `ref`, `kind`, `commitment_impact`. Class 6 records are never here, unless they carry `contradicted_by` in the dataset: then `kind` is `one_sided_contradicted` |
+| `data_problems_count` | integer | Required | The numbered data-problems table's count: classes 1–5 and 8 |
+
+---
+
+## Worked example
+
+A complete day, then a day whose downtime export did not land.
+
+```yaml
+contract_version: 1
+record_key: Fairview_2026-08-30
+site: Fairview
+production_day: 2026-08-30
+day_boundary: "day starts 07:00; third shift (23:00) belongs to the day it started"
+run_timestamp: 2026-08-31T04:12:00-04:00
+data_as_of: 2026-08-31T03:55:00-04:00
+data_complete: true
+gaps: []
+backfilled: true
+planned_qty: { each: 1530, box12: 520 }
+actual_qty: { each: 1502, box12: 509 }
+output_provisional: true
+oee: 0.712
+availability: 0.874
+performance: 0.833
+quality: 0.978
+quality_convention: "good ÷ (good + scrap); no rework column"
+oee_basis: "time-weighted across 5 assets; DOOSAN-PUMA-03 excluded, no output recorded"
+downtime_by_reason:
+ - { reason_code: MECH-01, minutes: 51, events: 1 }
+ - { reason_code: MECH-03, minutes: 44, events: 1 }
+downtime_minutes_total: 95
+open_outages: 0
+uncoded_share: { events: 0, minutes: 0, of_events: 2, of_minutes: 95 }
+blocked_safety_unknown: 0
+loss_usd: { scrap: 412.50, downtime: 1187.50, currency: USD }
+rate_source: profile_placeholder
+unpriced: ["PN-4402-A scrap, unit conflict each / box12"]
+exceptions:
+ - { ref: WO-88412, kind: late_job, commitment_impact: "Example Hydraulics PO ships 2 days late" }
+data_problems_count: 6
+---
+contract_version: 1
+record_key: Fairview_2026-08-31
+site: Fairview
+production_day: 2026-08-31
+day_boundary: "day starts 07:00; third shift (23:00) belongs to the day it started"
+run_timestamp: 2026-09-01T04:10:00-04:00
+data_as_of: 2026-09-01T03:52:00-04:00
+data_complete: false
+gaps: ["downtime export did not land; availability, OEE and downtime not computed"]
+backfilled: false
+planned_qty: { each: 1530, box12: 520 }
+actual_qty: { each: 1488, box12: 511 }
+output_provisional: true
+oee: null
+availability: null
+performance: null
+quality: 0.981
+quality_convention: "good ÷ (good + scrap); no rework column"
+oee_basis: "not computed: no downtime export, so no availability"
+downtime_by_reason: null
+downtime_minutes_total: null
+open_outages: 0
+uncoded_share: null
+blocked_safety_unknown: 0
+loss_usd: { scrap: 380.00, downtime: null, currency: USD }
+rate_source: profile_placeholder
+unpriced: ["all downtime: no downtime export", "PN-4402-A scrap, unit conflict each / box12"]
+exceptions: []
+data_problems_count: 6
+```
+
+Note the second record: `downtime_minutes_total: null`, not `0`, and
+`oee: null`. The trend shows a gap on 31 August for OEE and downtime, and a
+point for quality, which could still be computed.
+
+---
+
+## Missing behavior
+
+| Situation | What the reader does |
+|---|---|
+| `data_complete` is false | Plot a gap for every null metric on that day. Plot non-null metrics, marked partial. Leave the day out of week-over-week averages and say how many days each average rests on |
+| A metric is null | A gap in the chart and a blank in the table, labelled *not computed* with the reason from `gaps`. Never 0, never 1.0 |
+| No record for a day in the window | A gap labelled *no run for this day*. Different from a record with `data_complete: false` |
+| `planned_qty` or `actual_qty` carries two units | Two series, or one per unit. Never summed |
+| `output_provisional` is true | The output point carries the provisional mark, as the day's report did |
+| `contract_version` is older | Read the fields it knows; treat the rest as absent, per the README |
+| A second record with the same `record_key` | Cannot happen: the write is a `set` by key. If a reader ever sees two, it reports both and uses neither |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/quality-register-record.md b/plugins/claude-for-manufacturing/shared/contracts/quality-register-record.md
new file mode 100644
index 00000000..3a8f929a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/quality-register-record.md
@@ -0,0 +1,155 @@
+# Contract: the quality register record
+
+**Emitted by** `ncr-writeup` (creates and updates the row, and closes it on the user's word) and `root-cause-capa` (adds the investigation fields)
+**Consumed by** the Quality Register dashboard, rebuilt from every row on each run that writes one
+**Chains** 2 (inspection to CAPA) and 5 (supplier escape to alternate source)
+**Contract version** 1
+
+Rules that govern every contract are in [README.md](README.md). How records
+are stored, keyed and read is `../live-dashboard.md`.
+
+---
+
+## Why it exists, and why it is not the NCR
+
+A single run knows the one NCR in front of it. A register of open corrective
+actions needs every other one, so each NCR and 8D run leaves a row behind in
+the register's own database. The page is rebuilt from all of them.
+
+**This is a separate contract so [ncr.md](ncr.md) stays stable.** The NCR is
+the handoff between two skills; this is the register's row. It copies the few
+NCR fields the register shows and adds the fields only a register needs.
+
+**Each field is written by the skill that knows it at that moment.** The NCR
+fields and the status are known when `ncr-writeup` writes the NCR. The
+investigation fields are known when `root-cause-capa` drafts the 8D. A skill
+never writes a field it does not know yet: it leaves it null, and the page
+says *not yet*.
+
+**References, never documents.** The row carries the NCR reference and a one-
+line summary, never the NCR, the 8D or anything from a redacted customer pack.
+It does carry customer names and notification deadlines, which is why the
+register is internal (see `../secret-config.md`).
+
+---
+
+## Identification — from the NCR
+
+| Field | Type | Producer | Behavior | Notes |
+|---|---|---|---|---|
+| `contract_version` | integer | both | Required | |
+| `record_key` | string | `ncr-writeup` | Required | `<site>_<ncr_ref>`, e.g. `Fairview_NCR-2026-0141`. The `ArtifactData` document key in `ncrs`. A second run on the same NCR overwrites it |
+| `ncr_ref` | string | `ncr-writeup` | Required | |
+| `site` | string | `ncr-writeup` | Required | Rule 7 |
+| `part_number` / `part_number_verbatim` | string | `ncr-writeup` | Required | Rule 3 |
+| `lot_number` / `lot_number_verbatim` | string or null | `ncr-writeup` | Degrades | |
+| `found_at` | timestamp with zone | `ncr-writeup` | Required | Rule 4 |
+| `qty_found` / `uom` | number / string | `ncr-writeup` | Required | Rule 5 |
+| `requirement_cited` | string or null | `ncr-writeup` | Degrades | One line: document and locator. Null with `status: blocked` when not locatable |
+| `disposition_pending` | boolean | `ncr-writeup` | Required | |
+| `summary` | string | `ncr-writeup` | Required | One line. The condition found, never the document |
+| `customers` | list of strings | `ncr-writeup` | Required | Affected customers from containment. Empty list when no parts reached a customer |
+
+## Register state
+
+| Field | Type | Producer | Behavior | Notes |
+|---|---|---|---|---|
+| `status` | enum | `ncr-writeup`, `root-cause-capa` | Required | `blocked` (no locatable requirement), `awaiting_approval` (NCR not yet `approved`), `open`, `closed` |
+| `approval_state` | enum | `ncr-writeup` | Required | Copied from the NCR at the time of writing: `draft`, `approved`, `rejected` |
+| `containment_summary` | string | `ncr-writeup` | Required | e.g. "5 of 5 locations addressed; installed at customer not checked" |
+| `escape_clock` | timestamp with zone or null | `ncr-writeup` | Degrades | The NCR's `notification_deadline`. Null when there is no escape, or when the contractual window is unknown, and then `escape_clock_unknown` is true |
+| `escape_clock_unknown` | boolean | `ncr-writeup` | Required | True when parts reached a customer and no window could be computed |
+| `owner` | string or null | `ncr-writeup`, `root-cause-capa` | Degrades | The person named as owner in the run. Never guessed. Null reads *unassigned* |
+| `due_date` | date or null | `ncr-writeup`, `root-cause-capa` | Degrades | The next committed date: the escape clock, then a customer-stated 8D due date. Null reads *no due date*, never overdue |
+| `recurrence` | enum | `ncr-writeup` | Required | The NCR's value, unchanged |
+| `prior_ncr_refs` | list of strings | `ncr-writeup` | Degrades | From the NCR's `related_records` |
+| `previous_fix_held` | boolean or null | `ncr-writeup` | Degrades | Null when there is no prior record or no searchable history. Never read as true |
+
+## Investigation — from the 8D
+
+| Field | Type | Producer | Behavior | Notes |
+|---|---|---|---|---|
+| `eight_d_step` | string or null | `root-cause-capa` | Degrades | The last discipline drafted, e.g. "D5 drafted; D6 and D8 placeholders". Null until an 8D is drafted |
+| `leading_cause` | string or null | `root-cause-capa` | Degrades | One line. The top-ranked candidate, labelled as a candidate, never as established |
+| `supplier_caused` | boolean or null | `root-cause-capa` | Degrades | True only when the supplier-caused flag was raised. Null until investigated. The supplier signal itself lives on the Supply Chain page |
+| `effectiveness_check_due` | date or null | `root-cause-capa` | Degrades | Only when a date has been committed. Null until then |
+
+## Close and provenance
+
+| Field | Type | Producer | Behavior | Notes |
+|---|---|---|---|---|
+| `closed_at` | timestamp with zone or null | `ncr-writeup` | Required when `status` is `closed` | When the user said to close it |
+| `closed_by` | string or null | `ncr-writeup` | Required when `status` is `closed` | Who said so, as they gave it |
+| `last_written_by` | string | both | Required | `ncr-writeup` or `root-cause-capa` |
+| `last_written_at` | timestamp with zone | both | Required | Rule 4 |
+| `first_recorded_at` | timestamp with zone | `ncr-writeup` | Required | Kept from the first write. The oldest of these is the date in the banner |
+
+**An update rewrites the whole row.** `ArtifactData` `set` replaces the
+document, so a skill reads the existing row first and carries forward every
+field it does not own. `root-cause-capa` never blanks the escape clock;
+`ncr-writeup` re-run on an NCR never blanks the 8D fields.
+
+---
+
+## Worked example
+
+`NCR-2026-0141` after `ncr-writeup` and then `root-cause-capa`:
+
+```yaml
+contract_version: 1
+record_key: Fairview_NCR-2026-0141
+ncr_ref: NCR-2026-0141
+site: Fairview
+part_number: PN-4471-B
+part_number_verbatim: "PN-4471-B"
+lot_number: H-4140-2291
+lot_number_verbatim: "H-4140-2291"
+found_at: 2026-08-12T09:20:00-04:00
+qty_found: 3
+uom: each
+requirement_cited: "4471-B-drawing.pdf, p2, datum B, true position 0.002 in max"
+disposition_pending: true
+summary: "True position 0.0061 in against 0.002 in max; heat H-4140-2291 ran on three work orders."
+customers: ["Example Hydraulics"]
+
+status: open
+approval_state: approved
+containment_summary: "5 of 5 locations addressed; installed at customer not checked"
+escape_clock: 2026-08-14T09:20:00-04:00
+escape_clock_unknown: false
+owner: "Priya Raman"
+due_date: 2026-08-14
+recurrence: first_occurrence
+prior_ncr_refs: []
+previous_fix_held: null
+
+eight_d_step: "D5 drafted; D6 and D8 placeholders"
+leading_cause: "Candidate: bar stock from heat H-4140-2291 out of straightness spec"
+supplier_caused: true
+effectiveness_check_due: null
+
+closed_at: null
+closed_by: null
+last_written_by: root-cause-capa
+last_written_at: 2026-08-13T15:02:00-04:00
+first_recorded_at: 2026-08-12T10:05:00-04:00
+```
+
+Note `previous_fix_held: null`: there was no prior record, so there is no fix
+to have held. That is not the same as `true`.
+
+---
+
+## Missing behavior
+
+| Situation | What the register page does |
+|---|---|
+| `status` is `awaiting_approval` | Counted in *awaiting approval*, not in *open*. The row shows the draft state |
+| `status` is `blocked` | Listed with the open items, pill *blocked*, reason "no locatable requirement" |
+| `owner` null | *unassigned*. Never filled in by the reader |
+| `due_date` null | *no due date*. Never counted as overdue, never as on time |
+| `escape_clock_unknown` true | Sorted with the escape clocks, at the top, reading *window unknown* |
+| `previous_fix_held` null | *no prior fix on record* or *history not searchable*, from `recurrence`. Never read as held |
+| Investigation fields null | *not yet investigated* |
+| `status` is `closed` | Out of every open count. Shown in the collapsed closed section with `closed_at` |
+| `contract_version` is older | Read the fields it knows; treat the rest as absent, per the README |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/supplier-bid.md b/plugins/claude-for-manufacturing/shared/contracts/supplier-bid.md
new file mode 100644
index 00000000..41d9ecba
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/supplier-bid.md
@@ -0,0 +1,295 @@
+# Contract: the supplier bid, and the selection record
+
+**Emitted by** `supplier-quote-request`, when a returned bid is ingested (step 11), and when the buyer states a decision (step 13)
+**Consumed by** `supplier-quote-request` at the comparison (step 12), and `quote-build` at the cost buildup, where the awarded bid becomes a sourced outside-processing line
+**Chain** 5, and any sourcing event a quote started
+**Contract version** 1
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## What this carries
+
+**Two records, each written whole at its own emit time.**
+
+1. **The supplier bid** — one per supplier response, written when the bid is
+ ingested. It mirrors the mandated response format the package asked for
+ (`../../skills/supplier-quote-request/reference/bid-comparability.md`), so a
+ conforming bid fills every field and an off-format bid shows exactly where
+ it fell short.
+2. **The selection record** — one per sourcing event, written when the buyer
+ tells the skill which bid they chose. **The buyer decides; the skill records
+ it.** A recommendation is never a selection record.
+
+**Every value is what the supplier stated, with where they stated it.** A bid
+that quoted a lot price has no unit price on this record. A bid that said
+nothing about the quality clauses has not accepted them. Per
+`../absent-is-not-zero.md`, a field the supplier did not supply is null and
+listed in `fields_missing`, never zero, never a default, never "probably
+included."
+
+**Both records are internal.** Nothing on them goes to any supplier: not the
+prices, not the other bidders' names, not the ranking. Per
+`../secret-config.md`, *The outbound document check*.
+
+---
+
+## The supplier bid
+
+### Identification
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Rule 7 |
+| `event_ref` | string | Required | The sourcing event, e.g. `SRC-2026-10-14-PN-4471-B-BO` |
+| `bid_ref` | string | Required | `<event_ref>/<supplier_id>/<n>`; `n` increments when a supplier restates |
+| `supersedes` | string or null | Optional | The `bid_ref` this restatement replaces |
+| `supplier_id` / `supplier_id_verbatim` | string | Required | Rule 3. The vendor record ID, or `unlisted` with the name as the supplier wrote it |
+| `supplier_name` | string | Required | |
+| `approval_status` | enum | Required | `approved`, `approved_single_source`, `not_confirmed_approved`, from step 8's candidate list. Never upgraded by a good bid |
+| `received_at` | timestamp with zone or null | Required | Rule 4. From the email header or file; null with the reason when nothing dates it |
+| `received_via` | enum | Required | `email`, `pdf`, `spreadsheet`, `pasted` |
+| `source_ref` | string | Required | File name and page, sheet and row, or email subject and date. Rule 6 |
+| `ingested_at` | timestamp with zone | Required | When this record was written |
+
+### Price and quantity
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `currency` | string or null | Required | ISO code as stated. Null when not stated; never assumed from the supplier's country |
+| `breaks` | list of objects | Required | One per quantity break the package asked for, **including breaks the supplier did not price** |
+| `breaks[].quantity` / `breaks[].uom` | number, string | Required | The break as the package asked for it. Rule 5 |
+| `breaks[].unit_price` | number or null | Required | Per unit, as stated. Null when the supplier quoted a lot, a range or nothing |
+| `breaks[].as_quoted` | string | Required | The supplier's words for this break, verbatim: *"$240 per lot of up to 100 pcs"* |
+| `breaks[].lead_time_first_article` | string or null | Degrades | With its unit and named start event, as stated: *"5 working days from receipt of parts"* |
+| `breaks[].lead_time_production` | string or null | Degrades | Same |
+| `breaks[].source_ref` | string | Required | Where this break's figures were read |
+| `tooling_price` | number or null | Degrades | One-time tooling or NRE, as stated. `0` only when the supplier wrote that none is needed, with `tooling_note` quoting it |
+| `tooling_in_unit_price` | boolean or null | Degrades | True when the supplier folded tooling into the piece price. Null when the bid does not say |
+| `tooling_ownership` | string or null | Degrades | Who owns it at the end, as stated |
+| `tooling_note` | string or null | Optional | Verbatim |
+| `moq` / `moq_uom` | number or null, string | Degrades | Minimum order quantity as stated |
+| `validity_until` | date or null | Degrades | Or the stated period, converted to a date in code from `received_at` and shown both ways |
+| `freight_basis` | string or null | Degrades | Incoterm or freight term as stated |
+
+### Quality and exceptions
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `quality_clause_acceptance` | enum | Required | `accepted_all`, `accepted_with_exceptions`, `not_stated`. `not_stated` is never read as accepted |
+| `clause_exceptions` | list of strings | Required | Each clause the supplier excepted, with their words. Empty only under `accepted_all` |
+| `exceptions` | list of strings | Required | Every other exclusion or assumption the supplier listed, verbatim. Empty list means they listed none |
+| `conformance` | enum | Required | `conforming` or `off_format` |
+| `fields_missing` | list of strings | **Required** | Every mandated field the supplier did not supply, by name. Present and empty only for a conforming bid |
+| `restatement_requested` | boolean | Required | True once a restatement request has been drafted for the buyer to send. Drafted, not sent |
+
+**`fields_missing` is the reason this contract exists.** A buyer reading three
+bids sees three prices; what they cannot see is that one of them never stated
+a lead time, a minimum order or whether it accepts the right of access. The
+list is computed at ingest by checking every mandated field, not by noticing
+what stands out.
+
+---
+
+## The selection record
+
+Written once per decision, when the buyer says which bid they chose, after the
+comparison was on screen. Per `../approval-gates.md`, *Supplier send and
+selection*.
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Rule 7 |
+| `event_ref` | string | Required | |
+| `decision` | enum | Required | `award`, `split_award`, `no_award`, `rebid` |
+| `awarded` | list of objects | Required for `award` and `split_award` | Each: `bid_ref`, `supplier_id`, `supplier_name`, `breaks` (quantity, uom, unit_price, currency, as on the bid), `tooling_price`, `lead_time_production`, `validity_until`, `approval_status` |
+| `recommended_bid_refs` | list of strings | Required | What the skill recommended, so a decision against it stays visible. Empty when the skill made no recommendation |
+| `follows_recommendation` | boolean | Required | |
+| `buyer_reason` | string or null | Optional | The buyer's words, verbatim. Never written for them |
+| `decided_by` | string | **Required** | The name the buyer gave, as given. The skill asks for it rather than leaving it blank |
+| `decided_at` | timestamp with zone | Required | When the buyer stated the decision in this conversation. Where the buyer gave a date the session clock disagrees with, their date, with the time marked not known |
+| `compared_bid_refs` | list of strings | Required | Every bid on screen when the decision was made |
+| `not_responded` | list of strings | Required | Suppliers with no bid at the time of the decision. Empty list when every supplier responded |
+| `triggered_by` | object | Required | `{kind: quote, inquiry_ref, line_no, operation}`, `{kind: supplier_caused_flag, ncr_ref}` or `{kind: direct}` |
+| `po_raised` | boolean | Required | Always `false` from this skill. A purchase order is raised by the buyer in the ERP (NetSuite or Infor M3) |
+
+**A selection record is not a purchase order and not an award notice.**
+Nothing is written to the ERP and nothing goes to the supplier. An award
+notice and regret notes, if the buyer wants them, are drafts like every other
+supplier email.
+
+---
+
+## Worked example
+
+Black oxide for PN-4471-B Rev 2, sourced because the Example Hydraulics quote EH-RFQ-0912
+needs it. Two bids, one off-format, then the buyer's decision.
+
+```yaml
+contract_version: 1
+site: Fairview
+event_ref: SRC-2026-10-14-PN-4471-B-BO
+bid_ref: SRC-2026-10-14-PN-4471-B-BO/VEND-5120/1
+supersedes: null
+supplier_id: VEND-5120
+supplier_id_verbatim: "5120"
+supplier_name: "Example Finishing"
+approval_status: approved_single_source
+received_at: 2026-10-22T09:14:00-04:00
+received_via: pdf
+source_ref: "bid_example-finishing_2026-10-22.txt, p1"
+ingested_at: 2026-10-22T11:02:00-04:00
+currency: USD
+breaks:
+ - quantity: 50
+ uom: each
+ unit_price: 3.10
+ as_quoted: "50 pcs: $3.10 ea"
+ lead_time_first_article: "5 working days from receipt of parts"
+ lead_time_production: "5 working days from receipt of parts"
+ source_ref: "bid_example-finishing_2026-10-22.txt, price table row 1"
+ - quantity: 200
+ uom: each
+ unit_price: 2.20
+ as_quoted: "200 pcs: $2.20 ea"
+ lead_time_first_article: "5 working days from receipt of parts"
+ lead_time_production: "5 working days from receipt of parts"
+ source_ref: "bid_example-finishing_2026-10-22.txt, price table row 2"
+tooling_price: 0
+tooling_in_unit_price: false
+tooling_ownership: null
+tooling_note: "No tooling or racking charge."
+moq: 50
+moq_uom: each
+validity_until: 2026-12-21
+freight_basis: "FOB our dock, Example Manufacturing to deliver and collect"
+quality_clause_acceptance: accepted_with_exceptions
+clause_exceptions:
+ - "Right of access: 48 hours' notice required for customer audits."
+exceptions: []
+conformance: conforming
+fields_missing: []
+restatement_requested: false
+---
+contract_version: 1
+site: Fairview
+event_ref: SRC-2026-10-14-PN-4471-B-BO
+bid_ref: SRC-2026-10-14-PN-4471-B-BO/VEND-5141/1
+supersedes: null
+supplier_id: VEND-5141
+supplier_id_verbatim: "5141"
+supplier_name: "Example Metalworks"
+approval_status: not_confirmed_approved
+received_at: 2026-10-24T16:40:00-04:00
+received_via: email
+source_ref: "email 'RE: RFQ black oxide PN-4471-B', 2026-10-24"
+ingested_at: 2026-10-25T08:30:00-04:00
+currency: null
+breaks:
+ - quantity: 50
+ uom: each
+ unit_price: null
+ as_quoted: "$240 per lot of up to 100 pcs"
+ lead_time_first_article: null
+ lead_time_production: null
+ source_ref: "email body, para 1"
+ - quantity: 200
+ uom: each
+ unit_price: null
+ as_quoted: "$410 for 200"
+ lead_time_first_article: null
+ lead_time_production: null
+ source_ref: "email body, para 1"
+tooling_price: null
+tooling_in_unit_price: null
+tooling_ownership: null
+tooling_note: null
+moq: null
+moq_uom: each
+validity_until: null
+freight_basis: null
+quality_clause_acceptance: not_stated
+clause_exceptions: []
+exceptions: ["Certs available on request."]
+conformance: off_format
+fields_missing:
+ - "unit price at 50 (quoted per lot)"
+ - "unit price at 200 (quoted per lot)"
+ - "currency"
+ - "lead time, first article, from a named event ('about a week')"
+ - "lead time, production, from a named event"
+ - "tooling price, or a statement that none is needed"
+ - "tooling ownership"
+ - "minimum order quantity"
+ - "price validity"
+ - "quality clause acceptance"
+restatement_requested: true
+---
+# the selection record
+contract_version: 1
+site: Fairview
+event_ref: SRC-2026-10-14-PN-4471-B-BO
+decision: award
+awarded:
+ - bid_ref: SRC-2026-10-14-PN-4471-B-BO/VEND-5120/1
+ supplier_id: VEND-5120
+ supplier_name: "Example Finishing"
+ breaks:
+ - { quantity: 50, uom: each, unit_price: 3.10, currency: USD }
+ - { quantity: 200, uom: each, unit_price: 2.20, currency: USD }
+ tooling_price: 0
+ lead_time_production: "5 working days from receipt of parts"
+ validity_until: 2026-12-21
+ approval_status: approved_single_source
+recommended_bid_refs: [SRC-2026-10-14-PN-4471-B-BO/VEND-5120/1]
+follows_recommendation: true
+buyer_reason: "Approved source, no tooling, fits the Example Hydraulics date."
+decided_by: "Dana Whitfield"
+decided_at: 2026-10-27T10:05:00-04:00
+compared_bid_refs:
+ - SRC-2026-10-14-PN-4471-B-BO/VEND-5120/1
+ - SRC-2026-10-14-PN-4471-B-BO/VEND-5133/1
+ - SRC-2026-10-14-PN-4471-B-BO/VEND-5141/1
+not_responded: []
+triggered_by: { kind: quote, inquiry_ref: EH-RFQ-0912, line_no: 1, operation: "black oxide (OUTSIDE-FINISH)" }
+po_raised: false
+```
+
+Note the Example Metalworks bid: `unit_price: null` at both breaks, with the lot prices
+kept verbatim in `as_quoted`. Dividing $410 by 200 is the buyer's
+normalisation the mandated format exists to avoid; the comparison may show
+that division labelled *derived from a lot price, not quoted*, and never ranks
+on it.
+
+---
+
+## Missing behavior
+
+### For the comparison (`supplier-quote-request`, step 12)
+
+| Situation | What it does |
+|---|---|
+| `breaks[].unit_price` null | The cell reads *not quoted per unit* with `as_quoted` beside it. Not ranked at that break. Never 0 |
+| `currency` null, or two currencies across bids | No conversion. Each bid stays in its stated currency, and bids in different or unstated currencies are not ranked against each other |
+| `tooling_in_unit_price` true | Shown, and the bid is flagged: its piece price is not comparable to a bid with tooling separate |
+| `moq` above a break's quantity | Flagged on that break: the price does not buy that quantity |
+| `quality_clause_acceptance: not_stated` | Shown as *not stated*, never as accepted. A recommendation that relies on it says so |
+| `validity_until` before today | Flagged expired; the bid is shown and not recommended until restated |
+| `approval_status: not_confirmed_approved` | Shown, and any recommendation of it names the requalification it needs first |
+| `conformance: off_format` | Listed with its `fields_missing`, and the restatement request is drafted |
+| A supplier with no bid | Its row reads *no response*, with the due date and days past it. Never "declined", never dropped |
+
+### For `quote-build` (the outside-processing line)
+
+| Situation | What it does |
+|---|---|
+| A selection record with `decision: award` and this line's operation | Price the outside-processing line from the awarded break, citing supplier, `bid_ref`, `received_at`, `decided_by` and `decided_at`. Its production lead time goes to the date check |
+| A bid with no selection record | Cited as *a supplier quote, not awarded*, with its date. Not labelled sourced |
+| The quote's quantity matches no awarded break | Name the gap. No interpolation between breaks; ask the estimator which break applies |
+| `moq` above the quote's quantity | Flag it on the line: the price does not buy that quantity |
+| `validity_until` before the quote's date | Flag the price as expired on the internal sheet |
+| `decision` is `no_award` or `rebid` | No sourced line. The outside-processing line stays as it would have been without this event, and says the event is open |
+| `contract_version` is older | Read the fields it knows; treat the rest as absent, per the README |
diff --git a/plugins/claude-for-manufacturing/shared/contracts/supplier-caused-flag.md b/plugins/claude-for-manufacturing/shared/contracts/supplier-caused-flag.md
new file mode 100644
index 00000000..ea4c6959
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/supplier-caused-flag.md
@@ -0,0 +1,217 @@
+# Contract: the supplier-caused flag
+
+**Emitted by** `root-cause-capa`
+**Consumed by** `supplier-quote-request`
+**Chain** 5, supplier-caused escape to alternate source
+**Contract version** 2
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## Why this one is different
+
+This is **the only cross-area handoff in the plugin**, so its schema is
+defined explicitly. It is the plugin's cross-area proof point: a
+quality finding automatically starting a sourcing action, which essentially never
+happens today because quality and purchasing live in different systems and
+different departments.
+
+That is also what makes it the most consequential payload here. **A
+supplier-caused determination is a commercially significant claim.** It says a
+vendor caused a defect, and it starts a search for an alternate source. Chain 5
+gates on a human owner before this flag is acted on, and that approval is part of
+the payload rather than an assumption the consumer makes.
+
+---
+
+## Fields
+
+### The determination
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Rule 7 |
+| `determination` | enum | Required | `supplier_caused`, `supplier_contributing`, `not_supplier_caused` |
+| `confidence` | enum | Required | `high`, `medium`, `low` |
+| `is_leading_candidate` | boolean | Required | Whether this was the top-ranked causal chain or a lower one |
+| `competing_candidates` | list of strings | **Required** | The other candidate causes and their standing. See below |
+| `ncr_ref` | string | Required | The originating NCR |
+| `capa_ref` | string or null | Degrades | The 8D, where drafted |
+
+### What was supplied, and by whom
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `part_number` / `part_number_verbatim` | string | Required | Rule 3 |
+| `part_revision` | string or null | **Required for sourcing** | See below |
+| `lot_number` / `lot_number_verbatim` | string or null | Degrades | The implicated material lot |
+| `supplier_id` / `supplier_id_verbatim` | string | Required | Rule 3 |
+| `supplier_name` | string | Required | |
+| `purchase_order` | string or null | Degrades | The PO the lot arrived on |
+| `received_at` | timestamp with zone or null | Optional | Rule 4 |
+| `qty_affected` | number | Degrades | Paired with `uom`, rule 5 |
+| `uom` | string | Required with `qty_affected` | |
+
+### Evidence
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `evidence_for` | list of strings | Required | Each citing its source, rule 6 |
+| `evidence_against` | list of strings | **Required** | May be empty, but the field is present. See below |
+| `lot_clustering_observed` | boolean or null | Degrades | Whether failures clustered by material lot |
+| `recurrence` | enum | Degrades | `first_occurrence`, `recurrence_prior_capa_held`, `recurrence_prior_capa_failed`, `no_searchable_history` |
+| `escape_occurred` | boolean | Required | Whether nonconforming parts reached a customer |
+
+### Chain 5 instrumentation — three timestamps, not two
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `escape_detected_at` | timestamp with zone or null | **Required when `escape_occurred`** | Carried forward from `ncr.md`, where `ncr-writeup` stamped it. Opens the window |
+| `determination_made_at` | timestamp with zone | **Required** | Stamped by `root-cause-capa` when this flag is raised. **The middle stamp** |
+
+**The third stamp is not on this contract, deliberately.** `rfq_issued_at`
+belongs to `supplier-quote-request`, which *consumes* this flag — it cannot
+write back into a payload it received without reversing the direction of flow
+this contract is built on. It records that stamp in its own sourcing record,
+closing the window there.
+
+So this contract carries the two stamps that exist **at the moment it is
+emitted**, and the consumer adds the third at the moment it acts. That is the
+only arrangement where each stamp is written by the skill that actually owns
+the event.
+
+Chain 5's headline metric is *time from escape to alternate-source RFQ issued*,
+and it is owned in **two consecutive segments** rather than by one skill:
+
+| Segment | Window | Owner |
+|---|---|---|
+| Detection and investigation | `escape_detected_at` → `determination_made_at` | `ncr-writeup` (detection, containment) and `root-cause-capa` (investigation) |
+| The sourcing handoff | `determination_made_at` → `rfq_issued_at` | `supplier-quote-request` |
+
+**`determination_made_at` is the field most likely to be dropped and the one
+that cannot be recovered.** The other two bracket the window and are obvious;
+the middle one is what separates investigation time from handoff time. Without
+it the two segments collapse into a single number, and the second segment — the
+dead time this chain actually eliminates — becomes invisible behind an
+investigation that legitimately takes weeks.
+
+Segmented is deliberate, not an accounting nicety. If the plugin cuts the
+handoff from two weeks to two days, that has to show up **while the
+investigation still takes a week.** One blended figure would hide which half
+moved.
+
+### Approval — rule 8
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `approved_by` | string or null | **Required to act** | The human owner who confirmed the determination |
+| `approved_at` | timestamp with zone or null | Required to act | |
+| `approval_state` | enum | Required | `draft`, `approved`, `rejected` |
+
+---
+
+## Four fields that carry real weight
+
+**`evidence_against` is required even when empty.** `root-cause-capa` produces
+ranked candidate causal chains with supporting *and contradicting* evidence, and
+never a single unqualified verdict. If only supporting evidence crossed the
+boundary, the consumer would receive a confident claim built from a ranked
+hypothesis — which is how a supplier gets accused on half the picture.
+
+**`competing_candidates` is required for the same reason.** A determination that
+was the leading candidate among three near-equals is a different claim from one
+that was clearly ahead. The buyer opening a sourcing action deserves to know
+which.
+
+**`part_revision` is required for sourcing even though it is nullable
+elsewhere.** `supplier-quote-request` **hard stops** on a revision mismatch
+between the document library and the ERP item master, because sending a supplier
+the wrong revision is the classic and expensive error that skill exists to
+prevent. A flag arriving with no revision cannot clear that check, so it blocks
+rather than degrading.
+
+**`approval_state` gates the whole payload.** A `draft` flag is a finding to
+review. Only an `approved` flag starts a sourcing action, and the consumer must
+never infer approval from the flag's existence.
+
+---
+
+## Worked example
+
+An approved determination, leading candidate but not uncontested:
+
+```yaml
+contract_version: 2
+site: Fairview
+
+determination: supplier_caused
+confidence: medium
+is_leading_candidate: true
+competing_candidates:
+ - "Tool wear on cell B, ranked second. Supported by the tool-change interval; contradicted by the same tooling running 4402 in spec that week."
+ - "Operator print revision, ranked third. No evidence of uncontrolled prints in circulation."
+ncr_ref: NCR-2026-0418
+capa_ref: 8D-2026-0418
+
+part_number: PN-4471-B
+part_number_verbatim: PN-4471-B
+part_revision: "B"
+lot_number: LOT-77219
+lot_number_verbatim: "77219"
+supplier_id: VEND-3310
+supplier_id_verbatim: "3310"
+supplier_name: "Example Steel"
+purchase_order: PO-8841
+received_at: 2026-08-19T00:00:00-04:00
+qty_affected: 480
+uom: each
+
+evidence_for:
+ - "Material cert on LOT-77219 reports hardness 232 HB against a 187-217 HB requirement (cert-77219.pdf, p2)."
+ - "All 14 out-of-tolerance parts trace to LOT-77219; none to LOT-77188 run on the same cell (inspection-20260901.xlsx)."
+evidence_against:
+ - "Spindle load telemetry rose across the run on both lots, which a material-only cause does not explain (historian-20260901.csv)."
+lot_clustering_observed: true
+recurrence: recurrence_prior_capa_failed
+escape_occurred: true
+escape_detected_at: 2026-09-07T14:05:00-04:00
+determination_made_at: 2026-09-09T11:20:00-04:00
+
+approved_by: "Priya Raman, Quality Manager"
+approved_at: 2026-09-08T11:40:00-04:00
+approval_state: approved
+```
+
+Note `recurrence: recurrence_prior_capa_failed` and `escape_occurred: true`. A
+recurrence after a closed CAPA is a materially more serious finding than a first
+occurrence, and an escape means a customer already has parts. Both change what
+the consumer does with urgency.
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What `supplier-quote-request` does |
+|---|---|
+| `approval_state` is not `approved` | **Blocks.** Report the flag as an unapproved finding and name who needs to own it |
+| `part_revision` absent | **Blocks.** The revision check cannot clear |
+| `supplier_id` absent | Blocks. There is no determination without a named supplier |
+| `evidence_against` absent as a field | Blocks. Its absence means the producer did not follow its own ranking discipline |
+| `evidence_against` present and empty | Degrades. Proceed, and state that no contradicting evidence was found |
+| `recurrence` is `no_searchable_history` | Degrades. State that history could not be searched. **Never read as a first occurrence** |
+| `confidence` is `low`, or `is_leading_candidate` is false | Degrades. Proceed as an exploratory alternate-source search and label it as such, not as a response to an established supplier failure |
+| `lot_number` absent | Degrades. Widen the scope and say why it had to widen, never narrow it |
+
+## What the consumer does on receipt
+
+Chain 5's closing step, in order:
+
+1. **Check the gate.** No `approved` state, no outbound package.
+2. **Verify the revision** against the ERP item master. Mismatch is a hard stop.
+3. **Flag single-source risk.** If this part has exactly one qualified supplier
+ and that supplier is the one implicated, that is the finding, and it is
+ usually more urgent than the sourcing package itself.
+4. **Note requalification lead time.** An alternate cannot just start shipping,
+ which is why starting early is the value.
diff --git a/plugins/claude-for-manufacturing/shared/contracts/variant-manifest.md b/plugins/claude-for-manufacturing/shared/contracts/variant-manifest.md
new file mode 100644
index 00000000..8b9f77ae
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/contracts/variant-manifest.md
@@ -0,0 +1,237 @@
+# Contract: the variant manifest
+
+**Emitted by** `design-space-explore`
+**Consumed by** `trade-study-report`
+**Chain** none. This is the same producer-consumer relationship
+`breakdown-diagnosis` has with `daily-production-report` in Chain 4
+**Contract version** 4
+
+Rules that govern every contract are in [README.md](README.md).
+
+---
+
+## The constraint that shapes this contract
+
+`trade-study-report` is document-only and consumes a variant manifest, and
+**a person can fill one in by hand** if no CAD backend is
+available at all.
+
+That is a real design requirement, not a footnote. It means:
+
+- **The manifest must be hand-authorable.** A flat table a mechanical engineer can
+ fill in a spreadsheet, not a CAD-internal dump.
+- **Every CAD-specific field must be optional.** A hand-filled manifest has no
+ document IDs, no regeneration status and no backend.
+- **The consumer must not require anything only a CAD tool could produce.**
+
+So the required core is small and the CAD fields sit around it.
+
+---
+
+## Manifest header
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `contract_version` | integer | Required | |
+| `site` | string | Required | Which plant the study belongs to, rule 7. A hand-authored manifest still carries it |
+| `study_ref` | string | Required | Ties the variants to a trade study |
+| `base_model` | object or null | **Optional** | Null for a hand-authored manifest |
+| `cad_backend` | enum or null | Optional | `fusion` or `none`. See the adapter note |
+| `parameters_varied` | list of objects | Required | Each: name, unit, range, step or sampling strategy |
+| `parametric_check` | object or null | Optional | See below |
+| `generated_at` | timestamp with zone or null | Optional | Rule 4 |
+| `variant_count_confirmed` | boolean | Required | Whether the engineer approved the count before generation |
+
+`base_model` when present carries `document_ref`, `name` and `version`, and the
+base model is **never modified** — variants are new documents or clearly-named
+configurations.
+
+## Variant rows
+
+One row per variant. This is the part that must survive being typed by hand.
+
+| Field | Type | Behavior | Notes |
+|---|---|---|---|
+| `variant_id` | string | Required | Stable, and traceable to its parameter set |
+| `parameter_values` | object | Required | One entry per parameter in `parameters_varied` |
+| `status` | enum | Required | `generated`, `regeneration_failed`, `skipped`, `hand_authored`, or (from version 4) `reused_existing`: a variant document with the same name and parameter values already existed, from a partial batch or a re-run, and was measured rather than created again |
+| `status_detail` | string or null | Required when not `generated` | Why it failed or was skipped |
+| `document_ref` | string or null | Optional | Absent on a hand-authored row |
+| `properties` | object | Degrades | Model-computed values. See below |
+| `analysis_results` | object or null | **Optional** | See the handoff boundary |
+| `source_ref` | string | Required | Rule 6. Where each row's values came from |
+
+### `properties`
+
+Whatever the model could compute. Each value carries its unit, rule 5.
+
+```yaml
+properties:
+ mass: { value: 0.412, uom: kg }
+ volume: { value: 152.6, uom: cm3 }
+ bounding_box: { x: 180, y: 96, z: 42, uom: mm }
+```
+
+**A property the model could not compute is absent, not zero.** A variant with
+`mass: 0` reads as massless rather than unmeasured, which would win a
+lower-is-better weight criterion outright.
+
+---
+
+## The handoff boundary
+
+`design-space-explore` **does not run simulation.** It produces variants and the
+manifest describing them, so an analysis tool or a person evaluates each and
+returns results, which `trade-study-report` then consumes.
+
+That is why `analysis_results` is optional and why it lives on the variant row
+rather than in a separate payload. Three states the consumer must distinguish:
+
+| State | Meaning | What `trade-study-report` does |
+|---|---|---|
+| `analysis_results` absent on every row | No analysis has been run | Produce the scored comparison and **clearly mark it judgment-based, not analysis-based** |
+| Present on some rows | Partial analysis | Score what is analyzed, report the gap, **never impute a score** |
+| Present on all rows | Complete | Score normally, citing each result to its source |
+
+## `parametric_check`
+
+The single biggest practical risk in `design-space-explore` is that a real
+production model is not properly parametric, and the check must run **before**
+generation, not after.
+
+```yaml
+parametric_check:
+ ran: true
+ driving_parameters: ["wall_thickness", "rib_count", "fillet_radius"]
+ requested_not_driving: ["hole_pattern"]
+ external_references_present: true
+```
+
+`requested_not_driving` is the field that matters. A parameter the engineer wanted
+to vary that is not actually a driving dimension in the model means those variants
+could not be generated, and the manifest has to say which rather than silently
+producing fewer rows.
+
+## Regeneration failures are expected
+
+Geometry that self-intersects or features that fail to rebuild at range extremes
+are **normal**, not a bug, and they do not abort the batch. Each failure is a row
+with `status: regeneration_failed` and a `status_detail`.
+
+**A failed variant is never dropped from the manifest.** A dropped row is
+indistinguishable from a variant nobody considered, and the trade study would
+then report a design space narrower than the one actually explored.
+
+## Keep the adapter interface regardless
+
+Fusion is the one implementation behind the interface today. `cad_backend` is
+part of the contract even with one backend, so a CAD connector appearing later
+drops in as a new enum value without a redesign.
+
+**Version 3** (2026-10-13) removed the second CAD backend from the allowed
+values; it was never wired up. Nothing else changed. A version 2 manifest
+carrying that value is read under the missing behavior below.
+
+---
+
+## Worked example
+
+Six variants: four generated, one failed at a range extreme, one whose parameter
+was not driving. No analysis yet.
+
+```yaml
+contract_version: 4
+site: Fairview
+study_ref: TS-2026-014
+base_model:
+ document_ref: "fusion://Fairview/BracketUpper/v7"
+ name: "Bracket, Upper, 4471"
+ version: 7
+cad_backend: fusion
+parameters_varied:
+ - { name: wall_thickness, unit: mm, range: [3.0, 5.0], step: 0.5 }
+ - { name: rib_count, unit: count, range: [2, 4], step: 1 }
+parametric_check:
+ ran: true
+ driving_parameters: ["wall_thickness", "rib_count", "fillet_radius"]
+ requested_not_driving: ["hole_pattern"]
+ external_references_present: false
+generated_at: 2026-09-08T10:22:00-04:00
+variant_count_confirmed: true
+
+variants:
+ - variant_id: V-001
+ parameter_values: { wall_thickness: 3.0, rib_count: 2 }
+ status: generated
+ status_detail: null
+ document_ref: "fusion://Fairview/BracketUpper-V001/v1"
+ properties:
+ mass: { value: 0.351, uom: kg }
+ volume: { value: 130.0, uom: cm3 }
+ bounding_box: { x: 180, y: 96, z: 42, uom: mm }
+ analysis_results: null
+ source_ref: "design-space-explore/2026-09-08/TS-2026-014"
+
+ - variant_id: V-002
+ parameter_values: { wall_thickness: 3.5, rib_count: 3 }
+ status: generated
+ status_detail: null
+ document_ref: "fusion://Fairview/BracketUpper-V002/v1"
+ properties:
+ mass: { value: 0.418, uom: kg }
+ volume: { value: 154.8, uom: cm3 }
+ bounding_box: { x: 180, y: 96, z: 42, uom: mm }
+ analysis_results: null
+ source_ref: "design-space-explore/2026-09-08/TS-2026-014"
+
+ - variant_id: V-005
+ parameter_values: { wall_thickness: 5.0, rib_count: 4 }
+ status: regeneration_failed
+ status_detail: "Rib fillets self-intersect at 5.0 mm wall with 4 ribs; feature Fillet3 failed to rebuild."
+ document_ref: null
+ properties: {}
+ analysis_results: null
+ source_ref: "design-space-explore/2026-09-08/TS-2026-014"
+
+ - variant_id: V-006
+ parameter_values: { wall_thickness: 4.0, rib_count: 3 }
+ status: skipped
+ status_detail: "Requested hole_pattern variation is not a driving parameter in the base model; see parametric_check.requested_not_driving."
+ document_ref: null
+ properties: {}
+ analysis_results: null
+ source_ref: "design-space-explore/2026-09-08/TS-2026-014"
+```
+
+V-005 and V-006 stay in the manifest with empty `properties`. `trade-study-report`
+must report them as unevaluated options rather than scoring them at zero — which
+would rank them best on any lower-is-better mass criterion.
+
+---
+
+## Missing behavior for the consumer
+
+| Situation | What `trade-study-report` does |
+|---|---|
+| `analysis_results` absent throughout | Degrades. Score on judgment and **mark the study judgment-based** |
+| `analysis_results` on some rows only | Degrades. Report the gap per option. **Never impute a score** |
+| A `properties` value absent | Degrades. Report the option as unscored on that criterion. Never treat as zero |
+| `status` is `reused_existing` | Score it like `generated`; its `document_ref` is the existing document. Say it was reused |
+| `status` is `regeneration_failed` or `skipped` | Degrades. List as an unevaluated option, excluded from the ranking, and say it was excluded |
+| `requested_not_driving` is non-empty | Degrades. State that part of the requested design space was not explored |
+| `variant_count_confirmed` is false | Degrades. Note that the variant set was not confirmed with the engineer |
+| `source_ref` absent on a row | Blocks that row. Every score must cite its source, so an unsourced property cannot be scored |
+| `base_model` and `cad_backend` both null | Degrades silently. This is a valid hand-authored manifest and needs no comment |
+| `cad_backend` holds a value other than `fusion` or `none` (an older manifest) | Degrades. Read the rows as given; say the backend named is not one this plugin supports, so its document references cannot be reopened |
+
+## What the consumer adds
+
+The manifest carries variants and their measured properties. It does **not** carry
+criteria, weights or scores — those belong to the trade study matrix that
+`trade-study-report` loads separately, along with:
+
+- **Criterion direction** per criterion, since some are lower-is-better (mass,
+ cost) and some higher-is-better. Getting this wrong silently inverts the result.
+- **Constraint compliance**, checked separately from scoring. An option violating
+ a hard requirement is **disqualified, not low-scoring**, and mixing the two is a
+ common error.
diff --git a/plugins/claude-for-manufacturing/shared/erp-connectors.md b/plugins/claude-for-manufacturing/shared/erp-connectors.md
new file mode 100644
index 00000000..0624801a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/erp-connectors.md
@@ -0,0 +1,125 @@
+# The ERP connector: Oracle NetSuite or Infor M3
+
+**Shared across the plugin.** Wherever a skill says *the ERP*, it means
+whichever of these two is live for the plant: **Oracle NetSuite** or **Infor
+M3**. A plant runs one. The profile's `### Systems` line names it
+(`../skills/onboarding/reference/config-profile.md`).
+
+NetSuite is the worked example throughout the skills, because it was the first.
+This file is where M3 differs. Read it before any M3 pull.
+
+---
+
+## Which one is live
+
+**A connector is live only when its tools exist in this session and return.**
+
+- **NetSuite:** the NetSuite connector's tools.
+- **Infor M3:** tools named `M3_<program>_<transaction>`, for example
+ `M3_MNS150MI_GetUserData_CurrentUser`. The server's own name differs per
+ company; the `M3_` tool names do not. The connection test is
+ `MNS150MI_GetUserData_CurrentUser`: it returns the signed-in user's
+ `Company`, `Division`, `Facility` and `Warehouse`, and pulls no business data.
+
+Infor CloudSuite Industrial and Infor LN are different products. They are not
+this connector and stay in the `custom-connector` registry.
+
+---
+
+## Record by record
+
+The only M3 calls a skill may make are the ones in this table.
+
+| What the plugin reads | NetSuite | Infor M3 call | M3 fields used |
+|---|---|---|---|
+| Part master | `item`, `assemblyitem` | `MMS200MI_SearchItem`, `MMS200MI_GetItmBasic` | `ItemNumber`, `ItemName`, `Status`, `BasicUnitOfMeasure`, `MakeBuyCode`, `ItemGroup` |
+| Item at a warehouse | `item` by location | `MMS200MI_GetItmWhsBasic`, `MMS200MI_GetItmWhsBal` | `Warehouse`, `Location`, `Buyer` |
+| On hand by location and lot | `inventorynumber`, `location` | `MMS060MI_List` | `Location`, `BatchNumber` (the lot), `BalanceIdStatus`, `ApprovedOnHandBalance`, `AllocatedQuantityBasicUom` |
+| Production work orders | `workorder` | `PMS100MI_SearchMO`, `PMS100MI_Get` | `ManufacturingOrderNumber`, `ProductNumber`, `WorkOrderStatus`, `OrderedQuantity`, `ManufacturedQuantity`, `StartDate`, `PlannedFinishDate`, `Facility` |
+| Operation standards and actuals | closed work orders | `PMS100MI_LstOperations` | `OperationNumber`, `WorkCenter`, `SetupTime`, `RunTime`, `UsedLaborSetupTime`, `UsedLaborRunTime`, `CompletedQuantity`, `ScrappedQuantity`, `ReportingDate` |
+| Materials on a work order | work order components | `PMS100MI_LstMaterials` | component item and quantities, as returned |
+| Sales orders | `salesorder` | `OIS100MI_SearchHead_LimitedOutput` | `OrderNumber`, `CustomerNumber`, `OrderDate`, `RequestedDeliveryDateAtDestination`, `HighestOrderStatus`, `LowestOrderStatus` |
+| Shipped lines | `itemfulfillment` | `MWS411MI_LstDelLnByOrd`, `DRS100MI_LstShipment` | `DeliveryNumber`, `OrderNumber`, `OrderLineNumber`, `ItemNumber`, `TransactionQuantity`; shipment `DepartureDate`, `HighestShipmentStatus` |
+| Purchase orders | `purchaseorder` | `PPS200MI_SearchHead`, `PPS200MI_LstLine` | `PurchaseOrderNumber`, `SupplierNumber`, `ItemNumber`, `PurchasePrice`, `OrderedQuantity`, `ReceivedQuantity`, `RejectedQuantity`, `ReceiptDate` |
+| Receipts | `itemreceipt` | `PPS200MI_LstReceiptsByPO` | `ReceivingNumber`, `TransactionDate`, `ReportedQuantity` |
+| Suppliers | `vendor` | `CRS620MI_SearchSupplier`, `PPS115MI_LstAltSupplier` | `SupplierNumber`, `SupplierName`, `Status`, `Country` |
+| Usage and open demand | usage history | `MMS080MI_LstMtPlByItmWhs` | `PlanningDate`, `TransactionQuantity`, `OrderCategory`, `OrderNumber` |
+| Server clock | account time zone | `ARS200MI_ServerTimeZone` | `UTCTime` |
+
+**Scope.** NetSuite scopes by subsidiary and location; M3 scopes by
+**facility and warehouse**. Company and division come from the signed-in user.
+Every M3 pull is filtered by the facility and warehouses in the profile's
+`### ERP scope` and by the date window. Never an unfiltered search.
+
+---
+
+## What M3 does not give, and what the skill does instead
+
+Each of these takes the fallback the skill already has for that one input when
+the ERP is not connected. Say which input fell back and why, in the output.
+Every other ERP input still comes from M3.
+
+| Not available from M3 | Why | Fallback |
+|---|---|---|
+| Standard cost | `MMS200MI_GetItmPrice` is not called | Last purchase price from `PPS200MI_LstLine`, then an export or a supplied cost, labelled with its source. Never zero |
+| Quote history | `OIS100MI_SearchQuotation` is not called | Prior quotes from documents only |
+| Customer order lines by search | `OIS100MI_SearchLine_LimitedOutput` is not called | Lines come from delivery lines (`MWS411MI_LstDelLnByOrd`) and the material plan |
+| Lot on a shipment or a receipt | Not in either call's output | On-hand lots and lots on work orders are read; what shipped or came in by lot is **unverified** until confirmed |
+| Part revision | Not on the item record | Where the profile's `### ERP scope` says it lives: item-ID suffix, or the drawing |
+| Routings and BOMs | Not exposed by the M3 server | The routing or BOM export, as for a NetSuite account without routings licensed |
+| Customer contacts, supplier contacts | Not in the search output | Documents, or asked for |
+
+The skills do not call `MMS200MI_GetItmPrice`, `OIS100MI_SearchQuotation` or
+`OIS100MI_SearchLine_LimitedOutput`. If an Infor M3 tool call returns an
+error, tell the user and fall back to a file export.
+
+---
+
+## Reading M3 output
+
+1. **Empty comes back as an error.** "Record does not exist" from a list call
+ means *none found*. Report it as empty, never as a failed check and never as
+ zero (`absent-is-not-zero.md`). Any other error is a failed check, reported
+ with the call that failed.
+2. **Two date formats, sometimes in one record.** `YYYYMMDD` (`20261015`) and
+ `YYYY-MM-DD` (`2026-10-15`) both occur; shipments carry one of each. Read
+ both. A time like `1600` is 16:00.
+3. **Status codes come back as numbers or names.** A purchase order searched
+ with `Put-away` can return `"75"`. Key status logic on the code:
+ order lines `66` delivered, `77` invoiced, `90` deleted; purchase orders
+ `75` put away, `85` invoiced; work orders by `WorkOrderStatus` name
+ (`OrderCompleted`, `OrderReady` are closed). Deleted records (`90`) are out
+ of every count.
+4. **Searches stop at about 30 rows and say nothing.** When a call returns 30
+ or more rows, assume more exist: narrow the filter (by date, item, status)
+ and pull again until a page returns fewer. Say in the data quality report
+ when a source was pulled in slices.
+5. **`RunTimeHours` is not hours.** Use `SetupTime`, `RunTime`,
+ `UsedLaborSetupTime` and `UsedLaborRunTime`, in the time unit the profile's
+ `### ERP scope` records for M3, and never `RunTimeHours`. M3 sets the unit
+ per work center, so it is asked at onboarding, never assumed. Until it is
+ recorded, operation times are reported as read, unit unconfirmed, and are
+ not costed.
+6. **Quantities are positive.** M3 writes order, delivery and receipt
+ quantities positive. NetSuite writes sales order and fulfilment lines
+ negative. Only the material plan signs demand negative. Record the M3 sign
+ rule per record type in `join-keys.md`'s *Integrity checks*.
+7. **Inspection status is on the balance.** `BalanceIdStatus` `1` is under
+ inspection, `2` approved, `3` rejected. Stock under inspection is not
+ available stock, and NCR containment reads it as already held.
+
+**Source tags.** Rows from M3 carry `source_system` `infor_m3`, and a
+reference is `infor_m3:<record>/<id>`, such as `infor_m3:mo/4001015937` or
+`infor_m3:delivery/4111327`.
+
+---
+
+## Never written to
+
+The same write guard as NetSuite (`approval-gates.md`). **No skill calls any M3
+transaction outside the table above**, approval or not. The M3 server exposes
+writes that can add, change and delete customer orders, create, hold, split,
+reschedule and delete work orders, approve and change purchase orders, change
+item prices, confirm pick lists and release orders. None of them is ever
+called. A request to do one ("release MO 4001015937") gets a draft of the
+change for a person to make in M3, and says nothing was changed.
diff --git a/plugins/claude-for-manufacturing/shared/live-dashboard.md b/plugins/claude-for-manufacturing/shared/live-dashboard.md
new file mode 100644
index 00000000..b60d2827
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/live-dashboard.md
@@ -0,0 +1,287 @@
+# Live dashboards — one page per site, updated in place
+
+**Shared across the plugin.** Two pages are published to the Claude artifact
+store and then updated in place on every later run, instead of being handed
+over for the user to save over the last one:
+
+| Dashboard | Fixed title | Published by | Records |
+|---|---|---|---|
+| Operations | `<Site>: Operations Command Center` | `morning-plant-pulse` only | `pulse_days`, per `contracts/pulse-day-record.md` |
+| Quality | `<Site>: Quality Register` | `ncr-writeup` and `root-cause-capa` (and so `inspection-to-capa`, which runs them) | `ncrs`, per `contracts/quality-register-record.md` |
+
+Every other command-center page stays what `command-center.md` describes: a
+page offered in the conversation, with its placement line.
+
+**This is not a write to M365 or to any system of record.** The artifact store
+belongs to the user's Claude account. The M365 read-only rule in
+`artifact-style.md` stands unchanged, and nothing here gives a skill a write
+path into SharePoint, Teams, the ERP, the CMMS or the quality system.
+
+---
+
+## What "updated" means
+
+**A skill says "updated" only when the publish call returned a URL in this
+same run.** Not when it intended to publish, not when a publish was attempted,
+and not because the dashboard was updated yesterday. A plant person who reads
+"updated" stops checking, so the word has to be true every time it is printed.
+
+The line that reports it names the dashboard and the URL:
+
+> *Updated **Fairview: Operations Command Center** — `<url>`. Private to you
+> until you share it.*
+
+**The dashboard is private until the user shares it. No skill shares it, and
+no skill says it is shared.** Sharing is something the user does in claude.ai.
+Never write "shared with the team," "posted," "published to the plant" or
+"scheduled."
+
+---
+
+## Fall back, never stall
+
+**If the publish tools are not available in this session, or a call fails,
+the run still completes the old way:** the page in the conversation, its
+placement line, and one plain sentence saying the dashboard was not updated.
+
+> *The dashboard was not updated: the artifact tools are not available in this
+> session. Here is today's page; save it over yesterday's.*
+
+Say why in a few words (tools not available, the publish was refused, the
+record write failed). Never say "updated," "published," "scheduled" or
+"shared" on a fallback run, and never offer to publish it "later" or "once
+X is confirmed": that promises a run nobody has scheduled.
+
+**Unattended publishing is unverified.** Whether a session started by a
+schedule, with nobody watching, can publish and update artifacts has not been
+tested. Until it is, a scheduled pulse run checks for the tools like any other
+run and falls back when they are absent. **Never claim a scheduled run
+published anything.** Only the run's own tool results say what happened.
+
+---
+
+## Where the dashboard URL lives
+
+**In the `## Dashboards` block on the Open work page, one line per
+dashboard** (`replies.md`, *The open work*). Not in the
+`## Plant context` block: changing that block takes two turns and an approval
+(`onboarding`, *Two turns, never one*), which an unattended run cannot do. The
+URL is a pointer to the user's own page, not plant configuration, so the skill
+writes this line without a gate:
+
+```
+## Dashboards
+- Fairview: Operations Command Center — https://claude.ai/artifact/…
+- Fairview: Quality Register — https://claude.ai/artifact/…
+```
+
+Write the line the first time a dashboard is created, and replace it if a run
+has to create a new one, with `put --block "Dashboards" --entry "<title>"`, so
+no other line or block changes. If the page cannot be written this session,
+report the URL and say *"The link was not saved to your Open work page:
+[reason]."*; the title lookup below will still find it next time.
+
+---
+
+## The steps, with the tool calls
+
+These are the tools the dashboards are published and updated with. Use
+exactly these.
+
+| Step | Tool call |
+|---|---|
+| Find the dashboard | The `## Dashboards` line on the Open work page first. Then `Artifact` action `list`, matching the **exact** title |
+| Create on first run | `Artifact` publish with the HTML file, `capabilities: {db: {}}` and the fixed `title`. Save the returned URL to the `## Dashboards` line, then `open` the dashboard so it, not the Open work page, is what the person sees (`replies.md`) |
+| Update on later runs | `Artifact` action `read` with the URL, then publish with the same `url`. A publish without the read is refused |
+| Write a record | `ArtifactData` action `set` (overwrite by key), or `batch` for several, against the dashboard URL |
+| Read history for trends | `ArtifactData` action `query` or `list` on the collection |
+
+Where the runtime asks for its own capabilities or design guidance to be
+loaded before a publish, load it. The house style in `artifact-style.md` still
+governs the look.
+
+### 1. Find it before creating it
+
+**Scheduled runs start in a fresh session with no memory of earlier runs**, so
+the skill finds the dashboard every time rather than assuming:
+
+1. **The stored URL.** If the `## Dashboards` line on the Open work page has one, `read` it. If the
+ read works, that is the dashboard.
+2. **The exact title.** If there is no stored URL, or it no longer opens,
+ `list` and match the fixed title exactly. Write the URL found back to the
+ `## Dashboards` line.
+3. **Create it.** Only when both find nothing.
+
+**A renamed artifact breaks the title lookup.** If someone renames the
+dashboard and the stored URL is lost, the next run finds nothing and creates a
+second one. Say so in the run output whenever a dashboard is created on a run
+that is not the first: *"No dashboard titled 'Fairview: Operations Command
+Center' was found, so a new one was created. If you renamed the old one, its
+history is still there; rename it back and delete this one."*
+
+**Two artifacts with the exact title:** use the one the stored URL names. With
+no stored URL, use the most recently updated, and name both URLs in the run
+output. An unattended run cannot ask which one is right, so it says which it
+used.
+
+### 2. Keyed records, written before or after the publish
+
+History lives in the artifact's own database, one record per production day or
+per NCR. **Every write is a `set` by key, so a re-run overwrites and never
+adds a second record.** That is what keeps the pulse idempotent.
+
+| Collection | Key | Contract |
+|---|---|---|
+| `pulse_days` | `<site>_<YYYY-MM-DD>`, e.g. `Fairview_2026-08-31` | `contracts/pulse-day-record.md` |
+| `ncrs` | `<site>_<ncr_ref>`, e.g. `Fairview_NCR-2026-0141` | `contracts/quality-register-record.md` |
+
+Order the calls so a failure loses as little as possible:
+
+- **Dashboard already exists:** `read` it, `query` the history, `set` this
+ run's record(s), then compute and publish. If the publish then fails, the
+ history is already stored and the next run renders it.
+- **First run:** publish first (the database belongs to the artifact, so
+ there is nowhere to write until it exists), then `batch` the records against
+ the new URL.
+
+If a record write fails after a successful publish, the page is updated but
+its history is not: say *"Updated the dashboard; the record for 2026-08-31 was
+not stored, so the trend will show a gap for that day until this day is
+re-run."*
+
+**Every run shows its record(s) in the reply as well**, stored or not, so the
+numbers can be checked and a fallback run says what would have been written —
+as the summary table in `replies.md`, with the key and `data_complete` by
+those names, never as a raw YAML block.
+
+### 3. Keep the page static
+
+**The skill reads the records, computes every figure in code, and bakes the
+numbers into the HTML it publishes. The page never calls the database when
+someone opens it.** That way it opens with no consent prompt, works for anyone
+it is later shared with, and the figures block still covers every number on
+the page. The `db` declaration gives the records somewhere to live; it is not
+there so the page can read them.
+
+Declare `capabilities: {db: {}}` on the create. On an update, omit
+`capabilities` so the page keeps what it has.
+
+### 4. Report it
+
+The run output ends with the dashboard line: *Updated* with the URL, or the
+fallback sentence. A created dashboard says *Created* with the URL. On the
+Quality Register, the sensitivity line follows it (see below).
+
+---
+
+## Rules that carry over unchanged
+
+A published dashboard is still a page this plugin produced, and every rule a
+page follows applies:
+
+- **House style**, per `artifact-style.md`. No new palette.
+- **The freshness banner first**, never a footnote. Only a safety-flagged
+ record or a blocked safety status sits above it.
+- **Absent is not zero**, per `absent-is-not-zero.md`. A day whose export did
+ not land is stored `data_complete: false`, and the trend shows a **gap**
+ for it, never a zero plotted as if the line stopped. A metric that could
+ not be computed is null in the record and blank in the chart.
+- **The figures block**, per `computed-figures.md`. Every number on the page,
+ including every trend point and every count in the header, is printed from
+ a computation listed in the block.
+- **Every count has an example row.**
+- **The header carries both clocks:** *Updated [timestamp] · data as of
+ [timestamp]*. "Updated" is the publish time of this run; "data as of" is
+ the newest source the numbers rest on. A fallback page, which was not
+ published, says *Generated [timestamp] · data as of [timestamp]* instead.
+
+---
+
+## Back-fill on the first run
+
+**When the first run's exports cover several production days, the first run
+stores a record for each of them, so the trend opens with history.** Only for
+days the exports fully cover: the planning, production output and downtime
+exports each hold that day, and each export's window runs past the day's end.
+A day only partly covered is still written, as `data_complete: false` with
+its gaps named, so it shows as a gap rather than as a low day.
+
+Back-fill happens once, on the run that creates the dashboard. Later runs
+write their own production day; a re-run for an earlier day overwrites that
+day's record by key.
+
+**With no history at all**, the trend panel says so in a sentence (*"First run:
+no stored history yet. The trend starts tomorrow."*) and week-over-week is
+skipped, not shown empty.
+
+---
+
+## The Quality Register
+
+The register exists because a single run knows one NCR, and a list of open
+corrective actions needs the others. Each NCR or 8D run writes its own row
+and then rebuilds the page from every row in `ncrs`.
+
+**Banner, first, always:**
+
+> *Tracks NCRs run through this plugin since [date of the oldest record]. Not
+> your full quality library.*
+
+**The date is never dropped.** On a fallback run, with no register to read
+the oldest record from, it says *"since [date unknown: the register was not
+reachable this run]"* — the sentence keeps its shape, so a reader always sees
+that a start date exists and what it is or why it is missing.
+
+A manager reading "3 open" will assume that is everything. The banner is what
+stops it. Where the M365 quality library is readable in this run, a read-only
+check may list NCRs found there but missing from the register, as a separate
+*"In the library, not in this register"* list. Nothing is written to the
+library.
+
+**Page content, in order:**
+
+1. **Header counts:** open, overdue, awaiting approval. Each count is printed
+ from the records and carries example rows below it.
+2. **Open items table.** Customer-escape clocks first, soonest deadline at the
+ top; then the rest by age. Columns: NCR, part, lot, status, 8D step,
+ owner, due, escape clock, age in days. NCR, part and lot numbers in mono.
+ Status pills use the existing semantic colors: `--critical` for an escape
+ clock running or overdue, `--warn` for awaiting approval or blocked,
+ `--good` for closed. An owner nobody has assigned reads *unassigned*, never
+ blank.
+3. **Recurrence and supplier-caused flags.** A recurrence whose previous fix
+ did not hold is flagged on its row. The supplier-caused flag shows here as
+ a flag only; **the supplier signal stays on its own Supply Chain page**, per
+ `command-center.md`.
+4. **Closed items**, in a collapsed `<details>` section, with the close date.
+
+**Overdue** means a due date before today on a row that is not closed. A row
+with no due date is *no due date*, not overdue and not on time.
+
+**Closing an NCR is the user's decision.** For now the user tells the skill
+(*"close NCR-2026-0141"*) and the skill sets that row's status to `closed`,
+with who said so and when, and republishes. Closing it in the register does
+not close it in the plant's quality system; say that the NCR itself is closed
+by whoever owns it. If the register is unavailable this run, say the close was
+**not recorded** and the register was not updated. Never report it closed.
+There is no in-page editing.
+
+**Sensitivity.** The register is internal. It holds customer names and
+customer-notification deadlines. It carries the NCR and the 8D **by
+reference** — the identifier and a one-line summary — never the documents,
+and never any content from a redacted customer pack. Every line that reports
+the register's URL is followed by:
+
+> *Internal: it lists customer names and notification deadlines. Check who you
+> share it with.*
+
+See `secret-config.md`, *The audience rule*.
+
+---
+
+## One dashboard per site
+
+A plant with two sites has two Operations dashboards and two Quality
+Registers, each with its site in the title and in every record key. A record
+never lands in another site's dashboard. There is no combined multi-site view
+yet.
diff --git a/plugins/claude-for-manufacturing/shared/replies.md b/plugins/claude-for-manufacturing/shared/replies.md
new file mode 100644
index 00000000..34feed20
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/replies.md
@@ -0,0 +1,249 @@
+# What a reply holds — documents, records, memory and names
+
+**Shared across every skill.** Four rules about what goes in front of the
+person and where things are kept.
+
+---
+
+## Documents are printed in full; records are summarised
+
+A **document** is what a person reads, signs or sends: the quote, the cost
+sheet, the NCR, the 8D, the RFQ package, an email draft, the morning report,
+the intake form. **It is printed in the reply, in full.** Saving a copy to a
+file as well is fine; a file *instead of* the reply is not. The person reads
+the reply, and every delimited block and outbound check lives in it.
+
+### Reports are the exception: a short reply when the page was written
+
+The morning report, the Operations page and the supplier bid comparison are
+read on a page, not in the chat. For
+the bid comparison the headline is the provisional recommendation and its main
+tradeoff, the exceptions are the requirements still open before an award, and
+the decision waiting is the next-step question. **When this run wrote the full page
+somewhere the person can open** (a publish returned its URL, or the page was
+saved as an HTML file and the reply names the file), the reply is a summary
+of about 150 words. **200 words is a hard limit: count before sending.** Each
+item below is one sentence; an exception or a decision is the thing and its
+number, with the explanation left on the page.
+
+1. Safety first, one line per item: a safety-flagged record, a record under
+ *"Blocked — safety status unknown"*, or *"Safety status: not assessed"*.
+2. The site, the production day, and the freshness state in one line: data
+ complete, or the gap.
+3. The headline: good output against plan, and OEE or why it is not computed.
+4. Up to three exceptions, one line each.
+5. The decisions waiting today, or *"No decisions waiting today."*
+6. Where the full page is: the URL or the file path.
+
+No tables, logs or methods in the summary; they are on the page. Every
+number in the summary is one the page prints. **This is for the whole
+report only.** A request that picks sections or skips some ("freshness and
+the rankings, skip OEE this time"), a question, a record the person asked to
+see, or text to paste is answered in the reply in full, in report order, as
+always; the page may still be saved as well. **When nothing could be written**
+(no file writer and no publish), the page is printed in the reply in full, as
+above. Where a skill offers "the page in the conversation", a saved file named
+in the reply is that offer. Documents someone signs or sends (quotes, NCRs,
+8Ds, RFQ packages, email drafts) are always printed in full.
+
+### Saved copies: Word for documents, Excel for tables, never .txt
+
+When a document is also saved as a file, and it should be wherever the person
+downloads from a file card (Cowork), the file is one a plant opens without
+thinking about it:
+
+| What it is | File |
+|---|---|
+| A controlled document: customer quote, supplier RFQ package, NCR, escape notification, 8D, trade study memo | `.docx` |
+| A table someone works in: internal cost sheet, bid comparison, ranked candidates, scrap or downtime lists | `.xlsx` |
+| A report or dashboard | the HTML page, per `artifact-style.md` |
+| A record (contract payload, day record, register row) | its contract's format, as below |
+
+**Never `.txt` or `.md` for a document.** A plain-text quote reads as a draft
+nobody finished, and it is what a person gets when no format is named.
+
+- **How.** Use the session's Word or Excel skill where there is one (Cowork
+ has both); else `python-docx` or `openpyxl` where already installed. Never
+ install a package for it and never hand-build the file's XML: a file Word
+ cannot open is worse than none. With no writer, write no file and say so in
+ one line: *"No Word copy this session: no Word writer available."* The
+ reply already holds the document.
+- **The plant's template.** A controlled document keeps the structure
+ `onboarding` captured. Where that example is a `.docx` in the documents
+ folder, start the Word copy from that file; otherwise use a plain layout
+ and keep the *template not on file* flag the document already carries.
+- **What goes in which file.** The customer's file holds only what the
+ sendable block holds. Internal figures (hours, rates, margin, the cost
+ build-up) go in their own file, the internal cost sheet, and never into the
+ customer's.
+- **Names.** What it is and its reference: `quote-Q-EXAMPLE-MEDICAL-4402A-01.docx`,
+ `cost-sheet-Q-EXAMPLE-MEDICAL-4402A-01.xlsx`, `NCR-2026-0141.docx`. Name each file in
+ the reply.
+
+A **record** is a handoff to another skill or a store: a contract payload (a
+downtime record, a geometry estimate), a register row, a pulse day record, a
+supplier bid record, a selection record, a sourcing-event row. **It is never
+pasted into the reply as a raw YAML or JSON block.** A quality manager, a
+buyer or an estimator should not have to read 150 lines of field names to
+find out what happened.
+
+Instead:
+
+1. **Save the full record** where its contract says, or to a file next to the
+ run's other outputs, and **name the file** in the reply.
+2. **Show a short table of the fields a person decides on**, under their
+ contract names so nothing is lost in translation — the key, the status,
+ and whichever of these the record has: `fields_missing`, `data_complete`,
+ `decided_by`, `decided_at`, `follows_recommendation`, `actuals_confidence`,
+ `geometry_path`, `reading_basis`, `approval`. One row per record, or one
+ row per field for a single record. Never more than about a dozen rows.
+3. **If the record cannot be saved** (no write access this session), print it
+ in full, **as a table, not a code block**, marked *not stored — paste this
+ back next time*.
+
+The person can always ask for the raw record ("show me the YAML"). Then print
+it.
+
+## Where the plant's memory lives
+
+### The plant setup, the rates and the open work: three private pages
+
+The plant profile and the plant's rates are written once, by `onboarding`, and
+every later run finds them with no folder, no project and nothing to upload.
+**Every skill that reads the profile or a rate first runs, from the task's own
+folder (never from inside the plugin's folder, which the script refuses)**
+
+ python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find
+
+**and does its `setup_page_first` step before anything else.** That step lists
+the user's artifacts for two private pages and brings them into the task:
+
+| Page | File | Holds |
+|---|---|---|
+| `Plant setup: <company>` | `setup/plant-context.txt` | The `## Plant context` block. No rate values, so it can be shared with teammates |
+| `Plant rates: <company>` | `setup/plant-rates.txt` | The `## Plant rates` block: each rate's value, state, who gave it and when. Its readable view shows states only. It stays private |
+| `Open work: <company>` | `setup/open-work.txt`, plus `inquiries/` and `sourcing/` | The three working blocks, the paused intake forms and the bid records. Its readable view shows references and states, never a price. Private |
+
+The pages are read and published with the artifact tools: `Artifact` in
+Claude Code, `mcp__claude-artifacts__*` in Cowork. Either counts. An older page
+may hold the same file as `.md` (`setup/plant-context.md`,
+`setup/plant-rates.md`); read that when the `.txt` file is not there.
+
+Then read the profile at `profile_path` and any rate at `rates_path`. **No page
+and no file at `profile_path`:** read the `## Plant context` block from
+`CLAUDE.local.md` (Claude Code) or the project's memory (Cowork); that is an
+older profile. No
+artifact tools, or a call to them refused: use the files as printed and say
+nothing about a page.
+
+**Saving** (onboarding's yes, or a value written back later): write the files
+at `profile_path` and `rates_path`, then follow `install`'s
+`after_any_change`, or for a first save: `render` each file (`--kind rates` for
+the rates file), read the page itself before publishing when it already exists,
+publish with the `file_path` and `files` printed, read the file back, and give
+`saved`'s line word for word. `"yes, folder only"` skips the pages; in Cowork
+the files then last only for this task, so say so. A rate value never goes in
+the setup file: `render` refuses it.
+
+### The open work: `Open work: <company>`
+
+Three blocks persist between conversations: `## Dashboards` (the dashboard
+URLs, `live-dashboard.md`), `## Open inquiries` (one line per paused RFQ,
+`contracts/intake-form.md`) and `## Sourcing events` (the supplier tracker,
+`supplier-quote-request`). With them go the files they point to: each paused
+intake form (`inquiries/<customer-slug>-<rfq_reference>.intake.txt`) and each
+ingested bid record and selection record
+(`sourcing/<event-id>/<supplier-slug>.bid.txt`, `decision.txt`). All of it
+lives on the third private page, **in Claude Code and in Cowork alike**
+whenever the artifact tools exist, so a new chat with no project and nothing
+attached picks up where the last one stopped. The headings are unchanged; a
+paused line closed out (quoted, declined, withdrawn; an event decided and
+closed by the buyer) moves to `## Closed` with its date, and its files are
+dropped 90 days later. A Closed line reads `- <reference> | <state> <close
+date>`: the close date is the first date after the reference.
+
+**Finding it**, in this order, every time a skill reads or writes one of the
+three blocks:
+
+1. **The page.** `find`'s `setup_page_first` step brings it in when it exists:
+ `install --kind work`, then the blocks are at `work_path` and the files
+ beside it.
+2. **An older block**: no page, but a block kept in memory
+ (`CLAUDE.local.md` in Claude Code, the project's memory in Cowork).
+ Read it. On this skill's next write, move it: `migrate --from <that file>
+ --company <company>`, publish, check `saved`, then say *"Moved your open
+ RFQs and supplier tracker to your Open work page. The old copy in [where]
+ is untouched; you can delete it."* Never delete or keep writing to the old
+ copy. A line whose intake file cannot be found keeps `file: missing`; ask
+ for the RFQ when it is resumed.
+3. **A table the person pastes**, as before. Never reconstruct a send history.
+4. **Nothing found**: ask, as before.
+
+**More than one `Plant setup:` page and no company named: ask which plant
+before reading any page.** A company's open work is the page titled exactly
+`Open work: <company>`, the same company string as its setup page. Never merge
+two companies' open work. No setup page at all: create the Open work page
+anyway, titled from the company the person names; if they name none, ask.
+Never "unnamed plant".
+
+**Writing** needs no approval gate: it is the person's working record, not
+plant configuration, and the gates inside each workflow are unchanged.
+Change one block, or one entry in it, with
+
+ python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py put --block "<block>" --entry <reference or event id> --text-file <file holding the new text> [--company "<company>"] --by <skill>
+
+(`--remove` drops the entry). Every other block and every other file is left
+byte for byte. Write an intake form or bid record as a `.txt` file at the path
+its line names, under `work_path`'s folder. Then save the page in the same
+turn: `put` prints `after_any_change` (prune, render, read the page just before
+publishing, publish, read every file back, `saved`). A first save publishes
+without a URL, titled as `render` prints. If the publish is refused because a
+newer version exists, re-read it, `install` it, re-run only this run's `put`
+and publish again; never force; after two refusals stop and print the block,
+marked not saved.
+
+**The skill's own result is what opens, never a memory page.** The person
+sees the artifact published last. When a run publishes its own result (a
+dashboard, a register, a report page) and also saves one of the three pages,
+save the page first and publish the result last. Where the order can't be kept
+(a first run that needs the result's URL for `## Dashboards`), finish by opening
+the result (`Artifact` action `open` with its URL, or the same call in
+`mcp__claude-artifacts__*`) and end the reply with the result's link. Never end
+on the setup, rates or Open work page unless saving it was the whole request.
+
+**Say "saved to your Open work page" only after `saved` returned `ok: true` in
+this run.** Otherwise print the block (and the form) in the reply, marked
+*Not saved to your Open work page: [reason]*. Example: *"Saved the sourcing
+tracker to your Open work page."*
+
+**No artifact tools, or a call refused:** write the blocks to `CLAUDE.local.md`
+at the workspace root (Claude Code) and the files to `plant-setup/open-work/`
+beside the task, and say once that they last only as long as that folder. If
+the workspace is a git repository and `CLAUDE.local.md` is not ignored, add it
+to `.gitignore` and say so. **Never** in the export folder, a shared or synced
+folder, or a file a repository commits.
+
+## Who said yes is asked, never inferred
+
+An approval, a decision, a confirmed rate or a selection record carries **the
+name the person gave**. It is never taken from the session account, an email
+address, git config, the operating-system user, or a file's metadata — the
+person at the keyboard is often not the person whose name belongs on a quote
+release or a supplier award.
+
+If the name has not been given in the conversation, **ask once**, in the same
+turn as the request for the yes: *"Who should I record as approving this?"*
+If they decline, record `not given` and say so. Never fill it in.
+
+## A system the profile lists as file-based is not "waiting to be connected"
+
+When the `### Systems` section says a system is `file`, that is the plant's
+decision, recorded at onboarding. A skill working from that system's exports
+says so — *"NetSuite: from the export, per your profile"* — and does **not**
+tell the person it "needs authorising" or give connector setup steps, unless
+they ask how to connect it. Where data a connector would have supplied is
+missing, name the export or document that would supply it.
+
+A system the profile lists as `live` that turns out not to be live this
+session is different: say it is not live right now, and give its setup row
+from `../skills/custom-connector/reference/known-systems.md`, word for word.
diff --git a/plugins/claude-for-manufacturing/shared/scheduling.md b/plugins/claude-for-manufacturing/shared/scheduling.md
new file mode 100644
index 00000000..58795eaf
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/scheduling.md
@@ -0,0 +1,91 @@
+# Scheduling — what the plugin provides, and what it does not
+
+Chain 3 is the only scheduled chain, and the reason it
+matters is simple: the morning report is rewritten overnight so it exists before anyone
+asks for it. That is the plugin's clearest demonstration of its own concept.
+
+**A plugin cannot schedule itself.** It ships skills — markdown that shapes how
+Claude works — not a running process. Nothing inside this repository can wake up
+at 4am. Pretending otherwise is how a plant ends up believing a report is being
+produced when nothing is producing it.
+
+So the responsibility splits, and both halves have to hold:
+
+| | |
+|---|---|
+| **The plugin provides** | A run that is safe to execute unattended: it asks nobody anything, it is idempotent, and it reports its own gaps rather than stalling on them |
+| **The host provides** | The trigger — whatever wakes a Claude session on a cadence |
+
+---
+
+## What "safe to execute unattended" actually requires
+
+Three properties, and each is a real constraint on how the skills are written.
+
+**It asks nobody anything.** There is no one at 4am to answer. Where an
+attended run would ask — which date range, which export to use when several are
+present — the unattended run takes the production-day range from the
+`## Plant context` block and says which it used. A run that blocks on a question
+produces nothing, and nothing is worse than a partial report because nobody
+finds out until the meeting.
+
+**It is idempotent.** A re-run for the same production day rewrites that day's
+report rather than appending a second one. Someone will re-run it — after a late
+export lands, or because the first run was mistrusted — and two reports for one
+day is worse than one, because now the meeting argues about which is right.
+
+**It reports gaps rather than failing on them.** If last night's export did not
+land, the run still completes and says so at the top. A missing export is a
+finding, not an exception. Silence, stale data, or a crashed run all read the
+same way to a supervisor at 6am: nothing to look at.
+
+The corollary is that **the approval-gate posture is what makes this safe at
+all.** Chain 3 writes to no system of record — it reads and produces a page. It
+is the only chain with no approval gate, and that is precisely why it is the
+only one that may run unattended. No other chain in this build should ever be
+scheduled.
+
+## How a plant actually schedules it
+
+Any mechanism that starts a Claude session on a cadence works. The plugin does
+not care which, and does not ship one:
+
+- **Claude Code's own scheduling**, where the customer runs Claude Code and it
+ is available to them
+- **The operating system** — cron, systemd timers, Task Scheduler — invoking
+ Claude headlessly against a prompt like *"run the morning production report
+ for yesterday"*
+- **A person**, which is a legitimate answer. Saying "morning report" at 6:15am
+ produces the same artifact. It costs the supervisor two minutes rather than
+ the ninety they typically spend assembling it by hand, and it is where
+ most plants will start
+
+The plugin's job is to make all three produce the same output. That is what
+idempotence and the no-questions rule buy.
+
+## What a skill may claim
+
+**A skill may say it is safe to run unattended.** It may describe the run as
+overnight, because that is the intended cadence and it shapes correct behavior —
+the production-day boundary, the freshness banner, the fallback date range.
+
+**A skill may not claim it schedules itself, or report a scheduled run as having
+happened.** "Chain 3 runs this overnight" describes the design. "I have
+scheduled the morning report" would be false, and no skill says it.
+
+**A skill may say the dashboard was updated**, but only when the publish
+call returned a URL in that same run, per `live-dashboard.md`. That is a
+statement about a call that ran. It is still never a statement about a
+schedule: *"Updated the Operations Command Center"* is allowed after a
+successful publish; *"the dashboard will update every morning"* is not, because
+nothing in the plugin makes that happen.
+
+**Whether a scheduled, unattended session can publish at all is unverified.**
+No scheduled run has been observed publishing or updating an artifact. So the
+pulse checks for the publish tools on every run, and when they are absent it
+falls back to the page in the conversation and says the dashboard was not
+updated. A skill never claims that a scheduled run published anything; only
+that run's own tool results can say so.
+
+If a customer asks the plugin to schedule something, the honest answer is this
+file: here is what the run needs, here is how to trigger it on your side.
diff --git a/plugins/claude-for-manufacturing/shared/scripts/plant_setup.py b/plugins/claude-for-manufacturing/shared/scripts/plant_setup.py
new file mode 100644
index 00000000..9848ed83
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/scripts/plant_setup.py
@@ -0,0 +1,1419 @@
+#!/usr/bin/env python3
+"""The plant setup page: the plant profile (## Plant context) kept as a private
+page in the user's Claude account, titled "Plant setup: <company>", so a new
+Cowork task finds it with no folder and no project.
+
+Three pages, all private. Onboarding writes the first two once; any skill
+creates the third on its first write:
+
+ "Plant setup: <company>" setup/plant-context.txt, the ## Plant context block.
+ No rate values: it can be shared with teammates.
+ "Plant rates: <company>" setup/plant-rates.txt, the ## Plant rates block with
+ the confirmed and placeholder rate values. Its
+ readable view shows each rate's state, never the
+ number. It stays private.
+ "Open work: <company>" setup/open-work.txt (## Dashboards, ## Open
+ inquiries, ## Sourcing events, ## Closed) plus the
+ paused intake forms (inquiries/*.intake.txt) and the
+ bid records (sourcing/<event-id>/*.txt). Holds
+ customer quantities and supplier prices, so its
+ readable view shows references and states only. It
+ stays private.
+
+Each page carries its file byte for byte plus a readable view. Claude publishes
+and reads the pages with its artifact tools (Artifact, or mcp__claude-artifacts__*
+in Cowork); this script only builds and checks
+files, so every skill still reads a real file. `--kind rates` or `--kind work`
+selects the other pages; the default is the setup page.
+
+ find [--company NAME] [--titles <setup page titles from the list call>...]
+ Prints {setup_page_first, profile_path, exists, rates_path,
+ rates_exists, work_path, work_exists, companies, company, persistent}.
+ Every skill runs it before reading the profile, and does the
+ setup_page_first step before anything else.
+ render --profile <file> --out <dir>
+ Writes <dir>/index.html and <dir>/setup/plant-context.txt. Prints the
+ publish arguments: {title, file_path, files, sha256}.
+ install --from <file read from the page> [--company NAME]
+ Checks the file is a plant profile with no rate values, then copies it
+ to profile_path, keeping the old copy in history/ when it differs.
+ Prints {profile_path, company, sha256, changed, persistent,
+ after_any_change}.
+ saved --from <file read back after publishing> --sha256 <x> --title <t>
+ Prints {ok, line}: the saved line only when the read-back matches.
+ stamp --profile <file>
+ Sets the Configured date to today after a value is written back.
+ put --block <name> [--entry KEY] (--text-file F | --text T | --remove)
+ [--company NAME] [--by SKILL]
+ Open work only: replaces one block, or one entry in it (a "### KEY"
+ section or a "- KEY" line), in the working copy at work_path, creating
+ it for --company when there is none. Every other byte stays as it was.
+ prune [--days 90]
+ Open work only: drops ## Closed lines older than N days and their files.
+ migrate --from <file holding older blocks> --company NAME
+ Lifts ## Dashboards, ## Open inquiries and ## Sourcing events verbatim
+ into the Open work working copy and copies any rfq/...intake.yaml they
+ name into inquiries/. Never edits or deletes the source.
+
+For --kind work, render takes --profile <work_path>, install takes --from <the
+folder the page's files were saved to>, and saved takes --from <the folder
+read back> --rendered <render's --out folder>.
+
+`--selftest` runs the checks at the bottom.
+"""
+
+import argparse
+import datetime
+import hashlib
+import html
+import json
+import os
+import pathlib
+import re
+import shutil
+import sys
+import tempfile
+
+TOOLS = "the artifact tools (Artifact, or mcp__claude-artifacts__* in Cowork)"
+LOCAL_DIR = "plant-setup"
+KINDS = {
+ "setup": {"prefix": "Plant setup: ", "heading": "Plant context",
+ "data": "setup/plant-context.txt", "old": "setup/plant-context.md",
+ "name": "plant-context.md",
+ "noun": "plant setup page"},
+ "rates": {"prefix": "Plant rates: ", "heading": "Plant rates",
+ "data": "setup/plant-rates.txt", "old": "setup/plant-rates.md",
+ "name": "plant-rates.md",
+ "noun": "plant rates page"},
+ "work": {"prefix": "Open work: ", "heading": "Open work",
+ "data": "setup/open-work.txt", "old": None,
+ "name": "open-work.md",
+ "noun": "Open work page", "dirs": ["inquiries", "sourcing"]},
+}
+WORK_DIR = "open-work"
+WORK_BLOCKS = ("Dashboards", "Open inquiries", "Sourcing events", "Closed")
+SIZE_WARN = 1024 * 1024
+TITLE_PREFIX = KINDS["setup"]["prefix"]
+DATA_PATH = KINDS["setup"]["data"]
+PROFILE_NAME = KINDS["setup"]["name"]
+MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
+RESULT_LAST = ("If this run also publishes its own result (a dashboard, register or report "
+ "page), save this page first and publish the result last; if the result had to "
+ "come first, finish by opening the result (action open with its url) and end the "
+ "reply with its link, so the person sees the result, not this page.")
+NOT_SAVED_LINE = ("Not saved to your %s: the copy read back did not match. "
+ "The page is unchanged; ask me to save it again.")
+
+
+def _block_re(kind):
+ return re.compile(r"^##\s*%s\s*$(.*?)(?=^##\s(?!#)|\Z)" % KINDS[kind]["heading"], re.M | re.S)
+
+
+BLOCK_RE = _block_re("setup")
+RATES_RE = re.compile(r"^###\s*Commercial rates\s*$(.*?)(?=^#{2,3}\s|\Z)", re.M | re.S)
+EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
+
+
+class SetupError(Exception):
+ pass
+
+
+def _sha(path):
+ return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()
+
+
+def _field(block, label):
+ m = re.search(r"\*\*%s:\*\*[ \t]*(.+)" % re.escape(label), block)
+ return m.group(1).strip() if m else None
+
+
+def title_for(company, kind="setup"):
+ return KINDS[kind]["prefix"] + (company or "unnamed plant")
+
+
+def problems(text, kind="setup"):
+ """Why this text cannot be saved as that page: a list of plain sentences,
+ empty when it can. Names fields, never values. The setup page holds no
+ rate value (those go on the rates page); neither holds an email address."""
+ out = []
+ if kind == "setup":
+ # every line under Commercial rates, and under a Plant rates block kept in the same file
+ secs = [m.group(1) for m in (RATES_RE.search(text), _block_re("rates").search(text)) if m]
+ for line in "\n".join(secs).splitlines():
+ m = re.match(r"^\s*-\s*\*\*(.+?):\*\*\s*(.*)$", line)
+ if not m:
+ why = ("a rate value sits outside a rate line (a sub-bullet, a table or a paragraph); "
+ "rate values go on the rates page")
+ if not line.lstrip().startswith("#") and _no_values(line) != line and why not in out:
+ out.append(why)
+ continue
+ rest = re.sub(r"\b\d{4}-\d{2}-\d{2}\b", "", m.group(2)) # dates
+ rest = re.sub(r"\bMFG_\w+", "", rest) # variable names
+ why = ("the %s line holds a rate value; rate values go on the "
+ "rates page, and the setup records the state only" % m.group(1))
+ if re.search(r"\d", rest) and why not in out:
+ out.append(why)
+ if EMAIL_RE.search(text):
+ out.append("it holds an email address; record a role or the name the person gave")
+ return out
+
+
+def read_profile(path, kind="setup"):
+ """{company, version, text} for that page's file, or SetupError."""
+ try:
+ text = pathlib.Path(path).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as e:
+ raise SetupError("the file could not be read (%s)" % e)
+ m = _block_re(kind).search(text)
+ if not m:
+ raise SetupError("the file has no ## %s block" % KINDS[kind]["heading"])
+ company = _field(m.group(1), "Company")
+ if not company:
+ raise SetupError("the file names no company")
+ version = _field(m.group(1), "Profile version")
+ if kind == "setup" and not version:
+ raise SetupError("the profile has no Profile version line")
+ if kind == "work":
+ version = _field(m.group(1), "Format version")
+ if not version:
+ raise SetupError("the Open work file has no Format version line")
+ return {"company": company, "version": version, "text": text}
+
+
+def _slug(name):
+ return re.sub(r"[^a-z0-9]+", "-", (name or "").lower()).strip("-")
+
+
+PLUGIN_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
+
+
+def profile_path(cwd=None, kind="setup"):
+ """Where this task's working copy lives: {path, persistent}. Never inside
+ the plugin's own folder: run from there, the copy would land in the
+ installed plugin (or a git checkout of it), so that is refused."""
+ name = KINDS[kind]["name"]
+ if kind == "work":
+ name = "%s/%s" % (WORK_DIR, name)
+ data = os.environ.get("CLAUDE_PLUGIN_DATA")
+ if data and os.path.isdir(data) and os.access(data, os.W_OK):
+ return {"path": str(pathlib.Path(data) / name), "persistent": True}
+ base = pathlib.Path(cwd or os.getcwd()).resolve()
+ if base == PLUGIN_ROOT or PLUGIN_ROOT in base.parents:
+ raise SetupError("run this from the task's own folder, not from inside the plugin's "
+ "folder (%s): cd back to the folder the task started in" % PLUGIN_ROOT)
+ return {"path": str(base / LOCAL_DIR / name), "persistent": False}
+
+
+# --- find: the step every skill runs first -----------------------------------
+
+def setup_page_step(company=None):
+ script = pathlib.Path(__file__).resolve()
+ name = company or "<company>"
+ return ("Required before reading the plant profile or any rate, once per conversation, even "
+ "when profile_path does not exist yet: if you have %s, list the user's artifacts "
+ "(scope all) and look for '%s' and '%s'. If more than one 'Plant setup:' page exists "
+ "and the user has not named the company, ask which plant before reading any page "
+ "(run find again with --titles and the titles listed; companies names them). For each "
+ "page found, read its file with those tools (action read, path %s or %s; an older page "
+ "has %s or %s instead; never retype it), then run: python3 \"%s\" install "
+ "--from <the saved file> --company \"<company>\" (add --kind rates for the rates "
+ "file), and read profile_path and rates_path. If this skill reads or writes "
+ "## Dashboards, ## Open inquiries or ## Sourcing events, also look for '%s': read %s "
+ "and then every file it names and every file the page lists (action read with paths, or "
+ "one read per file) into one folder, keeping the page's paths, and run install --kind "
+ "work --from <that folder> --company \"<company>\"; the blocks are then at work_path. "
+ "Not found, no artifact tools, or a call refused: read the paths as printed and say "
+ "nothing about a page. Never show a rate value from rates_path outside an internal "
+ "artifact."
+ % (TOOLS, title_for(name), title_for(name, "rates"), KINDS["setup"]["data"],
+ KINDS["rates"]["data"], KINDS["setup"]["old"], KINDS["rates"]["old"], script,
+ title_for(name, "work"), KINDS["work"]["data"]))
+
+
+def companies_from(titles):
+ """The companies named by 'Plant setup: <company>' titles, in order, once each."""
+ out = []
+ for t in titles or []:
+ t = (t or "").strip()
+ if t.startswith(TITLE_PREFIX):
+ c = t[len(TITLE_PREFIX):].strip()
+ if c and c not in out:
+ out.append(c)
+ return out
+
+
+def find(company=None, cwd=None, titles=None):
+ loc = profile_path(cwd) # SetupError when run from inside the plugin's folder
+ rates = profile_path(cwd, "rates")["path"]
+ work = profile_path(cwd, "work")["path"]
+ out = {"setup_page_first": setup_page_step(company), "profile_path": loc["path"],
+ "exists": os.path.isfile(loc["path"]), "rates_path": rates,
+ "rates_exists": os.path.isfile(rates), "work_path": work,
+ "work_exists": os.path.isfile(work), "companies": companies_from(titles),
+ "company": None, "persistent": loc["persistent"]}
+ if len(out["companies"]) > 1 and not company:
+ out["ask_which_plant"] = ("More than one plant has a setup page (%s). Ask which plant "
+ "before reading any page." % ", ".join(out["companies"]))
+ if out["exists"]:
+ try:
+ out["company"] = read_profile(loc["path"])["company"]
+ except SetupError as e:
+ out["error"] = str(e)
+ return out
+
+
+# --- render: the page and its file -------------------------------------------
+
+def _inline(text):
+ out = html.escape(text, quote=False)
+ out = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", out)
+ return re.sub(r"`([^`]+)`", r"<code>\1</code>", out)
+
+
+def state_only(item):
+ """A rate line as its state and who gave it, without the number:
+ 'Labor rate: confirmed 71.00/hr - given by Pat Doyle' -> 'Labor rate: confirmed - given by Pat Doyle'."""
+ m = re.match(r"^(\*\*.+?:\*\*)\s*(.*)$", item)
+ if not m:
+ return _no_values(item)
+ head, sep, tail = m.group(2).partition(" - ")
+ tail = _no_values(tail)
+ if not re.search(r"\d", re.sub(r"\bMFG_\w+", "", head)):
+ return "%s %s%s%s" % (m.group(1), head, sep, tail)
+ state = next((w for w in head.split() if not re.search(r"\d", w)), "set")
+ return "%s %s%s" % (m.group(1), state, (" - " + tail) if tail else "")
+
+
+def _no_values(text):
+ """Text on the rates view with its numbers hidden. Dates, MFG_ names and
+ numbers inside a reference (FY25, PN-4471) stay. A word or reference is
+ matched whole first, so both ends of a range (30-45%) and a bare decimal
+ (.28) are hidden while PN-4471 is not."""
+ return re.sub(r"\d{4}-\d{2}-\d{2}|[A-Za-z]\w*(?:-\w+)*"
+ r"|(?<![\w.])[$€£]?\d+(?:,\d{3})*(?:\.\d+)?%?(?:/\w+)?|(?<!\w)[$€£]?\.\d+%?(?:/\w+)?",
+ lambda m: m.group(0) if m.group(0)[0].isalpha() or m.group(0)[4:5] == "-" else "[on file]", text)
+
+
+def details_html(block, hide_values=False):
+ """A block as panels: a ### heading starts a panel, bullets become a
+ list, pipe tables become tables. hide_values shows rate lines as their
+ state only."""
+ out, in_list, in_table, open_panel = [], False, False, False
+
+ def close():
+ nonlocal in_list, in_table
+ if in_list:
+ out.append("</ul>")
+ in_list = False
+ if in_table:
+ out.append("</tbody></table>")
+ in_table = False
+
+ for line in block.splitlines():
+ s = line.strip()
+ if not s:
+ continue
+ if s.startswith("### "):
+ close()
+ if open_panel:
+ out.append("</section>")
+ out.append('<section class="panel"><h2>%s</h2>' % html.escape(s[4:]))
+ open_panel = True
+ continue
+ if not open_panel:
+ out.append('<section class="panel"><h2>Plant</h2>')
+ open_panel = True
+ if s.startswith("|"):
+ cells = [c.strip() for c in s.strip("|").split("|")]
+ if all(re.fullmatch(r":?-{2,}:?", c) for c in cells):
+ continue
+ if not in_table:
+ close()
+ out.append("<table><tbody>")
+ in_table = True
+ out.append("<tr>%s</tr>" % "".join(
+ "<td>%s</td>" % _inline(_no_values(c) if hide_values else c) for c in cells))
+ continue
+ if s.startswith("- "):
+ if not in_list:
+ close()
+ out.append("<ul>")
+ in_list = True
+ out.append("<li>%s</li>" % _inline(state_only(s[2:]) if hide_values else s[2:]))
+ continue
+ if out and out[-1].startswith("<p>") and not in_list and not in_table:
+ out[-1] = out[-1][:-4] + " " + _inline(_no_values(s) if hide_values else s) + "</p>" # a wrapped paragraph stays one
+ continue
+ close()
+ out.append("<p>%s</p>" % _inline(_no_values(s) if hide_values else s))
+ close()
+ if open_panel:
+ out.append("</section>")
+ return "\n".join(out)
+
+
+PAGE = """<title>{title}</title>
+<meta name="claude:viewport-fit-sides" content="cover">
+<style>
+/* One column of panels, a record the plant reads, not a dashboard. */
+:root {{ --bg:#f7f8f6; --panel:#ffffff; --fg:#1c211e; --muted:#5f6862; --line:#dde2dd; --accent:#2f6b4f; }}
+@media (prefers-color-scheme: dark) {{ :root:not([data-theme="light"]) {{
+ --bg:#161a18; --panel:#1e2421; --fg:#e6ebe7; --muted:#9aa59e; --line:#323a35; --accent:#7cc3a0;
+ color-scheme:dark; }} }}
+:root[data-theme="dark"] {{ --bg:#161a18; --panel:#1e2421; --fg:#e6ebe7; --muted:#9aa59e; --line:#323a35;
+ --accent:#7cc3a0; color-scheme:dark; }}
+body {{ background:var(--bg); color:var(--fg); margin:0; padding-block:32px;
+ padding-left:max(16px, env(safe-area-inset-left, 0px)); padding-right:max(16px, env(safe-area-inset-right, 0px));
+ font:15px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif; }}
+main {{ max-width:860px; margin:0 auto; display:flex; flex-direction:column; gap:16px; }}
+h1 {{ font-size:24px; margin:0; text-wrap:balance; }}
+.sub {{ color:var(--muted); margin:0 0 8px; max-width:65ch; }}
+.panel {{ background:var(--panel); border:1px solid var(--line); border-radius:6px;
+ padding:16px 20px; overflow-wrap:anywhere; min-width:0; }}
+h2 {{ font-size:13px; letter-spacing:.06em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }}
+ul {{ margin:4px 0; padding-left:20px; }}
+li, p {{ margin:2px 0; }}
+table {{ border-collapse:collapse; width:100%; display:block; overflow-x:auto;
+ font-variant-numeric:tabular-nums; }}
+td, th {{ border-top:1px solid var(--line); padding:4px 8px; vertical-align:top; text-align:left; }}
+th {{ font-size:12px; color:var(--muted); font-weight:600; }}
+.stale {{ color:var(--accent); }}
+code {{ font-size:13px; }}
+</style>
+<main>
+<h1>{company}</h1>
+<p class="sub">{lede} {when} To change it, ask Claude;
+edits made on this page are not read.</p>
+{body}
+</main>
+"""
+
+
+LEDES = {
+ "setup": "The plant setup Claude reads at the start of every manufacturing task. "
+ "Rate values are not kept here.",
+ "rates": "The plant's commercial rates, read by Claude for internal costing only. Each "
+ "rate shows its state here; the numbers are never shown on this page. Keep this "
+ "page private.",
+}
+
+
+def render(profile, out, kind="setup"):
+ if kind == "work":
+ return render_work(profile, out)
+ p = read_profile(profile, kind)
+ bad = problems(p["text"], kind)
+ if bad:
+ raise SetupError("not saved: " + "; ".join(bad))
+ block = _block_re(kind).search(p["text"]).group(1)
+ data = KINDS[kind]["data"]
+ out = pathlib.Path(out)
+ (out / "setup").mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(profile, out / data)
+ title = title_for(p["company"], kind)
+ page = PAGE.format(title=html.escape(title), company=html.escape(title),
+ lede=LEDES[kind],
+ when="Configured %s." % html.escape(_field(block, "Configured") or "date not recorded"),
+ body=details_html(block, hide_values=(kind == "rates")))
+ (out / "index.html").write_text(page, encoding="utf-8")
+ return {"title": title, "file_path": str(out / "index.html"),
+ "files": {data: str(out / data)},
+ "sha256": _sha(out / data)}
+
+
+# --- install: the page's copy into this task ----------------------------------
+
+def _keep_history(dest):
+ hist = dest.parent / "history"
+ hist.mkdir(parents=True, exist_ok=True)
+ stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
+ kept = hist / ("%s-%s.md" % (dest.stem, stamp))
+ shutil.copyfile(dest, kept)
+ return kept
+
+
+def install(src, company=None, cwd=None, kind="setup"):
+ if kind == "work":
+ return install_work(src, company, cwd)
+ p = read_profile(src, kind)
+ bad = problems(p["text"], kind)
+ if bad:
+ raise SetupError("not installed: " + "; ".join(bad))
+ if company and _slug(company) != _slug(p["company"]):
+ raise SetupError("the page holds %s's setup, not %s's" % (p["company"], company))
+ loc = profile_path(cwd, kind)
+ dest = pathlib.Path(loc["path"])
+ changed = not dest.is_file() or _sha(dest) != _sha(src)
+ if changed:
+ if dest.is_file():
+ _keep_history(dest)
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=str(dest.parent))
+ os.close(fd)
+ shutil.copyfile(src, tmp)
+ os.replace(tmp, dest)
+ if _sha(dest) != _sha(src):
+ raise SetupError("the copy in this task does not match the page")
+ return {"profile_path": str(dest), "company": p["company"], "sha256": _sha(dest),
+ "changed": changed, "persistent": loc["persistent"]}
+
+
+def after_any_change(kind="setup"):
+ script = pathlib.Path(__file__).resolve()
+ if kind == "work":
+ return ("This tree came from the Open work page. Whenever a block changes later in this "
+ "conversation, change it only with python3 \"{script}\" put (one block, or one "
+ "entry, at a time; never edit another block), then save the page in the same turn, "
+ "without asking: run prune, then render --kind work --profile <work_path> --out <a "
+ "new empty folder>; read the page itself with {tools}, action read and url only, "
+ "immediately before the publish; publish to this page's url with the file_path and "
+ "files render printed (a refusal saying the content leaves out the live page's text "
+ "is answered by publishing the same files once more). If the publish is refused "
+ "because a newer version exists: read that version's files into a new folder, run "
+ "install --kind work --from it, run this run's same put commands again, render and "
+ "publish again. Never force. After two such refusals, stop and print the block, "
+ "marked not saved, with the reason. Then read every file back from the page (action "
+ "read with paths, or one read per file) into a new folder and run saved --kind work "
+ "--from <that folder> --rendered <render's out folder> --title <render's title>, and "
+ "show its line word for word. {last}").format(script=script, tools=TOOLS, last=RESULT_LAST)
+ path_word = "profile_path" if kind == "setup" else "rates_path"
+ kind_flag = " --kind rates" if kind == "rates" else ""
+ return ("This file came from the {noun}. Whenever {path_word} is changed later in this "
+ "conversation (a value the user confirmed, a reconfigure), update the page as part of "
+ "the same save, without asking again: run python3 \"{script}\" stamp --profile "
+ "<that path>, then render --profile <that path> --out <a working folder>{kind_flag}; "
+ "read the page itself with {tools}, action read and url only (reading the "
+ "file does not count), in a step before the publish; publish to this page's url with the "
+ "file_path and files render printed (the page is rebuilt from the file on purpose, so "
+ "a refusal saying the content leaves out the live page's text is answered by "
+ "publishing the same files once more); then read {data} back from the page and run "
+ "saved --from <that file> --sha256 <render's sha256> --title <render's title>, and "
+ "show its line word for word. {last}").format(last=RESULT_LAST, noun=KINDS[kind]["noun"], path_word=path_word,
+ script=script, kind_flag=kind_flag,
+ data=KINDS[kind]["data"], tools=TOOLS)
+
+
+# --- saved and stamp ----------------------------------------------------------
+
+def saved(src, sha256, title, when=None, rendered=None):
+ if rendered or (title or "").startswith(KINDS["work"]["prefix"]):
+ return saved_work(src, rendered or "", title, when)
+ noun = KINDS["rates" if (title or "").startswith(KINDS["rates"]["prefix"]) else "setup"]["noun"]
+ if not pathlib.Path(src).is_file() or _sha(src) != sha256:
+ return {"ok": False, "line": NOT_SAVED_LINE % noun}
+ when = when or datetime.datetime.now().astimezone()
+ stamp = "%d %s %d %02d:%02d" % (when.day, MONTHS[when.month - 1], when.year,
+ when.hour, when.minute)
+ return {"ok": True, "line": "Saved to your %s in Claude (%s), %s." % (noun, title, stamp)}
+
+
+def stamp(profile, when=None):
+ """Set the Configured line to today. Only that line changes."""
+ path = pathlib.Path(profile)
+ text = path.read_text(encoding="utf-8")
+ day = (when or datetime.date.today()).isoformat()
+ new, n = re.subn(r"^([ \t]*-[ \t]*\*\*Configured:\*\*[ \t]*).*$", # one line: an empty value stays on its own line
+ lambda m: m.group(1) + ("" if m.group(1)[-1] in " \t" else " ") + day, text, count=1, flags=re.M)
+ if n == 0:
+ raise SetupError("the profile has no Configured line")
+ fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=str(path.parent))
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write(new)
+ os.replace(tmp, str(path))
+ return {"configured": day}
+
+
+# --- the Open work page: three working blocks plus the files they name --------
+
+FILE_REF_RE = re.compile(r"\b((?:inquiries|sourcing)/[^\s|,;()`]+)")
+WORK_RATE_RE = re.compile(r"(?im)^[\s\-*]*(?:\*\*)?\s*(labou?r[ _-]?rate|burden(?:[ _-]?rate)?|"
+ r"margin(?:[ _-]?(?:rate|rules|pct|percent))?)\s*:\s*(?:\*\*)?([^\n]*)$")
+CONTACT_LINE_RE = re.compile(r"(?im)^\s*(?:contact\s*:|email\s*:).*$")
+MONEY_RE = re.compile(r"(?:[$€£]\s?\d[\d,]*(?:\.\d+)?|\b\d[\d,]*(?:\.\d+)?\s?(?:USD|EUR|GBP|CAD|MXN)\b"
+ r"|\b(?:USD|EUR|GBP|CAD|MXN)\s?\d[\d,]*(?:\.\d+)?)")
+ISO_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
+LEGACY_INTAKE_RE = re.compile(r"(?<![\w/])(?:file:\s*)?((?:[\w.-]+/)*rfq/[^\s|,;()`]+\.intake\.ya?ml)")
+
+
+def _work_root(src):
+ """(root, index) for an Open work tree: the folder the page's files were
+ saved to (index at setup/open-work.txt), or the working copy (open-work.md)."""
+ src = pathlib.Path(src)
+ if src.is_dir():
+ for cand in (src / KINDS["work"]["data"], src / KINDS["work"]["name"]):
+ if cand.is_file():
+ return src, cand
+ raise SetupError("no %s or %s in %s" % (KINDS["work"]["data"], KINDS["work"]["name"], src))
+ if src.name == pathlib.Path(KINDS["work"]["data"]).name and src.parent.name == "setup":
+ return src.parent.parent, src
+ return src.parent, src
+
+
+def _attached(root):
+ """Every file under inquiries/ and sourcing/, as page paths."""
+ out = []
+ for d in KINDS["work"]["dirs"]:
+ base = pathlib.Path(root) / d
+ if base.is_dir():
+ out += sorted(q.relative_to(root).as_posix() for q in base.rglob("*")
+ if q.is_file() and not q.name.startswith("."))
+ return out
+
+
+def _block(text, name):
+ m = re.search(r"^##[ \t]*%s[ \t]*$\n?(.*?)(?=^##\s(?!#)|\Z)" % re.escape(name), text, re.M | re.S)
+ return m.group(1) if m else ""
+
+
+def work_problems(root, index):
+ """Why this tree cannot be saved as the Open work page. Names files and
+ fields, never values. No labour, burden or margin rate anywhere; no email
+ address except an intake form's contact; every file a line names exists;
+ every attached file is .txt (Cowork refuses other uploads)."""
+ root, out = pathlib.Path(root), []
+ files = [(KINDS["work"]["data"], pathlib.Path(index))] + [(r, root / r) for r in _attached(root)]
+ for rel, path in files:
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as e:
+ out.append("%s could not be read (%s)" % (rel, e))
+ continue
+ for m in WORK_RATE_RE.finditer(text):
+ rest = re.sub(r"\bMFG_\w+", "", ISO_RE.sub("", m.group(2)))
+ if re.search(r"\d", rest):
+ out.append("%s holds a %s value; rates belong on the rates page" % (rel, m.group(1)))
+ body = CONTACT_LINE_RE.sub("", text) if ".intake." in rel else text
+ if EMAIL_RE.search(body):
+ out.append("%s holds an email address outside an intake form's contact" % rel)
+ if rel != KINDS["work"]["data"] and not rel.endswith(".txt"):
+ out.append("%s is not a .txt file; save page files as .txt" % rel)
+ index_text = pathlib.Path(index).read_text(encoding="utf-8", errors="replace")
+ for rel in sorted(set(FILE_REF_RE.findall(index_text))):
+ rel = rel.rstrip(".")
+ if not (root / rel).is_file():
+ out.append("%s is named in the blocks but is not in the folder" % rel)
+ return out
+
+
+def read_work(src):
+ root, index = _work_root(src)
+ p = read_profile(index, "work")
+ bad = work_problems(root, index)
+ if bad:
+ raise SetupError("; ".join(bad))
+ p.update({"root": root, "index": index, "files": _attached(root)})
+ return p
+
+
+def _tree_shas(root, index):
+ out = {KINDS["work"]["data"]: _sha(index)}
+ for rel in _attached(root):
+ out[rel] = _sha(pathlib.Path(root) / rel)
+ return out
+
+
+def _cells(line):
+ return [c.strip() for c in line.strip().strip("|").split("|")]
+
+
+def _no_money(s):
+ return MONEY_RE.sub("[on file]", s)
+
+
+def _kv(fields):
+ out = {}
+ for f in fields:
+ k, sep, v = f.partition(":")
+ if sep and re.fullmatch(r"[\w ]+", k.strip()):
+ out[k.strip().lower().replace(" ", "_")] = v.strip()
+ return out
+
+
+def _days_past(due, today):
+ try:
+ d = datetime.date.fromisoformat(due)
+ except ValueError:
+ return None
+ return (today - d).days if today > d else None
+
+
+def _table(head, rows, empty):
+ if not rows:
+ return "<p>%s</p>" % empty
+ th = "".join("<th>%s</th>" % html.escape(h) for h in head)
+ body = "".join("<tr>%s</tr>" % "".join("<td>%s</td>" % c for c in r) for r in rows)
+ return "<table><thead><tr>%s</tr></thead><tbody>%s</tbody></table>" % (th, body)
+
+
+def work_view(text, today=None):
+ """The readable view: references and states, never a price or a total."""
+ today = today or datetime.date.today()
+ esc = lambda s: html.escape(_no_money(s or ""), quote=False)
+ inq = []
+ for line in _block(text, "Open inquiries").splitlines():
+ if not line.strip().startswith("- "):
+ continue
+ f = _cells(line.strip()[2:])
+ kv = _kv(f[2:])
+ stale_after = kv.get("stale_after", "")
+ stale = (stale_after and kv.get("bid_decision_state") != "declined"
+ and _days_past(stale_after, today) is not None)
+ inq.append([esc(f[0]), esc(f[1] if len(f) > 1 else ""), esc(kv.get("paused_at_step", "")),
+ esc(kv.get("waiting_on", "")),
+ esc(stale_after) + (' <strong class="stale">stale</strong>' if stale else "")])
+ src, event, desc, status, head = [], None, "", "", []
+ for line in _block(text, "Sourcing events").splitlines():
+ s = line.strip()
+ if s.startswith("### "):
+ event, _, desc = s[4:].partition(" — ")
+ if not desc:
+ event, _, desc = s[4:].partition(" - ")
+ status, head = "", []
+ continue
+ if event and not s.startswith("|") and "Status:" in s:
+ status = _kv(_cells(s)).get("status", "")
+ continue
+ if event and s.startswith("|"):
+ cells = _cells(s)
+ if all(re.fullmatch(r":?-{2,}:?", c) for c in cells):
+ continue
+ if not head:
+ head = [c.lower() for c in cells]
+ continue
+ row = dict(zip(head, cells))
+ resp = row.get("response", "").strip()
+ state = ("no response" if resp.lower() in ("", "-", "none") or resp.lower().startswith("no response")
+ else resp.split()[0].rstrip(","))
+ due = row.get("due", "")
+ late = _days_past(due, today) if state == "no response" else None
+ src.append([esc(event.strip()), esc(desc.strip()), esc(row.get("supplier", "")),
+ esc(status), esc(due), esc(state), str(late) if late else "-"])
+ dash = []
+ for line in _block(text, "Dashboards").splitlines():
+ m = re.match(r"^\s*-\s*(.*?)\s*[—:-]*\s*(https?://\S+)", line)
+ if m:
+ dash.append([esc(m.group(1).rstrip(" —-:")),
+ '<a href="%s">%s</a>' % (html.escape(m.group(2)), html.escape(m.group(2)))])
+ closed = sum(1 for l in _block(text, "Closed").splitlines() if l.strip().startswith("- "))
+ return "\n".join([
+ '<section class="panel"><h2>Open inquiries</h2>%s</section>' % _table(
+ ["Reference", "Customer", "Paused at step", "Waiting on", "Stale after"], inq, "None open."),
+ '<section class="panel"><h2>Sourcing events</h2>%s</section>' % _table(
+ ["Event", "Part", "Supplier", "Status", "Due", "Response", "Days past due"], src, "None open."),
+ '<section class="panel"><h2>Dashboards</h2>%s</section>' % _table(["Title", "Link"], dash, "None saved."),
+ '<section class="panel"><h2>Closed</h2><p>%d closed item%s kept for 90 days.</p></section>'
+ % (closed, "" if closed == 1 else "s")])
+
+
+def render_work(profile, out, today=None):
+ w = read_work(profile)
+ out = pathlib.Path(out).resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ files = {}
+ for rel, path in [(KINDS["work"]["data"], w["index"])] + [(r, w["root"] / r) for r in w["files"]]:
+ dest = out / rel
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(path, dest)
+ files[rel] = str(dest)
+ title = title_for(w["company"], "work")
+ block = _block_re("work").search(w["text"]).group(1)
+ page = PAGE.format(title=html.escape(title), company=html.escape(title),
+ lede="Private working record for %s. Holds customer and supplier pricing. "
+ "Don't share. The prices stay in the files; this view shows references "
+ "and states only." % html.escape(w["company"]),
+ when="Last written %s." % html.escape(_field(block, "Last written") or "date not recorded"),
+ body=work_view(w["text"], today))
+ (out / "index.html").write_text(page, encoding="utf-8")
+ shas = {rel: _sha(p) for rel, p in files.items()}
+ (out / ".manifest.json").write_text(json.dumps(shas, indent=1), encoding="utf-8")
+ res = {"title": title, "file_path": str(out / "index.html"), "files": files,
+ "sha256": shas[KINDS["work"]["data"]], "rendered": str(out)}
+ if pathlib.Path(w["index"]).stat().st_size > SIZE_WARN:
+ res["warning"] = ("The Open work index is over 1 MB. Suggest closing old sourcing events "
+ "and inquiries.")
+ return res
+
+
+def install_work(src, company=None, cwd=None):
+ w = read_work(src)
+ if company and _slug(company) != _slug(w["company"]):
+ raise SetupError("the page holds %s's open work, not %s's" % (w["company"], company))
+ loc = profile_path(cwd, "work")
+ dest_index = pathlib.Path(loc["path"])
+ dest = dest_index.parent
+ new = _tree_shas(w["root"], w["index"])
+ old = _tree_shas(dest, dest_index) if dest_index.is_file() else None
+ changed = new != old
+ if changed:
+ dest.mkdir(parents=True, exist_ok=True)
+ if old is not None:
+ hist = dest / "history" / datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
+ hist.mkdir(parents=True)
+ for name in [KINDS["work"]["name"]] + KINDS["work"]["dirs"]:
+ if (dest / name).exists():
+ shutil.move(str(dest / name), str(hist / name))
+ tmp = pathlib.Path(tempfile.mkdtemp(prefix=".tmp-", dir=str(dest)))
+ shutil.copyfile(w["index"], tmp / KINDS["work"]["name"])
+ for rel in w["files"]:
+ (tmp / rel).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(w["root"] / rel, tmp / rel)
+ for name in [KINDS["work"]["name"]] + KINDS["work"]["dirs"]:
+ if (tmp / name).exists():
+ os.replace(str(tmp / name), str(dest / name))
+ shutil.rmtree(tmp, ignore_errors=True)
+ if _tree_shas(dest, dest_index) != new:
+ raise SetupError("the copy in this task does not match the page")
+ return {"work_path": str(dest_index), "company": w["company"], "sha256": new[KINDS["work"]["data"]],
+ "files": w["files"], "changed": changed, "persistent": loc["persistent"]}
+
+
+def saved_work(src, rendered, title, when=None):
+ """ok only when the index and every attached file read back match render."""
+ try:
+ want = json.loads((pathlib.Path(rendered) / ".manifest.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {"ok": False, "line": "Not saved to your Open work page: render's record of the "
+ "files was not found, so the read-back could not be checked."}
+ bad = [rel for rel, sha in sorted(want.items())
+ if not (pathlib.Path(src) / rel).is_file() or _sha(pathlib.Path(src) / rel) != sha]
+ if bad:
+ return {"ok": False, "line": "Not saved to your Open work page: %s did not read back the "
+ "same. Ask me to save it again." % ", ".join(bad), "differs": bad}
+ when = when or datetime.datetime.now().astimezone()
+ stamp_ = "%d %s %d %02d:%02d" % (when.day, MONTHS[when.month - 1], when.year, when.hour, when.minute)
+ return {"ok": True, "line": "Saved to your Open work page in Claude (%s), %s." % (title, stamp_)}
+
+
+def _new_work(company, when):
+ return ("## Open work\n\n- **Company:** %s\n- **Format version:** 1\n- **Last written:** %s\n\n"
+ "## Dashboards\n\n## Open inquiries\n\n## Sourcing events\n\n## Closed\n"
+ % (company, when))
+
+
+def _write(path, text):
+ path = pathlib.Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=str(path.parent))
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write(text)
+ os.replace(tmp, str(path))
+
+
+def put_block(doc, block, text=None, entry=None, remove=False):
+ """doc with one block, or one entry in it, replaced. Nothing else changes."""
+ if block not in WORK_BLOCKS:
+ raise SetupError("no block named %s; the blocks are %s" % (block, ", ".join(WORK_BLOCKS)))
+ m = re.search(r"^##[ \t]*%s[ \t]*$\n?(.*?)(?=^##\s(?!#)|\Z)" % re.escape(block), doc, re.M | re.S)
+ if not m:
+ doc = doc.rstrip("\n") + "\n\n## %s\n\n" % block
+ m = re.search(r"^##[ \t]*%s[ \t]*$\n?(.*?)(?=^##\s(?!#)|\Z)" % re.escape(block), doc, re.M | re.S)
+ body = m.group(1)
+ new = (text or "").strip("\n")
+ if entry is None:
+ nb = "" if remove else "\n" + new + "\n"
+ else:
+ sec = re.search(r"^###\s*%s(?=\s|$).*?(?=^###\s|\Z)" % re.escape(entry), body, re.M | re.S)
+ line = re.search(r"^\s*-\s*%s(?=\s|\||$).*\n?" % re.escape(entry), body, re.M)
+ hit = sec or line
+ if hit:
+ rep = "" if remove else new + ("\n\n" if sec else "\n")
+ nb = body[:hit.start()] + rep + body[hit.end():]
+ elif remove:
+ nb = body
+ else:
+ nb = body.rstrip("\n") + ("\n" if body.strip() else "\n") + new + "\n"
+ if nb.strip():
+ nb = "\n" + nb.strip("\n") + "\n\n"
+ else:
+ nb = "\n"
+ if m.end() == len(doc):
+ nb = nb.rstrip("\n") + "\n"
+ return doc[:m.start(1)] + nb + doc[m.end():]
+
+
+def put(block, text=None, entry=None, remove=False, company=None, by=None, cwd=None, when=None):
+ loc = profile_path(cwd, "work")
+ idx = pathlib.Path(loc["path"])
+ when = (when or datetime.datetime.now().astimezone()).strftime("%Y-%m-%dT%H:%M%z")
+ created = not idx.is_file()
+ if created:
+ if not company:
+ raise SetupError("there is no Open work page yet: name the company it is for "
+ "(--company), never 'unnamed plant'")
+ doc = _new_work(company, when)
+ else:
+ doc = idx.read_text(encoding="utf-8")
+ have = read_profile(idx, "work")["company"]
+ if company and _slug(company) != _slug(have):
+ raise SetupError("the Open work copy here is %s's, not %s's" % (have, company))
+ new = put_block(doc, block, text, entry, remove)
+ new = re.sub(r"^(\s*-\s*\*\*Last written:\*\*\s*).*$",
+ lambda m: m.group(1) + when + (" by %s" % by if by else ""), new, count=1, flags=re.M)
+ changed = new != doc or created
+ if changed:
+ _write(idx, new)
+ return {"work_path": str(idx), "block": block, "entry": entry, "created": created,
+ "changed": changed, "persistent": loc["persistent"]}
+
+
+def _plain_name(ref):
+ """True for one file or folder name; a path could reach outside its folder."""
+ return ref not in ("", ".", "..") and not re.search(r"[/\\:\x00]", ref)
+
+
+def prune(days=90, cwd=None, today=None):
+ """Drop ## Closed lines whose close date is more than `days` ago, and
+ their files. Moves nothing else."""
+ idx = pathlib.Path(profile_path(cwd, "work")["path"])
+ if not idx.is_file():
+ return {"dropped": [], "files_removed": []}
+ today = today or datetime.date.today()
+ doc, root = idx.read_text(encoding="utf-8"), idx.parent
+ dropped, removed = [], []
+ in_use = set(r.rstrip(".") for b in WORK_BLOCKS[:3] for r in FILE_REF_RE.findall(_block(doc, b)))
+ for line in _block(doc, "Closed").splitlines():
+ s = line.strip()
+ dates = ISO_RE.findall(s[2:].partition("|")[2]) # after the reference, which may hold a date itself
+ if not s.startswith("- ") or not dates:
+ continue
+ try:
+ age = (today - datetime.date.fromisoformat(dates[0])).days
+ except ValueError:
+ continue
+ if age > days:
+ key = _cells(s[2:])[0]
+ if not _plain_name(key):
+ continue
+ dropped.append(key)
+ for q in sorted((root / "inquiries").iterdir()) if (root / "inquiries").is_dir() else []:
+ rel = q.relative_to(root).as_posix()
+ if not re.fullmatch(r"(?:.*-)?%s\.intake\.\w+" % re.escape(key), q.name) or rel in in_use:
+ continue
+ q.unlink()
+ removed.append(rel)
+ ev = root / "sourcing" / key
+ if ev.is_dir() and not any(r.startswith("sourcing/%s/" % key) for r in in_use):
+ removed += sorted(q.relative_to(root).as_posix() for q in ev.rglob("*") if q.is_file())
+ shutil.rmtree(ev)
+ for key in dropped:
+ doc = put_block(doc, "Closed", entry=key, remove=True)
+ if dropped:
+ _write(idx, doc)
+ return {"dropped": dropped, "files_removed": removed}
+
+
+def migrate(src, company, cwd=None):
+ """Lift older blocks into the Open work working copy. The source
+ is only read. Blocks the working copy already holds are kept as they are."""
+ if not company:
+ raise SetupError("name the company the open work belongs to (--company)")
+ src = pathlib.Path(src)
+ text = src.read_text(encoding="utf-8")
+ loc = profile_path(cwd, "work")
+ idx = pathlib.Path(loc["path"])
+ root = idx.parent
+ when = datetime.datetime.now().astimezone().strftime("%Y-%m-%dT%H:%M%z")
+ doc = idx.read_text(encoding="utf-8") if idx.is_file() else _new_work(company, when)
+ moved, kept, missing = [], [], []
+ for name in ("Dashboards", "Open inquiries", "Sourcing events"):
+ m = re.search(r"^##[ \t]*%s[ \t]*$\n?(.*?)(?=^##\s(?!#)|\Z)" % re.escape(name), text, re.M | re.S)
+ if not m or not m.group(1).strip():
+ continue
+ if _block(doc, name).strip():
+ kept.append(name)
+ continue
+ body = m.group(1)
+ if name == "Open inquiries":
+ def lift(mm):
+ old = mm.group(1)
+ for base in (src.parent, pathlib.Path(cwd or os.getcwd())):
+ if (base / old).is_file():
+ stem = pathlib.Path(old).name.rsplit(".intake.", 1)[0]
+ rel = "inquiries/%s.intake.txt" % stem
+ (root / "inquiries").mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(base / old, root / rel)
+ return "file: " + rel
+ missing.append(old)
+ return "file: missing"
+ body = LEGACY_INTAKE_RE.sub(lift, body)
+
+ def gone(mm): # a page path the old block named that is not here
+ if (root / mm.group(1).rstrip(".")).is_file():
+ return mm.group(0)
+ missing.append(mm.group(1))
+ return "missing"
+ body = FILE_REF_RE.sub(gone, body)
+ doc = put_block(doc, name, body)
+ moved.append(name)
+ if moved:
+ _write(idx, doc)
+ return {"work_path": str(idx), "moved": moved, "kept_on_page": kept, "missing_files": missing,
+ "source_untouched": str(src)}
+
+
+# --- selftest -------------------------------------------------------------------
+
+SAMPLE = """## Plant context
+
+- **Profile version:** 2
+- **Configured:** 2026-09-08
+- **Company:** Example Manufacturing
+- **Sites:** Fairview (default) - Brantford
+- **Rates:** see Commercial rates - state and source per rate
+
+### Systems
+
+| System | Status |
+|---|---|
+| Oracle NetSuite | live |
+
+### Commercial rates
+
+- **Labor rate:** set in environment (MFG_LABOR_RATE)
+- **Burden rate:** from the ERP - confirmed by the plant controller, 2026-10-02
+- **Downtime cost per hour:** not set - see gaps
+"""
+
+
+RATES_SAMPLE = """## Plant rates
+
+- **Company:** Example Manufacturing
+- **Configured:** 2026-10-02
+
+### Commercial rates
+
+- **Labor rate:** confirmed 71.00/hr - given by Pat Doyle, 2026-10-02
+- **Burden rate:** set in environment (MFG_BURDEN_RATE)
+- **Margin rules:** confirmed `{"default":0.32}` - given by Pat Doyle, 2026-10-02
+- **Downtime cost per hour:** placeholder 62.00/hr - assumed from the FY25 budget, not confirmed
+- **Scrap costing basis:** standard cost from NetSuite
+"""
+
+
+WORK_SOURCING = """### SRC-2026-10-14-PN-4471-B-BO — black oxide, PN-4471-B Rev 2 (Fairview)
+
+Trigger: quote EH-RFQ-0912 line 1 | Breaks: 50, 200 each | Due: 2026-10-28 | Status: open
+
+| Supplier | Approval | Drafted | Sent (per buyer) | Due | Response | Chased |
+|---|---|---|---|---|---|---|
+| VEND-5120 Example Finishing | approved, single source | 2026-10-14 | 2026-10-14 | 2026-10-28 | bid 2026-10-22, sourcing/SRC-2026-10-14-PN-4471-B-BO/example-finishing.bid.txt | - |
+| VEND-5141 Example Coatings | approved | 2026-10-14 | 2026-10-14 | 2026-10-28 | - | - |"""
+
+INTAKE_SAMPLE = """rfq_reference: EH-RFQ-0912
+customer: Example Hydraulics
+contact: { name: "Ana Ruiz", email: "aruiz@example-hydraulics.example" }
+paused_at_step: 5
+lines:
+ - part: PN-4471-B
+ quantities: [50, 200]
+"""
+
+BID_SAMPLE = """bid_ref: SRC-2026-10-14-PN-4471-B-BO/example-finishing
+supplier_id: VEND-5120
+breaks:
+ - quantity: 50
+ unit_price: 3.10
+ currency: USD
+ - quantity: 200
+ unit_price: 2.20
+ currency: USD
+tooling_price: 0
+"""
+
+LEGACY = """# Workspace notes
+
+## Dashboards
+
+- Fairview: Operations Command Center — https://claude.ai/artifact/abc123
+
+## Open inquiries
+
+- EV-RFQ-0410 | Example Valve | rfq/example-valve-EV-RFQ-0410.intake.yaml | paused_at_step: 5
+- EH-RFQ-0001 | Example Hydraulics | rfq/example-hydraulics-EH-RFQ-0001.intake.yaml | paused_at_step: 3
+
+## Sourcing events
+
+""" + WORK_SOURCING + "\n"
+
+
+def _work_selftest(t):
+ """The Open work page: put, render, install, saved, prune, migrate."""
+ when = datetime.datetime(2026, 11, 10, 10, 15)
+ day = datetime.date(2026, 11, 10)
+ wd = t / "work"
+ wd.mkdir()
+ os.environ.pop("CLAUDE_PLUGIN_DATA", None)
+ try:
+ put("Open inquiries", "- EH-RFQ-0912 | Example Hydraulics | file: inquiries/example-hydraulics-EH-RFQ-0912.intake.txt "
+ "| paused_at_step: 5 | waiting_on: customer answers to Q1-Q3 | stale_after: 2026-11-05 | "
+ "bid_decision_state: draft", entry="EH-RFQ-0912", cwd=wd, when=when, company="Example Manufacturing")
+ except SetupError:
+ raise AssertionError("put refused a first write that named the company")
+ try:
+ put("Dashboards", "- x", cwd=t / "nowhere-yet", when=when)
+ raise AssertionError("put created a page with no company")
+ except SetupError as e:
+ assert "unnamed plant" in str(e), e
+ root = wd / LOCAL_DIR / WORK_DIR
+ (root / "inquiries").mkdir()
+ (root / "inquiries" / "example-hydraulics-EH-RFQ-0912.intake.txt").write_text(INTAKE_SAMPLE, encoding="utf-8")
+ ev = root / "sourcing" / "SRC-2026-10-14-PN-4471-B-BO"
+ ev.mkdir(parents=True)
+ (ev / "example-finishing.bid.txt").write_text(BID_SAMPLE, encoding="utf-8")
+ put("Sourcing events", WORK_SOURCING, entry="SRC-2026-10-14-PN-4471-B-BO", cwd=wd, when=when, by="supplier-quote-request")
+ put("Dashboards", "- Fairview: Operations Command Center — https://claude.ai/artifact/abc123", entry="Fairview: Operations Command Center", cwd=wd, when=when)
+ put("Closed", "- EH-RFQ-0877 | quoted 2026-07-30 | file kept until 2026-10-28", entry="EH-RFQ-0877", cwd=wd, when=when)
+ idx = root / KINDS["work"]["name"]
+ f = find(cwd=wd, titles=["Plant setup: Example Manufacturing", "Plant setup: Example Tool", "Plant rates: Example Manufacturing"])
+ assert f["work_exists"] and f["work_path"] == str(idx), f
+ assert f["companies"] == ["Example Manufacturing", "Example Tool"] and "ask_which_plant" in f, f
+ assert "Open work: <company>" in f["setup_page_first"] and "ask which plant" in f["setup_page_first"]
+ assert RESULT_LAST in after_any_change("work")
+
+ # only the block being written changes
+ doc = idx.read_text(encoding="utf-8")
+ keep = {b: _block(doc, b) for b in ("Dashboards", "Open inquiries", "Closed")}
+ put("Sourcing events", WORK_SOURCING.replace("Status: open", "Status: decided"),
+ entry="SRC-2026-10-14-PN-4471-B-BO", cwd=wd, when=when)
+ doc2 = idx.read_text(encoding="utf-8")
+ assert "Status: decided" in doc2 and doc2.count("### SRC-") == 1, doc2
+ for b, body in keep.items():
+ assert _block(doc2, b) == body, b
+ put("Sourcing events", WORK_SOURCING, entry="SRC-2026-10-14-PN-4471-B-BO", cwd=wd, when=when)
+
+ # render: every file byte for byte; the view hides every price
+ r = render(idx, t / "wpage", "work")
+ assert r["title"] == "Open work: Example Manufacturing", r
+ assert set(r["files"]) == {"setup/open-work.txt", "inquiries/example-hydraulics-EH-RFQ-0912.intake.txt",
+ "sourcing/SRC-2026-10-14-PN-4471-B-BO/example-finishing.bid.txt"}, r
+ view = (t / "wpage" / "index.html").read_text(encoding="utf-8")
+ assert not MONEY_RE.search(view) and "3.10" not in view and "2.20" not in view, view
+ assert "unit_price: 3.10" in (t / "wpage" / "sourcing/SRC-2026-10-14-PN-4471-B-BO/example-finishing.bid.txt").read_text()
+ assert "Don't share" in view and "EH-RFQ-0912" in view and "Example Coatings" in view and "<script" not in view
+ assert "aruiz@" not in view
+ v2 = work_view(idx.read_text(encoding="utf-8"), day)
+ assert 'class="stale">stale' in v2 and ">13<" in v2, v2 # stale after 5 Nov; Example Coatings 13 days past due
+
+ # problems: an email outside the contact, a rate in the index, a missing file, a .yaml file
+ bad_idx = t / "bad" / "setup"
+ shutil.copytree(t / "wpage", t / "bad")
+ (t / "bad" / "inquiries" / "example-hydraulics-EH-RFQ-0912.intake.txt").write_text(
+ INTAKE_SAMPLE + "notes: forwarded by ops@example-hydraulics.example\n", encoding="utf-8")
+ assert any("email" in x and ".intake." in x for x in work_problems(t / "bad", bad_idx / "open-work.txt"))
+ (t / "bad" / "inquiries" / "example-hydraulics-EH-RFQ-0912.intake.txt").write_text(INTAKE_SAMPLE, encoding="utf-8")
+ assert work_problems(t / "bad", bad_idx / "open-work.txt") == []
+ (bad_idx / "open-work.txt").write_text(doc + "- **Labor rate:** 71.00/hr\n", encoding="utf-8")
+ pr = work_problems(t / "bad", bad_idx / "open-work.txt")
+ assert pr and "Labor rate" in pr[0] and "71" not in pr[0], pr
+ (bad_idx / "open-work.txt").write_text(doc.replace(".intake.txt", ".intake.yaml"), encoding="utf-8")
+ assert any("not in the folder" in x for x in work_problems(t / "bad", bad_idx / "open-work.txt"))
+
+ # install from the folder the page was read into, then saved
+ i1 = install(t / "wpage", "Example Manufacturing", cwd=t / "other", kind="work")
+ assert i1["changed"] and len(i1["files"]) == 2 and i1["work_path"].endswith("plant-setup/open-work/open-work.md"), i1
+ assert not install(t / "wpage", cwd=t / "other", kind="work")["changed"]
+ try:
+ install(t / "wpage", "Example Tool", cwd=t / "other", kind="work")
+ raise AssertionError("installed another company's open work")
+ except SetupError:
+ pass
+ ok = saved(t / "wpage", None, r["title"], when, rendered=t / "wpage")
+ assert ok["ok"] and ok["line"].startswith("Saved to your Open work page"), ok
+ shutil.copytree(t / "wpage", t / "readback")
+ (t / "readback" / "sourcing/SRC-2026-10-14-PN-4471-B-BO/example-finishing.bid.txt").write_text(BID_SAMPLE + "#\n")
+ nok = saved(t / "readback", None, r["title"], when, rendered=t / "wpage")
+ assert not nok["ok"] and "example-finishing.bid.txt" in nok["line"], nok
+
+ # prune: closed lines past 90 days go, with their files; open lines stay
+ (root / "inquiries" / "acme-EH-RFQ-0877.intake.txt").write_text(INTAKE_SAMPLE, encoding="utf-8")
+ pr = prune(90, cwd=wd, today=day)
+ assert pr == {"dropped": ["EH-RFQ-0877"], "files_removed": ["inquiries/acme-EH-RFQ-0877.intake.txt"]}, pr
+ after = idx.read_text(encoding="utf-8")
+ assert "EH-RFQ-0877" not in after and "EH-RFQ-0912" in after and "SRC-2026-10-14" in after
+
+ # prune takes the reference whole (RFQ-12 is not RFQ-123), leaves a file an open line
+ # names, and ages by the close date, not a date inside the reference
+ for ref in ("RFQ-12", "RFQ-123"):
+ (root / "inquiries" / ("acme-%s.intake.txt" % ref)).write_text(INTAKE_SAMPLE, encoding="utf-8")
+ put("Open inquiries", "- RFQ-123 | acme | file: inquiries/acme-RFQ-123.intake.txt | paused_at_step: 2",
+ entry="RFQ-123", cwd=wd, when=when)
+ put("Closed", "- RFQ-12 | quoted 2026-07-30", entry="RFQ-12", cwd=wd, when=when)
+ put("Closed", "- RFQ-123 | withdrawn 2026-07-01, re-opened", entry="RFQ-123", cwd=wd, when=when)
+ put("Closed", "- SRC-2026-07-01-PN-1-A | decided and closed 2026-11-01", entry="SRC-2026-07-01-PN-1-A",
+ cwd=wd, when=when)
+ kept = root / "sourcing" / "SRC-2026-07-01-PN-1-A" / "decision.txt"
+ kept.parent.mkdir()
+ kept.write_text("decision\n", encoding="utf-8")
+ pr = prune(90, cwd=wd, today=day)
+ assert pr == {"dropped": ["RFQ-12", "RFQ-123"], "files_removed": ["inquiries/acme-RFQ-12.intake.txt"]}, pr
+ assert (root / "inquiries" / "acme-RFQ-123.intake.txt").is_file() and kept.is_file()
+ assert "SRC-2026-07-01-PN-1-A" in _block(idx.read_text(encoding="utf-8"), "Closed")
+ assert read_work(idx)["files"].count("inquiries/acme-RFQ-123.intake.txt") == 1
+
+ # put: an entry whose reference starts another's is its own section
+ d = put_block(_new_work("x", "t"), "Sourcing events", "### SRC-1-B-BO — a\n\nStatus: open", entry="SRC-1-B-BO")
+ d = put_block(d, "Sourcing events", "### SRC-1-B — b\n\nStatus: open", entry="SRC-1-B")
+ assert "### SRC-1-B-BO — a" in d and "### SRC-1-B — b" in d, d
+ d = put_block(d, "Sourcing events", entry="SRC-1-B", remove=True)
+ assert "### SRC-1-B-BO — a" in d and "### SRC-1-B —" not in d, d
+
+ # view: "no response" written out is that state, with its days past due
+ d = put_block(_new_work("x", "t"), "Sourcing events", "### SRC-1-B — b\n\nStatus: open\n\n| Supplier | Due | Response |\n"
+ "|---|---|---|\n| VEND-1 | 2026-10-28 | No response, chased |", entry="SRC-1-B")
+ assert "<td>no response</td><td>13</td>" in work_view(d, day), work_view(d, day)
+
+ # migrate: blocks lifted verbatim, the intake file copied, the source untouched
+ mig = t / "mig"
+ (mig / "rfq").mkdir(parents=True)
+ (mig / "rfq" / "example-valve-EV-RFQ-0410.intake.yaml").write_text(INTAKE_SAMPLE, encoding="utf-8")
+ legacy = mig / "CLAUDE.local.md"
+ legacy.write_text(LEGACY, encoding="utf-8")
+ m = migrate(legacy, "Example Manufacturing", cwd=mig)
+ assert m["moved"] == ["Dashboards", "Open inquiries", "Sourcing events"], m
+ assert m["missing_files"][0] == "rfq/example-hydraulics-EH-RFQ-0001.intake.yaml", m
+ assert legacy.read_text(encoding="utf-8") == LEGACY
+ moved = pathlib.Path(m["work_path"]).read_text(encoding="utf-8")
+ assert "file: inquiries/example-valve-EV-RFQ-0410.intake.txt" in moved and "| file: missing |" in moved, moved
+ assert m["missing_files"][-1].endswith("example-finishing.bid.txt") and "bid 2026-10-22, missing" in moved, m
+ assert render(m["work_path"], t / "migpage", "work")["title"] == "Open work: Example Manufacturing"
+ assert _block(moved, "Sourcing events").strip() == _block(LEGACY, "Sourcing events").strip().replace(
+ "sourcing/SRC-2026-10-14-PN-4471-B-BO/example-finishing.bid.txt", "missing")
+ assert (pathlib.Path(m["work_path"]).parent / "inquiries" / "example-valve-EV-RFQ-0410.intake.txt").is_file()
+
+
+def _selftest():
+ with tempfile.TemporaryDirectory() as t:
+ t = pathlib.Path(t).resolve() # macOS: /var is /private/var
+ prof = t / "in.md"
+ prof.write_text(SAMPLE, encoding="utf-8")
+
+ # 1. render: the file is the profile byte for byte; the page reads in plain words
+ r = render(prof, t / "page")
+ assert r["title"] == "Plant setup: Example Manufacturing", r
+ assert r["sha256"] == _sha(prof) and r["files"] == {DATA_PATH: str(t / "page" / DATA_PATH)}, r
+ page = (t / "page" / "index.html").read_text(encoding="utf-8")
+ assert "<title>Plant setup: Example Manufacturing</title>" in page
+ assert "<h2>Commercial rates</h2>" in page and "<td>Oracle NetSuite</td>" in page
+ assert "<script" not in page
+
+ # 2. no rate value and no email address is ever saved or installed
+ for bad_line, why in (("- **Labor rate:** confirmed 71.00/hr - given by Pat Doyle, 2026-10-02", "Labor rate"),
+ ("- **Burden rate:** placeholder 140% - assumed, not confirmed", "Burden rate"),
+ ("- **Margin rules:** confirmed `{\"default\":0.32}`", "Margin rules")):
+ dirty = t / "dirty.md"
+ dirty.write_text(SAMPLE.replace("- **Downtime cost per hour:** not set - see gaps", bad_line),
+ encoding="utf-8")
+ for fn in (lambda: render(dirty, t / "x"), lambda: install(dirty, cwd=t)):
+ try:
+ fn()
+ raise AssertionError("accepted a rate value: " + bad_line)
+ except SetupError as e:
+ assert why in str(e) and "71" not in str(e) and "140" not in str(e), e
+ mail = t / "mail.md"
+ mail.write_text(SAMPLE + "- **Confirmed by:** pat@example-manufacturing.example.com\n", encoding="utf-8")
+ assert problems(mail.read_text()) and "email" in problems(mail.read_text())[0]
+ # a value outside a rate line (sub-bullet, table row), or in a Plant rates block kept in the same file
+ for extra in (" - prototype: 0.45\n", "\n| prototype | 30-45% |\n", "\n" + RATES_SAMPLE):
+ pr = problems(SAMPLE + extra)
+ assert pr and "rate value" in pr[0] and not re.search(r"\d", "".join(pr)), (extra, pr)
+ assert problems(SAMPLE) == [] and problems(SAMPLE + "\nAssumed from the FY25 budget, 2026-10-02.\n") == []
+
+ # 3. install into the task folder: a new copy, then the same copy again
+ old = os.environ.pop("CLAUDE_PLUGIN_DATA", None)
+ try:
+ f0 = find(cwd=t)
+ assert not f0["exists"] and f0["setup_page_first"].startswith("Required before"), f0
+ i1 = install(t / "page" / DATA_PATH, cwd=t)
+ assert i1["changed"] and i1["company"] == "Example Manufacturing" and not i1["persistent"], i1
+ assert i1["profile_path"] == str(t / LOCAL_DIR / PROFILE_NAME)
+ i2 = install(t / "page" / DATA_PATH, cwd=t)
+ assert not i2["changed"] and not (t / LOCAL_DIR / "history").exists(), i2
+ assert find(cwd=t)["company"] == "Example Manufacturing"
+
+ # 4. a page that differs: the page wins, the old copy goes to history
+ newer = t / "newer.md"
+ newer.write_text(SAMPLE.replace("2026-09-08", "2026-11-05"), encoding="utf-8")
+ i3 = install(newer, cwd=t)
+ assert i3["changed"] and len(list((t / LOCAL_DIR / "history").iterdir())) == 1, i3
+
+ # 5. refusals: another company's page, a file that is not a profile
+ for bad, kw in ((newer, {"company": "Other Co"}), (t / "page" / "index.html", {})):
+ try:
+ install(bad, cwd=t, **kw)
+ raise AssertionError("install accepted %s" % bad)
+ except SetupError:
+ pass
+
+ # 6. the plugin data folder wins when it is set and writable
+ data = t / "data"
+ data.mkdir()
+ os.environ["CLAUDE_PLUGIN_DATA"] = str(data)
+ i4 = install(newer, cwd=t)
+ assert i4["persistent"] and i4["profile_path"] == str(data / PROFILE_NAME), i4
+ finally:
+ os.environ.pop("CLAUDE_PLUGIN_DATA", None)
+ if old is not None:
+ os.environ["CLAUDE_PLUGIN_DATA"] = old
+
+ # 6b. never a working copy inside the plugin's own folder
+ os.environ.pop("CLAUDE_PLUGIN_DATA", None)
+ for inside in (PLUGIN_ROOT, PLUGIN_ROOT / "shared" / "scripts"):
+ try:
+ find(cwd=inside)
+ raise AssertionError("find accepted the plugin folder %s" % inside)
+ except SetupError as e:
+ assert "task's own folder" in str(e), e
+ if old is not None:
+ os.environ["CLAUDE_PLUGIN_DATA"] = old
+
+ # 6c. the after-change steps name the right page, path and file for each kind
+ for kind, words in (("setup", ("plant setup page", "profile_path", "setup/plant-context.txt", "mcp__claude-artifacts__")),
+ ("rates", ("plant rates page", "rates_path", "--kind rates", "setup/plant-rates.txt"))):
+ text = after_any_change(kind)
+ assert all(w in text for w in words) and str(pathlib.Path(__file__).resolve()) in text, (kind, text)
+ assert RESULT_LAST in text, kind
+ here = os.getcwd()
+ os.chdir(t)
+ try:
+ assert "CLAUDE_PLUGIN_DATA" not in os.environ # main() set it aside: nothing here writes outside t
+ assert main(["install", "--from", str(t / "page" / DATA_PATH), "--company", "Example Manufacturing"]) == 0
+ finally:
+ os.chdir(here)
+
+ # 7. stamp changes the Configured line and nothing else
+ s = t / "stamp.md"
+ s.write_text(SAMPLE, encoding="utf-8")
+ assert stamp(s, datetime.date(2026, 11, 5)) == {"configured": "2026-11-05"}
+ assert s.read_text(encoding="utf-8") == SAMPLE.replace("Configured:** 2026-09-08", "Configured:** 2026-11-05")
+ # an empty value stays on its own line: the next line is neither read as it nor overwritten
+ s.write_text(SAMPLE.replace("Configured:** 2026-09-08", "Configured:**"), encoding="utf-8")
+ assert _field(s.read_text(encoding="utf-8"), "Configured") is None
+ stamp(s, datetime.date(2026, 11, 5))
+ assert s.read_text(encoding="utf-8") == SAMPLE.replace("Configured:** 2026-09-08", "Configured:** 2026-11-05")
+
+ # 8. the saved line only for a read-back that matches
+ when = datetime.datetime(2026, 11, 5, 14, 5)
+ ok = saved(t / "page" / DATA_PATH, r["sha256"], r["title"], when)
+ assert ok == {"ok": True, "line": "Saved to your plant setup page in Claude "
+ "(Plant setup: Example Manufacturing), 5 Nov 2026 14:05."}, ok
+ assert saved(newer, r["sha256"], r["title"], when) == {"ok": False, "line": NOT_SAVED_LINE % "plant setup page"}
+
+ # 9. the rates page: values in the file, states only on the page, private wording
+ rates = t / "rates.md"
+ rates.write_text(RATES_SAMPLE, encoding="utf-8")
+ rr = render(rates, t / "rpage", "rates")
+ assert rr["title"] == "Plant rates: Example Manufacturing", rr
+ assert list(rr["files"]) == ["setup/plant-rates.txt"] and rr["sha256"] == _sha(rates), rr
+ rpage = (t / "rpage" / "index.html").read_text(encoding="utf-8")
+ for value in ("71.00", "140", "0.32", "62.00"):
+ assert value not in rpage, value
+ assert "Labor rate:</strong> confirmed - given by Pat Doyle, 2026-10-02" in rpage, rpage
+ assert "set in environment (MFG_BURDEN_RATE)" in rpage and "Keep this page private" in rpage
+ # the value is hidden wherever it sits: first word, after the dash, a sub-bullet, a table
+ assert state_only("**Labor rate:** 71.00/hr confirmed - given by x") == "**Labor rate:** confirmed - given by x"
+ assert state_only("**Labor rate:** confirmed - 71.00/hr, given by x, 2026-10-02") == \
+ "**Labor rate:** confirmed - [on file], given by x, 2026-10-02"
+ assert state_only("**Burden rate:** set in environment (MFG_BURDEN_RATE)") == \
+ "**Burden rate:** set in environment (MFG_BURDEN_RATE)"
+ hidden = details_html("### Commercial rates\n\n- **Margin rules:** see the table\n - prototype: 0.45\n\n"
+ "| Job type | Margin |\n|---|---|\n| prototype | 45% |\n\nFY25 budget, 2026-10-02.\n",
+ hide_values=True)
+ assert "45" not in hidden and "FY25 budget, 2026-10-02." in hidden, hidden
+ # both ends of a range and a bare decimal are hidden; references, dates and MFG_ names are not
+ assert _no_values("30-45% by job type, 0.30-0.45 or .28") == "[on file]-[on file] by job type, [on file]-[on file] or [on file]"
+ refs = "PN-4471 FY25 RFQ-12 SRC-2026-10-14-PN-4471-B-BO VEND-5120 MFG_LABOR_RATE 2026-10-02"
+ assert _no_values(refs) == refs, _no_values(refs)
+ try:
+ os.environ.pop("CLAUDE_PLUGIN_DATA", None)
+ ri = install(t / "rpage" / "setup" / "plant-rates.txt", company="Example Manufacturing", cwd=t, kind="rates")
+ assert ri["profile_path"] == str(t / LOCAL_DIR / "plant-rates.md"), ri
+ f = find(cwd=t)
+ assert f["rates_exists"] and f["rates_path"] == ri["profile_path"], f
+ assert "Plant rates: <company>" in f["setup_page_first"], f
+ for w in ("mcp__claude-artifacts__", "setup/plant-context.txt", "setup/plant-rates.txt",
+ "setup/plant-context.md", "setup/plant-rates.md"): # .md: older pages
+ assert w in f["setup_page_first"], w
+ assert "Artifact tool" not in f["setup_page_first"], f
+ finally:
+ if old is not None:
+ os.environ["CLAUDE_PLUGIN_DATA"] = old
+ assert saved(rates, rr["sha256"], rr["title"], when)["line"].startswith("Saved to your plant rates page")
+ try:
+ install(t / "page" / DATA_PATH, cwd=t, kind="rates")
+ raise AssertionError("rates install accepted a setup file")
+ except SetupError:
+ pass
+
+ # 10. the Open work page
+ try:
+ _work_selftest(t)
+ finally:
+ os.environ.pop("CLAUDE_PLUGIN_DATA", None)
+ if old is not None:
+ os.environ["CLAUDE_PLUGIN_DATA"] = old
+ print("plant_setup selftest: ok")
+ return 0
+
+
+def main(argv=None):
+ argv = sys.argv[1:] if argv is None else argv
+ if "--selftest" in argv:
+ old = os.environ.pop("CLAUDE_PLUGIN_DATA", None) # the selftest writes only to its own temp folder
+ try:
+ return _selftest()
+ finally:
+ if old is not None:
+ os.environ["CLAUDE_PLUGIN_DATA"] = old
+ ap = argparse.ArgumentParser(prog="plant_setup.py")
+ ap.add_argument("command", choices=["find", "render", "install", "saved", "stamp", "put",
+ "prune", "migrate"])
+ ap.add_argument("--profile")
+ ap.add_argument("--out")
+ ap.add_argument("--from", dest="src")
+ ap.add_argument("--company")
+ ap.add_argument("--sha256")
+ ap.add_argument("--title")
+ ap.add_argument("--kind", choices=sorted(KINDS), default="setup")
+ ap.add_argument("--titles", nargs="*")
+ ap.add_argument("--rendered")
+ ap.add_argument("--block")
+ ap.add_argument("--entry")
+ ap.add_argument("--text")
+ ap.add_argument("--text-file", dest="text_file")
+ ap.add_argument("--remove", action="store_true")
+ ap.add_argument("--by")
+ ap.add_argument("--days", type=int, default=90)
+ a = ap.parse_args(argv)
+ try:
+ if a.command == "find":
+ res = find(a.company, titles=a.titles)
+ elif a.command == "put":
+ text = a.text
+ if a.text_file:
+ text = pathlib.Path(a.text_file).read_text(encoding="utf-8")
+ if text is None and not a.remove:
+ raise SetupError("put needs --text-file, --text or --remove")
+ res = put(a.block, text, a.entry, a.remove, a.company, a.by)
+ res["after_any_change"] = after_any_change("work")
+ elif a.command == "prune":
+ res = prune(a.days)
+ elif a.command == "migrate":
+ res = migrate(a.src, a.company)
+ elif a.command == "render":
+ res = render(a.profile, a.out, a.kind)
+ elif a.command == "install":
+ res = install(a.src, a.company, kind=a.kind)
+ res["after_any_change"] = after_any_change(a.kind)
+ elif a.command == "saved":
+ res = saved(a.src, a.sha256, a.title, rendered=a.rendered)
+ else:
+ res = stamp(a.profile)
+ except (SetupError, OSError, TypeError) as e:
+ sys.stdout.write(json.dumps({"error": str(e)}) + "\n")
+ return 2
+ sys.stdout.write(json.dumps(res, ensure_ascii=False) + "\n")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/claude-for-manufacturing/shared/secret-config.md b/plugins/claude-for-manufacturing/shared/secret-config.md
new file mode 100644
index 00000000..2d0130eb
--- /dev/null
+++ b/plugins/claude-for-manufacturing/shared/secret-config.md
@@ -0,0 +1,302 @@
+# Commercial rates and credentials — where sensitive values live
+
+`onboarding` captures a small set of commercially sensitive values, and the
+first rule of their handling is **storage**:
+
+> Storage — the encrypted/secret side of config, not a plain-text config file
+> that could be committed to a repo or copied between customers. The rest of the
+> config can live in the clear.
+
+This file is what that rule actually means in a running plugin, so no skill
+has to invent it. Before this existed the phrase appeared across
+`onboarding`, `quote-build` and `daily-production-report` with no mechanism
+behind it — which meant a rate could never actually be stored, and
+`quote-build` blocks the line a missing rate feeds. Every quote would have
+blocked on labor and burden.
+
+---
+
+## Two routes for a rate
+
+| Value | Variable | Plant profile field | Sensitive |
+|---|---|---|---|
+| Labor rate | `MFG_LABOR_RATE` | **Labor rate** | **Yes** |
+| Burden / overhead rate | `MFG_BURDEN_RATE` | **Burden rate** | **Yes** |
+| Margin rules | `MFG_MARGIN_RULES` | **Margin rules** | **Yes** |
+| Downtime cost per hour | `MFG_DOWNTIME_COST_PER_HOUR` | **Downtime cost per hour** | **Yes** — derived from the three above, inherits their handling |
+| Scrap costing basis | `MFG_SCRAP_COSTING_BASIS` | **Scrap costing basis** | No — internal-only, but not confidential in the same way |
+
+**Environment variables** — the same mechanism `.mcp.json` uses for a
+connector's settings (`${FUSION_MCP_PORT}`), and a custom connector for its
+credentials (`custom-connector`'s Limble example): the value is available to the
+running session, and it is not a file in the repository. This is the stricter
+route, and it wins whenever it is set.
+
+**The plant's rates file** — the `## Plant rates` block, written by
+`onboarding` step 10 after the plant has seen the values and said yes, and
+kept on the private `Plant rates: <company>` page in the user's Claude account
+(`replies.md`, *The plant setup and the rates*). This is the route for anyone
+who cannot set an environment variable, which includes every Cowork user. The
+profile's `### Commercial rates` section then records each rate's state only.
+Field layout is fixed by `../skills/onboarding/reference/config-profile.md`.
+
+Standard cost is **not** here. It comes from the ERP, where plenty of internal
+people already see it.
+
+Everything else `onboarding` captures — export paths, shift boundaries,
+vocabulary, the capability profile, templates, standards and clauses — is a
+preference, not a secret, and lives in the readable config profile.
+
+## The four states
+
+Every rate is in exactly one of these. The `### Commercial rates` section
+records which.
+
+| State | Block line | Prices the job? |
+|---|---|---|
+| **Set in environment** | `- **Labor rate:** set in environment (MFG_LABOR_RATE)` — the name only, never the value | Yes |
+| **Confirmed in profile** | `- **Labor rate:** confirmed 71.00/hr - given by Pat Doyle, 2026-10-02` | Yes |
+| **Placeholder** | `- **Labor rate:** placeholder 62.00/hr - assumed from the FY25 budget, not confirmed` | Yes, labelled **"placeholder rate — not confirmed"** |
+| **Not set** | `- **Labor rate:** not set - see gaps` | **No** — the line it feeds is blocked |
+
+Margin rules hold the same JSON shape in both routes, because margin is rarely
+one number:
+
+```
+MFG_MARGIN_RULES='{"default":0.32,"by_customer":{"EXAMPLE-AEROSPACE":0.28},"by_job_type":{"prototype":0.45}}'
+```
+
+```markdown
+- **Margin rules:** confirmed `{"default":0.32,"by_customer":{"EXAMPLE-AEROSPACE":0.28},"by_job_type":{"prototype":0.45}}` - given by Pat Doyle, 2026-10-02
+```
+
+## Resolving a rate
+
+**Every skill that needs a rate resolves it in this order, and no other.**
+Link here rather than restating it.
+
+1. **The `MFG_*` variable**, if it is set in the environment. Check that it is
+ set by name, without printing it. If the profile also holds a value for
+ that rate, it is **not used and not printed anywhere**, the internal cost
+ sheet included — not as a comparison, not as a conflict note. Say by name
+ that it exists: *"labor rate from `MFG_LABOR_RATE`; the plant profile also
+ holds one"*. Two numbers for one rate on the same sheet invite someone to
+ pick the other.
+2. **A confirmed rate in the plant's rates file**, the `## Plant rates` block
+ at `rates_path` from `plant_setup.py find` (brought in from the private
+ `Plant rates: <company>` page). For an older profile, the
+ profile's own `### Commercial rates` section. Price on it with no label.
+ Cite it as *"plant profile, confirmed by <name> on <date>"*.
+3. **A placeholder in the same place.** Price on it and label it, per
+ *What a skill does when one is missing* below.
+4. **Nothing.** Block the line. Name the rate, name both ways to set it — say
+ *"update our labour rate"* to record it on the plant's rates page, or set
+ `MFG_LABOR_RATE` — and say which lines it blocks. It is asked once: on a
+ yes it is saved to the rates page, never asked again.
+
+The source goes on the internal artifact next to the value, so an estimator
+can see which route priced the job: `MFG_LABOR_RATE`, *plant profile
+(confirmed)*, or *plant profile (placeholder)*.
+
+## How a plant sets them
+
+**Through onboarding.** Step 10 asks for each rate in plain language. Before
+asking, it says the numbers go on the plant's private rates page in their
+Claude account, never on the setup page a teammate may be shown, so the person
+answering knows where they go. Margin is asked as a default plus any customer or job type that
+differs, and written in the JSON shape above. The values are shown back
+**once**, in their own section of the approval draft, so a typo can be caught
+before anything is written. On an explicit yes they are written as
+**confirmed**, with the name of the person who gave them and the date.
+
+**Later.** *"Update our labour rate"* re-runs step 10 for that rate only: the
+current state against the proposed value, a yes, and only that line of the
+rates file rewritten, then the rates page saved again. *"Clear our rates"* sets the named
+rates back to **not set**, after the same yes.
+
+**Through the environment.** A plant that prefers the stricter route sets the
+variables in the environment its Claude session runs in, and `onboarding`
+confirms **by name** that the value is readable — `"burden rate is set"` —
+never by value. The profile then records the rate as *set in environment*.
+
+## Never repeat what was typed
+
+People paste things anyway: a NetSuite token "so you can check the connection,"
+a Limble secret "so you can just connect it." The rule for credentials has not
+changed, and rates have their own rule below it.
+
+**Never reproduce a credential, token or secret the user typed, in any form:
+not quoted, not in code formatting, not in a warning, not in a rotation
+instruction. Refer to it as "the token you pasted." Never name an
+illustrative, typical or industry figure for a missing rate, even to reject
+it.**
+
+Each clause closes a way this has actually gone wrong:
+
+- *"`<the token>` is now in a chat transcript and I am not going to repeat it
+ back"* repeats it. So does *"revoke `<the secret>` in the admin settings."*
+ The instruction to rotate is right; the string inside it is the leak.
+- *"A 'typical' figure of `<amount>` an hour would look authoritative"* names
+ the benchmark in order to reject it. The number is now on the page, and it is
+ the one that gets used.
+
+**What to say instead, for a credential:** it has touched the transcript, so
+it must be rotated; connector auth happens in Claude's connector settings or
+the environment, never in chat; and nothing was done with it. Credentials are
+never accepted from chat — this file's profile route is for commercial rates
+only.
+
+### Rates typed into the chat
+
+A rate is not a credential. It is the plant's answer to a question
+`onboarding` asks, and it is stored.
+
+- **Given to `onboarding` step 10, or to a step 10 update** — including *"our
+ labour rate is X, write it into the config"* — it goes into the approval
+ draft, shown there **once**, and is written only after a yes. That draft is
+ the one place in the conversation a typed rate is restated. Everywhere
+ else in the reply, it is "the rate you gave." **Unless that rate is already
+ set in the environment**: then it is not stored, not put in the draft and
+ not repeated — say by name that the variable is set and wins, and that the
+ variable is where it changes.
+- **Given anywhere else** — *"use X an hour for this quote"* in the middle of
+ `quote-build` — it is **not used for that run and not repeated back**. Say
+ the rate is not on file, and offer the step 10 update, which records it with
+ a name and a date and then prices every quote that follows. A rate used ad
+ hoc is nobody's recorded number, and the next quote would not have it.
+- **After it is written**, confirm by name — *"labor rate is confirmed in the
+ plant profile"* — not by value. The value reappears only where the audience
+ rule below allows it.
+- A declined-then-echoed rate is still echoed: *"I'm deliberately not
+ restating either number … if `<rate>` and `<percent>` are current"*
+ restates both.
+
+**The check before sending.** Read the reply once more for any run of eight or
+more characters from a pasted credential, and for any rate number the user
+typed **outside the approval draft**. If one is there, rewrite the sentence
+around "the token you pasted" or "the rate you gave."
+
+**This does not change the audience rule below.** A rate on file, from either
+route, is multiplied out and shown on internal artifacts; that is the point of
+a cost basis.
+
+## What a skill does when one is missing
+
+**Never invent one, never substitute a plausible industry figure, and never
+name one — not as an example, not as a range, not to say why it would be
+wrong.** The three behaviors, and no others:
+
+| Situation | Behavior |
+|---|---|
+| A rate a line needs is not set in either route | **Block that line.** Name the rate and both ways to set it, say which lines it blocks, quote everything it does not touch |
+| Downtime cost per hour not set in either route | `daily-production-report` prices scrap only and states plainly that downtime is unpriced |
+| A marked placeholder is on file instead of a real value | **Proceed.** A placeholder the plant recorded at onboarding, with its assumption, is a valid rate. Price on it, label every affected line and the cost sheet **"placeholder rate — not confirmed"**, and keep the item on the gaps list by name |
+
+A placeholder is **not** a sensitive value — it is not the plant's number — so
+it may sit in the readable config, the gaps list and the setup summary. When
+the real value arrives it becomes **confirmed** (or *set in environment*) and
+drops off the gaps list.
+
+**The line between a placeholder and an invented rate is who supplied it.** A
+placeholder was recorded by the plant, at onboarding, with a stated assumption
+("assumed from last year's budget"); it is the plant's own best guess and the
+plant has seen it. A "typical Midwest shop rate" the model reaches for, or a
+figure looked up anywhere, is nobody's number and is refused. Only the first
+kind prices anything.
+
+## The audience rule, restated because it is the one that bites
+
+These values are **used and displayed**, not hidden. `quote-build`'s whole
+worth is that an estimator can see and defend the cost basis, and a burden rate
+has to be multiplied by hours and then shown. A write-only rate would break the
+skill.
+
+**Where they may appear:** the internal cost-basis sheet, the internal margin
+line, priced downtime in the morning report, and — once, for the plant to
+check — the approval draft in `onboarding` step 10.
+
+**Where they may never appear:** a customer-facing artifact, the readable setup
+summary, the config profile page, the gaps list, sample data, or
+logs. The setup summary and the config profile page show each rate's **state,
+who gave it and the date** — *"labor rate: confirmed, given by Pat Doyle on
+2026-10-02"* — never the value.
+
+**The two live dashboards are internal pages.** The Operations dashboard
+carries priced downtime; the Quality Register carries customer names and
+customer-notification deadlines. Both are private until the user shares them,
+and no skill shares them. Every run that reports the Quality Register's URL
+follows it with *"Internal: it lists customer names and notification
+deadlines. Check who you share it with."* The register carries the NCR and the
+8D by reference only, never a redacted customer pack's content. Per
+`live-dashboard.md`.
+
+### The outbound document check
+
+A customer quote and a supplier RFQ package are the two documents this plugin
+produces that leave the building. Both have leaked, and neither leak was a
+rate: one was a note *inside the customer's quote* explaining which margin rule
+had been applied and that a different rule exists for a named other customer;
+the other was the incumbent's unit price and PO number inside the package going
+to the incumbent's competitors.
+
+**Every outbound document is emitted between explicit delimiters, and nothing
+internal goes inside them.**
+
+```
+=== CUSTOMER QUOTE — SENDABLE ===
+…
+=== END ===
+```
+
+```
+=== SUPPLIER RFQ PACKAGE — SENDABLE ===
+…
+=== END ===
+```
+
+Internal notes, assumptions about pricing policy, candidate supplier lists,
+what is paid today, the figures block — all of it sits **outside** the block.
+The internal cost sheet gets its own delimiters too
+(`=== INTERNAL COST SHEET — NOT FOR CUSTOMER ===` … `=== END ===`), so the
+two documents are explicit and a reader never has to guess which is which.
+
+**Before sending, read the delimited block alone and reject it if it holds any
+of these:**
+
+- any rate value — read from an `MFG_*` variable or from the plant profile,
+ confirmed or placeholder — or a figure that is one of those values times
+ something
+- the word "margin" in any form — "standard margin applied," a margin
+ percentage, a margin line — or any description of how a price was arrived
+ at: default rule, customer-specific rule, discount tier
+- any customer's name other than the addressee's; in a supplier package, any
+ other supplier's name
+- any unit price, PO number or total taken from the plant's purchase-order
+ history — what the plant pays its current source is the one number a
+ competing supplier most wants
+- a target price, in a supplier package
+
+An assumption the recipient needs ("priced for delivery to your Fairview
+dock") stays in. An assumption that reveals policy ("no customer was named, so
+the default margin applies") moves out to the internal sheet, where it is just
+as useful to the estimator and tells the customer nothing.
+
+The gaps list carries **names, never values** — *"burden rate — not confirmed,
+quote-build is running on a placeholder,"* never the number.
+
+## Why the profile, and what it trades away
+
+The storage rule puts these values on "the encrypted/secret side of config." Where
+the plugin runs in Claude Code, environment variables are that side, and they
+remain supported and take precedence. In Cowork there is no such side a plugin
+can reach: no environment variables and no protected per-organisation store.
+Without the profile route, every Cowork quote blocks on labor, burden and
+margin, and every morning report leaves downtime unpriced.
+
+What the profile route gives up, stated so nobody has to discover it:
+
+- **It is plain text in the plant's Claude memory**, readable by anyone at the
+ plant with access to that memory. `onboarding` says so before asking.
+- **It is not in this repository.** Nothing in this plugin writes rates to a
+ file in the repo, and no skill reads one from it. `.gitignore` covers `.env`,
+ so a plant that prefers a local file for the environment route can use one.
diff --git a/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/SKILL.md b/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/SKILL.md
new file mode 100644
index 00000000..fe90e4ae
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/SKILL.md
@@ -0,0 +1,361 @@
+---
+name: breakdown-diagnosis
+description: "When a machine goes down, reads the sensor window before the failure, the asset's maintenance history including the free-text close-out notes technicians actually wrote, photos of what they can see, and the manufacturer's troubleshooting tree — then ranks likely causes, each with its supporting evidence, the specific prior work orders behind it, and the cheapest test that would tell them apart. Surfaces any safety implication before any diagnosis. Drafts the PM interval change that would stop it recurring, and emits a downtime record for the next production report. Batch mode ranks bad actors across every asset. Use when someone says \"the machine is down,\" \"what's wrong with this machine,\" \"why does this keep failing,\" \"diagnose this,\" or \"which machines are hurting us most.\""
+compatibility: "Requires none. Reads a CMMS connector (Limble, added through custom-connector, is the worked example) for assets, maintenance history and PM plans when connected, plus historian sensor exports, photos and manuals from Microsoft 365. Runs usefully with no sensor data and no connector. Output is always a draft the technician applies."
+---
+
+# Breakdown Diagnosis
+
+A machine is down. Every minute it stays down, the plant is not producing — and
+**the largest component of MTTR is usually not the repair, it is working out what
+is wrong.**
+
+The technician has five sources of evidence available and time to assemble none
+of them. That gap is this skill.
+
+**Quick start**
+
+```
+→ Capture the event: asset, time down, symptom, fault codes
+→ SAFETY FIRST: if there is a safety implication, that leads. Always
+→ Pull the sensor window; read shapes, not just threshold breaches
+→ Mine maintenance history and the free-text close-out notes
+→ Read the photos; consult the manual's troubleshooting tree
+→ Rank candidate causes: evidence, cheapest discriminating test, expected fix
+→ Cite the specific prior work orders behind each candidate
+→ Draft the PM interval change that would stop it recurring
+→ Emit the downtime record for the next production report
+```
+
+---
+
+## Safety leads. Always.
+
+**Where a failure has a safety implication, surface it first — before any
+diagnosis.** Never let a diagnostic suggestion precede a safety flag.
+
+**Every diagnosis opens with this line, flagged or not:** *"Follow your plant's
+lockout procedure before anyone works on this machine. This is not a safety
+assessment."* A false flag never removes it, and no step sends anyone to the
+machine above it.
+
+A technician reading a ranked list of likely causes is already reaching for
+tools. If the honest answer is "this guard is defeated" or "that is a stored
+energy hazard," it has to arrive before the thing that sends them toward the
+machine, not underneath it.
+
+This is a done-when condition, and it is the one non-negotiable ordering rule in
+the skill.
+
+**What counts as a safety implication.** Set `safety_flagged: true` when the
+evidence shows any of these, and write which one, with its evidence, in
+`safety_reason`:
+
+- a seized or locked rotating part: spindle, chuck, bar feeder, conveyor
+- a defeated, bypassed or failed guard or interlock
+- stored energy: springs, counterweights, a part under load, a raised axis
+- hydraulic or pneumatic pressure that has to be bled before work
+- an electrical fault: a trip, a burnt smell, exposed or damaged wiring
+- a fault that was cleared by restarting rather than fixed (*"ran off and
+ restarted"*), now repeating
+
+When none of these is shown, the flag is false and `safety_reason` says *"none
+of the safety triggers shown"*. Never set the flag on a feeling, and never leave it off
+because the diagnosis is uncertain: an uncertain stored-energy hazard is a
+safety implication.
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| The breakdown event | User report, or a maintenance work order | Conversation / CMMS connector or maintenance export |
+| Asset record and specs | CMMS | CMMS connector, else the asset register export |
+| Maintenance history and close-out notes | CMMS | CMMS connector, else the maintenance export |
+| Current PM plan for the asset | CMMS | CMMS connector |
+| Sensor window around the failure | Historian export to M365, scheduled or on-demand | CSV |
+| Technician photos | M365, or uploaded in conversation | Images |
+| Manufacturer's manual | M365 document library | PDF |
+| Production context — what was running | `data-consolidate` output, or a direct MES export | `../../shared/contracts/consolidated-dataset.md` |
+
+---
+
+## Workflow
+
+### Step 1 — Capture the event
+
+Asset, time it went down, the symptom as the technician describes it, and any
+fault codes the machine is showing. Take their words; do not translate a symptom
+into a cause at capture.
+
+### Step 2 — Pull the sensor window
+
+A configurable period before the failure. **Read excursions, trends and step
+changes, not just threshold breaches** — a vibration reading that climbed for six
+hours without ever crossing its alarm limit is a bearing failing in plain sight.
+
+Verify the window covers the event. If it does not, say so and do not reason
+from adjacent data as if it were the event.
+
+### Step 3 — Mine the maintenance history and close-out notes
+
+Weight recency and symptom similarity. Search this asset, **then siblings of the
+same model** — a new machine with no history is not a dead end.
+
+**Run both searches as queries, in code, and keep what they returned.** One
+filter on this asset's ID, one across every asset of the same model on the
+symptom's own words. The work orders each query returned go into the figures
+block (`../../shared/computed-figures.md`) by number. "This asset has eleven
+prior records" and "the sister machine has no bearing history" are both claims
+about a query result, and both have been wrong when written from memory: a
+count is printed from the filter, and an absence names the filter that came
+back empty.
+
+**Then run the template check, every time, before any note is cited.** Group
+every close-out note in the history by its exact text, and for each group count
+the distinct assets and the distinct makes and models it appears on. The model
+comes from the asset name where the asset record has no model column, and the
+output says so. The grouped result goes in the figures block. Then:
+
+- **Same text on assets of different makes** is a template — a default the
+ technician clicked, not an observation about this machine. It is **shown**,
+ labelled *"same text on N assets — not specific to this machine"*, may be
+ mentioned as a fleet-wide pattern, and is **never cited as this machine's
+ evidence** for any candidate.
+- **The same failure recurring on siblings of the same model** is exactly what
+ the sibling search is for: cite it as a fleet pattern for that model, with
+ the work orders named.
+- A note that appears once is this asset's evidence, and is cited.
+
+Skipping this check is how two runs on the same data cite two different sets
+of work orders. With it, the cited set is a function of the data.
+
+The free-text close-out notes are the highest-value input here and the least used
+anywhere. Read `reference/evidence-sources.md` for how to mine them and how to
+report their coverage honestly.
+
+### Step 4 — Read the photos
+
+Visible damage, leaks, wear, part numbers on the failed component, readings on
+the machine's own display. Describe what is visible; **never assert a diagnosis
+from an unclear image.**
+
+### Step 5 — Consult the manual
+
+Match the fault code and symptom to the manufacturer's troubleshooting tree, and
+cite the page. A manufacturer's stated tolerance beats an inference.
+
+### Step 6 — Rank candidate causes
+
+Ordered by likelihood. Each one carries three things:
+
+1. **The evidence supporting it**, from the sources above
+2. **What to check first** — the cheapest and fastest test that would
+ discriminate between this candidate and the next one
+3. **The expected fix**, and the repair path
+
+That second item is the one that saves time. Ranking three causes is useful;
+naming the five-minute check that eliminates two of them is what shortens MTTR.
+
+**Every candidate is written under the same three sub-headings, in this
+order: Evidence / First check / Expected fix and repair path.** Fixed
+headings, every candidate, including the leading one. A candidate whose
+Expected fix is missing shows an empty heading, which a reader can see; the
+rerun found the leading candidate silently lacking one while candidate 2 had
+it, and a fixed shape is what stops that.
+
+### Step 7 — Cite the specific prior work orders
+
+Behind each candidate, the actual work order numbers and close-out notes, so the
+technician can read what was done last time rather than taking a ranked list on
+trust.
+
+**A candidate with no citation is a guess and is labelled as one.** Not omitted —
+an experienced hunch is worth stating — but marked as reasoning rather than
+evidence.
+
+### Step 8 — Propose the PM plan adjustment
+
+Once a diagnosis lands, the specific interval or procedure change for **that
+asset and that failure mode**, drafted for the maintenance planner.
+
+If a bearing failed from misalignment at 1,400 hours, the interval or the
+procedure should probably change. This almost never happens today, because the
+person diagnosing is not the person who owns the PM schedule. Closing that loop
+is the reactive-to-proactive step and it is core behaviour, not an extra.
+
+**Without the current PM plan** this degrades to a recommendation that first asks
+what today's interval is. The step stays either way.
+
+**Pricing the stoppage.** Where someone asks what the downtime cost, resolve
+the downtime cost per hour per `../../shared/secret-config.md`, *Resolving a
+rate* — `MFG_DOWNTIME_COST_PER_HOUR` if set, then a confirmed rate in the plant
+profile, then a placeholder there, labelled — multiply hours by it, and show it
+as an internal figure with its source. Where neither route holds one, report
+minutes and hours, name the rate and both ways to set it, and stop — see Edge
+cases. Never reach for an industry figure.
+
+### Step 9 — Batch mode: the bad actor ranking
+
+Run across all assets instead of one incident, ranked by total downtime minutes
+**and** by failure frequency. A different question from "what is wrong with this
+machine right now," which is why it is a mode here rather than a separate report.
+
+Read `reference/bad-actor-mode.md`.
+
+---
+
+## Approval gates
+
+**Everything this skill produces is a draft the technician or planner applies.**
+Nothing is written back to any system of record.
+
+A CMMS connector's write scope is not assumed — Limble's, the worked example,
+is not confirmed in its public setup guide — so this is designed for read-only and treats write as an
+upgrade rather than an assumption. Concretely:
+
+- **Never update a maintenance ticket automatically.** The diagnosis is output
+ the technician applies.
+- **Asked to close out or update the ticket, write the close-out note as a
+ labelled draft.** Say it never writes to a system of record — and, where
+ no CMMS connector is live, say that too — then **produce the note itself**:
+ what was found, what was done, what to watch, in the words a technician
+ would put in the close-out field. "Paste it into the ticket if it is right"
+ with nothing to paste hands the work back. Never offer to close it later.
+ Per `../../shared/command-center.md`.
+- **The PM adjustment is a draft for the planner**, who owns that schedule.
+- **The diagnosis stays advisory** until a technician confirms it. Its downtime
+ record carries that state explicitly, so the production report cannot present
+ an unconfirmed cause as established.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**Ranked candidate causes** — evidence, what to check first, expected fix,
+repair path.
+
+**Cited history** — the specific prior work orders and close-out notes behind
+each candidate.
+
+**Sensor observation summary** — what the data showed in the failure window,
+plainly stated, including when it showed nothing.
+
+**The figures block** — required whenever the output states a count, a
+duration, a ratio or an absence. Every record count, every "N of M notes were
+usable," and every "no history found" appears here with the query behind it,
+and the prose quotes it. Per `../../shared/computed-figures.md`. An absence
+found by a document search is reported as *not found by search*, never as *does
+not exist*.
+
+**PM plan adjustment proposal** — drafted for the planner.
+
+**The downtime record** — per `../../shared/contracts/downtime-record.md`, in
+exactly the shape `daily-production-report` consumes with no transformation
+between. Note in particular that an ongoing outage carries a null duration
+rather than zero, and that `safety_flagged` travels with it.
+
+**Bad actor ranking** — in batch mode.
+
+**The Operations command-center page, maintenance section** — the diagnosis
+and its current status, produced as an artifact you place. Nothing is written
+to a system. Read `../../shared/command-center.md`. Chain 4's other half,
+folding the diagnosis into the next production report's downtime log, happens
+on `daily-production-report`'s side of the handoff.
+
+Rendered in the house artifact style (`../../shared/artifact-style.md`) when the
+output is something the technician will refer back to.
+
+---
+
+## Edge cases and failure modes
+
+- **No sensor data for this asset** — very common; most assets are not
+ instrumented. Proceed on history, notes, photos and the manual, and say clearly
+ that sensor evidence was unavailable. This is the normal run, not a degraded one.
+- **The sensor export does not cover the failure window** — say so. Do not reason
+ from adjacent data.
+- **A new asset with no history** — fall back to the manual and to sibling assets
+ of the same model. State which.
+- **Close-out notes are terse or useless** — "fixed," "repaired," "OK now."
+ Report the coverage honestly rather than over-reading them.
+- **Photos are ambiguous** — describe what is visible and name what cannot be
+ told apart from the image.
+- **A safety-critical failure** — the safety implication leads, before any
+ diagnosis.
+- **Evidence supports two candidates equally** — present both. Do not break the
+ tie artificially.
+- **Asked what the downtime has cost, with no rate on file** — say the rate is
+ not set in either route, name `MFG_DOWNTIME_COST_PER_HOUR` and the plant
+ profile ("update our downtime cost"), and report the downtime in
+ minutes and hours. **No dollar-per-hour figure of any kind appears**: not a
+ typical one, not a range, not an example of what *not* to use. A benchmark
+ named in order to reject it is still the number that gets used. Per
+ `../../shared/secret-config.md`.
+
+---
+
+## Degradation
+
+**If no CMMS connector is live** (the default: Limble and other CMMS
+systems are added through `custom-connector`) — this is the skill most affected.
+Without Limble or any CMMS connector, it reads the maintenance export.
+
+**What is lost:** live asset records, open maintenance work orders, and the
+current PM plan.
+
+**What survives, and it is the important part:** maintenance history including
+the free-text close-out notes, because those are a field on the work order record
+and export cleanly. The notes are the highest-value input in the skill, so its
+core reasoning is intact.
+
+**What actually changes is freshness.** A breakdown is a real-time event and a
+nightly export is not. Diagnosing a machine that went down twenty minutes ago
+means the most recent — and often most relevant — tickets are not in the data
+yet. Say so rather than letting the history look current.
+
+**Three mitigations, all built, because any one recovers most of the value:**
+
+1. An **on-demand export** the technician can trigger before the run.
+2. **Pasted or uploaded work orders** for that asset.
+3. A **spoken description of recent work** in conversation. "We were in there
+ last Tuesday for the same thing" is real evidence.
+
+The PM adjustment step degrades to a recommendation that first asks what the
+current interval is. It stays in the skill either way.
+
+---
+
+## Chain position
+
+**Chain 4, Breakdown to next report** — step 1, feeding
+`daily-production-report`. The chain pauses at step 4 by nature, because that
+step is a human working a physical machine, and the diagnosis is advisory
+throughout.
+
+**Metric.** Mean time to repair.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/evidence-sources.md` | Steps 2 to 5 — the five sources, how to read each, and the citation rule |
+| `reference/bad-actor-mode.md` | Step 9 — the batch ranking and its coverage traps |
+| `../../shared/computed-figures.md` | Step 3 and on emit — the figures block, and how to state an absence |
+| `../../shared/contracts/downtime-record.md` | On emit — the exact shape `daily-production-report` consumes |
diff --git a/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/bad-actor-mode.md b/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/bad-actor-mode.md
new file mode 100644
index 00000000..5127a81b
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/bad-actor-mode.md
@@ -0,0 +1,90 @@
+# Batch mode — the bad actor ranking
+
+A different question from the rest of the skill, which is why it is a **mode of
+this skill rather than a separate report**.
+
+| Normal mode asks | Batch mode asks |
+|---|---|
+| What is wrong with this machine, right now? | Which machines are hurting us most, over time? |
+| One asset, deep | Every asset, ranked |
+| Read by a technician holding a wrench | Read by a maintenance manager holding a budget |
+
+**A "bad actor" is the asset causing the most downtime.** The ranked list of them
+is what maintenance managers actually use to decide where to spend — on a rebuild,
+a replacement, a PM overhaul, or a spare nobody currently stocks.
+
+---
+
+## Rank both ways, always
+
+Exactly as `daily-production-report` ranks its downtime log, and for the same
+reason: **by total downtime minutes, and by failure frequency.**
+
+These identify different problems and the fixes are different:
+
+- **High minutes, low frequency** — one or two catastrophic failures. Points at a
+ major component, a rebuild, or a spare that should be on the shelf.
+- **High frequency, low minutes** — chronic small stoppages. Usually the more
+ fixable of the two, often a PM interval, an adjustment, or a design issue that
+ everyone has learned to live with.
+- **High on both** — the genuine bad actor, and the easy decision.
+
+A single ranking hides whichever problem it does not sort by, and the chronic
+one is the one that hides, because forty six-minute stoppages disappear next to
+one eight-hour outage.
+
+---
+
+## What each row carries
+
+| Column | Notes |
+|---|---|
+| Asset, in the plant's own vocabulary | Per the `## Plant context` block |
+| Total downtime minutes | Over a stated window |
+| Failure count | Over the same window |
+| MTTR | Mean time from down to running again |
+| Most common reason code | And the share of events it accounts for |
+| Recurring theme from close-out notes | Where the notes support one. This is the differentiated column |
+| History coverage | See below |
+
+That close-out-notes column is what makes this more than a pivot table. A
+ranking that says "spindle motor, 412 minutes, 6 events" is a spreadsheet. One
+that adds *"four of six close-out notes mention coupling alignment"* is a
+recommendation.
+
+---
+
+## Coverage honesty
+
+Three ways this ranking lies if you let it.
+
+**An asset with no history is not a good actor.** It is unreported. Do not let a
+machine with no maintenance records sit at the bottom of the ranking implying
+reliability. List unreported assets separately and say so, per
+`../../../shared/absent-is-not-zero.md`.
+
+**State the window, and check every asset has data across all of it.** An asset
+commissioned two months into a twelve-month window will look better than it is.
+Report its actual coverage rather than its apparent total.
+
+**Reason code coverage is a finding of its own.** Where stoppages are heavily
+coded "Other," the ranking by reason is not trustworthy and the report says so.
+That gap is itself worth fixing and nobody has ever mentioned it to them.
+
+---
+
+## Requirements and degradation
+
+Needs maintenance history across the asset base rather than for one machine.
+
+| Available | Behavior |
+|---|---|
+| Live maintenance history for all assets | Full ranking |
+| Exported maintenance history | Full ranking, at the export's freshness, stated |
+| Partial asset coverage | Rank what is covered, list what is not, never imply the uncovered are clean |
+| No maintenance history | Say the ranking cannot be produced and what would be needed. Do not substitute the downtime log alone, which describes stoppages rather than assets |
+
+That last row is worth holding to. Downtime events and maintenance history
+answer different questions, and a ranking built only from stoppages misses every
+failure that was caught before it stopped the machine — which is exactly the
+population a good PM programme creates.
diff --git a/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/evidence-sources.md b/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/evidence-sources.md
new file mode 100644
index 00000000..392df459
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/breakdown-diagnosis/reference/evidence-sources.md
@@ -0,0 +1,146 @@
+# The five evidence sources, and how to read each
+
+A technician standing at a stopped machine has all five of these available and
+time to assemble none of them. That gap is the skill.
+
+**MTTR's largest component is usually not the repair.** It is the diagnosis —
+working out what is actually wrong. Every minute spent there is a minute the
+plant is not producing.
+
+Listed in order of value, which is not the order anyone expects.
+
+---
+
+## 1. Free-text close-out notes — the highest-value input in the plugin
+
+When a technician closes a maintenance work order, they write what they found in
+prose:
+
+> *"Bearing was hot, replaced, coupling was misaligned again."*
+
+That sentence contains a diagnosis, a repair, and a recurring root cause that
+nobody has acted on. It is written by the person with their hands on the machine,
+it is the most honest record in the plant, and **nobody has ever aggregated it.**
+It sits in a text field on a work order and is read once, by the person who wrote
+it, never again.
+
+### How to mine it
+
+**Search this asset first, then siblings of the same model.** A machine that is
+new or has thin history is not a dead end — the same model in the next bay has
+been failing in the same ways for years.
+
+**Weight by symptom similarity, then by recency.** A note describing this exact
+symptom from two years ago beats a generic note from last month.
+
+**Read what the words actually say, including the throwaway ones.** "Again" is
+the single highest-signal word in a close-out note. So are "still," "same as
+last time," "temporary fix," and "needs proper repair when we have time." Each
+one is a technician telling you this is unresolved.
+
+### Check for templates before citing anything
+
+A CMMS lets a technician pick a stock close-out phrase, and many do. "Spindle
+noise reported. Could not reproduce. Monitored." on five machines of three
+different makes on the same day is a default, not five observations. Group the
+notes by exact text and count the makes and models each group spans (model from
+the asset name if the record has no model column; say so). Text shared across
+makes is shown, labelled "same text on N assets — not specific to this
+machine", and never cited as this asset's evidence. The same failure on
+same-model siblings is cited, as a fleet pattern. Do the grouping in code and
+print it, so the cited set is the same on every run over the same data.
+
+### Report coverage honestly
+
+Many notes are useless. "Fixed." "Repaired." "OK now." A field that exists is
+not a field that says anything.
+
+**State what fraction of the relevant history carried usable notes.** Do not
+over-read a terse note into a pattern — per
+`../../../shared/absent-is-not-zero.md`, an empty note is not evidence of a
+simple repair.
+
+> *"Nine prior work orders on this asset. Four have substantive close-out notes;
+> five say only 'repaired' or similar. The pattern below rests on those four."*
+
+---
+
+## 2. The sensor window — read shapes, not thresholds
+
+The historian logs temperature, vibration, pressure and spindle load at high
+frequency. Pull a configurable period **before** the failure.
+
+**Look for excursions, trends and step changes — not just threshold breaches.**
+This is the whole point. A vibration reading that climbed steadily for six hours
+and never once crossed its alarm limit is a bearing failing in plain sight, and a
+threshold check reports nothing at all. Three shapes worth naming:
+
+| Shape | Typically means |
+|---|---|
+| A steady climb | Progressive wear — bearing, tool, belt |
+| A step change | Something discrete happened — a part let go, a setting changed, a fixture moved |
+| An excursion that recovered | An intermittent fault, which is the hardest kind to catch and the most valuable to have caught |
+
+**Verify the window actually covers the event.** If the export stops an hour
+before the failure, say so and **do not reason from adjacent data as if it were
+the event.** That is the highest-risk error available here.
+
+**No sensor data at all is very common** — most assets in most plants are not
+instrumented. Proceed on the other four sources and say plainly that sensor
+evidence was unavailable. This is not a degraded run; it is the normal one.
+
+---
+
+## 3. Maintenance history
+
+What has broken before, what fixed it, what has been replaced recently.
+
+Weight **recency and symptom similarity** together. A part replaced last week is
+relevant to a failure this week in a way a five-year-old record is not — both
+because it may be the cause and because it may have been installed wrong.
+
+**A new asset with no history falls back to the manual and to sibling assets of
+the same model.** State which you used.
+
+---
+
+## 4. Photos — a genuine multimodal advantage
+
+Technicians photograph what they see, and always have. Read them for:
+
+- Visible damage, leaks, scoring, discolouration, wear patterns
+- Part numbers on the failed component, which shortens the repair
+- Display readings and fault codes on the machine's own panel
+
+**Describe what is visible. Never assert a diagnosis from an unclear image.** A
+blurry photo of a dark housing supports nothing, and saying so costs nothing.
+
+> *"The photo shows fluid pooled below the left side of the housing and
+> discolouration around the upper bearing cap. I can't tell from this image
+> whether the fluid is coolant or hydraulic oil, and that distinction changes
+> the diagnosis — worth a look."*
+
+---
+
+## 5. The manufacturer's manual
+
+A PDF sitting in a document library, containing exactly what is needed and never
+opened during a breakdown: troubleshooting trees keyed to fault codes,
+tolerances, and specified procedures.
+
+Match the fault code the machine is displaying to the manufacturer's own tree,
+and **cite the page**. A manufacturer's stated tolerance beats an inference every
+time.
+
+---
+
+## The citation rule
+
+Every candidate cause carries the specific evidence behind it — including the
+**specific prior work order numbers**, so the technician can read what was
+actually done last time rather than taking a ranked list on trust.
+
+**A candidate with no citation is a guess, and is labelled as one.** Not omitted:
+an experienced hunch is worth stating. But it is marked as reasoning rather than
+evidence, so the technician knows which of the five sources it came from — and
+that it came from none of them.
diff --git a/plugins/claude-for-manufacturing/skills/breakdown-to-next-report/SKILL.md b/plugins/claude-for-manufacturing/skills/breakdown-to-next-report/SKILL.md
new file mode 100644
index 00000000..f681021b
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/breakdown-to-next-report/SKILL.md
@@ -0,0 +1,210 @@
+---
+name: breakdown-to-next-report
+description: "Runs the chain from a machine going down to the diagnosis landing in tomorrow's production report: reads the sensor window, the maintenance history and its free-text close-out notes, technician photographs and the manufacturer's manual together, ranks likely causes with the cheapest test that tells them apart, then folds the diagnosis and its downtime into the next morning's downtime log and exceptions. Use when someone says \"run the breakdown chain,\" \"a machine went down,\" \"diagnose this and get it into the report,\" or \"breakdown to next report.\""
+compatibility: "Requires none. Chains breakdown-diagnosis and daily-production-report. Reads a CMMS connector (Limble is the worked example) for assets, history and PM plans when connected, plus a historian export and uploaded photos. Runs with no sensor data and no connector at all. Safety implications surface before any diagnosis. The diagnosis is advisory throughout and is never written back to a ticket."
+---
+
+# Breakdown to Next Report
+
+Chain 4. `breakdown-diagnosis` → `daily-production-report`.
+
+Every minute a machine is down, the plant is not producing. The largest
+component of MTTR is usually not the repair; it is working out what is actually
+wrong. This chain does that part, then makes sure the answer does not evaporate
+before the morning meeting.
+
+**Quick start**
+
+```
+→ Capture the event: asset, time down, symptom, fault codes
+→ SAFETY FIRST. Any safety implication surfaces before any diagnosis. Always
+→ Read sensor window, maintenance history, close-out notes, photos, the manual
+→ Rank causes. Each CITES specific prior work orders. No citation means a guess
+→ The technician works the list. The chain pauses here by nature
+→ The diagnosis and its downtime land in the next report's log and exceptions
+```
+
+---
+
+## Inputs
+
+| Input | Source | Form |
+|---|---|---|
+| The breakdown event | A user report, or a maintenance work order | Conversation, CMMS connector or maintenance export |
+| Sensor window around the failure | Historian export, scheduled or on demand | CSV |
+| Technician photos | Uploaded, or M365 | Images |
+| Everything else | Whatever the two member skills read | See each skill |
+
+---
+
+## The five steps
+
+**1. A machine goes down.**
+
+**2. Read the evidence together** — the recent sensor window, the maintenance
+history including its free-text close-out notes, the technician's photographs,
+and the manufacturer's manual. The close-out notes are the highest-signal input
+and the least used: what the technician actually wrote about what they found,
+in prose, which nobody ever aggregates.
+
+**3. Rank the likely causes**, each with the evidence supporting it, **the
+cheapest and fastest test that tells it apart from the others**, and the
+expected fix. Every candidate cites the specific prior work orders behind it,
+so the technician can read what was actually done last time. A candidate with
+no citation is a guess and is labelled as one.
+
+**4. The technician works the list.** The chain pauses here by nature: this is
+a person at a physical machine.
+
+**5. The diagnosis and the resulting downtime feed into the next production
+report's downtime log and exceptions**, through `daily-production-report`.
+
+**State the match rule, and say the stoppage was counted once.** The
+diagnosis record and the MES downtime row describe the same stoppage. The
+chain matches them on **asset plus start time** — same `asset_id`, and
+`started_at` within the same shift — and the report carries one row for the
+stoppage, with the diagnosis fields attached to it. Two required lines in the
+output: *"Matched the diagnosis record to MES row <asset, started_at> on asset
+plus start time"* and *"counted once."* Where no MES row matches, say that,
+and the diagnosis record stands alone as the row. Flagging the possible
+double count without stating the rule leaves the reader to reconcile it.
+
+---
+
+## Approval gates
+
+**Step 4 is the pause, and it is not a gate the plugin enforces** — it is a
+human working a machine. The chain simply has nothing to do until they are
+done.
+
+**Say whether step 4 happened.** The record carries `technician_step`:
+`confirmed` when the technician came back with a confirmed or corrected cause,
+`pending` while the chain waits, `skipped` when the record was folded in with
+no technician step (a test, a demo, or "put it in the report now"). The output
+states it in one line, and the report carries it beside the cause: *"cause
+proposed, technician step skipped"* reads differently from *"cause proposed,
+technician still working"*.
+
+**The diagnosis is advisory throughout.** A CMMS connector's write scope for
+closing or updating work orders is unconfirmed (Limble's is not public), so the output is a draft the technician
+applies, never an automatic ticket update. Nothing here writes to a system.
+
+**Safety outranks the sequence.** Where a failure has a safety implication, it
+surfaces **first**, before any diagnosis. Never let a diagnosis suggestion
+precede a safety flag.
+
+---
+
+## The handoff is the chain's whole risk
+
+`breakdown-diagnosis` emits a downtime record in **exactly** the shape
+`daily-production-report` consumes, with **no transformation step in between**.
+
+The reason is specific: the report already reads downtime events from the MES
+or historian export. A record arriving from a diagnosis is a **row in that same
+log**, not a separate feed. If the two shapes differ, the report has to
+reconcile them, and a reconciliation step between two sources of downtime is
+exactly how a stoppage gets counted twice or dropped.
+
+Read `../../shared/contracts/downtime-record.md`.
+
+Two fields carry weight across the handoff. `safety_flagged` is required, and a
+missing value is treated as unknown rather than false. `duration_minutes` is
+null while the machine is still down and **never zero**, because a zero would
+rank an ongoing outage last in a log sorted by minutes.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+The ranked candidate causes with their evidence and discriminating tests, the
+cited history behind each, a plain statement of what the sensor data showed,
+the PM plan adjustment drafted for the planner, and the structured downtime
+record that flows into the next report.
+
+**The figures block** — required. How many maintenance records the asset has,
+how many carried usable notes, how many downtime events and minutes: each is
+printed from a query run in this session, listed with that query, and quoted by
+the prose rather than retyped. A chain summary is where a count most often
+drifts from the step that produced it. Per
+`../../shared/computed-figures.md`.
+
+**The Operations command-center page, maintenance section** — an artifact you
+place. Read `../../shared/command-center.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **No sensor data for this asset** — very common, most machines are not
+ instrumented. Proceed on history, notes, photos and the manual, and say
+ clearly that sensor evidence was unavailable.
+- **A new machine with no history** — fall back to the manual and to sibling
+ assets of the same model.
+- **Close-out notes are terse or useless** — report the coverage honestly
+ rather than over-reading "fixed."
+- **Photos are ambiguous** — describe what is visible. Do not assert a
+ diagnosis from an unclear image.
+- **The machine is still down when the report runs** — the record carries a
+ null duration, leads the exceptions, and is excluded from the minutes ranking
+ with that exclusion stated.
+
+---
+
+## Degradation
+
+| Not available | What happens |
+|---|---|
+| The historian export | Run on history, notes, photos and the manual. Say sensor evidence was unavailable |
+| The current PM plan | The PM-plan-adjustment step degrades to a recommendation that first asks what today's interval is. **The step stays either way** |
+| **A CMMS connector** (Limble or any other) | See below |
+
+**Check the freshness of anything export-sourced, and say it.** A scheduled
+export that silently stopped is the normal failure here, and a diagnosis built
+on a stale sensor window or stale history reads exactly like one built on
+current data. Name the age of each source in the output.
+
+**If Limble isn't included, or no CMMS connector is live** — the
+default — this is the chain that changes most. It still
+runs end to end: step 2 reads maintenance history from a scheduled export
+rather than live tickets, and everything downstream is unchanged. What is lost
+is the chain's real-time character. A breakdown is happening *now* and a nightly
+export is not, so the tickets closest to the event are exactly the ones
+missing.
+
+**Any of three mitigations satisfies step 2**, and all three are cheap: an
+on-demand export the technician triggers, pasted or uploaded work orders for
+that asset, or the technician simply describing recent work in conversation.
+Build the chain so any one of them is enough.
+
+---
+
+## Chain position
+
+**This is Chain 4 itself.** Members: `breakdown-diagnosis`,
+`daily-production-report`.
+
+**Metric.** MTTR, owned by `breakdown-diagnosis`. Downtime cost visibility,
+owned by `daily-production-report`, which prices downtime against the
+configured cost-per-hour on every run.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `../breakdown-diagnosis/SKILL.md` | Steps 2 and 3, and the bad-actor batch mode |
+| `../daily-production-report/SKILL.md` | Step 5 |
+| `../../shared/contracts/downtime-record.md` | The handoff — the shape that must not be transformed |
+| `../../shared/command-center.md` | The Operations page, and why it is never a write |
+| `../../shared/computed-figures.md` | Before stating any count — the figures block |
diff --git a/plugins/claude-for-manufacturing/skills/custom-connector/SKILL.md b/plugins/claude-for-manufacturing/skills/custom-connector/SKILL.md
new file mode 100644
index 00000000..8b541dbc
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/custom-connector/SKILL.md
@@ -0,0 +1,418 @@
+---
+name: custom-connector
+description: "Gets the plugin talking to a manufacturing system that has no vendor MCP, working down a seven-tier access ladder in order — vendor MCP, community MCP, a scoped API wrapper, a read-only database view, a Zapier bridge, screen automation as a last resort, or a scheduled export contract — and stopping at the highest rung that actually works. States plainly at every rung what the customer gets, what it costs, and how it will eventually break. Most often the answer is that a vendor MCP already exists and nothing needs building — just an admin turning it on. Maps whatever it reaches onto the consolidated dataset schema, so no downstream skill changes. Credentials never enter the conversation. Use when someone says \"connect our ERP,\" \"we use SAP,\" \"can you reach our MES,\" \"set up a connector for this system,\" or \"our system isn't supported.\""
+compatibility: "Requires none of its own. Reads whatever the target system exposes — an existing MCP, a documented API, a database view, a Zapier connector, or a scheduled export — and produces setup instructions, a wrapper, a view definition, a Zap specification, or an export specification depending on which tier the system actually supports. Never accepts a credential in conversation."
+---
+
+# Custom Connector
+
+SAP and Infor have the largest installed base in manufacturing, and neither
+has an official MCP for business data. Neither does most of what actually
+runs a mid-market plant — a large share of it is on-prem, a decade old, and
+has a SQL database but no API at all. **That is not a failure case. It is
+the normal case**, and this skill is what turns "your system isn't
+supported" from a dead end into scoped, buildable work with a known
+ceiling.
+
+**A Claude skill produces artifacts. It does not stand up and host
+infrastructure.** That boundary decides what "as far as it can go" means
+at every rung of the ladder below — this is not a deployment tool, and
+scoping it as one is the most common way to get it wrong.
+
+**The most common good outcome is the one most likely to be missed.** A
+vendor has often already shipped an MCP server, quietly, without
+announcing it anywhere the customer would see. Recognizing that and
+walking an admin through turning it on is worth more than a week of
+wrapper code, and it is the first thing this skill checks, not an
+afterthought.
+
+**Quick start**
+
+```
+→ Identify the system precisely: vendor, product, version, on-prem or cloud
+→ Scope the need. "Connect our ERP" is unbuildable; one data flow is
+→ Work the ladder in order. Don't build before checking what already exists
+→ Report the finding and its tier before building anything
+→ Pick the tier, record why, and what was ruled out
+→ Handle credentials narrowly. They never enter the conversation
+→ Build only what Step 2 scoped, then map it onto the consolidated schema
+→ Test against real data, show it back, ask what's still missing
+→ Say how it will break, while the customer is still listening
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| System identity | User, in conversation | Vendor, product, version, cloud or on-prem, who administers it |
+| The specific need | User, and the skill being unblocked | What data out or action in, how often, which skill it serves |
+| Consolidated dataset schema | `data-consolidate` | `../../shared/contracts/consolidated-dataset.md` — the mapping target |
+| MCP registries and vendor docs | Web research | — |
+| Credentials | Customer IT, through a secure path | Never in a skill file, a prompt, or the chat |
+
+---
+
+## Workflow
+
+### Step 1 — Identify the system precisely
+
+Vendor, product, version, deployment model, and who administers it inside
+the customer's organization. **"We use SAP" is not enough** — S/4HANA
+cloud and ECC on-prem are different problems on different tiers. Where the
+name is ambiguous, ask the system's administrator for product, version and
+hosting. Never infer them from a login URL. Version and hosting narrow the
+search; they do not by themselves prove any rung works. Read
+`reference/known-systems.md`.
+
+### Step 2 — Scope the need before looking at access
+
+**"Connect our ERP" is unbounded and unbuildable.** "Pull closed work
+orders with actual cost, so `quote-build` has real cost history" is
+buildable today. (How fresh it is depends on the tier: live at Tiers 1 to 3,
+where nothing is scheduled; a stated cadence only at Tiers 4 to 7. Never
+promise a nightly sync a live connector does not do.) Scope is what keeps this an afternoon instead of an
+engagement.
+
+### Step 3 — Work the ladder, in order
+
+Vendor MCP, community MCP, documented API, database access, Zapier,
+export. **Do not build before checking what already exists** — most of the
+time something does. Read `reference/access-ladder.md`.
+
+**Report each rung by the call that checked it, in the connection plan**
+(step 4), not rung by rung in the reply. *"I searched the public MCP
+registry for SAP and found nothing official"* — if a registry search is what
+ran. Never *"I checked your connector directory"* or *"three connectors are
+installed on this account"* unless the account's own connector listing was
+queried in this run; which tools happen to be loaded in the session is not
+that listing. A rung that could not be checked is reported as not checked,
+with the reason. Per `../../shared/command-center.md`.
+
+**Tier 2 is searched, not handed back.** "A community MCP might exist, worth
+ten minutes of your time" is the rung skipped. Search for one with the tools
+available and report what came back, marked community and unverified; where
+no search tool exists in the session, say the rung was not checked and why.
+**Then land on a tier in the same turn, with reasons** — Tier 2 found and
+reviewed, or Tier 3 because nothing at Tier 2 was found or fit. Deferring the
+Tier-2-versus-3 call to the user is not a landing.
+
+### Step 4 — Report the finding before building anything
+
+**The reply leads with the decision, and the ladder research goes in the
+connection plan**. For a plan or "can you connect X"
+request, the reply is, in this order:
+
+1. **The recommendation**: the path for each system in plain words (vendor
+ MCP, API, database view, scheduled export), why, and that it is
+ conditional on what is still open.
+2. **Connection status, honestly**: nothing is connected; what this run
+ confirmed, and each condition still open.
+3. **Three first questions, each labelled with who answers it**: for example
+ the ERP administrator (version, hosting, whether the licence includes API
+ access), the MES developer (where the data lives, whether hours are
+ measured or backflushed), and the person asking (what the data is for and
+ how fresh it must be). Three, not a questionnaire.
+4. **A short comparison of manual, export and API**: what each gives, what it
+ needs, how it breaks, and a provisional effort.
+5. **Where the connection plan is.** Save it as
+ `connector-output/connection-plan.html` (house style, internal), one file
+ saved over the last run's: per system, the tier decision record with each
+ rung and the call that checked it (or *not checked*, and why), what was
+ ruled out, the sources, and the proposed field mapping. Name the path.
+ With no way to write a file, print it in the reply below the comparison.
+
+No tier-by-tier walk in the reply, and about 250 words before the comparison
+table; the reply never claims a check the plan does not show. **This layout
+is for a plan or "how do we connect" request only.** A request to set up,
+build, map files, test a connection, register or verify one, or a question
+about one system is answered in the reply in full, as before: **the field
+mapping onto the dataset's own column names, its transforms and the test
+results are always in the reply** when the person asked for any of those,
+even when the reply also leads with a recommendation. The plan file still
+holds the ladder. Setup steps for a Tier 1 or 2 system are an exception: the
+admin acts on them, so they stay in the reply, quoted as below.
+
+State the tier and its consequences, in the customer's own terms, before a
+line of anything gets built:
+
+> *"Limble already publishes a hosted MCP — Tier 1, nothing to build. It
+> isn't one of the plugin's four supported connectors, so it's added for your plant. A Limble
+> Super User generates an API key at Settings → Configuration → API Keys. The
+> secret is shown once. The client ID and secret are sent as the
+> `Limble-Client-ID` and `Limble-Client-Secret` headers, set as
+> `LIMBLE_CLIENT_ID` and `LIMBLE_CLIENT_SECRET` in the environment the
+> connector runs in. That gives assets, work orders and maintenance history in
+> real time. The one limit: write scope for closing out work orders isn't
+> confirmed publicly, so plan on `breakdown-diagnosis` drafting an update the
+> technician applies rather than updating the ticket itself. Want me to walk
+> through it?"*
+
+**Setup steps are quoted word for word from `reference/known-systems.md`** —
+the four supported connectors from its setup-steps table, and a
+vendor-published MCP (Limble, Onshape) from its *Vendor-published MCP* table;
+the Limble steps above are that row. Never paraphrase a row and never add a
+step it does not contain: not "install it from the connector directory," not
+"sign in and authorise." For Onshape that means opt in to Onshape Labs and
+Subscribe to the FeatureScript MCP Server app, with the cost stated as not
+public and unconfirmed. No admin step: none is documented. **How the plant
+registers the vendor's MCP address with Claude is not written in the table,
+so do not invent it** — no menu path, no "ask your admin to enable it." Give
+the address and what it needs, and say that registering it as a custom
+connector in Claude is done by whoever manages connectors for their Claude
+account.
+
+**Readiness is conditional until this run has evidence for it.** Never write
+*"works today"*, *"available now"* or *"nothing needed from IT"* unless this run
+saw it: a licence or permission the customer confirmed, an export or report
+they showed exists, records shown back. Otherwise name each condition still
+open: whether the licence includes API access, whether the integration user
+can be granted the scope, whether the deployment is reachable, whether the
+export or report exists and who may schedule it. Every proposed field mapping
+stays *proposed, unverified* until instance evidence exists.
+
+**Sources: the vendor's and publisher's own documentation first.** A technical
+specific (auth method, paging, endpoint names, rate limits) that no official
+source in this run states stays *unknown*, and a community README that
+contradicts the vendor is reported as a contradiction, not resolved. **Never
+give a link this run did not open**; a file this run wrote is named by its
+path. Every effort estimate is labelled *provisional* with what it assumes.
+
+Once connected, record the system's `### Systems` line in the plant profile as
+`live (custom)`, through `onboarding`'s reconfigure, so every skill that reads
+"CMMS connector live" or "CAD connector live" takes its live path.
+
+### Step 5 — Pick the tier, and record why
+
+Which tier, why, and what was ruled out and on what evidence. **The
+decision record matters more than the code** — it's what the next engineer
+reads, and it's what stops the same question being re-litigated in three
+months.
+
+### Step 6 — Handle credentials properly
+
+Narrowest scope that does the job. Read-only unless a write is genuinely
+required and approved. A dedicated integration user, never someone's
+personal login, so access can be revoked without locking a person out.
+Tokens and OAuth only, never a password. Read
+`reference/credentials-and-failure-modes.md`.
+
+### Step 7 — Build scoped
+
+Only the entities Step 2 defined. A narrow connector is easier to secure,
+easier to reason about, and far less likely to break on a vendor update.
+
+### Step 8 — Gate every write path
+
+The same draft-and-approve rule as the rest of the plugin. A connector does
+not get an exception for being infrastructure rather than a skill output.
+
+### Step 9 — Map onto the consolidated dataset schema
+
+So downstream skills read it without knowing it is new. **This is what makes a
+connector useful rather than merely present** — one that returns data in its
+own shape has moved the problem, not solved it. Per
+`../../shared/contracts/consolidated-dataset.md`. Map every field the scoped
+need names: closed-job cost goes to `production_work_orders`' actual-cost
+columns. **Where the schema has no home for a field, say so and stop**: the
+contract gains it with a version bump, or the field stays out. Never claim "no
+downstream skill changes" for a field no skill can read.
+
+**Every mapping row keeps its evidence**: the source field, its original value
+and unit, the proposed destination, the transform it needs, its status
+(*proposed* until instance evidence exists, *confirmed* only after Step 10), the
+owner role who confirms it, and the open question. Review, never drop or force:
+rate-based routing standards (pieces per hour is a stated transform to time per
+piece, the original kept beside it), cost elements such as material burden,
+lower-level assembly costs rolled into a parent, and units. A field with no
+honest destination is listed as unmapped, with the reason.
+
+**Job hours: measured or backflushed, and which system owns them.** Before
+labour hours are offered to `quote-build` as actuals, establish whether they
+are measured (clock-in, MES) or posted standards backflushed on completion, and
+which system is the source of record. Until that is confirmed, map them with
+`actuals_confidence` low and `confidence_reason` *"hours basis unconfirmed:
+measured or backflushed not known"*; discovery and mapping go on, with the
+confirmation named as the prerequisite. Where the ERP and the MES disagree on
+hours for the same job, that is the two-sources-of-truth edge case below.
+
+### Step 10 — Test against real data, and show it back
+
+Pull actual records, display them, and ask whether anything expected is
+missing. **That last question is what catches the field that quietly
+wasn't mapped.** Vendor example payloads prove nothing; customized fields
+are the norm in manufacturing.
+
+**Validation has a named scope, never a blanket "verified".** Record what was
+actually checked, each kind separately: fields an admin confirmed, records
+sampled and compared (with how many), transforms checked, and completeness
+reconciled against an independent count from the source system itself. A row
+count that matches the export's own manifest proves the file is internally
+consistent, not that the source query returned everything. Five records
+checked verify those records, not every mapping. The status line says
+*validated for <scope>* and lists what remains open.
+
+**No real records, no registration.** Where Step 10 cannot run (no instance
+yet, access not granted, a test), the connector's status is
+**Untested: not registered**, stated in the reply and on the credential record, and Step 11
+waits until real records have been shown back and confirmed.
+
+### Step 11 — Register it
+
+Only after Step 10 passed on real records. What it reaches, what it cannot do, how it refreshes, and which skills it
+now unblocks — stated concretely, not as a general capability claim.
+
+### Step 12 — Say how it will break
+
+While the customer is still paying attention: token expiry and the
+renewal path, vendor API changes that arrive without warning, rate
+limits, schema drift at Tier 4, task limits at Tier 5. **A connector that
+fails silently is worse than no connector.** Read
+`reference/credentials-and-failure-modes.md`.
+
+---
+
+## Approval gates
+
+**A write path is never assumed, only granted.** Read-only by default; a
+write is proposed, its scope named, and it proceeds only on explicit
+approval — the same rule every skill in this build follows for a
+consequential action. **Every refusal of write scope, and every "build us the
+connector," carries the sentence:** *"A Claude skill produces artifacts; it
+does not stand up or host infrastructure."* What this skill produces is the
+wrapper, the view definition, the Zap specification or the export
+specification; an engineer, a DBA or IT deploys it.
+
+**Tier 4 is declined with the view definition in hand.** When someone says
+"just query the production database," the reply declines direct access, names
+the outage risk, **and supplies the draft read-only view definition in the
+same turn, in the reply itself** — the `CREATE VIEW` scoped to the entities
+Step 2 named, as a SQL block the DBA can read where they are, not only a file
+written to disk that "is available in the workspace". Declining without the
+draft on the page hands the work back.
+
+**A Tier 7 specification names its own owner role.** Every export spec ends
+with: how it fails (silently, the folder stops getting newer), how that is
+detected (`data-consolidate`'s freshness check, which is why that check is
+mandatory), and **who owns the export, as a role** — "your ERP administrator,"
+"the IT person who schedules the report" — even when no name is known. Asking
+the user to designate someone is not naming the owner.
+
+**Credentials never enter the conversation.** Not pasted, not typed, not
+read back for confirmation. They go into connector settings on the
+customer's side, through their own secure path. If someone pastes one
+anyway, say plainly that it should be rotated because it has touched the
+transcript, and that nothing was done with it. **Never repeat any part of
+it** — not quoted, not in code formatting, not inside the rotation
+instruction. It is "the key you pasted." Check the reply for any run of
+eight or more of its characters before sending. Per
+`../../shared/secret-config.md`, *Never repeat what was typed*.
+
+**Tier 6 requires the customer's explicit, informed acceptance of the
+fragility** before anything is built there — it is recommended against by
+default, not merely discouraged.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked. The
+connection plan is the exception: it is saved and named, per step 4, and
+printed in full only when no file can be written.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**A working connection** (Tiers 1–6), or **an export specification**
+(Tier 7).
+
+**Setup instructions** for the customer's admin, where the path is Tier 1
+or 2 — the most common and most valuable output this skill produces. **At
+Tier 1 or 2, this is the whole output — nothing gets built.** A vendor or
+community MCP that already exists is a setup task, not an engineering one.
+
+**The tier decision record** — which rung, why, what was ruled out, and
+what the customer gives up by not being one rung higher. It lives in the
+connection plan, `connector-output/connection-plan.html`, with each rung and
+the call that checked it; the reply leads with the recommendation, status,
+three questions and the manual/export/API comparison per step 4, and names
+the file.
+
+**The field mapping document** — the new system onto the consolidated
+dataset schema, **so that no downstream skill ever has to change** to read
+data from a newly connected system. A connector that returns data in its
+own shape has moved the problem, not solved it.
+
+**The credential and scope record** — what access was granted, to what,
+read or write.
+
+**Test results against real customer data**, shown back to the user.
+
+**A failure-mode note** — how this breaks, what it looks like when it
+does, and who fixes it. Said **up front, while the customer is still
+paying attention** — never something discovered for the first time in
+production.
+
+**At Tier 7, the export specification is complete enough to hand to the
+customer's IT department as-is** — exact fields with types and units,
+format, encoding, naming convention, landing path, cadence, and what to
+do about late or corrected records — with no follow-up call needed to
+fill in something this skill should have already asked.
+
+---
+
+## Edge cases and failure modes
+
+- **A vendor MCP exists but the customer's plan tier doesn't include it** —
+ say what the upgrade unlocks so they can price the trade-off, then drop
+ to the next viable tier.
+- **License tier excludes API access** — Tier 4, 5 or 7, and say what an
+ API license would buy.
+- **On-prem behind a firewall with no external reachability** — Tier 7.
+ Don't design around a VPN the customer hasn't agreed to.
+- **Customer IT won't grant any access** — common, and it needs a named
+ escalation path rather than a stalled build. Tier 7 with an export
+ request usually unblocks it, because IT is far more willing to schedule
+ a report than issue credentials.
+- **Rate limits too low for the data volume** — move the bulk path to
+ Tier 7 and keep the API for events. The two tiers coexist.
+- **Vendor terms prohibit third-party access or direct schema reads** —
+ stop. That's a legal question for the customer, not an engineering one.
+- **ITAR or export-controlled data in scope** — blocking gate. Do not
+ proceed without explicit clearance.
+- **Genuinely undocumented homegrown software** — Tier 4 or 7, and expect
+ the customer's own developer to be the only reliable source of truth.
+- **Two systems claim to be the source of truth for the same record** —
+ surface the conflict; don't silently pick one. A business decision, not
+ a mapping decision.
+
+---
+
+## Chain position
+
+**Not part of a chain.** A utility that widens what every other skill can
+reach — like `onboarding`, it sits outside the five named chains by
+design.
+
+**Metric.** Systems reachable per customer; time to first data from an
+unsupported system.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/access-ladder.md` | Step 3 — the seven tiers in full: path, freshness, build cost, maintainer, and the catch at each rung |
+| `reference/known-systems.md` | Step 1 — the systems landscape by category, and where common systems land today |
+| `reference/credentials-and-failure-modes.md` | Steps 6 and 12 — credential handling, and stating failure modes before they happen |
+| `../../shared/contracts/consolidated-dataset.md` | Step 9 — the schema every new system maps onto |
diff --git a/plugins/claude-for-manufacturing/skills/custom-connector/reference/access-ladder.md b/plugins/claude-for-manufacturing/skills/custom-connector/reference/access-ladder.md
new file mode 100644
index 00000000..be58b861
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/custom-connector/reference/access-ladder.md
@@ -0,0 +1,224 @@
+# The seven-tier access ladder
+
+Work down it in order. **Stop at the highest rung that works, and tell the
+customer what they gave up by not being one rung higher.** Never skip a
+rung without saying why — "we built a custom API wrapper" is the wrong
+answer when a vendor MCP existed and nobody looked.
+
+| Tier | Path | Freshness | Build cost | Who maintains it | The catch |
+|---|---|---|---|---|---|
+| 1 | Vendor-native / hosted MCP already exists | Real-time | None — setup only | The vendor | You inherit the vendor's scope exactly, including its limits |
+| 2 | Community or third-party MCP | Real-time | Low — evaluate and wire | Nobody, unless you fork it | You own it the moment it breaks |
+| 3 | Documented API → scoped custom MCP wrapper | Real-time | Medium | You | API access may be a paid license tier; rate limits; vendor deprecation |
+| 4 | Read-only database view or replica | Near-real-time | Medium | You and the customer's DBA | Schema changes break it silently; may void vendor support |
+| 5 | Zapier / iPaaS bridge | Minutes (polled) | Low | Zapier and you | Limited to exposed triggers/actions; per-task cost; another vendor in the data path |
+| 6 | Screen-level automation (RPA) | Varies | High | You, constantly | Fragile, and often prohibited by vendor terms |
+| 7 | Scheduled export contract | Export cadence | Low | Customer's IT | Not real-time; silently stops running |
+
+**One deliberate crossover:** for bulk or historical data, skip Tiers 5 and
+6 and go straight to Tier 7. Pulling three months of production history
+through Zapier is slow, expensive and pointless when a nightly CSV does it
+properly. **Use Tier 5 for events** — "a work order was created," "a
+quality hold was raised" — **Tier 7 for volume.**
+
+---
+
+## What the skill delivers, and what a person still does
+
+A Claude skill produces artifacts. It does not stand up and host
+infrastructure — that's the boundary that decides what "as far as it can
+go" means at every rung.
+
+| Tier | What the skill produces | What a person does |
+|---|---|---|
+| 1 — Vendor MCP | Research finding, plan-tier check, step-by-step setup instructions, scope recommendation, a test call once connected | The customer's admin generates credentials and enables the connector |
+| 2 — Community MCP | Evaluation (currency, maintainer, requested scope, security review), a recommendation, setup instructions | The customer or engineer installs it |
+| 3 — API wrapper | The API assessment, the scoped surface design, the generated wrapper code, the field mapping, deployment instructions | An engineer reviews, deploys and hosts it |
+| 4 — DB view | The view definition or SQL, the field mapping, the access request to hand the DBA | The customer's DBA creates the view and grants read access |
+| 5 — Zapier bridge | The Zap specification — trigger, filter, action, field mapping, destination — plus the cost estimate at their volume | The customer builds it in Zapier's UI |
+| 6 — RPA | A recommendation against it, with the specific reasons | Nothing, preferably |
+| 7 — Export contract | The complete export specification — fields, types, format, cadence, naming, landing path | The customer's IT builds the scheduled export |
+
+Read down the right-hand column and the pattern holds throughout: **the
+skill removes the thinking, the research and the writing; a person
+performs the privileged action.** That's not a limitation — it's the same
+approval boundary the rest of the plugin runs on, and it's what makes a
+connector skill safe to ship.
+
+---
+
+## Tier 1 — A vendor-native or hosted MCP already exists
+
+**The most common good outcome, and the one most likely to be missed.**
+Several manufacturing vendors have shipped MCP servers quietly, without
+announcing them anywhere the customer would see. The job here is not to
+build anything — it's to recognize the situation and walk the customer's
+admin through turning it on.
+
+The output is setup instructions specific to that system, never code:
+
+- Where in the vendor's admin console to generate credentials, named
+ exactly
+- What scope to request — read-only unless a write is genuinely needed
+- Whether the customer's plan tier includes it, and what to do if it
+ doesn't
+- Where to enter the credentials on our side, with an explicit instruction
+ **not** to paste them into the chat
+- A test call that proves it works, with real records shown back
+
+**Worked example — Limble CMMS**, a vendor-published MCP that is not
+one of the four supported connectors, and exactly this case. Limble publishes a hosted MCP server at
+`mcp.limblecmms.com`, authenticated with an API client ID and secret.
+Nothing needs building. A Limble admin generates the credentials in
+Limble's admin settings; those go into connector settings on our side, not
+into the conversation. Once connected it gives assets, maintenance work
+orders, maintenance history and PM schedules.
+
+The ceiling to state up front: write scope for closing out or updating
+work orders isn't confirmed in Limble's public setup guide. Plan for
+read-only, which is why `breakdown-diagnosis` produces a draft the
+technician applies rather than updating the ticket itself. If write turns
+out to be available, that's an upgrade, not a redesign.
+
+**Repercussion of landing here: none.** This is the best available
+outcome. The only thing the customer gives up is whatever the vendor's MCP
+doesn't expose, and that's worth naming explicitly rather than discovering
+it later.
+
+---
+
+## Tier 2 — A community or third-party MCP exists
+
+**Search for it; do not tell the customer to.** Query the public MCP
+registries and the vendor's community with the tools the session has, and
+report the hits, marked community and unverified. No search tool in the
+session means the rung is reported as not checked, with that reason, and the
+ladder moves on in the same turn.
+
+Faster than building, but it comes with an obligation: a third-party MCP
+will see the customer's production data, so it gets a real security
+review, not a glance. Answer each of these in the evaluation, and say
+*not found* where the listing does not say:
+
+| Check | Why |
+|---|---|
+| Publisher and maintainer, and when it last changed | A stale community server is a fork you will own |
+| Licence, **and what it depends on** | A free MCP that needs a paid commercial driver (a JDBC licence, a vendor SDK) is not free |
+| Transport: local `stdio` or remote | A `stdio` server only reaches the session while the machine running it is on |
+| Where it runs, and who hosts it | The customer's machine, their server, or the publisher's cloud: that decides who sees the data |
+| Read-only, **enforced at the credential** | A listing's "read-only" claim is not enforcement. Give it a read-only account; where listings contradict themselves, assume write |
+| Scope it requests, and where it sends data | A server that phones anywhere but the system is out |
+| Who owns the security review | A named role at the customer, before it is wired |
+
+**Repercussion of landing here: you own it the moment it breaks, without
+having written it.** Either fork it into the customer's control or budget
+for the day the vendor changes their API and the maintainer has moved on.
+Say this to the customer before wiring it, not after.
+
+---
+
+## Tier 3 — Documented API, scoped custom wrapper
+
+The usual answer for modern cloud ERP and QMS. Build a thin wrapper
+covering only the entities the skills actually need — not the whole API.
+
+Check three things before committing:
+
+1. **Does the customer's license tier include API access?** Some ERP
+ vendors charge separately for it. Finding this out late costs a week,
+ and it's the single most common surprise at this tier.
+2. **Rate limits against the data volume the skills actually need.**
+3. **Auth model and token lifetime** — a token expiring every 90 days
+ needs a renewal path the customer knows about.
+
+**Repercussion of landing here: you now maintain an integration.** Vendor
+API version changes arrive without warning, and the surface has to be
+re-tested against them. This is where "an afternoon" becomes "a week" if
+the scope isn't held narrow — hold it narrow.
+
+---
+
+## Tier 4 — Read-only database view or replica
+
+Often the only path for on-prem legacy systems, and sometimes better than
+the API because it exposes history the API doesn't.
+
+Work against a read-only view or a replica, **never the live production
+database directly**, and never without the customer's DBA signing off. A
+badly-scoped query against a production ERP database is a plant outage,
+not a bug. Have the DBA create the view; don't ask for schema-wide access.
+**Supply the draft view definition in the turn that declines direct access**:
+a `CREATE VIEW` over only the columns the scoped need requires, with a
+comment on each column naming the dataset field it maps to, for the DBA to
+review and own.
+
+**Repercussion of landing here: two real ones.** First, vendor upgrades
+change schemas silently — nothing errors, the query just returns the wrong
+thing or nothing. Second, some ERP vendors treat direct schema access as
+support-voiding. Ask the customer to confirm their position rather than
+assuming — that's their commercial risk, not ours.
+
+---
+
+## Tier 5 — Zapier or iPaaS bridge
+
+Reach for this when there's no reachable API but the system has a Zapier
+(or Make, or Workato) integration. Genuinely fast to stand up, and the
+right tool for event-driven pushes — "a work order was created," "a
+quality hold was raised" — landing a record where the plugin can see it.
+
+State all of these before building:
+
+- **A paid plan is required**, and pricing is per task, so cost scales with
+ volume.
+- **Limited to the triggers and actions the connector exposes** — usually a
+ fraction of the underlying API. If the field isn't in the connector, it
+ isn't available at this tier.
+- **Polling means latency** — minutes, not real-time.
+- **Another vendor in the data path.** In regulated manufacturing
+ (aerospace, medical, defense) that's a security and data-processing
+ question the customer's IT has to sign off on, not a technical detail.
+
+**Repercussion of landing here: it's the wrong tool for bulk history** —
+go to Tier 7 for that — and the customer pays per record, forever, for
+something a nightly export would do for free.
+
+---
+
+## Tier 6 — Screen-level automation
+
+Named for completeness, and **recommended against.** It breaks on any UI
+change, any session timeout, and anything with MFA. It's frequently
+prohibited by the vendor's terms of service.
+
+Only reach for it if the customer explicitly accepts the fragility and
+confirms it's permitted under their agreement. Say plainly that it will
+break, and that it will break without a useful error.
+
+---
+
+## Tier 7 — Scheduled export contract
+
+The floor that always works, and the one the rest of the plugin already
+assumes. A plant that can't give you an API can almost always give you a
+nightly CSV, because it's already producing one for somebody's Excel
+report.
+
+The deliverable is a specification the customer's IT can implement without
+a follow-up call:
+
+- Exact fields, with types and units
+- File format, encoding and delimiter
+- Naming convention and landing path in the M365 folder
+- Cadence, and what time window each file covers
+- What to do about late or corrected records
+
+**Repercussion of landing here: freshness is capped by the export
+cadence** — everything the plugin reports is as of the last drop. That's
+fine for `daily-production-report` and `quote-build`, not fine for a live
+breakdown diagnosis, so say which skills degrade and by how much. Also:
+exports stop running silently, which is exactly why `data-consolidate`'s
+freshness check is mandatory rather than nice-to-have. **The export request names the
+owner as a role** — "your ERP administrator" — even when the person is unknown;
+a spec whose owner line is blank has no one to call when the folder stops
+getting newer.
diff --git a/plugins/claude-for-manufacturing/skills/custom-connector/reference/credentials-and-failure-modes.md b/plugins/claude-for-manufacturing/skills/custom-connector/reference/credentials-and-failure-modes.md
new file mode 100644
index 00000000..391ba185
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/custom-connector/reference/credentials-and-failure-modes.md
@@ -0,0 +1,67 @@
+# Handling credentials, and saying how it will break
+
+---
+
+## Credentials
+
+**Narrowest scope that does the job.** Read-only unless a write is
+genuinely required and has been approved — not "might be useful later,"
+approved for a stated, current need.
+
+**A dedicated integration user, never someone's personal login.** Access
+tied to a person breaks the day they change roles or leave, usually at the
+worst possible moment, and it can't be revoked without locking that person
+out of everything else they use the same login for.
+
+**Tokens and OAuth only. Never a password.** A password is a standing
+secret with no expiry and no scope; a token can be scoped, rotated, and
+revoked without touching anything else the account can do.
+
+**Say plainly what the connector will be able to reach before it's
+created.** Not after — the customer's admin is granting access based on
+what they're told, and finding out afterward that the scope was broader
+than expected is how a plant stops trusting the next connector request.
+
+**Never accept a credential in conversation.** Not pasted, not typed, not
+read back to confirm it was copied correctly. If someone pastes one
+anyway, say plainly that it should be rotated — a credential that has
+touched a chat transcript is not clean again just because nobody used it.
+
+---
+
+## Registering what was built
+
+Once a connector is working, record — concretely, not as a general
+capability claim:
+
+- **What it reaches.** The specific entities and fields, not "NetSuite
+ data."
+- **What it cannot do.** The boundary is as important as the capability;
+ a downstream skill needs to know what to ask for elsewhere.
+- **How it refreshes.** Real-time, polled at an interval, or on an export
+ cadence — and what that means for anything time-sensitive that reads it.
+- **Which skills it now unblocks.** Named specifically, so the person who
+ requested it can see the actual payoff.
+
+---
+
+## Say how it will break, while the customer is still listening
+
+**A connector that fails silently is worse than no connector.** No
+connector produces an obvious gap; a silently failing one produces
+confident, wrong output that looks exactly like a working connection.
+
+State the specific failure mode for the tier that was built, before
+handing it over:
+
+| Tier | How it fails |
+|---|---|
+| 1, 2, 3 | Token expiry — name the renewal path. Vendor API version changes arrive with no warning; the surface needs re-testing when they do |
+| 3 | Rate limits, hit under real load rather than in testing |
+| 4 | Schema drift — a vendor upgrade changes the underlying table with no error, and the view returns the wrong thing or nothing |
+| 5 | Task limits on the plan tier, and per-task cost that scales with volume nobody budgeted for |
+| 7 | An export that stops landing, silently, with no error anywhere — this is exactly why `data-consolidate`'s freshness check exists |
+
+**Name who fixes it, too.** A failure mode with no owner is a failure mode
+nobody responds to until a downstream skill reports something wrong and
+someone traces it back here.
diff --git a/plugins/claude-for-manufacturing/skills/custom-connector/reference/known-systems.md b/plugins/claude-for-manufacturing/skills/custom-connector/reference/known-systems.md
new file mode 100644
index 00000000..bedef45e
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/custom-connector/reference/known-systems.md
@@ -0,0 +1,106 @@
+# The systems landscape, and where common systems land today
+
+Give the engineer a head start, but **re-verify at build time** — this
+landscape moves quickly, and a system that was Tier 3 last quarter may be
+Tier 1 now.
+
+---
+
+## What plants actually run, by category
+
+| Category | What plants actually run | Access reality |
+|---|---|---|
+| ERP | SAP S/4HANA and ECC, Infor M3, Infor CloudSuite/LN, Epicor Kinetic, Plex, Global Shop, JobBoss, E2 | Most have REST or OData APIs. SAP exposes OData services and the BTP layer. API access is sometimes a separately-priced license tier |
+| MES | Tulip, Plex MES, Aegis, Critical Manufacturing — plus a great deal of homegrown | Cloud ones have APIs; homegrown usually means a database or an export |
+| Historian / SCADA | AVEVA/OSIsoft PI, Ignition, Wonderware, Kepware | PI has a Web API; Ignition has a web API and SQL access. Usually on-prem and firewalled |
+| Quality / QMS | ETQ, MasterControl, Greenlight Guru, IQS | Mostly REST |
+| PLM | Windchill, Teamcenter, Arena, Autodesk Vault | Varies widely; Vault is on-prem |
+
+**A large share of what's running in mid-market plants is on-prem, a
+decade old, and has a SQL database but no API at all.** That's not a
+failure case — it's the normal case, and the access ladder has an answer
+for it at Tier 4 or Tier 7.
+
+---
+
+## Known-systems registry
+
+**This table is a starting point, not an answer.** It never replaces the
+Tier 1 and 2 search in `access-ladder.md`: a vendor or community MCP the
+search finds outranks the tier written here. "Tier 2 seen" names candidates
+to evaluate, not to trust.
+
+| System | Tier today | Notes |
+|---|---|---|
+| Oracle NetSuite | 1 — supported | Vendor-native read-write MCP. Heavily customized per account — expect custom fields |
+| Infor M3 | 1 — supported | The company's own M3 MCP server, one per M3 tenant. Read only in this plugin, though the server exposes writes. If an Infor M3 tool call returns an error, tell the user and fall back to a file export. |
+| Microsoft 365 | 1 — supported | Anthropic connector. Read-only by default, write is admin opt-in, no Teams write path |
+| Autodesk Fusion | 1 — supported | First-party integration. Desktop app only |
+| Limble CMMS | 1 — vendor MCP, added via custom-connector | See *Vendor-published MCP — add via custom-connector* below |
+| Onshape | 1 — vendor MCP, added via custom-connector | See *Vendor-published MCP — add via custom-connector* below |
+| SAP S/4HANA | 3 | OData services / BTP. No official MCP for business data. API access may need a license tier |
+| SAP ECC (on-prem) | 3 or 4 | Older estate — RFC/BAPI, or a read-only DB view. Expect a project, not an afternoon |
+| Infor CloudSuite / LN | 3 | REST APIs via Infor ION. Not the M3 connector |
+| Epicor Kinetic | 3 | REST API. Tier 2 seen: a CData community MCP (needs a paid CData JDBC driver, local `stdio`; evaluate per the Tier 2 checklist) |
+| Plex (ERP + MES) | 3 | REST API; cloud-native, so usually straightforward |
+| Global Shop / JobBoss / E2 | 4 or 7 | Typically on-prem SQL. Export is often the pragmatic answer |
+| Tulip | 3 | API available |
+| AVEVA / OSIsoft PI | 3 in theory, 7 in practice | PI Web API exists, but the historian is usually firewalled with no external route |
+| Ignition | 3 or 4 | Web API, or direct SQL against its database |
+| ETQ / MasterControl | 3 | REST |
+| Windchill / Teamcenter | 3 or 4 | Heavy enterprise PLM. Scope tightly or it becomes its own engagement |
+| Homegrown MES | 4 or 7 | The customer's own developer is the only reliable source of truth |
+
+**The plugin works with four systems once they are connected: Microsoft 365,
+Oracle NetSuite, Infor M3 and Autodesk Fusion. These are the supported
+connectors; only Fusion is declared in the plugin's `.mcp.json`.** Every other row is a `custom-connector`
+engagement — including the two with a vendor-published MCP, which are Tier 1
+in reach but are not among the four, and the "3 or 4" and
+"3 in theory, 7 in practice" rows are not indecision — they're the honest
+answer for systems where the real tier depends on the specific customer's
+deployment, license, and network posture, which is exactly what Step 1's
+precise identification is for.
+
+---
+
+## Vendor-published MCP — add via custom-connector
+
+Systems whose vendor publishes an MCP server. **Not among the four supported connectors**:
+`onboarding` Step 12 reports them as an option, and `custom-connector` adds one
+when the plant chooses. These are not setup steps for `onboarding` to quote —
+they are what `custom-connector` works from.
+
+| System | Vendor MCP | What adding it takes | Notes |
+|---|---|---|---|
+| **Limble CMMS** | `https://mcp.limblecmms.com/mcp` | A Limble **Super User** generates an API key at *Settings → Configuration → API Keys*. The secret is shown once. The client ID and secret are sent as the `Limble-Client-ID` and `Limble-Client-Secret` headers, set as `LIMBLE_CLIENT_ID` and `LIMBLE_CLIENT_SECRET` in the environment the connector runs in | Write scope unconfirmed. Credentials never enter the conversation |
+| **Onshape** | `https://fs-mcp.labs.onshape.app/mcp` | Opt in to Onshape Labs, then open the Onshape App Store, find **FeatureScript MCP Server** and click **Subscribe**. Sign-in is automatic — there is nothing to generate | An Onshape Labs app. Whether the subscription costs anything is not stated publicly, so it is unconfirmed. **No skill in this plugin uses it:** `design-space-explore` and `rfq-to-quote` are built on Fusion, so connecting Onshape enables nothing today — say so |
+
+---
+
+## Setup steps for the four supported connectors, word for word
+
+**This is the only place these steps are written.** `onboarding`,
+`custom-connector`, `design-space-explore`, `rfq-to-quote` and any answer to
+"which systems can you reach" **quote the row below exactly**. The same text is in the plugin's
+README.
+
+**Never describe a setup step that is not in this table.** Not "install it
+from the connector directory," not "sign in and authorise," not a service name
+that does not appear here. Where a row says something is unconfirmed, say it is
+unconfirmed. If a customer needs a step this table does not have, say the step
+is not documented here and point them to the vendor's own setup guide.
+
+| System | What to do |
+|---|---|
+| **Microsoft 365** | Enable the Microsoft 365 connector in Claude's connector settings. Documents, mail and the export folder |
+| **Oracle NetSuite** | Enable the Oracle NetSuite connector in Claude's connector settings. Read and write; the sign-in picks your account, so there is no account ID to enter here |
+| **Infor M3** | Add your company's Infor M3 MCP server as a custom connector in Claude's connector settings, using the server address your Infor administrator gives you. The plugin only reads from it |
+| **Autodesk Fusion** | In the Fusion **desktop** app: *Preferences → General → API* → enable **Fusion MCP Server**. It runs locally on your machine and needs Fusion open with a document. If you changed the port from 27182, set `FUSION_MCP_PORT` |
+
+**Connector auth is always owner-initiated.** The plugin never attempts a
+connection on anyone's behalf, so "did you try connecting it?" has one answer:
+no, and here are the steps for the person who can.
+
+**Reported live only when its tools exist in the session.** A connector is
+live when its tools are present and return for this account — not because it is
+declared in `.mcp.json`, and not because the customer says it is set up.
diff --git a/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/SKILL.md b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/SKILL.md
new file mode 100644
index 00000000..c5bccce8
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/SKILL.md
@@ -0,0 +1,393 @@
+---
+name: customer-inquiry-intake
+description: "Reads a customer RFQ in whatever shape it arrived — a PDF drawing package, a 40-line spreadsheet, a portal export, a phone photo of a marked-up print, or a forwarded thread where the real requirement is four messages down — and pulls specifications, quantities and dates into one consistent intake form with every field traceable to the file and page it came from. Records how each tolerance was read and which geometry path each line takes. Reports what was never stated separately from what was stated two different ways. Checks the request against what the plant can actually build before asking the customer anything, drafts the questions back as sendable text, and returns a provisional bid/no-bid that names which unanswered question would change it. Use when someone says \"an RFQ came in,\" \"can we quote this,\" \"should we bid this job,\" \"read this inquiry,\" or \"what's missing from this RFQ?\""
+compatibility: "Requires none. Reads Microsoft 365 mail, attachments and document libraries, and the ERP (Oracle NetSuite or Infor M3) for closed-work-order actual cost and quote history. Runs on a pasted email or an uploaded PDF with no connector. Never infers a tolerance from a drawing, never computes machine hours, never asserts a no-bid as a decision, and never closes an inquiry because a customer went quiet."
+---
+
+# Customer Inquiry Intake
+
+An RFQ is a customer asking *what would this cost, and when could I have it?*
+
+In make-to-order manufacturing there is **no standard format**, and the
+estimator's first job is always the same one: extract the specs, quantities,
+dates and terms into a consistent shape, and work out what is missing. That
+extraction is mechanical, high-volume, and currently done by the most expensive
+person in the department.
+
+**Quick start**
+
+```
+→ Ingest everything as ONE inquiry, however many attachments arrived
+→ Extract into the intake form; every field cites its file and page
+→ Per line: what geometry arrived, and its path (C2 drawing, C1 STEP, B prior part, A text, none). A text-only line is a ROM at most
+→ Per tolerance: how it was read. A general note applied to a feature is reading, and cites the note
+→ Split what was never stated from what was stated two ways. Two registers
+→ Check manufacturability FIRST. A hard disqualifier stops here, before we ask the customer anything
+→ Draft the questions back as a sendable email, not a checklist
+→ Recommend bid or no-bid PROVISIONALLY — never wait for answers; name which answer would change it
+→ Answers re-enter at extract, not at scoring. Re-score and say what moved
+→ No reply? Surface as stale. Stale never cancels, declines or closes
+→ Never infer a tolerance. Never decide. Recommend
+→ Stop at the registers, the questions and the bid/no-bid. No hours, no cycle times, no costing — that is quote-build's
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| The RFQ itself | M365 Outlook mail and attachments, or a SharePoint folder | PDF, XLSX, DOCX, image, email body |
+| Prior quotes for similar parts | M365 documents, NetSuite quote history. Infor M3 gives none (`../../shared/erp-connectors.md`): documents only | Documents and connector |
+| Plant capability profile | `## Plant context`, captured during `onboarding` | Config |
+| Plant constraint set | `## Plant context` | Config |
+| Actual cost on comparable prior jobs | `production_work_orders` actual-cost columns in the dataset: NetSuite, Infor M3, or any ERP `custom-connector` mapped | Dataset |
+
+---
+
+## Workflow
+
+### Step 1 — Ingest
+
+**First, look for it on the Open work page.** Before building a form, look
+for the RFQ reference (or the customer and part) in `## Open inquiries`
+(`../../shared/replies.md`, *The open work*). If it is there, resume that form
+from the page at its `paused_at_step` rather than starting a new one. **The
+reply's first line says so:** *"Picking up EH-RFQ-0912 from your Open work
+page, paused at step 5."* An
+answer pasted into a new chat with nothing attached is enough to resume.
+
+Accept an email with attachments, a folder, or a pasted document.
+
+**A multi-attachment RFQ is one inquiry with several line items, never several
+inquiries.** Different parts in one package legitimately carry different dates
+and quantities; the form holds those per line.
+
+Detect whether this revises an earlier RFQ and **link rather than duplicate**.
+Read `reference/arrival-formats.md`.
+
+### Step 2 — Extract into the intake form
+
+Header, line items, quantities as a structure, specs, dates, commercial terms.
+
+**Every extracted field carries its source — which file, which page** — so the
+estimator can verify without re-reading the package. An estimator who cannot
+trace a number will re-derive all of them, and the skill has saved nobody
+anything.
+
+**Never average a quantity range or a set of price breaks.** Setup amortizes
+across quantity, which is the whole reason unit price drops with volume.
+
+**Read the drawing fully, callout by callout.** Every dimension and tolerance
+with its view and zone; the datums as the drawing identifies them; every key
+characteristic by its label. **Each `specs` entry records its
+`reading_basis`**: `printed_callout`, `general_note`, `from_text` or
+`unreadable_flagged`. **Applying the drawing's stated general tolerance to a
+feature that carries no callout is reading, not inferring** — cite the note
+beside the feature. Assigning a tolerance from what is typical is still never
+done.
+
+**Per line, record the geometry that arrived and classify its path.** List each
+file or statement the part's shape can be read from in `geometry_inputs` —
+name, type, revision, source — and set `geometry_path`:
+
+| Path | The package holds | What it means downstream |
+|---|---|---|
+| `C2` | A drawing — PDF, image or text extract | The normal case |
+| `C1` | A STEP or 3D file and no drawing | Imported and read, nothing generated. STEP import is unverified |
+| `B` | A drawing plus a **different** prior part's model named as the starting point | That model is adapted and saved as new; without it, C2 |
+| `A` | Written specifications, no drawing | Built from the text. A ROM at most, never a firm quote |
+| `none` | A part number only — a repeat part | Priced from its routing, or a question |
+
+Classifying is reading the package; it never builds anything, and **a line is
+never relabelled to a path it is not**. **A new revision of a part we have run before
+is `C2`**: the drawing is the geometry, and the earlier revision's routing and
+actuals are history for `quote-build`, not a model to adapt. Do not tell the
+estimator the old routing is where pricing will start — a routing for another
+revision is superseded.
+
+### Step 3 — Flag missing and ambiguous, separately
+
+**Never stated** is a different problem from **stated two different ways.** The
+first needs a question to the customer; the second needs a decision. Each
+register carries why it matters, and the ambiguous one carries every value found
+with its source.
+
+Never silently resolve an ambiguity — not to the later value, not to the
+stricter one. Read `reference/registers.md`.
+
+**Two drawing facts always reach the missing register.** A drawing — or a
+part — with no revision stated: the quote must say which revision it is priced
+to, and nobody can yet. And **a change the customer mentions as pending**
+("engineering may change the port thread"): a risk to the revision being
+quoted, with the customer's own words as its source. Both become questions in
+Step 5.
+
+### Step 4 — Check manufacturability, before anything goes to the customer
+
+Check the request against the plant's known constraints — materials, processes,
+size envelope, demonstrated tolerance capability, certifications held — on
+whatever is stated so far. **The envelope and the tolerances read off the
+drawing count as stated**, with their source: a 0.002 in true position read
+from KC-2 is checked against demonstrated capability like any other stated
+requirement.
+
+**Report each violated constraint specifically**, never as a general fail.
+"0.0005 in true position is below this plant's demonstrated capability on this
+process" is actionable; "does not meet plant capability" is not.
+
+**A hard disqualifier stops the sequence here.** Wrong process entirely, outside
+the size envelope, a certification the plant does not hold — return a no-bid
+recommendation with its specific reason, before any questions go out. There is
+no point asking a customer five questions about a part the plant physically
+cannot make.
+
+Two limits on that stop, and both matter:
+
+- **It stops the automated sequence, not the inquiry.** The estimator can
+ override and proceed. The inquiry stays open.
+- **Only violations determinable from stated facts qualify.** Anything resting
+ on a field that is missing is a *scoring input* for step 6, not a stop. A
+ disqualifier inferred from a blank is a guess.
+
+Softer concerns — tight but achievable tolerances, an awkward material, a date
+that looks difficult — carry forward to step 6 as scoring input rather than
+stopping the flow.
+
+### Step 5 — Draft the questions back
+
+One clear list, written **as an email the estimator can send**, in the order a
+person would ask, with enough context that the customer can answer without
+opening the file again.
+
+A bulleted list of field names is a to-do list. A short note is what gets the
+answer back today.
+
+**Keep the email word for word in the form's `open_questions`, numbered as
+sent**, so a later chat matches each answer to its question without guessing.
+If the estimator says they changed it before sending, store their version.
+
+### Step 6 — Score the provisional bid/no-bid recommendation
+
+Against capability, against the constraint check above, and against **actual
+cost on comparable closed work orders** rather than standard cost — because
+actual cost is the number that says whether the last job of this kind made
+money.
+
+Cite each comparable as of the date its work order closed, and say how old it
+is. A comparable from two years ago was priced in a different material market,
+and an estimator weighing it needs to know that without going to look.
+
+**Score each line, then roll up.** Each line gets its own
+`line_recommendation`; the inquiry's is `bid`, `no_bid` or `partial`, and each
+entry in `would_change_recommendation` names the line it moves. "No-bid line 1"
+lives in those fields, never only in prose, because `quote-build` reads the
+fields to decide which lines to quote.
+
+**This runs immediately on what is known. It never waits for the customer's
+answers.** Most RFQs arrive with at least one gap, so a recommendation that
+blocked on answers would stall on nearly all of them — which defeats the point
+of the skill.
+
+**While questions are open the recommendation is marked provisional, and it
+names which specific unanswered questions would change it** — *"if the material
+is 4140 rather than 4130 this becomes a no-bid."* That tells the estimator which
+answer to chase rather than chasing all of them equally, and it is the
+difference between a recommendation and a guess wearing one's clothes.
+
+**Recommend with reasoning. Never decide.** The skill does not know about the
+customer relationship or the strategic reason to take a marginal job. Read
+`reference/bid-no-bid.md`.
+
+**This skill stops at the registers, the questions and the bid/no-bid.** The
+actual-cost evidence the score rests on is cited — work order, date, outcome —
+and that is all. **No machine hours, no setup or cycle times, no per-operation
+work content, no comparables analysis and no costing**: those are
+`quote-build`'s, derived from the ladder after Gate 3. An hours figure written
+here would be a second, unlabelled estimate of the same job, and the quote
+would have to pick between them.
+
+### Step 7 — Fold in the answers, and handle the ones that never come
+
+**An answer is new source material, so it re-enters at step 2, not here.** It is
+extracted like anything else, with its own source reference; the gaps register
+shrinks; and step 6 re-scores on the fuller picture. It is a **revision of the
+existing inquiry, never a new one** — the same mechanism a revised RFQ uses.
+
+**Where an answer flips the recommendation, say plainly that it changed and
+why.** A recommendation that silently reverses between two readings is worse
+than either version of it.
+
+**After a configurable interval with no reply, surface the inquiry as stale** —
+with its provisional recommendation and its still-open questions attached — so
+the estimator either quotes it with exclusions or drops it deliberately. The
+interval is `MFG_RFQ_STALE_DAYS`, else the profile's *RFQ stale after* line,
+else **5 business days, stated as the default, not plant-set**. There is always
+an interval: an unconfigured plant whose inquiries never go stale is the unbid
+book this rule exists to prevent. Check it every time this skill or
+`rfq-to-quote` runs, reading `stale_after` from the Open work page, so a new
+chat surfaces stale inquiries with nothing attached. The clock starts at `questions_sent_at`; with no send
+recorded, it starts at `received_at` and says so. An inquiry already declined
+is never surfaced as stale.
+
+**Stale is a visibility change, never a status change.** The skill does not
+cancel, decline, close or no-bid an inquiry because a customer went quiet. It
+stays open, with its provisional score and open questions intact, and the
+decision stays the estimator's.
+
+This step is not optional. Silently aging out is the single most common way an
+RFQ joins the unbid book — the number this skill exists to reduce.
+
+---
+
+## Approval gates
+
+**Nothing goes to the customer.** The open questions are drafted as sendable
+text and **the estimator sends them — that is Chain 1's first gate.** Microsoft
+365 is read-only by default and no mail is sent on anyone's behalf.
+
+**The bid/no-bid is a recommendation the estimator confirms** — Chain 1's second
+gate, and what makes the chain valuable rather than merely fast. It sits after
+the questions rather than at the very front because a sound call often needs
+those questions already in flight, but it is still ahead of every costing step.
+`quote-build` proceeds on a `no_bid` if the estimator says to, because it is a
+recommendation and not a verdict.
+
+The intake form leaves this skill with `bid_decision_state: draft` every time.
+Only an estimator moves it to `confirmed` or `declined`, and the form records
+who and when. Never emit a state other than `draft` — the gate is theirs to
+pass, and a form that arrives at `quote-build` already marked confirmed by the
+skill that wrote it is not a gate at all.
+
+Nothing is written back to the ERP.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The intake form** — per `../../shared/contracts/intake-form.md`, in exactly
+the shape `quote-build` consumes. Customer and contact, RFQ reference, dates
+received and due, commercial terms as stated (payment, freight, packaging,
+liability), and per line: part and description, revision, quantities with their
+breaks, material, key specs and tolerances each with its reading basis, finish,
+certifications, per-line delivery date, estimated annual usage for a repeat
+part, and the line's geometry inputs and geometry path.
+
+**Print the form itself, with its field names**, as a field table (field,
+value, source, reading basis), not a YAML block —
+`geometry_path: C2`, each tolerance with its `reading_basis` and `source_ref`
+— after the summary, not in place of it. A summary that says "line 1 is C2"
+is not the form: `quote-build` and the estimator check the fields, and a field
+nobody printed is a field nobody checked.
+
+Flag a customer term that clashes with the plant's standard. Do not silently
+accept it.
+
+**Open questions** — drafted as sendable email text.
+
+**Missing register** — never stated: the field, why it matters, where it should
+have come from.
+
+**Ambiguous register** — stated more than once: every value with its source, and
+why the difference matters.
+
+**Bid/no-bid recommendation** — with reasoning and the specific constraint
+violations behind it. Marked **provisional** while questions are open, naming
+which unanswered questions would change it, and re-scored when answers land with
+a plain statement of what moved.
+
+**Staleness** — where the configured interval has passed with no reply, the
+inquiry is surfaced as stale with its provisional recommendation and open
+questions attached. It remains open.
+
+The intake summary renders in the house artifact style
+(`../../shared/artifact-style.md`); the questions to the customer are plain
+sendable text.
+
+---
+
+## Edge cases and failure modes
+
+- **The drawing is an image with no dimensions in text** — extract what is
+ visible and mark the line for human review. **Never infer a tolerance from a
+ drawing.**
+- **A feature with no callout, under a general tolerance note** — apply the
+ note, `reading_basis: general_note`, citing the note. That is reading.
+- **No drawing revision, or a change the customer says is coming** — both on
+ the missing register, both as questions.
+- **Asked for hours or a price at intake** — say that is `quote-build`'s step,
+ after the bid is confirmed. Do not estimate them here.
+- **Quantity given as a range or with price breaks** — capture the structure.
+ Never average.
+- **This RFQ revises an earlier one** — detect and link. Do not create a
+ duplicate inquiry. **Customer answers to open questions use the same
+ mechanism** — they revise the existing inquiry, they do not start a new one.
+- **The customer never answers** — after the configured interval, surface as
+ stale with the provisional recommendation and open questions attached. The
+ inquiry stays open; **a timeout is never a decline.** Never let it go quiet
+ either — that is how the unbid book grows.
+- **Answers arrive that flip the recommendation** — re-score and **say plainly
+ that it changed and why.** A recommendation that silently reverses between
+ readings is worse than either version.
+- **A hard disqualifier is only arguable from a missing field** — that is not a
+ disqualifier. It is a scoring input. Never stop the sequence on a blank.
+- **Multiple parts with different dates** — one inquiry, multiple line items,
+ per-line dates.
+- **Customer terms conflict with our standard terms** — flag it. Do not silently
+ accept.
+
+---
+
+## Degradation
+
+Runs on a pasted email and an uploaded PDF with no connector at all.
+
+| Not available | What happens |
+|---|---|
+| M365 | Accept the RFQ pasted or uploaded. Extraction is unchanged |
+| Capability profile | The recommendation is **constraint-free and says so.** It cannot have checked manufacturability against a profile it did not have |
+| ERP closed-work-order cost | Score on capability and dates alone, **and say so.** No actual-cost comparable is available |
+| Prior quote history | No precedent to compare against. State it rather than reading absence as a new part |
+
+A recommendation that does not name what it could not check reads exactly like
+one that checked everything — which is the failure
+`../../shared/absent-is-not-zero.md` exists to prevent.
+
+---
+
+## Chain position
+
+**Chain 1, RFQ to quote** — step 1, feeding `data-consolidate` and then
+`quote-build`. The front door of the clearest revenue story in the plugin.
+
+**The chain does not run in one sitting.** Steps 1–6 happen on arrival, then it
+pauses while the customer's answers are pending — often days, and usually the
+longest single stretch in quote turnaround. Treat the inquiry as resumable
+state, not one pass: answers re-enter at step 2 and the recommendation
+re-scores.
+
+**Metric.** Quote turnaround.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/arrival-formats.md` | Steps 1 and 2 — the five formats, multi-attachment handling, and revisions |
+| `reference/registers.md` | Step 3 — missing versus ambiguous, and quantity structure |
+| `reference/bid-no-bid.md` | Steps 4, 6 and 7 — the constraint check and its hard-disqualifier stop, actual-cost comparables, the provisional recommendation, staleness, and the two stated degradations |
+| `../../shared/contracts/intake-form.md` | On emit — the exact shape `quote-build` consumes |
diff --git a/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/arrival-formats.md b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/arrival-formats.md
new file mode 100644
index 00000000..a1639b85
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/arrival-formats.md
@@ -0,0 +1,81 @@
+# How an RFQ actually arrives
+
+**There is no standard format, and that is exactly the problem this skill
+exists to solve.** In one week an estimator might get all five of these.
+
+The extraction is mechanical, high-volume work, and it is currently done by the
+most expensive person in the department.
+
+---
+
+## The five formats
+
+### 1. A PDF drawing package with "can you do this?" in the email body
+
+The commercial terms are often in the email, the technical content in the
+attachments. The email body is an input, not a covering note.
+
+### 2. A spreadsheet with 40 line items and no drawings
+
+The column headers are the customer's. Extract what is there. Do not invent
+drawings that did not arrive.
+
+### 3. A customer portal export with fields in an unfamiliar order
+
+The field names are the portal's, not yours. Extract into the intake form
+anyway.
+
+Portal exports carry a generation timestamp. **Note it** — a portal export
+pulled a week ago may no longer match what the portal says today, and the
+response deadline is usually counted from the portal's date rather than the
+day the file reached you.
+
+### 4. A phone photo of a marked-up print
+
+Extract what is visible and **mark the line for human review**.
+
+**Never infer a tolerance from a drawing**, and never from a photograph of one.
+A `specs` entry with no source reference is not permitted.
+
+### 5. A forwarded thread where the requirement is in the fourth message down
+
+Read the thread. Cite the message each field came from. Do not treat the latest
+message as the requirement just because it is latest.
+
+---
+
+## One inquiry, several line items
+
+**A multi-attachment RFQ is one inquiry with several line items, never several
+inquiries.**
+
+Different parts in one package can carry different delivery dates, different
+quantities and different certifications. That is normal — the contract holds
+dates per line for exactly this reason. Splitting the package into separate
+inquiries loses the fact that the customer is asking for them together, which is
+often the whole commercial point.
+
+---
+
+## Revisions of an earlier RFQ
+
+Detect and **link** rather than creating a duplicate. Set `supersedes_rfq`.
+
+A revised RFQ that quietly becomes a second inquiry is how a plant ends up
+quoting the same job twice against different requirements, then sending both.
+
+Signals worth checking: the customer's own reference reappearing, the same part
+and customer within a short window, "revised," "updated," or "rev 2" in a
+filename or subject line.
+
+---
+
+## Provenance on every field
+
+Every extracted field carries **which file and which page it came from**, so the
+estimator can verify without re-reading the package.
+
+This is what separates a useful extraction from one that has to be checked from
+scratch, and it is why `field_sources` is a required field the consumer blocks
+on. An estimator who cannot trace a number will re-derive all of them, and the
+skill has then saved nobody anything.
diff --git a/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/bid-no-bid.md b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/bid-no-bid.md
new file mode 100644
index 00000000..0d9872d9
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/bid-no-bid.md
@@ -0,0 +1,161 @@
+# The manufacturability check, then the recommendation
+
+**The ordering is the point, twice over.** The constraint check runs *before*
+the questions go out and *before* the bid/no-bid call — so a job that cannot be
+built as specified is caught at intake rather than after somebody has spent
+hours pricing it, and the plant never asks a customer five questions about a
+part it physically cannot make.
+
+---
+
+## Why a no-bid is a win
+
+Quoting is expensive — often hours of the most senior person in the department.
+**Quoting a job you will lose, or one you should not want, is pure cost.**
+
+Wrong material, a tolerance the plant has never held, a size outside the
+envelope, an impossible date: each of those is a job that either does not get
+won, or gets won and then loses money. A defensible no-bid returns those hours
+to the RFQs that can be won.
+
+---
+
+## Step 1 — Check the request against what the plant can actually build
+
+From the capability profile captured during `onboarding`: materials, processes,
+size envelope, demonstrated tolerance capability, certifications held.
+
+**Report each violated constraint specifically**, never as a general fail:
+
+> *"True position of 0.0005 in on the 4x mounting holes is below this plant's
+> demonstrated capability on 3-axis milling, which is 0.002 in. Everything else
+> on this line — 6061-T6, the envelope, clear anodize — is within profile."*
+
+That is a sentence an estimator can act on. They may know the plant can hold it
+on a different machine, or that the customer will accept a deviation, or that
+this is the reason to decline. **"Does not meet plant capability" tells them
+none of that** and sends them back to work out which constraint failed.
+
+---
+
+## The hard-disqualifier stop
+
+Some violations end the automated sequence at the check rather than feeding the
+score: **wrong process entirely, outside the size envelope, a certification the
+plant does not hold.** Return a no-bid recommendation with its specific reason,
+before the questions are drafted.
+
+Two limits, and both matter:
+
+**It stops the sequence, not the inquiry.** The estimator can override and
+proceed. The inquiry stays open, and nothing about it is cancelled or closed.
+
+**Only violations determinable from stated facts qualify.** If the disqualifier
+depends on a field that is missing, it is not a disqualifier — it is a scoring
+input for the recommendation below. Stopping on a blank is guessing, and it
+would stop the plant from asking the very question that resolves it.
+
+Everything softer — a tight but achievable tolerance, an awkward material, a
+date that looks difficult — carries forward as scoring input and does not stop
+anything.
+
+---
+
+## Step 2 — Score the recommendation, provisionally
+
+Three inputs, weighted by the estimator's own priorities where those are known:
+
+**Capability**, from the profile — how far inside or outside the plant's
+demonstrated envelope this sits.
+
+**The constraint violations** from step 1 — how many, how severe, and whether
+each has a plausible workaround.
+
+**Actual cost on comparable prior jobs**, from closed work orders in the ERP (NetSuite or Infor M3).
+
+### Actual cost, not standard cost
+
+This distinction is deliberate and it matters.
+
+Standard cost is what the job was *planned* to cost. Actual cost on a closed
+work order is what it *did* cost, and **that is the number that says whether the
+last job of this kind made money.** A part family that consistently runs 30%
+over standard is one the plant loses money on every time it wins, and the
+standard cost will never say so.
+
+Cite the specific work orders, with their dates and what made each comparable.
+Note how old they are — **a comparable from two years ago was priced in a
+different material market**, and the estimator should weigh it accordingly.
+
+---
+
+### It never waits for the customer
+
+The recommendation runs immediately on what is known. **Most RFQs arrive with at
+least one gap**, so a recommendation that blocked until every answer came back
+would stall on nearly all of them — and an inquiry sitting unscored for a week
+is exactly the inquiry that joins the unbid book.
+
+While questions are open, the recommendation is **provisional**, and it names
+**which specific unanswered questions would change it**:
+
+> *"Provisional bid. If the material is 4140 rather than 4130 this becomes a
+> no-bid — we have never held this tolerance in 4140 on this process."*
+
+That is what tells the estimator which answer to chase. A provisional
+recommendation that does not name its own dependencies is just a recommendation
+with a caveat, and the caveat does no work.
+
+---
+
+## Step 3 — Fold in answers, and handle silence
+
+**An answer is new source material.** It re-enters extraction, carrying its own
+source reference, and the recommendation re-scores on the fuller picture. It
+revises the existing inquiry — it never opens a new one.
+
+**Where an answer flips the recommendation, say so plainly and say why.** A
+recommendation that silently reverses between two readings is worse than either
+version of it, because it destroys the estimator's ability to trust either.
+
+**Where no answer comes**, after the configured interval the inquiry surfaces as
+**stale**, carrying its provisional recommendation and its still-open questions.
+
+**Stale is a visibility change, never a status change.** The skill does not
+cancel, decline, close or no-bid an inquiry because a customer went quiet. It
+stays open and the decision stays the estimator's — they quote it with
+exclusions, or they drop it deliberately. Both are decisions; aging out
+silently is not, and it is the single most common way an RFQ joins the unbid
+book.
+
+---
+
+## Step 4 — Recommend, never decide
+
+The output is `bid` or `no_bid`, with reasoning that an estimator can read and
+disagree with.
+
+**The skill never asserts a no-bid as a decision.** It does not know about the
+relationship with this customer, the strategic reason to take a marginal job, or
+the conversation somebody had at a trade show last month. It knows what is in
+the data, and the data is not all of it.
+
+Constraint violations stay on their own list. A `bid` can still carry them.
+That is a bid with reasoning, not a third recommendation.
+
+---
+
+## Two degradations that must be stated, not silent
+
+**No capability profile** → the recommendation is **constraint-free and must say
+so.** It cannot have checked manufacturability against a profile it did not
+have, and an unqualified "bid" that never ran the check reads exactly like one
+that passed it.
+
+**No cost history** → the recommendation scores on **capability and dates
+alone, and must say so.** Without closed work orders there is no comparable, and
+without a comparable the commercial half of the judgment is missing.
+
+Per `../../../shared/absent-is-not-zero.md`, a recommendation that does not name
+what it could not check is the failure this rule exists to prevent — it is
+confident in exactly the shape of a recommendation that checked everything.
diff --git a/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/registers.md b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/registers.md
new file mode 100644
index 00000000..f03fa4e5
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/customer-inquiry-intake/reference/registers.md
@@ -0,0 +1,98 @@
+# Missing and ambiguous
+
+Two states that get collapsed into "incomplete" everywhere else, and keeping
+them apart is most of the value of a structured intake.
+
+---
+
+## Missing is not ambiguous
+
+**A field that was never stated is a different problem from one stated
+contradictorily in two places.**
+
+| | Missing | Ambiguous |
+|---|---|---|
+| What happened | Nobody said | Two sources disagree |
+| What it needs | A question to the customer | A decision, usually by the estimator |
+| Who resolves it | Them | Us, sometimes after asking |
+| How long it takes | A reply | Often minutes |
+
+Collapsing them into one list means the estimator has to re-sort it before they
+can do anything, which is the work you were trying to remove.
+
+### The missing register
+
+Per entry: the line, the field, **why it matters**, and **where it should have
+come from.**
+
+Those last two are what make it actionable. "Packaging not stated" is a
+complaint. *"Packaging not stated — anodized parts ship with interleaving and
+that is unpriced if we do not know; it should have been on the customer's terms
+page"* is a question that answers itself half the time.
+
+### The ambiguous register
+
+Per entry: the line, the field, **every value found with its source**, and why
+the difference matters.
+
+> *Required delivery: 3 November on page 1, "week of 10 November" on page 2. A
+> week decides whether current shop load can absorb it.*
+
+**Never silently pick one.** Not the later one, not the stricter one, not the
+one in the more official-looking document. The estimator picks, and downstream
+`quote-build` quotes against one value while naming the other explicitly.
+
+---
+
+## Quantities are a structure
+
+**Never average a range or a set of price breaks.**
+
+Setup cost amortizes across quantity, which is the entire reason unit price
+drops with volume and the reason quantity breaks exist at all. Averaging 100,
+500 and 1,000 into 533 destroys the thing `quote-build` is for.
+
+Capture each break as its own entry with its unit of measure. Where the customer
+gives a range — "500 to 2,000 depending on the program" — capture the endpoints
+and note that it is a range rather than a set of breaks, because the two ask for
+different quotes.
+
+---
+
+## Drawings are read, never inferred from
+
+Where a drawing is an image with no dimensional text, extract what is visible
+and mark the line for human review.
+
+**Never infer a tolerance.** Not from the feature type, not from what is
+typical, not from the other dimensions on the print. A `specs` entry with no
+source reference is rejected by the contract, and downstream `quote-build`
+blocks on it — because an unsourced tolerance is an inference, and inferences get
+priced and then contractually committed to.
+
+**A stated general tolerance is not an inference.** "Unspecified tolerances
+±0.005 in" is printed on the drawing; applying it to a feature with no callout
+is reading the drawing, recorded as `reading_basis: general_note` with the note
+cited beside the feature. What is never done is the other thing: a tolerance
+taken from the feature type or from what is typical, where the drawing states
+none.
+
+**The revision is a drawing fact, and so is a pending change.** No revision on
+the drawing or in the RFQ is a missing-register row: *"Drawing revision — the
+quote must state which revision it is priced to; should have come from the
+title block."* A customer remark that a change is coming — *"engineering
+mentioned a possible change to the port thread"* — is a missing-register row
+too, recorded as a risk to the revision being quoted, with their words as the
+source. Both go into the questions.
+
+---
+
+## The open questions are an email, not a checklist
+
+Draft them as **sendable text the estimator can actually send**, in the order a
+person would ask them, with enough context that the customer can answer without
+opening the file again.
+
+A bulleted list of field names is a to-do list for the estimator. A short, clear
+note is the thing that gets the answer back today. Getting the answer back today
+is the metric this chain ships against.
diff --git a/plugins/claude-for-manufacturing/skills/daily-production-report/SKILL.md b/plugins/claude-for-manufacturing/skills/daily-production-report/SKILL.md
new file mode 100644
index 00000000..11d20dfa
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/daily-production-report/SKILL.md
@@ -0,0 +1,486 @@
+---
+name: daily-production-report
+description: "Produces the morning production report: output against plan by line, cell and product; OEE with availability, performance and quality shown separately; the downtime log ranked both by minutes and by frequency; scrap and downtime priced in dollars; week-over-week movers; and the exceptions needing a decision today. For each significant exception it drafts a specific reschedule or changeover move with its consequences traced, never a re-optimised day. Reads the consolidated dataset and leads with data freshness. When the plant has a floor plan on file, or attaches one, it also draws each machine's OEE, availability and downtime on a schematic of the floor. Use when someone says \"morning report,\" \"production report,\" \"how did we do yesterday,\" \"what's our OEE,\" \"downtime report,\" \"what's late,\" or \"what do I take into the production meeting.\""
+compatibility: "Requires a consolidated dataset from data-consolidate. Reads the ERP (Oracle NetSuite or Infor M3) for standard cost and open work orders, and a CMMS connector (Limble is the worked example) for maintenance work orders in progress, when connected. Runs on export-only data. Writes nothing to any system of record."
+---
+
+# Daily Production Report
+
+Every plant runs a morning production meeting, and somebody spends 60 to 90
+minutes before it assembling the same report by hand out of the same four or
+five exports. This is that report.
+
+**Chain 3 runs this overnight, so the page exists before anyone asks for it.**
+The run is built to be safe unattended — it asks nothing, it is idempotent, and
+it reports its own gaps. **The trigger is the host's, not the plugin's**: see
+`../../shared/scheduling.md`. Never tell a user the report has been scheduled.
+That is the clearest demonstration of the plugin's concept, and it
+is why the run must be idempotent — a re-run rewrites the same report for that
+production day rather than producing a second one.
+
+**Quick start**
+
+```
+→ Confirm freshness; if last night's export didn't land, lead with that
+→ Output against plan by line, cell, product, with variances
+→ OEE per asset or line, three components always shown separately
+→ Downtime ranked by minutes and by frequency, both
+→ Price scrap and downtime in dollars, with the rate assumption stated
+→ Week-over-week movers from history: the pulse's day records, or the exports
+→ Fold in any breakdown diagnoses
+→ Exceptions, each with its impact on a commitment
+→ One traced reschedule move per significant exception, drafted not applied
+→ Floor view: each machine's figures drawn where it sits; set up once from a
+ floor plan, confirmed by a person, saved on the plant setup page
+→ Page saved to report-output/; the reply is a ~150-word summary naming it
+→ Run alone: never publishes. End with the placement line, "save it over yesterday's"
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| Consolidated dataset | `data-consolidate` | **Primary input.** `../../shared/contracts/consolidated-dataset.md` |
+| New breakdown diagnoses | `breakdown-diagnosis` | `../../shared/contracts/downtime-record.md` |
+| Production plan / schedule | Planning export to the M365 folder | CSV / XLSX |
+| Actual output, good and scrap | MES export to the M365 folder | CSV / XLSX |
+| Downtime events with reason codes | MES or historian export | CSV |
+| Standard cost per part | The ERP. Infor M3 gives none (`../../shared/erp-connectors.md`): the profile's cost read order applies | Connector |
+| Open work orders and due dates | The ERP | Connector |
+| Maintenance work orders in progress | CMMS | CMMS connector, else the maintenance export |
+| Stored day history, inside Chain 3 only | `morning-plant-pulse` | `../../shared/contracts/pulse-day-record.md` |
+| Floor layout (optional) | The `### Floor layout - <site>` section of the plant profile at `profile_path` (the plant setup page) | `../../shared/contracts/floor-layout.md` |
+| Floor plan (optional, setup only) | A PDF or image the user attaches | Read once, in the setup turn of step 9a; never stored |
+| OEE thresholds (optional) | The plant profile's `OEE thresholds` line | Defaults apply, labelled not confirmed, when absent |
+
+---
+
+## Workflow
+
+### Step 1 — Confirm freshness
+
+Confirm freshness via `data-consolidate` — the data quality report and each
+row's `as_of`. **If last night's export did not land, say so at the top of the
+report**, directly under any safety block. Nothing about data age goes above a
+safety-flagged record, not even a one-line note.
+
+A source whose timestamps run later than now is flagged `future_timestamp`:
+say its dates can't be trusted and give it no age. A production report built on
+stale data is worse than no production report,
+because it gets believed and acted on. Never silently reuse yesterday's data.
+The rule is `../../shared/absent-is-not-zero.md`.
+
+**On reading both the dataset and the raw exports.** The dataset is the primary
+input — it carries the freshness picture and the classified key mismatches. The
+plan, output and downtime exports give rows at their native grain. Where the two
+disagree on a count, **report both and name which is which**; a discrepancy is a
+finding about the export, not a number to choose between. See *What this dataset
+is authoritative for* in `../../shared/contracts/consolidated-dataset.md`.
+
+### Step 2 — Output against plan
+
+By line, cell and product, with variances. Use the plant's own word for the
+organizational unit, from the `## Plant context` block.
+
+**Where plan and output spell a part differently, do not match them silently,
+and do not refuse to match them.** Run on raw exports, the plan says
+`PN-4471-B` and the MES says `4471B`. Dropping the row makes output against
+plan look broken; joining it without a word applies a fix nobody approved. So:
+
+1. Use any normalization already approved — in the consolidated dataset, or
+ on the profile's `### Approved normalizations` list — as it stands.
+2. For every other match that depends on a normalization, **show the variance
+ labelled provisional**, and beside it **each normalization it rests on, with
+ both spellings verbatim** — `4471B` → `PN-4471-B`, format drift.
+3. **Ask for a yes on each**, the same "apply?" gate `data-consolidate` uses.
+ Until then the rows stay provisional, in the table and in any total built
+ on them.
+
+An unattended run cannot ask: it carries the same provisional table and lists
+the normalizations as *proposed, awaiting approval*. Per
+`../../shared/approval-gates.md`.
+
+### Step 3 — Compute OEE
+
+Per asset or line, **with the three components always shown separately**. Read
+`reference/oee.md` first — the denominators carry real traps, and a missing
+component is never substituted with 1.0.
+
+**State the quality convention on every run**, as a line under the OEE table:
+*"quality = good ÷ (good + scrap)"*. **Only when the export has no rework
+column** does the line continue: *"no rework column, so first-pass yield could
+not be applied."* Where the export does carry rework, quality is first-pass
+yield, good ÷ (good + scrap + rework), and the line says so instead. Never
+print the no-rework caveat against an export that has the column.
+
+### Step 4 — Build the downtime log
+
+Ranked **two ways, both always shown**: by total minutes, and by frequency.
+
+**`Other` never appears in a cause ranking.** Before ranking by reason code,
+count the events and minutes coded `Other` or left blank and state that share
+as a finding of its own: *"18 of 39 events, 46%, carry no usable reason code."*
+Then rank the named codes only, with the caveat that the picture is incomplete
+by that share. A table with `Other` in row 1, priced, tells the meeting the
+plant's biggest problem is a word, and it is the single most common way this
+report has been wrong.
+
+**A downtime row that ends before it starts, or whose duration disagrees with
+its own start and end, has no trustworthy minutes.** It carries
+`end_before_start` or `duration_mismatch` from the dataset; reading the export
+raw, test it in code. Hold its minutes out of every total and the minutes
+ranking, count it as an event, and state the exclusion beside the ranking with
+the row: *"DOOSAN-PUMA-07, 4 Aug: ends 14:01 after starting 14:05, 56 minutes
+stated, not counted."* Never pick a figure for it.
+
+These describe different problems. One long outage and forty chronic small
+stoppages can total the same minutes, and the second is usually the more fixable
+of the two. A single ranking hides whichever one it does not sort by.
+
+### Step 5 — Price the losses
+
+Scrap × standard cost. Downtime × the plant's configured cost-per-hour.
+
+**Scrap dollars are an estimate at standard cost, and say so** where they are
+printed (*"$180 scrap, estimated at standard cost"*): they are exposure, not
+a booked loss. With no rate, downtime dollars are *unknown*, never $0.
+
+"47 parts scrapped" does not land in a production meeting. "$8,400 of scrap, 71%
+of it on one part number" does, and it is the same data multiplied by a cost.
+
+**Every quantity in the priced-losses table is the figures-block row, printed.**
+The scrap count beside a part's dollar figure is the same number the dollar
+figure was multiplied from; a table that says 155 units against a figure
+computed from 62 has been typed, not printed. Build the table from the block,
+per `../../shared/computed-figures.md`, and never from memory of it.
+
+**A part whose scrap is recorded in a different unit from its standard cost is
+unpriced, not converted.** Scrap in `box12` against a cost per `each` has no
+dollar figure until the plant says what a box holds: report the quantity in
+its own unit, mark the dollar cell "unpriced — unit conflict," and name the
+conflict. Never price it two ways ("$5,465 if singles, $65,584 if boxes of
+12"): both numbers are guesses, and the larger one is the one that gets
+repeated. The rule is the same one `data-consolidate` applies at the join.
+
+**Always state the assumption behind the downtime rate.** Resolve it per
+`../../shared/secret-config.md`, *Resolving a rate* —
+`MFG_DOWNTIME_COST_PER_HOUR` if set, then a confirmed rate in the plant
+profile, then a placeholder there, labelled "placeholder rate — not
+confirmed" — and name the source next to the priced downtime. This is an
+unattended overnight run, so there's no one to ask. Without a rate in either
+route, price scrap only and say plainly that downtime is unpriced, per
+`../onboarding/reference/config-profile.md`.
+
+### Step 6 — Week-over-week movers
+
+Compare against earlier production days and surface the biggest improvements
+and deteriorations. **The history comes from one of two places, never from a
+prior page.** Inside Chain 3, `morning-plant-pulse` hands over the stored day
+records. Run alone, this skill compares only against earlier days the exports
+in front of it cover, and says that is the basis. Trend beats snapshot: a 68% OEE that was 61% last week is a
+different conversation from one that was 74%.
+
+**Compare all four: output against plan, OEE by component, downtime minutes and
+scrap dollars.** A movers section that shows only OEE has missed the number the
+plant manager looks at first. Each mover names the metric, last week's value,
+this week's, and the change.
+
+**With no earlier day to compare against, skip the section rather than
+showing an empty comparison.**
+
+### Step 7 — Fold in breakdown diagnoses
+
+Any downtime record from `breakdown-diagnosis` appends into the downtime log and
+the exceptions, with no transformation step. Its contract governs how — including
+that an ongoing outage has a null duration rather than zero, that a safety flag
+leads with its `safety_reason`, and that an advisory cause is attributed as
+proposed rather than established, with its `technician_step` beside it
+(*"proposed; technician step skipped"*).
+
+**Check `safety_flagged` on every record where `source_system` is
+`breakdown_diagnosis`, before it goes anywhere:**
+
+- **Absent — block the record.** It appears only in a separate **"Blocked —
+ safety status unknown"** list, **placed first, above both rankings**, with
+ its asset, start time and the reason: *safety status missing on a diagnosis
+ record — not ranked until confirmed.* It is not in the minutes ranking, not in the frequency ranking, not in any
+ total, and not priced, until the flag is known. Labelling it "unknown" and
+ ranking it anyway is not blocking it. Never read a missing flag as false.
+- **True — it leads the report**, above both rankings.
+- **False** — it joins the log as an ordinary row.
+
+**No diagnosis records at all is not a clear safety status.** When the drop
+holds none, write *"Safety status: not assessed (no breakdown diagnosis records
+in this drop)"* once, where the safety block would sit. Never "no safety
+issues", and never read an empty maintenance or quality export as nothing open.
+
+**Rows from the MES or historian export are not contract records and are left
+exactly as they are.** They never carry this field; its absence there means
+nothing, and blocking them would empty the report.
+
+### Step 8 — Identify exceptions
+
+Late jobs, machines down, material shortages, quality holds. **Each with its
+impact on a commitment** — an exception with no stated consequence is not
+actionable. The commitment is read through the work order's `sales_order`.
+Where the source holds no work order to sales order link, say *"commitment
+impact not traceable: no work order to sales order link in the ERP"* once,
+with the count it affects, and never infer the order from part and customer.
+
+**A genuine one-sided record is not an exception, and is never counted as
+one.** A part in the item master with no plan and no production, a machine
+with no downtime, a supplier with no purchase orders in the window: that is
+Class 6 in `../data-consolidate/reference/mismatch-classes.md` — *report, do
+not alarm* — and usually nothing is wrong at all. Build the list in two
+passes:
+
+1. Classify each candidate first. Class 6 records leave the exceptions list
+ and every count of exceptions or problems.
+2. Show them in a separate **"Checked, nothing wrong"** block, one line each:
+ *"in the item master, not planned and not produced this month."*
+
+Decide it by class, from the record's own type and dates, never by recognising
+a part number. **Route by class number before numbering any row**: classes 1,
+2, 3, 4, 5 and 8 are exceptions or problems; class 7 is the coverage line in
+the freshness banner; class 6 is "Checked, nothing wrong" **unless the record
+carries `contradicted_by`**. A one-sided record that another source
+contradicts (WO-88412, closed with no output, while NCR-2026-0141 found bad
+parts from it) is an exception, *"one-sided, contradicted by NCR-2026-0141"*,
+and never sits under "nothing wrong". A duplicate key (class 8) is counted by
+the rows that collide at the tab's grain, from the query: WO-88201 has three
+rows, two of them (509 and 480, both 07:00) collide, and the 95 on the 23:00
+shift is its own shift. State both numbers. One false alarm in the list is what makes a supervisor stop
+reading the rest of it. A date-window gap (Class 7) is different: it stays a
+coverage statement in the freshness banner, and is not a record-level
+exception either.
+
+### Step 9 — Propose the reschedule or changeover move
+
+For each significant exception: the specific move, what it displaces, what still
+misses its date, and what was checked versus not checked.
+
+**Read `reference/reschedule-scope.md` before doing this.** There is a hard scope
+line — one or two traced moves, never a re-optimised day — and the reason is that
+a plausible-looking schedule that quietly violates constraints is worse than no
+proposal at all.
+
+Drafted for the scheduler. Never applied.
+
+### Step 9a — Floor view
+
+**Read `reference/floor-schematic.md` first.** It holds the setup turn, the
+save, the drawing rules, the states, the thresholds and the failure modes.
+
+- **The user attaches a floor plan, or asks for a floor view and none is on
+ file:** run the setup turn. State the count first, propose each match with
+ both spellings verbatim, list what did not match on either side, and **ask
+ for a yes per area**. Turn 1 shows, turn 2 saves, and only with a name or
+ role the person typed. Per `../../shared/approval-gates.md`.
+- **A layout is on file** (the `### Floor layout - <site>` section of the
+ profile): draw it from the figures block. **Compute nothing new.** An
+ unconfirmed mapping is a neutral outline with no figure. No data is grey,
+ never 0%. Data but no computable OEE is grey *OEE N/A* with its reason.
+- **No layout:** one line saying none is on file and how to set one up.
+
+**An unattended run never sets up, edits or re-maps a layout**, and never
+draws a guess. Colours follow the profile's `OEE thresholds` line; until the
+plant confirms one, the defaults are used and the legend says so.
+
+### Step 10 — Emit
+
+**Build the figures block first, in code, then write from it.** Every count,
+total, percentage and "N of M" in the report — events per reason code, events
+sharing a timestamp, minutes per asset, scrap share per part — is printed from
+a computation run in this session and listed in the block with its filter. The
+prose and the tables quote the block; nothing is retyped from memory. Per
+`../../shared/computed-figures.md`. "Thirty of the 39 events" written beside a
+log that holds thirty-one is what this step exists to stop.
+
+Render the report and the structured data behind it, per Output below. Chain 3
+emits overnight so the report exists before the morning meeting.
+
+**The run is idempotent.** A re-run for the same production day rewrites that
+day's report; it does not create a second one.
+
+---
+
+## Approval gates
+
+**This skill is read-only.** It reads, computes, prices and proposes, and it
+writes nothing to any system of record — which is precisely why Chain 3 is safe
+to run unattended.
+
+**Asked to post, send or share the report** — to a Teams channel, by mail, to
+Slack — **say it does not post, and give the text ready to paste.** *"I don't
+post to Teams. Here's the report as text to paste into the Production
+channel."* No send tool is called, even where one is available, and **no offer
+to post later**: not "confirm the channel and I will post this." The report is
+still produced in full. Per `../../shared/command-center.md`.
+
+Two things are drafts requiring a human, not actions:
+
+- **The reschedule proposal** is drafted for the scheduler to accept or reject.
+- **A breakdown diagnosis carried in** stays labelled as advisory unless its
+ contract says a technician confirmed it.
+
+---
+
+## Output
+
+**The morning report is written to a file, and the reply is its summary.**
+Save the full page as `report-output/morning-report.html`, one file saved over
+the last run's, as the placement line says, with the site and production day
+in its title; name that path in the reply, which is the short summary in
+`../../shared/replies.md` (about 150 words, 200 at most). A request that picks
+or skips sections is not the whole report: those sections go in the reply in
+full. **With no way to write a file,
+print the full page in the reply instead.** Any other document this skill
+produces (a reschedule proposal handed to the scheduler, text to paste) is
+printed in the reply in full.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The morning report** — an HTML page in the house style
+(`../../shared/artifact-style.md`), and the Operations command-center page
+(`../../shared/command-center.md`) — an artifact you place, never a write.
+Chain 3 rewrites it overnight, which is the whole demonstration.
+
+**Run alone, this skill does not publish.** It never creates or updates the
+Operations Command Center dashboard and never writes a day record: only
+`morning-plant-pulse` does, per `../../shared/live-dashboard.md`. A standalone
+run returns its page in the conversation with the placement line, *"save it
+over yesterday's,"* and never says the dashboard was updated. Two dashboards
+showing the same numbers is how a meeting ends up arguing about which is
+right. **The page leads with what the meeting acts on and keeps all the
+evidence below it**. In order:
+
+1. **Safety blocks, whenever they have anything in them.** A safety-flagged
+ diagnosis record first, then its own section headed exactly "Blocked —
+ safety status unknown", above the freshness banner
+2. **Freshness banner** — required, directly under any safety block and first
+ otherwise, never a footnote. It states the shifts the day actually holds;
+ a day with fewer shifts than usual says so, and is not a complete plant day
+3. **Headline figures**: good output against plan, total output beside good
+ when they differ, OEE with its three components, downtime minutes, and
+ scrap at standard cost (an estimate). Each caveat sits on its own figure
+4. **Today's actions**: one row per exception that needs someone, with the
+ issue, its impact (on a commitment where traceable), the next step, the
+ owner role, and its type. **A decision** is something genuinely waiting
+ on an approval: a normalization not yet approved, a reschedule move for the
+ scheduler. **An investigation** is something to find out first: an unknown
+ work order, a contradicted record, an uncoded stop. **An observation**
+ needs no action today. The owner role is the one the source names, else
+ *"suggested: <role>"*; never a person's name the data does not hold. With
+ nothing waiting, say *"No decisions waiting today."* Never present a
+ reschedule, a reserved capacity or a root cause as already approved
+5. **Floor view**: the schematic, its legend, *"State as of the last
+ export, [time]. Not live."* and the lists under it, per
+ `reference/floor-schematic.md`. Every number is a figures-block row. With
+ no layout, one line
+6. **The detail**, every table the report has always held, collapsible but
+ never removed: output against plan with variances; OEE per asset or line,
+ three components separate; downtime ranked by minutes and by frequency;
+ priced losses with the rate assumption stated; week-over-week movers,
+ omitted entirely when there is no earlier day to compare; exceptions with
+ their commitment impact; reschedule proposals, one per significant
+ exception; then sources, methods and assumptions
+
+**Safety leads the report, freshness comes straight after it.** A safety
+implication goes before anything else, and a banner of source ages is not
+a reason for a lockout instruction to sit second. **When there is a safety
+block, it is the first thing under the title.** The title names the site and
+the production day, nothing else: no data age, no scope line, no intro
+sentence above the safety block. *"Fairview: morning report, 31 Aug"*, then
+the safety block, then the freshness banner. Both stay above every
+ranking and figure. "Blocked — safety status unknown" lists every diagnosis
+record held out of the rankings. **"Checked, nothing wrong"** follows the
+exceptions, holding the one-sided records that were looked at and are fine —
+outside every problem count.
+
+**The structured data behind the report**, so every number can be checked rather
+than taken on trust. **It includes the figures block** — required on every
+run, attended or not: each stated figure, its value, and the filter that
+produced it, per `../../shared/computed-figures.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **Last night's export did not land** — report the gap prominently. Never
+ silently reuse yesterday's data.
+- **Partial data, one line's export missing** — report on what is there, name
+ what is missing. Never let a section quietly shrink.
+- **Reason codes inconsistent or heavily "Other"** — report the coverage problem.
+ That is a finding of its own, not a data-cleaning task.
+- **A machine ran unscheduled overtime** — availability can exceed 100%. Report
+ it; do not clamp it.
+- **Three shifts crossing midnight** — the production-day attribution rule is
+ configured per site, and the report states which convention is in use.
+- **No earlier day in the history or the exports** — skip week-over-week.
+- **An asset in the plan with no output data** — it is unreported, **not 0% OEE**.
+ Name it and exclude it from averages, saying so.
+- **No standard cost available** — report scrap in units and say it could not be
+ priced.
+- **Anything in the floor view** (an unreadable plan, a label that could be
+ two assets, a down machine, an asset added later, a busy drawing) — per
+ `reference/floor-schematic.md`, *Failure modes*.
+
+---
+
+## Degradation
+
+**If Limble isn't included, or no CMMS connector is live** — minor. The report loses its "maintenance work
+orders in progress" line. Replace it from the maintenance export where one
+exists, or omit the line **and say so** — never leave a silently empty section,
+which reads as "no open maintenance" rather than "we could not see it."
+
+Chain 3 is unaffected in any meaningful way: it is an overnight batch, so export
+cadence is already the right cadence. The freshness banner names maintenance as
+export-sourced so nobody assumes it is live.
+
+**Without a planning export** — output against plan cannot be computed. Report
+actual output and say plan comparison was unavailable.
+
+**Without a downtime cost rate** — price scrap only, and state that downtime is
+unpriced.
+
+**Without a floor layout** — one line saying none is on file and how to set
+one up. Nothing else changes. Without OEE thresholds, the defaults, labelled.
+
+---
+
+## Chain position
+
+- **Chain 3, Morning plant pulse (scheduled)** — step 2, from `data-consolidate`.
+ The only scheduled chain, read-only throughout, which is why it needs no
+ approval gate.
+- **Chain 4, Breakdown to next report** — step 2, from `breakdown-diagnosis`.
+ Step 7 folds its downtime record into the log and exceptions with no
+ transformation, per `../../shared/contracts/downtime-record.md`.
+
+**Metric.** OEE visibility; supervisor hours; downtime and scrap cost
+visibility — step 5 prices both on every run, not only when a breakdown fed
+in.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/oee.md` | Step 3 — the three components, the denominator traps, and the never-substitute-1.0 rule |
+| `reference/reschedule-scope.md` | Step 9 — what a proposal must contain and where the scope stops |
+| `reference/floor-schematic.md` | Step 9a — the setup turn, the drawing rules, the OEE thresholds |
+| `../../shared/contracts/floor-layout.md` | Step 9a — the stored layout's shape and missing behaviors |
+| `../../shared/contracts/consolidated-dataset.md` | Step 1 — the primary input's schema and its missing behaviors |
+| `../../shared/contracts/downtime-record.md` | Step 7 — the shape a breakdown diagnosis arrives in |
+| `../../shared/approval-gates.md` | Step 2 — a match that rests on an unapproved normalization is provisional |
+| `../../shared/computed-figures.md` | Step 10 — the figures block every stated number is quoted from |
diff --git a/plugins/claude-for-manufacturing/skills/daily-production-report/reference/floor-schematic.md b/plugins/claude-for-manufacturing/skills/daily-production-report/reference/floor-schematic.md
new file mode 100644
index 00000000..dbfde6df
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/daily-production-report/reference/floor-schematic.md
@@ -0,0 +1,265 @@
+# The floor view — setting it up and drawing it
+
+Loaded at step 9a. The record it reads and writes is
+`../../../shared/contracts/floor-layout.md`. House style is
+`../../../shared/artifact-style.md`, component *Floor schematic*.
+
+**What it is.** The plant's own floor, redrawn as a clean schematic, with each
+machine's numbers sitting where the machine is. A supervisor reads "the
+bottleneck is the second machine in Cell B" faster off a map than off a table.
+It is a **view of figures the report already computed**, never a new
+calculation: every number on it is a row of the figures block.
+
+**What it is not.** Not live: it shows the state at the last export, and says
+so. Not to scale: positions are approximate. Not a replacement for the OEE
+table, which stays below it and carries the three components for every asset.
+
+---
+
+## Two turns, never one
+
+**Turn 1 shows the proposed layout and asks. Turn 2 saves it.** Same rule as
+`onboarding`, *Two turns, never one*, and `../../../shared/approval-gates.md`:
+a yes covers the matches that were shown, with both spellings, and nothing
+else.
+
+### Setup turn (attended, once per site)
+
+Runs when the user attaches a floor plan, or asks for a floor view and no
+layout is on file.
+
+**1. Read the drawing.** PDF or image. A DWG or other CAD file cannot be read
+directly: say so and ask for a PDF or image export.
+
+- **Machines are labelled shapes.** Walls, dimension lines, utilities, doors,
+ columns, aisle names and notes are not machines and are ignored. A box with
+ no label is not assumed to be a machine: count it, and ask in step 3.
+- **A legend or key comes first.** Where the drawing labels machines with codes
+ (`M-04`) and carries a key, read the key before the machines. The drawing
+ label stays verbatim (`M-04`); the key supplies the name used to propose the
+ asset, and the proposal says it came from the key.
+- **Every label gets a read mark, `clear` or `unsure`.** `unsure` is a label
+ that is small, rotated, overlapped, cut off or low-contrast. **Never propose
+ an asset from an `unsure` label.** Quote what was read, with a question mark,
+ and ask the user to correct it.
+- **One floor per drawing.** A plan that shows more than one floor or a
+ mezzanine: say so, ask for one floor at a time, and set up the main floor
+ first. Other floors are not supported yet.
+- **Set `read_confidence`:** `clean` when every label is `clear`; `partial`
+ when some are `unsure` (list them); `poor` when more than a quarter of the
+ machines are `unsure`, or the text cannot be read at normal size. **On
+ `poor`, stop and ask for a clearer plan or a larger export.** Never guess
+ labels. The quarter is a starting cutoff, not a plant-set value.
+
+**2. State the count before anything else.** *"I read 23 machines and 4
+unlabeled shapes, in 5 areas."* The user can say at a glance whether a
+machine was missed. A count that does not match what the plant expects is the
+first thing to check.
+
+**3. List what was read, by area.** One table per zone or area in the drawing's
+own order, never one long list. One row per machine: the label **verbatim**,
+the read mark, the position in plain words ("Cell B, upper left"), and the
+proposed asset match with **both spellings verbatim**
+(`Haas VF4 #2` → `HAAS-VF4-02`) and why (name, cell, or both). Candidate
+assets come from the consolidated dataset's asset list, not from memory of
+earlier runs. Then, for the whole drawing:
+
+- Drawing labels with no plausible asset (*"Bandsaw: no asset by that name in
+ the data"*).
+- Assets in the data that no label matched (*"HAAS-UMC-01 has no machine on the
+ drawing"*).
+- The unlabeled shapes, asking whether any is a machine.
+
+Neither list is empty-by-omission: if both are empty, say so.
+
+**4. Ask for a yes per match, or per zone.** *"Yes to Cell 1 as shown"* covers
+the rows shown in Cell 1 and nothing else. Where a label could match two
+assets (`Puma 3` against `DOOSAN-PUMA-03` and `DOOSAN-PUMA-07`), propose none
+and ask which. A blanket "looks good" confirms the rows shown, not rows the
+user did not see. **On a drawing with more than about 12 machines, take it a
+zone at a time**: show a zone, take its yes, save, and move on. Each save is
+turn 2 for that zone; unanswered zones stay `proposed` and draw no figures.
+
+**5. Ask for the name or role** to put on the confirmation. Never take it from
+the account. **No name or role, no save**: ask again, and keep the rows
+`proposed` until one is given.
+
+### Save turn
+
+On the yes, and with a name or role: write the layout into the plant profile
+at `profile_path`, as a `### Floor layout - <site>` section in the shape of
+`../../../shared/contracts/floor-layout.md`. `mapping_status` is `confirmed`
+only for the rows the user confirmed, `proposed` or `unmapped` for the rest;
+increment `Layout version`. Replace only that section; every other line of the
+profile stays as it was.
+
+**Then save the profile the way every write-back does**, per
+`../../../shared/replies.md`, *The plant setup and the rates*: follow
+`install`'s `after_any_change` when the profile came from the plant setup
+page, or for a first save `render`, publish, read back and give `saved`'s line
+word for word. The layout then rides the plant setup page, and any new task
+finds it with `plant_setup.py find`, with no file attached.
+
+Say "saved" only after `saved` confirms it, and name the page. Without the
+artifact tools, or with the page refused, say the layout is in this task's
+`profile_path` only and lasts only for this task. The yes in the setup turn
+covers this save; no further approval is asked.
+
+---
+
+## Every run
+
+1. **Find the layout**: the `### Floor layout - <site>` section of the
+ profile at `profile_path`, after `plant_setup.py find` has brought in the
+ plant setup page. A layout with no `Layout version` line is version 1: read
+ it with the defaults in the contract. An unattended run never writes. None
+ found: skip the section with the one-line statement in the contract, and
+ carry on.
+2. **Compute nothing new.** For each `confirmed` machine, read its row from the
+ figures block: OEE, availability, performance, quality, downtime minutes,
+ open-outage start if any. A machine with no row has no data (below). A
+ machine with a row but no OEE (output with no scrap or no ideal cycle time
+ recorded) is *OEE N/A* (below).
+3. **Colour by the plant's thresholds**, read from the profile's
+ `OEE thresholds` line. See *Thresholds*.
+4. **Choose the density** from the machine count (see *Dense floors*), then
+ **draw** the schematic as inline SVG built in code, numbers baked in,
+ canvas proportions from `canvas_aspect`.
+5. **Print the lists under it**: not on the floor plan, on the plan with no
+ data, OEE not computable (with the reason), mapping not confirmed. Each with
+ its count.
+
+---
+
+## Dense floors
+
+The schematic has to stay readable at the page width. The density is chosen by
+the count of **confirmed machines drawn**, and the chosen mode is named in the
+caption.
+
+| Machines | Mode | What each machine shows |
+|---|---|---|
+| Up to 24 | Full | Name, OEE, availability, state word |
+| 25 to 60 | Compact | Name, OEE, state word. Availability stays in the OEE table below |
+| More than 60 | By area | One schematic per zone, in the drawing's order, each with its own legend line, preceded by an overview of the plant: one block per zone coloured by its worst machine, with the counts (*"Cell 3: 2 poor, 1 watch, 9 OK"*) |
+
+The cutoffs are starting values, to be tuned against real plants.
+
+- **A state word is never dropped to make room.** `OK`, `WATCH`, `POOR`,
+ `DOWN`, `NO DATA`, `OEE N/A`, `UNCONFIRMED` are short; the name is what gets abbreviated
+ first, and the full name is in the table.
+- **No text smaller than the house `--text-xs`.** If a name does not fit at
+ that size, it is shortened with the full name in the table, never shrunk.
+- **Zones that are not rectangles** are drawn from their outline points when
+ the layout holds them, and as their bounding box when it does not.
+- **Machines are drawn as boxes** whatever their real shape. Positions stay
+ approximate.
+
+---
+
+## Thresholds
+
+The plant sets them; the skill supplies defaults only until it does.
+
+| State | Default | Rule |
+|---|---|---|
+| Good | OEE at or above 75% | Configurable |
+| Watch | OEE from 60% up to the good line | Configurable |
+| Poor | OEE below 60% | Configurable |
+| Down | Machine currently down | **Always poor**, whatever the day's OEE |
+| No data | No row in the figures block | **Always neutral grey.** Never coloured, never 0% |
+| OEE N/A | A row, but OEE cannot be computed | **Neutral grey**, *OEE N/A*, availability still shown, the reason listed under the schematic |
+
+- **Read them** from the `OEE thresholds` line of the plant profile:
+ *"good at or above X%, poor below Y%"*. A line with a confirmed value is the
+ plant's.
+- **Missing line, or a placeholder:** use the defaults above and print, once, in
+ the legend: *"Colours use default thresholds (75% / 60%), not confirmed for
+ this plant."* The note disappears only when the plant has confirmed values.
+- **The legend always prints the active cutoffs**, whichever source they came
+ from.
+- **Thresholds colour OEE only.** They never recolour a down machine, a
+ no-data machine or an unconfirmed mapping.
+- **Nothing here changes a threshold.** A run cannot edit the profile; that
+ takes the profile's two-turn approval via `onboarding`.
+
+---
+
+## Rules inherited from the rest of the skill
+
+- **Absent is not zero** (`../../../shared/absent-is-not-zero.md`). A confirmed
+ machine with no output or downtime row reads *no data* in grey. It is
+ excluded from every average and named in the list under the schematic. It is
+ never 0% OEE.
+- **An ongoing outage has a null duration.** Draw *"down since 02:20"*, never
+ *"down 0 min"*, per `../../../shared/contracts/downtime-record.md`.
+- **Availability above 100% is shown, not clamped** (`oee.md`). The machine's
+ fill follows OEE; the cell prints the availability as it is.
+- **Safety leads.** A machine with a safety-flagged diagnosis record is
+ outlined in the critical colour with the words *"see safety block"*, and the
+ safety block stays the first thing under the title, above the schematic. A
+ record blocked for missing `safety_flagged` does not colour its machine; the
+ machine carries *"blocked, safety status unknown"*.
+- **Provisional matches.** A machine whose figures rest on an unapproved
+ normalization is marked *provisional*, as in the tables.
+- **Status never by colour alone.** Every machine prints a word or glyph with
+ its state.
+- **Freshness stays above it.** The schematic sits below the freshness banner
+ and carries its own line: *"State as of the last export, [timestamp]. Not
+ live."* A missing export is the banner's first row and the schematic's
+ machines show *no data*, not yesterday's numbers.
+- **Nothing is silently dropped.** An asset in the data with no machine on the
+ plan is listed with its figures under *Not on the floor plan*. A drawn
+ machine with no asset is listed under *On the plan, not in the data*.
+- **Layout drift.** An asset that appears in the data after the layout was
+ confirmed, and is on neither list, goes under *Not on the floor plan* with
+ *"new since the layout was confirmed"*. The skill does not place it.
+- **Approximate by design.** One line says positions are schematic, not to
+ scale.
+
+---
+
+## What it does not do
+
+- No click-through detail; the OEE table below carries every machine's three
+ components.
+- No per-machine trend.
+- No live status.
+- No DWG or CAD input, and one floor per layout. A drawing that shows several
+ floors is set up one floor at a time, and only the main floor is supported.
+- No automatic re-reading of a changed drawing. A changed floor is a new setup
+ turn, `Layout version` + 1, confirmed again.
+
+---
+
+## Failure modes
+
+- **A plan that cannot be read reliably** (`poor`): stop the setup turn and ask
+ for a clearer one. A DWG or other CAD file: ask for a PDF or image export.
+- **A drawn machine that matches no asset, or an asset with no machine on the
+ drawing**: both listed under the schematic. Neither is dropped, and neither
+ is given figures.
+- **A label that could be two assets**: propose neither, ask which.
+- **A machine currently down**: always poor, whatever its day's OEE, printed
+ *down since* its start time, never a zero duration.
+- **An asset added after the layout was confirmed**: listed as new since the
+ layout was confirmed, not placed.
+- **A busy drawing**: the count first, one table per area, a yes a zone at a
+ time past about 12 machines, one floor per layout; density per *Dense
+ floors*.
+- **The page cannot be saved**: the layout stays in this task's
+ `profile_path`; say it lasts only for this task.
+
+## What this section exists to prevent
+
+- A machine shown with *another* machine's OEE because a label was matched by
+ guess, or because a small label was misread.
+- A down machine coloured green because the day's average was fine.
+- A machine with no export row drawn red at 0%, read by the meeting as a
+ breakdown.
+- A stale layout silently hiding a machine added last month.
+- A schematic that looks live and is a day old.
+- A machine missed on a busy drawing and nobody noticing, which is why the
+ count comes first.
+- A layout that only exists in the task where it was set up, so every new
+ thread starts from nothing.
diff --git a/plugins/claude-for-manufacturing/skills/daily-production-report/reference/oee.md b/plugins/claude-for-manufacturing/skills/daily-production-report/reference/oee.md
new file mode 100644
index 00000000..a6f0e520
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/daily-production-report/reference/oee.md
@@ -0,0 +1,152 @@
+# OEE — the three components and the traps
+
+Load this before computing anything.
+
+**OEE is the number everyone in operations knows by heart.** A plant reporting
+60–70% is normal; 85% is world-class. That familiarity is exactly why a wrong OEE
+destroys trust in the whole report — a supervisor who sees 91% on a bad week
+stops reading.
+
+```
+OEE = Availability × Performance × Quality
+```
+
+---
+
+## Never report the composite alone
+
+**Always show the three components separately.** This is a done-when condition,
+not a presentation preference.
+
+An OEE of 62% caused by availability is a maintenance problem. The same 62%
+caused by quality is a completely different meeting with different people in it.
+The composite tells a plant manager the day was bad; the components tell them who
+to call.
+
+---
+
+## Availability
+
+```
+Availability = run time / planned production time
+```
+
+**Planned production time is a configured definition, not a derivation.**
+`onboarding` captures it per site: scheduled shift hours minus whatever that plant
+excludes — planned maintenance windows, breaks, scheduled changeovers. Read it
+from the `## Plant context` block and **state the definition in the report**, because
+two plants computing availability against different denominators are not
+comparable and neither is one plant before and after a definition change.
+
+### Four denominator traps
+
+**Unscheduled overtime.** A machine that ran hours it was never scheduled for can
+produce run time exceeding planned production time, and availability above 100%.
+**Report it; do not clamp it to 100%.** An availability of 118% is a finding
+about the schedule definition, and silently capping it hides both the overtime
+and the definitional problem.
+
+**Cross-midnight shifts.** A three-shift plant has a shift that starts on one
+calendar day and ends on the next. The `production_day` attribution rule is
+configured per site — the day the shift started, or the day it ended — and the
+report states which convention is in use. Getting it wrong moves a whole shift of
+output to the wrong day, which makes one day look bad and the next look good.
+
+**Planned downtime counted as downtime.** A scheduled PM window is excluded from
+the denominator, not counted as a stoppage. Counting it as unavailability
+punishes a plant for doing maintenance correctly.
+
+**A machine idle because there was nothing to run.** This is real, common, and
+not a maintenance problem. Whether the plant excludes no-demand time from planned
+production time is their definitional choice, captured at onboarding. Do not
+decide it here.
+
+---
+
+## Performance
+
+```
+Performance = (ideal cycle time × total count) / run time
+```
+
+Ideal cycle time comes from the routing's standard time for the operation.
+Where a plant's routing standards are stale or absent, **performance cannot be
+computed** — see the rule below.
+
+Performance above 100% means the part ran faster than its standard, which
+usually means the standard is wrong rather than the machine being miraculous.
+Report it as a finding about the standard.
+
+---
+
+## Quality
+
+```
+Quality = good count / total count
+```
+
+Total count is good plus scrap plus rework, per the plant's own convention.
+**Rework is the ambiguous one** — a part reworked into conformance was not made
+right the first time, so first-pass yield excludes it. State which convention was
+used, on every run, as one line under the table:
+
+- Export has a rework column → *quality = good ÷ (good + scrap + rework),
+ first-pass yield.*
+- Export has no rework column → *quality = good ÷ (good + scrap); no rework
+ column, so first-pass yield could not be applied.*
+
+The caveat belongs to the second case only. Printing "no rework column"
+against an export that has one is a false statement about the plant's data.
+
+---
+
+## The rule that matters most: never substitute 1.0 for a missing component
+
+If a component cannot be computed, **report the components you have and say the
+composite is unavailable.** Do not multiply by 1.0 in place of the missing one.
+
+This is `../../../shared/absent-is-not-zero.md` applied to the most-watched number
+in the plant, and it fails in the flattering direction. A plant with no routing
+standards, whose performance is therefore unknown, would report:
+
+```
+Availability 0.78 × Performance [unknown as 1.0] × Quality 0.96 = 75%
+```
+
+That 75% looks like a decent day and it is arithmetic on a value nobody measured.
+Real performance of 0.71 would have made it 53%. **Absent is not zero, and absent
+is also not one hundred percent.**
+
+The honest output:
+
+> *"Availability 78%, quality 96%. Performance can't be computed — the routing
+> standards for these parts aren't in the dataset, so there's no ideal cycle time
+> to compare against. Composite OEE is unavailable until those land."*
+
+---
+
+## Grain
+
+Compute per asset or per line, and **state which**. An OEE averaged across a cell
+of five machines hides the one machine causing the problem, which is usually the
+entire point of looking.
+
+Where the plant's vocabulary calls it a cell, a line or a work center, use their
+word, per the `## Plant context` block.
+
+---
+
+## Sanity checks before reporting
+
+| Check | If it fails |
+|---|---|
+| Each component within 0–100% | Report the value and the likely denominator cause. Never clamp |
+| Composite within 0–100% | Follows from the components; a composite outside range means one is wrong |
+| Total count equals good plus scrap plus rework | Report the discrepancy; it means two sources disagree |
+| Run time not greater than planned production time | Usually unscheduled overtime. Report it |
+| Every asset in the plan appears in the output | A missing asset is not a 0% asset. Name it as not reported |
+
+That last row is the one most likely to be got wrong. **A machine with no data is
+not a machine at 0% OEE.** It drags a plant average down and invents a
+maintenance crisis. Report it as unreported and exclude it from the average,
+saying so.
diff --git a/plugins/claude-for-manufacturing/skills/daily-production-report/reference/reschedule-scope.md b/plugins/claude-for-manufacturing/skills/daily-production-report/reference/reschedule-scope.md
new file mode 100644
index 00000000..bceda190
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/daily-production-report/reference/reschedule-scope.md
@@ -0,0 +1,108 @@
+# The reschedule proposal — and where it stops
+
+Load this before proposing any schedule move.
+
+---
+
+## What this is not
+
+**This is not finite-capacity scheduling.**
+
+Producing an optimal shop schedule is a constraint-optimisation problem. A
+language model asked to do it will return a plausible-looking schedule that
+quietly violates constraints — and that is **worse than returning nothing**,
+because a scheduler who accepts it discovers the violation on the floor, at
+which point the report has actively caused a problem it was supposed to report.
+
+So there is a hard line here, and it is drawn deliberately rather than
+apologetically.
+
+| Out of scope | In scope |
+|---|---|
+| Re-optimising the day | One or two specific moves |
+| Sequencing every job across every cell | Moving one job, and tracing what that displaces |
+| Balancing load across the plant | Naming what still misses its date after the move |
+| Anything presented as optimal | Something presented as checked, with the checks listed |
+
+---
+
+## What a proposal must contain
+
+Four parts. A proposal missing any of them is not actionable and should not be
+offered.
+
+1. **The move.** Specific: which job, from where, to where — and **the
+ changeover it implies**: what the receiving cell was running before, and
+ what switching it costs. A move that reads as free because nobody named
+ the changeover is not a checked move.
+2. **What it displaces.** Every job the move pushes, and where each one lands.
+3. **What still misses.** After the move, which commitments are still not met.
+ **A proposal that claims nothing misses is the one to distrust most.**
+4. **What was checked, and what was not.** Explicitly. This is what lets a
+ scheduler accept or reject without rebuilding the analysis.
+
+An example, with the changeover made explicit:
+
+> *"Run 4471 on cell B instead of cell A; cell B was running 4390's finishing
+> pass, so this costs a changeover — call it 40 minutes on this tooling. That
+> pushes 4402 to second shift, where it still makes its date; 4390 now misses
+> by one day."*
+
+Four clauses. One move with its changeover, one displacement with its
+outcome, one casualty named. That is the whole deliverable. Where the
+changeover cost genuinely can't be estimated, say that explicitly rather than
+silently dropping it — it is degradation, per the table below, not omission.
+
+---
+
+## The honesty requirement
+
+**State what was not checked.** A move traced through due dates but not through
+tooling availability, operator certification, or material on hand is a partial
+check, and saying so is what keeps it useful.
+
+> *"Checked: due dates on the three affected jobs, and cell B's routing for 4471.
+> Not checked: whether cell B has the fixture, whether second shift has a
+> certified operator for 4402, and material availability. Worth confirming those
+> before committing."*
+
+A scheduler reading that knows exactly how much of their own judgment is still
+required. A scheduler reading a bare proposal does not, and will either
+over-trust it or ignore it.
+
+---
+
+## One or two moves, not a plan
+
+Propose per significant exception, not for the day as a whole. Where three
+exceptions each need a move and the moves interact, **say that they interact and
+stop** rather than composing them into a schedule.
+
+> *"These three exceptions all want cell B. Individually each move works; together
+> they conflict, and untangling that is a scheduling decision rather than
+> something I can check. Here are the three moves separately, with the conflict
+> named."*
+
+---
+
+## Never applied
+
+The proposal is **drafted for the scheduler**, never applied to any system. This
+skill writes nothing to a system of record. It reports, prices, and proposes.
+
+---
+
+## Degradation
+
+The proposal depends on the schedule export and on changeover or routing data.
+
+| Available | Behavior |
+|---|---|
+| Schedule export and routing data | Propose the move, fully traced |
+| Schedule export, no routing or changeover data | Propose the move; state that changeover time was not accounted for |
+| Neither | **Report the exception with its impact on commitments and no proposed move — and say which** |
+
+That last row is the important one. Per `../../../shared/absent-is-not-zero.md`,
+the report says the move was not proposed because the schedule data was not
+available. It does not silently omit the proposal, which reads as "nothing needed
+to move."
diff --git a/plugins/claude-for-manufacturing/skills/data-consolidate/SKILL.md b/plugins/claude-for-manufacturing/skills/data-consolidate/SKILL.md
new file mode 100644
index 00000000..f3e5622f
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/data-consolidate/SKILL.md
@@ -0,0 +1,486 @@
+---
+name: data-consolidate
+description: "Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders, purchase orders, inventory, routings and closed-job operation actuals; CMMS assets and maintenance work orders; and the MES, historian, quality and planning files landing in the Microsoft 365 export folder. Keys on part number, production work order, sales order, lot, asset and supplier, classifies every key that fails to match into one of eight mismatch classes, and proposes the correction rather than reporting a count, applying nothing without a yes. Runs file-only with no connector, or connector-only with no files. Use when someone says \"pull the data together,\" \"consolidate the exports,\" \"build the dataset,\" \"join production to the ERP,\" or \"why don't these numbers match,\" and before any reporting or quoting skill runs."
+compatibility: "Requires none. Reads the ERP (Oracle NetSuite or Infor M3), a CMMS connector (Limble is the worked example) and the Microsoft 365 export folder when connected, and runs on files alone or connectors alone. Emits an XLSX dataset plus an HTML data quality report."
+---
+
+# Data Consolidate
+
+The foundation layer. The dataset this skill produces is where every
+data-dependent skill reads from by default, rather than going back to the raw
+sources — and it is the only place the sources are joined and their key
+mismatches classified.
+
+**"By default" is exact, not a hedge.** Three skills also read a
+raw export, and they are right to: see
+`../../shared/contracts/consolidated-dataset.md`, *What this dataset is
+authoritative for*. Nothing here carries a high-frequency sensor trace, and a
+normalized value is not always the value as recorded.
+
+**The reason it exists.** The majority of real manufacturing data does not arrive
+through a connector. It arrives as a file. The plant already runs scheduled
+exports out of its MES, historian, inspection system and planning tool, usually
+into a shared drive for somebody's spreadsheet. This skill reads that folder plus
+the live connectors, joins everything on the identifiers the plant already has,
+and hands back one dataset with every unmatched record explained.
+
+**Quick start**
+
+> "Pull last month's production together with the ERP."
+
+```
+→ Read the export folder; identify each file by name and header signature
+→ Report each source's timestamp and coverage window before joining anything
+→ Pull the ERP (NetSuite or Infor M3) and any live CMMS connector scoped to the same window
+→ Normalize keys up the ladder, logging every rule that fires
+→ Join around the five anchors: part, production work order, sales order, lot, asset
+→ Classify every mismatch, propose each fix, apply nothing without a yes
+→ Emit the dataset and the data quality report
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| Item / part master | The ERP: NetSuite or Infor M3 | Connector |
+| Sales orders | The ERP | Connector |
+| Production work orders | The ERP | Connector |
+| Purchase orders and suppliers | The ERP | Connector |
+| Inventory positions | The ERP | Connector |
+| Routings — operations, work centers, setup and run standards per part and revision | NetSuite where manufacturing routings are licensed; else an ERP export or an Excel sheet dropped in. Infor M3 always takes the export | Connector, CSV / XLSX |
+| Operation actuals — setup and run hours per closed production work order and operation | NetSuite closed work orders where licensed, or Infor M3 work order operations; else an export or an Excel sheet | Connector, CSV / XLSX |
+
+Which M3 call fills each row, and what M3 does not give, is
+`../../shared/erp-connectors.md`. Read it before an M3 pull.
+| Assets and maintenance work orders | CMMS | CMMS connector, else the maintenance export |
+| Actual production output | MES export to the M365 folder | CSV / XLSX |
+| Downtime events | MES or historian export to the M365 folder | CSV |
+| Inspection / quality results | Quality system export to the M365 folder | CSV / XLSX |
+| Planning / schedule | Planning tool export to the M365 folder | CSV / XLSX |
+
+Four of those have no connector and never will. File-only is the designed path,
+not the degraded one. Routings and actuals are often a spreadsheet someone
+keeps, and that is a complete input.
+
+The machine class to work center and cell map, the time units, and anything
+else this skill reads about machining come from `### Machining data` in the
+`## Plant context` block, which `onboarding` writes. Where that section is
+absent, say so once and carry on without it.
+
+---
+
+## Workflow
+
+### Step 1 — Discover
+
+Read the configured export folder. Identify each file by name pattern and header
+signature, and say what each one was identified as.
+
+**Report anything unrecognized rather than guessing.** A file that cannot be
+identified is named and set aside, not silently skipped and not hopefully parsed.
+
+**Routings and operation actuals are recognized by header, not by hope.** A
+routing carries part, operation sequence, work center and a setup and run
+standard; an actuals file carries a production work order, an operation and
+the hours booked against it. The signatures are in `reference/join-keys.md`,
+*Routings and operation actuals*. A file that looks like either but misses a
+signature column is unrecognized and named, not loaded with the gap filled.
+
+**When the folder holds months of daily files**, do not read everything. Offer
+the choice — latest drop, or a named date range — and state which was used.
+
+`onboarding` owns the folder path, the file inventory and the refresh cadence —
+read them from the `## Plant context` block rather than asking. If no profile
+exists, ask for the path once, carry it through the run, and offer `onboarding`
+so the next run does not ask again.
+
+**If the folder is empty, missing, or there are no files at all**, do not stall
+on discovery. Ask for the date window once, then go to step 3 and run
+connector-only. **In an unattended run (Chain 3, triggered host-side — see
+`../../shared/scheduling.md`) there is no
+one to ask** — use the production-day range from the `## Plant context`
+block instead, per Step 2's fallback, and say the window was chosen rather
+than inherited from a file. That path is specified under Degradation.
+
+### Step 2 — Freshness check
+
+Record every source's last refresh timestamp and the window it covers, and put
+that in front of the user **before** any joining or any figure.
+
+**Refuse to join sources whose windows do not overlap meaningfully**, and say so
+plainly rather than producing a dataset full of manufactured mismatches. The
+rule is `../../shared/absent-is-not-zero.md`; a stale export is the normal
+failure here, not the exotic one.
+
+**A source timestamp later than the run time is a critical freshness
+finding.** A created, last-modified or transaction date after now means the
+source's clock is ahead or its data was seeded with future dates; either way
+none of its `as_of` values can be trusted. Say so in the banner, by source and
+with the latest such timestamp, give no "data as of" or age for that source,
+and do not use its dates to set a window. The rows stay, flagged
+`future_timestamp`. A due, promised or delivery date in the future is a
+commitment, not this finding.
+
+**Where the windows overlap only in part, state the overlap in dates and offer
+exactly two choices, named as such:** *(1) narrow the join to the overlap,
+2026-08-01 to 2026-08-31, or (2) wait for the next export and re-run.* Never
+one choice, and never narrow silently: "I've scoped every total to August" is
+a decision the user did not make. Whichever they pick, every total below is
+labelled as scoped to that window.
+
+**The window applies by entity, not to every row alike.** Narrowing scopes
+activity records only. Open commitments are kept by status, and reference
+history by a lookback, because those are exactly the records later skills
+need. The three kinds, and the lookback, are in `reference/join-keys.md`,
+*Date windows by entity*. Say in the report which kind each tab was scoped as.
+
+### Step 3 — Pull connector data
+
+The ERP (NetSuite or Infor M3) and any live CMMS connector, scoped to the same date window as the file exports. Pulling
+a wider window than the files cover creates Class 7 mismatches out of nothing.
+
+**If there are no file exports**, the window is the one the user just gave, or
+the production-day range from the `## Plant context` block. Scope the connector
+pull to that, and say that the window was chosen rather than inherited from a
+file.
+
+**Never hard-fail on a missing custom field.** Customers configure NetSuite
+heavily and field names vary by account. Fall back, and report what could not be
+read. An Infor M3 search stops at about 30 rows without saying so: pull in
+slices until one returns fewer, per `../../shared/erp-connectors.md`.
+
+**Scope every pull by the profile's `### ERP scope`**, per
+`../onboarding/reference/erp-scope.md`: this plant's subsidiary, locations and
+parts. With no scope set, say *scope not set* as a gap, and **ask, in so many
+words: "Which of these items are your plant's parts?"**, showing what a filter
+would catch (*"10 of 515 items start `PN-`"*). Never pick a filter silently, and
+never answer "how many parts" with one figure until the scope is answered. Where the scope says production work orders are **MES
+only**, take work order identity from the MES export and say so once; never
+report every MES row as unmatched against an ERP that holds none.
+
+**When a connector and an export cover the same entity, check key overlap
+before joining them.** Zero or low overlap means they are not two views of one
+system: ask which is authoritative (or read the profile's *Source of truth*
+line), join only that one, and set the other aside by name. Never merge them,
+and never report every record of one as unmatched against the other.
+
+### Step 4 — Normalize keys
+
+Apply the normalization ladder in order — trim, case, punctuation, leading zeros,
+revision suffix. Read `reference/join-keys.md` for the ladder, the six keys and
+their sources of truth.
+
+Compare on the normalized form and store the original verbatim. **Every
+normalization that fires is logged and reportable.** A missing part prefix
+(`4471B` against `PN-4471-B`) is part of rung 3 only where exactly one part
+on the `parts` tab matches once its prefix is dropped; the ladder says which prefix it used.
+
+**Until a fix is approved, the rows it would join are not joined.** They carry
+`join_status: proposed_normalization`, and only a yes turns them into
+`normalized`. A downstream skill reading the status alone must never take a
+proposal for a join.
+
+### Step 5 — Join
+
+Build the dataset around the anchor entities: part, production work order, sales
+order, lot, asset. Tabs, columns and required fields are fixed by
+`../../shared/contracts/consolidated-dataset.md` — that schema is the plugin's
+stable interface and `custom-connector` maps new systems onto it, so it changes
+deliberately and with a version bump, never incidentally.
+
+Keep production work orders and maintenance work orders distinct — the two
+systems use the same word for different records.
+
+**Detect unit-of-measure columns and flag a mismatch rather than summing across
+it.** Each versus box of twelve, inches versus millimetres. A total computed
+across two units is not a total. **A units conflict is an integrity flag on the
+row**, carried on the dataset and named in the report: refuse a single total
+for that key, report each quantity in its own unit, **and compute no
+conversion** — not "about 6,200 each if box12 means twelve", not a speculative
+factor of any kind. What a `box12` holds is a fact from the plant, not an
+inference.
+
+**Run the integrity checks on every row, in code**, per
+`reference/join-keys.md`, *Integrity checks*: the sign of a quantity (NetSuite
+writes sales order and fulfilment lines as negative; Infor M3 writes them positive), a downtime event that
+ends before it starts or whose duration disagrees with its own start and end,
+and an NCR whose part or date disagrees with the production work order it
+cites. Each failure is a named value in the row's `integrity_flags`, counted
+in the figures block and reported. None is fixed silently.
+
+**Time units on routings and actuals get the same rule.** Record each time in
+its source unit with the unit named — minutes or hours, read from the header or
+a unit column, never from the size of the number. Where a unit is undeclared,
+or a routing states minutes and the actuals for the same operation state hours,
+**flag it on both rows and compute no conversion** into the dataset. The
+backflush check below may convert for its own comparison, and prints that it
+did.
+
+**Map each work center to its cell** through the `Machine classes` table in the
+Plant context (its `Work centers` and `Cell` columns). A work center the map
+does not list is named, with its cell left null — not guessed from its name.
+
+**Run the backflush check on every actuals row, in code.** Set
+`actuals_confidence: probable_standard` where actual run hours ÷ quantity
+matches the routing's run standard within 1%, or where two or more work
+orders for the same part and operation agree on run hours per unit within
+about 1%. Real shop time is not that tidy; an ERP posting the standard is.
+Print the figures that set it, and **name the flag by its value,
+`probable_standard`**, in the report, so the estimator can find it on the tab.
+The rows stay in the dataset, shown, and
+`quote-build` will not rank them above a geometry-derived estimate.
+
+### Step 6 — Classify mismatches
+
+Every unmatched record goes into one of the eight classes in
+`reference/mismatch-classes.md`, reported separately, with counts **and example
+rows**.
+
+**Two routing findings are named by what they are.** A routing for a part the
+item master does not hold is an orphan (class 1): *routing with no matching
+part*. A routing written for a different revision from the one being quoted
+or held as current is a *routing revision mismatch* (class 4), and **for
+routings class 4 has no automatic fix**: stripping the revision to make it
+join would price the new revision on the old one's operations. Detail in
+`reference/mismatch-classes.md`.
+
+**A one-sided record another source contradicts is not left as nothing
+wrong.** Before calling a record Class 6, check whether another source records
+the very activity whose absence made it one-sided: an NCR, inspection rows or
+a lot citing a production work order with no output. Where one does, the record stays Class 6 and
+carries `contradicted_by` naming that source and record, and every consumer
+treats it as an exception. Downtime or maintenance on a machine with no
+production does not contradict anything.
+
+**Check the date window class first.** It explains most large mismatch counts,
+and reporting the other seven on top of an unnoticed window gap sends someone
+chasing problems that do not exist.
+
+**`as_of` carries a zone, or the row says it could not.** The contract requires
+a timestamp with zone on every row. A NetSuite record gives a date and time;
+its zone comes from the account's company preference, or failing that from the
+`## Plant context` source-clock row for NetSuite. An Infor M3 record's zone is
+the server clock (`ARS200MI_ServerTimeZone`), or the source-clock row for M3. Where neither is available,
+**do not invent a time or a zone**: mark the row `as_of` date-only, flag it,
+and say which downstream checks that weakens (cross-source correlation in
+`root-cause-capa`; cross-midnight attribution in `daily-production-report`).
+
+### Step 7 — Count in code, and reconcile before writing
+
+Every figure the report states — rows in, rows joined, matched exactly,
+matched after normalization, rows awaiting a proposed fix, records per class,
+rows per integrity flag, actuals rows flagged `probable_standard` — is
+counted in code and put in
+the figures block (`../../shared/computed-figures.md`). **Reconcile the block
+before writing a word from it:** exact plus normalized equals matched, and the
+normalized total equals the sum of the classes that make it up. A headline
+that disagrees with the report's own class counts is the first thing a reader
+finds, and it discredits every finding beside it.
+
+### Step 8 — Emit
+
+The dataset and the data quality report, per Output below.
+
+---
+
+## Approval gates
+
+**Propose the fix; never apply it silently.** For every mismatch class, produce
+the correction rather than a count — "37 records match if the `Rev 2` suffix is
+stripped; apply?" — **or, where a class has no automatic fix, say so explicitly**
+rather than leaving the finding to speak for itself. The proposal (or the
+explicit no-automatic-fix statement) is always shown; an applied fix always
+needs an explicit yes. A flagged mismatch with neither a proposed fix nor a
+stated reason there isn't one is work handed back to the user, which is the
+thing this skill exists to stop.
+
+**A yes covers what was shown.** Every class is presented with its rule, its
+count and its example rows before anything is applied. Then:
+
+- **"Apply them all" applies every class already shown in this conversation**
+ with those details. It is a yes to each of them, because the user has read
+ each of them.
+- **Any class not yet shown is presented and asked about first.** A blanket
+ yes never reaches a class nobody has read.
+- **Classes with no automatic fix are never applied by any yes** — duplicate
+ keys, orphans, genuine one-sided records. They are questions, and a yes to
+ "apply the fixes" is not an answer to them.
+- **The reply lists each class it applied, with its count**, and notes that
+ the verbatim values are kept in the `_verbatim` columns so any of it can be
+ undone.
+- **Each approved rule is saved to the profile's `### Approved
+ normalizations` list** (rule, both spellings, who said yes, date), where the
+ plant's memory lives per `../../shared/replies.md`, and the reply says so.
+ Every later run applies the rules on that list and only those; an overnight
+ run rebuilds the dataset, and without the list every night would re-propose
+ the same fixes.
+
+The rule is `../../shared/approval-gates.md`.
+
+**A pending decision leads the reply and the report, without replacing
+either.** Above the sources and the details, one bold block headed
+**DECISION REQUIRED: APPROVE OR REJECT** for each normalization still
+awaiting a yes: the exact pair (`4471B` to `PN-4471-B`), why it is proposed
+and its limits, the rows and quantities it touches, what approving and what
+rejecting each do, and the reply asked for. A rule already on the approved
+list shows as **APPROVED** and is never asked again; a rejected one stays
+unmatched and is not re-proposed. Questions with no automatic fix (orphans,
+duplicates, missing units) are never folded into the block, and approving
+the block resolves none of them. With nothing pending, say so in one line and
+lead with the real next action. The full report keeps every section it had.
+
+- **Duplicate keys have no automatic fix, ever.** Surface both rows and let
+ the user say which is real. Never pick, never sum.
+- **Orphan records and genuine one-sided records have no automatic fix
+ either** — they're questions, not formatting problems. Report them with
+ the evidence that bears on which explanation fits.
+
+This skill writes nothing back to any system of record. It reads, joins, and
+hands back files.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The consolidated dataset** — one queryable workbook, per
+`../../shared/contracts/consolidated-dataset.md`. One tab per input
+entity, including `inventory` (on-hand by part and location, not a
+single total on `parts`), `ncrs` where an NCR export was read, and `routings`
+and `operation_actuals` where those sources exist. XLSX is the v1 writer, not a commitment; the shape is the
+contract.
+
+**The data quality report** — rendered as an HTML page in the house artifact
+style (`../../shared/artifact-style.md`), using the freshness banner, stat tiles
+for rows in versus rows joined, a status pill per mismatch class, and a proposal
+block for anything awaiting a yes. It carries:
+
+- Source inventory with each source's freshness and coverage window
+- Row counts in versus row counts joined, per entity
+- Mismatches by class, each block headed by its plain-language name with the
+ number in brackets — *"Format drift (class 2)"* — with its count, its example
+ rows, **and how many records would join if the fix were applied**
+- Every normalization rule that was applied, and what it touched
+- Where routings or actuals were read: each time-unit flag with both units
+ named, each work center with no cell, and each `probable_standard` row with
+ the arithmetic that set it — or the routing tab named missing
+- What each finding means for the plant, in one line each
+- **The figures block** — every count above with the filter that produced it,
+ reconciled per Step 7. The stat tiles and the prose quote it
+- **A verbatim lookup, shown by example**: the report demonstrates that the
+ `_verbatim` columns answer a search by the spelling a source prints — one
+ lookup each for a format-drift, a revision-suffix and a case-and-whitespace
+ spelling, each finding its source row. A plant person searches by the number
+ their MES prints, and this is how they know they can. **When only one system
+ was read**, no second spelling exists: say *not applicable: single-source
+ run* for the lookups and for classes 2 to 5, rather than inventing an example
+- Every integrity flag raised, by name and count, with example rows: sign
+ conventions applied, downtime that ends before it starts, NCRs that
+ disagree with their work order, future timestamps
+
+**Write it for a plant person, not an engineer.** A quality manager or a
+supervisor has to read this report and know what to go fix, in their own
+vocabulary. If it reads like a diff, it has failed.
+
+---
+
+## Edge cases and failure modes
+
+- **An export is stale by weeks and nobody noticed** — the freshness check is
+ loud, at the top, never a footnote.
+- **The folder holds three months of daily files** — offer latest or a range;
+ never read everything by default.
+- **A file is open and locked** — handle it gracefully, name the file, continue
+ with the rest.
+- **A customer-added NetSuite field is missing** — never hard-fail; report it.
+- **An Infor M3 list call returns "Record does not exist"** — that is an empty
+ result, reported as empty, not a failed pull.
+- **Units differ between sources** — flag, do not sum.
+- **A routing in minutes, actuals in hours** — flag both rows, convert nothing
+ in the dataset.
+- **Two work orders agree to the hundredth of an hour per piece** — that is
+ the backflush check, not a good week. Flag `probable_standard` and show why.
+- **A routing has no revision** — revision unknown, never assumed current.
+
+---
+
+## Degradation
+
+**If Limble isn't included, or no CMMS connector is live** (the
+default) — minor. The CMMS is one of roughly ten inputs, and
+assets and maintenance work orders arrive in the same scheduled export as
+everything else. The skill treats them identically; this is precisely the case it
+was designed for.
+
+The one real change: maintenance data inherits the export's freshness instead of
+being live. **Name it explicitly in the freshness banner** rather than letting it
+sit unlabelled among the other sources, so nobody reads exported maintenance
+history as this morning's tickets.
+
+**If no connector is available at all** — the skill runs on the export folder
+alone, and that is a complete outcome. State which sources were file-sourced.
+
+**If no files are available at all** — the skill runs on the live connectors
+alone, and that is also a complete outcome. Ask for the date window (or take it
+from the plant context), pull the ERP and any live CMMS connector scoped to it, and emit the
+tabs those connectors can fill: parts, production work orders, sales orders,
+inventory, assets, purchase orders, maintenance work orders.
+
+Name every tab that could not be built — production output, downtime,
+inspection, plan, **and lots**, because lot numbers come only from the MES or
+quality exports — as missing, not empty. Per
+`../../shared/contracts/consolidated-dataset.md`, an absent tab is a named gap;
+an empty tab reads as "nothing happened." State that every source in this run
+was connector-sourced, so the freshness banner is the connector timestamps, not
+an export cadence.
+
+Join and classify only across the keys that exist on both sides of a connector.
+Do not invent MES-shaped mismatches because the MES file was never there.
+
+**If there is no routing data at all** — no routing connector, no routing file
+— the `routings` tab is **named missing, not left empty**. An empty routings
+tab reads as "this part has no operations." The same holds for
+`operation_actuals`. Say which quoting rungs that removes, in one line:
+without routings, `quote-build` starts at closed-job actuals; without either,
+at a geometry-derived or first-principles estimate.
+
+---
+
+## Chain position
+
+- **Chain 1, RFQ to quote** — step 2, between `customer-inquiry-intake` and
+ `quote-build`
+- **Chain 3, Morning plant pulse** — step 1, feeding `daily-production-report`
+- Feeds `quote-build`, `daily-production-report`, and every reporting skill
+
+Those skills read this dataset rather than the raw sources. If the join is
+wrong, they are wrong in ways that are hard to debug.
+
+**Metric.** Enabling only. It does not move a plant number by itself; measure it
+by whether downstream skills can run.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/join-keys.md` | Before joining — the six keys, their sources of truth, the normalization ladder, date windows by entity, the integrity checks, and the routing and actuals signatures, cell map and backflush check |
+| `reference/mismatch-classes.md` | When classifying join failures — the eight classes, detection and proposed fix for each |
+| `../../shared/contracts/consolidated-dataset.md` | Steps 5 and 8 — the output schema every downstream skill reads |
+| `../../shared/approval-gates.md` | Before applying any fix — what a yes covers, and a blanket yes |
+| `../../shared/computed-figures.md` | Step 7 — the figures block, and reconciling it before writing |
diff --git a/plugins/claude-for-manufacturing/skills/data-consolidate/reference/join-keys.md b/plugins/claude-for-manufacturing/skills/data-consolidate/reference/join-keys.md
new file mode 100644
index 00000000..d5445182
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/data-consolidate/reference/join-keys.md
@@ -0,0 +1,195 @@
+# Join keys and the normalization ladder
+
+Load this before joining anything.
+
+## Why this file exists
+
+A plant does not have one database. It has five to eight systems bought at
+different times by different departments, and the same physical thing carries a
+different identifier in each one. A single part might be:
+
+| Where | How it appears |
+|---|---|
+| ERP item master | `PN-4471-B` |
+| MES production export | `4471B` |
+| Quality inspection export | `4471-B Rev 2` |
+| Maintenance spares list | `Bracket, Upper, 4471` |
+
+All four are the same part. Only the first three are joinable, and none of them
+match as-is.
+
+## The six join keys
+
+These are the identifiers that should be common across systems. Everything the
+consolidated dataset is built around hangs off one of them.
+
+| Join key | Links | Source of truth |
+|---|---|---|
+| Part number | Product ↔ production ↔ quality ↔ purchasing | ERP item master (NetSuite or Infor M3) |
+| Production work order number | Production run ↔ output ↔ quality results ↔ cost | The ERP. In Infor M3 it is the manufacturing order number |
+| Sales order number | Customer commitment ↔ production ↔ shipping | The ERP. In Infor M3 it is the customer order number |
+| Lot / batch number | Material ↔ parts made from it ↔ customers who received them | MES or quality export |
+| Asset ID | Machine ↔ downtime ↔ maintenance history | CMMS connector or maintenance export |
+| Supplier ID / vendor number | Purchase orders ↔ incoming material ↔ supplier quality | The ERP |
+
+**Source of truth decides direction.** When two sides disagree on a key's shape,
+normalize toward the source of truth rather than toward whichever side has more
+rows. The ERP item master is the reference for part numbers even when the MES
+export has ten times the volume.
+
+### The work order name collision
+
+Maintenance systems also call their repair tickets "work orders." A production
+work order and a maintenance work order are different records with different
+numbering, and joining one to the other produces nonsense.
+
+Always disambiguate in output and in column naming: **production work order** and
+**maintenance work order**, never bare "work order" or "WO."
+
+## The normalization ladder
+
+Apply in this order. Each rung is more aggressive than the last, so stopping
+early is safer than going further than needed.
+
+| Rung | Transformation | Notes |
+|---|---|---|
+| 1 | Trim leading and trailing whitespace | Manual exports carry trailing spaces constantly |
+| 2 | Normalize case | Fold to a single case for comparison only |
+| 3 | Normalize punctuation | `PN-4471-B` / `PN_4471_B` / `PN4471B` collapse to one comparison form. A lost part prefix (`4471B` against `PN-4471-B`) collapses too, **only where exactly one part on the `parts` tab matches once its prefix is dropped**. Name the prefix in the log. Where two or more parts would match (`PN-4471-B` and `AX-4471-B`), nothing is matched by this rung: the record is reported with every candidate, and the plant says which |
+| 4 | Restore lost leading zeros | `451` matches `00451` only if a zero-padded variant exists on the other side. Test for it; do not pad blindly |
+| 5 | Strip revision suffix | `4471-B` matches `4471-B Rev 2`. The revision is extra information, not a different part |
+
+**Rungs 1, 2 and 3 are safe to propose as automatic.** Rungs 4 and 5 change
+meaning and always carry their own proposal, because a stripped revision or an
+assumed zero can be wrong.
+
+### Two hard rules
+
+**Compare on the normalized form; store and display the original.** The
+consolidated dataset carries the source system's own identifier verbatim
+alongside the normalized key. A plant person searching for `PN-4471-B` in their
+own vocabulary must find it. Never overwrite a source identifier with a
+normalized one.
+
+**Every normalization applied is logged and reportable.** The data quality report
+names each rule that fired, how many records it touched, and an example of the
+before and after. A silent normalization is indistinguishable from a bug, and the
+first time a total looks wrong this log is the only way to tell them apart.
+
+### Revision data is preserved, never discarded
+
+When rung 5 fires, the revision that was stripped goes into its own column and
+the report states that revision data existed on one side only. Stripping it to
+make the join work is correct; losing it is not.
+
+## Date windows by entity
+
+When the user narrows the join to the overlap, the window does not apply to
+every tab alike. Three kinds of record, three rules:
+
+| Kind | Tabs | What the window does |
+|---|---|---|
+| **Activity** | `production_output`, `downtime_events`, `inspection_results`, `plan`, `operation_actuals` | Scoped to the overlap. A row outside it is Class 7 |
+| **Open commitments** | Open `sales_orders` lines, open `production_work_orders` | **Kept by status, whatever their dates.** An open order is in scope until it closes. A sales order line that carries only a promised date and no order date is never out of window for lacking one |
+| **Reference history** | `purchase_orders` and their receipts, `maintenance_work_orders`, `ncrs`, `lots` | Kept for a lookback before the window start: the Plant context's lookback if one is set, otherwise **180 days, stated as a default, not plant-set**. Labelled as history in the report and never counted in the window's totals |
+
+Closed commitments (a shipped sales order, a closed work order) are activity:
+scoped by their own close or ship date. Never class a record 7 because the
+narrowing removed the history that explains it. A material receipt from
+before the window is how a heat is traced to the work orders it fed, and a
+repair from June is how a breakdown is read in August.
+
+## Integrity checks
+
+Run in code, on every row, after the join. A failure is a named value in the
+row's `integrity_flags`, per `../../../shared/contracts/consolidated-dataset.md`.
+None is a mismatch class, none is fixed silently, and each is counted in the
+figures block and reported with example rows.
+
+| Flag | Tab | Test | What happens |
+|---|---|---|---|
+| `sign_convention` | `sales_orders`, fulfilment rows | Every line of that record type from that source is negative. NetSuite writes sales order and item fulfilment line quantities as negative: stock leaving. Infor M3 writes them positive, so M3 rows never raise it | `qty` is the absolute value; the signed value stays in `qty_verbatim`; the rule is stated in the figures block, once per source. A demand total is never negative |
+| `mixed_sign` | the same | Some lines of that record type are negative and some positive | No sign is changed and no total is computed for that record type until the plant says what the signs mean |
+| `end_before_start` | `downtime_events` | `ended_at` is earlier than `started_at` | The stated duration is not trusted: the row's minutes are held out of every minutes total and the minutes ranking, the stoppage still counts as an event, and the exclusion is stated with the row |
+| `duration_mismatch` | `downtime_events` | Stated duration differs from end minus start by more than a minute | Both figures shown. Minutes held out as above, until the plant says which is right |
+| `ncr_part_differs` | `ncrs` | The NCR's part is not the part the ERP holds for the production work order it cites | The NCR's part label is not trusted for same-part history. Show both parts |
+| `ncr_dated_before_wo` | `ncrs` | The NCR is dated before the first output recorded for the work order it cites | Show both dates. The NCR is not used to date the defect |
+| `future_timestamp` | any | A created, last-modified or transaction date after the run time | The source's `as_of` is untrusted (`data-consolidate` Step 2). Due, promised and delivery dates are excluded from this test |
+| `units_conflict` | any | Two units for one key, as in Step 5 | No total across them, no conversion |
+
+A row can carry more than one flag.
+
+## Plant vocabulary
+
+`onboarding` captures what this plant calls its join keys and its organizational
+units — job versus work order versus traveler, cell versus line versus work
+center. Every output uses the plant's words, not these canonical ones.
+
+Read the plant's words from the `## Plant context` block's `Vocabulary` line for
+the relevant site. If no profile exists, use these canonical names, say that they
+are canonical rather than the plant's own, and ask once per session rather than
+re-asking per output.
+
+## Routings and operation actuals
+
+Two inputs `quote-build` derives machine hours from. Neither is keyed on a
+seventh identifier: a routing joins on part, an actuals row on production work
+order and part. Work center is carried as a pair like a key, but it is mapped,
+not joined.
+
+### Recognizing the files
+
+By header signature, case-insensitive, punctuation folded the way rung 3 folds
+a key. Column names vary by ERP; the meaning does not.
+
+| File | Must carry | Usually also carries |
+|---|---|---|
+| Routing | a part number; an operation sequence (`op_seq`, `operation`, `oper no`); a work center or resource; a setup time; a run time per unit | revision, operation description, a time unit column, an as-of or effective date, an outside-processing flag |
+| Operation actuals | a production work order; an operation sequence; a work center; hours booked (setup and run, or one lumped figure); a quantity completed | part number, closed date, unit of measure |
+
+A file carrying a work order and hours but no operation sequence is a work
+order cost file, not operation actuals. Name it as such and do not load it into
+`operation_actuals`.
+
+### Time units
+
+Read the unit from the header (`setup_hours`, `run_min_per_unit`) or from a
+unit column. **Never from the size of the number** — 0.12 is a plausible run
+time in hours and in minutes. Where no unit is declared, the unit is
+`undeclared` and the row is flagged.
+
+Where the routing and the actuals for the same part and operation carry
+different units, flag both rows naming both units. The dataset holds each value
+as its source wrote it. Minutes to hours is an exact factor, and it is still
+not applied to the dataset: the flag is there so a person sees two units, and a
+silently harmonized column hides that the sources disagreed.
+
+### Work center to cell
+
+Read the `Machine classes` table under `### Machining data` in the
+`## Plant context` block. Its `Work centers` column lists the work centers in
+each machine class, and `Cell` names the cell. Fill `cell` on both tabs from
+it. A work center in no row is listed in the report with `cell` null. Without
+the table at all, every `cell` is null and the report says the map is missing
+from the Plant context, once.
+
+### The backflush check
+
+Run in code, over every actuals row, after the join:
+
+1. **Against the routing.** Put actual run hours ÷ quantity completed and the
+ routing's run standard in the same unit for this comparison only. Within 1%
+ of each other: `probable_standard`.
+2. **Against each other.** For each part and operation with two or more closed
+ work orders, compare run hours per unit. Two or more within about 1% of each
+ other: every one of them is `probable_standard`.
+
+`confidence_reason` carries the figures — which work orders, the per-unit
+values, the percentage apart. Everything else is `recorded`. A lumped figure
+with no setup and run split cannot be checked against a run standard; say so
+in `confidence_reason` and leave it `recorded`.
+
+**Probable, not proven.** The flag says the numbers look posted rather than
+measured. The plant may know otherwise, and the report says what would settle
+it: the operation's labor tickets, or the ERP's backflush setting for that
+work center.
diff --git a/plugins/claude-for-manufacturing/skills/data-consolidate/reference/mismatch-classes.md b/plugins/claude-for-manufacturing/skills/data-consolidate/reference/mismatch-classes.md
new file mode 100644
index 00000000..dc88eb1b
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/data-consolidate/reference/mismatch-classes.md
@@ -0,0 +1,208 @@
+# The eight mismatch classes
+
+Load this when classifying join failures.
+
+When two datasets are joined on a key, some rows find no partner. That is not a
+nuisance to be counted — it is usually a real business problem in disguise. The
+skill classifies every mismatch into one of the eight classes below and reports
+each class separately, with counts **and example rows**.
+
+**A count on its own is not a finding.** "312 mismatches" tells a plant person
+nothing they can act on. "298 of them are one export covering three days the
+other does not" tells them to re-run tomorrow.
+
+---
+
+## Check the date window first
+
+**Class 7 is checked before any other class is reported.** A date-window
+mismatch manufactures apparent mismatches across every key at once, and it
+explains most large mismatch counts. Reporting format drift and orphan records
+on top of an unnoticed window gap sends someone chasing problems that do not
+exist.
+
+Order of work: window overlap, then key shape, then genuine one-sided records.
+
+---
+
+## Class 1 — Orphan record
+
+**What it is.** A record references a key that does not exist on the other side
+at all. A production record reports output against production work order
+`WO-88213`, and no such work order exists in NetSuite.
+
+**What it means.** One of three things, and they are very different: somebody ran
+an unauthorized job, a work order was deleted after the fact, or the two exports
+are from different dates.
+
+**Detection.** Key is well-formed and no normalization rung produces a match.
+
+**Proposed fix.** None automatic — this is a question, not a formatting problem.
+Report the orphans with their quantities and dates, and state which of the three
+explanations the surrounding evidence supports. Check the date window before
+concluding anything.
+
+**On routings: routing with no matching part.** A routing whose part number no
+normalization rung matches to the item master. Either the part was renamed,
+retired, or never set up in the item master. Report it by that name, with its
+operations; no automatic fix. It is never used to quote a part it merely looks
+like.
+
+---
+
+## Class 2 — Format drift
+
+**What it is.** `PN-4471-B` versus `4471B` versus `4471_B`. Same part, different
+punctuation.
+
+**What it means.** Nothing about the business. It is the most common class by
+volume and the least interesting.
+
+**Detection.** Normalization ladder rungs 1–3 produce a match.
+
+**Proposed fix.** Apply the punctuation and case normalization, with the
+normalization shown.
+
+---
+
+## Class 3 — Leading-zero loss
+
+**What it is.** `00451` became `451` because a system exported to CSV and a
+spreadsheet stripped the zeros on open.
+
+**What it means.** A tooling artifact, extremely common, and not a data entry
+problem.
+
+**Detection.** Rung 4 — test whether a zero-padded variant of the short key
+exists on the other side. Do not pad blindly; only claim the class when the
+padded partner is actually present.
+
+**Proposed fix.** Restore the padding to the source-of-truth width. Report the
+width used.
+
+---
+
+## Class 4 — Revision suffix mismatch
+
+**What it is.** `4471-B` versus `4471-B Rev 2`. The part is the same; the
+revision is additional information carried on one side only.
+
+**What it means.** One system tracks revision on the identifier and the other
+does not.
+
+**Detection.** Rung 5 — a match appears once the revision suffix is stripped.
+
+**Proposed fix.** Strip and match, preserve the stripped revision in its own
+column, and report that revision data existed on one side only. Never discard it.
+
+**On routings: routing revision mismatch — no automatic fix.** A routing
+written for revision 1, read against a drawing at revision 2, matches once the
+suffix is stripped, and that match is exactly the mistake. A routing is the
+operation list for one revision; a later revision may have tightened a
+tolerance that adds an operation. Report it as a *routing revision mismatch*:
+which revision the routing is for, which revision is being quoted or is
+current, and what the drawing's revision history says changed where it is
+available. The routing stays on the `routings` tab, marked `revision_mismatch`,
+and `quote-build` shows it as superseded, never prices from it. A routing with
+no revision at all is not a mismatch but it is not a match either: report it
+as revision-unknown, never assumed current. `quote-build` may use it only with
+that label on every line it touches.
+
+---
+
+## Class 5 — Case and whitespace
+
+**What it is.** Trailing spaces and inconsistent capitalization, usually from a
+manual export or a hand-maintained sheet.
+
+**Detection.** Rungs 1–2 produce a match.
+
+**Proposed fix.** Trim and case-fold for comparison.
+
+---
+
+## Class 6 — Genuine one-sided record
+
+**What it is.** A part in the ERP that has never been produced. A machine in
+the CMMS that appears in no production record. A supplier with no purchase orders
+in the window.
+
+**What it means.** Usually nothing wrong at all. An item master legitimately
+contains parts that are not currently running.
+
+**Detection.** Key is well-formed, no normalization produces a match, and the
+absence is consistent with the record's own type and dates.
+
+**Proposed fix.** None. **Report, do not alarm.** Distinguish this class clearly
+from Class 1, because an orphan is a problem and a one-sided record generally is
+not, and conflating them makes the whole report look like noise.
+
+**Unless another source contradicts it.** A closed production work order with
+no MES output is one-sided; the same work order cited on an NCR, on inspection
+rows or by a lot was plainly run, and its parts were plainly made. Check for
+that evidence before calling a record nothing wrong. Where it exists, the
+record keeps class 6 and carries `contradicted_by`, naming the source and the
+record (`quality_ncrs.csv NCR-2026-0141`). Consumers route it as an exception,
+*"one-sided, contradicted by NCR-2026-0141"*, never to "Checked, nothing
+wrong". Only evidence of the missing activity itself contradicts: downtime or
+maintenance on a machine with no production does not.
+
+---
+
+## Class 7 — Date-window mismatch
+
+**What it is.** The production export covers 1–31 August; the ERP pull covers
+1 August to 3 September. Records in the non-overlapping days have no possible
+partner.
+
+**What it means.** A coverage problem, not a data problem.
+
+**Detection.** Compare each source's coverage window before joining. Any
+**activity** record whose date falls outside the intersection is this class,
+not any other. Open commitments and reference history are not windowed the
+same way, and are never this class for falling outside it: see
+`join-keys.md`, *Date windows by entity*.
+
+**Proposed fix.** Two options, and the user chooses: narrow the join to the
+overlapping window, or wait for the next export and re-run. Report the
+overlapping window explicitly either way, because every total below it is scoped
+to that window.
+
+**Check this first.** Per `../../../shared/absent-is-not-zero.md`, sources whose
+windows do not overlap meaningfully are not joined at all.
+
+---
+
+## Class 8 — Duplicate key
+
+**What it is.** The same production work order appearing twice with different
+quantities. The same lot number on two different parts.
+
+**What it means.** Either a genuine duplicate that needs deleting, a corrected
+record that was appended rather than replaced, or two systems using the same
+number space for different things.
+
+**Detection.** Key appears more than once on a side where it should be unique.
+**Unique means unique at the tab's grain**, per the contract: on
+`production_output` that is production work order, shift and production day.
+The same work order on two shifts is two legitimate rows, not a duplicate.
+Count a duplicate by the rows that collide at the grain, from the query: if
+WO-88201 has three rows, and two of them (509 and 480 good, both on
+the 07:00 shift) are the duplicate; the 95 on the 23:00 shift is its own shift.
+Say both: how many rows the key has, and how many collide.
+
+**Proposed fix.** **None automatic, ever. Never silently pick one.** Surface both
+rows with their full values and let the user say which is real. Summing them and
+picking the larger are both wrong, and both are invisible once done.
+
+---
+
+## Reporting shape
+
+Every class that fired gets its own block in the data quality report:
+
+- The class name in plain language, not the class number
+- How many records it affects, and how many records would join if the fix were applied
+- Two or three real example rows, before and after
+- The proposed correction, or an explicit statement that this class has no automatic fix
+- What it means for the plant, in one line
diff --git a/plugins/claude-for-manufacturing/skills/design-space-explore/SKILL.md b/plugins/claude-for-manufacturing/skills/design-space-explore/SKILL.md
new file mode 100644
index 00000000..e0231ce3
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/design-space-explore/SKILL.md
@@ -0,0 +1,234 @@
+---
+name: design-space-explore
+description: "Generates a batch of CAD variants directly in Autodesk Fusion by applying changed parameters to an engineer's existing model, never designing from scratch and never overwriting the base. Checks first whether the parameters the engineer wants to vary actually drive the model's geometry, and stops rather than generating garbage if they don't. Confirms the variant count with the engineer before generating anything. Captures mass, volume, bounding box and every other model-computed property per variant, and hands the batch off in the shape trade-study-report consumes — it does not run analysis itself. Use when someone says \"explore the design space,\" \"generate variants,\" \"try different wall thicknesses,\" \"run a parameter sweep,\" or \"vary this and see what happens.\""
+compatibility: "Requires Autodesk Fusion (desktop, with the document open). There is no other CAD backend and no file-only path — without Fusion connected, the skill reports exactly what is needed rather than running degraded. Never overwrites the base model."
+---
+
+# Design Space Explore
+
+An engineering team designing a part rarely has one answer. They have a
+**design space** — a range of possible designs bounded by what they're
+allowed to vary (wall thickness, rib count, hole pattern, material) and what
+the part must satisfy (envelope, mass, load, cost, manufacturability).
+Modeling one design at a time, by hand, means evaluating three to five
+options and picking the best of a small set. This skill generates many at
+once, directly in the CAD tool the engineer already has open.
+
+**It does not design from scratch.** It takes a model the engineer already
+has and generates variants of it — that constraint is what makes the output
+trustworthy and reviewable rather than a pile of new geometry nobody asked
+for.
+
+**It does not run analysis.** It produces the variants and the manifest
+describing them, so an analysis tool or a person evaluates each one and
+returns results, which `trade-study-report` then consumes.
+
+**Quick start**
+
+```
+→ Connect: Fusion, with the base model open in the desktop app
+→ Read the model's parameter set. Not driving what was asked? Stop and say so
+→ Confirm the variant plan — parameters, ranges, step, and the resulting count
+→ Generate. Verify each regenerated; failures at range extremes are expected
+→ Capture per-variant properties: parameter values, mass, volume, bounding box
+→ Produce the manifest in the shape trade-study-report consumes
+→ Never touch the base model. Variants are new documents, clearly named
+```
+
+---
+
+## Inputs
+
+| Input | Source | Form |
+|---|---|---|
+| The base model | Fusion (open desktop document) | Live CAD connection |
+| Parameters to vary, with ranges | Engineer, in conversation | Conversation |
+| Constraints | Engineer, in conversation, and the trade study definition | Conversation / document |
+| Trade study targets and criteria | `trade-study-report` definition, or a document in M365 | Document |
+| Prior variants and results | M365 | Documents |
+
+---
+
+## Workflow
+
+### Step 1 — Connect to the CAD environment
+
+One implementation, Fusion, behind one interface. Read
+`reference/cad-adapter.md` for the interface and the connector behaviors that
+break a naive script.
+
+- **Fusion** — desktop only, and acts on the open document via command-based
+ operations on live geometry. There is no server-side fetch path; if the
+ document is not open on the user's machine, there is nothing to act on.
+
+Record the backend as `cad_backend` on the manifest, so a second CAD
+connector drops in later without a contract change.
+
+### Step 2 — Read the parameter set, and check what actually drives it
+
+**This check comes first, before anything else, and it is the single
+biggest practical risk in the skill.** A parametric model is built from
+driving dimensions — change `wall_thickness` and the geometry regenerates.
+Many real production models are not properly parametric, and automated
+variant generation on one that isn't will not work.
+
+Read the model's parameters and report which ones are actually driving
+geometry. **Where a parameter the engineer wants to vary is not a driving
+dimension, stop and say so** rather than generating variants that silently
+ignore it. Read `reference/parametric-check.md`.
+
+### Step 3 — Confirm the variant plan
+
+Before generating anything: which parameters, which ranges, which step or
+sampling strategy, and **the resulting variant count, stated plainly.**
+
+**Generating 200 variants nobody asked for is the obvious failure.** Five
+parameters at five values each is 3,125 combinations — show the count and
+get an explicit yes before the batch runs. Read
+`reference/variant-generation.md`.
+
+### Step 4 — Generate, and verify each one
+
+Apply each confirmed parameter set to the existing model. After each,
+verify the model regenerated without error. The open, save-as-new, apply and
+untouched-check sequence is `reference/adapt-prior-model.md` — the same
+mechanism `rfq-to-quote` uses to adapt a prior part's model.
+
+**A failed regeneration is expected, not a bug** — geometry that
+self-intersects or a feature that fails to rebuild at a range extreme
+happens routinely and does not abort the batch. Report it per variant, with
+what failed.
+
+### Step 5 — Capture per-variant properties
+
+Parameter values, mass, volume, bounding box, and any other property the
+model computed.
+
+**A property the model could not compute is absent, not zero.** A variant
+with no mass reading is unmeasured, not massless, and reporting it as zero
+would win a lower-is-better weight criterion outright.
+
+### Step 6 — Produce the handoff manifest
+
+One row per variant — its ID, its parameter values, its computed
+properties, its status, and its document reference — per
+`../../shared/contracts/variant-manifest.md`, in exactly the shape
+`trade-study-report` consumes.
+
+**A failed or skipped variant stays in the manifest, never dropped.** A
+dropped row is indistinguishable from a variant nobody considered, and the
+trade study would then report a design space narrower than the one actually
+explored.
+
+### Step 7 — Never touch the base model
+
+Variants are new documents, or clearly-named configurations of the base —
+never a modification in place. State what was created, and where.
+
+---
+
+## Approval gates
+
+**Nothing generates without the variant plan being confirmed** — parameters,
+ranges, and the resulting count, agreed before the batch runs. This is the
+skill's one real chance to prevent a runaway job; a live CAD connection
+generates 3,000 low-value variants exactly as easily as 30 good ones.
+
+**The base model is never modified.** Every variant is a new document or a
+clearly-named configuration, so there is nothing to approve or roll back on
+the original.
+
+This skill does not run analysis and does not decide anything about the
+trade study — it hands the manifest off. `trade-study-report` and the
+engineer own what happens next.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The generated variants**, in the CAD system, consistently named and
+traceable back to their parameter set.
+
+**The variant manifest** — per
+`../../shared/contracts/variant-manifest.md`: the parameters varied, the
+parametric check result, and per variant its ID, parameter values, computed
+properties, status, and document reference.
+
+**The generation report** — what succeeded, what failed to regenerate and
+why, what was skipped and why. Rendered in the house artifact style
+(`../../shared/artifact-style.md`) when there is enough of a batch to be
+worth referring back to.
+
+**The handoff package** — the manifest plus the generation report, ready for
+an analysis tool or a person to evaluate and return results into, which
+`trade-study-report` then consumes.
+
+---
+
+## Edge cases and failure modes
+
+- **The base model isn't properly parametric** — the most likely real-world
+ blocker. Detect and report before generating anything.
+- **Fusion isn't open, or the customer uses Fusion's web client** — the
+ connector cannot work at all. Detect and say so plainly; there is no
+ server-side fetch path.
+- **The connector replays an earlier script** — geometry nobody asked for
+ appears, or read-only calls fail with "cannot modify." Stop and ask the user
+ to restart Fusion; see `reference/cad-adapter.md`.
+- **Geometry fails to regenerate at a range extreme** — expected. Report it
+ per variant; do not abort the batch.
+- **The parameter combination count explodes** — five parameters at five
+ values is 3,125. Always show the count and confirm before generating.
+- **The model has external references or in-context relationships** —
+ variant generation can break them. Detect and warn before generating.
+- **CAD operations are slow** — this is a long-running batch, not a single
+ blocking call. Design for progress reporting, not silence until it
+ finishes.
+
+---
+
+## Degradation
+
+**One CAD tool, on one platform.** The skill works for customers running
+Fusion on the desktop, with no cloud path. There is no fallback CAD backend —
+no connector currently reaches SolidWorks, Creo, NX or Inventor, so a customer
+on any of those has no path to this skill at all. State that plainly rather
+than letting a prospect discover it for the first time in a demo. Keep the
+CAD-adapter layer regardless, so a CAD connector appearing later drops in
+without a redesign.
+
+**If Fusion is not available** — the skill cannot generate variants and says
+so, naming exactly what is needed: Fusion desktop with the document open.
+`trade-study-report` is unaffected — its manifest can be hand-authored by an
+engineer with no CAD backend at all, per its own contract.
+
+---
+
+## Chain position
+
+Not part of a named chain, but feeds `trade-study-report` directly — the
+same producer-consumer relationship `breakdown-diagnosis` has with
+`daily-production-report` in Chain 4.
+
+**Metric.** Configurations evaluated per program; design cycle time.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/cad-adapter.md` | Step 1 — the backend behind the interface, and the connector behaviors to read before the first call |
+| `reference/parametric-check.md` | Step 2 — always, before generating anything |
+| `reference/variant-generation.md` | Steps 3 to 7 — confirming the plan, generating, and the manifest |
+| `reference/adapt-prior-model.md` | Steps 4 and 7 — open the base, save as new, apply, confirm the base is untouched |
+| `../../shared/contracts/variant-manifest.md` | On emit — the exact shape `trade-study-report` consumes |
diff --git a/plugins/claude-for-manufacturing/skills/design-space-explore/reference/adapt-prior-model.md b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/adapt-prior-model.md
new file mode 100644
index 00000000..6a6af83c
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/adapt-prior-model.md
@@ -0,0 +1,146 @@
+# Open a prior model, apply parameters, save as new
+
+**One mechanism, two callers.** Both start from a model that already exists,
+change some of its driving parameters, and keep the result in a new document.
+Neither ever writes to the model they started from.
+
+- **`design-space-explore`**, step 4 — once per variant, from the engineer's
+ base model. The variant plan says which parameters and which values.
+- **`rfq-to-quote`, step 7, path B** — once per line, from a *different* prior
+ part's model that the customer or the estimator named as the starting point.
+ The changed parameters come from the customer's drawing.
+
+Everything here runs through the adapter surface in `cad-adapter.md`, and
+every connector behavior listed there applies: `run(context)`, `print()` as the
+only output, `readOnly: true` on every inspection call, each call under about
+25 seconds, the Design workspace active.
+
+---
+
+## The rule this exists to keep
+
+**The prior model is never overwritten.** Not saved over, not edited in place
+and saved, not "updated to the new revision." It is the thing the engineer, or
+the next quote, starts from, and an accidental edit to it is not recoverable by
+re-running anything: the input the next run needs would already be gone.
+
+A request to edit the prior model in place, *"it's quicker, just resave it"*,
+is declined in one line, and the new-document route is offered instead. It
+takes one extra call.
+
+---
+
+## The sequence
+
+### 1. Open the prior model, and read it without touching it
+
+Fusion has no file-only path: **the prior model must be open in the desktop
+app.** Ask the user to open it. Opening it from the hub by script is not
+verified on this connector; do not rely on it.
+
+Read-only, record:
+
+- its name, its document reference and its version number
+- its parameters, and which of them drive geometry (`parametric-check.md`)
+- its bodies and sketches, by name
+- **whether it has unsaved changes.** If it does, stop. Someone has work open
+ in it, and a save-as would carry that work into the new document. Ask the
+ user to save or discard it themselves.
+
+### 2. Save as a new document, before any parameter changes
+
+Save the open model under the new name first — the caller's naming
+convention, below — and **confirm, read-only, that the active document is now
+the new one**, by name, before the first write. From here on every write lands
+in the new document. If the active document is still the prior model, stop.
+
+| Caller | New document name |
+|---|---|
+| `design-space-explore` | The variant's ID, traceable to its parameter set (`variant-generation.md`) |
+| `rfq-to-quote` path B | `<inquiry>_L<line>_<part>_R<rev>`, the same as a model built from a drawing |
+
+`design-space-explore` may instead use a clearly-named configuration of the
+base where the engineer asked for one. Path B always uses a new document.
+
+### 3. Integrity check, before
+
+List bodies and sketches in the new document, read-only. **They must match the
+prior model's list from step 1, name for name.** A new document that is a copy
+is not empty, so "a fresh document lists none" does not apply here; "it lists
+exactly what the prior model held" does. Anything else is foreign geometry: the
+add-in is replaying an earlier script. Stop, and ask the user to restart
+Fusion.
+
+### 4. Apply the parameters, and verify the regeneration
+
+Apply each changed parameter. After the set, confirm the model regenerated
+with no failed feature. A failure is reported with the feature that failed and
+why: for `design-space-explore` the row is `regeneration_failed` and the batch
+goes on; for path B the line falls back to C2 (below).
+
+### 5. Read back
+
+Bodies, bounding box, volume, and whatever else the caller records. For path
+B, check each changed dimension against the drawing value it came from.
+
+### 6. Integrity check, after
+
+Same bodies and sketches by name, plus only what this step created. Anything
+else is foreign geometry and the step fails, with both lists recorded.
+
+### 7. Confirm the prior model is untouched
+
+Read-only: the prior model's version number is the one recorded at step 1.
+**If it moved, stop and tell the user at once**, naming the model and both
+version numbers. Restoring an earlier version is the user's call, made in
+Fusion, never this skill's.
+
+### 8. Record
+
+Per run: the prior model's reference and version, the new document's
+reference, each parameter as *from → to*, the regeneration result, both
+integrity lists, and the untouched check. `design-space-explore` writes these
+into the variant manifest (`base_model`, per-variant `document_ref`); path B
+writes them into the geometry estimate (`base_model_ref`, `document_ref`,
+`document_integrity`).
+
+---
+
+## Path B only: what the parameters may change
+
+**The drawing is still the geometry.** The prior model supplies a shape that
+is already modelled; every dimension and every tolerance on the geometry
+estimate is read from the customer's drawing and cites its view and zone,
+exactly as for a model built from the drawing. A tolerance is never carried
+over from the prior part.
+
+Path B fits a line only where **every difference between the prior part and
+the drawing is a driving parameter of the prior model.** Compare the drawing
+with the prior model's parameters first, and list each change as *parameter:
+prior value → drawing value, drawing view and zone*. Where a difference is a
+feature the prior model does not have, or one it has and the drawing does not,
+or a dimension no driving parameter controls, path B does not fit that line.
+
+**When path B does not fit, the line falls back to C2**: built from the drawing
+in a fresh new document, and said in one line — *"Path B: <prior model>
+<reason>; built from the drawing as C2."* The reasons:
+
+- the prior model is not on file, cannot be found, or the user cannot open it
+- it has unsaved changes the user has not resolved
+- a change on the drawing is not a driving parameter of the prior model
+- the regeneration failed
+- the read-back does not match the drawing
+
+The geometry estimate is then emitted as `geometry_path: C2`, `origin:
+built_from_drawing`, `base_model_ref: null`, with the fallback and its reason
+as the first entry in `questions_for_estimator` so it is seen at Gate 3.
+
+**No Fusion at all** is not a path B fallback; it is the same degradation as
+every path: the hand-entered feature list from the drawing, or no design step.
+
+## What has and has not run
+
+The variant mechanism above is `design-space-explore`'s, unchanged. **The
+open, save-as-new and untouched-check calls have not been run through the
+connector in this repo, for either caller.** Say so where a run depends on
+them, and do not report the prior model as untouched without the step 7 read.
diff --git a/plugins/claude-for-manufacturing/skills/design-space-explore/reference/cad-adapter.md b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/cad-adapter.md
new file mode 100644
index 00000000..8228f297
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/cad-adapter.md
@@ -0,0 +1,202 @@
+# One backend, one interface
+
+Fusion is the CAD backend this plugin reaches today. Nothing downstream of
+this file should have to know that: build to the adapter surface below, not to
+Fusion's command set directly, so a second CAD connector drops in later as an
+implementation rather than a rewrite.
+
+Three callers use this file:
+
+- **`design-space-explore`** — variants of an existing model. It reads
+ parameters, applies parameter sets, reads properties and creates variant
+ documents. **It never designs from scratch.**
+- **`rfq-to-quote`, step 7** — the design step. Path C2 (a drawing) and path A
+ (text specs) build an estimating model in a **new** document with the
+ create-from-scratch calls below. Path B adapts a prior part's model with the
+ same open, apply and save-as-new mechanism `design-space-explore` uses —
+ `adapt-prior-model.md`. Path C1 imports a customer's STEP file, which is
+ **unverified**.
+- **`quote-build`, the CAM path** — setups, operations, toolpaths and machining
+ time on the model `rfq-to-quote` built and the estimator confirmed.
+
+---
+
+## Fusion — desktop, live geometry
+
+Real-time modeling and command-based operations against **whatever design
+is currently open in the desktop app.**
+
+- **Desktop app only.** Does not work with Fusion's web client at all.
+- **No server-side fetch path.** The skill can only act on a document
+ already open on the user's machine. There is no way to reach a Fusion
+ document that isn't open in front of the person running this.
+- If the document is not open, **say so and stop** — this is not a
+ degradation to work around, it's a precondition that isn't met yet.
+
+There is no fallback CAD backend. No connector currently reaches SolidWorks,
+Creo, NX or Inventor; a plant on any of those runs the paths that need no CAD.
+
+---
+
+## What every backend implementation has to expose
+
+### Variant operations — `design-space-explore`
+
+| Operation | What it does |
+|---|---|
+| Read parameters | List the model's dimensions and which are driving geometry |
+| Apply a parameter set | Regenerate the model against one set of values |
+| Read computed properties | Mass, volume, bounding box, whatever else the tool exposes |
+| Create a variant document | A new document or named configuration, never the base |
+
+Everything in `parametric-check.md` and `variant-generation.md` is written
+against this surface.
+
+### Open, apply, save as new — `design-space-explore` and `rfq-to-quote` path B
+
+The sequence is `adapt-prior-model.md`. The calls it needs:
+
+| Operation | What it does | Notes |
+|---|---|---|
+| Read the open document | Name, document reference, version number, unsaved changes | Read-only. The user opens the prior model; opening it from the hub by script is not verified |
+| Save as new document | Copy the open model to a new name and make the copy the active document | **Before** any parameter change. Read the active document's name back before the first write |
+| Apply a parameter set | As above | In the new document only |
+| Read the prior model's version | Confirm it did not move | Read-only, after the run. A moved version stops the run |
+
+**Not run through the connector in this repo.** The prior model is never
+saved, never edited in place, and never the active document during a write.
+
+### STEP import — `rfq-to-quote` path C1 (unverified)
+
+| Operation | What it does | Notes |
+|---|---|---|
+| Import STEP to a new document | The customer's STEP file as bodies in a new document, named like any estimating model | **Unverified.** Never run through the connector. The file has to be on the machine running Fusion |
+| Read bodies and faces | Bounding box, volume, planar and cylindrical faces with their sizes | Read-only. A STEP file carries bodies, not a feature history: holes and pockets are recognised from faces, and each one is a reading to confirm at Gate 3 |
+
+**Nothing is generated on path C1** — no sketch, no extrude, no change to the
+imported bodies. The import is read. A STEP file carries no tolerances this
+path reads; every tolerance comes from a drawing or the customer's text, or
+goes on `unreadables`. Where the import fails, or Fusion is not connected,
+`rfq-to-quote` reads the STEP file as text without CAD, labelled unverified,
+or takes a hand-entered feature list; see `../../rfq-to-quote/reference/design-step.md`.
+
+### Create-from-scratch operations — `rfq-to-quote` step 7
+
+Always in a **new document the step creates itself**, named for the inquiry,
+line and revision (`<inquiry>_L<line>_<part>_R<rev>`). **Even when the open
+document is empty** — it is the user's document, and a replayed script has
+been seen to land geometry in an "empty" one. Never build in a document that
+holds anything else, and never in a customer's file. Report the new document's
+name.
+
+| Operation | What it does | Notes |
+|---|---|---|
+| Create sketch | A sketch on a named plane or face | Dimensions from the drawing, each with its view and zone |
+| Extrude | Profile to a distance, new body or join | Stock and the main prismatic form |
+| Hole / cut | Through, blind or counterbored, by extrude-cut or the hole feature | The bore; a pocket |
+| Fillet | Edge set and radius | Read edges back to confirm the right ones took it |
+| Chamfer | Edge set and distance | A "break all edges" note is a chamfer set, cited to the note |
+| Read back | Bodies, bounding box, volume | Checked against a hand calculation from the drawing |
+
+Prismatic features are verified this way, from a drawing. Anything else —
+threads, lofts, sheet metal — is unverified; build it if it works, and say it
+was not verified. Path A uses the same calls with dimensions read from text;
+that has not been run.
+
+### CAM operations — `quote-build` CAM path
+
+| Operation | What it does | Notes |
+|---|---|---|
+| Create setup | Machine class, stock, work coordinate system | One per `setups` row of the geometry estimate. Stock-to-leave set explicitly |
+| Create operation | Strategy, tool, geometry selection, feeds | In `op_seq` order — there is no reorder |
+| `generateToolpath` | Start generation | Poll; do not wait on its return |
+| Read toolpath | Points along the path | For the geometry check |
+| `getMachiningTime` | Cycle time per operation | Ignores the tool-change time it is given; add tool changes yourself |
+
+---
+
+## Connector behaviors that break a naive script
+
+Observed on the live Fusion connector (`fusion_mcp_read` and
+`fusion_mcp_execute`, script feature type). Each one has produced
+a wrong answer or a lost call. **Read these before the first call.**
+
+- **A script must define `run(context)`.** Top-level code fails. **Return
+ values are discarded; `print()` is the only output channel**, so every value
+ you need back is printed. **The tool calls `run()` itself: a script that also
+ calls `run()` at the bottom executes twice**, and a write runs twice. Define
+ it; never call it.
+- **There is no read command for parameters, regeneration health or physical
+ properties.** Every one is a `readOnly: true` script: the parametric check
+ reads `userParameters` and what drives each feature; mass, volume and
+ bounding box come from the body's `physicalProperties`. **The regeneration
+ test is each timeline item's `healthState`**: any item not healthy after a
+ parameter change is a failed variant, recorded as such, never measured.
+- **`readOnly: true` is enforced server-side.** Use it on every inspection
+ call — listing bodies, reading parameters, reading a toolpath.
+- **A 60-second device timeout means the call was not delivered**, not that it
+ ran silently. Keep each call under about 25 seconds and split long work
+ across calls. Poll toolpath generation across calls.
+- **The add-in can retain an earlier script and append it to every later
+ call until Fusion restarts.** The symptom is geometry nobody asked for on a
+ write, and read-only calls failing with "cannot modify." There is no fix from
+ the script side: **stop, and ask the user to restart Fusion.**
+- **The wrapper crashes when the active product is CAM.** Make every call
+ with the Design workspace active and switch to Manufacture inside the
+ script. After a crash, workspace sync is lost until a person clicks a
+ workspace tab — ask them to.
+- **The `generateToolpath` future is unreliable.** Poll `op.isGenerating` and
+ `op.hasToolpath`.
+- **A parameter edit does not invalidate an existing toolpath.** Call
+ `clearToolpath` before regenerating, or the old path is read as new.
+- **Operations cannot be reordered** through the API. Create them in order.
+- **Flute count set through operation parameters fails silently.** Set it
+ through `op.tool`, which resets the feeds — so set the tool first, feeds
+ last, and read both back.
+- **Chain side is controlled only through `isReverted`.**
+- **A stock-contour slot cannot be cleared once set, and the setup's virtual
+ stock cannot be selected as a boundary.** Sketch a circle for the boundary,
+ or set `useStockContours = false`.
+- **Fusion must be open with the document active.** There is no file-only
+ path.
+
+---
+
+## Document integrity — before and after every design or CAM step
+
+Because of the replayed-script behavior above, a write can land geometry from
+an earlier call.
+
+1. **Before**, read-only: list every body and sketch in the document. A fresh
+ document should list none.
+2. Run the step.
+3. **After**, read-only: list them again. Every new body and sketch must be one
+ this step created, by name.
+4. **Anything else is foreign geometry and the step fails.** Record the
+ result in the geometry estimate's `document_integrity` with both lists. If
+ it turned up in a fresh document, the add-in is replaying: tell the user to
+ restart Fusion, and do not retry until they have.
+
+A clean result is recorded too. "Not checked" is a result, and it is reported
+as one.
+
+## Toolpath verification — by geometry, per operation
+
+`isToolpathValid` says the path can be cut. It does not say it cuts the right
+place: a path reported valid has cut the wrong region of a part.
+
+After generation, read the toolpath points and test them against the
+operation's intent — **outside the boss** for a profile, **inside the pocket**
+boundary for a pocket, **within the hole** radius for a bore. Record per
+operation the points read, how many satisfy the intent, and pass or fail. A
+failed operation is fixed or dropped, never timed.
+
+---
+
+## Record which backend ran
+
+`cad_backend` travels with every output that came from CAD — `fusion`, or
+`none` for anything hand-authored — on the variant manifest and on the geometry
+estimate alike. A record with no backend is not distinguishable from one
+nobody thought to check, and the day a second CAD connector appears, every
+existing record needs to already carry the field it will be filtered on.
diff --git a/plugins/claude-for-manufacturing/skills/design-space-explore/reference/parametric-check.md b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/parametric-check.md
new file mode 100644
index 00000000..16d62fe5
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/parametric-check.md
@@ -0,0 +1,85 @@
+# The parametric check — the single biggest risk in the skill
+
+**This runs before generation, not after.** Everything else in this skill
+assumes the model can actually do what is about to be asked of it, and this
+is the step that finds out.
+
+---
+
+## What "driving" actually means
+
+A parametric CAD model is built from dimensions that other geometry
+depends on. Change `wall_thickness` from 3mm to 4mm, and every feature
+defined relative to it — fillets, ribs, mounting bosses — regenerates
+automatically.
+
+**Not every dimension that looks like a parameter is actually driving
+anything.** A hole pattern might be positioned by a sketch constraint that
+ignores the "hole_spacing" parameter the engineer thinks controls it. A
+fillet radius might be hard-coded on one feature and parametric on another
+of the same name. The model *looks* parametric in the tree and is not, and
+this is exactly the failure that doesn't show up until generation is
+already running.
+
+**Many real production models are not properly parametric.** This is not
+an edge case to handle gracefully — it is the single biggest practical risk
+in this skill, and it is worth taking at face value.
+
+---
+
+## How to check it
+
+For each parameter the engineer named:
+
+1. **Read its current value and confirm it exists** as an actual model
+ parameter, not a dimension typed into a sketch that happens to look
+ similar.
+2. **Test whether changing it regenerates dependent geometry.** Where the
+ CAD tool supports it, this can be a small probe change and revert rather
+ than a destructive test.
+3. **Record the result** as `driving_parameters` (confirmed) or
+ `requested_not_driving` (asked for, not actually driving) on the
+ `parametric_check` block.
+
+Also check, once, for the model as a whole:
+
+- **External references** — does this model reference geometry in another
+ document (an assembly context, a derived part)? These can break silently
+ when a parameter change propagates through them. Record
+ `external_references_present`, and **say so to the engineer before
+ generating** — this is a warning, not just a logged flag: name what's
+ referenced and that variant generation can break it, so the engineer can
+ decide whether to proceed with that risk understood rather than discover
+ a broken assembly reference after the batch runs.
+
+---
+
+## When a requested parameter isn't driving
+
+**Stop before generating anything for that parameter**, and say precisely
+which one and why:
+
+> *"`hole_spacing` is set on the sketch that positions the mounting holes,
+> but the sketch also carries a fixed 22mm dimension that isn't tied to it
+> — changing `hole_spacing` won't move the holes. I can vary
+> `wall_thickness` and `rib_count`, which are both genuinely driving. Do
+> you want to fix the sketch constraint first, or proceed on the two that
+> work?"*
+
+This is not a reason to abandon the run. **Generate variants for the
+parameters that do drive geometry, and name the ones that were requested
+but can't be honored** — `requested_not_driving` on the manifest, so
+`trade-study-report` can state that part of the requested design space was
+not actually explored, rather than silently reporting fewer rows with no
+explanation.
+
+---
+
+## Report the check either way
+
+`parametric_check.ran` is always `true` once this step executes, even when
+every parameter checks out clean. **A model that passed the check and one
+that was never checked look identical unless the check itself is on the
+record.** Per `../../../shared/absent-is-not-zero.md`, an absent
+verification is not the same fact as a confirmed one, and the manifest
+needs to be able to tell them apart.
diff --git a/plugins/claude-for-manufacturing/skills/design-space-explore/reference/variant-generation.md b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/variant-generation.md
new file mode 100644
index 00000000..036917f0
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/design-space-explore/reference/variant-generation.md
@@ -0,0 +1,126 @@
+# Confirming the plan, generating, and building the manifest
+
+---
+
+## Confirm before generating anything
+
+**A live CAD connection makes 3,000 low-value variants exactly as easily as
+30 good ones.** There is no natural ceiling the way there is with, say, a
+file export — the only check is asking first.
+
+Show, before running anything:
+
+- Each parameter and its range
+- The step or sampling strategy — a fixed step, a set of named values, or a
+ sampling method — and why
+- **The resulting count, as a number**, not implied by the ranges
+
+> *"wall_thickness 3.0 to 5.0mm in 0.5mm steps (5 values) × rib_count 2 to 4
+> (3 values) = 15 variants. Confirm before I generate?"*
+
+Five parameters at five values each is 3,125 combinations. **Always compute
+and show the actual count** — a plan that sounds reasonable described in
+words can be an unreasonable number of variants once multiplied out, and
+the engineer needs the number, not the description, to make that call.
+
+`variant_count_confirmed` on the manifest records that this happened.
+Confirmation is a hard precondition for this skill, not a best practice —
+nothing generates without it, per `SKILL.md`'s Approval gates, so on any
+manifest this skill produces the field is always `true`. The field can
+read `false` only on a manifest `trade-study-report` receives from
+elsewhere — a hand-authored manifest never routed through this skill at
+all — which is why the consuming skill still has to check it rather than
+assume.
+
+---
+
+## Generate, and verify each one
+
+Apply each confirmed parameter set, one variant at a time, by the sequence
+in `adapt-prior-model.md`: open the base read-only, save as the variant's new
+document (or its named configuration), apply, verify, and confirm the base
+did not move. After each variant:
+
+**Verify the model actually regenerated without error** before recording it
+as successful. A silent failure that still produces *a* geometry — just not
+the one the parameters describe — is worse than an explicit failure,
+because nothing downstream will know to distrust it.
+
+### Regeneration failures are normal, not bugs
+
+Geometry that self-intersects, or a feature that fails to rebuild, happens
+routinely at range extremes — a wall thin enough to intersect a rib, a
+fillet radius too large for the available edge length. **This does not
+abort the batch.**
+
+Record the variant as `status: regeneration_failed` with a specific
+`status_detail` — which feature failed and why, where the tool reports it:
+
+> *"Rib fillets self-intersect at 5.0mm wall thickness with 4 ribs; feature
+> Fillet3 failed to rebuild."*
+
+A vague `status_detail` like "failed to regenerate" is barely better than
+omitting the row. The specific feature and the specific reason are what let
+someone decide whether the failure is informative (the design genuinely
+doesn't work at that extreme) or an artifact of how the model was built.
+
+### A skipped variant is not a failed one
+
+Where step 2's parametric check found a requested parameter that isn't
+driving, the variants that would have varied only that parameter are
+`status: skipped`, with `status_detail` pointing back to
+`requested_not_driving`. Skipped and failed are different facts — one is a
+model limitation discovered at generation time, the other is a configuration
+that was never viable to attempt.
+
+---
+
+## Long-running batches need progress, not silence
+
+Applying and verifying a parameter set is not instant, and a batch of even
+a few dozen variants can run for minutes. **Report progress as it happens**
+rather than returning nothing until the whole batch completes — a stalled
+connection and a slow-but-working one look identical from the outside
+without it.
+
+---
+
+## The base model is never touched
+
+Every variant is a **new document, or a clearly-named configuration** —
+never an edit to the base in place. State what was created and its
+document reference as each one completes, not only at the end.
+
+**Generation is idempotent.** Before creating a variant, look for an existing
+document with the same name and the same parameter values: after a partial
+batch, a re-run, or a call that executed twice. If one exists, reuse it and
+record it in the manifest as `reused_existing` with its reference; never create
+a second copy. Two documents for one variant leave a manifest that cannot say
+which is authoritative.
+
+**Why this matters more than it might seem to:** the base model is the
+thing the engineer will keep working from after this run. An accidental
+edit to it is not recoverable by re-running this skill — the input the next
+run needs would already be gone.
+
+---
+
+## Building the manifest
+
+One row per variant, generated or not — per
+`../../../shared/contracts/variant-manifest.md`:
+
+- `variant_id`, stable and traceable to its parameter set
+- `parameter_values`, one entry per parameter in `parameters_varied`
+- `status`, one of `generated`, `regeneration_failed`, `skipped`,
+ `hand_authored`
+- `properties`, whatever the model could compute — **absent where it
+ couldn't, never zero.** A `mass: 0` variant reads as massless and would
+ win a lower-is-better weight criterion outright, which is exactly the
+ wrong outcome for a variant nobody could actually measure.
+- `source_ref`, so every downstream score can be traced back to this run
+
+**Never drop a failed or skipped row.** A manifest that only lists what
+worked describes a design space narrower than the one actually explored,
+and `trade-study-report` would score against that narrower, silently
+incomplete picture without knowing it was incomplete.
diff --git a/plugins/claude-for-manufacturing/skills/inspection-to-capa/SKILL.md b/plugins/claude-for-manufacturing/skills/inspection-to-capa/SKILL.md
new file mode 100644
index 00000000..4f9af876
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/inspection-to-capa/SKILL.md
@@ -0,0 +1,193 @@
+---
+name: inspection-to-capa
+description: "Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether this has happened before and whether the last fix held, reads sensor and inspection data on one verified timeline, proposes ranked candidate causes with evidence for and against, drafts the 8D, and produces the customer pack behind a redaction diff. Use when someone says \"run the CAPA chain,\" \"take this nonconformance through to an 8D,\" \"inspection to CAPA,\" or asks for the full corrective-action workflow."
+compatibility: "Requires none. Chains ncr-writeup and root-cause-capa. Reads Microsoft 365 and the ERP (Oracle NetSuite or Infor M3) where connected; runs on pasted findings and file exports with no connector. Never asserts a requirement it cannot locate, never correlates across clocks it could not align, and nothing customer-facing leaves without review of the redaction diff."
+---
+
+# Inspection to CAPA
+
+Chain 2. `ncr-writeup` → `root-cause-capa`.
+
+The path from "we found a bad part" to "we fixed the reason, and we can prove
+it." It ends on the 8D and its redacted customer pack.
+
+**Quick start**
+
+```
+→ Write the NCR against a CITED requirement. Cannot find one? Block. Never invent
+→ Search history AT CREATION, not on request. Did the earlier fix hold?
+→ Gate 1: the quality owner confirms the NCR and its containment
+→ Verify the clocks BEFORE correlating. Misaligned? Refuse, and say what survives
+→ Ranked candidate chains with evidence FOR and AGAINST. Never one verdict
+→ 8D: D1-D5 and D7 populated. D6 and D8 stay empty placeholders
+→ Gate 2: nothing customer-facing leaves without the redaction diff reviewed
+```
+
+---
+
+## Inputs
+
+| Input | Source | Form |
+|---|---|---|
+| The finding | Inspector notes, an inspection export, an operator report, a customer complaint | Conversation, M365, pasted |
+| Everything else | Whatever the two member skills read | See each skill |
+
+---
+
+## The seven steps
+
+**1. An inspection result or a suspect lot starts it.**
+
+**2. Write the nonconformance** against the requirement, with quantity and
+location. All five containment locations are addressed, including with a zero
+quantity, because an omitted location reads as "none there" rather than "not
+checked."
+
+**Gate 1** — the quality owner confirms the NCR and the containment plan.
+**This is a pause, and the chain says so:** *"Paused at Gate 1, after step 2.
+The NCR is a draft. A quality owner confirms four things before step 4 — the
+finding, the cited requirement, the suspect scope, and the containment plan."*
+A missing citation is one reason the NCR is not ready; it is not the gate.
+Fixing the citation does not unblock the chain — the owner's confirmation does.
+The history search in step 3 still runs at write time, because it belongs to
+the NCR. Per `../../shared/approval-gates.md`.
+
+**3. Search history for the same problem.** This runs automatically at write
+time, not on request, because the moment of detection is the only moment anyone
+is looking.
+
+**Whether the earlier fix held is the highest-value single line in this
+chain.** A recurrence after a *closed* CAPA is a materially different finding
+from a first occurrence, and it changes what happens next. Surface it as such.
+
+**4. Read the prior tickets, inspection data and production history together**,
+aligned onto one zone-aware timeline. Verify the clocks first; where alignment
+cannot be verified, refuse to correlate and say which conclusions survive
+anyway.
+
+**5. Propose ranked candidate causal chains**, each stated as a chain with
+supporting *and contradicting* evidence attached to each link, and the cheapest
+test that would confirm or kill it. Never one confident verdict: a confident
+wrong root cause closes the investigation and the fix fails.
+
+**6. Draft the 8D.** D1 to D5 and D7 populated from the evidence. D6 and D8
+stay as structured placeholders, because they need a real-world outcome and a
+human signature.
+
+**7. Produce the customer-facing pack with a redaction pass.** **Gate 2.**
+
+---
+
+## Approval gates
+
+| Gate | Where | What it protects |
+|---|---|---|
+| 1 | After step 2 | The quality owner confirms the finding, the cited requirement, the suspect scope and the containment plan |
+| 2 | After step 7 | Nothing customer-facing leaves without review of the **redaction diff** |
+
+The redaction pass is a reviewable diff, never a silent filter. The internal 8D
+carries cost data, other customers' names, supplier identity and internal
+process detail; the customer version must not. **A recurrence stays in** —
+removing it is misrepresentation, not redaction.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+The NCR in the plant's controlled template, the containment plan ordered by
+urgency, the recurrence finding with whether the previous fix held, the ranked
+candidate causes with their discriminating tests, the drafted 8D, the evidence
+appendix, and the redacted customer pack.
+
+**The figures block** — required, inside the evidence appendix. Every
+measurement, control limit, ratio and count the chain states is printed from
+the computation and listed with it, and the prose quotes the block. Two member
+skills doing the same arithmetic must not arrive at two different multiples of
+the same limit. Per `../../shared/computed-figures.md`.
+
+Where the leading candidate points at purchased material, the **supplier-caused
+flag** is raised, which is the trigger into Chain 5. See
+`supplier-escape-to-alternate-source`.
+
+**The Quality command-center page: the Quality Register** — open corrective
+actions, carrying the NCR and the 8D by reference, updated in place per
+`../../shared/live-dashboard.md`. **The chain writes no register row of its
+own.** `ncr-writeup` writes the row at step 2 and `root-cause-capa` adds the
+8D fields at step 6, both keyed `<site>_<ncr_ref>`, so one chain run leaves
+one row. The chain reports the register once, at the end: the dashboard line
+with its URL and the sensitivity line, or the fallback with *"The Quality
+Register was not updated: [reason]."* It is reported as updated only when a
+publish returned a URL in this run, and never as shared. Read
+`../../shared/command-center.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **The requirement cannot be located** — the chain **blocks at step 2**. Never
+ invent one. That is a complete and honest outcome.
+- **Traceability is incomplete** — the suspect scope **widens** and says why.
+ Never narrow it to make the number look better.
+- **The clocks cannot be aligned** — step 4 refuses to correlate. Non
+ time-dependent analysis still runs, and the output says which is which.
+- **Two candidates are supported equally** — present both. A stated tie is a
+ real finding, and it names the test that would settle it.
+- **No prior history exists** — say so. Absence of recurrence is not evidence
+ of a one-off.
+
+---
+
+## Degradation
+
+| Not available | What happens |
+|---|---|
+| The quality document library | Report "no searchable history available" at step 3. **Never silence**, which reads as "no recurrence" |
+| The sensor export, or it misses the event window | Say so. Do not reason from adjacent data as if it were the event |
+| The plant's 8D template | Use the standard eight-discipline structure and flag that the controlled template was unavailable |
+| A CMMS connector (Limble or any other) | See below |
+
+**Check the freshness of every export before correlating on it.** A scheduled
+export that silently stopped produces a timeline with a hole in it, and the
+hole looks like an absence of evidence rather than an absence of data. State
+the coverage window of each source in the evidence appendix.
+
+**If Limble isn't included, or no CMMS connector is live** — minor here. Maintenance history arrives in the
+same scheduled export as everything else and the maintenance-correlation check
+runs on it unchanged. What changes is freshness: name maintenance explicitly as
+an export-sourced input in the evidence appendix rather than letting it read as
+live, since a repair logged after the last export will not be on the timeline
+at all.
+
+---
+
+## Chain position
+
+**This is Chain 2 itself.** Members: `ncr-writeup`, `root-cause-capa`.
+
+**Metric.** CAPA closure time and first-pass yield, both owned by
+`root-cause-capa`. `ncr-writeup` also moves nonconformance closure time and
+escape response time inside this chain; the chain does not claim them, because
+it is named for the corrective-action loop.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `../ncr-writeup/SKILL.md` | Steps 2 and 3 |
+| `../root-cause-capa/SKILL.md` | Steps 4 to 7 |
+| `../../shared/contracts/ncr.md` | The handoff, and what blocks `root-cause-capa` |
+| `../../shared/command-center.md` | The Quality page, and when "updated" may be said |
+| `../../shared/live-dashboard.md` | The Quality Register: one row per NCR, the banner, the fallback |
+| `../../shared/computed-figures.md` | Before stating any figure — the figures block |
+| `../../shared/approval-gates.md` | At both gates — a gate is a pause, and how to say where the chain stopped |
diff --git a/plugins/claude-for-manufacturing/skills/morning-plant-pulse/SKILL.md b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/SKILL.md
new file mode 100644
index 00000000..b1109ab1
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/SKILL.md
@@ -0,0 +1,371 @@
+---
+name: morning-plant-pulse
+description: "Runs the overnight chain that has the morning production report waiting before anyone asks for it: joins last night's planning, production and maintenance exports, flags the mismatched keys, then computes output against plan, OEE with its three components, downtime ranked two ways, priced losses and the exceptions needing a decision. Stores a record per production day and keeps one Operations Command Center dashboard per site up to date, with a 14 and 30 day trend. Safe to run unattended. Use when someone says \"run the morning pulse,\" \"do the overnight report,\" \"morning plant pulse,\" \"update the operations dashboard,\" or schedules the daily production run."
+compatibility: "Requires none. Chains data-consolidate and daily-production-report, then publishes the site's Operations Command Center dashboard to the Claude artifact store where the artifact tools exist, else offers the page in the conversation. Reads M365 exports, NetSuite or Infor M3, and a CMMS connector where connected; runs on the export folder alone. Writes to no system of record, so it is safe to schedule. Asks nothing, is idempotent, reports its own gaps."
+---
+
+# Morning Plant Pulse
+
+Chain 3. `data-consolidate` → `daily-production-report` → publish.
+
+**The only scheduled chain, and the only one with no approval gate.** Those two
+facts are the same fact: it reads, it produces a page, and it writes to no
+system of record. The dashboard it publishes lives in the user's own Claude
+artifact store, which is not a system of record either. That is precisely why
+it is safe to run unattended, and why no other chain in this build should ever
+be scheduled.
+
+The page is rebuilt overnight so it exists before the morning meeting. A
+supervisor otherwise spends sixty to ninety minutes assembling it by hand out
+of the same four or five exports. **The first run creates one dashboard per
+site; every later run updates that same dashboard**, so nobody has to save
+over yesterday's page.
+
+**Quick start**
+
+```
+→ Join last night's exports; flag mismatched keys by class
+→ Compute output vs plan, OEE with its three components shown separately
+→ Downtime ranked BOTH ways: by minutes and by frequency
+→ Price the losses. Week-over-week movers come from the stored day records
+→ Write the day record, keyed <site>_<YYYY-MM-DD>. Missing export? data_complete: false
+→ Find the dashboard: stored URL, then exact title. Neither? Create it
+→ Say "updated" ONLY when the publish returned a URL in this run
+→ Can't publish? Page saved to pulse-output/ + "the dashboard was not updated"
+→ Reply: ~150-word summary naming the page; full page in the reply only if nothing could be written
+→ Export did not land? STILL RUN. Gap at the top, gap in the trend, never a zero
+→ Ask nothing. There is nobody there at 4am
+→ Idempotent: a re-run overwrites that day's record on the same dashboard
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| Planning, production and maintenance exports | The M365 export folder | CSV/XLSX |
+| Standard cost, open work orders | The ERP (NetSuite or Infor M3) | Connector |
+| Maintenance work orders in progress | CMMS | CMMS connector, else the maintenance export |
+| Stored day records, for the trend and week-over-week | The dashboard's own `pulse_days` collection | `ArtifactData` `query`, per `../../shared/contracts/pulse-day-record.md` |
+| The dashboard's URL | The `## Dashboards` line on the Open work page, then an exact-title lookup | Open work page, `Artifact` `list` |
+| Source clocks, shift pattern, day boundary | `## Plant context` | Config |
+
+---
+
+## The three steps
+
+**First, run the compute engine.** Steps 1 and 2 are done in code that ships
+with this skill, so every run computes the same numbers the same way:
+
+```
+python3 -I <this skill's folder>/scripts/pulse_compute.py --exports <export folder> \
+ --out pulse-output [--day YYYY-MM-DD] [--profile <profile_path>] [--rates <rates_path>]
+```
+
+It applies the ladder, the eight classes and the integrity flags of
+`data-consolidate`, and the OEE, ranking, pricing and exception rules of
+`daily-production-report`, and writes `figures.csv` (the figures block, one row
+per number with its filter), `pulse_model.json` (everything the page shows,
+already computed) and `day_records.json` (one day record per covered day).
+**Build the page from `pulse_model.json` and quote `figures.csv`. Never
+recompute, retype or round a number it holds.** The judgment stays yours: the
+wording, which exceptions are significant, the reschedule move, the publish.
+What each key holds is `reference/compute-engine.md`. **If the engine cannot
+run** (no code execution) **or exits non-zero**, do steps 1 and 2 as written
+below and say which happened; never mix the two.
+
+**1. Join the exports** through `data-consolidate`, on the records the plant
+already has, with mismatched keys flagged by class.
+
+**2. Compute the report** through `daily-production-report`: output against
+plan, equipment losses ranked by minutes and by frequency, priced in dollars,
+and the exceptions that need a decision today. **Week-over-week movers come
+from the stored day records**, read at the start of step 3 before the page is
+built, never from a prior page. The pulse hands that history to step 6 of
+`daily-production-report`.
+
+**3. Publish the dashboard.** Per `../../shared/live-dashboard.md`, which names
+every tool call. In order:
+
+1. **Find the dashboard.** The `## Dashboards` line on the Open work page first; then
+ `Artifact` `list` for the exact title *"<Site>: Operations Command
+ Center"*; only when both find nothing does this run create it. A scheduled
+ run starts with no memory of earlier runs, so it looks every time.
+2. **Build the day record** for the production day, every field, per
+ `../../shared/contracts/pulse-day-record.md`, keyed `<site>_<YYYY-MM-DD>`.
+ A missing export makes it `data_complete: false` with the gap named. Its
+ metrics are null, never zero.
+3. **Existing dashboard:** `read` it, `query` `pulse_days`, `set` the day
+ record, compute the trend from the stored records in code, then publish to
+ the same `url`. **First run:** back-fill (below), publish with
+ `capabilities: {db: {}}` and the fixed title, `batch` the records against
+ the new URL, write the URL to the `## Dashboards` line on the Open work
+ page, then `open` the dashboard so it is what the person sees.
+4. **Render the short Operations page,** after the publish so it can link
+ to the dashboard: `python3 -I <this skill's folder>/scripts/render_short.py
+ --out pulse-output [--full-page-url <url>]`. It writes
+ `operations-short-<site>-<day>.html` beside the figures and checks itself;
+ on a failed check it writes nothing, and the reply says so. It is a
+ separate page from the dashboard and never replaces it. Per
+ `reference/short-page.md`.
+5. **Report it,** as the last line of the run: *"Updated **Fairview:
+ Operations Command Center**, `<url>`. Private to you until you share it."*
+ Or the fallback: the page saved as
+ `pulse-output/operations-<site>-<day>.html` (in the reply only when no
+ file can be written), its placement line, and
+ *"The dashboard was not updated: [reason]."*
+
+**Say "updated" only when the publish returned a URL in this run.** Never
+"shared," never "scheduled," never "posted." The dashboard is private until
+the user shares it, and the pulse never shares it. A run that says "updated"
+without a URL from this run has told the meeting to trust a page nobody
+rebuilt.
+
+**Only the pulse publishes the Operations dashboard.** `daily-production-report`
+run alone, and Chain 4, keep offering their page in the conversation. Two
+dashboards showing the same numbers is how a meeting ends up arguing about
+which one is right.
+
+**Back-fill on the first run only.** When the exports cover several production
+days, the run that creates the dashboard writes a record for every day the
+planning, production and downtime exports fully cover, so the trend opens with
+history. A day they only partly cover is written `data_complete: false`, so it
+shows as a gap rather than as a bad day. Later runs write their own day.
+
+What the page holds, panel by panel, is `reference/operations-dashboard.md`.
+
+---
+
+## What "safe to run unattended" actually requires
+
+Three properties. Each is a real constraint, not a nicety.
+
+**It asks nobody anything.** There is no one at 4am to answer. Where an
+attended run would ask which date range or which of several exports to use, the
+unattended run takes the production-day range from the `## Plant context` block
+and **says which it used**. **With no Plant context at all**, it uses the latest
+complete production day present in the exports, says so in the freshness
+banner, and lists *no plant profile* among the gaps. It never blocks on the
+missing profile, and never picks today's date, which has no data. A run that blocks on a question produces nothing,
+and nothing is worse than a partial report, because the gap is only discovered
+at the meeting. The publish step asks nothing either: where two artifacts carry
+the exact title, it uses the stored URL's, or the most recently updated, and
+names both.
+
+**Asking nobody does not mean deciding for them.** Where plan and output spell
+a part differently, the unattended run neither drops the row nor joins it
+silently. It shows the variance **labelled provisional**, shows both spellings
+verbatim, and lists each normalization it relied on as **proposed, awaiting
+approval**, for whoever reads the page to accept or reject. Normalizations on
+the profile's `### Approved normalizations` list are used as they stand; each
+overnight run rebuilds the dataset, so that list is what carries a yes from one
+night to the next. This is
+not a gate — nothing is applied and nothing is written — and the rule is
+`../../shared/approval-gates.md`, *When nobody is there to ask*.
+
+**A list of data problems holds problems, and it is built by class number.**
+Take the classified mismatches from step 1 and route each class before any
+row is numbered:
+
+| Class | Where it goes |
+|---|---|
+| 1 orphan, 2 format drift, 3 leading zeros, 4 revision suffix, 5 case and whitespace, 8 duplicate key | The numbered **Data problems** table, and its count |
+| 7 date window | The coverage line in the freshness banner. Not a numbered row |
+| 6 genuine one-sided record | **"Checked, nothing wrong"**, a separate block after the table. Never a row number, never in the count |
+| 6 with `contradicted_by` set | The numbered **Data problems** table, as *one-sided, contradicted by* the named record, and its count. Never "Checked, nothing wrong" |
+
+A record decides its class from its own type and dates, never from a part
+number someone recognises. A Class 6 record that appears in the table *and*
+in the recap has still been counted as a problem; it appears in the recap
+only. **A duplicate key is counted by the rows that collide at the tab's
+grain, from the query** (work order, shift and production day): if WO-88201
+has three rows, and two of them (509 and 480 good, both 07:00)
+are the duplicate; the 95 on the 23:00 shift is its own shift. Say both
+numbers, and the figures block shows the filter. And a downtime record
+from `breakdown-diagnosis` with no `safety_flagged` is **blocked**: listed
+first under "Blocked — safety status unknown," held out of both rankings, the totals
+and the pricing. MES and historian rows are untouched. Both rules are
+`../daily-production-report/SKILL.md`, steps 7 and 8. The day record carries
+the same split: `data_problems_count` is the table's count, and a blocked
+record is outside every downtime figure stored.
+
+**It is idempotent.** A re-run for the same production day overwrites that
+day's record by key and updates the same dashboard, rather than adding a
+second record or creating a second page. Somebody will re-run it, after a late
+export lands or because the first run was mistrusted, and two reports for one
+day is worse than one because the meeting then argues about which is right.
+
+**It reports gaps rather than failing on them.** If last night's export did not
+land, the run still completes and says so at the top. A missing export is a
+finding, not an exception. Silence, stale data and a crashed run all read the
+same way to a supervisor at 6am: nothing to look at. A publish that fails is a
+gap of the same kind: the run falls back and says so.
+
+---
+
+## Approval gates
+
+**None, by design.** This chain is read-only and writes to no system of record.
+That is the whole reason it can be scheduled.
+
+Anything that would need a gate does not belong in this chain. The reschedule
+proposals it produces are drafted for the scheduler and **never applied**.
+
+**Publishing the dashboard is not a gate.** It writes to the user's own
+artifact store, not to M365 or any system of record, and the page is private
+until the user shares it. The `## Dashboards` line on the Open work page is
+written without a gate for the same reason; never say the page was saved
+unless `saved` returned ok in this run. The `## Plant context` block is never touched by
+this chain: changing it takes two turns and an approval nobody is there to
+give.
+
+---
+
+## Scheduling
+
+**The plugin does not schedule itself.** It provides a run that is safe to
+execute unattended; the host provides the trigger. Read
+`../../shared/scheduling.md`.
+
+Never tell a user the report has been scheduled. Describing the run as
+overnight is accurate; claiming to have scheduled it is not.
+
+**Whether an unattended, scheduled session can publish is unverified.** The
+run checks for the `Artifact` and `ArtifactData` tools every time and falls
+back when they are absent. It never claims a scheduled run published.
+
+---
+
+## Output
+
+**The reply is a summary of about 150 words; the full page is on the
+dashboard or in a file**. When the publish did not
+return a URL, save the full page as `pulse-output/operations-<site>-<YYYY-MM-DD>.html`
+and name that path. The summary is the one in `../../shared/replies.md`
+(200 words at most), plus one line per day record: its key, `data_complete`,
+the gap if any, and whether it was stored. A request that picks or skips
+sections is not the whole report: those sections go in the reply in full. **With no way to write a file and no publish, print
+the full page in the reply instead.**
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The Operations Command Center dashboard** — *"<Site>: Operations Command
+Center"*, one per site, created on the first run and updated in place after
+that, per `../../shared/live-dashboard.md` and
+`reference/operations-dashboard.md`. Its header reads *Updated [timestamp] ·
+data as of [timestamp]*. Two panels:
+
+- **Today:** a safety-flagged diagnosis record first, then the freshness
+ banner, never a footnote, then today's actions (issue, impact, next step,
+ owner role, and whether it is a decision, an investigation or an
+ observation, per step 4 of the report order in
+ `../daily-production-report/SKILL.md`), then output against plan, OEE with its three components shown separately, downtime ranked both
+ ways, priced losses, exceptions with a traced reschedule move per
+ significant exception, "Blocked — safety status unknown," the numbered
+ data-problems table with its count, and "Checked, nothing wrong" outside
+ that count.
+- **Trend:** OEE and its three components, output against plan, and downtime
+ minutes for the last 14 and 30 days, and the week-over-week movers, all
+ from the stored day records. A day with no data is a gap, never a zero.
+ With no history yet, the panel says so and week-over-week is skipped.
+
+Plus the structured dataset behind it so the numbers can be checked —
+**including the figures block**, which matters most here because nobody is
+watching the run. Every count in the page, and every count in any list of data
+problems, is printed from a computation and listed with its filter, and the
+page quotes the block. Every trend point is in the block too, with the records
+it came from. A problem count that does not equal the problems listed under it
+is the defect to look for. Per `../../shared/computed-figures.md`.
+
+**The day record(s)** — per `../../shared/contracts/pulse-day-record.md`, on
+every run, stored or not: one line each in the reply (key, `data_complete`,
+the gap, stored or *computed, not stored*), and the field and value table of
+`../../shared/replies.md` on the page.
+
+**The short Operations page** — a file, never pasted into the reply. Name
+its path and give its decisions, one line each, above the last line. With no
+code execution there is no short page; say so in one line.
+
+**The last line** — the dashboard line with its URL; or, when the dashboard
+could not be published, the page in the conversation, its placement line
+(*"save it over yesterday's"*), and *"The dashboard was not updated:
+[reason]."* Read `../../shared/command-center.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **Last night's export did not land** — run anyway, and report the gap
+ prominently. Never silently reuse yesterday's data. The day is stored
+ `data_complete: false`, and the trend shows a gap, never a zero.
+- **Partial data, one line's export missing** — report on what is there and
+ name what is missing.
+- **A re-run for a day already reported** — overwrite that day's record and
+ update the same dashboard. Never a second record, never a second page.
+- **A late export lands after the run** — a re-run for that day overwrites its
+ `data_complete: false` record with the complete one.
+- **First run, no stored history** — back-fill what the exports fully cover.
+ With nothing to back-fill, the trend panel says there is no history yet and
+ week-over-week is skipped rather than shown empty.
+- **The dashboard was renamed** — the title lookup cannot find it, so a new one
+ is created. Say so, per `../../shared/live-dashboard.md`.
+- **The publish fails or the tools are absent** — fall back: page in the
+ conversation, placement line, "the dashboard was not updated." The run
+ never stalls on it.
+- **Reason codes heavily "Other"** — that coverage problem is a finding of its
+ own, not something to smooth over.
+
+---
+
+## Degradation
+
+| Not available | What happens |
+|---|---|
+| The export folder | Run connector-only and name every tab that could not be built. Never treat a missing tab as empty |
+| The downtime cost-per-hour | Price scrap only, and say downtime is unpriced |
+| Stored day records | Skip week-over-week; the trend panel says there is no history yet |
+| The `Artifact` or `ArtifactData` tools, including on an unattended run | The page in the conversation, its placement line, and "the dashboard was not updated." The day record is still in the structured output, marked not stored. Never "updated," "scheduled" or "shared" |
+| The Open work page can't be written, for the `## Dashboards` line | Find the dashboard by exact title, report the URL, and say the link was not saved |
+| A CMMS connector (Limble or any other) | See below |
+
+**If Limble isn't included, or no CMMS connector is live** — negligible for this chain. It is an overnight
+batch, so an export cadence is already the correct cadence: the maintenance
+rows simply arrive in the same scheduled drop as production and planning. The
+freshness banner must name maintenance as an export-sourced input so nobody
+assumes it is live.
+
+---
+
+## Chain position
+
+**This is Chain 3 itself.** Members: `data-consolidate`,
+`daily-production-report`, then this skill's own publish step.
+
+**Metric.** OEE visibility and supervisor hours, both owned by
+`daily-production-report`. The scheduled delivery is what earns the supervisor
+hours: the report exists before anyone builds it by hand.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/compute-engine.md` | Before building the page: what `pulse_model.json` holds and how each part is labelled |
+| `reference/short-page.md` | Step 3.4 — the short Operations page: what it holds, and how it differs from the dashboard |
+| `../data-consolidate/SKILL.md` | Step 1 — the join and the eight mismatch classes, when the engine cannot run |
+| `../daily-production-report/SKILL.md` | Step 2 — OEE, the rankings, the reschedule scope boundary |
+| `../../shared/live-dashboard.md` | Step 3 — finding, creating and updating the dashboard, the tool calls, the fallback |
+| `../../shared/contracts/pulse-day-record.md` | Step 3 — every field of the day record, and the gap rule |
+| `reference/operations-dashboard.md` | Step 3 — the Today and Trend panels |
+| `../../shared/scheduling.md` | Before claiming anything about the trigger |
+| `../../shared/command-center.md` | The Operations page, and when "updated" may be said |
+| `../../shared/computed-figures.md` | Before emitting — the figures block |
+| `../../shared/approval-gates.md` | When a match rests on a normalization nobody has approved |
diff --git a/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/compute-engine.md b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/compute-engine.md
new file mode 100644
index 00000000..9cb5d254
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/compute-engine.md
@@ -0,0 +1,78 @@
+# The compute engine: what it writes and how to read it
+
+Loaded before building the page. The engine is `../scripts/pulse_compute.py`,
+standard-library Python, run once per pulse. It reads the export folder
+(CSV, or XLSX one table per sheet), recognises each file by its header, and
+computes every figure the Operations page prints. The page code selects and
+formats; it does no arithmetic.
+
+```
+python3 -I ../scripts/pulse_compute.py --exports exports --out pulse-output \
+ [--day 2026-08-31] [--profile <profile_path>] [--rates <rates_path>] [--diagnoses exports/diagnoses] \
+ [--manifest columns.json] [--run-time 2026-09-01T04:10:00-04:00] [--tz America/New_York]
+```
+
+- `--day` is the production day asked for. Without it the engine takes the
+ `Production day` the plant context names, else the latest day the plan,
+ output and downtime exports all cover, and says which.
+- `--profile` is any file holding the `## Plant context` block: `profile_path`
+ from `plant_setup.py find`, or for an older profile, the memory
+ file or a `plant-context.md` in the drop. Without one, the time zone and the
+ day start are assumed and listed in `context.assumptions`.
+- `--rates` is the `## Plant rates` file at `rates_path`; its downtime cost per
+ hour wins over a value left in an older profile.
+- Breakdown-diagnosis records (YAML or JSON) are read from
+ `exports/diagnoses/` unless `--diagnoses` names another folder.
+- `--manifest` is only for a plant whose headers the engine does not
+ recognise: `{"roles": {"<file>": "output"}, "columns": {"output": {"qty_good": "<header>"}}}`.
+ A file it cannot place is listed in `context.files_not_used` with the reason.
+
+It prints a short summary, and exits 2 with the failed checks listed when a
+subtotal does not reconcile. On exit 2 nothing it wrote is used.
+
+---
+
+## `figures.csv` — the figures block
+
+One row per number: `id, figure, value, unit, period, source, filter`. A
+value that could not be computed reads `not computable`, never 0. The page's
+figures block is this file; the prose and every table quote it. A number on
+the page with no row here is a defect.
+
+## `pulse_model.json` — what the page is built from
+
+| Key | Holds | Page rule it carries |
+|---|---|---|
+| `context` | Site, time zone and whether it was assumed, day start and the day-boundary rule, run time, `assumptions`, files used and not used, `part_reference`, `unit_reference` | Every assumption goes in the freshness banner or the run notes, in its own words |
+| `freshness` | Production day and how it was chosen, newest day and its age, `data_as_of`, `data_complete`, `gaps`, per-source `coverage` (first, last, rows, `landed`), `activity_window`, `future_timestamps` | A gap is the banner's first row. A day whose MES output has fewer shifts than most days is a gap too (*only the 07:00 shift for …*): not a complete plant day. `future_timestamps` makes that source's dates untrusted |
+| `normalizations` | Each spelling matched by a rung: verbatim, canonical, rule, class, rows, `status` | `approved` rules are used as they stand and never re-proposed. Everything else is *proposed, awaiting approval*, and its rows are provisional |
+| `today` | The production day: `parts` (plan, good, variance, status, both spellings, held-out rows), `oee_by_asset` with `why_not`, site `availability` / `performance` / `quality` / `oee`, `quality_convention`, `scrap` by part, `scrap_priced_usd`, `downtime_usd`, `rate_source`, `unpriced`, `stops` | A part's `status` is the label: `comparable`, `not comparable, unit conflict` (no variance), `held out` (plan *not counted*, good *held out*), `no output recorded`. A null component is *not computable* with its `why_not`, never 1.0 |
+| `periods` | `day`, `week` (Mon–Sun to date) and `month` (1st to the day) roll-ups: per-part totals, days under plan, scrap and priced scrap, held-out rows | A day whose output for a part is an unresolved duplicate is out of that part's period totals |
+| `downtime` | `day`, `week`, `month` and `window` rankings: `by_asset` and `by_code`, each with events, minutes, ongoing, held out, `rank_minutes`, `rank_events` (1, 2, 2, 4); `held_out` rows; uncoded events and minutes | Both rankings, always. `by_code` never holds `Other` or blank: state `uncoded_events` of `events` as its own finding first. An ongoing stop counts as an event with no minutes |
+| `data_problems` | `numbered` (classes 1–5 and 8, class 6 contradicted, and unit conflicts, each with `n`), `count`, `waiting_on_decision` (unit conflicts, normalizations awaiting approval, provisional row count, NCR keys that disagree with the ERP), `class7`, `checked_nothing_wrong`, `integrity` | The numbered table is `numbered` and its count is `count`. `checked_nothing_wrong` is a separate block, never numbered, never counted |
+| `exceptions` | `items` (late job, machine down, quality hold, one-sided contradicted), `late_jobs`, `late_undeterminable`, `so_link`, `maintenance_history` per asset | A null `commitment_impact` is yours to trace through `sales_order`; with `so_link` false say *"commitment impact not traceable: no work order to sales order link in the ERP"* once, with the count |
+| `diagnoses` | `safety_flagged` records (lead the page), `blocked_safety_unknown` (first list, outside every figure), `matched_to_mes_row` (records matched to an MES downtime row on asset plus start time, each with `matched_mes_row`; the stoppage is counted once), `assets_with_diagnosis` (assets with a record whose safety status is known; a blocked record does not count) | A record with the flag true or false is already in the rankings, as its own row or on the MES row it matched; a blocked one is in none |
+| `week_over_week` | This week and last, from the exports, with the days each rests on; `skip` when last week has no data | Labelled *from this run's exports, not stored history* unless stored records were read |
+| `checks` | How many self-checks ran, and any that failed | |
+
+## `periods.json` and `figures-short-page.csv`
+
+Written for the short Operations page (`short-page.md`), and read by
+`../scripts/render_short.py`, not by you. `periods.json` holds a Day, Week
+(Monday to Sunday) and Month-to-date roll-up for every production day, with
+its partial marking; `figures-short-page.csv` holds every value in them. The
+full page does not need either file; do not read them into the reply.
+
+## `day_records.json`
+
+One record per production day the exports cover, every field of
+`../../../shared/contracts/pulse-day-record.md`, keyed `<site>_<YYYY-MM-DD>`.
+The day asked for has `backfilled: false`; the rest are the first-run
+back-fill. Store them as they are. In the reply, give the day's record one
+line (key, `data_complete`, the gap, stored or not); on the page, and in a
+reply that prints the page in full, show it as
+the field and value table `../../../shared/replies.md` asks for, plain values
+(`data_complete | false`), never as a YAML or JSON block. Until a `set` has
+returned in this run, a record is *computed, not stored*: never write that a
+day "is stored" or "was saved" on a run that could not publish. Add commitment impact to the day's
+`exceptions` where you traced it; change nothing else.
diff --git a/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/operations-dashboard.md b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/operations-dashboard.md
new file mode 100644
index 00000000..9ecd2589
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/operations-dashboard.md
@@ -0,0 +1,113 @@
+# The Operations Command Center — what each panel holds
+
+Loaded at step 3. The mechanism (finding the dashboard, the tool calls, the
+fallback) is `../../../shared/live-dashboard.md`. This file is only the page.
+House style is `../../../shared/artifact-style.md`; components named below are
+defined there.
+
+**The page is static.** Every number is computed in code during the run and
+written into the HTML. The page never reads the database when someone opens
+it, so it works for anyone it is shared with and the figures block covers
+every number on it.
+
+---
+
+## Header
+
+```
+<Site>: Operations Command Center
+Fairview Plant · Updated Sep 1, 2026 04:12 · data as of Sep 1, 2026 03:52
+Production day: Aug 31, 2026 · day starts 07:00
+```
+
+"Updated" is the publish time of this run. On a fallback page, offered in the
+conversation, the same line says "Generated." The production day and the
+day-boundary convention are always on the page, because the third shift
+crossing midnight changes which day a number belongs to.
+
+---
+
+## Panel 1 — Today
+
+In this order, the same order as the morning report in
+`../../daily-production-report/SKILL.md`; the dashboard is where it now lives.
+
+1. **Safety-flagged diagnosis records**, when any, above everything else,
+ the freshness banner included.
+2. **"Blocked — safety status unknown"**, when any: each record held out of
+ both rankings, the totals and the pricing, with its asset, start time and
+ the reason.
+3. **Freshness banner.** Directly under any safety block, and first when
+ there is none; never a footnote. A missing or stale export is the banner's
+ first row, with a `--critical` or `--warn` pill. A day stored
+ `data_complete: false` says so here in one sentence: *"Downtime export did
+ not land. Availability, OEE and downtime are not computed for Aug 31."*
+4. **Today's actions**: issue, impact, next step, owner role, and whether
+ it is a decision (waiting on an approval), an investigation or an
+ observation, per step 4 of the report order. *"No decisions waiting
+ today"* when none is.
+5. **Output against plan**, by line, cell and product, with variances.
+ Provisional rows marked, with the proposed normalizations listed.
+6. **OEE** per asset or line, three components in separate columns, and the
+ quality-convention line under the table.
+7. **Downtime**, ranked by minutes and by frequency, both. The `Other` share
+ stated as its own finding, never ranked.
+8. **Priced losses**, with the rate source named and every unpriced quantity
+ listed with its reason.
+9. **Exceptions**, each with its commitment impact, and one traced reschedule
+ move per significant exception, drafted, never applied.
+10. **Data problems**, a numbered table with its count: classes 1 to 5 and 8
+ only, two or three example rows per finding.
+11. **"Checked, nothing wrong"**, after the table, outside its count: Class 6
+ records, one line each.
+
+---
+
+## Panel 2 — Trend
+
+Drawn from the `pulse_days` records, never from a prior page.
+
+**Series, each over the last 14 and the last 30 production days:**
+
+- OEE, and availability, performance and quality as separate lines
+- Output against plan, one series per unit of measure, never summed across
+ units
+- Downtime minutes, ranked records only
+
+**Charts are inline SVG built in code**, with the numbers baked in, using the
+house tokens: `--accent` for the measured series, `--line` for gridlines,
+`--warn` for a partial day's marker. A table under each chart lists the same
+values, because a chart cannot be checked against the figures block and a
+table can.
+
+**A gap is drawn as a gap.** A day with no record, a record with
+`data_complete: false`, or a null metric breaks the line there. It is never
+plotted as zero and never interpolated across. The table cell reads *not
+computed* or *no run for this day*, with the reason from the record's `gaps`.
+
+**Week-over-week movers.** The seven production days ending on the report day
+against the seven before, from `data_complete` records only, for all four:
+output against plan, OEE by component, downtime minutes and scrap dollars.
+Each mover names the metric, last week's value, this week's and the change,
+and says how many days of seven each side rests on (*"5 of 7 days"*). When
+the earlier window has no complete record, skip the section and say why.
+
+**No stored history yet**, and nothing to back-fill: the panel says *"First
+run: no stored history yet. The trend starts with tomorrow's run."* and holds
+no empty chart.
+
+**On a fallback run** the trend cannot read stored records. Where the exports
+themselves cover earlier days, the panel may be built from them in this run,
+labelled *"from this run's exports, not stored history"*; otherwise it says
+the trend is unavailable because the dashboard could not be read.
+
+---
+
+## Footer
+
+```
+Generated by morning-plant-pulse — Manufacturing · <N> production days stored
+```
+
+The stored-day count is printed from the `query`, and sits in the figures
+block with the rest.
diff --git a/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/short-page.md b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/short-page.md
new file mode 100644
index 00000000..4e1d46ad
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/reference/short-page.md
@@ -0,0 +1,64 @@
+# The short Operations page
+
+Loaded at step 3.4. The page is rendered by `../scripts/render_short.py`
+from the engine's output in the same run; you run it and report it, you do not
+write it.
+
+**It is a second page, not a replacement.** The Operations Command Center
+dashboard (`operations-dashboard.md`) stays exactly as it is: one per site,
+updated in place, trend panel and all. The short page is one HTML file per
+production day, `operations-short-<site>-<day>.html`, written beside the
+figures. Its footer says so: *"The full Operations page is separate; keep
+both."* It never tells anyone to save over the full page.
+
+---
+
+## What is on it, in order
+
+1. **Header**: site, production day, generated time, *"Generated from the
+ morning-plant-pulse run of <date>. Read-only, nothing written to any
+ system."*
+2. **Safety**, when a diagnosis record is safety-flagged or blocked for a
+ missing flag. Above the freshness line, as on the full page: the safety
+ rule in `../../daily-production-report/SKILL.md`, step 7, outranks every
+ other ordering rule.
+3. **Freshness line**: one line, not a table, unless sources disagree. With
+ no plant profile it ends *"Times are plant local, assumed <zone>; no plant
+ profile."*
+ When the day holds fewer shifts than most days it says *"Not a complete
+ plant day: …"* with the shifts that are in.
+4. **Today's decisions**: three at most, in this order: export failure, the
+ machine decision for the worst asset by downtime month to date, a customer
+ quality hold, then anything else by what is at stake. One line after them
+ names the fixes still waiting and links to the full page.
+ - **The machine decision** is four sentences at most: *"Safety status: not
+ assessed"* whenever no diagnosis record exists; the actions; one evidence
+ line; and, only with lockout advice, *"Precaution, not a finding: …"*.
+ - **Lockout** appears only when the asset has no diagnosis record AND its
+ maintenance history shows a repeat failure or a seizure.
+5. **Exceptions**, the whole data window, one card each.
+6. **Day / Week / Month**, controlling Output, Downtime, and Scrap, cost and
+ quality only. Week is Monday to Sunday around the selected day; Month is
+ the 1st through the selected day, marked *Partial month* until the last
+ day. Clicking a day in any breakdown opens that day.
+7. **What this report can't show yet**: exactly three items.
+8. **Data problems**, collapsed, last: waiting on a decision, other gaps, run
+ assumptions, part-number normalizations, *Mismatched records · N*
+ (classes 1–5 and 8 only), integrity flags, checked, nothing wrong.
+9. **Footer**: where the figures live, with row counts, and the placement line.
+
+## The checks it runs before writing anything
+
+No new numbers (each printed number is a figures row, and the page carries
+the row id); no draft wording; the assumed zone named when there is no
+profile; the safety label, the lockout trigger and the four-sentence cap; the
+decision order; the Month view on the last day equal to the full page's month;
+the Provisional label in every view a normalization touched. Any failure: no
+page, and the reply says the short page was not written and why.
+
+## A stop whose duration disagrees with its timestamps
+
+This page holds those minutes out, as the full page does
+(`../../daily-production-report/SKILL.md`, step 4), so the Month view always
+equals the full page. The conflict is listed on the stop's row and under each
+table.
diff --git a/plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/pulse_compute.py b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/pulse_compute.py
new file mode 100644
index 00000000..94bb2525
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/pulse_compute.py
@@ -0,0 +1,2273 @@
+"""Morning plant pulse: every figure the Operations pages print, computed in one place.
+
+ python3 -I pulse_compute.py --exports exports/ --out pulse-output/ \
+ [--day YYYY-MM-DD] [--profile FILE] [--rates FILE] [--diagnoses DIR] \
+ [--manifest manifest.json] [--run-time ISO-8601] [--tz Area/City]
+
+Standard library only, so it runs wherever Python 3.9+ does. It reads the
+export folder (CSV, or XLSX with one table per sheet), recognises each file by
+its header signature, and writes three files to --out:
+
+ figures.csv the figures tab: one row per printed number, with its
+ filter, period and source. A number the pages print
+ and this file does not hold is a defect.
+ pulse_model.json everything the pages are built from, already computed.
+ The page code selects and formats; it does no arithmetic.
+ day_records.json one pulse day record per production day the exports
+ cover, per shared/contracts/pulse-day-record.md.
+
+It then checks itself (subtotals reconcile, no absent value stored as 0) and
+exits 2 with the failures listed if any check fails. Nothing is written to any
+system of record. Rules it applies, by file:
+
+ skills/data-consolidate/reference/join-keys.md the ladder, integrity flags
+ skills/data-consolidate/reference/mismatch-classes.md classes 1-8
+ skills/daily-production-report/reference/oee.md OEE and its traps
+ shared/absent-is-not-zero.md absent is never 0
+"""
+import argparse
+import csv
+import io
+import json
+import os
+import re
+import sys
+import zipfile
+from collections import Counter, OrderedDict, defaultdict
+from datetime import date, datetime, timedelta, timezone
+from xml.etree import ElementTree
+
+try:
+ from zoneinfo import ZoneInfo
+except ImportError: # pragma: no cover - Python < 3.9
+ ZoneInfo = None
+
+ENGINE_VERSION = "1"
+DEFAULT_TZ = "America/New_York"
+LOOKBACK_DAYS = 180
+TERSE_NOTES = {"fixed", "fixed.", "done", "done.", "ok", "ok.", "repaired", "repaired.", "n/a", ""}
+SEIZURE_WORDS = ("seiz", "seized", "seizure", "locked up", "crash")
+
+
+# --------------------------------------------------------------------------
+# Reading files
+# --------------------------------------------------------------------------
+
+def fold(name):
+ """Header comparison form: case-folded, punctuation collapsed to _."""
+ return re.sub(r"[^a-z0-9]+", "_", str(name).strip().lower()).strip("_")
+
+
+def read_csv(path):
+ try:
+ with open(path, newline="", encoding="utf-8-sig") as f:
+ text = f.read()
+ except UnicodeDecodeError: # a spreadsheet's "CSV" is often Windows-1252, not UTF-8
+ with open(path, newline="", encoding="cp1252", errors="replace") as f:
+ text = f.read()
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
+ rows = list(csv.reader(io.StringIO(text)))
+ return rows
+
+
+def read_xlsx(path):
+ """Every sheet of an XLSX, as {sheet_name: rows}, with the standard library."""
+ ns = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships"}
+ out = OrderedDict()
+ with zipfile.ZipFile(path) as z:
+ shared = []
+ if "xl/sharedStrings.xml" in z.namelist():
+ root = ElementTree.fromstring(z.read("xl/sharedStrings.xml"))
+ for si in root.findall("m:si", ns):
+ shared.append("".join(t.text or "" for t in si.iter("{%s}t" % ns["m"])))
+ wb = ElementTree.fromstring(z.read("xl/workbook.xml"))
+ rels = ElementTree.fromstring(z.read("xl/_rels/workbook.xml.rels"))
+ target = {r.get("Id"): r.get("Target") for r in rels}
+ for sh in wb.find("m:sheets", ns):
+ rid = sh.get("{%s}id" % ns["r"])
+ t = target[rid].lstrip("/")
+ t = t if t.startswith("xl/") else "xl/" + t
+ root = ElementTree.fromstring(z.read(t))
+ rows = []
+ for row in root.iter("{%s}row" % ns["m"]):
+ cells = {}
+ for c in row.findall("m:c", ns):
+ ref = re.match(r"([A-Z]+)", c.get("r", "A")).group(1)
+ col = 0
+ for ch in ref:
+ col = col * 26 + ord(ch) - 64
+ v = c.find("m:v", ns)
+ if c.get("t") == "s" and v is not None:
+ val = shared[int(v.text)]
+ elif c.get("t") == "inlineStr":
+ val = "".join(x.text or "" for x in c.iter("{%s}t" % ns["m"]))
+ else:
+ val = v.text if v is not None else ""
+ cells[col - 1] = val
+ if cells:
+ rows.append([cells.get(i, "") for i in range(max(cells) + 1)])
+ out[sh.get("name")] = rows
+ return out
+
+
+def read_flat_yaml(path):
+ """One contract record per file: flat `key: value` lines, as breakdown-diagnosis emits."""
+ rec = OrderedDict()
+ for line in open(path, encoding="utf-8"):
+ if not line.strip() or line.lstrip().startswith("#") or line.startswith((" ", "\t", "-")):
+ continue
+ k, _, v = line.partition(":")
+ v = v.strip()
+ if v.startswith(("'", '"')) and v.endswith(v[0]) and len(v) >= 2:
+ v = v[1:-1]
+ elif v in ("null", "~", ""):
+ v = None
+ elif v in ("true", "false"):
+ v = v == "true"
+ elif v.startswith("[") and v.endswith("]"):
+ v = [x.strip().strip("'\"") for x in v[1:-1].split(",") if x.strip()]
+ rec[k.strip()] = v
+ return rec
+
+
+# --------------------------------------------------------------------------
+# Recognising each export by its header signature
+# --------------------------------------------------------------------------
+
+# Canonical column name -> accepted folded spellings. A plant whose headers
+# differ passes a manifest; this list only spares the common cases.
+ALIASES = {
+ "part_number": ["part_number", "part", "part_no", "item", "item_number", "item_id", "pn"],
+ "work_order": ["work_order", "production_work_order", "wo", "wo_number", "job", "job_number"],
+ "qty_good": ["qty_good", "good", "good_qty", "quantity_good", "qty_complete_good"],
+ "qty_scrap": ["qty_scrap", "scrap", "scrap_qty", "quantity_scrap"],
+ "qty_rework": ["qty_rework", "rework", "rework_qty"],
+ "qty_ordered": ["qty_ordered", "order_qty", "quantity_ordered", "qty"],
+ "uom": ["uom", "unit", "unit_of_measure", "units"],
+ "shift": ["shift", "shift_start"],
+ "production_day": ["production_day", "prod_day", "production_date"],
+ "lot_number": ["lot_number", "lot", "batch", "lot_no", "heat"],
+ "asset_id": ["asset_id", "asset", "machine", "machine_id", "equipment_id"],
+ "cell": ["cell", "line"],
+ "due_date": ["due_date", "due"],
+ "status": ["status"],
+ "site": ["site", "location_site", "subsidiary_site"],
+ "planned_qty": ["planned_qty", "plan_qty", "qty_planned", "planned_quantity"],
+ "plan_date": ["plan_date", "date", "scheduled_date"],
+ "planned_hours": ["planned_hours", "scheduled_hours"],
+ "work_center": ["work_center", "workcenter", "resource"],
+ "started_at": ["started_at", "start", "start_time", "down_start"],
+ "ended_at": ["ended_at", "end", "end_time", "down_end"],
+ "duration_minutes": ["duration_minutes", "minutes", "duration_min", "duration"],
+ "reason_code": ["reason_code", "reason", "code"],
+ "reason_text": ["reason_text", "reason_description", "comment", "description"],
+ "maintenance_wo": ["maintenance_wo", "maintenance_work_order", "mwo", "ticket"],
+ "opened_date": ["opened_date", "opened", "open_date", "created"],
+ "closed_date": ["closed_date", "closed", "close_date"],
+ "type": ["type", "wo_type", "maintenance_type"],
+ "close_out_note": ["close_out_note", "closeout_note", "notes", "note", "resolution"],
+ "ncr_id": ["ncr_id", "ncr", "ncr_number"],
+ "found_at": ["found_at", "found", "date_found", "created_at"],
+ "customer": ["customer", "customer_name"],
+ "description": ["description", "desc"],
+ "std_cost": ["std_cost", "standard_cost", "unit_cost"],
+ "measured": ["measured", "measurement", "value"],
+ "nominal": ["nominal", "spec", "target"],
+ "characteristic": ["characteristic", "feature"],
+ "sales_order": ["sales_order", "so", "so_number"],
+ "promised_date": ["promised_date", "promise_date", "ship_date"],
+ "customer_id": ["customer_id"],
+ "op_seq": ["op_seq", "operation", "oper_no", "op"],
+ "run_min_per_unit": ["run_min_per_unit"],
+ "run_hours_per_unit": ["run_hours_per_unit", "run_hrs_per_unit"],
+ "setup_hours": ["setup_hours", "setup_hrs"],
+ "recorded_at": ["recorded_at", "timestamp", "ts"],
+ "asset_name": ["asset_name", "name"],
+ "location": ["location"],
+ "found_by": ["found_by"],
+ "source_file": ["source_file", "file"],
+ "generated_at": ["generated_at", "generated", "exported_at"],
+ "covers_from": ["covers_from"],
+ "covers_to": ["covers_to"],
+}
+
+# role -> (columns that must all resolve, columns that must not be present)
+ROLES = OrderedDict([
+ ("drop_manifest", (["source_file", "generated_at"], [])),
+ ("ncrs", (["ncr_id"], [])),
+ ("downtime", (["asset_id", "started_at"], ["recorded_at", "opened_date", "closed_date"])),
+ ("maintenance", (["maintenance_wo", "asset_id"], [])),
+ ("historian", (["asset_id", "recorded_at"], [])),
+ ("output", (["work_order", "qty_good"], [])),
+ ("inspection", (["measured", "nominal"], [])),
+ ("routings", (["part_number", "op_seq"], [])),
+ ("plan", (["part_number", "planned_qty"], [])),
+ ("work_orders", (["work_order", "part_number", "qty_ordered", "status"], ["qty_good", "closed_date", "promised_date"])),
+ ("sales_orders", (["sales_order", "part_number"], [])),
+ ("customers", (["customer_id", "customer"], ["part_number", "ncr_id", "sales_order"])),
+ ("items", (["part_number", "std_cost"], ["work_order", "op_seq"])),
+ ("assets", (["asset_id", "location"], ["started_at", "maintenance_wo"])),
+])
+
+# Files the pulse recognises but does not read.
+UNUSED_SIGNATURES = [
+ ("purchase_orders", ["po_number"]), ("suppliers", ["supplier_name"]),
+ ("bom", ["qty_per_piece"]), ("closed_job_costs", ["actual_material_cost"]), ("capacity", ["available_hours"]),
+]
+
+
+def resolve_columns(header, overrides=None):
+ folded = {fold(h): h for h in header}
+ cols = {}
+ for canon, spellings in ALIASES.items():
+ for s in spellings:
+ if s in folded:
+ cols[canon] = folded[s]
+ break
+ for canon, actual in (overrides or {}).items():
+ if actual in header:
+ cols[canon] = actual
+ return cols
+
+
+def recognise(header, overrides=None):
+ cols = resolve_columns(header, overrides)
+ folded = {fold(h) for h in header}
+ for role, (must, must_not) in ROLES.items():
+ if all(c in cols for c in must) and not any(c in cols and fold(cols[c]) in folded for c in must_not):
+ # "description" doubles as reason text; only downtime keeps it.
+ return role, cols
+ for role, marks in UNUSED_SIGNATURES:
+ if all(m in folded for m in marks):
+ return "unused:" + role, cols
+ return None, cols
+
+
+class Table:
+ def __init__(self, name, role, header, rows, cols):
+ self.name, self.role, self.header, self.cols = name, role, header, cols
+ self.rows = []
+ for r in rows:
+ if not any(str(v).strip() for v in r):
+ continue
+ rec = {h: (r[i] if i < len(r) else "") for i, h in enumerate(header)}
+ self.rows.append(rec)
+
+ def get(self, row, canon, default=""):
+ c = self.cols.get(canon)
+ return row.get(c, default) if c else default
+
+ def has(self, canon):
+ return canon in self.cols
+
+
+def load_exports(folder, manifest):
+ tables, skipped = {}, []
+ role_override = (manifest or {}).get("roles", {})
+ col_override = (manifest or {}).get("columns", {})
+ for fn in sorted(os.listdir(folder)):
+ path = os.path.join(folder, fn)
+ if not os.path.isfile(path) or fn.startswith("."):
+ continue
+ low = fn.lower()
+ if low.endswith(".csv"):
+ sheets = {fn: read_csv(path)}
+ elif low.endswith(".xlsx"):
+ try:
+ sheets = {"%s[%s]" % (fn, k): v for k, v in read_xlsx(path).items()}
+ except Exception as e: # noqa: BLE001 - report, never crash on one file
+ skipped.append({"file": fn, "why": "could not read XLSX: %s" % e})
+ continue
+ else:
+ skipped.append({"file": fn, "why": "not CSV or XLSX"})
+ continue
+ for name, rows in sheets.items():
+ if not rows:
+ skipped.append({"file": name, "why": "empty"})
+ continue
+ header = [h.strip() for h in rows[0]]
+ forced = role_override.get(name) or role_override.get(fn)
+ role, cols = recognise(header, col_override.get(forced) if forced else None)
+ if forced:
+ role = forced
+ cols = resolve_columns(header, col_override.get(forced))
+ else: # a columns entry needs no roles entry: it applies to the file it makes recognisable as that role
+ for want, over in col_override.items():
+ r2, c2 = recognise(header, over)
+ if r2 == want and any(v in header for v in over.values()):
+ role, cols = r2, c2
+ break
+ if role is None:
+ skipped.append({"file": name, "why": "header not recognised: " + ", ".join(header)})
+ continue
+ if role.startswith("unused:"):
+ skipped.append({"file": name, "why": "recognised as %s; the pulse does not read it" % role[7:]})
+ continue
+ if role in tables:
+ skipped.append({"file": name, "why": "second %s file; %s used" % (role, tables[role].name)})
+ continue
+ tables[role] = Table(name, role, header, rows[1:], cols)
+ return tables, skipped
+
+
+# --------------------------------------------------------------------------
+# The plant profile (## Plant context)
+# --------------------------------------------------------------------------
+
+def parse_rates(path):
+ """The downtime rate from the plant's rates file (## Plant rates, at
+ plant_setup.py's rates_path). {downtime_rate, downtime_rate_kind} or {}."""
+ if not path or not os.path.exists(path):
+ return {}
+ text = open(path, encoding="utf-8").read()
+ if not re.search(r"^##\s*Plant rates\s*$", text, re.M):
+ return {}
+ dc = re.search(r"[Dd]owntime cost per hour[:*| \t]*(?:[A-Za-z]+[ \t]+)?[$~]?[ \t]*(\d[\d,]*(?:\.\d+)?)", text)
+ if not dc or "not set" in dc.group(0):
+ return {}
+ return {"downtime_rate": float(dc.group(1).replace(",", "")),
+ "downtime_rate_kind": "profile_placeholder" if "placeholder" in dc.group(0).lower() else "profile_confirmed"}
+
+
+def parse_profile(path):
+ if not path or not os.path.exists(path):
+ return None
+ text = open(path, encoding="utf-8").read()
+ m = re.search(r"^##\s*Plant context\s*$(.*?)(?=^##\s(?!#)|\Z)", text, re.M | re.S)
+ if not m:
+ return None
+ body = m.group(1)
+ p = {"source": path}
+
+ def field(label):
+ mm = re.search(r"\*\*%s:\*\*\s*(.+)" % re.escape(label), body)
+ return mm.group(1).strip() if mm else None
+
+ p["company"] = field("Company")
+ sites = field("Sites")
+ if sites:
+ names = [x for x in re.split(r"\s+-\s+|,", sites) if x.strip()] or [sites]
+ p["site"] = re.sub(r"\s*\(default\)", "", next((x for x in names if "(default)" in x), names[0])).strip()
+ tz = field("Time zone") or field("Timezone")
+ if tz:
+ p["tz"] = tz.split()[0]
+ ds = field("Production day")
+ if ds and re.match(r"^\d{4}-\d{2}-\d{2}$", ds):
+ p["production_day"] = ds
+ ds = None
+ if ds:
+ mm = re.search(r"starts\s+(\d{1,2}:\d{2})", ds)
+ if mm:
+ p["day_start"] = mm.group(1)
+ p["day_boundary_text"] = ds
+ mm = re.match(r"\d{1,2}:\d{2}", field("Production day starts") or "")
+ if mm:
+ p.setdefault("day_start", mm.group(0))
+ ppt = field("Planned production time")
+ if ppt:
+ mm = re.search(r"([\d.]+)\s*hours?\s*per\s*shift", ppt)
+ if mm:
+ p["planned_hours_per_shift"] = float(mm.group(1))
+ p["planned_production_time_text"] = ppt
+ shifts = field("Shifts")
+ if shifts:
+ p["shifts"] = re.findall(r"(\d{1,2}:\d{2})\s*-\s*\d{1,2}:\d{2}", shifts)
+ elif field("Shift pattern"):
+ p["shifts"] = re.findall(r"\d{1,2}:\d{2}", field("Shift pattern"))
+ rates = field("Rates") or ""
+ dc = re.search(r"[Dd]owntime cost per hour[:*| \t]*(?:[A-Za-z]+[ \t]+)?[$~]?[ \t]*(\d[\d,]*(?:\.\d+)?)", body)
+ if dc and "not set" not in dc.group(0):
+ p["downtime_rate"] = float(dc.group(1).replace(",", ""))
+ p["downtime_rate_kind"] = "profile_placeholder" if "placeholder" in dc.group(0).lower() else "profile_confirmed"
+ p["rates_text"] = rates
+ # Approved normalizations: lines like - `4471B` -> `PN-4471-B`
+ ap = re.search(r"^###\s*Approved normalizations\s*$(.*?)(?=^###|\Z)", body, re.M | re.S)
+ p["approved"] = {}
+ if ap:
+ for a, b in re.findall(r"`([^`]+)`\s*(?:->|→|=>)\s*`([^`]+)`", ap.group(1)):
+ p["approved"][a] = b
+ for line in ap.group(1).splitlines():
+ ticks = re.findall(r"`([^`]*)`", line)
+ if line.strip().startswith("|") and len(ticks) >= 2:
+ p["approved"][ticks[0]] = ticks[1]
+ # Reason codes table
+ rc = re.search(r"^###\s*Reason codes\s*$(.*?)(?=^###|\Z)", body, re.M | re.S)
+ p["reason_codes"] = {}
+ if rc:
+ for code, meaning in re.findall(r"^\|\s*([^|\s][^|]*?)\s*\|\s*([^|]+?)\s*\|\s*$", rc.group(1), re.M):
+ if code.lower() not in ("code", "---", "-") and not set(code) <= set("-: "):
+ p["reason_codes"][code] = meaning
+ # Machine classes: work centers -> cell
+ p["cells"] = {}
+ mc = re.search(r"Machine classes:(.*?)(?=^###|\Z)", body, re.M | re.S)
+ if mc:
+ for line in mc.group(1).splitlines():
+ parts = [x.strip() for x in line.strip().strip("|").split("|")]
+ if len(parts) >= 3 and parts[0] and not set(parts[0]) <= set("-: ") and parts[0] != "Machine class":
+ for wc in parts[1].split(","):
+ p["cells"][wc.strip()] = parts[2].split(",")[0].strip()
+ return p
+
+
+# --------------------------------------------------------------------------
+# Figures
+# --------------------------------------------------------------------------
+
+class Figures:
+ def __init__(self):
+ self.rows = []
+ self.ids = set()
+
+ def add(self, fid, label, value, source, filt, period="window", unit=""):
+ if fid in self.ids:
+ raise ValueError("duplicate figure id " + fid)
+ self.ids.add(fid)
+ self.rows.append({"id": fid, "figure": label, "value": value, "unit": unit,
+ "period": period, "source": source, "filter": filt})
+ return value
+
+ SHORT_PREFIXES = ("sp-", "decision.", "remaining.", "per.sp-", "dt.sp-")
+
+ def write(self, path, short_path=None):
+ """figures.csv holds the full page's rows; the short page's view roll-ups go to short_path."""
+ full = [r for r in self.rows if not r["id"].startswith(self.SHORT_PREFIXES)]
+ short = [r for r in self.rows if r["id"].startswith(self.SHORT_PREFIXES)]
+ self._write(path, full)
+ if short_path and short:
+ self._write(short_path, short)
+
+ @staticmethod
+ def _write(path, rows):
+ with open(path, "w", newline="", encoding="utf-8") as f:
+ w = csv.DictWriter(f, fieldnames=["id", "figure", "value", "unit", "period", "source", "filter"])
+ w.writeheader()
+ for r in rows:
+ v = r["value"]
+ if v is None:
+ v = "not computable"
+ elif isinstance(v, float):
+ v = ("%.4f" % v).rstrip("0").rstrip(".")
+ w.writerow(dict(r, value=v))
+
+
+# --------------------------------------------------------------------------
+# Helpers
+# --------------------------------------------------------------------------
+
+def num(s):
+ s = str(s).strip().replace(",", "")
+ if s == "":
+ return None
+ try:
+ return float(s)
+ except ValueError:
+ return None
+
+
+def intish(x):
+ return int(x) if x is not None and float(x).is_integer() else x
+
+
+def excel_serial(s):
+ """A date cell read from XLSX arrives as its serial number (days since 1899-12-30)."""
+ if re.match(r"^\d{5}(\.\d+)?$", s):
+ return datetime(1899, 12, 30) + timedelta(seconds=round(float(s) * 86400))
+ return None
+
+
+def parse_ts(s, tz):
+ s = str(s).strip()
+ if not s:
+ return None
+ try:
+ d = datetime.fromisoformat(s.replace("Z", "+00:00"))
+ except ValueError:
+ d = excel_serial(s)
+ if d is None:
+ return None
+ if d.tzinfo is None:
+ d = d.replace(tzinfo=tz)
+ return d.astimezone(tz)
+
+
+def parse_day(s):
+ s = str(s).strip()
+ try:
+ return date.fromisoformat(s[:10])
+ except ValueError:
+ d = excel_serial(s)
+ return d.date() if d else None
+
+
+def hm(s):
+ h, m = s.split(":")
+ return int(h) * 60 + int(m)
+
+
+def local_str(d):
+ return d.strftime("%Y-%m-%d %H:%M") + " (plant local)" if d else None
+
+
+def comp_rank(items, key):
+ """Competition ranking: 1, 2, 2, 4. items sorted by key descending."""
+ ranks, prev, r = [], object(), 0
+ for i, it in enumerate(items):
+ k = key(it)
+ if k != prev:
+ r = i + 1
+ prev = k
+ ranks.append(r)
+ return ranks
+
+
+def week_of(d):
+ start = d - timedelta(days=d.weekday())
+ return start, start + timedelta(days=6)
+
+
+# --------------------------------------------------------------------------
+# The normalization ladder, toward the item master
+# --------------------------------------------------------------------------
+
+REV_RE = re.compile(r"\s*(?:rev\.?|revision|r)\s*[-.]?\s*([A-Za-z0-9]+)\s*$", re.I)
+
+
+def punct(s):
+ return re.sub(r"[^A-Z0-9]", "", s.upper())
+
+
+class Ladder:
+ """Rungs 1-5 of join-keys.md. Returns (canonical, class, rule, revision)."""
+
+ def __init__(self, master, approved):
+ self.master = list(master)
+ self.set = set(self.master)
+ self.approved = approved or {}
+ self.cache = {}
+
+ def match(self, raw):
+ if raw in self.cache:
+ return self.cache[raw]
+ res = self._match(raw)
+ self.cache[raw] = res
+ return res
+
+ def _match(self, raw):
+ if raw in self.set:
+ return raw, None, None, None
+ if raw in self.approved and self.approved[raw] in self.set:
+ return self.approved[raw], "approved", "approved normalization", None
+ t = raw.strip()
+ if t in self.set:
+ return t, 5, "trim whitespace", None
+ for m in self.master:
+ if t.lower() == m.lower():
+ return m, 5, "trim whitespace and fold case" if t != raw else "fold case", None
+ key = punct(t)
+ hits = [m for m in self.master if punct(m) == key]
+ if len(hits) == 1:
+ return hits[0], 2, "normalize punctuation", None
+ prefixed = [m for m in self.master if re.match(r"^[A-Za-z]+[-_ ]", m)
+ and punct(re.sub(r"^[A-Za-z]+[-_ ]", "", m)) == key]
+ if len(prefixed) == 1:
+ pre = re.match(r"^([A-Za-z]+)[-_ ]", prefixed[0]).group(1)
+ return prefixed[0], 2, "normalize punctuation; prefix %s- restored" % pre, None
+ if len(prefixed) > 1:
+ return None, 1, "ambiguous: " + ", ".join(prefixed), None
+ if t.isdigit():
+ pad = [m for m in self.master if m.isdigit() and len(m) > len(t) and m.lstrip("0") == t.lstrip("0")]
+ if len(pad) == 1:
+ return pad[0], 3, "restore leading zeros to width %d" % len(pad[0]), None
+ rv = REV_RE.search(t)
+ if rv:
+ base = t[:rv.start()].strip()
+ sub = self._match(base) if base != t else (None, None, None, None)
+ if sub[0]:
+ return sub[0], 4, "strip revision suffix (Rev %s kept in its own column)" % rv.group(1), rv.group(1)
+ return None, 1, "no rung matches the item master", None
+
+
+# --------------------------------------------------------------------------
+# The engine
+# --------------------------------------------------------------------------
+
+class Pulse:
+ def __init__(self, args):
+ self.args = args
+ self.F = Figures()
+ self.manifest = json.load(open(args.manifest)) if args.manifest else {}
+ self.profile = parse_profile(args.profile)
+ rates = parse_rates(getattr(args, "rates", None))
+ if rates: # the rates file wins over a value left in an older profile
+ self.profile = dict(self.profile or {}, **rates)
+ p = self.profile or {}
+ self.assumptions = []
+ tzname = args.tz or p.get("tz")
+ if not tzname:
+ tzname = DEFAULT_TZ
+ self.assumptions.append("Times are plant local, assumed %s; %s." % (
+ tzname, "the plant profile sets no time zone" if self.profile else "no plant profile"))
+ self.tzname = tzname
+ self.tz = ZoneInfo(tzname) if ZoneInfo else timezone(timedelta(hours=-4))
+ self.run_time = parse_ts(args.run_time, self.tz) if args.run_time else datetime.now(self.tz)
+ self.T, self.skipped = load_exports(args.exports, self.manifest)
+ self.model = OrderedDict()
+ self.checks = []
+
+ # -- small accessors -------------------------------------------------
+ def t(self, role):
+ return self.T.get(role)
+
+ def check(self, ok, what):
+ self.checks.append({"check": what, "ok": bool(ok)})
+
+ # -- context -----------------------------------------------------------
+ def context(self):
+ p = self.profile or {}
+ out = self.t("output")
+ site = p.get("site")
+ if not site:
+ for role in ("output", "work_orders", "plan", "items"):
+ tb = self.t(role)
+ if tb and tb.has("site"):
+ vals = {tb.get(r, "site") for r in tb.rows if tb.get(r, "site")}
+ if len(vals) == 1:
+ site = vals.pop()
+ break
+ self.site = site or "Plant"
+ # One run reports one site: other sites' rows in a shared export are left out, and the run says so.
+ seen = sorted({tb.get(r, "site").strip() for tb in self.T.values() if tb.has("site") for r in tb.rows} - {""})
+ if len(seen) > 1 and self.site.lower() in [s.lower() for s in seen]:
+ for tb in self.T.values():
+ if tb.has("site"):
+ tb.rows = [r for r in tb.rows if tb.get(r, "site").strip().lower() in ("", self.site.lower())]
+ self.assumptions.append("The exports carry more than one site (%s); only %s rows are used." % (", ".join(seen), self.site))
+ elif len(seen) > 1:
+ self.assumptions.append("The exports carry more than one site (%s) and none is %s; their rows are pooled." % (
+ ", ".join(seen), self.site))
+ elif seen and seen[0].lower() != self.site.lower():
+ self.assumptions.append("The exports are marked site %s, not %s, the site this run reports under; check which "
+ "site the export is for." % (seen[0], self.site))
+ # Day start: the profile's, else the earliest shift label in the MES.
+ if p.get("day_start"):
+ self.day_start = p["day_start"]
+ self.day_rule = p.get("day_boundary_text") or "day starts %s" % self.day_start
+ else:
+ why = "the plant profile sets no day start" if self.profile else "no plant profile"
+ shifts = sorted({out.get(r, "shift") for r in out.rows if re.match(r"^\d{1,2}:\d{2}$", out.get(r, "shift"))},
+ key=hm) if out and out.has("shift") else []
+ self.day_start = shifts[0] if shifts else "00:00"
+ self.day_rule = ("day starts %s, the earliest MES shift; a shift belongs to the production day it "
+ "starts on (assumed; %s)" % (self.day_start, why)) if shifts else \
+ ("calendar day, plant local (assumed; %s and no MES shift labels)" % why)
+ self.assumptions.append("Production-day rule: " + self.day_rule + ".")
+ self.model["context"] = OrderedDict([
+ ("engine_version", ENGINE_VERSION), ("site", self.site),
+ ("company", p.get("company")), ("profile", bool(self.profile)),
+ ("profile_source", p.get("source")), ("time_zone", self.tzname),
+ ("time_zone_assumed", not (self.args.tz or p.get("tz"))),
+ ("day_start", self.day_start), ("day_boundary", self.day_rule),
+ ("run_time", self.run_time.isoformat()), ("run_time_local", local_str(self.run_time)),
+ ("assumptions", self.assumptions),
+ ("files_used", {r: tb.name for r, tb in self.T.items()}),
+ ("files_not_used", self.skipped),
+ ])
+
+ def prod_day_of(self, ts):
+ """Production day for a plant-local timestamp under the day-start rule."""
+ return (ts - timedelta(minutes=hm(self.day_start))).date()
+
+ # -- normalization -------------------------------------------------------
+ def normalize(self):
+ items = self.t("items")
+ self.master = OrderedDict()
+ self.master_source = None
+ if items:
+ for r in items.rows:
+ self.master[items.get(r, "part_number").strip()] = r
+ self.master_source = items.name + " (item master)"
+ else:
+ # No item master: the ERP work orders, then the plan, stand in, and the page says so.
+ for role in ("work_orders", "plan"):
+ tb = self.t(role)
+ if tb and tb.has("part_number"):
+ for r in tb.rows:
+ self.master.setdefault(tb.get(r, "part_number").strip(), {})
+ self.master_source = "%s part numbers (no item master in the drop)" % tb.name
+ break
+ approved = (self.profile or {}).get("approved", {})
+ approved.update(self.manifest.get("approved_normalizations", {}))
+ self.ladder = Ladder(self.master.keys(), approved)
+ self.norm_log = OrderedDict()
+ self.unmatched_parts = OrderedDict()
+ for role in ("plan", "output", "work_orders", "inspection", "ncrs", "sales_orders", "routings"):
+ tb = self.t(role)
+ if not tb or not tb.has("part_number"):
+ continue
+ for r in tb.rows:
+ raw = tb.get(r, "part_number")
+ canon, cls, rule, rev = self.ladder.match(raw) if self.master else (raw, None, None, None)
+ r["_part"] = canon
+ r["_part_class"] = cls
+ r["_part_verbatim"] = raw
+ r["_provisional"] = cls in (2, 3, 4, 5)
+ if rev:
+ r["_revision_stripped"] = rev
+ if cls in (2, 3, 4, 5, "approved"):
+ k = (tb.name, raw)
+ e = self.norm_log.setdefault(k, OrderedDict([
+ ("source", tb.name), ("role", role), ("verbatim", raw), ("canonical", canon),
+ ("class", cls), ("rule", rule), ("status", "approved" if cls == "approved" else
+ "proposed, awaiting approval"), ("rows", 0)]))
+ e["rows"] += 1
+ elif cls == 1 and role in ("plan", "output", "inspection", "ncrs", "sales_orders"):
+ k = (tb.name, raw)
+ e = self.unmatched_parts.setdefault(k, {"source": tb.name, "verbatim": raw, "why": rule, "rows": 0})
+ e["rows"] += 1
+ for n, e in enumerate(self.norm_log.values()):
+ self.F.add("norm.%d.rows" % n, "Rows resting on %s normalization %r -> %s (%s)" % (
+ e["status"].split(",")[0], e["verbatim"], e["canonical"], e["rule"]), e["rows"], e["source"],
+ "part_number == %r" % e["verbatim"])
+ self.model["normalizations"] = list(self.norm_log.values())
+ self.model["context"]["part_reference"] = self.master_source
+
+ # -- freshness and coverage -------------------------------------------------
+ def freshness(self):
+ req = self.args.day or (self.profile or {}).get("production_day")
+ cov = OrderedDict()
+ spec = [("plan", "plan_date", "date"), ("output", "production_day", "date"),
+ ("downtime", "started_at", "ts"), ("inspection", "production_day", "date"),
+ ("ncrs", "found_at", "ts"), ("maintenance", "opened_date", "date"),
+ ("work_orders", "due_date", "date"), ("sales_orders", "promised_date", "date"),
+ ("historian", "recorded_at", "ts")]
+ newest_ts = None
+ landed_dt = {}
+ future = []
+ unread = {}
+ for role, col, kind in spec:
+ tb = self.t(role)
+ if not tb or not tb.has(col):
+ continue
+ days = []
+ for r in tb.rows:
+ v = tb.get(r, col)
+ if str(v).strip() and (parse_ts(v, self.tz) if kind == "ts" else parse_day(v)) is None:
+ unread.setdefault(role, []).append(str(v).strip())
+ if kind == "ts":
+ d = parse_ts(v, self.tz)
+ if d is None:
+ continue
+ if role in ("downtime", "historian", "ncrs"):
+ newest_ts = d if newest_ts is None or d > newest_ts else newest_ts
+ if d > self.run_time:
+ future.append({"source": tb.name, "value": v})
+ days.append(self.prod_day_of(d) if role == "downtime" else d.date())
+ else:
+ d = parse_day(v)
+ if d:
+ days.append(d)
+ if days:
+ path = os.path.join(self.args.exports, tb.name.split("[")[0])
+ mtime = datetime.fromtimestamp(os.path.getmtime(path), self.tz) if os.path.exists(path) else None
+ landed_dt[role] = mtime
+ cov[role] = OrderedDict([("file", tb.name), ("first", str(min(days))), ("last", str(max(days))),
+ ("rows", len(tb.rows)), ("landed", local_str(mtime)),
+ ("activity", role in ("plan", "output", "downtime", "inspection"))])
+ man = self.t("drop_manifest")
+ if man:
+ for r in man.rows:
+ fn = man.get(r, "source_file").strip()
+ for c in cov.values():
+ if c["file"] == fn:
+ g = parse_ts(man.get(r, "generated_at"), self.tz)
+ c["landed"] = local_str(g)
+ c["landed_source"] = "drop manifest generated_at"
+ for role_, c_ in cov.items():
+ if c_ is c and g:
+ landed_dt[role_] = g
+ if g:
+ c["landed_days_before_run"] = (self.run_time.date() - g.date()).days
+ for role, c in cov.items():
+ self.F.add("cov.%s" % role, "Coverage, %s" % c["file"], "%s to %s" % (c["first"], c["last"]), c["file"],
+ "min/max of the date column")
+ act = [c for c in cov.values() if c["activity"]]
+ # A plan looks forward, so output and downtime date the data; the plan only when neither landed, never past the run date.
+ run_day = self.run_time.date()
+ newest_day = max((min(date.fromisoformat(cov[r]["last"]), run_day) for r in ("output", "downtime") if r in cov),
+ default=min(date.fromisoformat(cov["plan"]["last"]), run_day) if "plan" in cov else None)
+ day = date.fromisoformat(req) if req else None
+ need = ("plan", "output", "downtime")
+ if day is None:
+ # Latest production day every needed export covers; else the newest any covers.
+ ends = [date.fromisoformat(cov[r]["last"]) for r in need if r in cov]
+ day = min(ends) if len(ends) == len(need) else newest_day
+ self.day_source = "latest complete production day in the exports (no day requested)"
+ else:
+ self.day_source = "requested" if self.args.day else "set in the plant context"
+ self.day = day
+ missing = [r for r in need if r not in self.T]
+ not_cover = [r for r in need if r in cov and not (cov[r]["first"] <= str(day) <= cov[r]["last"])]
+ gaps = []
+ names = {"plan": "planning export", "output": "production (MES output) export", "downtime": "downtime export"}
+ for r in missing:
+ gaps.append("%s did not land" % names[r])
+ for r in not_cover:
+ gaps.append("%s has no rows for %s (covers %s to %s)" % (names[r], day, cov[r]["first"], cov[r]["last"]))
+ for r in need:
+ if unread.get(r): # rows whose date cannot be read are in no day: a gap, never silence
+ gaps.append("%s has %d rows whose date could not be read (first: %r); dates must be YYYY-MM-DD" % (
+ names[r], len(unread[r]), unread[r][0]))
+ for r in need: # recognised, has rows, but no date column resolved (or it is blank): its rows are in no day
+ if self.t(r) and self.t(r).rows and r not in cov and not unread.get(r):
+ gaps.append("%s has no readable date column, so none of its rows can be placed in a production day" % names[r])
+ self.data_complete = not gaps
+ # Activity window intersection (class 7 reference)
+ inter = None
+ if act:
+ lo = max(c["first"] for c in act)
+ hi = min(c["last"] for c in act)
+ inter = (lo, hi) if lo <= hi else None
+ age = (self.run_time.date() - newest_day).days if newest_day else None
+ # The newest refresh the figures rest on: when the activity exports landed (manifest, else file time).
+ landed = [landed_dt[r] for r in ("plan", "output", "downtime") if landed_dt.get(r)]
+ as_of = max(landed) if landed else newest_ts
+ as_of_basis = "when the plan, output and downtime exports landed (drop manifest, else file time)" if landed \
+ else ("newest event timestamp in the exports" if newest_ts else "no source could be dated")
+ self.model["freshness"] = OrderedDict([
+ ("production_day", str(day) if day else None), ("day_source", self.day_source),
+ ("newest_production_day", str(newest_day) if newest_day else None),
+ ("days_old", age), ("data_as_of", as_of.isoformat() if as_of else None),
+ ("data_as_of_local", local_str(as_of)), ("data_as_of_basis", as_of_basis),
+ ("newest_event", local_str(newest_ts)), ("data_complete", self.data_complete), ("gaps", gaps),
+ ("coverage", cov), ("activity_window", list(inter) if inter else None),
+ ("future_timestamps", future),
+ ("sources_disagree", len({(c["first"], c["last"]) for c in act}) > 1),
+ ])
+ self.F.add("fresh.days_old", "Days between the newest production day and the run date", age,
+ "run clock vs exports", "run date - newest production day")
+ self.F.add("fresh.future", "Records timestamped after the run time (future_timestamp)", len(future),
+ "downtime, historian, NCR exports", "timestamp > run time; due and promised dates excluded")
+ if day:
+ self.F.add("fresh.day", "Production day reported", str(day), "exports", self.day_source)
+ self.window = (date.fromisoformat(inter[0]), date.fromisoformat(inter[1])) if inter else None
+
+ # -- production output and the work order join --------------------------
+ def output(self):
+ out, wos = self.t("output"), self.t("work_orders")
+ self.WO = OrderedDict()
+ if wos:
+ for r in wos.rows:
+ self.WO[wos.get(r, "work_order").strip()] = r
+ self.out_rows = []
+ self.dup_list = []
+ self.unit_conflicts = OrderedDict()
+ self.shared_lots = {}
+ self.unit_ref, self.unit_ref_short = None, "item master"
+ problems, integrity = [], defaultdict(list)
+ if not out:
+ self.model["output_rows"] = None
+ self.problems, self.integrity = problems, integrity
+ return
+ items = self.t("items")
+ self.unit_ref = "item master" if items and items.has("uom") else None
+ dominant = None
+ if not self.unit_ref and out.has("uom"):
+ c = Counter(out.get(r, "uom").strip() for r in out.rows if out.get(r, "uom").strip())
+ if c:
+ dominant = c.most_common(1)[0][0]
+ self.unit_ref = "the unit most MES rows carry (%s); no item master in the drop, so unconfirmed" % dominant
+ self.model["context"]["unit_reference"] = self.unit_ref
+ self.unit_ref_short = "item master" if self.unit_ref == "item master" else "rest of the MES (no item master)"
+ grain = defaultdict(list)
+ for i, r in enumerate(out.rows):
+ wo = out.get(r, "work_order").strip()
+ day = parse_day(out.get(r, "production_day"))
+ good = num(out.get(r, "qty_good"))
+ scrap_raw = out.get(r, "qty_scrap") if out.has("qty_scrap") else None
+ scrap = num(scrap_raw) if scrap_raw is not None else None
+ unit = out.get(r, "uom").strip() if out.has("uom") else None
+ part = r.get("_part")
+ item_unit = (self.master.get(part, {}).get(items_col(items, "uom"), None) if part and items else dominant)
+ rec = OrderedDict([
+ ("i", i), ("work_order", wo), ("part", part_key(r)), ("part_verbatim", r.get("_part_verbatim")),
+ ("part_class", r.get("_part_class")), ("provisional", r.get("_provisional", False)),
+ ("good", good), ("scrap", scrap), ("scrap_recorded", scrap is not None),
+ ("scrap_column", out.has("qty_scrap")), ("rework", num(out.get(r, "qty_rework")) if out.has("qty_rework") else None),
+ ("unit", unit), ("item_unit", item_unit),
+ ("unit_conflict", bool(unit and item_unit and unit.strip().lower() != str(item_unit).strip().lower())),
+ ("shift", out.get(r, "shift")), ("day", str(day) if day else None),
+ ("lot", out.get(r, "lot_number").strip() if out.has("lot_number") else None),
+ ("asset", out.get(r, "asset_id").strip() if out.has("asset_id") else None),
+ ("cell", out.get(r, "cell").strip() if out.has("cell") else None),
+ ("in_erp", wo in self.WO), ("held_out", None if good is not None else "no readable good quantity")])
+ self.out_rows.append(rec)
+ grain[(wo, rec["shift"], rec["day"])].append(rec)
+ # Class 8 at the tab's grain: work order, shift, production day.
+ dups = []
+ for (wo, sh, d), rs in grain.items():
+ if len(rs) > 1:
+ for x in rs:
+ x["held_out"] = "duplicate key"
+ allrows = [x for x in self.out_rows if x["work_order"] == wo]
+ dups.append(OrderedDict([
+ ("work_order", wo), ("shift", sh), ("day", d), ("rows_for_key", len(allrows)),
+ ("rows_colliding", len(rs)), ("good_values", [intish(x["good"]) for x in rs]),
+ ("other_rows", [OrderedDict([("shift", x["shift"]), ("day", x["day"]), ("good", intish(x["good"]))])
+ for x in allrows if x not in rs])]))
+ for n, d in enumerate(dups):
+ allvals = [intish(x["good"]) for x in self.out_rows if x["work_order"] == d["work_order"]]
+ d["all_good_values"] = allvals
+ self.F.add("dup.%d.values" % n, "Good on every row of %s" % d["work_order"], " / ".join(str(v) for v in allvals),
+ out.name, "work_order == %r; none picked or summed" % d["work_order"])
+ self.F.add("dup.%d.rows" % n, "Class 8: rows for %s (all shifts)" % d["work_order"], d["rows_for_key"],
+ out.name, "work_order == %r" % d["work_order"])
+ self.F.add("dup.%d.colliding" % n, "Class 8: rows colliding at %s %s %s" % (d["work_order"], d["day"], d["shift"]),
+ d["rows_colliding"], out.name, "work_order, shift and production_day equal; good " +
+ " / ".join(str(g) for g in d["good_values"]))
+ problems.append(OrderedDict([
+ ("class", 8), ("name", "Duplicate key"), ("key", d["work_order"]),
+ ("what", "%s has %d MES rows; %d collide on %s at %s (good %s, none picked or summed)%s" % (
+ d["work_order"], d["rows_for_key"], d["rows_colliding"], d["day"], d["shift"],
+ " / ".join(str(g) for g in d["good_values"]),
+ "; " + "; ".join("the %s on the %s shift is its own shift" % (o["good"], o["shift"]) for o in d["other_rows"])
+ if d["other_rows"] else "")),
+ ("rows", d["rows_colliding"]), ("fix", "None automatic. Both rows held out of every total until someone says which is real.")]))
+ self.dup_list = dups
+ # Lot on two different parts: class 8. Same lot across work orders of one part is traceability, not a duplicate.
+ lot_parts = defaultdict(set)
+ lot_wos = defaultdict(set)
+ for x in self.out_rows:
+ if x["lot"]:
+ lot_parts[x["lot"]].add(x["part"])
+ lot_wos[x["lot"]].add(x["work_order"])
+ for lot, parts in lot_parts.items():
+ if len(parts) > 1:
+ problems.append(OrderedDict([("class", 8), ("name", "Duplicate key"), ("key", lot),
+ ("what", "Lot %s is on %d different parts: %s" % (lot, len(parts), ", ".join(sorted(map(str, parts))))),
+ ("rows", sum(1 for x in self.out_rows if x["lot"] == lot)),
+ ("fix", "None automatic. The plant says which part the lot belongs to.")]))
+ self.shared_lots = {l: sorted(w) for l, w in lot_wos.items() if len(w) > 1 and len(lot_parts[l]) == 1}
+ # Class 1: output against a work order the ERP does not hold.
+ if wos:
+ orphans = [x for x in self.out_rows if not x["in_erp"]]
+ self.F.add("orphan.count", "Class 1: MES rows whose production work order is not in the ERP", len(orphans),
+ out.name + " vs " + wos.name, "work_order not in ERP")
+ for x in orphans:
+ x["held_out"] = x["held_out"] or "orphan"
+ problems.append(OrderedDict([
+ ("class", 1), ("name", "Orphan record"), ("key", x["work_order"]),
+ ("what", "%s in the MES (%s, %s good, %s, %s shift) is not in the ERP" % (
+ x["work_order"], x["part_verbatim"], fmtq(x["good"]), x["day"], x["shift"])),
+ ("rows", 1), ("fix", "None automatic: an unauthorized job, a deleted order, or a typo. A question for whoever ran that shift.")]))
+ # Part on the MES row disagrees with the ERP work order's part.
+ for x in self.out_rows:
+ if x["in_erp"] and x["part_verbatim"] and x["part_class"] != 1:
+ erp_part = self.WO[x["work_order"]].get("_part")
+ if erp_part and erp_part != x["part"]:
+ integrity["mes_part_differs"].append(x)
+ # Unit conflicts and absent scrap.
+ units = defaultdict(set)
+ for x in self.out_rows:
+ if x["unit_conflict"]:
+ units[x["part"]].add(x["unit"])
+ self.unit_conflicts = OrderedDict()
+ for part, us in units.items():
+ n = sum(1 for x in self.out_rows if x["part"] == part and x["unit_conflict"])
+ item_unit = next(x["item_unit"] for x in self.out_rows if x["part"] == part)
+ self.unit_conflicts[part] = OrderedDict([("export_units", sorted(us)), ("item_unit", item_unit), ("rows", n)])
+ self.F.add("unit.%s" % part, "units_conflict rows: %s, MES %s vs %s %s" % (part, "/".join(sorted(us)), self.unit_ref_short, item_unit),
+ n, out.name + " vs " + self.unit_ref_short, "part == %r and uom != %r" % (part, item_unit))
+ problems.append(OrderedDict([
+ ("class", "units"), ("name", "Unit conflict"), ("key", part),
+ ("what", "%s is counted in %s in the MES and %s in the %s; no conversion factor on file" % (
+ part, "/".join(sorted(us)), item_unit, self.unit_ref_short)),
+ ("rows", n), ("fix", "Waiting on a decision: how many %s per %s. Until then no variance, no price." % (item_unit, "/".join(sorted(us))))]))
+ blank_scrap = [x for x in self.out_rows if not x["scrap_recorded"]]
+ self.F.add("scrap.absent_rows", "MES rows with no scrap recorded (absent, not zero)", len(blank_scrap), out.name,
+ "qty_scrap blank or column missing")
+ missing_lot = [x for x in self.out_rows if out.has("lot_number") and not x["lot"]]
+ for x in missing_lot:
+ integrity["blank_lot"].append(x)
+ self.problems, self.integrity = problems, integrity
+
+ # -- downtime ----------------------------------------------------------
+ def downtime(self):
+ dt = self.t("downtime")
+ self.events = []
+ if not dt:
+ self.load_diagnoses()
+ return
+ for i, r in enumerate(dt.rows):
+ s = parse_ts(dt.get(r, "started_at"), self.tz)
+ e = parse_ts(dt.get(r, "ended_at"), self.tz) if dt.has("ended_at") else None
+ stated = num(dt.get(r, "duration_minutes")) if dt.has("duration_minutes") else None
+ code_raw = dt.get(r, "reason_code").strip() if dt.has("reason_code") else ""
+ flags = []
+ minutes = None
+ if s is None:
+ flags.append("no_start")
+ elif e is None and not stated:
+ flags.append("ongoing")
+ elif e is None:
+ minutes = stated # a start and a stated length: finished, with no end time written
+ else:
+ span = (e.astimezone(timezone.utc) - s.astimezone(timezone.utc)).total_seconds() / 60.0
+ if span < 0:
+ flags.append("end_before_start")
+ elif stated is not None and abs(stated - span) > 1:
+ flags.append("duration_mismatch")
+ else:
+ minutes = stated if stated is not None else span
+ uncoded = code_raw == "" or code_raw.lower() == "other"
+ self.events.append(OrderedDict([
+ ("i", i), ("asset", dt.get(r, "asset_id").strip()), ("start", s), ("end", e),
+ ("start_local", local_str(s)), ("end_local", local_str(e)),
+ ("day", str(self.prod_day_of(s)) if s else None), ("stated_minutes", stated),
+ ("minutes", minutes), ("flags", flags), ("code", code_raw or "(blank)"),
+ ("uncoded", uncoded), ("text", dt.get(r, "reason_text") if dt.has("reason_text") else ""),
+ ("blocked", None)]))
+ # breakdown-diagnosis contract records, when handed in
+ self.load_diagnoses()
+
+ def load_diagnoses(self):
+ self.diagnoses = []
+ folder = self.args.diagnoses or os.path.join(self.args.exports, "diagnoses")
+ if not os.path.isdir(folder):
+ return
+ for fn in sorted(os.listdir(folder)):
+ path = os.path.join(folder, fn)
+ try:
+ if fn.endswith(".json"):
+ d = json.load(open(path))
+ recs = d if isinstance(d, list) else [d]
+ elif fn.endswith((".yaml", ".yml")):
+ recs = [read_flat_yaml(path)]
+ else:
+ continue
+ except ValueError:
+ self.skipped.append({"file": fn, "why": "diagnosis record could not be read"})
+ continue
+ for rec in recs:
+ rec["_file"] = fn
+ self.diagnoses.append(rec)
+
+ def rank_events(self, evs, label, period):
+ """Both rankings, by asset and by named reason code, for a set of events."""
+ trusted = [e for e in evs if e["minutes"] is not None and not e["blocked"]]
+ ranked = [e for e in evs if not e["blocked"]]
+ def agg(key, pool):
+ g = OrderedDict()
+ for e in pool:
+ k = key(e)
+ a = g.setdefault(k, OrderedDict([("key", k), ("events", 0), ("minutes", 0.0), ("ongoing", 0),
+ ("held_out", 0)]))
+ a["events"] += 1
+ if "ongoing" in e["flags"]:
+ a["ongoing"] += 1
+ elif e["minutes"] is None:
+ a["held_out"] += 1
+ else:
+ a["minutes"] += e["minutes"]
+ rows = list(g.values())
+ for a in rows:
+ a["minutes"] = intish(a["minutes"])
+ by_min = sorted(rows, key=lambda a: (-a["minutes"], -a["events"], str(a["key"])))
+ rm = comp_rank(by_min, lambda a: a["minutes"])
+ by_ev = sorted(rows, key=lambda a: (-a["events"], -a["minutes"], str(a["key"])))
+ re_ = comp_rank(by_ev, lambda a: a["events"])
+ rank_m = {a["key"]: r for a, r in zip(by_min, rm)}
+ rank_e = {a["key"]: r for a, r in zip(by_ev, re_)}
+ for a in rows:
+ a["rank_minutes"] = rank_m[a["key"]]
+ a["rank_events"] = rank_e[a["key"]]
+ return by_min
+ assets = agg(lambda e: e["asset"], ranked)
+ codes = agg(lambda e: e["code"], [e for e in ranked if not e["uncoded"]])
+ other = [e for e in ranked if e["uncoded"]]
+ out = OrderedDict([
+ ("label", label), ("events", len(ranked)),
+ ("minutes", intish(sum(e["minutes"] for e in trusted))),
+ ("ongoing", sum(1 for e in ranked if "ongoing" in e["flags"])),
+ ("held_out", [OrderedDict([("asset", e["asset"]), ("start", e["start_local"]), ("end", e["end_local"]),
+ ("stated_minutes", intish(e["stated_minutes"])), ("flags", e["flags"])])
+ for e in ranked if e["minutes"] is None and "ongoing" not in e["flags"]]),
+ ("uncoded_events", len(other)),
+ ("uncoded_minutes", intish(sum(e["minutes"] for e in other if e["minutes"] is not None))),
+ ("by_asset", assets), ("by_code", codes),
+ ])
+ f = self.F
+ p = "dt.%s" % label
+ f.add(p + ".events", "Downtime events [%s]" % label, out["events"], "downtime export", period, period=label)
+ f.add(p + ".minutes", "Downtime minutes, trusted rows only [%s]" % label, out["minutes"], "downtime export",
+ period + "; minutes held out for end_before_start, duration_mismatch and ongoing", period=label)
+ f.add(p + ".ongoing", "Ongoing events, length unknown [%s]" % label, out["ongoing"], "downtime export",
+ period + "; no end time", period=label)
+ f.add(p + ".held", "Events with untrusted minutes [%s]" % label, len(out["held_out"]), "downtime export",
+ period + "; end_before_start or duration_mismatch", period=label)
+ f.add(p + ".uncoded_events", "Events coded Other or blank [%s]" % label, out["uncoded_events"], "downtime export",
+ period + "; reason_code in ('Other', '')", period=label)
+ f.add(p + ".uncoded_minutes", "Minutes coded Other or blank [%s]" % label, out["uncoded_minutes"], "downtime export",
+ period + "; reason_code in ('Other', ''); trusted rows", period=label)
+ if out["events"]:
+ f.add(p + ".uncoded_pct", "Share of events coded Other or blank [%s]" % label,
+ round(100.0 * out["uncoded_events"] / out["events"]), "downtime export", "uncoded / events", period=label, unit="%")
+ f.add(p + ".uncoded_min_pct", "Share of minutes coded Other or blank [%s]" % label,
+ round(100.0 * out["uncoded_minutes"] / out["minutes"]) if out["minutes"] else None, "downtime export",
+ "uncoded minutes / minutes; not computable with no recorded minutes", period=label, unit="%")
+ if label.startswith("sp-"):
+ for kind, rows in (("asset", assets), ("code", codes)):
+ for a in rows:
+ for fld in ("events", "minutes", "ongoing", "held_out", "rank_minutes", "rank_events"):
+ f.add("%s.%s.%s.%s" % (p, kind, a["key"], fld), "%s %s, %s [%s]" % (kind, a["key"], fld, label), a[fld],
+ "downtime export", period + "; %s == %r" % (kind, a["key"]), period=label)
+ assets_c, codes_c = [], []
+ else:
+ assets_c, codes_c = assets, codes
+ for a in assets_c:
+ f.add("%s.asset.%s" % (p, a["key"]), "Downtime on %s [%s]" % (a["key"], label),
+ "%s events, %s min%s%s; rank %s by minutes, %s by events" % (
+ a["events"], a["minutes"], ", %d ongoing" % a["ongoing"] if a["ongoing"] else "",
+ ", %d held out" % a["held_out"] if a["held_out"] else "", a["rank_minutes"], a["rank_events"]),
+ "downtime export", period + "; asset_id == %r" % a["key"], period=label)
+ for a in codes_c:
+ f.add("%s.code.%s" % (p, a["key"]), "Reason code %s [%s]" % (a["key"], label),
+ "%s events, %s min%s; rank %s by minutes, %s by events" % (
+ a["events"], a["minutes"], ", %d held out" % a["held_out"] if a["held_out"] else "",
+ a["rank_minutes"], a["rank_events"]),
+ "downtime export", period + "; reason_code == %r" % a["key"], period=label)
+ # Reconcile: per-asset events and minutes sum to the totals.
+ self.check(sum(a["events"] for a in assets) == out["events"], "%s: asset events sum to the total" % label)
+ self.check(abs(sum(a["minutes"] for a in assets) - out["minutes"]) < 1e-6, "%s: asset minutes sum to the total" % label)
+ self.check(sum(a["events"] for a in codes) + out["uncoded_events"] == out["events"],
+ "%s: coded + uncoded events equal the total" % label)
+ return out
+
+ # -- per-day computation ---------------------------------------------------
+ def days(self):
+ plan, rout = self.t("plan"), self.t("routings")
+ self.plan_rows = []
+ if plan:
+ for r in plan.rows:
+ d = parse_day(plan.get(r, "plan_date"))
+ self.plan_rows.append(OrderedDict([
+ ("part", part_key(r)), ("part_verbatim", r.get("_part_verbatim")), ("provisional", r.get("_provisional")),
+ ("qty", num(plan.get(r, "planned_qty"))), ("day", str(d) if d else None),
+ ("asset", plan.get(r, "asset_id").strip() if plan.has("asset_id") else None),
+ ("cell", plan.get(r, "cell").strip() if plan.has("cell") else None),
+ ("work_center", plan.get(r, "work_center").strip() if plan.has("work_center") else None),
+ ("planned_hours", num(plan.get(r, "planned_hours")) if plan.has("planned_hours") else None)]))
+ # Ideal cycle minutes per unit, per part and work center, from the routing.
+ self.ideal = {}
+ if rout:
+ unit_col = None
+ if rout.has("run_min_per_unit"):
+ unit_col, factor = "run_min_per_unit", 1.0
+ elif rout.has("run_hours_per_unit"):
+ unit_col, factor = "run_hours_per_unit", 60.0
+ if unit_col:
+ for r in rout.rows:
+ v = num(rout.get(r, unit_col))
+ if v is not None and r.get("_part"):
+ key = (r["_part"], rout.get(r, "work_center").strip() if rout.has("work_center") else None)
+ self.ideal[key] = self.ideal.get(key, 0.0) + v * factor
+ rate, rate_source = self.downtime_rate()
+ all_days = sorted({x["day"] for x in self.out_rows if x["day"]} | {x["day"] for x in self.plan_rows if x["day"]} |
+ {e["day"] for e in self.events if e["day"]})
+ self.perday = OrderedDict()
+ for d in all_days:
+ self.perday[d] = self.one_day(d, rate, rate_source)
+
+ def downtime_rate(self):
+ env = os.environ.get("MFG_DOWNTIME_COST_PER_HOUR")
+ if env and num(env) is not None:
+ return num(env), "env_variable"
+ p = self.profile or {}
+ if p.get("downtime_rate") is not None:
+ return p["downtime_rate"], p.get("downtime_rate_kind", "profile_confirmed")
+ return None, "unset"
+
+ def one_day(self, d, rate, rate_source):
+ p = self.profile or {}
+ outs = [x for x in self.out_rows if x["day"] == d]
+ plans = [x for x in self.plan_rows if x["day"] == d]
+ evs = [e for e in self.events if e["day"] == d]
+ units_by_part = {x["part"]: x["item_unit"] for x in self.out_rows}
+ items_unit = lambda part: (self.master.get(part, {}).get(items_col(self.t("items"), "uom")) if self.t("items")
+ else units_by_part.get(part)) if part else None
+ # Output against plan, by part.
+ parts = OrderedDict()
+ for x in plans:
+ a = parts.setdefault(x["part"], new_part(x["part"]))
+ a["planned"] = (a["planned"] or 0) + (x["qty"] or 0)
+ a["plan_spellings"].add(x["part_verbatim"])
+ a["provisional"] = a["provisional"] or bool(x["provisional"])
+ for part in {x["part"] for x in plans if x["qty"] is None}: # a plan quantity that cannot be read is not 0
+ parts[part]["planned"] = None
+ for x in outs:
+ a = parts.setdefault(x["part"], new_part(x["part"]))
+ a["mes_spellings"].add(x["part_verbatim"])
+ a["provisional"] = a["provisional"] or bool(x["provisional"])
+ a["units"].add(x["unit"])
+ if x["held_out"]:
+ a["held_out_rows"].append(OrderedDict([("work_order", x["work_order"]), ("good", intish(x["good"])),
+ ("shift", x["shift"]), ("why", x["held_out"])]))
+ continue
+ a["good"] = (a["good"] or 0) + (x["good"] or 0)
+ a["rows_counted"] += 1
+ for part, a in parts.items():
+ iu = items_unit(part)
+ a["item_unit"] = iu
+ a["unit_conflict"] = any(u and iu and u.strip().lower() != str(iu).strip().lower() for u in a["units"])
+ dup_day = any(h["why"] == "duplicate key" for h in a["held_out_rows"])
+ if a["planned"] is not None and a["held_out_rows"] and (a["rows_counted"] == 0 or dup_day):
+ # Unresolved output for the day: plan "not counted", good "held out", day out of period totals.
+ a["status"] = "held out"
+ elif a["unit_conflict"]:
+ a["status"] = "not comparable, unit conflict"
+ elif a["planned"] is None:
+ a["status"] = "no plan"
+ elif a["rows_counted"] == 0:
+ a["status"] = "no output recorded"
+ else:
+ a["status"] = "comparable"
+ a["variance"] = intish(a["good"] - a["planned"])
+ a["variance_pct"] = round(100.0 * (a["good"] - a["planned"]) / a["planned"], 1) if a["planned"] else None
+ a["under_plan"] = a["good"] < a["planned"]
+ a["plan_spellings"] = sorted(s for s in a["plan_spellings"] if s)
+ a["mes_spellings"] = sorted(s for s in a["mes_spellings"] if s)
+ a["units"] = sorted(u for u in a["units"] if u)
+ a["planned"] = intish(a["planned"]) if a["planned"] is not None else None
+ a["good"] = intish(a["good"]) if a["good"] is not None else None
+ planned_qty = defaultdict(float)
+ actual_qty = defaultdict(float)
+ for part, a in parts.items():
+ if a["planned"] is not None and a["status"] != "held out":
+ planned_qty[a["item_unit"] or "unit"] += a["planned"]
+ for x in outs:
+ if x["part"] == part and not x["held_out"]:
+ actual_qty[(x["unit"] if a["unit_conflict"] else a["item_unit"]) or x["unit"] or "unit"] += x["good"] or 0
+ # OEE per asset.
+ assets = OrderedDict()
+ for x in plans:
+ if not x["asset"]:
+ continue
+ a = assets.setdefault(x["asset"], OrderedDict([
+ ("asset", x["asset"]), ("cell", x["cell"]), ("work_center", x["work_center"]),
+ ("planned_minutes", 0.0), ("parts", set())]))
+ if x["planned_hours"] is not None:
+ if a["planned_minutes"] is not None:
+ a["planned_minutes"] += x["planned_hours"] * 60
+ elif p.get("planned_hours_per_shift"):
+ a["planned_minutes"] = None
+ a["parts"].add(x["part"])
+ oee_rows = []
+ for asset, a in assets.items():
+ ev = [e for e in evs if e["asset"] == asset and not e["blocked"]]
+ mine = [x for x in outs if x["asset"] == asset]
+ held = [e for e in ev if e["minutes"] is None]
+ down = sum(e["minutes"] for e in ev if e["minutes"] is not None)
+ pm = a["planned_minutes"] or None
+ row = OrderedDict([("asset", asset), ("cell", a["cell"]), ("planned_minutes", intish(pm) if pm else None),
+ ("downtime_minutes", intish(down) if self.t("downtime") else None), ("availability", None), ("performance", None),
+ ("quality", None), ("oee", None), ("why_not", [])])
+ if not mine:
+ row["why_not"].append("no output recorded for this asset")
+ if self.t("downtime") is None:
+ row["why_not"].append("no downtime export, so availability is not computed")
+ elif pm is None:
+ row["why_not"].append("no planned production time")
+ elif held:
+ row["why_not"].append("downtime minutes untrusted or open (%s)" % ", ".join(
+ "%s %s" % (e["start_local"], "/".join(e["flags"])) for e in held))
+ elif down > pm:
+ row["why_not"].append("stops charged to this day (%s min) exceed its planned production time (%s min): "
+ "an outage runs past the day, so availability is not computed" % (intish(down), intish(pm)))
+ else:
+ row["availability"] = round((pm - down) / pm, 4)
+ counted = [x for x in mine if not x["held_out"]]
+ if mine and len(counted) < len(mine):
+ row["why_not"].append("duplicate, orphan or unreadable-quantity rows held out")
+ if counted and all(x["scrap_recorded"] for x in counted) and not any(x["held_out"] for x in mine):
+ g = sum(x["good"] or 0 for x in counted)
+ s = sum(x["scrap"] or 0 for x in counted)
+ rw = sum(x["rework"] or 0 for x in counted) if any(x["rework"] is not None for x in counted) else 0
+ if g + s + rw:
+ row["quality"] = round(g / (g + s + rw), 4)
+ elif counted and not all(x["scrap_recorded"] for x in counted):
+ row["why_not"].append("scrap not recorded (absent, not zero)")
+ if row["availability"] is not None and counted and not any(x["held_out"] for x in mine):
+ ideal = 0.0
+ ok = True
+ for x in counted:
+ k = (x["part"], a["work_center"])
+ if k not in self.ideal or x["unit_conflict"]:
+ ok = False
+ break
+ ideal += self.ideal[k] * ((x["good"] or 0) + (x["scrap"] or 0))
+ run = pm - down
+ if ok and run > 0:
+ row["performance"] = round(ideal / run, 4)
+ elif not ok:
+ row["why_not"].append("performance not computable: " + (
+ "no routing file in the drop, so no ideal cycle time" if not self.ideal else
+ "no routing run standard for this part and work center, or a unit conflict"))
+ if None not in (row["availability"], row["performance"], row["quality"]):
+ row["oee"] = round(row["availability"] * row["performance"] * row["quality"], 4)
+ oee_rows.append(row)
+ # Site roll-up: time-weighted availability, ideal/run performance, pooled quality, over assets with each.
+ reported = {x["asset"] for x in outs} # oee.md: an asset with no output is unreported, and out of the average
+ av = [r for r in oee_rows if r["availability"] is not None and r["asset"] in reported]
+ site_av = round(sum(r["planned_minutes"] - r["downtime_minutes"] for r in av) / sum(r["planned_minutes"] for r in av), 4) if av else None
+ pf = [r for r in oee_rows if r["performance"] is not None]
+ site_pf = round(sum(r["performance"] * (r["planned_minutes"] - r["downtime_minutes"]) for r in pf) /
+ sum(r["planned_minutes"] - r["downtime_minutes"] for r in pf), 4) if pf else None
+ q = [r for r in oee_rows if r["quality"] is not None]
+ site_q = None
+ if q:
+ gs = ts = 0.0
+ for r in q:
+ mine = [x for x in outs if x["asset"] == r["asset"] and not x["held_out"]]
+ gs += sum(x["good"] or 0 for x in mine)
+ ts += sum((x["good"] or 0) + (x["scrap"] or 0) + (x["rework"] or 0) for x in mine)
+ site_q = round(gs / ts, 4) if ts else None
+ same = [r["asset"] for r in av] == [r["asset"] for r in pf] == [r["asset"] for r in q]
+ site_oee = round(site_av * site_pf * site_q, 4) if same and None not in (site_av, site_pf, site_q) else None
+ excluded = ["%s (%s)" % (r["asset"], "; ".join(r["why_not"])) for r in oee_rows if r["why_not"]]
+ if not same and None not in (site_av, site_pf, site_q):
+ excluded.append("site composite (the three components rest on different assets)")
+ # Scrap and cost.
+ scrap_parts = OrderedDict()
+ unpriced = []
+ for x in outs:
+ if x["held_out"]:
+ continue
+ s = scrap_parts.setdefault(x["part"], OrderedDict([("part", x["part"]), ("scrap", 0.0), ("unit", x["unit"]),
+ ("recorded", True), ("unit_conflict", False), ("scrap_usd", None)]))
+ if not x["scrap_recorded"]:
+ s["recorded"] = False
+ continue
+ s["scrap"] += x["scrap"] or 0
+ s["unit_conflict"] = s["unit_conflict"] or x["unit_conflict"]
+ priced_total = 0.0
+ cost_col = items_col(self.t("items"), "std_cost")
+ for part, s in scrap_parts.items():
+ cost = num(self.master.get(part, {}).get(cost_col, "")) if cost_col and part else None
+ s["scrap"] = intish(s["scrap"]) if s["recorded"] else None
+ if not s["recorded"]:
+ unpriced.append("%s scrap: not recorded in the MES export (absent, not zero)" % part)
+ elif s["unit_conflict"]:
+ unpriced.append("%s scrap: unit conflict, MES %s / %s %s" % (part, s["unit"], self.unit_ref_short, items_unit(part)))
+ elif cost is None:
+ unpriced.append("%s scrap: no standard cost on file" % part)
+ else:
+ s["scrap_usd"] = round(s["scrap"] * cost, 2)
+ priced_total += s["scrap_usd"]
+ any_priced = any(s["scrap_usd"] is not None for s in scrap_parts.values())
+ for s in scrap_parts.values():
+ s["share_of_priced"] = round(100.0 * s["scrap_usd"] / priced_total, 1) if s["scrap_usd"] is not None and priced_total else None
+ held_out_scrap = [x for x in outs if x["held_out"]]
+ if held_out_scrap:
+ unpriced.append("held-out rows (%s): duplicate, orphan or no readable quantity, none counted" % ", ".join(
+ sorted({x["work_order"] for x in held_out_scrap})))
+ trusted = [e for e in evs if e["minutes"] is not None and not e["blocked"]]
+ down_total = sum(e["minutes"] for e in trusted)
+ down_usd = round(down_total / 60.0 * rate, 2) if rate is not None else None
+ if rate is None:
+ unpriced.insert(0, "all downtime: no downtime cost rate (MFG_DOWNTIME_COST_PER_HOUR not set, none in the plant's rates)")
+ rework_col = self.t("output") is not None and self.t("output").has("qty_rework")
+ return OrderedDict([
+ ("day", d), ("parts", parts), ("planned_qty", {k: intish(v) for k, v in planned_qty.items()}),
+ ("actual_qty", {k: intish(v) for k, v in actual_qty.items()}),
+ ("output_provisional", any(a["provisional"] for a in parts.values())),
+ ("oee_by_asset", oee_rows), ("availability", site_av), ("performance", site_pf), ("quality", site_q),
+ ("oee", site_oee), ("oee_excluded", excluded),
+ ("quality_convention", "good ÷ (good + scrap + rework), first-pass yield" if rework_col else
+ "good ÷ (good + scrap); no rework column, so first-pass yield could not be applied"),
+ ("scrap", list(scrap_parts.values())), ("scrap_priced_usd", round(priced_total, 2) if any_priced else None),
+ ("downtime_usd", down_usd), ("rate_source", rate_source), ("unpriced", unpriced),
+ ("downtime_minutes", intish(down_total) if self.t("downtime") else None),
+ ("events", len([e for e in evs if not e["blocked"]]) if self.t("downtime") else None),
+ ("open_outages", sum(1 for e in evs if "ongoing" in e["flags"])),
+ ("stops", [OrderedDict([("asset", e["asset"]), ("cell", self.cell_of(e["asset"])), ("start", e["start_local"]),
+ ("minutes", intish(e["minutes"])), ("stated_minutes", intish(e["stated_minutes"])),
+ ("code", e["code"]), ("text", e["text"]), ("flags", e["flags"])]) for e in
+ sorted(evs, key=lambda e: e["start"] or self.run_time)]),
+ ])
+
+ def cell_of(self, asset):
+ assets = self.t("assets")
+ if assets and assets.has("location"):
+ for r in assets.rows:
+ if assets.get(r, "asset_id").strip() == asset:
+ return assets.get(r, "location").strip()
+ for x in self.plan_rows:
+ if x["asset"] == asset and x["cell"]:
+ return x["cell"]
+ return None
+
+ # -- class 6, class 7 and the remaining integrity flags ------------------------
+ def classes(self):
+ out, wos = self.t("output"), self.t("work_orders")
+ problems = self.problems
+ checked = []
+ produced = {x["part"] for x in self.out_rows}
+ planned = {x["part"] for x in self.plan_rows}
+ for part in self.master:
+ if part not in produced and part not in planned:
+ checked.append(OrderedDict([("record", part), ("type", "part"),
+ ("line", "in the item master, not planned and not produced in the window")]))
+ assets = self.t("assets")
+ active_assets = {x["asset"] for x in self.out_rows if x["asset"]} | {x["asset"] for x in self.plan_rows if x["asset"]}
+ if assets:
+ for r in assets.rows:
+ a = assets.get(r, "asset_id").strip()
+ if a not in active_assets:
+ checked.append(OrderedDict([("record", a), ("type", "asset"),
+ ("line", "in the asset list, in no plan and no production record")]))
+ # Closed work orders with no output: one-sided, unless another source contradicts it.
+ self.contradicted = []
+ if wos and out:
+ produced_wos = {x["work_order"] for x in self.out_rows}
+ evidence = defaultdict(list)
+ for role in ("ncrs", "inspection"):
+ tb = self.t(role)
+ if tb and tb.has("work_order"):
+ for r in tb.rows:
+ ref = tb.get(r, "ncr_id") if role == "ncrs" else "inspection rows"
+ evidence[tb.get(r, "work_order").strip()].append("%s %s" % (tb.name, ref))
+ for wo, r in self.WO.items():
+ st = wos.get(r, "status").strip().lower()
+ if wo in produced_wos or st not in ("closed", "complete", "completed"):
+ continue
+ ev = sorted(set(evidence.get(wo, [])))
+ if ev:
+ c = OrderedDict([("record", wo), ("type", "production work order"), ("contradicted_by", ev),
+ ("line", "closed with no MES output, contradicted by %s" % ", ".join(ev))])
+ self.contradicted.append(c)
+ problems.append(OrderedDict([("class", 6), ("name", "One-sided, contradicted"), ("key", wo),
+ ("what", "%s is closed with no MES output, but %s" % (wo, ", ".join(ev))),
+ ("rows", 1), ("contradicted_by", ev),
+ ("fix", "None automatic: the work order was run. Find its output.")]))
+ else:
+ checked.append(OrderedDict([("record", wo), ("type", "production work order"),
+ ("line", "closed in the ERP with no MES output in the window")]))
+ # Class 2-5 rows for the numbered table, one block per verbatim spelling.
+ names = {2: "Format drift", 3: "Leading-zero loss", 4: "Revision suffix", 5: "Case and whitespace"}
+ for e in self.norm_log.values():
+ if e["class"] in names:
+ problems.append(OrderedDict([("class", e["class"]), ("name", names[e["class"]]), ("key", e["verbatim"]),
+ ("what", "%s spells %r; the item master has %s (%s)" % (e["source"], e["verbatim"], e["canonical"], e["rule"])),
+ ("rows", e["rows"]), ("fix", "Proposed, awaiting approval: read %r as %s. %d rows stay provisional until then." % (
+ e["verbatim"], e["canonical"], e["rows"]))]))
+ for e in self.unmatched_parts.values():
+ problems.append(OrderedDict([("class", 1), ("name", "Orphan record"), ("key", e["verbatim"]),
+ ("what", "%s carries part %r, which matches nothing in the item master (%s)" % (e["source"], e["verbatim"], e["why"])),
+ ("rows", e["rows"]), ("fix", "None automatic.")]))
+ # Class 7: activity rows outside the overlapping window.
+ c7 = []
+ if self.window:
+ lo, hi = self.window
+ for role, col in (("output", "day"), ("plan", "day")):
+ rows = self.out_rows if role == "output" else self.plan_rows
+ n = sum(1 for x in rows if x[col] and not (str(lo) <= x[col] <= str(hi)))
+ if n:
+ c7.append("%s: %d rows outside %s to %s" % (role, n, lo, hi))
+ n = sum(1 for e in self.events if e["day"] and not (str(lo) <= e["day"] <= str(hi)))
+ if n:
+ c7.append("downtime: %d events outside %s to %s" % (n, lo, hi))
+ # NCR integrity.
+ ncrs = self.t("ncrs")
+ first_out = {}
+ for x in self.out_rows:
+ if x["day"]:
+ first_out[x["work_order"]] = min(first_out.get(x["work_order"], x["day"]), x["day"])
+ self.ncr_flags = []
+ if ncrs:
+ for r in ncrs.rows:
+ wo = ncrs.get(r, "work_order").strip()
+ erp = self.WO.get(wo)
+ flags = []
+ if erp and r.get("_part") and erp.get("_part") and r["_part"] != erp["_part"]:
+ flags.append("ncr_part_differs: NCR says %s, the ERP holds %s for %s" % (r["_part_verbatim"], erp["_part"], wo))
+ fd = parse_ts(ncrs.get(r, "found_at"), self.tz)
+ if fd and wo in first_out and str(fd.date()) < first_out[wo]:
+ flags.append("ncr_dated_before_wo: found %s, before %s's first output on %s" % (fd.date(), wo, first_out[wo]))
+ if flags:
+ self.ncr_flags.append(OrderedDict([("ncr", ncrs.get(r, "ncr_id")), ("work_order", wo), ("flags", flags)]))
+ # Terse maintenance close-out notes.
+ maint = self.t("maintenance")
+ terse = []
+ if maint and maint.has("close_out_note"):
+ for r in maint.rows:
+ if maint.get(r, "close_out_note").strip().lower() in TERSE_NOTES:
+ terse.append(OrderedDict([("maintenance_wo", maint.get(r, "maintenance_wo")), ("asset", maint.get(r, "asset_id")),
+ ("note", maint.get(r, "close_out_note"))]))
+ dt_flags = [OrderedDict([("asset", e["asset"]), ("start", e["start_local"]), ("end", e["end_local"]),
+ ("stated_minutes", intish(e["stated_minutes"])), ("flags", e["flags"])])
+ for e in self.events if set(e["flags"]) & {"end_before_start", "duration_mismatch"}]
+ # Number the table: classes 1-5 and 8, contradicted one-sided records, and unit conflicts, which the
+ # Operations page has always listed among its problems.
+ order = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 8: 8, 6: 6, "units": 9}
+ numbered = [x for x in problems if x["class"] in order]
+ numbered.sort(key=lambda x: (order[x["class"]], str(x["key"])))
+ for n, x in enumerate(numbered, 1):
+ x["n"] = n
+ self.F.add("problem.%d.what" % n, "Data problem %d, as described" % n, x["what"], "this run", "class %s %s" % (x["class"], x["key"]))
+ self.F.add("problems.count", "Data problems (classes 1-5, 8, contradicted one-sided and unit conflicts), numbered table count",
+ len(numbered), "this run", "; ".join("class %s %s" % (x["class"], x["key"]) for x in numbered))
+ self.F.add("checked.count", "Checked, nothing wrong (class 6), outside the count", len(checked), "this run",
+ "; ".join(c["record"] for c in checked))
+ mismatched = [x for x in numbered if x["class"] in (1, 2, 3, 4, 5, 8)]
+ self.F.add("mismatched.count", "Mismatched records: classes 1-5 and 8", len(mismatched), "this run",
+ "; ".join("class %s %s" % (x["class"], x["key"]) for x in mismatched))
+ by_class = Counter(x["class"] for x in numbered)
+ for c, n in sorted(by_class.items(), key=lambda kv: str(kv[0])):
+ self.F.add("problems.class%s" % c, "Data problems, class %s" % c, n, "this run", "class == %s" % c)
+ self.check(sum(by_class.values()) == len(numbered), "data problems by class sum to the table count")
+ self.F.add("integrity.dt_flags", "Downtime rows held out for end_before_start or duration_mismatch", len(dt_flags),
+ "downtime export", "; ".join("%s %s" % (x["asset"], x["start"]) for x in dt_flags))
+ self.F.add("integrity.ncr", "NCRs whose part or date disagrees with their work order", len(self.ncr_flags),
+ "NCR export vs ERP and MES", "; ".join(x["ncr"] for x in self.ncr_flags))
+ self.F.add("integrity.terse", "Maintenance close-out notes that say nothing", len(terse), "maintenance export",
+ "close_out_note in ('Fixed.', 'Done', ...)")
+ self.F.add("integrity.blank_lot", "MES rows with a blank lot number", len(self.integrity["blank_lot"]), "MES export",
+ "lot_number == ''")
+ self.model["data_problems"] = OrderedDict([
+ ("numbered", numbered), ("count", len(numbered)),
+ ("mismatched", [x for x in numbered if x["class"] in (1, 2, 3, 4, 5, 8)]), ("duplicates", self.dup_list),
+ ("waiting_on_decision", OrderedDict([
+ ("unit_conflicts", self.unit_conflicts),
+ ("normalizations", [e for e in self.norm_log.values() if e["status"] != "approved"]),
+ ("provisional_rows", sum(e["rows"] for e in self.norm_log.values() if e["status"] != "approved")),
+ ("ncr_keys", self.ncr_flags)])),
+ ("class7", c7), ("checked_nothing_wrong", checked), ("contradicted", self.contradicted),
+ ("integrity", OrderedDict([
+ ("downtime_duration_conflicts", dt_flags),
+ ("blank_lots", [OrderedDict([("work_order", x["work_order"]), ("day", x["day"])]) for x in self.integrity["blank_lot"]]),
+ ("mes_part_differs", [OrderedDict([("work_order", x["work_order"]), ("mes_part", x["part_verbatim"])]) for x in self.integrity["mes_part_differs"]]),
+ ("terse_close_out_notes", terse), ("shared_lots", self.shared_lots)])),
+ ])
+
+ # -- exceptions -------------------------------------------------------------
+ def exceptions(self):
+ wos, ncrs, maint = self.t("work_orders"), self.t("ncrs"), self.t("maintenance")
+ d = str(self.day) if self.day else None
+ exc = []
+ so_link = wos is not None and wos.has("sales_order")
+ good_by_wo = defaultdict(float)
+ unclear = set()
+ for x in self.out_rows:
+ if x["held_out"]:
+ unclear.add(x["work_order"])
+ continue
+ if x["unit_conflict"]:
+ unclear.add(x["work_order"])
+ good_by_wo[x["work_order"]] += x["good"] or 0
+ late, cannot = [], []
+ if wos and d:
+ for wo, r in self.WO.items():
+ if wos.get(r, "status").strip().lower() in ("closed", "complete", "completed", "cancelled", "canceled"):
+ continue
+ due = parse_day(wos.get(r, "due_date"))
+ if not due or str(due) > d:
+ continue
+ if wo in unclear:
+ cannot.append(wo)
+ continue
+ g = good_by_wo.get(wo, 0.0)
+ q = num(wos.get(r, "qty_ordered")) or 0
+ if g < q:
+ late.append(OrderedDict([("work_order", wo), ("part", r.get("_part")), ("ordered", intish(q)),
+ ("good", intish(g)), ("due", str(due))]))
+ for x in late:
+ self.F.add("exc.late.%s" % x["work_order"], "Good / ordered, %s" % x["work_order"], "%s / %s" % (x["good"], x["ordered"]),
+ "ERP vs MES", "due %s" % x["due"])
+ exc.append(OrderedDict([("kind", "late_job"), ("ref", x["work_order"]), ("detail", x),
+ ("commitment_impact", None if so_link else "not traceable: no work order to sales order link in the ERP")]))
+ self.F.add("exc.late", "Open work orders due on or before %s with good output short of ordered" % d, len(late),
+ "ERP vs MES", "; ".join("%s %s/%s due %s" % (x["work_order"], x["good"], x["ordered"], x["due"]) for x in late))
+ self.F.add("exc.late_undeterminable", "Open work orders due on or before %s whose completion cannot be judged" % d,
+ len(cannot), "ERP vs MES", "unit conflict or held-out rows: " + ", ".join(cannot))
+ # Machines down: ongoing at the window close.
+ for e in self.events:
+ if "ongoing" in e["flags"]:
+ exc.append(OrderedDict([("kind", "machine_down"), ("ref", e["asset"]),
+ ("detail", OrderedDict([("down_since", e["start_local"]), ("code", e["code"]), ("text", e["text"])])),
+ ("commitment_impact", None if so_link else "not traceable: no work order to sales order link in the ERP")]))
+ # Quality holds: open NCRs tied to a customer.
+ if ncrs:
+ for r in ncrs.rows:
+ st = ncrs.get(r, "status").strip().lower() if ncrs.has("status") else "open"
+ cust = ncrs.get(r, "customer").strip() if ncrs.has("customer") else ""
+ if st == "open" and cust:
+ exc.append(OrderedDict([("kind", "quality_hold"), ("ref", ncrs.get(r, "ncr_id")),
+ ("detail", OrderedDict([("customer", cust), ("work_order", ncrs.get(r, "work_order")),
+ ("part", r.get("_part")), ("lot", ncrs.get(r, "lot_number"))])),
+ ("commitment_impact", None)]))
+ for c in self.contradicted:
+ exc.append(OrderedDict([("kind", "one_sided_contradicted"), ("ref", c["record"]), ("detail", c),
+ ("commitment_impact", None)]))
+ self.F.add("exc.count", "Exceptions (late jobs, machines down, quality holds, contradicted one-sided)", len(exc),
+ "this run", ", ".join("%s %s" % (x["kind"], x["ref"]) for x in exc))
+ # Maintenance history per asset, for the machine decision.
+ hist = OrderedDict()
+ if maint:
+ lo = (self.day - timedelta(days=LOOKBACK_DAYS)) if self.day else None
+ for r in maint.rows:
+ a = maint.get(r, "asset_id").strip()
+ od = parse_day(maint.get(r, "opened_date"))
+ if lo and od and od < lo:
+ continue
+ h = hist.setdefault(a, OrderedDict([("records", 0), ("corrective", 0), ("seizure", []), ("notes", [])]))
+ h["records"] += 1
+ typ = maint.get(r, "type").strip().lower() if maint.has("type") else ""
+ note = maint.get(r, "close_out_note") if maint.has("close_out_note") else ""
+ if typ == "corrective":
+ h["corrective"] += 1
+ if any(w in note.lower() for w in SEIZURE_WORDS):
+ h["seizure"].append(OrderedDict([("maintenance_wo", maint.get(r, "maintenance_wo")), ("date", str(od)), ("note", note)]))
+ h["notes"].append(OrderedDict([("maintenance_wo", maint.get(r, "maintenance_wo")), ("date", str(od)),
+ ("type", typ), ("note", note)]))
+ for a, h in hist.items():
+ h["repeat_failure"] = h["corrective"] >= 2
+ self.model["exceptions"] = OrderedDict([("items", exc), ("late_jobs", late), ("late_undeterminable", cannot),
+ ("so_link", so_link), ("maintenance_history", hist)])
+
+ # -- breakdown-diagnosis records -------------------------------------------
+ def fold_diagnoses(self):
+ blocked, flagged, matched, assessed = [], [], [], set()
+ for rec in getattr(self, "diagnoses", []):
+ if rec.get("source_system") not in (None, "breakdown_diagnosis"):
+ continue
+ s = parse_ts(rec.get("started_at") or "", self.tz)
+ e = parse_ts(rec.get("ended_at") or "", self.tz)
+ sf = rec.get("safety_flagged")
+ if sf is not None and not isinstance(sf, bool): # True, yes, 1, or a trailing comment; anything else is unknown
+ sf = {"true": True, "yes": True, "y": True, "1": True, "false": False, "no": False, "n": False, "0": False}.get(
+ str(sf).split("#")[0].strip().strip("'\"").lower())
+ item = OrderedDict([("file", rec.get("_file")), ("asset", rec.get("asset_id")), ("start", local_str(s)),
+ ("end", local_str(e)), ("duration_minutes", rec.get("duration_minutes")),
+ ("reason_code", rec.get("reason_code")), ("reason_text", rec.get("reason_text")),
+ ("leading_cause", rec.get("leading_cause")), ("diagnosis_state", rec.get("diagnosis_state")),
+ ("technician_step", rec.get("technician_step")),
+ ("safety_flagged", sf), ("safety_reason", rec.get("safety_reason"))])
+ if sf is None:
+ item["why"] = "safety status missing on a diagnosis record - not ranked until confirmed"
+ blocked.append(item)
+ continue
+ assessed.add(str(rec.get("asset_id")))
+ if sf is True:
+ flagged.append(item)
+ # A flagged record (true or false) joins the log as a row, untransformed.
+ stated = num(rec.get("duration_minutes") or "")
+ mins = stated if (s and e and stated is not None and
+ abs(stated - (e.astimezone(timezone.utc) - s.astimezone(timezone.utc)).total_seconds() / 60) <= 1) else None
+ code = rec.get("reason_code") or ""
+ # The same stoppage as an MES row (same asset, start within the same shift) is counted once.
+ same = [m for m in self.events if s and m["start"] and "source" not in m and "diagnosis" not in m
+ and m["asset"] == rec.get("asset_id") and abs((m["start"] - s).total_seconds()) <= 8 * 3600]
+ if same:
+ m = min(same, key=lambda m: abs((m["start"] - s).total_seconds()))
+ m["diagnosis"] = rec.get("_file")
+ item["matched_mes_row"] = m["start_local"]
+ matched.append(item)
+ continue
+ self.events.append(OrderedDict([
+ ("i", "diag:%s" % rec.get("_file")), ("asset", rec.get("asset_id")), ("start", s), ("end", e),
+ ("start_local", local_str(s)), ("end_local", local_str(e)), ("day", str(self.prod_day_of(s)) if s else None),
+ ("stated_minutes", stated), ("minutes", mins),
+ ("flags", ["ongoing"] if s and not e else ([] if mins is not None else ["duration_mismatch"])),
+ ("code", code or "(blank)"), ("uncoded", code == "" or code.lower() == "other"),
+ ("text", rec.get("reason_text") or ""), ("blocked", None), ("source", "breakdown_diagnosis")]))
+ self.model["diagnoses"] = OrderedDict([("blocked_safety_unknown", blocked), ("safety_flagged", flagged),
+ ("matched_to_mes_row", matched),
+ ("assets_with_diagnosis", sorted(assessed))])
+ self.F.add("diag.blocked", "Diagnosis records blocked, safety status unknown", len(blocked), "breakdown-diagnosis records",
+ "safety_flagged absent")
+
+ # -- week over week -------------------------------------------------------
+ def week_over_week(self):
+ if not self.day:
+ self.model["week_over_week"] = None
+ return
+ def window(a, b):
+ ds = [str(self.day - timedelta(days=i)) for i in range(a, b)]
+ recs = [self.perday[x] for x in ds if x in self.perday]
+ cmp_plan = sum(p["planned"] for r in recs for p in r["parts"].values() if p["status"] == "comparable")
+ cmp_good = sum(p["good"] for r in recs for p in r["parts"].values() if p["status"] == "comparable")
+ av = [r["availability"] for r in recs if r["availability"] is not None]
+ q = [r["quality"] for r in recs if r["quality"] is not None]
+ return OrderedDict([("from", ds[-1]), ("to", ds[0]), ("days", len(recs)),
+ ("output_vs_plan_pct", round(100.0 * cmp_good / cmp_plan, 1) if cmp_plan else None),
+ ("availability", round(sum(av) / len(av), 4) if av else None), ("availability_days", len(av)),
+ ("quality", round(sum(q) / len(q), 4) if q else None), ("quality_days", len(q)),
+ ("downtime_minutes", intish(sum(r["downtime_minutes"] for r in recs))
+ if recs and self.t("downtime") else None),
+ ("scrap_usd", round(sum(r["scrap_priced_usd"] for r in recs if r["scrap_priced_usd"] is not None), 2)
+ if any(r["scrap_priced_usd"] is not None for r in recs) else None)])
+ this, prev = window(0, 7), window(7, 14)
+ self.model["week_over_week"] = OrderedDict([("basis", "per-day figures computed this run from the exports"),
+ ("this_week", this), ("last_week", prev),
+ ("skip", prev["days"] == 0)])
+ for lab, w in (("this", this), ("prev", prev)):
+ for k in ("days", "output_vs_plan_pct", "availability", "quality", "downtime_minutes", "scrap_usd"):
+ self.F.add("wow.%s.%s" % (lab, k), "Week over week, %s week %s..%s: %s" % (lab, w["from"], w["to"], k), w[k],
+ "per-day figures, this run", "%s to %s" % (w["from"], w["to"]))
+
+ # -- period roll-ups: every Day, Week and Month-to-date figure ---------------
+ def rollup(self, days, label, period):
+ """Sum per-day figures over a period. Every value lands in the figures tab."""
+ recs = [self.perday[d] for d in days if d in self.perday]
+ parts = OrderedDict()
+ for r in recs:
+ for part, a in r["parts"].items():
+ t = parts.setdefault(part, OrderedDict([
+ ("part", part), ("planned", 0), ("good", 0), ("days_compared", 0), ("days_under_plan", 0),
+ ("days_held_out", []), ("unit_conflict", False), ("provisional", False), ("q_good", 0), ("q_total", 0),
+ ("plan_spellings", set()), ("mes_spellings", set()), ("units", set()), ("item_unit", a["item_unit"])]))
+ t["provisional"] = t["provisional"] or a["provisional"]
+ t["plan_spellings"].update(a["plan_spellings"])
+ t["mes_spellings"].update(a["mes_spellings"])
+ t["units"].update(a["units"])
+ if a["status"] == "held out":
+ t["days_held_out"].append(r["day"])
+ elif a["status"] == "not comparable, unit conflict":
+ t["unit_conflict"] = True
+ t["planned"] += a["planned"] or 0
+ t["good"] += a["good"] or 0
+ elif a["status"] == "comparable":
+ t["planned"] += a["planned"]
+ t["good"] += a["good"]
+ t["days_compared"] += 1
+ t["days_under_plan"] += 1 if a["under_plan"] else 0
+ # Quality by part, over days whose scrap was recorded and whose output was not held out.
+ for r in recs:
+ for x in r["scrap"]:
+ a = r["parts"].get(x["part"])
+ if x["part"] in parts and x["scrap"] is not None and a and a["status"] != "held out" and a["good"] is not None:
+ parts[x["part"]]["q_good"] += a["good"]
+ parts[x["part"]]["q_total"] += a["good"] + x["scrap"] + sum(
+ o["rework"] or 0 for o in self.out_rows if o["day"] == r["day"] and o["part"] == x["part"] and not o["held_out"])
+ for part, t in parts.items():
+ for k in ("plan_spellings", "mes_spellings", "units"):
+ t[k] = sorted(t[k])
+ t["quality"] = round(t["q_good"] / t["q_total"], 4) if t["q_total"] else None
+ del t["q_good"], t["q_total"]
+ if t["unit_conflict"]:
+ t["status"] = "not comparable, unit conflict"
+ t["planned"], t["good"] = intish(t["planned"]), intish(t["good"])
+ t["variance"] = t["variance_pct"] = None
+ elif not t["days_compared"]:
+ t["status"] = "no comparable day"
+ t["planned"] = t["good"] = t["variance"] = t["variance_pct"] = None
+ else:
+ t["status"] = "comparable"
+ t["variance"] = intish(t["good"] - t["planned"])
+ t["variance_pct"] = round(100.0 * (t["good"] - t["planned"]) / t["planned"], 1) if t["planned"] else None
+ t["planned"], t["good"] = intish(t["planned"]), intish(t["good"])
+ scrap = OrderedDict()
+ for r in recs:
+ for x in r["scrap"]:
+ s_ = scrap.setdefault(x["part"], OrderedDict([("part", x["part"]), ("scrap", 0), ("scrap_usd", 0.0), ("unit", x["unit"]),
+ ("days_not_recorded", 0), ("unit_conflict", False), ("priced", True)]))
+ if x["scrap"] is None:
+ s_["days_not_recorded"] += 1
+ else:
+ s_["scrap"] += x["scrap"]
+ s_["unit_conflict"] = s_["unit_conflict"] or x["unit_conflict"]
+ if x["scrap_usd"] is None:
+ s_["priced"] = False
+ else:
+ s_["scrap_usd"] += x["scrap_usd"]
+ for s_ in scrap.values():
+ if s_["days_not_recorded"] and not s_["scrap"]:
+ s_["scrap"] = None
+ s_["scrap"] = intish(s_["scrap"]) if s_["scrap"] is not None else None
+ s_["scrap_usd"] = round(s_["scrap_usd"], 2) if s_["priced"] and s_["scrap"] is not None else None
+ priced = round(sum(s_["scrap_usd"] for s_ in scrap.values() if s_["scrap_usd"] is not None), 2) \
+ if any(s_["scrap_usd"] is not None for s_ in scrap.values()) else None
+ for s_ in scrap.values():
+ s_["share_of_priced"] = round(100.0 * s_["scrap_usd"] / priced, 1) if s_["scrap_usd"] is not None and priced else None
+ held = [h for r in recs for a in r["parts"].values() for h in a["held_out_rows"]]
+ comp = [t for t in parts.values() if t["status"] == "comparable"]
+ summ = OrderedDict([
+ ("comparable_parts", len(comp)),
+ ("max_abs_variance_pct", max((abs(t["variance_pct"]) for t in comp if t["variance_pct"] is not None), default=None)),
+ ("all_under", bool(comp) and all(t["variance"] < 0 for t in comp)),
+ ("all_over", bool(comp) and all(t["variance"] > 0 for t in comp)),
+ ("days_under", [OrderedDict([("part", t["part"]), ("under", t["days_under_plan"]), ("of", t["days_compared"])]) for t in comp]),
+ ("provisional", [OrderedDict([("part", t["part"]), ("held_out_days", t["days_held_out"])]) for t in parts.values() if t["provisional"]]),
+ ("held_out_parts", [OrderedDict([("part", t["part"]), ("days", t["days_held_out"])]) for t in parts.values() if t["days_held_out"]]),
+ ("not_comparable", [OrderedDict([("part", t["part"]), ("why", "unit conflict" if t["unit_conflict"] else "no comparable day")])
+ for t in parts.values() if t["status"] != "comparable"])])
+ out = OrderedDict([("label", label), ("period", period), ("days", [r["day"] for r in recs]), ("summary", summ),
+ ("parts", parts), ("scrap", scrap), ("scrap_priced_usd", priced),
+ ("held_out_rows", len(held)), ("held_out_good", intish(sum(h["good"] or 0 for h in held)))])
+ f, k = self.F, "per.%s" % label
+ for part, t in parts.items():
+ for fld in ("planned", "good", "variance", "variance_pct", "days_under_plan", "days_compared", "quality"):
+ f.add("%s.out.%s.%s" % (k, part, fld), "%s, %s [%s]" % (fld.replace("_", " ").capitalize(), part, label), t[fld],
+ "plan and MES", period + "; comparable days only; held-out days excluded", period=label)
+ for part, s_ in scrap.items():
+ f.add("%s.scrap.%s" % (k, part), "Scrap qty, %s [%s]" % (part, label), s_["scrap"], "MES export",
+ period + "; held-out rows excluded; absent when not recorded", period=label, unit=s_["unit"] or "")
+ f.add("%s.scrapusd.%s" % (k, part), "Scrap $, %s [%s]" % (part, label), s_["scrap_usd"], "MES x item master std_cost",
+ period + "; unpriced on a unit conflict or no record", period=label, unit="USD")
+ f.add("%s.scrapusd" % k, "Priced scrap $ [%s]" % label, priced, "MES x item master std_cost", period, period=label, unit="USD")
+ for part, s_ in scrap.items():
+ f.add("%s.scrapshare.%s" % (k, part), "Share of priced scrap $, %s [%s]" % (part, label), s_["share_of_priced"],
+ "MES x item master std_cost", period + "; part's scrap $ / priced total", period=label, unit="%")
+ f.add("%s.maxvar" % k, "Largest absolute variance among comparable parts [%s]" % label, summ["max_abs_variance_pct"],
+ "plan and MES", period + "; comparable parts only", period=label, unit="%")
+ f.add("%s.comparable" % k, "Comparable parts [%s]" % label, summ["comparable_parts"], "plan and MES", period, period=label)
+ f.add("%s.heldgood" % k, "Good on held-out rows, not in totals [%s]" % label, out["held_out_good"], "MES export",
+ period + "; duplicate, orphan or no readable quantity", period=label)
+ f.add("%s.held" % k, "Held-out output rows [%s]" % label, out["held_out_rows"], "MES export", period + "; duplicate, orphan or no readable quantity", period=label)
+ # Reconcile: each comparable part's period total equals the sum of its days.
+ for part, t in parts.items():
+ if t["status"] == "comparable":
+ dsum = sum(r["parts"][part]["good"] for r in recs if part in r["parts"] and r["parts"][part]["status"] == "comparable")
+ self.check(dsum == t["good"], "%s %s: daily good sums to the period" % (label, part))
+ self.check(abs(sum(s_["scrap_usd"] or 0 for s_ in scrap.values()) - (priced or 0)) <= 0.005, "%s: priced scrap sums" % label)
+ return out
+
+ def periods(self):
+ self.model["periods"] = OrderedDict()
+ if not self.day:
+ return
+ d = self.day
+ ws, _ = week_of(d)
+ ms = d.replace(day=1)
+ spans = [("day", [d], "production day == %s" % d),
+ ("week", [ws + timedelta(days=i) for i in range((d - ws).days + 1)], "%s to %s (Mon-Sun week to date)" % (ws, d)),
+ ("month", [ms + timedelta(days=i) for i in range((d - ms).days + 1)], "%s to %s (month to date)" % (ms, d))]
+ for name, ds, period in spans:
+ self.model["periods"][name] = self.rollup([str(x) for x in ds], "%s:%s..%s" % (name, ds[0], ds[-1]), period)
+
+ # -- the short Operations page: every view, precomputed ---------------------
+ def short_periods(self):
+ """Day, Week (Mon-Sun containing the day) and Month (1st to the day) for every production day.
+
+ Written to periods.json so the full page's model stays small. Every value is a figures row."""
+ lo, hi = (str(self.window[0]), str(self.window[1])) if self.window else (None, None)
+ if lo and self.day: # the reported day has a view even when one export stops short of it
+ lo, hi = min(lo, str(self.day)), max(hi, str(self.day))
+ days = sorted(d for d in self.perday if not lo or lo <= d <= hi)
+ if not days:
+ self.short = None
+ return
+ first, last = date.fromisoformat(days[0]), date.fromisoformat(days[-1])
+ latest = str(self.day) if self.day and str(self.day) in self.perday else days[-1]
+ rollups, views = OrderedDict(), OrderedDict()
+
+ def build(key, kind, span, label, period):
+ if key in rollups:
+ return
+ ds = [str(x) for x in span]
+ have = [x for x in ds if x in days]
+ r = self.rollup(have, "sp-" + key, period)
+ evs = [e for e in self.events if e["day"] in have]
+ r["downtime"] = self.rank_events(evs, "sp-" + key, period) if self.t("downtime") else None
+ r["kind"] = kind
+ r["span"] = [ds[0], ds[-1]]
+ r["label"] = label
+ r["covered"] = have
+ r["missing"] = [x for x in ds if x not in self.perday or not (str(first) <= x <= str(last))]
+ r["partial"] = bool(r["missing"]) if kind == "week" else (kind == "month" and span[-1].month == (span[-1] + timedelta(days=1)).month)
+ if r["downtime"]:
+ tie_assets(r["downtime"])
+ for i, row in enumerate(r["downtime"]["asset_rows"]):
+ if row.get("tied"):
+ row["tie_id"] = "sp-%s.tie.%d" % (key, i)
+ self.F.add(row["tie_id"], "Assets tied on minutes and events [%s]" % key, len(row["assets"]),
+ "downtime export", "same minutes and events: " + ", ".join(row["assets"]), period=key)
+ if kind == "day" and have:
+ r["stops"] = self.perday[have[0]]["stops"]
+ for i, st in enumerate(r["stops"]):
+ self.F.add("sp-%s.stop.%d" % (key, i), "Stop %s at %s [%s]" % (st["asset"], st["start"], key),
+ st["minutes"], "downtime export", "minutes held out when the duration disagrees with the "
+ "times, or the stop is ongoing; stated %s" % st["stated_minutes"], period=key)
+ if st["minutes"] is None and "ongoing" not in st["flags"]:
+ self.F.add("sp-%s.stop.%d.stated" % (key, i), "Stated minutes, held out, %s at %s" % (st["asset"], st["start"]),
+ st["stated_minutes"], "downtime export", "duration_minutes as written", period=key)
+ self.F.add("sp-%s.covered" % key, "Days with data [%s]" % key, len(have), "exports", period, period=key)
+ rollups[key] = r
+
+ for d in days:
+ dd = date.fromisoformat(d)
+ ws, we = week_of(dd)
+ ms = dd.replace(day=1)
+ dk, wk, mk = "day:%s" % d, "week:%s..%s" % (ws, we), "month:%s..%s" % (ms, d)
+ build(dk, "day", [dd], dd.strftime("%A, %Y-%m-%d"), "production day == %s" % d)
+ build(wk, "week", [ws + timedelta(days=i) for i in range(7)], "Week of %s to %s" % (ws, we),
+ "%s to %s (Monday to Sunday)" % (ws, we))
+ build(mk, "month", [ms + timedelta(days=i) for i in range((dd - ms).days + 1)],
+ "%s to date: 1-%d" % (dd.strftime("%B"), dd.day), "%s to %s (month to date)" % (ms, d))
+ views[d] = OrderedDict([("day", dk), ("week", wk), ("month", mk)])
+ self.short = OrderedDict([("latest", latest), ("days", days), ("views", views), ("rollups", rollups),
+ ("data_window", [str(first), str(last)])])
+
+ def decisions(self):
+ """Today's decisions, in the rev 2 priority order, from computed facts only."""
+ fr, ex, dp = self.model["freshness"], self.model["exceptions"], self.model["data_problems"]
+ out, f = [], self.F
+ # 1. Export failure: an export missing, or last night's drop holds nothing newer than days ago.
+ missing = [g for g in fr["gaps"] if "did not land" in g]
+ stale = fr["days_old"] is not None and fr["days_old"] > 1
+ if missing or stale:
+ out.append(OrderedDict([("kind", "export"), ("missing", missing), ("stale", stale),
+ ("newest_day", fr["newest_production_day"]), ("days_old", fr["days_old"])]))
+ # 2. The machine decision, for the worst asset by downtime minutes, month to date.
+ mk = self.short["views"][self.short["latest"]]["month"] if self.short else None
+ rk = self.short["rollups"][mk]["downtime"] if mk else None
+ if rk and rk["by_asset"]:
+ worst = rk["by_asset"][0]
+ a = worst["key"]
+ evs = sorted([e for e in self.events if e["asset"] == a and e["day"] and e["day"] <= self.short["latest"]],
+ key=lambda e: e["start"])
+ open_ev = next((e for e in reversed(evs) if "ongoing" in e["flags"]), None)
+ texts = Counter(e["text"] for e in evs if e["text"])
+ text = texts.most_common(1)[0][0] if texts else None
+ hist = ex["maintenance_history"].get(a, {})
+ diagnosed = a in self.model["diagnoses"]["assets_with_diagnosis"]
+ repeat = bool(hist.get("repeat_failure"))
+ seized = hist.get("seizure", [])
+ lockout = (not diagnosed) and (repeat or bool(seized))
+ share = round(100.0 * worst["minutes"] / rk["minutes"]) if rk["minutes"] else None
+ f.add("decision.machine.share", "Share of downtime minutes on %s [%s]" % (a, mk), share, "downtime export",
+ "asset minutes / total minutes, month to date; trusted rows", period=mk, unit="%")
+ out.append(OrderedDict([
+ ("kind", "machine"), ("asset", a), ("cell", self.cell_of(a)), ("period", mk), ("minutes", worst["minutes"]),
+ ("total_minutes", rk["minutes"]), ("share_pct", share), ("approximate", worst["held_out"] > 0),
+ ("reason_text", text), ("down_since", open_ev["start_local"] if open_ev else None),
+ ("as_of", fr["newest_production_day"]), ("stale", stale), ("diagnosed", diagnosed),
+ ("safety", next((("flagged", d["safety_reason"]) for d in self.model["diagnoses"]["safety_flagged"] if d["asset"] == a), None)),
+ ("lockout", lockout), ("repeat_failure", repeat), ("seizure", seized[-1] if seized else None)]))
+ # 3. Customer quality hold, for any open NCR tied to a customer.
+ holds = [x for x in ex["items"] if x["kind"] == "quality_hold"]
+ ncrs = self.t("ncrs")
+ if holds:
+ n_ncr = len(ncrs.rows) if ncrs else 0
+ n_diff = len([x for x in dp["waiting_on_decision"]["ncr_keys"] if any(fl.startswith("ncr_part_differs") for fl in x["flags"])])
+ f.add("decision.hold.ncrs", "NCRs in the log", n_ncr, "NCR export", "all rows")
+ f.add("decision.hold.ncr_part_differs", "NCRs naming a different part than the ERP for their work order", n_diff,
+ "NCR export vs ERP", "ncr_part_differs")
+ for h in holds:
+ d = h["detail"]
+ lot_wos = sorted({x["work_order"] for x in self.out_rows if d.get("lot") and x["lot"] == d["lot"]})
+ out.append(OrderedDict([("kind", "quality_hold"), ("ncr", h["ref"]), ("customer", d["customer"]),
+ ("work_order", d["work_order"]), ("part", d["part"]), ("lot", d["lot"]),
+ ("orders_on_lot", lot_wos), ("open_lines", self.open_lines(d["customer"])),
+ ("ncrs", n_ncr), ("ncrs_part_differs", n_diff)]))
+ # 4. Any other decision, by what is at stake: the late jobs, priced at standard cost.
+ late = ex["late_jobs"]
+ if late:
+ cost_col = items_col(self.t("items"), "std_cost")
+ short_units = sum(x["ordered"] - x["good"] for x in late)
+ usd = None
+ if cost_col:
+ vals = [(x["ordered"] - x["good"]) * num(self.master.get(x["part"], {}).get(cost_col, "")) for x in late
+ if num(self.master.get(x["part"], {}).get(cost_col, "")) is not None]
+ usd = round(sum(vals), 2) if len(vals) == len(late) else None
+ f.add("decision.late.count", "Late open work orders", len(late), "ERP vs MES", "due on or before the day; good < ordered")
+ f.add("decision.late.units", "Units short on late work orders", intish(short_units), "ERP vs MES", "sum(ordered - good)")
+ f.add("decision.late.usd", "Units short on late work orders, at standard cost", usd, "ERP, MES, item master",
+ "sum((ordered - good) x std_cost)", unit="USD")
+ out.append(OrderedDict([("kind", "late_jobs"), ("count", len(late)), ("units_short", intish(short_units)),
+ ("usd_at_stake", usd), ("work_orders", [x["work_order"] for x in late])]))
+ shown, rest = out[:3], out[3:]
+ wd = dp["waiting_on_decision"]
+ remaining = OrderedDict([
+ ("unit_conflicts", list(wd["unit_conflicts"].keys())),
+ ("normalizations", len(wd["normalizations"])), ("provisional_rows", wd["provisional_rows"]),
+ ("ncr_keys", len(wd["ncr_keys"])), ("overflow", [x["kind"] for x in rest])])
+ f.add("remaining.normalizations", "Normalizations awaiting approval", remaining["normalizations"], "this run", "status != approved")
+ f.add("remaining.provisional_rows", "Rows provisional until approved", remaining["provisional_rows"], "this run", "rows on unapproved normalizations")
+ f.add("remaining.unit_conflicts", "Unit conflicts waiting on a factor", len(remaining["unit_conflicts"]), "this run", "units_conflict")
+ self.model["short_page"] = OrderedDict([("decisions", shown), ("remaining", remaining)])
+
+ def open_lines(self, customer):
+ so = self.t("sales_orders")
+ if not so:
+ return None
+ cust_ids = {customer}
+ cu = self.t("customers")
+ if cu:
+ cust_ids |= {cu.get(r, "customer_id") for r in cu.rows if cu.get(r, "customer").strip() == customer}
+ lines = [OrderedDict([("sales_order", so.get(r, "sales_order")), ("part", r.get("_part")), ("qty", so.get(r, "qty_ordered"))])
+ for r in so.rows if so.get(r, "status").strip().lower() in ("open", "") and
+ (so.get(r, "customer").strip() in cust_ids or so.get(r, "customer_id").strip() in cust_ids)]
+ return lines
+
+ # -- the day, the records, the figures ----------------------------------------
+ def emit(self):
+ out_dir = self.args.out
+ os.makedirs(out_dir, exist_ok=True)
+ d = str(self.day) if self.day else None
+ dt_tb = self.t("downtime")
+ rk = OrderedDict()
+ if dt_tb and d:
+ day_evs = [e for e in self.events if e["day"] == d]
+ rk["day"] = self.rank_events(day_evs, d, "production day == %s" % d)
+ ws, _ = week_of(self.day)
+ rk["week"] = self.rank_events([e for e in self.events if e["day"] and str(ws) <= e["day"] <= d],
+ "%s..%s" % (ws, d), "production day %s to %s (week to date, Mon-Sun)" % (ws, d))
+ ms = self.day.replace(day=1)
+ rk["month"] = rk["week"] if ms == ws else self.rank_events(
+ [e for e in self.events if e["day"] and str(ms) <= e["day"] <= d],
+ "%s..%s" % (ms, d), "production day %s to %s (month to date)" % (ms, d))
+ rk["window"] = self.rank_events([e for e in self.events if e["day"]], "window", "every event in the export")
+ self.model["downtime"] = rk
+ if d and d in self.perday:
+ today = self.perday[d]
+ f = self.F
+ for part, a in today["parts"].items():
+ k = "out.%s.%s" % (d, part)
+ f.add(k + ".planned", "Planned, %s, %s" % (part, d), a["planned"], "plan export", "plan_date == %s; part == %s" % (d, part), period=d, unit=a["item_unit"] or "")
+ f.add(k + ".good", "Good, %s, %s" % (part, d), a["good"], "MES export", "production_day == %s; part == %s; held-out rows excluded" % (d, part), period=d, unit=", ".join(a["units"]))
+ if a["status"] == "comparable":
+ f.add(k + ".variance", "Variance, %s, %s" % (part, d), a["variance"], "plan and MES", "good - planned", period=d)
+ f.add(k + ".variance_pct", "Variance %%, %s, %s" % (part, d), a["variance_pct"], "plan and MES", "(good - planned) / planned", period=d, unit="%")
+ for n, h in enumerate(a["held_out_rows"]):
+ f.add("%s.held.%d" % (k, n), "Held-out row, %s %s" % (h["work_order"], h["shift"]), h["good"], "MES export", h["why"], period=d)
+ for comp in ("availability", "performance", "quality", "oee"):
+ f.add("oee.%s.%s" % (d, comp), "Site %s, %s" % (comp, d), today[comp], "plan, MES, downtime, routings",
+ "time-weighted availability; ideal ÷ run performance; pooled quality", period=d)
+ for r in today["oee_by_asset"]:
+ for comp in ("availability", "performance", "quality", "oee"):
+ f.add("oee.%s.%s.%s" % (d, r["asset"], comp), "%s %s, %s" % (r["asset"], comp, d), r[comp],
+ "plan, MES, downtime, routings", "; ".join(r["why_not"]) or "asset == %s" % r["asset"], period=d)
+ for s in today["scrap"]:
+ f.add("scrap.%s.%s" % (d, s["part"]), "Scrap qty, %s, %s" % (s["part"], d), s["scrap"], "MES export",
+ "production_day == %s; held-out rows excluded" % d, period=d, unit=s["unit"] or "")
+ f.add("scrapusd.%s.%s" % (d, s["part"]), "Scrap $, %s, %s" % (s["part"], d), s["scrap_usd"], "MES x item master std_cost",
+ "unpriced when not recorded or a unit conflict", period=d, unit="USD")
+ f.add("scrapusd.%s.total" % d, "Priced scrap $, %s" % d, today["scrap_priced_usd"], "MES x item master std_cost", "sum of priced parts", period=d, unit="USD")
+ f.add("dtusd.%s" % d, "Downtime $, %s" % d, today["downtime_usd"], "downtime minutes x rate", today["rate_source"], period=d, unit="USD")
+ self.check(abs(sum(s["scrap_usd"] or 0 for s in today["scrap"]) - (today["scrap_priced_usd"] or 0)) <= 0.005,
+ "priced scrap per part sums to the total")
+ self.model["today"] = today
+ else:
+ self.model["today"] = None
+ # Day records, one per production day the exports cover.
+ records = []
+ for day, r in self.perday.items():
+ complete = all(self.covers(role, day) for role in ("plan", "output", "downtime"))
+ gaps = [] if complete else [
+ ("%s export did not land" % role) if role not in self.T else ("%s export has no rows for %s" % (role, day))
+ for role in ("plan", "output", "downtime") if not self.covers(role, day)]
+ if day in self.partial_shifts:
+ complete = False
+ gaps.append(self.partial_shifts[day])
+ rk_day = self.day_reasons(day)
+ records.append(OrderedDict([
+ ("contract_version", 1), ("record_key", "%s_%s" % (self.site, day)), ("site", self.site),
+ ("production_day", day), ("day_boundary", self.day_rule), ("run_timestamp", self.run_time.isoformat()),
+ ("data_as_of", self.model["freshness"]["data_as_of"]), ("data_complete", complete), ("gaps", gaps),
+ ("backfilled", day != d),
+ ("planned_qty", r["planned_qty"] if self.t("plan") else None),
+ ("actual_qty", r["actual_qty"] if self.t("output") else None),
+ ("output_provisional", r["output_provisional"]),
+ ("oee", r["oee"]), ("availability", r["availability"]), ("performance", r["performance"]),
+ ("quality", r["quality"]), ("quality_convention", r["quality_convention"]),
+ ("oee_basis", "per asset, time-weighted to site; excluded: " + ("; ".join(r["oee_excluded"]) or "none")),
+ ("downtime_by_reason", rk_day if self.t("downtime") else None),
+ ("downtime_minutes_total", r["downtime_minutes"] if self.t("downtime") else None),
+ ("open_outages", r["open_outages"]),
+ ("uncoded_share", self.uncoded(day) if self.t("downtime") else None),
+ ("blocked_safety_unknown", len(self.model.get("diagnoses", {}).get("blocked_safety_unknown", []))),
+ ("loss_usd", OrderedDict([("scrap", r["scrap_priced_usd"]), ("downtime", r["downtime_usd"]), ("currency", "USD")])),
+ ("rate_source", r["rate_source"]), ("unpriced", r["unpriced"]),
+ ("exceptions", [OrderedDict([("ref", x["ref"]), ("kind", x["kind"]), ("commitment_impact", x["commitment_impact"])])
+ for x in self.model["exceptions"]["items"]] if day == d else []),
+ ("data_problems_count", self.model["data_problems"]["count"]),
+ ]))
+ # Self-checks.
+ for day, r in self.perday.items():
+ for part, a in r["parts"].items():
+ if a["status"] == "comparable":
+ self.check(a["variance"] == intish(a["good"] - a["planned"]), "%s %s: variance = good - planned" % (day, part))
+ for rec in records:
+ for k in ("availability", "performance", "quality", "oee"):
+ v = rec[k]
+ self.check(v is None or v >= 0, "%s %s is not negative" % (rec["record_key"], k))
+ if rec["oee"] is not None:
+ self.check(None not in (rec["availability"], rec["performance"], rec["quality"]),
+ "%s: OEE only with all three components" % rec["record_key"])
+ self.model["checks"] = OrderedDict([("run", len(self.checks)), ("failed", [c["check"] for c in self.checks if not c["ok"]])])
+ n_short = sum(1 for r in self.F.rows if r["id"].startswith(Figures.SHORT_PREFIXES))
+ if n_short:
+ self.F.add("sp-figures.rows", "Rows in figures-short-page.csv", n_short + 1, "this file", "row count, this row included")
+ self.F.add("figures.rows", "Rows in figures.csv", len(self.F.rows) - n_short - (1 if n_short else 0) + 1, "this file",
+ "row count, this row included")
+ self.F.write(os.path.join(out_dir, "figures.csv"), os.path.join(out_dir, "figures-short-page.csv"))
+ with open(os.path.join(out_dir, "pulse_model.json"), "w", encoding="utf-8") as f:
+ json.dump(self.model, f, indent=1, default=jsonable)
+ if getattr(self, "short", None):
+ with open(os.path.join(out_dir, "periods.json"), "w", encoding="utf-8") as f:
+ json.dump(self.short, f, indent=1, default=jsonable)
+ with open(os.path.join(out_dir, "day_records.json"), "w", encoding="utf-8") as f:
+ json.dump(records, f, indent=1, default=jsonable)
+ return records
+
+ def shift_coverage(self):
+ """A day whose MES output carries fewer shifts than most days is not a complete plant day."""
+ by_day = defaultdict(set)
+ for x in self.out_rows:
+ s = (x["shift"] or "").strip()
+ if x["day"] and re.match(r"^\d{1,2}:\d{2}$", s):
+ by_day[x["day"]].add(s)
+ self.partial_shifts = {}
+ if len(by_day) >= 3:
+ counts = Counter(s for v in by_day.values() for s in v)
+ usual = sorted((s for s, c in counts.items() if c * 2 > len(by_day)), key=hm)
+ for d, have in by_day.items():
+ if have and any(s not in have for s in usual):
+ self.partial_shifts[d] = "production (MES output) export has only the %s shift%s for %s; most days carry %s" % (
+ ", ".join(sorted(have, key=hm)), "" if len(have) == 1 else "s", d, ", ".join(usual))
+ fr = self.model["freshness"]
+ g = self.partial_shifts.get(str(self.day))
+ if g:
+ fr["gaps"].append(g)
+ fr["day_source"] += "; only part of that day is in"
+ fr["data_complete"] = self.data_complete = False
+
+ def covers(self, role, day):
+ c = self.model["freshness"]["coverage"].get(role)
+ return bool(c and c["first"] <= day <= c["last"]) and role in self.T
+
+ def day_reasons(self, day):
+ g = OrderedDict()
+ for e in self.events:
+ if e["day"] != day or e["uncoded"] or e["blocked"]:
+ continue
+ a = g.setdefault(e["code"], OrderedDict([("reason_code", e["code"]), ("minutes", 0), ("events", 0), ("_held", 0)]))
+ a["events"] += 1
+ if e["minutes"] is None:
+ a["_held"] += 1
+ else:
+ a["minutes"] += e["minutes"]
+ rows = []
+ for a in sorted(g.values(), key=lambda a: -a["minutes"]):
+ rows.append(OrderedDict([("reason_code", a["reason_code"]), ("minutes", intish(a["minutes"]) if not a["_held"] else None),
+ ("events", a["events"])]))
+ return rows
+
+ def uncoded(self, day):
+ evs = [e for e in self.events if e["day"] == day and not e["blocked"]]
+ un = [e for e in evs if e["uncoded"]]
+ return OrderedDict([("events", len(un)), ("minutes", intish(sum(e["minutes"] for e in un if e["minutes"] is not None))),
+ ("of_events", len(evs)), ("of_minutes", intish(sum(e["minutes"] for e in evs if e["minutes"] is not None)))])
+
+ def run(self):
+ self.context()
+ self.normalize()
+ self.freshness()
+ self.output()
+ self.shift_coverage()
+ self.downtime()
+ self.fold_diagnoses()
+ self.days()
+ self.classes()
+ self.exceptions()
+ self.week_over_week()
+ self.periods()
+ self.short_periods()
+ if self.short:
+ self.decisions()
+ records = self.emit()
+ return records
+
+
+def tie_assets(rk):
+ """Assets tied on both minutes and events collapse into one row; single assets stay their own rows."""
+ groups = OrderedDict()
+ for a in rk["by_asset"]:
+ groups.setdefault((a["minutes"], a["events"], a["ongoing"]), []).append(a)
+ rows = []
+ for (mins, evs, ong), g in groups.items():
+ if len(g) == 1:
+ rows.append(OrderedDict([("assets", [g[0]["key"]])] + [(k, v) for k, v in g[0].items() if k != "key"]))
+ else:
+ rows.append(OrderedDict([("assets", [a["key"] for a in g]), ("events", evs), ("minutes", mins), ("ongoing", ong),
+ ("held_out", sum(a["held_out"] for a in g)), ("rank_minutes", g[0]["rank_minutes"]),
+ ("rank_events", g[0]["rank_events"]), ("tied", True)]))
+ rk["asset_rows"] = rows
+
+
+def items_col(items, canon):
+ return items.cols.get(canon) if items else None
+
+
+def part_key(r):
+ """What a plan or MES row is grouped under: its item-master part, else its own spelling. Never None."""
+ return r["_part"] if r.get("_part") is not None else (r.get("_part_verbatim") or "(no part number)")
+
+
+def new_part(part):
+ return OrderedDict([("part", part), ("planned", None), ("good", None), ("rows_counted", 0),
+ ("plan_spellings", set()), ("mes_spellings", set()), ("units", set()),
+ ("provisional", False), ("held_out_rows", []), ("status", None),
+ ("variance", None), ("variance_pct", None), ("under_plan", None)])
+
+
+def fmtq(v):
+ return "absent" if v is None else str(intish(v))
+
+
+def jsonable(o):
+ if isinstance(o, (datetime, date)):
+ return o.isoformat()
+ if isinstance(o, set):
+ return sorted(map(str, o))
+ raise TypeError(type(o))
+
+
+def summary(p, records):
+ m = p.model
+ fr = m["freshness"]
+ lines = ["site: %s | production day: %s (%s) | data complete: %s" % (
+ m["context"]["site"], fr["production_day"], fr["day_source"], fr["data_complete"])]
+ if fr["gaps"]:
+ lines.append("gaps: " + "; ".join(fr["gaps"]))
+ for a in m["context"]["assumptions"]:
+ lines.append("assumption: " + a)
+ lines.append("data problems (numbered): %d | checked, nothing wrong: %d | exceptions: %d" % (
+ m["data_problems"]["count"], len(m["data_problems"]["checked_nothing_wrong"]), len(m["exceptions"]["items"])))
+ t = m.get("today")
+ if t:
+ lines.append("OEE %s: availability %s, performance %s, quality %s, composite %s" % (
+ fr["production_day"], t["availability"], t["performance"], t["quality"], t["oee"]))
+ lines.append("downtime %s: %s min trusted, %s events, %s open | scrap priced $%s | downtime $ %s (%s)" % (
+ fr["production_day"], t["downtime_minutes"], t["events"], t["open_outages"], t["scrap_priced_usd"],
+ t["downtime_usd"] if t["downtime_usd"] is not None else "unpriced", t["rate_source"]))
+ lines.append("figures: %d rows | day records: %d | self-checks: %d run, %d failed" % (
+ len(p.F.rows), len(records), m["checks"]["run"], len(m["checks"]["failed"])))
+ return "\n".join(lines)
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("--exports", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--day")
+ ap.add_argument("--profile")
+ ap.add_argument("--rates", help="the plant's rates file (## Plant rates), plant_setup.py's rates_path")
+ ap.add_argument("--diagnoses")
+ ap.add_argument("--manifest")
+ ap.add_argument("--run-time")
+ ap.add_argument("--tz")
+ args = ap.parse_args(argv)
+ p = Pulse(args)
+ records = p.run()
+ print(summary(p, records))
+ failed = p.model["checks"]["failed"]
+ if failed:
+ print("SELF-CHECK FAILED:\n " + "\n ".join(failed), file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/render_short.py b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/render_short.py
new file mode 100644
index 00000000..422e6407
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/morning-plant-pulse/scripts/render_short.py
@@ -0,0 +1,806 @@
+"""Render the short Operations page from the compute engine's output.
+
+ python3 -I render_short.py --out pulse-output [--full-page-url URL] [--day YYYY-MM-DD]
+
+Reads pulse_model.json, periods.json, figures.csv and figures-short-page.csv
+from --out, written by pulse_compute.py in the same run, and writes
+operations-short-<site>-<day>.html there. It selects and formats values; it
+does no arithmetic. Every number it prints is a figures row, and the page
+carries that row's id, so the checks at the end can prove it.
+
+The checks at the end run on every render. Any failure exits 2 and no page is
+written.
+"""
+import argparse
+import csv
+import html
+import json
+import os
+import re
+import sys
+from collections import OrderedDict
+
+DRAFT_WORDS = ("hand-edited", "mockup")
+LEVELS = ("day", "week", "month")
+
+
+def esc(s):
+ return html.escape("" if s is None else str(s), quote=True)
+
+
+def idn(s):
+ """An identifier (part, work order, lot): mono, and never read as a quantity."""
+ return '<code class="id">%s</code>' % esc(s)
+
+
+def load_figures(*paths):
+ figs = OrderedDict()
+ for p in paths:
+ if os.path.exists(p):
+ with open(p, newline="", encoding="utf-8") as f:
+ for r in csv.DictReader(f):
+ figs[r["id"]] = r
+ return figs
+
+
+class Page:
+ def __init__(self, out, full_page_url=None, day=None):
+ self.out = out
+ self.model = json.load(open(os.path.join(out, "pulse_model.json"), encoding="utf-8"))
+ self.per = json.load(open(os.path.join(out, "periods.json"), encoding="utf-8"))
+ self.figs = load_figures(os.path.join(out, "figures.csv"), os.path.join(out, "figures-short-page.csv"))
+ self.url = full_page_url
+ ctx, fr = self.model["context"], self.model["freshness"]
+ self.site = ctx["site"]
+ self.requested = day or fr["production_day"]
+ self.latest = self.per["latest"]
+ self.errors = []
+
+ # -- numbers: every one is a figures row -----------------------------------
+ def n(self, fid, kind="count", none=None, scale=1, unit=""):
+ """A figure, formatted. `none` is what an absent value says (a label, never 0, blank or a dash)."""
+ row = self.figs.get(fid)
+ if row is None:
+ self.errors.append("no figures row %s" % fid)
+ return '<span class="na">not computable</span>'
+ v = row["value"]
+ if v in ("not computable", ""):
+ return none or '<a class="na" href="#dp-gaps">not computable &#8595;</a>'
+ try:
+ x = float(v) * scale
+ except ValueError:
+ return '<span class="n" data-fig="%s">%s</span>' % (esc(fid), esc(v))
+ if kind == "usd":
+ txt = "${:,.2f}".format(x)
+ elif kind == "pct":
+ txt = ("{:,.1f}".format(x).rstrip("0").rstrip(".") if abs(x) % 1 else "{:,.0f}".format(x)) + "%"
+ elif kind == "signed":
+ txt = ("+" if x > 0 else "") + ("{:,.0f}".format(x) if x == int(x) else "{:,.1f}".format(x))
+ elif kind == "signedpct":
+ txt = ("+" if x > 0 else "") + "{:,.1f}".format(x) + "%"
+ else:
+ txt = "{:,.0f}".format(x) if x == int(x) else "{:,}".format(x)
+ sc = "" if scale == 1 else ' data-scale="%s"' % scale
+ return '<span class="n" data-fig="%s"%s>%s</span>%s' % (esc(fid), sc, txt, esc(unit))
+
+ def text_fig(self, fid):
+ """A sentence the engine wrote, printed verbatim from its figures row and checked as such."""
+ row = self.figs.get(fid)
+ if row is None:
+ self.errors.append("no figures row %s" % fid)
+ return ""
+ return '<span class="ft" data-figtext="%s">%s</span>' % (esc(fid), esc(row["value"]))
+
+ def has(self, fid):
+ return fid in self.figs and self.figs[fid]["value"] not in ("not computable", "")
+
+ # -- the page ---------------------------------------------------------------
+ def render(self):
+ m = self.model
+ parts = [self.header(), self.safety(), self.freshness(), self.decisions(), self.exceptions(),
+ self.toggle(), self.views(), self.cant_show(), self.data_problems(), self.footer()]
+ body = "\n".join(p for p in parts if p)
+ title = "%s: short Operations page, %s" % (self.site, self.requested)
+ return TEMPLATE.replace("{{TITLE}}", esc(title)).replace("{{CSS}}", CSS).replace("{{BODY}}", body) \
+ .replace("{{VIEWS}}", json.dumps(self.per["views"])).replace("{{LATEST}}", json.dumps(self.latest)) \
+ .replace("{{START}}", json.dumps(self.latest if self.requested not in self.per["views"] else self.requested)) \
+ .replace("{{LABELS}}", json.dumps({k: self.view_label(k) for k in self.per["rollups"]}))
+
+ def header(self):
+ run = self.model["context"]["run_time"][:10]
+ return ('<header class="page-header avoid"><h1>%s: short Operations page</h1>'
+ '<p class="meta">%s &middot; production day %s &middot; generated %s</p>'
+ '<p class="sub">Generated from the morning-plant-pulse run of %s. Read-only, nothing written to any system.</p>'
+ '</header>') % (esc(self.site), esc(self.site), esc(self.requested), esc(self.model["context"]["run_time_local"]), esc(run))
+
+ def safety(self):
+ dg = self.model["diagnoses"]
+ out = []
+ for d in dg["safety_flagged"]:
+ out.append('<div class="card critical avoid"><span class="status status--critical">Safety</span> '
+ '<strong>%s</strong>, %s to %s: %s. %s</div>' % (
+ esc(d["asset"]), esc(d["start"]), esc(d["end"]), esc(d["reason_text"]),
+ esc(d["safety_reason"] or "Flagged by breakdown-diagnosis.")))
+ for d in dg["blocked_safety_unknown"]:
+ out.append('<div class="card warn avoid"><span class="status status--warn">Blocked, safety status unknown</span> '
+ '<strong>%s</strong> from %s: %s. Held out of every figure on this page.</div>' % (
+ esc(d["asset"]), esc(d["start"]), esc(d["why"])))
+ return '<section class="safety">%s</section>' % "".join(out) if out else ""
+
+ def freshness(self):
+ fr, ctx = self.model["freshness"], self.model["context"]
+ missing = [g for g in fr["gaps"] if "did not land" in g]
+ partial = [g for g in fr["gaps"] if "has only the" in g]
+ other = [g for g in fr["gaps"] if g not in missing and g not in partial] # coverage, unreadable dates, any other
+ if missing:
+ landed = "Last night's export did not land in full: %s." % "; ".join(esc(g) for g in missing)
+ elif fr["days_old"] is not None and fr["days_old"] > 1:
+ landed = "Last night's export landed, but holds nothing after %s." % esc(fr["newest_production_day"])
+ elif other or (fr.get("data_complete") is False and not partial):
+ landed = "Last night's export is not complete for this day."
+ else:
+ landed = "Last night's export landed."
+ line = ['<p class="fresh avoid" id="freshness">', landed]
+ if partial:
+ line.append(" Not a complete plant day: %s." % "; ".join(esc(g) for g in partial))
+ if other:
+ line.append(" Gaps: %s." % "; ".join(esc(g) for g in other))
+ if fr.get("data_as_of_local"):
+ line.append(" Sources last landed %s." % esc(fr["data_as_of_local"]))
+ if fr["newest_production_day"]:
+ line.append(" Newest production day %s, %s day%s old." % (esc(fr["newest_production_day"]), self.n("fresh.days_old"),
+ "" if fr["days_old"] == 1 else "s"))
+ w = self.per["data_window"]
+ line.append(" This page covers %s to %s." % (esc(w[0]), esc(w[1])))
+ if ctx["time_zone_assumed"]:
+ why = "no plant profile" if not ctx["profile"] else "the plant profile sets no time zone"
+ line.append(" Times are plant local, assumed %s; %s." % (esc(ctx["time_zone"]), esc(why)))
+ line.append("</p>")
+ table = ""
+ cov = fr["coverage"]
+ if fr["sources_disagree"]:
+ rows = "".join("<tr><td>%s</td><td>%s</td><td>%s to %s</td></tr>" % (esc(c["file"]), esc(c.get("landed") or "not dated"),
+ esc(c["first"]), esc(c["last"])) for c in cov.values())
+ table = ('<div class="table-scroll"><table class="avoid"><thead><tr><th>Source</th><th>Landed</th><th>Covers</th></tr>'
+ '</thead><tbody>%s</tbody></table></div>' % rows)
+ return "".join(line) + table
+
+ # -- today's decisions ------------------------------------------------------
+ def decisions(self):
+ sp = self.model["short_page"]
+ items = []
+ for d in sp["decisions"]:
+ items.append("<li class=\"avoid\">%s</li>" % getattr(self, "decision_" + d["kind"])(d))
+ rem = sp["remaining"]
+ bits = []
+ if rem["unit_conflicts"]:
+ bits.append("the unit conflict%s on %s" % ("s" if len(rem["unit_conflicts"]) > 1 else "", ", ".join(idn(x) for x in rem["unit_conflicts"])))
+ if rem["normalizations"]:
+ bits.append("%s part-number fixes awaiting approval, %s rows provisional until then" % (
+ self.n("remaining.normalizations"), self.n("remaining.provisional_rows")))
+ if rem["ncr_keys"]:
+ bits.append("NCR keys that disagree with the ERP")
+ for k in rem["overflow"]:
+ bits.append({"late_jobs": "the late work orders", "quality_hold": "a customer quality hold",
+ "machine": "a machine decision", "export": "the export"}.get(k, k))
+ link = ('<a href="%s">the full Operations page</a>' % esc(self.url)) if self.url else \
+ "the full Operations page (in this run's reply)"
+ rest = ('<p class="remaining avoid">Also waiting on a decision: %s. Details on %s.</p>' % ("; ".join(bits), link)) if bits else \
+ '<p class="remaining avoid">Nothing else is waiting on a decision. Details on %s.</p>' % link
+ return '<section class="panel" id="decisions"><h2>Today&#8217;s decisions</h2><ol>%s</ol>%s</section>' % ("".join(items), rest)
+
+ def decision_export(self, d):
+ if d["missing"]:
+ what = "%s." % "; ".join(esc(x[0].upper() + x[1:]) for x in d["missing"])
+ else:
+ what = "Last night&#8217;s drop holds nothing after %s (%s day%s old)." % (esc(d["newest_day"]), self.n("fresh.days_old"),
+ "" if d["days_old"] == 1 else "s")
+ return ("<strong>Export.</strong> %s Restart the export, then re-run the pulse; a re-run rewrites this page "
+ "rather than adding a second one." % what)
+
+ def decision_machine(self, d):
+ a, mk = d["asset"], "dt.sp-" + d["period"]
+ s = []
+ if not d["diagnosed"]:
+ s.append("Safety status: not assessed.")
+ elif d["safety"]:
+ s.append("Safety status: flagged by breakdown-diagnosis (%s)." % esc(d["safety"][1] or "see the diagnosis record"))
+ else:
+ s.append("Safety status: no safety trigger in the diagnosis record; this is not a safety assessment.")
+ acts = "confirm whether %s is still down, then run a breakdown diagnosis." % esc(a)
+ s.append(("Lock out %s, " % esc(a) + acts) if d["lockout"] else acts[0].upper() + acts[1:])
+ ev = "%s%s carries %s of downtime minutes month to date (%s of %s min)%s" % (
+ esc(a), " (%s)" % esc(d["cell"]) if d["cell"] else "", self.n("decision.machine.share", "pct"),
+ self.n("%s.asset.%s.minutes" % (mk, a)), self.n("%s.minutes" % mk),
+ ", approximate because some of its stops have durations that disagree with their timestamps" if d["approximate"] else "")
+ if d["reason_text"]:
+ ev += "; MES reason text &#8220;%s&#8221;" % esc(d["reason_text"])
+ if d["down_since"]:
+ since = d["down_since"].replace(" (plant local)", "")
+ if d["stale"]:
+ ev += "; down since %s (plant local; as of %s, current state unknown)" % (esc(since), esc(d["as_of"]))
+ else:
+ ev += "; down since %s" % esc(d["down_since"])
+ s.append(ev + ".")
+ if d["lockout"]:
+ if d["seizure"]:
+ first = re.split(r"(?<=[.!?])\s", d["seizure"]["note"].strip())[0].rstrip(".")
+ why = "%s on %s records &#8220;%s&#8221;" % (esc(d["seizure"]["maintenance_wo"]), esc(d["seizure"]["date"]), esc(first))
+ else:
+ why = "its maintenance history shows a repeat failure"
+ s.append("Precaution, not a finding: safety hasn&#8217;t been assessed and %s." % why)
+ return "<strong>Machine: %s.</strong> %s" % (esc(a), " ".join(s))
+
+ def decision_quality_hold(self, d):
+ wos = ", ".join(esc(x) for x in (d["orders_on_lot"] or [d["work_order"]]))
+ s = "<strong>Quality hold: %s.</strong> %s is open against %s from lot %s, work orders %s." % (
+ esc(d["customer"]), esc(d["ncr"]), idn(d["part"]), idn(d["lot"]), wos)
+ if d["open_lines"] is None:
+ s += " The customer&#8217;s open lines are not in this drop (no sales order export)."
+ elif d["open_lines"]:
+ s += " Open lines: %s." % ", ".join(esc(x["sales_order"]) for x in d["open_lines"])
+ if d["ncrs_part_differs"]:
+ s += " Hold scope unreliable: %s of %s NCRs name a different part than the ERP for the same work order." % (
+ self.n("decision.hold.ncr_part_differs"), self.n("decision.hold.ncrs"))
+ return s
+
+ def decision_late_jobs(self, d):
+ usd = (" (%s at standard cost)" % self.n("decision.late.usd", "usd")) if self.has("decision.late.usd") else ""
+ s = "<strong>Late work orders.</strong> %s open work orders are past due and short by %s units%s: close them short or schedule the make-up." % (
+ self.n("decision.late.count"), self.n("decision.late.units"), usd)
+ if not self.model["exceptions"]["so_link"]:
+ s += " Commitment impact not traceable: no work order to sales order link in the ERP."
+ return s
+
+ # -- exceptions, the whole data window ---------------------------------------
+ def exceptions(self):
+ cards = []
+ for x in self.model["exceptions"]["items"]:
+ k, d = x["kind"], x["detail"]
+ if k == "late_job":
+ body = "<strong>%s</strong> &middot; %s &middot; good / ordered %s &middot; due %s" % (
+ esc(x["ref"]), idn(d["part"]), self.n("exc.late." + x["ref"]), esc(d["due"]))
+ elif k == "machine_down":
+ body = "<strong>%s</strong> down since %s, ongoing, length unknown &middot; %s &#8220;%s&#8221;" % (
+ esc(x["ref"]), esc(d["down_since"]), esc(d["code"]), esc(d["text"]))
+ elif k == "quality_hold":
+ body = "<strong>%s</strong> open for %s &middot; %s &middot; %s &middot; lot %s" % (
+ esc(x["ref"]), esc(d["customer"]), esc(d["work_order"]), idn(d["part"]), idn(d["lot"]))
+ else:
+ body = "<strong>%s</strong> %s" % (esc(x["ref"]), esc(d.get("line", "")))
+ label = {"late_job": "Late", "machine_down": "Machine down", "quality_hold": "Quality hold",
+ "one_sided_contradicted": "One-sided, contradicted"}.get(k, k)
+ cards.append('<div class="card avoid"><span class="status status--warn">%s</span> %s</div>' % (label, body))
+ if not cards:
+ cards.append('<p>No exceptions in the data window.</p>')
+ return '<section class="panel" id="exceptions"><h2>Exceptions</h2><p class="note">Covers the whole data window.</p>%s</section>' % "".join(cards)
+
+ # -- the period toggle and its three sections ---------------------------------
+ def view_label(self, key):
+ r = self.per["rollups"][key]
+ if r["kind"] == "day":
+ return r["label"]
+ if r["kind"] == "week":
+ if r["partial"]:
+ return "%s. Partial: data for %d of 7 days (%s); the export has nothing for %s" % (
+ r["label"], len(r["covered"]), ", ".join(r["covered"]), ", ".join(r["missing"]))
+ return r["label"]
+ return r["label"]
+
+ def toggle(self):
+ req_note = ""
+ if self.requested not in self.per["views"]:
+ req_note = "Latest day with data: %s (no data for %s)" % (self.latest, self.requested)
+ return ('<div class="toggle" id="toggle"><div class="buttons" role="group" aria-label="Period">'
+ '<button type="button" data-level="day">Day</button><button type="button" data-level="week">Week</button>'
+ '<button type="button" data-level="month">Month</button></div>'
+ '<p class="period-label" id="period-label" data-note="%s"></p><span class="pill" id="partial-pill" hidden>Partial month</span>'
+ '<a href="#" id="back" hidden></a></div>' % esc(req_note))
+
+ def views(self):
+ blocks = []
+ for key, r in self.per["rollups"].items():
+ blocks.append('<div class="view" data-view="%s" hidden>%s%s%s</div>' % (
+ esc(key), self.output_section(key, r), self.downtime_section(key, r), self.scrap_section(key, r)))
+ return '<div id="views">%s</div>' % "".join(blocks)
+
+ def heading(self, name, r):
+ return "<h2>%s &middot; %s</h2>" % (name, r["kind"])
+
+ def out_fig(self, key, part, fld, kind="count"):
+ return self.n("per.sp-%s.out.%s.%s" % (key, part, fld), kind)
+
+ def output_section(self, key, r):
+ sm, k = r["summary"], r["kind"]
+ sent = []
+ if sm["comparable_parts"]:
+ mood = "all under" if sm["all_under"] else ("all over" if sm["all_over"] else "some over, some under")
+ s = "Comparable parts within %s of plan (%s)" % (self.n("per.sp-%s.maxvar" % key, "pct"), mood)
+ if k != "day":
+ s += ", under plan on %s days" % ", ".join("%s of %s" % (self.out_fig(key, x["part"], "days_under_plan"),
+ self.out_fig(key, x["part"], "days_compared")) for x in sm["days_under"])
+ sent.append(s + ".")
+ else:
+ sent.append("No part is comparable with plan in this view.")
+ prov = [x for x in sm["provisional"]]
+ if prov:
+ sent.append("%s rest%s on unapproved part-number fixes." % (" and ".join(idn(x["part"]) for x in prov), "" if len(prov) > 1 else "s"))
+ for h in sm["held_out_parts"]:
+ sent.append("%s excludes %s (duplicate-key output, unresolved)." % (idn(h["part"]), ", ".join(esc(x) for x in h["days"])))
+ for x in sm["not_comparable"]:
+ sent.append("%s: not comparable, %s." % (idn(x["part"]), esc(x["why"])))
+ rows = []
+ for part, t in r["parts"].items():
+ label = '<span class="status status--warn">Provisional</span>' if t["provisional"] else '<span class="status status--good">Exact match</span>'
+ spell = "plan: %s &middot; MES: %s" % (", ".join("<code>%s</code>" % esc(x) for x in t["plan_spellings"]) or "none",
+ ", ".join("<code>%s</code>" % esc(x) for x in t["mes_spellings"]) or "none")
+ if t["status"] == "comparable":
+ plan, good = self.out_fig(key, part, "planned"), self.out_fig(key, part, "good")
+ var = "%s (%s)" % (self.out_fig(key, part, "variance", "signed"), self.out_fig(key, part, "variance_pct", "signedpct"))
+ last = ("yes" if t["days_under_plan"] else "no") if k == "day" else "%s of %s" % (
+ self.out_fig(key, part, "days_under_plan"), self.out_fig(key, part, "days_compared"))
+ elif t["status"] == "not comparable, unit conflict":
+ plan = "%s %s" % (self.out_fig(key, part, "planned"), esc(t["item_unit"] or ""))
+ good = "%s %s" % (self.out_fig(key, part, "good"), esc(", ".join(t["units"])))
+ var, last = '<span class="status status--warn">Unit conflict</span>', "not comparable"
+ elif t["days_held_out"] and k == "day":
+ plan, good, var, last = "not counted", "held out", "held out", "held out"
+ else:
+ plan = good = var = last = "no comparable day"
+ rows.append("<tr><td><strong>%s</strong> %s<br><small>%s</small></td><td class=\"num\">%s</td><td class=\"num\">%s</td>"
+ "<td class=\"num\">%s</td><td class=\"num\">%s</td></tr>" % (idn(part), label, spell, plan, good, var, last))
+ held = ""
+ if r["held_out_rows"]:
+ dups = self.model["data_problems"]["duplicates"]
+ vals = "; ".join("%s: %s good, none picked or summed" % (esc(d["work_order"]), self.n("dup.%d.values" % i))
+ for i, d in enumerate(dups) if d["day"] in r["covered"])
+ held = '<p class="note">%s held-out rows (%s good) are not in these totals%s.</p>' % (
+ self.n("per.sp-%s.held" % key), self.n("per.sp-%s.heldgood" % key), ("; " + vals) if vals else "")
+ table = ('<details class="tbl" open><summary>Output by part (table)</summary><div class="table-scroll"><table>'
+ '<thead><tr><th>Part</th><th class="num">Plan</th><th class="num">Good</th><th class="num">Variance</th>'
+ '<th class="num">%s</th></tr></thead><tbody>%s</tbody></table></div></details>' % (
+ "Under plan" if k == "day" else "Days under plan", "".join(rows)))
+ bd = self.breakdown(r, "output") if k != "day" else ""
+ return '<section class="panel">%s<p class="summary">%s</p>%s%s%s</section>' % (
+ self.heading("Output against plan", r), " ".join(sent), table, held, bd)
+
+ def breakdown(self, r, what):
+ parts = list(r["parts"].keys()) if what == "output" else list(r["scrap"].keys())
+ head = "".join("<th class=\"num\">%s</th>" % idn(p) for p in parts)
+ if what == "scrap":
+ head += '<th class="num">Priced $</th>'
+ if what == "downtime":
+ head = '<th class="num">Events</th><th class="num">Recorded min</th><th class="num">Ongoing</th><th class="num">Other or blank</th>'
+ rows = []
+ for d in r["covered"]:
+ dk = "day:%s" % d
+ dr = self.per["rollups"][dk]
+ cells = []
+ if what == "output":
+ for p in parts:
+ t = dr["parts"].get(p)
+ if not t:
+ cells.append("no plan")
+ elif t["status"] == "comparable":
+ cells.append("%s / %s (%s)" % (self.out_fig(dk, p, "good"), self.out_fig(dk, p, "planned"),
+ self.out_fig(dk, p, "variance", "signed")))
+ elif t["status"] == "not comparable, unit conflict":
+ cells.append("unit conflict")
+ elif t["days_held_out"]:
+ cells.append("held out")
+ else:
+ cells.append("no comparable day")
+ elif what == "scrap":
+ for p in parts:
+ cells.append(self.scrap_qty(dk, p, dr["scrap"].get(p)) if p in dr["scrap"] else "no output")
+ cells.append(self.n("per.sp-%s.scrapusd" % dk, "usd", none="none priced"))
+ else:
+ p = "dt.sp-" + dk
+ cells = [self.n(p + ".events"), self.n(p + ".minutes"), self.n(p + ".ongoing"),
+ "%s min, %s events" % (self.n(p + ".uncoded_minutes"), self.n(p + ".uncoded_events"))]
+ rows.append('<tr><td><a href="#" class="go-day" data-day="%s">%s</a></td>%s</tr>' % (
+ esc(d), esc(d), "".join("<td class=\"num\">%s</td>" % c for c in cells)))
+ return ('<details class="breakdown"><summary>Day by day</summary><div class="table-scroll"><table><thead><tr><th>Day</th>%s</tr>'
+ '</thead><tbody>%s</tbody></table></div></details>' % (head, "".join(rows)))
+
+ def downtime_section(self, key, r):
+ dt = r.get("downtime")
+ if dt is None:
+ return '<section class="panel">%s<p>The downtime export did not land, so downtime is not computable for this view. ' \
+ '<a href="#dp-gaps">&#8595;</a></p></section>' % self.heading("Downtime", r)
+ p = "dt.sp-" + key
+ if dt["events"]:
+ lead = '<p class="summary">%s events (incl. %s ongoing), %s min recorded. %s of %s events (%s) and %s of %s min (%s) carry no usable reason code (Other or blank).</p>' % (
+ self.n(p + ".events"), self.n(p + ".ongoing"), self.n(p + ".minutes"), self.n(p + ".uncoded_events"),
+ self.n(p + ".events"), self.n(p + ".uncoded_pct", "pct"), self.n(p + ".uncoded_minutes"), self.n(p + ".minutes"),
+ self.n(p + ".uncoded_min_pct", "pct", none="share not computable"))
+ else:
+ lead = '<p class="summary">No stops recorded in this view.</p>'
+ if r["kind"] == "day":
+ rows = []
+ for i, st in enumerate(r.get("stops", [])):
+ if "ongoing" in st["flags"]:
+ mins = "ongoing, length unknown"
+ elif st["minutes"] is None:
+ mins = 'held out: %s, %s <a href="#dp-integrity">&#8595;</a>' % (
+ (self.n("sp-%s.stop.%d.stated" % (key, i)) + " stated") if st.get("stated_minutes") is not None
+ else "no duration stated",
+ esc("/".join(st["flags"]).replace("_", " ")))
+ else:
+ mins = self.n("sp-%s.stop.%d" % (key, i))
+ rows.append("<tr><td>%s%s</td><td>%s</td><td class=\"num\">%s</td><td>%s</td><td>%s</td></tr>" % (
+ esc(st["asset"]), (" (%s)" % esc(st["cell"])) if st["cell"] else "", esc(st["start"]), mins, esc(st["code"]), esc(st["text"])))
+ table = ('<div class="table-scroll"><table><thead><tr><th>Machine (cell)</th><th>Start</th><th class="num">Minutes</th>'
+ '<th>Code</th><th>Reason text</th></tr></thead><tbody>%s</tbody></table></div>' % "".join(rows)) if rows else ""
+ return '<section class="panel">%s%s%s</section>' % (self.heading("Downtime", r), lead, table)
+ rows = ['<tr class="grp"><th colspan="5">Assets</th></tr>']
+ for a in dt["asset_rows"]:
+ k0 = a["assets"][0]
+ base = "%s.asset.%s" % (p, k0)
+ if len(a["assets"]) > 1:
+ name = "%s assets tied at %s min, %s events each: %s" % (self.n(a["tie_id"]), self.n(base + ".minutes"), self.n(base + ".events"),
+ ", ".join(esc(x) for x in a["assets"]))
+ else:
+ name = esc(k0)
+ rows.append(self.rank_row(name, base, a))
+ rows.append('<tr class="grp"><th colspan="5">Named reason codes</th></tr>')
+ for c in dt["by_code"]:
+ rows.append(self.rank_row(idn(c["key"]), "%s.code.%s" % (p, c["key"]), c))
+ held = ""
+ if dt["held_out"]:
+ held = '<p class="note">Duration conflicts, minutes held out of these totals: %s.</p>' % "; ".join(
+ "%s %s to %s" % (esc(h["asset"]), esc(h["start"]), esc(h["end"])) for h in dt["held_out"])
+ table = ('<div class="table-scroll"><table><thead><tr><th>Asset or code</th><th class="num">Minutes</th><th class="num">Events</th>'
+ '<th class="num">Rank by minutes</th><th class="num">Rank by events</th></tr></thead><tbody>%s</tbody></table></div>' % "".join(rows))
+ return '<section class="panel">%s%s%s%s%s</section>' % (self.heading("Downtime", r), lead, table, held, self.breakdown(r, "downtime"))
+
+ def rank_row(self, name, base, a):
+ if a["ongoing"] and a["ongoing"] == a["events"]:
+ mins = "ongoing, length unknown"
+ else:
+ mins = self.n(base + ".minutes")
+ evs = self.n(base + ".events") + ((" (incl. %s ongoing)" % self.n(base + ".ongoing")) if a["ongoing"] else "")
+ return '<tr><td>%s</td><td class="num">%s</td><td class="num">%s</td><td class="num">%s</td><td class="num">%s</td></tr>' % (
+ name, mins, evs, self.n(base + ".rank_minutes"), self.n(base + ".rank_events"))
+
+ def scrap_qty(self, key, part, s):
+ if s is None or s["scrap"] is None:
+ return '<a class="na" href="#dp-gaps">absent &#8595;</a>'
+ return "%s %s" % (self.n("per.sp-%s.scrap.%s" % (key, part)), esc(s["unit"] or ""))
+
+ def scrap_section(self, key, r):
+ rows = []
+ for part, s in r["scrap"].items():
+ if s["scrap"] is None:
+ usd = '<a class="na" href="#dp-gaps">absent &#8595;</a>'
+ elif s["unit_conflict"]:
+ usd = 'unpriced (set how many %s per %s)' % (esc(r["parts"].get(part, {}).get("item_unit") or "units"), esc(s["unit"]))
+ else:
+ usd = self.n("per.sp-%s.scrapusd.%s" % (key, part), "usd", none="unpriced (no standard cost on file)")
+ share = self.n("per.sp-%s.scrapshare.%s" % (key, part), "pct", none="not priced")
+ qual = self.out_fig(key, part, "quality", "pct") if part in r["parts"] else "not computable"
+ if part in r["parts"] and self.has("per.sp-%s.out.%s.quality" % (key, part)):
+ qual = self.n("per.sp-%s.out.%s.quality" % (key, part), "pct", scale=100)
+ rows.append("<tr><td>%s</td><td class=\"num\">%s</td><td class=\"num\">%s</td><td class=\"num\">%s</td><td class=\"num\">%s</td></tr>" % (
+ idn(part), self.scrap_qty(key, part, s), usd, share, qual))
+ priced = self.n("per.sp-%s.scrapusd" % key, "usd", none="nothing priced")
+ top = max((s for s in r["scrap"].values() if s["share_of_priced"] is not None), key=lambda s: s["share_of_priced"], default=None)
+ tail = (" Top part %s is %s of it." % (idn(top["part"]), self.n("per.sp-%s.scrapshare.%s" % (key, top["part"]), "pct"))) if top else ""
+ t = self.model["today"] or {}
+ conv = esc(t.get("quality_convention") or "quality = good ÷ (good + scrap)")
+ if not conv.startswith("quality"):
+ conv = "quality = " + conv
+ oee = []
+ for comp, name in (("availability", "Availability"), ("performance", "performance"), ("oee", "composite OEE")):
+ fid = "oee.%s.%s" % (self.model["freshness"]["production_day"], comp)
+ oee.append("%s %s" % (name, self.n(fid, "pct", scale=100) if self.has(fid) else '<a class="na" href="#dp-gaps">not computable &#8595;</a>'))
+ left = [r["asset"] for r in t.get("oee_by_asset") or [] if r["availability"] is None and
+ any("untrusted or open" in w or "no planned production time" in w for w in r["why_not"])]
+ if left and self.has("oee.%s.availability" % self.model["freshness"]["production_day"]):
+ oee[0] += " (leaves out %s: a stop still open, untrusted minutes or no planned time)" % ", ".join(idn(a) for a in left)
+ note = '<p class="note">%s.</p><p class="note oee">OEE, %s: %s.</p>' % (conv, esc(self.model["freshness"]["production_day"]), ", ".join(oee))
+ table = ('<div class="table-scroll"><table><thead><tr><th>Part</th><th class="num">Scrap</th><th class="num">Scrap $</th>'
+ '<th class="num">Share of priced $</th><th class="num">Quality</th></tr></thead><tbody>%s</tbody></table></div>' % "".join(rows))
+ bd = self.breakdown(r, "scrap") if r["kind"] != "day" else ""
+ return '<section class="panel">%s<p class="summary">Scrap at standard cost, an estimate: %s.%s Downtime is unpriced: set MFG_DOWNTIME_COST_PER_HOUR or a plant profile rate.</p>%s%s%s</section>' % (
+ self.heading("Scrap, cost and quality", r), priced, tail, table, note, bd) if self.model["today"] and self.model["today"]["downtime_usd"] is None else \
+ '<section class="panel">%s<p class="summary">Scrap at standard cost, an estimate: %s.%s</p>%s%s%s</section>' % (self.heading("Scrap, cost and quality", r), priced, tail, table, note, bd)
+
+ # -- what the page cannot show, the data problems, the footer -----------------
+ def cant_show(self):
+ dec = {d["kind"]: d for d in self.model["short_page"]["decisions"]}
+ m = dec.get("machine")
+ q = dec.get("quality_hold")
+ worst = esc(m["asset"]) if m else "the worst machine"
+ cell = esc(m["cell"]) if m and m["cell"] else "its cell"
+ last = esc(self.model["freshness"]["newest_production_day"])
+ items = [
+ "Whether %s is down now: the data stops at %s." % (worst, last),
+ "Which orders depend on %s: %s" % (cell, "the ERP holds no work order to sales order link." if not self.model["exceptions"]["so_link"]
+ else "no routing or schedule in this drop ties orders to the cell."),
+ "Whether %s received parts from lot %s: no shipment records in this drop." % (esc(q["customer"]), esc(q["lot"])) if q else
+ "Whether any customer received parts from a suspect lot: no shipment records in this drop.",
+ ]
+ return '<section class="panel" id="cant-show"><h2>What this report can&#8217;t show yet</h2><ul>%s</ul></section>' % "".join(
+ "<li>%s</li>" % x for x in items)
+
+ def data_problems(self):
+ dp, ctx, fr, t = self.model["data_problems"], self.model["context"], self.model["freshness"], self.model["today"] or {}
+ wd = dp["waiting_on_decision"]
+ b1 = []
+ for x in wd["ncr_keys"]:
+ b1.append("<li>%s on %s: %s</li>" % (esc(x["ncr"]), esc(x["work_order"]), esc("; ".join(x["flags"]))))
+ for part, u in wd["unit_conflicts"].items():
+ b1.append("<li>Unit conflict: %s is %s in the MES and %s in the %s; no conversion factor on file.</li>" % (
+ idn(part), esc("/".join(u["export_units"])), esc(u["item_unit"]), esc("item master")))
+ if wd["normalizations"]:
+ b1.append("<li>%s part-number fixes awaiting approval; %s rows stay provisional until then.</li>" % (
+ self.n("remaining.normalizations"), self.n("remaining.provisional_rows")))
+ gaps = ["OEE components: %s." % esc("; ".join(t.get("oee_excluded") or ["see the full Operations page"]))]
+ gaps += ["%s." % esc(u[0].upper() + u[1:]) for u in t.get("unpriced", [])]
+ if "first-pass yield could not be applied" in (t.get("quality_convention") or ""):
+ gaps.append("First-pass yield: the export has no rework column.")
+ gaps.append("Output by cell, week-over-week movers and reschedule proposals: on the full Operations page.")
+ if "bom" not in " ".join(x["why"] for x in ctx["files_not_used"]):
+ gaps.append("Material shortages: no BOM or inventory in this drop.")
+ b3 = ["%s" % esc(a) for a in ctx["assumptions"]]
+ if not any(a.startswith("Production-day rule") for a in ctx["assumptions"]):
+ b3.append("Production-day rule: %s." % esc(ctx["day_boundary"]))
+ b3 += ["Not used: %s (%s)." % (esc(x["file"]), esc(x["why"])) for x in ctx["files_not_used"]]
+ b3.append("Every source is an export file; no system was queried live.")
+ b3 += ["Date window: %s." % esc(x) for x in dp["class7"]] or []
+ b4 = ["<li><code>%s</code> &#8594; <code>%s</code>, %s, %s rows. Proposed, awaiting approval.</li>" % (
+ esc(e["verbatim"]), esc(e["canonical"]), esc(e["rule"]), self.n("norm.%d.rows" % i))
+ for i, e in enumerate(self.model["normalizations"]) if e["status"] != "approved"]
+ mm = "".join("<tr><td class=\"num\">%s</td><td>%s</td><td><code>%s</code></td><td>%s</td></tr>" % (
+ '<span class="ord">%d</span>' % (i + 1), esc(x["name"]), esc(x["key"]), self.text_fig("problem.%d.what" % x["n"]))
+ for i, x in enumerate(dp["mismatched"]))
+ integ = dp["integrity"]
+ b6 = ["<li>Duration conflict: %s, %s to %s, %s.</li>" % (esc(x["asset"]), esc(x["start"]), esc(x["end"]), esc("/".join(x["flags"]).replace("_", " ")))
+ for x in integ["downtime_duration_conflicts"]]
+ b6 += ["<li>Blank lot: %s on %s.</li>" % (esc(x["work_order"]), esc(x["day"])) for x in integ["blank_lots"]]
+ b6 += ["<li>Cross-source conflict: %s on %s: %s.</li>" % (esc(x["ncr"]), esc(x["work_order"]), esc("; ".join(x["flags"]))) for x in wd["ncr_keys"]]
+ b6 += ["<li>Uninformative close-out note: %s on %s, &#8220;%s&#8221;</li>" % (esc(x["maintenance_wo"]), esc(x["asset"]), esc(x["note"]))
+ for x in integ["terse_close_out_notes"]]
+ b7 = ["<li>%s: %s.</li>" % (esc(c["record"]), esc(c["line"])) for c in dp["checked_nothing_wrong"]]
+
+ def ul(items, empty):
+ return "<ul>%s</ul>" % ("".join(x if x.startswith("<li>") else "<li>%s</li>" % x for x in items) if items else "<li>%s</li>" % empty)
+ return ('<details class="panel dp" id="data-problems"><summary><h2>Data problems</h2></summary>'
+ '<h3 id="dp-waiting">Waiting on a decision</h3>%s'
+ '<h3 id="dp-gaps">Other gaps in this run</h3>%s'
+ '<h3 id="dp-assumptions">Run assumptions</h3>%s'
+ '<h3 id="dp-normalizations">Part-number normalizations</h3>%s'
+ '<h3 id="dp-mismatched">Mismatched records &middot; %s</h3><div class="table-scroll"><table><thead><tr><th class="num">#</th>'
+ '<th>Class</th><th>Key</th><th>What</th></tr></thead><tbody>%s</tbody></table></div>'
+ '<h3 id="dp-integrity">Integrity flags</h3><p class="note">Not in the count above.</p>%s'
+ '<h3 id="dp-checked">Checked, nothing wrong</h3><p class="note">Not problems, and in no count.</p>%s'
+ '</details>') % (ul(b1, "Nothing waiting."), ul(gaps, "None."), ul(b3, "None."), ul(b4, "None awaiting approval."),
+ self.n("mismatched.count"), mm, ul(b6, "None."), ul(b7, "None."))
+
+ def footer(self):
+ run = self.model["context"]["run_time"][:10]
+ files = "figures.csv (%s rows) and figures-short-page.csv (%s rows), in the run's output folder" % (
+ self.n("figures.rows"), self.n("sp-figures.rows"))
+ return ('<footer class="page-footer"><p>Generated from the morning-plant-pulse run of %s. Read-only, nothing written to any system.</p>'
+ '<p>Every number on this page is in the figures tab: %s, each with its filter.</p>'
+ '<p>This is the short Operations page for production day %s. The full Operations page is separate; keep both.</p></footer>') % (
+ esc(run), files, esc(self.requested))
+
+ # -- the acceptance checks that need no browser ---------------------------------
+ def check(self, page):
+ errs = list(self.errors)
+ text = re.sub(r"<script\b.*?</script[^>]*>|<style\b.*?</style[^>]*>", "", page, flags=re.S | re.I)
+ low = text.lower()
+ for w in DRAFT_WORDS:
+ if w in low:
+ errs.append("draft wording on the page: %r" % w)
+ if re.search(r"save (it|this|the page|this page)? ?over", low):
+ errs.append("the footer must never say to save over the full Operations page")
+ # No new numbers: every data-fig span equals its row; no other digit outside dates, times and identifiers.
+ for fid, scale, shown in re.findall(r'data-fig="([^"]+)"(?: data-scale="([^"]+)")?>([^<]*)<', text):
+ scale = scale or "1"
+ row = self.figs.get(html.unescape(fid))
+ vals = [float(x) * float(scale) for x in re.findall(r"-?\d+(?:\.\d+)?", row["value"].replace(",", ""))] if row else []
+ got = [float(x) for x in re.findall(r"-?\d+(?:\.\d+)?", shown.replace(",", "").replace("+", ""))]
+ if not got or not all(any(abs(g - v) < 0.051 for v in vals) for g in got):
+ errs.append("number %r does not match figures row %s (%s)" % (shown, fid, row and row["value"]))
+ for fid, shown in re.findall(r'data-figtext="([^"]+)">([^<]*)<', text):
+ row = self.figs.get(html.unescape(fid))
+ if not row or html.unescape(shown) != row["value"]:
+ errs.append("text %s differs from its figures row" % fid)
+ bare = re.sub(r'<span class="(?:n|ft|ord)"[^>]*>[^<]*</span>|<code[^>]*>[^<]*</code>', "", text)
+ bare = re.sub(r"<[^>]+>", " ", bare)
+ bare = html.unescape(bare)
+ idents = set()
+ for r in self.per["rollups"].values():
+ for t in r["parts"].values():
+ idents.update([t["part"]] + t["plan_spellings"] + t["mes_spellings"])
+ for e in self.model["normalizations"]:
+ idents.update([e["verbatim"], e["canonical"]])
+
+ def strings(o):
+ # Every string the engine put in its output (asset, work order, lot, reason code, a
+ # date-window line) is text printed verbatim, never a quantity this page computed.
+ if isinstance(o, str):
+ idents.add(o)
+ elif isinstance(o, dict):
+ idents.update(o)
+ for v in o.values():
+ strings(v)
+ elif isinstance(o, list):
+ for v in o:
+ strings(v)
+ ctx = self.model["context"] # of the run's context, only what the page prints; never the self-check tally
+ strings({k: v for k, v in self.model.items() if k not in ("context", "checks")})
+ strings([ctx.get(k) for k in ("site", "time_zone", "day_boundary", "run_time_local", "assumptions", "files_not_used")])
+ strings(self.per)
+ for ident in sorted((i for i in idents if i and re.search(r"\d", i) and i.strip() in bare), key=len, reverse=True):
+ bare = re.sub(r"(?<![\w-])%s(?![\w])" % re.escape(ident.strip()), " ", bare)
+ bare = re.sub(r"\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?|\b\d{1,2}:\d{2}\b", " ", bare)
+ bare = re.sub(r"[A-Za-z][A-Za-z0-9_]*[-_ ]?[A-Za-z0-9-]*\d[A-Za-z0-9-]*", " ", bare)
+ bare = re.sub(r"\b(?:of 7 days|1-\d{1,2}|Rev \d+)\b", " ", bare)
+ stray = re.findall(r"(?<![\w-])\d[\d,.]*", bare)
+ stray = [x for x in stray if x.rstrip(".,") != "7"]
+ if stray:
+ errs.append("numbers printed with no figures row: %s" % ", ".join(sorted(set(stray))[:20]))
+ # Assumed time zone shown when no plant profile exists.
+ ctx = self.model["context"]
+ if ctx["time_zone_assumed"]:
+ fresh = re.search(r'<p class="fresh[^>]*>(.*?)</p>', text, re.S)
+ if not fresh or ctx["time_zone"] not in fresh.group(1) or ("no plant profile" not in fresh.group(1) and not ctx["profile"]):
+ errs.append("the freshness line must name the assumed time zone and 'no plant profile'")
+ # Safety label, lockout trigger, four sentences.
+ decs = self.model["short_page"]["decisions"]
+ mach = next((d for d in decs if d["kind"] == "machine"), None)
+ if mach:
+ li = re.search(r"<strong>Machine: [^<]*</strong>(.*?)</li>", text, re.S)
+ body = html.unescape(re.sub(r"<[^>]+>", "", li.group(1))) if li else ""
+ if not mach["diagnosed"] and "Safety status: not assessed" not in body:
+ errs.append("machine decision lacks 'Safety status: not assessed'")
+ if ("Lock out" in body) != bool(mach["lockout"]):
+ errs.append("lockout text does not follow the lockout trigger")
+ if "Lock out" in body and "Precaution, not a finding" not in body:
+ errs.append("lockout without its 'Precaution, not a finding' basis")
+ # Quoted source text and bracketed asides are counted with their sentence, not as sentences of their own.
+ prose = re.sub(r"\u201c.*?\u201d|\([^()]*\)", "", body, flags=re.S)
+ n_sent = len([x for x in re.split(r"(?<=[.!?])\s+(?=[A-Z])", prose.strip()) if x.strip()])
+ if n_sent > 4:
+ errs.append("machine decision has %d sentences, more than four" % n_sent)
+ order = {"export": 1, "machine": 2, "quality_hold": 3}
+ ranks = [order.get(d["kind"], 4) for d in decs]
+ if ranks != sorted(ranks) or len(decs) > 3:
+ errs.append("decisions out of priority order: %s" % [d["kind"] for d in decs])
+ # Month on the last day equals the full page's month figures.
+ mk = self.per["views"][self.latest]["month"]
+ full = self.model.get("periods", {}).get("month")
+ if full and full["days"] and full["days"][-1] == self.latest:
+ short = self.per["rollups"][mk]
+ for part, t in full["parts"].items():
+ s = short["parts"].get(part, {})
+ if (t.get("good"), t.get("variance")) != (s.get("good"), s.get("variance")):
+ errs.append("Month view differs from the full page for %s" % part)
+ if full["scrap_priced_usd"] != short["scrap_priced_usd"]:
+ errs.append("Month view priced scrap differs from the full page")
+ # Provisional labels survive in every view where a normalization was used.
+ for key, r in self.per["rollups"].items():
+ block = re.search(r'data-view="%s" hidden>(.*?)</div><div class="view"|data-view="%s" hidden>(.*)' % (re.escape(key), re.escape(key)), text, re.S)
+ chunk = (block.group(1) or block.group(2)) if block else ""
+ for part, t in r["parts"].items():
+ if t["provisional"] and "Provisional" not in chunk:
+ errs.append("view %s drops the Provisional label" % key)
+ break
+ return errs
+
+
+CSS = r"""
+:root{--ink:#1A1D21;--paper:#F2F3F5;--paper-raised:#FFFFFF;--line:#D6D9DD;--accent:#1F5C8B;--accent-soft:#E4EDF4;
+--good:#2E7248;--good-soft:#E3EFE7;--warn:#A8641A;--warn-soft:#F7EBDA;--critical:#A93226;--critical-soft:#F9E9E7;
+--font-display:'IBM Plex Sans Condensed','Arial Narrow',sans-serif;--font-body:'IBM Plex Sans',-apple-system,BlinkMacSystemFont,sans-serif;
+--font-mono:'IBM Plex Mono','SF Mono',Consolas,monospace}
+@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--ink:#E8EAEC;--paper:#15181B;--paper-raised:#1D2126;--line:#2E343A;
+--accent:#6BA8D4;--accent-soft:#1B2C39;--good:#6FBF88;--good-soft:#1B2E22;--warn:#D9A15C;--warn-soft:#33271A;--critical:#DE8378;--critical-soft:#35201E}}
+:root[data-theme="dark"]{--ink:#E8EAEC;--paper:#15181B;--paper-raised:#1D2126;--line:#2E343A;--accent:#6BA8D4;--accent-soft:#1B2C39;
+--good:#6FBF88;--good-soft:#1B2E22;--warn:#D9A15C;--warn-soft:#33271A;--critical:#DE8378;--critical-soft:#35201E}
+*{box-sizing:border-box}[hidden]{display:none!important}html,body{margin:0;background:var(--paper);color:var(--ink);font:400 15px/1.5 var(--font-body)}
+.page{display:flex;flex-direction:column;gap:1.1rem;max-width:900px;margin:0 auto;padding:1.5rem 16px}
+h1,h2,h3{font-family:var(--font-display);font-weight:600;margin:0 0 .5rem}h1{font-size:1.75rem}h2{font-size:1.25rem}h3{font-size:1rem;margin-top:1rem}
+.meta,.sub,.note{color:var(--ink);opacity:.8;font-size:.875rem;margin:.25rem 0}
+.panel{background:var(--paper-raised);border:1px solid var(--line);border-radius:4px;padding:1rem 1.25rem}
+.card{background:var(--paper-raised);border:1px solid var(--line);border-radius:4px;padding:.6rem .8rem;margin:.4rem 0}
+.card.critical{border-color:var(--critical)}.card.warn{border-color:var(--warn)}
+.fresh{background:var(--accent-soft);border:1px solid var(--line);border-radius:4px;padding:.6rem .8rem;margin:0}
+.status{display:inline-block;padding:.1rem .5rem;border-radius:2px;font:600 .72rem var(--font-body);text-transform:uppercase;letter-spacing:.04em}
+.status--good{background:var(--good-soft);color:var(--good)}.status--warn{background:var(--warn-soft);color:var(--warn)}
+.status--critical{background:var(--critical-soft);color:var(--critical)}
+.pill{display:inline-block;padding:.1rem .5rem;border-radius:999px;background:var(--warn-soft);color:var(--warn);font-size:.75rem;font-weight:600}
+.table-scroll{overflow-x:auto;max-width:100%}table{border-collapse:collapse;width:100%;font-size:.875rem}
+th,td{text-align:left;padding:.35rem .5rem;border-bottom:1px solid var(--line);vertical-align:top}
+.num{text-align:right;font-family:var(--font-mono);font-variant-numeric:tabular-nums;white-space:nowrap}
+td.num .na,td .na{font-family:var(--font-body)}a{color:var(--accent)}code{font-family:var(--font-mono);font-size:.85em;white-space:nowrap}
+tr.grp th{background:var(--paper);font-family:var(--font-display)}
+.toggle{position:sticky;top:0;z-index:5;background:var(--paper);padding:.5rem 0;border-bottom:1px solid var(--line)}
+.toggle button{font:600 .875rem var(--font-body);padding:.35rem .9rem;border:1px solid var(--line);background:var(--paper-raised);color:var(--ink);cursor:pointer}
+.toggle button[aria-pressed="true"]{background:var(--accent);color:#fff;border-color:var(--accent)}
+.period-label{margin:.35rem 0 0;font-size:.875rem}#back{font-size:.875rem;margin-left:.5rem}
+details summary{cursor:pointer;font-weight:600}details.dp>summary h2{display:inline}
+.page-footer{font-size:.75rem;opacity:.85}
+@media (max-width:480px){.panel{padding:.75rem}h1{font-size:1.4rem}}
+@media print{
+:root{--ink:#1A1D21;--paper:#FFFFFF;--paper-raised:#FFFFFF;--line:#C9CDD2;--accent:#1F5C8B;--accent-soft:#EEF3F7}
+html,body,.page,section,.panel,.card,details,.table-scroll,#views,.view{height:auto!important;overflow:visible!important;max-height:none!important}
+.card,li,tr,p,.fresh,.page-header,.page-footer,.avoid{break-inside:avoid}
+.page-footer{display:inline-block;width:100%}
+h1,h2,h3,summary{break-after:avoid}
+details::details-content{content-visibility:visible;display:contents}
+.toggle .buttons,#back{display:none!important}.toggle{position:static;border:0}
+thead{display:table-header-group}td.num,th.num{word-break:normal;overflow-wrap:normal}
+}
+"""
+
+TEMPLATE = """<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
+<title>{{TITLE}}</title>
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Condensed:wght@500;600&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap" rel="stylesheet">
+<style>{{CSS}}</style></head>
+<body><main class="page">
+{{BODY}}
+</main>
+<script>
+(function(){
+ var VIEWS={{VIEWS}}, LATEST={{LATEST}}, LABELS={{LABELS}}, state={day:{{START}}, level:"day"};
+ function show(){
+ var key=VIEWS[state.day][state.level];
+ document.querySelectorAll(".view").forEach(function(v){v.hidden=(v.getAttribute("data-view")!==key);});
+ document.querySelectorAll(".toggle button").forEach(function(b){b.setAttribute("aria-pressed", String(b.getAttribute("data-level")===state.level));});
+ var lab=document.getElementById("period-label"); var note=lab.getAttribute("data-note");
+ lab.textContent=LABELS[key]+(note&&state.day===LATEST&&state.level==="day"?". "+note:"");
+ document.getElementById("partial-pill").hidden=!(state.level==="month"&&/ to date: 1-/.test(LABELS[key])&&!isMonthEnd(state.day));
+ var back=document.getElementById("back"); back.hidden=(state.day===LATEST); back.textContent="Back to "+LATEST;
+ }
+ function isMonthEnd(d){var x=new Date(d+"T12:00:00");var y=new Date(x.getTime()+864e5);return y.getMonth()!==x.getMonth();}
+ document.querySelectorAll(".toggle button").forEach(function(b){b.addEventListener("click",function(){state.level=b.getAttribute("data-level");show();});});
+ document.getElementById("back").addEventListener("click",function(e){e.preventDefault();state.day=LATEST;state.level="day";show();});
+ document.addEventListener("click",function(e){var a=e.target.closest(".go-day");if(!a)return;e.preventDefault();state.day=a.getAttribute("data-day");state.level="day";show();window.scrollTo(0,document.getElementById("toggle").offsetTop);});
+ window.addEventListener("beforeprint",function(){document.querySelectorAll("details").forEach(function(d){d.setAttribute("data-was-open",d.open?"1":"0");d.open=true;});});
+ window.addEventListener("afterprint",function(){document.querySelectorAll("details").forEach(function(d){d.open=d.getAttribute("data-was-open")==="1";});});
+ show();
+})();
+</script>
+</body></html>
+"""
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("--out", required=True, help="the folder pulse_compute.py wrote")
+ ap.add_argument("--full-page-url", help="the Operations Command Center URL, when this run published it")
+ ap.add_argument("--day", help="the production day asked for, when it differs from the engine's")
+ args = ap.parse_args(argv)
+ if not os.path.exists(os.path.join(args.out, "periods.json")):
+ print("no periods.json in %s: run pulse_compute.py first; no short page written" % args.out, file=sys.stderr)
+ return 2
+ pg = Page(args.out, args.full_page_url, args.day)
+ page = pg.render()
+ errs = pg.check(page)
+ if errs:
+ print("SHORT PAGE CHECKS FAILED, no page written:\n " + "\n ".join(errs[:40]), file=sys.stderr)
+ return 2
+ name = "operations-short-%s-%s.html" % (re.sub(r"[^A-Za-z0-9]+", "-", pg.site), pg.requested)
+ path = os.path.join(args.out, name)
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(page)
+ n_views = len(pg.per["rollups"])
+ print("short page: %s | %d views (%d days) | checks passed" % (path, n_views, len(pg.per["days"])))
+ sec = re.search(r'id="decisions">(.*?)</section>', page, re.S).group(1)
+ for i, li in enumerate(re.findall(r"<li[^>]*>(.*?)</li>", sec, re.S), 1):
+ print("decision %d: %s" % (i, html.unescape(re.sub(r"<[^>]+>", "", li)).strip()))
+ rem = re.search(r'<p class="remaining[^>]*>(.*?)</p>', sec, re.S)
+ if rem:
+ print("then: " + html.unescape(re.sub(r"<[^>]+>", "", rem.group(1))).strip())
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/claude-for-manufacturing/skills/ncr-writeup/SKILL.md b/plugins/claude-for-manufacturing/skills/ncr-writeup/SKILL.md
new file mode 100644
index 00000000..f0e03c3d
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/ncr-writeup/SKILL.md
@@ -0,0 +1,383 @@
+---
+name: ncr-writeup
+description: "Writes the nonconformance report: what was found and measured, the specific requirement it violates cited to its document and locator, how many parts are actually suspect and why that scope rather than a narrower one, and where every one of them physically is across all five locations. Searches prior NCRs and CAPAs at the moment of writing and reports whether the earlier fix held. Where containment places parts at a customer, drafts the escape notification automatically against its contractual clock. Never asserts a requirement it cannot locate. Keeps the site's Quality Register of open NCRs up to date, and closes an NCR there when told to. Use when someone says \"write up this nonconformance,\" \"we found bad parts,\" \"raise an NCR,\" \"the inspector rejected this lot,\" \"a customer is complaining about a part,\" or \"close NCR-2026-0141.\""
+compatibility: "Requires none. Reads the consolidated dataset for work orders, lots and on-hand inventory by location; the ERP (Oracle NetSuite or Infor M3) for shipments, which the workbook never carries; and Microsoft 365 for drawings, specs and the quality document library. Runs on pasted findings, inspection exports and uploaded drawings with no connector. The NCR uses the plant's or the customer's controlled template, never the house style."
+---
+
+# NCR Writeup
+
+The formal record that something did not meet its requirement, written by
+whoever found it — an inspector, an operator, a customer complaint landing in
+somebody's inbox.
+
+**It has to answer four questions**, and the skill is built around them in
+order, because each one depends on the last:
+
+1. **What was found** — the observed condition, measured where possible.
+ "Hole diameter 0.512 in," not "hole too big."
+2. **Against which requirement** — cited to a document and a locator.
+3. **How many parts** — rarely just the one somebody found.
+4. **Where they physically are** — which is containment.
+
+**Quick start**
+
+```
+→ Capture the finding, structured: part, WO, lot, operation, condition, who, when
+→ Cite the requirement. Cannot locate one? Flag blocking. Never invent one
+→ Scope the suspect quantity, and show the reasoning behind the scope
+→ Locate the parts across all five locations
+→ Recommend containment per location, ordered by urgency
+→ Search history NOW: prior NCRs and CAPAs, and whether the fix held
+→ Parts at a customer? Draft the escape notification against its clock
+→ Write the register row, keyed <site>_<ncr_ref>, and update the Quality Register
+→ "Close NCR-…"? The user's decision: set the row closed and republish
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| The finding | Inspector notes, operator report, customer complaint email | Conversation, M365 mail, pasted text |
+| Inspection measurements | Quality system export to the M365 folder | CSV/XLSX |
+| The requirement | Drawing, spec, standard clause, customer PO flow-down | M365 documents |
+| Work order, lot, quantity produced | `data-consolidate` workbook, then the ERP | `../../shared/contracts/consolidated-dataset.md` |
+| Where the parts are, on-hand | `inventory` tab — one row per part per location | Same workbook |
+| Where the parts are, shipped | ERP shipment records. Infor M3 delivery lines carry no lot (`../../shared/erp-connectors.md`): they give candidate shipments by part and date, each unverified until confirmed | Connector |
+| Prior NCRs and CAPAs | M365 quality document library | Documents |
+| The plant's NCR template | `## Plant context`, captured during `onboarding` | Template |
+
+**The inspection measurements come from the quality export rather than the
+workbook**, because an NCR quotes the condition as measured — "hole diameter
+0.512 in" — and that is the value the gage wrote, not the normalized one.
+Everything about *identity* still comes from the dataset: which work order,
+which lot, where the parts are. See *What this dataset is authoritative for* in
+`../../shared/contracts/consolidated-dataset.md`.
+
+Read the plant's vocabulary, sites, standards and template location from the
+`## Plant context` block. A plant that says "traveler" gets an NCR that says
+traveler.
+
+---
+
+## Workflow
+
+### Step 1 — Capture the finding, structured
+
+Part and revision, production work order, lot, the operation it was found at,
+quantity found, the measured or observed condition, who found it, and when with
+its timezone.
+
+Take the measurement as recorded, with its gage. A characteristic measured on a
+gage whose calibration has lapsed is a finding of its own — check the date if
+one is available.
+
+### Step 2 — Cite the requirement
+
+Locate the drawing, spec or clause and cite the **document, the locator inside
+it, the characteristic, and the stated value.** Cite it at the revision the part
+was actually built to, not the current one.
+
+**If the requirement cannot be located, flag the NCR as blocking and say what
+was searched.** Never assert one. Read `reference/requirement-citation.md` —
+this is the field the whole chain gates on, and blocking here is a normal,
+correct outcome.
+
+### Step 3 — Scope the affected quantity
+
+From the work order quantity, the lot, and the production window. Reason
+explicitly from the suspected mechanism outward, and **state the assumption**.
+
+Where traceability is incomplete, the scope widens and says why. Never narrow it
+to make the number look better. **Where the widened number is still only what
+can be counted, it is a floor**: set `qty_suspect_is_minimum` and write *at
+least 660* everywhere it is printed. Where the source records no count of parts
+found, `qty_found` is null with `qty_found_reason`, never a number filled in.
+Read `reference/scope-and-containment.md`.
+
+### Step 4 — Locate the parts
+
+**Read the workbook first.** Place on-hand quantity from the `inventory` tab —
+one row per part per location — and from `production_output` for what is still
+at the machine. Map each location into the five containment types using the
+plant's vocabulary from the `## Plant context` block.
+
+Then read shipment records for in-transit and at-customer. Those are not on
+`inventory`. Use the ERP when it is connected.
+
+**If the `inventory` tab is absent**, do not treat that as zero on hand. Ask
+location by location, or read the ERP / an inventory export, and record each
+answer as unverified until confirmed. That is the missing behavior on
+`../../shared/contracts/consolidated-dataset.md`.
+
+**Address all five, including with a zero quantity.** An omitted location reads
+as "none there" rather than "not checked," and `checked: false` is not `qty: 0`.
+
+**Two shapes, one meaning.** In the structured record every entry carries a
+number, because `../../shared/contracts/ncr.md` requires `qty` and `uom`: an
+unchecked location is written `qty: 0`, `uom: <the part's unit>`,
+`checked: false`, never `null`. In the human-readable containment table the
+same row reads **"not checked"** and never "0 parts" — a zero in the table is
+the false statement `absent-is-not-zero.md` exists to prevent. If "unknown"
+ever needs to be representable in the payload itself, that is a contract
+change raised with its owner, not a null emitted quietly.
+
+**The table's quantity cell is built from `checked`, not from `qty`:**
+
+| Location | Suspect qty | Action | Urgency |
+|---|---|---|---|
+| Installed at customer | **not checked** | Confirm with the customer whether any of the lot was installed | immediate |
+| Finished goods | 0 (checked, none on hand) | — | routine |
+
+A checked location with none on hand says "0 (checked)"; an unchecked one says
+"not checked" and no number. The two are never the same cell.
+
+### Step 5 — Recommend containment per location
+
+Ordered by urgency, with the action for each and the owner left blank for
+assignment. Containment happens before anyone knows the root cause — the point
+is to stop the bleeding.
+
+**The order is customer side first, always:** `installed_at_customer`,
+`at_customer`, `in_transit`, `wip_at_machine`, `finished_goods`. Parts already
+in a customer's product are the escape with a contractual clock running; parts
+on our own shelf can wait an hour. Every entry carries its `urgency`
+(`immediate`, `same_day`, `routine`), and the table is sorted by it, not by
+where the parts happen to be easiest to find.
+
+### Step 6 — Search history, now
+
+Prior NCRs and CAPAs on the same part, the same defect, the same process, the
+same supplier. **This runs when the NCR is written, not on request**, because
+the moment of detection is the only moment anyone is looking.
+
+Report **whether the earlier corrective action held** — the highest-value single
+line in Chain 2. With no searchable library, say "no searchable history
+available" rather than nothing. **Prior NCRs with no CAPA records are reported
+as both facts**: `prior_ncrs_found` counts them, and the line says whether a fix
+held cannot be judged. Read `reference/recurrence-and-escape.md`.
+
+**A prior NCR's part label is checked before it counts as same-part
+history.** Where the dataset's `ncrs` tab flags it `ncr_part_differs` or
+`ncr_dated_before_wo`, or where the ERP holds a different part for the work
+order the NCR cites, it is not same-part history: list it as unreliable, with
+both parts, and say what it would take to settle.
+
+### Step 7 — Draft the escape notification
+
+If containment placed any suspect parts at or past a customer, draft the
+customer notification **as the immediate next output**, with the required
+content and the contractual clock stated at the top.
+
+**If the customer locations are unchecked and shipment is plausible** (orders
+for the suspect parts promised before today, a customer named on the NCR), the
+escape is possible, not ruled out: set `escape_possible`, leave
+`escape_detected_at` null, draft the notification **marked conditional on the
+shipment check**, and name that check as an action with an owner to fill:
+*"Confirm whether any of WO-88412/413/414 shipped on Example Hydraulics's 7 and 19 Sep
+orders."* Saying nothing because nothing was verified is how the clock runs out.
+
+Chained straight off containment so nobody has to remember it separately, under
+time pressure, against a 24 to 48 hour window. Missing that window is a bigger
+problem than the defect.
+
+### Step 8 — Write the register row, and update the Quality Register
+
+A single run knows one NCR. The Quality Register lists all of them, so this
+run leaves a row behind. Per `../../shared/live-dashboard.md`, which names
+every tool call:
+
+1. **Find the register.** The `## Dashboards` line on the Open work page, then `Artifact`
+ `list` for the exact title *"<Site>: Quality Register"*, then create it.
+2. **Build the row** per `../../shared/contracts/quality-register-record.md`,
+ keyed `<site>_<ncr_ref>`: status, containment summary, the escape clock,
+ the recurrence finding and whether the previous fix held. `status` is
+ `blocked` when no requirement could be located, `awaiting_approval` until
+ the quality owner approves the NCR, then `open`.
+3. **Read the existing row first, if there is one,** and carry forward every
+ field this skill does not own. A second run on the same NCR overwrites its
+ row and keeps the 8D fields `root-cause-capa` wrote. **One NCR, one row.**
+4. `set` the row, `list` the collection, compute the register in code and
+ publish it, per the register layout in `../../shared/live-dashboard.md`.
+5. **Report it:** *"Updated **Fairview: Quality Register**, `<url>`. Private
+ to you until you share it."* followed by the sensitivity line, *"Internal:
+ it lists customer names and notification deadlines. Check who you share it
+ with."* On a fallback: the Quality page in the conversation, its placement
+ line, and *"The Quality Register was not updated: [reason]."* That page
+ could not read the other rows, so it shows this NCR only and says so; it
+ never prints an open count it could not compute. The row is still in the
+ reply's summary table, marked not stored.
+
+**The register banner says what it is not:** *"Tracks NCRs run through this
+plugin since [date]. Not your full quality library."* A manager reading
+"3 open" will otherwise assume that is everything.
+
+**Not a gate.** The register is not a system of record, the row carries the
+NCR's own approval state, and nothing in it reaches a customer. The NCR's two
+gates are unchanged.
+
+### Closing an NCR
+
+**Closing is the user's decision, never this skill's.** When the user says
+*"close NCR-2026-0141,"* read that row, set `status: closed` with `closed_at`
+and `closed_by` as the user gave them, and republish. It leaves every open
+count and moves to the closed section. Say that this closes it in the register
+only; the NCR in the plant's quality system is closed by whoever owns it.
+
+**If the register cannot be read or written this run, the close was not
+recorded.** Say so plainly: *"NCR-2026-0141 was not closed in the register:
+[reason]. The Quality Register was not updated."* Never report an NCR closed
+that was not written closed. There is no in-page editing.
+
+---
+
+## Approval gates
+
+**Two gates, and neither is a formality.**
+
+**Before the NCR is final** — a quality owner confirms the finding, the cited
+requirement, the suspect scope and the containment plan. This is the Chain 2 and
+Chain 5 gate. The NCR carries `approval_state`, and `root-cause-capa` blocks
+anything customer-facing until it reads `approved`.
+
+**Before anything reaches a customer** — the escape notification is drafted,
+shown, and sent by a person. Nothing goes to a customer unattended, ever. Speed
+is the point of drafting it automatically; unattended sending is not.
+
+Nothing is written back to the ERP or to the quality system. The NCR is a
+document the quality owner files.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**Report depth follows the plant's preference.** The `## Plant context`
+block's **Report depth** line is `summary-first` or `full` (absent means
+`full`). Summary-first puts a short summary — what was found, what it
+affects, what happens next — above the full document; it moves nothing out and
+drops nothing. Every required field is still in the document below it.
+
+**The NCR**, in the plant's or the customer's controlled template captured
+during `onboarding` — identification, requirement cited, condition found with
+measurements, affected quantity with its reasoning, and the disposition-pending
+flag.
+
+Per `../../shared/artifact-style.md`, **a controlled document is never
+house-styled.** An NCR has a contractual shape and restyling it would make it
+wrong, not nicer.
+
+**Containment plan** — actions by location, ordered by urgency, owners blank.
+
+**Recurrence finding** — prior related records, and whether the previous fix
+held.
+
+**Escape notification draft** — when applicable.
+
+**The structured NCR** — per `../../shared/contracts/ncr.md`, in exactly the
+shape `root-cause-capa` consumes with no transformation between.
+
+**The register row** — per `../../shared/contracts/quality-register-record.md`,
+with its key `<site>_<ncr_ref>`, in the reply's summary table on every run, stored
+or not.
+
+**The Quality Register** — *"<Site>: Quality Register"*, the Quality
+command-center page, updated in place per `../../shared/live-dashboard.md`.
+It carries this NCR by reference, never the document. The run ends with the
+dashboard line and the sensitivity line, or with the fallback and *"The
+Quality Register was not updated."* Never "shared," never "posted." Read
+`../../shared/command-center.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **The requirement genuinely cannot be found** — flag as blocking, list what was
+ searched. Do not invent it.
+- **Traceability is incomplete, no lot recorded** — widen the suspect scope and
+ say why it had to widen.
+- **The finding is subjective** — "surface looks wrong." Capture as observed, set
+ the subjective flag, note that no measurable requirement was cited.
+- **Parts shipped to multiple customers** — separate containment and a separate
+ notification per customer. Never merge.
+- **Multiple defects on one part** — one NCR with multiple findings, not several
+ NCRs, unless the customer's template requires otherwise.
+- **The inspection export is stale or does not cover the run** — say so at the
+ top. A containment scope computed from data that stops before the event is
+ wrong in the dangerous direction.
+- **Two revisions of the print in circulation** — record both, say which the part
+ was built to. This is often the finding rather than a nuisance.
+- **The same NCR written up twice** — the second run overwrites its register
+ row by key. One NCR, one row, and the 8D fields already on it are kept.
+- **Asked to close an NCR that has no register row** — say it is not in the
+ register, and close nothing. The register only knows NCRs run through this
+ plugin.
+
+---
+
+## Degradation
+
+The skill runs on a pasted finding and an uploaded drawing with no connector at
+all.
+
+| Not available | What happens |
+|---|---|
+| Consolidated dataset, or no `inventory` tab | Ask where the parts are, location by location, or read the ERP / an inventory export. Record each answer as unverified until confirmed. Never treat a missing tab as zero on hand |
+| The ERP (NetSuite or Infor M3) | On-hand can still come from the workbook. In-transit and at-customer cannot. Ask about shipments, and record those two locations as unverified until confirmed |
+| Inspection export | Work from the finding as described. Measurements are whatever the inspector reports |
+| Quality document library | `no_searchable_history`. Never presented as a first occurrence |
+| The plant's or the customer's template | Use a neutral NCR structure covering the four questions, and flag that the controlled template was not available |
+| Customer contractual terms | Draft the notification without a computed deadline and ask where the terms are recorded. Do not guess a window |
+| The `Artifact` or `ArtifactData` tools | The NCR is unaffected. The Quality page is offered in the conversation, showing this NCR only, with *"The Quality Register was not updated."* A close request is not recorded, and the reply says so |
+
+---
+
+## Chain position
+
+**Chain 2, inspection to CAPA** — step 1, feeding `root-cause-capa`.
+
+**Chain 5, supplier escape to alternate source** — step 1. Where the cause turns
+out to trace to purchased material, the chain runs on through `root-cause-capa`
+into sourcing.
+
+**Metric.** Nonconformance closure time; escape response time — the clock
+from detection to customer notified, which step 7 is what moves.
+
+**Chain 5's escape-to-RFQ metric is segmented, and this skill opens it.** That
+window runs escape detected → supplier-caused determination → RFQ issued, and no
+single skill controls it. This skill owns detection and containment speed in the
+first segment, alongside `root-cause-capa`'s investigation time; the second
+segment belongs to `supplier-quote-request`.
+
+**Stamp `escape_detected_at` on the NCR when containment first places parts at
+or past a customer.** That is the start of the window, it is not the same moment
+as `found_at`, and it cannot be reconstructed afterwards. `root-cause-capa`
+carries it forward onto the supplier-caused flag.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/requirement-citation.md` | Step 2 — what counts as a requirement, revisions, and what to do when there is none |
+| `reference/scope-and-containment.md` | Steps 3 to 5 — reasoning the scope outward, and the five locations |
+| `reference/recurrence-and-escape.md` | Steps 6 and 7 — searching at creation, and the contractual clock |
+| `../../shared/contracts/consolidated-dataset.md` | Step 4 — the `inventory` tab, and what to do when it is absent |
+| `../../shared/contracts/ncr.md` | On emit — the exact shape `root-cause-capa` consumes |
+| `../../shared/live-dashboard.md` | Step 8 and on a close — finding and updating the Quality Register, the banner, the fallback |
+| `../../shared/contracts/quality-register-record.md` | Step 8 — the register row, and which fields this skill owns |
+| `../../shared/command-center.md` | When "updated" may be said |
diff --git a/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/recurrence-and-escape.md b/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/recurrence-and-escape.md
new file mode 100644
index 00000000..d26399d6
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/recurrence-and-escape.md
@@ -0,0 +1,99 @@
+# Recurrence and escape
+
+Two steps that both exist because of the same problem: they are things everyone
+agrees should happen, and they do not happen, because the moment they need to
+happen is the moment everybody is busy.
+
+---
+
+## Recurrence — searched at creation, not on request
+
+**The search runs automatically when the NCR is written.** Not when somebody
+thinks to ask for it. The moment of detection is the only moment anyone is
+looking at this part and this defect, and if the question is not answered then,
+it is not answered at all.
+
+### Search four ways
+
+| Search | Finds |
+|---|---|
+| Same part number | Has this part done this before |
+| Same defect on any part | A process problem wearing a different part number |
+| Same process, operation or cell | A machine or a setup that keeps producing this |
+| Same supplier or material lot | The signal that routes into Chain 5 |
+
+Search prior NCRs and closed CAPAs in the plant's quality document library.
+
+### The highest-value line in the whole chain
+
+For any match, report **whether the earlier corrective action held.**
+
+A recurrence after a closed CAPA is a materially more serious finding than a
+first occurrence. It says the fix did not work, or was never really implemented,
+or addressed a symptom. It changes what happens next, it changes who needs to
+know, and in an audit it is the difference between a minor observation and a
+systemic finding.
+
+Three distinct outcomes, and they must not be collapsed:
+
+- `first_occurrence` — searched, nothing found
+- `recurrence_prior_capa_held` — it happened before, the fix worked, this is
+ something new
+- `recurrence_prior_capa_failed` — it happened before, the fix did not hold
+
+### "No searchable history" is its own answer
+
+`no_searchable_history` is a separate value from `first_occurrence` on purpose.
+
+If there is no quality document library, or it holds nothing for this part, say
+**"no searchable history available."** Never say nothing — per
+`../../../shared/absent-is-not-zero.md`, silence reads as "no recurrence," which
+is a far stronger claim than the evidence supports and exactly the wrong thing to
+tell a quality manager.
+
+---
+
+## Escape — the clock starts without you
+
+**An escape is a nonconforming part that reached a customer.** It is triggered
+the moment containment places any suspect quantity at `at_customer` or
+`installed_at_customer`.
+
+That usually starts a contractual notification window — often 24 to 48 hours in
+automotive and aerospace. **Missing that window is a bigger problem than the
+defect itself.** A defect is a quality event. A missed notification is a breach,
+and it is the thing that costs an approved-supplier status.
+
+### Chained straight off containment
+
+The notification draft is produced **automatically**, as the immediate next
+output after containment finds parts at a customer. Nobody has to remember it,
+under time pressure, against a clock they are not watching.
+
+This is the single most valuable piece of automation in the skill, and it is
+valuable precisely because it is boring.
+
+### What the draft contains
+
+- Part, revision, quantity shipped and the shipments involved
+- What the nonconformance is, in plain terms, against the cited requirement
+- What we are asking the customer to do — usually quarantine the receipt and
+ confirm whether any have been installed or shipped on
+- What we are doing about it and when they will hear next
+- The NCR reference
+
+### The clock, stated
+
+Record `notification_deadline` as a **timestamp with its zone**, computed from
+`found_at` plus the contractual window, and put it at the top of the draft.
+
+Where the contractual window is not known, say so and do not guess one — an
+invented 48 hours that is really 24 is worse than an open question. Ask where the
+customer's terms are recorded.
+
+### It still does not send
+
+The draft is a draft. Nothing customer-facing leaves without a quality owner
+approving it — this is the Chain 2 and Chain 5 approval gate, and an escape
+notification is the most consequential thing this plugin will ever put in front
+of a person. Speed is the point; unattended sending is not.
diff --git a/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/requirement-citation.md b/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/requirement-citation.md
new file mode 100644
index 00000000..0390a816
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/requirement-citation.md
@@ -0,0 +1,93 @@
+# Citing the requirement — the field the whole chain gates on
+
+**Nonconformance is always against a specific requirement, never just "it looked
+wrong."** An NCR without a cited requirement is not an NCR, and
+`root-cause-capa` blocks on one with a pointer back here.
+
+This is the single most common way a nonconformance record is written badly, and
+it is worth being strict about, because a quality manager reads the citation
+before they read anything else.
+
+---
+
+## What counts as a requirement
+
+A requirement is **stated, measurable, and locatable in a document.** Four
+sources, roughly in order of how often they are the right one:
+
+| Source | Where it lives | The locator you need |
+|---|---|---|
+| Customer drawing | M365 document library | Page, view or datum, and the feature |
+| Internal specification | M365 controlled documents | Section number |
+| Standard clause | The standards the plant is certified to, captured in `## Plant context` | Clause number, e.g. AS9100 8.5.1 |
+| Customer purchase-order requirement | The ERP, or the PO document | The flowed-down line |
+
+Each one produces four things: **the document, the locator inside it, the
+characteristic, and the stated value.** A citation missing the locator is not
+usable — "it's on the drawing somewhere" sends the next person back to do the
+work again.
+
+---
+
+## Get the revision right
+
+**Cite the requirement at the revision the part was actually built to**, not the
+current one.
+
+Two revisions of a print in circulation is a genuine root cause, and it is one of
+the most common ones in the industry. If the shop copy was Rev A and the library
+holds Rev C, that discrepancy is not a nuisance to resolve quietly — it is
+probably the finding, and it belongs in the NCR.
+
+Where the two disagree, record both and say which the part was made against. Do
+not silently take the newer one.
+
+---
+
+## When the requirement cannot be found
+
+This happens, and it happens most on exactly the parts where it matters.
+
+**Never invent one.** Set `requirement_not_locatable: true`, leave
+`requirement_cited` null, and flag the NCR as blocking. Per
+`../../../shared/absent-is-not-zero.md`, a plausible-looking tolerance that
+nobody can trace is worse than an admitted gap, because it will be believed and
+then defended to a customer.
+
+State what was searched, so the next person does not repeat it:
+
+> *"I could not locate a requirement for surface finish on this feature. I
+> searched the 4471-B drawing package (Rev B and Rev C), the internal spec
+> QS-114, and the Example Aerospace flow-down on PO-4471. The drawing calls surface
+> finish on two other features but not this one. Either it is uncontrolled here,
+> or the requirement lives somewhere I cannot see. This NCR is blocked until
+> someone confirms which."*
+
+That is a complete, honest, useful outcome.
+
+---
+
+## Subjective findings
+
+"The surface looks wrong." "It sounded rough." "The colour is off."
+
+These are real observations and they are often correct — an experienced
+inspector's eye is genuine evidence. Capture the finding **as observed**, set
+`is_subjective: true`, and be explicit that no measurable requirement was cited.
+
+The consumer needs that flag before it tries anything: `root-cause-capa` cannot
+run a computed pattern check against a characteristic that was never measured,
+and it needs to know that rather than discovering it.
+
+Do not convert a subjective finding into a measured one by inventing a number
+for it. Do ask whether the characteristic *could* be measured, because often it
+can and nobody did.
+
+---
+
+## Blocking is a normal outcome
+
+An NCR blocked on a missing requirement is not a failed run. It is the skill
+doing the one thing it exists to do — refusing to record a nonconformance
+against nothing — and it hands back a specific, answerable question instead of a
+document that would not survive an audit.
diff --git a/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/scope-and-containment.md b/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/scope-and-containment.md
new file mode 100644
index 00000000..7a227864
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/ncr-writeup/reference/scope-and-containment.md
@@ -0,0 +1,109 @@
+# Scope, then containment
+
+Two steps that have to happen in that order, because the scope decides how many
+parts containment has to go find.
+
+Containment happens **before anyone knows the root cause.** The point is to stop
+the bleeding, not to explain it. A containment plan that waits on a diagnosis is
+not containment.
+
+---
+
+## Part 1 — How many parts are actually suspect
+
+The quantity somebody found is almost never the quantity that is suspect.
+
+An inspector pulls three parts for a first-article recheck and two fail. The
+answer is not "2." The question is what else the same cause could have reached,
+and the honest starting position is that **if the cause could have affected the
+whole run, the whole run is suspect until proven otherwise.**
+
+### Reason from the cause outward
+
+Work through what the suspected mechanism could touch:
+
+- **One setup, no intervening tool change** → the whole run made on that setup
+- **One material lot** → every part made from that lot, which may span several
+ work orders and several weeks
+- **A drifting process** → a time window, bounded at each end by whatever
+ evidence you actually have, not by convenience
+- **A gage whose calibration lapsed** → every inspection that gage performed
+ since the lapse. This is one of the most common audit findings there is, and
+ the scope is usually much larger than anyone first assumes
+- **A genuinely one-off event** — a dropped part, a single mis-load — → that part
+
+### Show the reasoning, always
+
+`scope_reasoning` is a required field and it is required for a reason. The
+consumer needs it because **a run-wide cause and a single-part cause point at
+completely different root causes**, and the number alone does not say which was
+assumed.
+
+> *"All 480 parts on WO-88201 were machined from LOT-77219 on one setup with no
+> intervening tool change, so the whole lot is suspect until sampled. The 3 found
+> were a first-article recheck, not a full inspection."*
+
+### Where traceability is incomplete, widen — and say so
+
+No lot number recorded, or lot recorded only at the pallet rather than the part.
+The suspect scope **widens**, and `traceability_complete` goes false with the
+reason attached.
+
+**Never narrow the scope to make the number look better.** That is the failure
+mode this pair of fields exists to prevent, and it is the one that turns a
+contained problem into a recall. A widened scope with an honest explanation is a
+defensible position; a narrow one built on traceability nobody has is not.
+
+Downstream, `root-cause-capa` carries the widened scope forward and never
+re-narrows it.
+
+---
+
+## Part 2 — Where the parts physically are
+
+Five locations. **Every one is addressed in every NCR**, including with a zero
+quantity, because an omitted location reads as *"no parts there"* rather than
+*"nobody has checked."*
+
+Ordered by urgency, which is roughly the reverse of how easy they are to reach:
+
+| Location | Where to look | Typical action | Usual urgency |
+|---|---|---|---|
+| `installed_at_customer` | Not visible in our records at all — you have to ask | Ask the customer whether any have been installed or shipped on | Immediate |
+| `at_customer` | Shipment records, delivered — the ERP, not the `inventory` tab | Notify, request quarantine of the receipt | Immediate |
+| `in_transit` | Shipment records, not yet delivered — the ERP | Intercept at the carrier while it is still ours to stop | Immediate |
+| `wip_at_machine` | `inventory` rows at the cell or machine, plus `production_output` | Stop the next operation, hold at the cell | Immediate |
+| `finished_goods` | `inventory` rows at a warehouse or cage location | Move to quarantine, tag with the NCR reference | Same day |
+
+Read the `inventory` tab before the ERP. It is on-hand by part and location.
+A missing tab is not zero on hand.
+
+### `checked: false` is not `qty: 0`
+
+The most dangerous entry in a containment plan is a location nobody has walked
+yet, and it must not read as clear.
+
+- `qty: 0, checked: true` — somebody looked, there are none there.
+- `qty: 0, checked: false` — nobody has looked. **Not clear. Not contained.**
+
+`installed_at_customer` is very often the second kind, because our records
+genuinely cannot answer it. Write it that way rather than leaving it out.
+
+### Every entry cites where the quantity came from
+
+A row on the `inventory` tab, a shipment record, a row in `production_output`. Per
+rule 6 in `../../../shared/contracts/README.md`, a derived number carries its
+provenance — someone will need to go stand in front of that quantity.
+
+### Owners are left blank
+
+`owner` is a required field with a null value. Containment actions are assigned
+by a person who knows who is on shift; the skill does not guess at names.
+
+---
+
+## Multiple customers
+
+Separate containment entries and a separate notification per customer. Never
+merge them — the contractual clocks differ, the contacts differ, and one
+customer must not appear in another's notification.
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/SKILL.md b/plugins/claude-for-manufacturing/skills/onboarding/SKILL.md
new file mode 100644
index 00000000..fe381c1d
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/SKILL.md
@@ -0,0 +1,489 @@
+---
+name: onboarding
+description: "Sets the plugin up for one plant on first run. Asks which ERP, CAD, CMMS and document system the plant uses and tests the four supported connectors (Microsoft 365, Oracle NetSuite, Infor M3, Autodesk Fusion), takes a bulk drop of the plant's own documents so it asks only what they don't answer, profiles the export folder, and runs the time interview with a clock-skew check. Also captures vocabulary, sites, capability, machining data, standards, templates and commercial rates, reports which skills are limited by anything missing, and ends with connector options for every other system named. Unknowns are deferred, never blocking. Use on a first session or when someone says \"set us up,\" \"get started,\" \"configure the plugin,\" \"which of our systems can you reach,\" \"which ERP can you reach,\" \"can you connect to our CMMS,\" \"here are our documents,\" \"our shifts changed,\" \"we added a plant,\" \"update our labour rate,\" \"change our margin,\" or \"reconfigure.\""
+compatibility: "Requires none. Tests Microsoft 365, Oracle NetSuite, Infor M3 and Autodesk Fusion. Any other system is named in the interview, runs on exports, and gets a connector-options check at the end of setup. Writes a Plant context memory block, including commercial rates the plant confirms, and renders a config profile page."
+---
+
+# Onboarding
+
+Every configurable value in this plugin has its home here, and no skill
+hard-codes one. Nine other skills read what this produces.
+
+**Who is answering.** A quality manager, a supervisor, an estimator or a plant
+manager — not an IT admin. Ask in their language, one question at a time, and
+treat "I'd have to ask" as a complete answer.
+
+**Hand-hold, don't interrogate.** Say what each step is for before asking
+anything in it, read what the plant can hand over before asking what it
+can't, and turn every question a document already answered into *confirm or
+correct*, naming the file.
+
+**Setup never blocks.** Every group can be deferred. A deferred group goes on the
+gaps list with the skills it limits named, and the run completes.
+
+**Quick start**
+
+```
+→ 1 Ask which ERP, CAD, CMMS and documents system; test the four supported connectors
+→ 2 Bulk document drop: name the exact documents, skip what a live connector covers
+→ 3 Export folder and dropped files; confirm every file one at a time
+→ 4 Time interview, then cross-check a shared event for clock skew
+→ 5–9 Vocabulary, sites, capability and machining data, standards, templates
+→ 10 Commercial rates into the profile, shown once for a yes — internal-use only
+→ 11 Show the profile, write it on approval, render the config page; gaps list
+→ 12 Connector options for every named system that isn't one of the four
+```
+
+---
+
+## The connector model
+
+**The plugin works with four connectors once they are connected: Microsoft
+365, Oracle NetSuite, Infor M3 and Autodesk Fusion.** Only Fusion is declared
+in the plugin's `.mcp.json`; the other three are enabled in Claude. These four
+are the supported connectors: the only rows in the setup-steps table in
+`../custom-connector/reference/known-systems.md`, and the only ones this skill
+tests or gives setup steps for. NetSuite and M3 are the two ERP options, and a
+plant runs one; read `../../shared/erp-connectors.md` before testing M3.
+
+**Every other system is named, not one of the four.** The plant names whatever it
+runs — SAP, SolidWorks, Limble, a homegrown MES — and any name is accepted.
+It runs on exports from then on, and Step 12 reports how it could be
+connected. `custom-connector` does the connecting, later, when the plant
+chooses.
+
+---
+
+## Workflow
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read any existing profile at
+`profile_path` and rates at `rates_path` (a reconfigure starts from them), per `../../shared/replies.md`.
+
+**A dropped plant profile** (a `## Plant context` file, "save this as our plant setup"): check it with
+`plant_setup.py render --profile <file> --out <a new folder>` (it refuses rate values and emails), show it
+and its gaps, and on a yes in a later turn save it as Step 11 does. Ask only what it leaves out.
+
+### Step 1 — Systems interview and connector test
+
+One open question per category. Name no product as an option: the person
+types what they run, and any name, or none, is accepted:
+
+```
+ERP / invoicing "What do you use for orders and invoicing?"
+Design / CAD "What do you use for design or CAD, if anything?"
+Maintenance / CMMS "What do you use for maintenance, if anything?"
+Documents / mail "What do you use for documents and email?"
+```
+
+Per answer:
+
+- **One of the four supported connectors** — test it now and report **what it
+ actually returns for this account**. Do not assume the standard schema:
+ for the ERP, check the record types the plugin uses and ask the scope,
+ revision, cost-field and work-order questions in `reference/erp-scope.md`. If it is not live, give
+ its setup steps by **quoting its row in the known-systems table word for
+ word**.
+- **Anything else** — *"No supported connector for SolidWorks. I'll run it on
+ exports for now and look at connector options at the end."* Record the name
+ for Step 12. Nothing else: Step 1 does not search, does not describe setup
+ steps for it, does not quote its registry row, and does not mention
+ `custom-connector`. **Step 12 is not pulled forward**, even when the user
+ asks for "just the systems part": connector options come after the gaps
+ list, or when the user asks for them by name ("what are our connector
+ options").
+
+This is a reachability and shape check. **Do not pull business data here.**
+
+**A connector is live only when its tools exist in this session and return.**
+Not because `.mcp.json` declares it, and not because someone says it is set up.
+
+**The setup-steps table is the only place the steps are written.** Never
+improvise one — not "install it from the connector directory," not "sign in
+and authorise," not a service name that is not in the row.
+
+**Asked "did you try connecting it?" the answer is no.** *"I didn't attempt a
+connection; connector auth is always owner-initiated."* Then the steps, for a
+supported connector; for anything else, "connector options come at the end."
+
+Record each choice in the `### Systems` section of the profile — name and
+state (`live (supported)`, `live (custom)`, `file`, `none`) — per
+`reference/config-profile.md`.
+
+### Step 2 — Bulk document intake
+
+Runs once Step 1 has established what is live, so the list never asks for
+something a live connector already covers. **Name the exact documents, grouped,
+and tag each line a live connector covers** `(skip — NetSuite is connected)`.
+The list, the routing table and how each kind of file is mined are
+`reference/document-intake.md`.
+
+- **Skippable, and re-runnable later** ("here's more").
+- **Classify first, deep-read second.** The first pass reads a header row or a
+ first page only. Only a file that routes to a step is read in full.
+- **Mined is not confirmed.** A value read from a file is shown labelled
+ *inferred, from <file>* — never in a table of findings as if it were settled —
+ and stays inferred until the user says yes to it in its own step, where the question becomes *confirm or
+ correct*, with the file named. **The production-day boundary is still asked
+ directly** in Step 4, whatever a shift calendar says.
+- **No vocabulary or capability from a single document.** Two consistent
+ sources, or ask.
+- **A rate found in a file follows Step 10.** It appears only in the approval
+ draft's internal rates section, once, with the file name as its source, and
+ is written only on a yes.
+- **An unidentifiable file goes on the gaps list by name**, asked about in one
+ line.
+
+### Step 3 — Export folder and dropped files
+
+The data foundation is not "connect to the MES." It is a folder where the plant's
+existing scheduled exports already land.
+
+List what is there, infer what each file is from its headers, and **have the user
+confirm each one**. Never accept the inference alone — a file identified wrong is
+worse than a file not identified, because it will be joined. Record the refresh
+cadence and coverage window per file.
+
+**Put the files to the user one at a time.** *"`mes_downtime.csv` looks like
+downtime events from the MES — asset, start, end, minutes, reason code. Is that
+right?"* Then the next. Never one table of every file with "confirm or correct
+each line": it gets a single "looks fine," which confirms none of them. **Record
+an identity only once that file was confirmed**; the rest stay inferred, marked
+unconfirmed, and go on the gaps list. If the user asks to confirm the remainder
+in one go, show the remaining list and take that yes — they have now seen it.
+Per `../../shared/approval-gates.md`.
+
+**If the exports do not exist yet, or any one expected source is missing from
+the folder**, write the export request specification for that source in this
+run — exact fields with types and units, format, naming, landing path,
+cadence, window, late-record handling — rather than only listing it on the
+gaps. A missing historian or quality export gets its spec the same as an empty
+folder does. Details in `reference/interview.md`.
+
+**A file dragged into the conversation is a valid first-run source**, from
+Step 2 or here. Confirm its identity one at a time like any other, and record
+its cadence as **manual, not scheduled**. Say plainly what that means: the
+scheduled skills (`morning-plant-pulse`) need a scheduled export or a live
+connector, and the export request spec is the path from manual to scheduled.
+
+### Step 4 — Run the time interview
+
+Per-source timezones and whether timestamps are zone-aware or naive, then shift
+pattern, production-day boundary, cross-midnight attribution and the
+planned-production-time definition.
+
+**Ask the production-day boundary as its own direct question, in the plant's
+terms**, and never assume midnight: *"Your 23:00 shift runs past midnight.
+Does its output belong to the day it started or the day it ended, and when
+does your production day begin?"* A folder whose files show a 23:00 shift is
+the cue; the question is asked whether or not the answer looks obvious, because
+a wrong boundary moves a whole shift of output to the wrong day on every
+report that follows.
+
+**Then run the offset self-check.** Take one event recorded in two systems,
+convert both timestamps using the declarations just captured, and report the
+observed skew. A non-zero skew means the declared config is wrong, and catching
+it here is the entire point of the step.
+
+The full procedure, including how to read each result, is
+`reference/time-config.md`. This is the highest-risk configuration in the plugin.
+
+### Step 5 — Map vocabulary
+
+Capture the plant's own word for each join key and organizational unit, so every
+output speaks their language. Short step, and it changes every report they ever
+read.
+
+**Report depth** (optional, one question): *"Do you want reports summary-first
+with the detail behind it, or full detail?"* Stored in the profile; read by
+`ncr-writeup` and `root-cause-capa`. Not asked again if deferred — the default
+is full detail.
+
+### Step 6 — Confirm sites
+
+One plant or several. Site-scoped groups are time, vocabulary, capability and
+machining data; ask those per site and offer inheritance rather than repeating
+the interview. The inheritance rule is in `reference/config-profile.md`.
+
+### Step 7 — Capture the capability profile and machining data
+
+Materials, processes, size envelope, demonstrated tolerance capability, and
+certifications held. Ask for demonstrated capability, not aspirational — this is
+the basis on which work gets declined.
+
+**Then the machining data `quote-build` derives hours from.** Machine classes
+with their work centers, cell, setup hours and tool-change time; cutting data
+per material and tool class (SFM and chip load), or the name of the plant's
+Fusion tool library; the variance-flag threshold; and the stale interval for
+cost history. **Every setup and tool-change figure carries `basis: measured`
+or `basis: assumed`** — an assumed 0.5-minute tool change once explained a 36%
+hours gap, and nobody could see it was a guess. An estimator's ballpark is
+recorded as assumed, never as plant data. A routing or asset export from
+Step 2 or 3 answers most of this as *confirm or correct*. Fields and format:
+`reference/config-profile.md`, *Machining data*.
+
+### Step 8 — Capture standards, clauses and approved suppliers
+
+Which standards the plant is certified to, its standard supplier quality
+clauses, its standard commercial terms, and **its approved supplier list by
+commodity** — `supplier-quote-request` builds its candidate list from it.
+Ask for each existing list as a document rather than reconstructing it in
+conversation. Where the ERP (NetSuite or Infor M3) is live, read the vendor list from it
+and ask only which vendors are approved for what.
+
+### Step 9 — Collect templates
+
+One real example of each of the five controlled documents, and derive the
+structure from it. **Never derive from a generic version** — a customer-required
+8D has a contractual shape, and a plausible substitute is worse than an admitted
+gap.
+
+### Step 10 — Capture commercial rates
+
+Labor rate, burden rate, margin rules, and downtime cost per hour (derived from
+them, same handling). Capture the actual values — not a pointer to who holds
+them — so `quote-build` and `daily-production-report` price without asking
+again. The full rule is `../../shared/secret-config.md`; what follows is how
+this step applies it.
+
+**Two routes.** An `MFG_*` environment variable, which wins when set, or a
+**confirmed** rate in the `## Plant rates` file at `rates_path`. Check each
+variable by name first, without printing it. A rate set in the environment is
+*set in environment* and not asked. Every other rate is asked here, once.
+
+**Before asking, say where the numbers go:** onto the plant's private rates
+page in their Claude account, never the setup page and never a customer quote.
+A plant that wants the stricter route can set the `MFG_*` variables instead.
+
+- **Margin in plain language.** "What margin do you usually quote at, and is
+ there any customer or kind of job where it's different?" Record a default
+ plus `by_customer` and `by_job_type` overrides in the `MFG_MARGIN_RULES`
+ JSON shape. Never ask anyone to write JSON.
+- **Downtime cost per hour, asked explicitly, never computed here.** Without
+ it the morning report prices scrap only — permanently, and quietly.
+- **Who is giving the rates**, unless already said. Each confirmed rate
+ carries that name and the date. Never infer a name.
+
+**Storage, audience, echo.** Stored in an `MFG_*` variable or the rates file,
+never a file that could be committed or copied between customers. Shown on
+internal artifacts (cost-basis sheet, internal margin line, priced downtime);
+never on a customer-facing artifact, the setup summary, the config profile
+page, the gaps list, sample data or logs. **Shown back once**, in the approval
+draft's own section headed *Commercial rates — internal, check these before
+you say yes*, so a typo can be caught. Nowhere else in the conversation;
+after the write, confirm by name, not value. Nothing is written until the
+yes, per Step 11.
+
+**If someone types a rate unprompted** — "our labour rate is X and burden runs
+Y, write those into the config" — that is a step 10 answer. **A rate already
+set in the environment is not stored from chat and its typed value is not
+repeated anywhere**: say by name that it is set in the environment, that the
+environment wins, and that the variable is where it changes. Every other typed
+rate goes into the approval draft, written only on a yes. Do not restate any
+typed rate anywhere else in the reply — the check to run before sending is
+`../../shared/secret-config.md`, *Never repeat what was typed*.
+
+**Credentials are never accepted this way.** A token, password or API key
+pasted into the chat is refused, never repeated, and the user is told to
+rotate it.
+
+Standard cost and scrap costing basis sit in the ERP where plenty of internal
+people see them, so they are not subject to these rules.
+
+**A rate nobody knows is a marked placeholder** with its assumption, on the
+gaps list. It goes in the rates file with the confirmed ones, labelled. When the real value arrives it becomes confirmed
+and drops off the gaps list.
+
+### Step 11 — Write the profile, then report the gaps
+
+Show the full profile, write it on approval, and render the config profile page.
+Format and field names are fixed by `reference/config-profile.md`.
+
+**Two turns, never one.** The turn that first shows the full Plant context
+draft ends there, with a plain ask for a yes. The block is written and the
+config page rendered or published only in a later turn, after an explicit yes
+given with the draft on the screen. "Set us up," "carry on" and "use what you
+have" started the work; they do not approve a draft nobody had seen when they
+were said.
+
+**Write the two files `plant_setup.py find` names, then the two pages.** The
+profile goes to `profile_path` (each rate as its state only) and the values to
+`rates_path`, per `../../shared/replies.md`. The yes ask offers *"yes"* (files
+and both private pages, so every new task finds them) or *"yes, folder only"*.
+Never the export folder. Nothing writable: say so, print both, and stop.
+
+Then produce the gaps list — **the most useful output of this skill**. For every
+item still missing: what it is, which skills are affected, and how each one
+degrades. Generated from the degradation map in `reference/config-profile.md`.
+**Name every affected skill the map lists, not only the most affected one** —
+without a CMMS connector that is `breakdown-diagnosis` *and*
+`daily-production-report`'s maintenance-work-orders-in-progress line, among
+others.
+
+### Step 12 — Connector options
+
+Runs once, after the gaps list, over **every system named in Step 1 that is
+not one of the four**: the registry row first, then a search for a
+vendor-published MCP (vendor domain or vendor docs only; where web search is
+not available, say so and give *"not in our registry — check your vendor's
+docs"*), then the registry's access tier and what `custom-connector` would
+need. One table: *System · What exists · Route · Next step*. The procedure is
+`reference/connector-options.md`.
+
+**Onboarding reports options; it never connects.** No setup steps for these
+systems, no attempted connection, no credential taken. The plant chooses, and
+`custom-connector` does the work. **Deferrable:** "later" ends the step, and
+each system stays on the gaps list as *connector options not reviewed*.
+
+### Reconfigure
+
+Setup is not a one-time event. Shift patterns change, connectors come online,
+sites get added. Re-running touches only what changed: show current against
+proposed, change what the user confirms, and **never wipe unrelated
+configuration**.
+
+**Updating a rate.** "Update our labour rate," "change our margin" or "our
+burden went up" re-runs Step 10 for the named rates only — none of Steps 1 to
+9. Show each rate's current state against the proposed value, in the same
+internal section of the draft, and write only the `### Commercial rates`
+section after a yes. A rate set in the environment cannot be changed from
+here: say it is set in the environment, by name, and that the variable is
+where it changes.
+
+**Clearing a rate.** "Clear our rates" or "remove the labour rate" sets the
+named rates to **not set**, after the same yes. Say which lines each one will
+block from then on.
+
+**More documents.** "Here's more" re-runs Step 2 over the new files only, then
+the steps they route to, each as *confirm or correct*.
+
+---
+
+## Approval gates
+
+- **Show the profile before writing it.** Display the full draft and wait for an
+ explicit yes, given after the draft was shown. Never show and write in the
+ same turn. What counts as a yes is `../../shared/approval-gates.md`.
+- **Never overwrite silently.** On a re-run, show current against proposed
+ side by side before changing anything.
+- **Never connect a tool on the user's behalf.** Guide; do not act. Connector
+ auth is always owner-initiated. Step 12 reports options; it never attempts a
+ connection and never describes setup steps outside the four-row table.
+- **Never accept a credential in conversation.** API keys and client secrets go
+ into connector settings. If someone pastes one, say plainly that it should be
+ rotated because it has touched the transcript, that nothing was done with it,
+ and that connector auth happens in Claude's connector settings.
+- **Never repeat a pasted credential — not any part of it.** Not quoted, not
+ in code formatting, not in the rotation instruction itself. It is "the token
+ you pasted," "the secret you pasted." Before sending, check the reply for any
+ run of eight or more characters from the pasted value, and rewrite if one is
+ there. Per `../../shared/secret-config.md`.
+- **Show a typed rate once, in the approval draft, and nowhere else.** Not in
+ the sentence that asks for the yes, not in the confirmation after the write,
+ not in the setup summary, the config profile page or the gaps list. Before
+ sending, check the reply for any rate number the user typed outside the
+ draft's internal rates section, and rewrite if one is there.
+- **Never pull business data during Step 1.** Step 2 reads only what the user
+ hands over, and classifies before it deep-reads.
+- **Never push for a deferred answer.** "I'd have to ask" ends the question.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The `## Plant context` memory block** — authoritative, read by every skill via
+heading match. Schema in `reference/config-profile.md`.
+
+**The config profile page** — an HTML artifact in the house style
+(`../../shared/artifact-style.md`), as the plant's own readable record. A
+rendering of the block, regenerated rather than hand-edited. It shows each
+commercial rate by state, who gave it and the date, and never renders a rate
+value.
+
+**The setup summary** — plain language: what is configured, what each live
+connector gives this plant specifically, and one line per file read in Step 2
+saying what it supplied. Commercial rates appear by state, who
+gave them and the date, never by value. One line more: *"Paused RFQs, supplier
+quotes and dashboard links will be kept on a private Open work page the first
+time you need one."*
+
+**The time configuration report** — declared zones per source, the shift and day
+boundary rules, and the offset self-check result including a zero result. **The
+Source clocks table has one row per source, each with its own timezone and
+zone-aware flag**: every export file (MES production, MES downtime, historian,
+quality, planning) and every live connector (the ERP, a CMMS connector) is its
+own row,
+per the template in `reference/config-profile.md`. Never merge sources into a
+shared "date-only" row; the row a source is missing from is the one whose
+clock nobody checked.
+
+**The gaps list** — every missing item, the skills it affects, and how each one
+degrades.
+
+**The connector options table** — Step 12's *System · What exists · Route ·
+Next step*, one row per named system that is not one of the four supported
+connectors.
+
+---
+
+## Edge cases and failure modes
+
+- **The user does not know an answer** — very common for rates, machining data
+ **and time config alike**. Record a marked placeholder with its assumption,
+ put it on the gaps list, and move on. Never block. A placeholder isn't a
+ sensitive value; a real rate, once supplied, is shown by state, never by
+ value, outside the approval draft and internal artifacts. A placeholder
+ source clock is never acted on as verified: a skill correlating across it
+ refuses and reports the alignment gap (`reference/time-config.md`).
+- **The user names a system the plugin has never heard of** — accept it,
+ record it, run it on exports, and give it a Step 12 row. Never steer them
+ toward one of the four.
+- **No documents to hand** — skip Step 2; ask every later step directly.
+- **A document contradicts the user** — the user's answer wins, and the
+ contradiction is named once with the file, so a stale document is found.
+- **Exports are not set up yet** — the export request specification.
+- **Multi-site plant** — config per site with shared values inherited. Getting
+ this wrong means one plant's shift boundary silently applied to another.
+- **Connectors not yet provisioned** — partial config now, resumable later, with
+ the gaps list reflecting it.
+- **The offset self-check finds a skew and the user insists the config is
+ right** — report it, do not override. A real clock drift is a finding worth
+ surfacing to their IT.
+- **No shared event exists to test the offset against** — record the config as
+ declared but unverified, and put it on the gaps list.
+- **A single-site plant** — still gets one site block, named `(default)`, so
+ adding a second site later changes nothing about how the first is read.
+
+---
+
+## Chain position
+
+Not part of a chain. It is the utility every chain depends on, and the
+configuration it captures is what keeps the other skills from hard-coding
+assumptions or re-asking the same questions every run.
+
+**Metric.** Adoption and setup quality. No plant metric.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/interview.md` | Running the interview — every group, in order, with the wording |
+| `reference/erp-scope.md` | Step 1 — the ERP record types, this plant's scope, revision, cost fields, work order source, RFQ staleness |
+| `reference/document-intake.md` | Step 2 — the document list, the routing table, what each file is mined for |
+| `reference/time-config.md` | Step 4 — per-source clocks, shift definition, and the offset self-check |
+| `reference/config-profile.md` | Step 11 — the storage schema, site inheritance, and the degradation map |
+| `reference/connector-options.md` | Step 12 — the options check and its table |
+| `../custom-connector/reference/known-systems.md` | Steps 1 and 12 — the setup steps for the four supported connectors, quoted word for word, and the registry |
+| `../../shared/approval-gates.md` | Steps 3 and 11 — confirming one at a time, and what approves a draft |
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/reference/config-profile.md b/plugins/claude-for-manufacturing/skills/onboarding/reference/config-profile.md
new file mode 100644
index 00000000..7dea0fa5
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/reference/config-profile.md
@@ -0,0 +1,405 @@
+# The config profile — storage format and contract
+
+This file is the contract. Every other skill reads the profile by heading match,
+so the headings and field names below are not editable per plant.
+
+---
+
+## Two artifacts, one source of truth
+
+| Artifact | Form | Who reads it |
+|---|---|---|
+| `## Plant context` block | Markdown file at `profile_path` (`plant_setup.py find`), kept on the private `Plant setup: <company>` page | Every skill, at run time, by heading match |
+| `## Plant rates` block | Markdown file at `rates_path`, kept on the private `Plant rates: <company>` page | Skills that price, per `../../../shared/secret-config.md` |
+
+The files are authoritative; each page carries its file byte for byte plus a
+readable view, rebuilt by `plant_setup.py render`, never edited by hand
+(`../../../shared/replies.md`, *The plant setup and the rates*). **The setup
+file never holds a rate value** and `render` refuses one: its
+`### Commercial rates` lines carry each rate's state only. The rates page's
+view shows each rate's state, never the number.
+
+---
+
+## The block
+
+Write this under the heading `## Plant context`, in the file at
+`profile_path`. **Never the export folder, a shared or synced folder, or a
+file a repository commits.** Say the path it was written to. An older profile may
+live in `CLAUDE.local.md` or the project's memory; a reconfigure
+reads it from there and writes the new files.
+
+```markdown
+## Plant context
+
+- **Profile version:** 2
+- **Configured:** 2026-09-08
+- **Company:** Example Manufacturing
+- **Sites:** Fairview (default) - Brantford
+- **Connectors live:** Microsoft 365, Oracle NetSuite
+- **Connectors not live:** Autodesk Fusion
+- **Export folder:** Shared Documents/Plant Exports
+- **Export refresh:** nightly, lands by 02:00 local
+- **Standards certified to:** ISO 9001:2015, AS9100D
+- **Templates on file:** NCR form, 8D format
+- **Templates missing:** quote layout, supplier RFQ package, trade study memo
+- **Report depth:** full
+- **Rates:** see Commercial rates - state per rate, values shown only on internal artifacts
+- **Gaps open:** 4
+```
+
+### Systems
+
+One line per category, from Step 1. The name is whatever the plant uses; the
+state is one of `live (supported)`, `live (custom)`, `file` or `none`. Only
+Microsoft 365, Oracle NetSuite, Infor M3 and Autodesk Fusion can be `live (supported)`;
+anything else is `live (custom)` once `custom-connector` has connected it, and
+`file` until then.
+
+```markdown
+### Systems
+
+- **ERP:** Oracle NetSuite - live (supported)
+- **CAD:** SolidWorks - file
+- **CMMS:** Limble CMMS - file - connector options reviewed 2026-09-08
+- **Documents:** Microsoft 365 - live (supported)
+```
+
+A skill reads the **state**, not the vendor name: "CMMS connector live" means the
+CMMS line says `live (custom)`, whichever CMMS it is. "ERP live" means the ERP
+line says `live (supported)`, whether it names Oracle NetSuite or Infor M3. A system whose Step 12
+options were deferred says `connector options not reviewed`.
+
+### ERP scope
+
+From Step 1, per `erp-scope.md`: the record types checked, this plant's
+subsidiary, locations and parts, where the part revision lives, which cost
+field means what, where production work orders come from, which source wins
+when a connector and an export overlap, and how long an RFQ may wait. Below it,
+`### Approved normalizations`, which `data-consolidate` appends to on each
+yes. The format is in `erp-scope.md`, *The section*. A line not yet answered
+says **not set** and is on the gaps list.
+
+### Documents read at setup
+
+One row per file from Step 2, so a later run can tell where a value came from.
+
+```markdown
+### Documents read at setup
+
+| File | Identified as | Fed | Status |
+|---|---|---|---|
+| Fairview shifts 2026.pdf | Shift calendar | Step 4 | confirmed |
+| QM-001 Quality Manual RevF.pdf | Quality manual | Steps 7, 8 | confirmed |
+| scan_0412.pdf | Unidentified | - | on gaps list |
+```
+
+### Export file inventory
+
+One row per file. Identified in Step 3 and **confirmed by the user**, never
+accepted from inference alone. A file dragged into the conversation rather
+than landing in the folder is recorded with cadence **manual** — it works for
+a run the user starts, and no scheduled skill can rely on it.
+
+```markdown
+### Export files
+
+| File pattern | What it is | System | Cadence | Covers |
+|---|---|---|---|---|
+| prod-output-*.csv | Actual production output, good and scrap | MES | daily | prior day |
+| downtime-*.csv | Downtime events with reason codes | MES | daily | prior day |
+| inspection-*.xlsx | Inspection results against spec | QMS | weekly | prior week |
+| schedule-*.xlsx | Planned quantity by part and date | Planning | daily | next 14 days |
+| cmms_maintenance.csv | Maintenance work orders | CMMS (file) | manual | last 90 days |
+```
+
+### Machining data
+
+Read by `quote-build`'s hours ladder and `rfq-to-quote`'s design step when a
+part has no current routing. Site-scoped. **Every setup and tool-change figure
+carries its basis**, `measured` or `assumed`, and an assumed figure is named
+whenever it accounts for a variance — that is what makes a 36% gap traceable
+to a guessed tool-change time rather than a mystery.
+
+```markdown
+### Machining data
+
+| Machine class | Work centers | Cell | Setup hours | Tool change min | Basis |
+|---|---|---|---|---|---|
+| SAW | SAW-01 | CELL-A | 0.25 | - | measured |
+| VMC-3AX | HAAS-VF4-02, HAAS-UMC-01 | CELL-B | 1.25 | 0.5 | assumed |
+| LATHE-2AX | DOOSAN-PUMA-07, DOOSAN-PUMA-03 | CELL-C | 1.00 | 0.2 | measured |
+| DEBURR | BENCH-02 | CELL-D | 0.10 | - | measured |
+| OUTSIDE-FINISH | (black oxide, outside) | - | 5 working days per lot | - | measured |
+
+| Material | Tool class | SFM | Chip load ipt | Basis |
+|---|---|---|---|---|
+| 4140 | carbide end mill, roughing | 400 | 0.002 | assumed |
+| 4140 | face mill | 600 | 0.004 | assumed |
+
+- **Fusion tool library:** not used
+- **Variance flag threshold:** 15% - default, not plant-set
+- **Stale interval:** 365 days
+```
+
+- **Cutting data** is either the table or a named Fusion tool library — record
+ `Fusion tool library: <name>` instead of the table when that is where the
+ plant keeps it. Neither means hours derived in Fusion run on library
+ defaults, which `quote-build` treats as first-principles and labels so.
+- **An estimator's ballpark is `assumed`.** Never recorded as measured because
+ it was typed with confidence.
+- **Variance flag threshold** deferred is recorded as *15% - default, not
+ plant-set*, and every flag raised on it says so.
+
+### Approved suppliers
+
+From Step 8. Read by `supplier-quote-request` for its candidate list.
+
+```markdown
+### Approved suppliers
+
+| Commodity | Approved | Notes |
+|---|---|---|
+| 4140 bar | VEND-3310, VEND-3402 | |
+| Black oxide | VEND-5120 | single source |
+```
+
+A commodity with one approved supplier is marked single source, so the
+supplier skills can flag it rather than discover it.
+
+### Source clocks
+
+**The highest-risk configuration in the plugin.** One row per data source, per
+`time-config.md`.
+
+```markdown
+### Source clocks
+
+| Source | Timezone | Zone-aware | Observed skew | Checked |
+|---|---|---|---|---|
+| NetSuite | America/New_York | yes | none | 2026-09-08 |
+| CMMS (Limble, live custom) | America/New_York | yes | none | 2026-09-08 |
+| MES production export | America/New_York | no, naive | +1h vs NetSuite | 2026-09-08 |
+| MES downtime export | America/New_York | yes, -04:00 | none | 2026-09-08 |
+| Historian export | UTC | yes, +00:00 | none | 2026-09-08 |
+| Quality export | America/New_York | no, naive | not checked | — |
+| Planning export | America/New_York | no, naive | not checked | — |
+```
+
+**One row per source, always.** A source not yet asked about gets its own row
+with "not checked," never a shared row with other sources: two exports can
+carry `-04:00` and `+00:00` in the same folder, and a merged row hides
+exactly that.
+
+A non-zero skew stays in the table. It is a finding, not something to correct
+away.
+
+---
+
+## Sites and inheritance
+
+**One plant is still a site.** A single-site plant gets one site block named
+`(default)`. This keeps the read path identical for every skill and means adding
+a second site later changes nothing about how the first one is read.
+
+Values in the top-level block are **shared**. Values in a site block are
+**overrides** and win for that site only.
+
+```markdown
+### Site: Fairview (default)
+
+- **Timezone:** America/New_York
+- **Shift pattern:** three 8s - 07:00, 15:00, 23:00
+- **Production day starts:** 07:00
+- **Cross-midnight shift belongs to:** the day the shift started
+- **Planned production time:** scheduled shift hours minus planned PM windows
+- **Vocabulary:** job = production work order - cell = work center - area = department
+- **Capability:** aluminium and 300-series stainless - 3-axis and 4-axis milling, turning - max envelope 600 x 400 x 300 mm - demonstrated true position 0.002 in
+
+### Site: Brantford
+
+- **Timezone:** America/Toronto
+- **Shift pattern:** two 12s - 06:00, 18:00
+- **Production day starts:** 06:00
+```
+
+Brantford inherits everything not restated. It has its own timezone, shift
+pattern and day boundary, and takes Fairview's vocabulary and capability.
+
+**Two optional lines and one optional section for the morning report's floor
+view.** `- **OEE thresholds:** good at or above 75%, poor below 60% - confirmed
+by <name or role>, <date>` (shared, or a site override) sets the floor view's
+colours; absent, the report uses those defaults and says they are not
+confirmed. `### Floor layout - <site>` is written only by
+`daily-production-report`'s setup turn, after the person confirms each
+machine, in the shape of `../../../shared/contracts/floor-layout.md`.
+Onboarding keeps both lines as they are when it rewrites the profile.
+
+**The failure this structure exists to prevent:** one plant's shift boundary
+silently applied to another. A skill reading a site-scoped value must resolve it
+through the site block first and only then fall back to shared. **When a run
+spans more than one site, ask which site rather than resolving to the default.**
+
+---
+
+## Sensitive values — stored, not just pointed to
+
+Labor rate, burden rate, margin rules and the downtime cost per hour derived
+from them are commercially sensitive, but they **are** stored. This isn't
+"treat it like a credential": a credential is used opaquely and never
+displayed, but a burden rate has to be multiplied by hours and shown —
+`quote-build`'s cost-basis sheet and `daily-production-report`'s priced
+downtime both depend on reading the actual value, not asking a person for
+it every run.
+
+There are two routes, and the full rule is
+`../../../shared/secret-config.md`: an `MFG_*` environment variable, which
+wins when set, or a **confirmed** rate in the `## Plant rates` file, written by
+step 10 after the plant has seen it and said yes. Cowork users have only the
+second route.
+
+Three rules govern them, wherever they're read:
+
+- **Storage** — an `MFG_*` variable, or the `## Plant rates` file and its
+ private page. Never a file in a repo, never a file copied between customers,
+ never the setup file a teammate may be shown. Step 10 says where they go
+ before asking.
+- **Audience** — usable and displayable in internal artifacts (cost-basis
+ sheets, internal margin lines, priced downtime). Never in a
+ customer-facing artifact, the readable setup summary, the config profile
+ page, the gaps list, sample data, or logs.
+- **Echo** — shown back once, in the step 10 approval draft, so the plant can
+ catch a typo. After that, used and shown where the audience rule allows,
+ and confirmed by name, not value.
+
+Every rate carries exactly one of four states. **The rates file** holds the
+values, under its own heading with the company and the date:
+
+```markdown
+## Plant rates
+
+- **Company:** Example Manufacturing
+- **Configured:** 2026-10-02
+
+### Commercial rates
+
+- **Labor rate:** confirmed 71.00/hr - given by Pat Doyle, 2026-10-02
+- **Burden rate:** set in environment (MFG_BURDEN_RATE)
+- **Margin rules:** confirmed `{"default":0.32,"by_customer":{"EXAMPLE-AEROSPACE":0.28},"by_job_type":{"prototype":0.45}}` - given by Pat Doyle, 2026-10-02
+- **Downtime cost per hour:** not set - see gaps
+- **Scrap costing basis:** standard cost from NetSuite (not sensitive - stored in the clear)
+```
+
+**The setup file** holds the same lines with each value removed, so a teammate
+shown the setup page sees the state and nothing more:
+
+```markdown
+### Commercial rates
+
+- **Labor rate:** confirmed - on the rates page - given by Pat Doyle, 2026-10-02
+- **Burden rate:** set in environment (MFG_BURDEN_RATE)
+- **Margin rules:** confirmed - on the rates page - given by Pat Doyle, 2026-10-02
+- **Downtime cost per hour:** not set - see gaps
+- **Scrap costing basis:** standard cost from NetSuite
+```
+
+| State | What the rates file's line holds |
+|---|---|
+| **Set in environment** | The variable name only. The value lives in the environment and is read at run time |
+| **Confirmed** | The value, who gave it and the date. Written only after an explicit yes on the approval draft |
+| **Placeholder** | The value and its assumption, marked "not confirmed" |
+| **Not set** | Nothing to price on. The gaps list names it |
+
+Margin rules use the JSON shape of `MFG_MARGIN_RULES`: a `default`, plus
+`by_customer` and `by_job_type` overrides, each a fraction of price. A rule
+the plant states that does not fit that shape is recorded as said and put on
+the gaps list, never forced into it.
+
+A placeholder goes in the rates file with its assumption, like a confirmed
+rate:
+
+```markdown
+- **Labor rate:** placeholder 62.00/hr - assumed from the FY25 budget, not confirmed
+- **Burden rate:** placeholder 140% - assumed, not confirmed
+```
+
+`quote-build` prices on a placeholder and labels every line it touches
+"placeholder rate — not confirmed". The gaps list names the placeholder, never
+its value.
+
+A rate the person answering didn't know is a **placeholder**, not a
+sensitive value — it isn't the plant's real number. Its value sits in the
+rates file with its assumption; the gaps list and the setup summary name it
+as a placeholder. When the real value is supplied it becomes **confirmed** and the
+placeholder marker drops.
+
+**How the setup summary and the config profile page show this section.** By
+state, never by value: *"Labor rate: confirmed, given by Pat Doyle on
+2026-10-02"*, *"Burden rate: set in environment"*, *"Downtime cost per hour:
+not set"*. A placeholder may show its value, because it is not the plant's
+number.
+
+**Never accept a credential, API key or client secret in conversation.** Those go
+into connector settings on the plugin side. If someone pastes one, say plainly
+that it should be rotated — **without repeating any part of it**. It is "the
+token you pasted," never the string, not even inside the rotation instruction.
+
+Commercial rates are not credentials: they are asked about directly, per
+`interview.md` group 10, and stored as above. A rate typed at step 10 is shown
+once in the approval draft and nowhere else in the conversation; a rate typed
+to any other skill is not used for that run and not repeated, and the step 10
+update is offered instead. Both rules are
+`../../../shared/secret-config.md`, *Never repeat what was typed*.
+
+---
+
+## Degradation map
+
+Step 11's gaps list is generated from this table. Each row is a config item, who
+reads it, and **what the consuming skill does when it is missing** — which is
+always "state the limit," never "guess."
+
+| Config item | Consumed by | Missing behavior |
+|---|---|---|
+| Connectors live | Every skill | Skill runs its file-only path and names which sources were file-sourced |
+| CMMS connector live (custom) — Limble is the worked example | `breakdown-diagnosis`, `breakdown-to-next-report`, `daily-production-report`, `morning-plant-pulse`, `data-consolidate`, `root-cause-capa` | `breakdown-diagnosis` loses live asset records, open tickets and the current PM plan, and reads history from the export. `daily-production-report` loses its **maintenance work orders in progress** line: replaced from the maintenance export where one exists, otherwise omitted and said so. The others read maintenance from the export and name it export-sourced in the freshness banner |
+| Fusion live, or a CAD connector live (custom) | `design-space-explore`, `rfq-to-quote` | `design-space-explore` cannot generate variants without one; names exactly what is needed, quoting `../../custom-connector/reference/known-systems.md`. `rfq-to-quote`'s design step is skipped and hours fall back down the ladder, labelled. `trade-study-report` is unaffected |
+| Machining data | `quote-build`, `rfq-to-quote` | Hours derived from a drawing run on library defaults and rank as first-principles, labelled "library defaults, not plant data". An assumed setup or tool-change figure is used and named in every variance it drives |
+| ERP scope: plant parts and locations | `data-consolidate`, every ERP reader | Says *scope not set* as a gap and pulls nothing it would have to guess the scope of; offers the item prefix it saw as a question |
+| ERP scope: part revision | `supplier-quote-request`, `quote-build` | The revision check says where it looked and that the ERP's revision location is not set; the hard stop holds |
+| ERP scope: cost fields | `quote-build`, `supplier-quote-request`, `daily-production-report` | Reads standard, then average, then last purchase price, naming the field each figure came from; never treats a field equal to the sell price as a cost |
+| ERP scope: work order source | `data-consolidate` | Treats the ERP as the work order source; where it returns none, says so once rather than reporting every MES row unmatched |
+| Approved normalizations | `data-consolidate`, `morning-plant-pulse`, `daily-production-report` | Every fix is proposed again and every affected figure is provisional |
+| RFQ stale after | `customer-inquiry-intake`, `rfq-to-quote` | 5 business days, labelled *default, not plant-set* |
+| Approved suppliers | `supplier-quote-request` | Candidate list from ERP vendors only, every one flagged as not confirmed approved |
+| Connector options | Systems named in Step 1 | Stay on exports; listed on the gaps list as "connector options not reviewed" |
+| Report depth | `ncr-writeup`, `root-cause-capa` | Full detail |
+| Export folder path | `data-consolidate`, `daily-production-report` | Ask once per run; produce an export request specification if none exists |
+| Export file inventory | `data-consolidate`, `daily-production-report` | Identify by header signature and ask the user to confirm each file |
+| Source clocks | `root-cause-capa`, `daily-production-report` | Refuse to correlate across sources; report the alignment gap |
+| Shift pattern and day boundary | `root-cause-capa`, `daily-production-report` | `root-cause-capa`: the shift-clustering check cannot run — report it among the checks that could not run, and treat cross-midnight attribution as unresolved rather than guessing which day an event belongs to. `daily-production-report`: cannot compute availability; report output only and say why |
+| Vocabulary | `data-consolidate`, `breakdown-diagnosis`, every report | Use canonical names and say they are canonical, not the plant's |
+| Capability profile | `customer-inquiry-intake` | Bid/no-bid degrades to a constraint-free recommendation and must say so |
+| Commercial rates | `quote-build`, `daily-production-report`, `breakdown-diagnosis` | Resolved per `../../../shared/secret-config.md`: `MFG_*` variable, then a confirmed rate in this block, then a placeholder. Without a rate on file in either route, the gaps list names it (never its value) and the consuming skill states the limit — `quote-build` blocks the line the rate feeds, `daily-production-report` prices scrap only and states downtime is unpriced, `breakdown-diagnosis` reports downtime in hours only |
+| Templates | `ncr-writeup`, `root-cause-capa`, `quote-build`, `supplier-quote-request`, `trade-study-report` | Use a neutral structure and flag that it is not the plant's controlled format |
+| Standards and clauses | `supplier-quote-request` | List clauses found on the part record and flag the set as unverified |
+| Sites | Everything | Treat as single-site; ask before applying any site-scoped value |
+
+All twelve skills are built. This table is the contract they're built
+against — the profile captures every value listed here regardless of which
+skill happens to read it in a given run.
+
+---
+
+## Versioning and reconfigure
+
+**`Profile version` increments when the schema changes**, not when a value
+changes. A skill reading an older version fills only the fields it needs and
+leaves the rest alone.
+
+**Reconfigure never wipes unrelated configuration.** A shift pattern change
+touches one site block. A newly connected system touches the connector lines,
+its `### Systems` line and the source clock table. More documents ("here's
+more") add rows to `### Documents read at setup` and touch only what they were
+confirmed to change. Show the current value and the proposed value side by
+side, change only what the user confirms, and update `Configured`.
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/reference/connector-options.md b/plugins/claude-for-manufacturing/skills/onboarding/reference/connector-options.md
new file mode 100644
index 00000000..9d2e183b
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/reference/connector-options.md
@@ -0,0 +1,62 @@
+# Step 12 — Connector options
+
+Runs once, after the gaps list, over every system the plant named in Step 1
+that is **not** one of the four supported connectors (Microsoft 365, Oracle
+NetSuite, Infor M3, Autodesk Fusion). Its job is to report what exists, so the plant can
+choose. It never connects anything.
+
+---
+
+## The order, per system
+
+Stop at the first rung that answers.
+
+1. **The registry.** Look up the system's row in
+ `../../custom-connector/reference/known-systems.md`. If the row is under
+ *Vendor-published MCP — add via custom-connector*, say a vendor-published
+ MCP exists, give its address as the row states it, and name
+ `custom-connector` as the route. Quote the row's notes; add nothing.
+2. **No row — search for a vendor-published MCP server.** Accept a result only
+ if it is on the vendor's own domain or linked from the vendor's own
+ documentation. Report:
+ - vendor, URL, and the documentation page it came from
+ - any beta, preview or labs label, exactly as the vendor states it
+ - a third-party or community server as **unofficial, not recommended** —
+ named, so nobody installs it thinking it was checked
+
+ **Where web search is not available in this session** — common in Cowork and
+ in scheduled runs — say so, and give *"not in our registry — check your
+ vendor's docs for an MCP server"*. Never answer from memory: a URL recalled
+ rather than found is an invented one.
+3. **No MCP.** Give the registry's access tier for that kind of system (REST
+ API, OData, SQL, export) and what `custom-connector` would need from the
+ plant to build on it — an API user, a read-only database view, an export
+ path.
+
+---
+
+## Output
+
+One table, one row per named system:
+
+| System | What exists | Route | Next step |
+|---|---|---|---|
+| Limble CMMS | Vendor-published MCP (registry) | `custom-connector` | Say "connect Limble" when a Limble Super User is available |
+| SolidWorks | No vendor MCP found | Export (already running) | Nothing needed; revisit if a vendor MCP appears |
+| Epicor Kinetic | REST API (registry, tier 3) | `custom-connector` | An Epicor API user with read access to jobs and parts |
+| Homegrown MES | Nothing published | Export (already running) | The plant's own developer is the source of truth |
+
+**Routes are one of three:** `custom-connector`, export (already running), or
+planned (the plant has said it is moving systems).
+
+**What this step never does:**
+
+- describe setup steps for any system not in the four-row setup table — that
+ is `custom-connector`'s job, once the plant chooses
+- attempt a connection, or take a credential
+- recommend a third-party server
+- report a system as connectable because a search result looked plausible
+
+**Deferrable.** "Later" ends the step. Each system stays on the gaps list as
+*connector options not reviewed*, and "what are our connector options" runs
+this step again on its own.
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/reference/document-intake.md b/plugins/claude-for-manufacturing/skills/onboarding/reference/document-intake.md
new file mode 100644
index 00000000..a6d67a6d
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/reference/document-intake.md
@@ -0,0 +1,120 @@
+# Step 2 — Bulk document intake
+
+The plant almost always has the answers to half the interview already, in
+documents nobody thought to hand over. This step asks for them up front, reads
+them, and turns the interview that follows into *confirm or correct*.
+
+It runs **after** Step 1 on purpose: once the live connectors are known, the
+list never asks for a document a connector already covers. Nobody uploads a part
+master when the ERP (NetSuite or Infor M3) is connected.
+
+---
+
+## The prompt
+
+Name the exact documents, grouped. Tag every line a live connector covers with
+`(skip — <system> is connected)`, generated per line from Step 1's results —
+never a fixed list.
+
+> "Drop in whatever you have from this list — any count, any format. I'll read
+> through them and only ask what they don't answer.
+>
+> **Production and maintenance data**
+> - MES or production export (jobs, work orders, cycle times, downtime)
+> - Maintenance history / work-order dump from your CMMS
+> - Asset or equipment register (machines, work centers, cells)
+> - Historian or sensor export, if you have one
+>
+> **Quality**
+> - A recent NCR
+> - A recent 8D or corrective action report
+> - Inspection records or FAI reports
+> - Quality manual, or your ISO / AS9100 / IATF certificate
+>
+> **Quoting and commercial**
+> - A recent quote you sent a customer
+> - Your supplier RFQ package, if you have a standard one
+> - Standard supplier quality clauses and commercial terms
+> - A trade study or design memo, if you've done one
+>
+> **Plant setup**
+> - Shift calendar or shift pattern
+> - Part master / routing export *(skip — NetSuite is connected)*
+> - Machine classes, setup times or cutting data, if you keep them
+> - Approved supplier list
+>
+> Anything else you think is relevant is fine too."
+
+Which lines get the skip tag:
+
+| Line | Skipped when |
+|---|---|
+| Part master / routing export | NetSuite is live. With Infor M3 live, only the part master is skipped: M3 gives this plugin no routings, so the routing export is still asked for |
+| Approved supplier list | Never skipped — the ERP holds vendors, not which are approved for what |
+| Maintenance history | A CMMS connector is live (`live (custom)`) |
+| Anything in Microsoft 365 | Never skipped — the connector reads documents, it does not know which one is the template |
+
+**Skippable, and re-runnable.** "I don't have any of that" ends the step and
+every later question is asked directly. "Here's more" later re-runs this step
+over the new files only.
+
+---
+
+## Classify first, deep-read second
+
+**The first pass reads only a header row or a first page.** It decides what
+each file is and where it routes. Only a file that routes to a step is read in
+full, and only for what that step needs. A quality manual is not read cover to
+cover to find a certificate date.
+
+| File looks like | Routes to | Mined |
+|---|---|---|
+| Tabular export | Step 3 | Source identity, cadence, timezone hints, shift times |
+| Asset / equipment register | Step 3 and Step 7 | Assets, work centers, cells → vocabulary and machine classes |
+| Routing or cycle-time export | Step 7 | Setup hours and cycle times by work center, as candidate machining data |
+| Quote / estimate | Step 9 and Step 10 | Quote layout; labor, burden and margin if stated |
+| NCR, 8D, trade memo, RFQ package | Step 9 | Template structure |
+| Quality manual / certificate | Step 8 and Step 7 | Standards and revisions, certificate expiry, processes |
+| Clause list / T&Cs | Step 8 | Supplier clauses, commercial terms |
+| Approved supplier list | Step 8 | Approved suppliers by commodity |
+| Shift calendar / HR doc | Step 4 | Shift pattern; day-boundary hint only |
+| Unidentifiable | Gaps list | Named; asked about in one line |
+
+---
+
+## Guardrails
+
+1. **Mined is not confirmed.** Every value read from a file is inferred until
+ the user says yes to it in the step it routes to, and is **shown labelled
+ that way** — *"three shifts, 07:00 / 15:00 / 23:00 (inferred, from
+ Fairview-shift-calendar-2026.txt)"*. A table of what each file gave carries
+ an *inferred* column or label; a bare value reads as settled. The question becomes
+ *confirm or correct*, with the source file named: *"Your shift calendar
+ shows three shifts starting 07:00, 15:00 and 23:00 — is that still right?"*
+ **The production-day boundary is asked directly in Step 4 regardless** —
+ a calendar shows when shifts start, not which day the 23:00 shift's output
+ belongs to.
+2. **A file-sourced rate follows Step 10.** It goes into the approval draft's
+ internal rates section, shown once, with the file name as its source —
+ *"labor rate 71.00/hr, from Q-2026-0412 quote.xlsx"* — and is written as
+ confirmed only on a yes, with the name of the person who said yes. It is
+ never restated anywhere else, including the setup summary's line for that
+ file.
+3. **No vocabulary or capability from a single document.** One quote that says
+ "tolerance ±0.0005" is not a demonstrated capability. Two consistent
+ sources, or ask.
+4. **A file that contradicts the user loses, and is named.** The user's answer
+ is recorded; the contradiction is stated once with the file, so a stale
+ document gets found.
+5. **Nothing from a file is acted on before Step 11's yes.** Mining is
+ reading; the profile is written once, after approval, like everything else.
+
+---
+
+## What the setup summary says about files
+
+One line per file: what it was identified as, which step it fed, and what it
+supplied — *"`Fairview shifts 2026.pdf` — shift calendar; supplied the three
+shift start times (confirmed)."* A file that supplied a rate says *"supplied
+commercial rates (see the approval draft)"*, never the value. An unidentified
+file is listed as unidentified.
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/reference/erp-scope.md b/plugins/claude-for-manufacturing/skills/onboarding/reference/erp-scope.md
new file mode 100644
index 00000000..79844942
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/reference/erp-scope.md
@@ -0,0 +1,170 @@
+# ERP scope — what the plant's ERP holds, and which part of it is this plant
+
+Load in Step 1, once the ERP is live or its exports are in hand. Every answer
+goes in the `### ERP scope` section of the `## Plant context` block
+(`config-profile.md`). Each one replaces a guess a skill would otherwise make
+on every run.
+
+An ERP account is rarely one plant's. It is shared with other businesses, or
+customised field by field, or both. One NetSuite account we have seen held 515
+items, 10 of them the plant's parts; the rest were coffee and retail.
+
+---
+
+## 1. Check only the record types the plugin uses
+
+Do not pull the full metadata catalogue. On a real account it runs past 100k
+characters and hundreds of custom record types. Check these, and for each say
+**present or absent**, plus its custom fields:
+
+| Record type | Used by |
+|---|---|
+| `item`, `assemblyitem` | every skill: the part master, standard and average cost |
+| `salesorder`, `itemfulfillment` | demand, late orders, shipments for containment |
+| `purchaseorder`, `itemreceipt`, `vendor` | supplier history, heat and lot receipts |
+| `inventorynumber` | lots on receipts and fulfilments |
+| `workorder` | production work orders and closed-job actuals |
+| `location` | where stock sits, and which locations are this plant |
+
+A query that fails with a SuiteScript error is reported as the error, with the
+query that caused it, and the record type marked **not checked**, never
+absent.
+
+## 2. This plant's scope
+
+Three answers, each confirmed by the user, never taken from a pattern alone:
+
+- **Subsidiary**, where the account has more than one
+- **Locations** that are this plant (by name or ID)
+- **Which items are its parts**: an item class, a prefix (`PN-`), or a list
+
+Propose from what Step 1 saw (*"10 items start `PN-`; are those your parts?"*)
+and record the answer. `data-consolidate` scopes every pull by it. Without it,
+the skill says *scope not set* as a gap and never guesses one.
+
+## 3. Where the part revision lives
+
+One of:
+
+- **a field**, named (`custitem_revision`)
+- **the item-ID suffix**, with its pattern (`PN-10047-A`: the letter after the
+ last hyphen)
+- **not in the ERP**: it lives on the drawing only
+
+`supplier-quote-request`'s revision hard stop and `quote-build` read this. A
+skill never infers the suffix pattern on its own.
+
+## 4. Which cost field means what
+
+NetSuite is customised, and the same idea has several homes. Record which
+field holds each, and the order skills read them in:
+
+| Meaning | Usual NetSuite field | Read order |
+|---|---|---|
+| Standard cost | `standardcost` (only with Standard Costing on) | 1 |
+| Average cost | `averagecost` | 2 |
+| Last purchase price | `lastpurchaseprice` | 3 |
+| Purchase price | `cost` | 4 |
+
+**Check that a cost is a cost.** If a cost field equals the latest sales order
+price on every item, say so and do not record it as a cost basis: it is a
+price, and quoting from it gives zero margin. Where a field is empty on every
+item, record it empty, not missing.
+
+## 5. Where production work orders come from
+
+**ERP** when `workorder` is present and returns this plant's work orders.
+**MES only** when the ERP holds none, as at plants that run production in the
+MES. Then `data-consolidate` takes work order identity from the MES export and
+reports *"work orders: MES only, per the plant profile"*, never hundreds of
+mismatches.
+
+## 6. When a connector and an export cover the same thing
+
+If both the live ERP and an ERP export are in hand, `data-consolidate` checks
+key overlap before joining them. Where the overlap is zero or low it asks
+which one is authoritative. Record the answer here, per entity, so it is asked
+once.
+
+## 7. Approved normalizations
+
+Not asked at onboarding: written by `data-consolidate` each time the user says
+yes to a fix, one row per rule. Every later run, attended or overnight, applies
+the rules on this list and only these.
+
+## 8. RFQ staleness
+
+How many business days an inquiry may wait on the customer before it is
+stale. **Default 5 business days**, labelled *default, not plant-set*, until
+the plant gives a number. `MFG_RFQ_STALE_DAYS` overrides it, like the rate
+variables.
+
+## 9. When the ERP is Infor M3
+
+The same answers, asked in M3's terms. What M3 returns and what it does not is
+`../../../shared/erp-connectors.md`.
+
+- **1, the record types:** check each call in that file's table once, with a
+ narrow filter, and say **answers, empty or fails** per call. "Record does
+ not exist" is *empty*. A call that fails is reported with its error and
+ marked **not checked**.
+- **2, the scope:** company and division come from
+ `MNS150MI_GetUserData_CurrentUser`. Ask which **facilities** and
+ **warehouses** are this plant (propose the user's defaults, never assume
+ them), and which items are its parts.
+- **3, the revision:** never a field; M3's item record holds none. The item-ID
+ suffix, or the drawing.
+- **4, the cost fields:** standard cost is **not available** from M3 to this
+ plugin. Record the read order as last purchase price from purchase order
+ lines, then a supplied cost, and put standard cost on the gaps list.
+- **5, the work orders:** **ERP** when `PMS100MI_SearchMO` returns this
+ facility's manufacturing orders; otherwise MES only, as above.
+- **The time unit for operation times.** Ask what unit the plant's work
+ centers report setup and run time in. Record it. Until then, operation times
+ are not costed.
+
+---
+
+## The section
+
+```markdown
+### ERP scope
+
+- **Record types:** item, assemblyitem, salesorder, purchaseorder, itemreceipt,
+ inventorynumber, vendor, location - present. itemfulfillment - present, none
+ for this plant. workorder - absent
+- **Subsidiary:** Example Manufacturing (ID 3)
+- **Locations:** Fairview Plant (ID 12), Fairview FG (ID 14)
+- **Parts:** item ID prefix `PN-` - confirmed 2026-10-14
+- **Part revision:** item-ID suffix, letter after the last hyphen
+- **Cost fields:** standard cost - not used (Standard Costing off) - average
+ cost `averagecost` - last purchase `lastpurchaseprice` - purchase price
+ `cost` (equals sell price on all 10 parts: not a cost basis)
+- **Production work orders:** MES only
+- **Source of truth:** items, sales orders - NetSuite connector; work orders -
+ MES export
+- **RFQ stale after:** 5 business days (default, not plant-set)
+
+### Approved normalizations
+
+| Rule | Source spelling | Matches | Approved by | Date |
+|---|---|---|---|---|
+| format drift | `4471B` | `PN-4471-B` | J. Okafor | 2026-10-13 |
+| leading zeros | `451` | `00451` | J. Okafor | 2026-10-13 |
+```
+
+With Infor M3 the lines that differ read:
+
+```markdown
+- **Calls:** MMS200MI, MMS060MI, PMS100MI, OIS100MI head, MWS411MI, PPS200MI,
+ CRS620MI - answer. MMS200MI_GetItmPrice, OIS100MI_SearchQuotation - not used
+- **Company / division:** 400 / AAA (from the signed-in user)
+- **Facilities:** A01 - **Warehouses:** 001
+- **Cost fields:** standard cost - not available from M3 (on the gaps list) -
+ last purchase price from purchase order lines
+- **Operation time unit:** minutes - confirmed 2026-11-06
+- **Source of truth:** items, sales orders, work orders - Infor M3 connector
+```
+
+A line not yet answered says **not set** and is on the gaps list. Never
+omitted: an omitted line reads as "nothing to configure."
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/reference/interview.md b/plugins/claude-for-manufacturing/skills/onboarding/reference/interview.md
new file mode 100644
index 00000000..68a6e048
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/reference/interview.md
@@ -0,0 +1,381 @@
+# The interview — every config group, in order
+
+**Who is answering.** A quality manager, a supervisor, an estimator or a plant
+manager. Not an IT admin. Ask in their language, one question at a time, and
+accept "I'd have to ask" as a complete answer.
+
+**The whole interview is answerable in one sitting**, and every group can be
+deferred. A deferred group goes on the gaps list with the affected skills named.
+Nothing here blocks setup.
+
+Group numbers match the step numbers in `../SKILL.md`. Time configuration is
+group 4 and has its own file, `time-config.md`; the document drop is group 2
+and has its own file, `document-intake.md`; connector options are Step 12 and
+have their own file, `connector-options.md`.
+
+---
+
+## Order, and why
+
+Run in this order. It front-loads what can be read rather than asked, so the
+user answers fewer questions.
+
+| # | Group | Mostly read, or mostly asked |
+|---|---|---|
+| 1 | Systems | Asked by category, then the four supported connectors tested |
+| 2 | Documents | Collected in bulk, classified, mined |
+| 3 | Export folder and dropped files | Read, then confirmed one at a time |
+| 4 | Time configuration | Asked, then tested |
+| 5 | Vocabulary and report depth | Asked, short — or confirm-or-correct from documents |
+| 6 | Sites | Asked, short |
+| 7 | Capability profile and machining data | Asked, medium — mostly confirm-or-correct where a routing or asset register came in |
+| 8 | Standards, clauses and approved suppliers | Collected as documents |
+| 9 | Templates | Collected as files |
+| 10 | Commercial rates | Asked, shown once for a yes, saved as confirmed in the plant profile unless set in the environment |
+
+**Any question a Step 2 document already answered is asked as *confirm or
+correct*, naming the file.** *"Your quality manual says AS9100 Rev D, certificate
+expiring March 2027 — still right?"* Never ask the user to retype what they
+just handed over.
+
+Sites is group 6 rather than last because groups 4, 5 and 7 are site-scoped. Ask
+whether there is more than one plant before capturing anything that varies by
+plant.
+
+---
+
+## 1 — Systems
+
+One open question per category. **Name no product as an option**: a list of
+examples reads as the plugin's preference, and the person types what they
+actually run. Any name, or none, is accepted.
+
+> *"First, what you run. What do you use for orders and invoicing?"*
+>
+> *"What do you use for design or CAD, if anything?"*
+>
+> *"What do you use for maintenance, if anything?"*
+>
+> *"And for documents and email?"*
+
+**One of the four supported connectors** (Microsoft 365, Oracle NetSuite,
+Infor M3, Autodesk Fusion) — test it now.
+
+- **What is live, what is not.**
+- **What it actually returns for this account.** Do not assume the standard
+ schema. NetSuite in particular is heavily customised per customer, so read
+ back the record types and a sample of fields that actually came through.
+ For Infor M3, the test is `MNS150MI_GetUserData_CurrentUser`; read back the
+ company, division, facility and warehouse it returns, and the calls in
+ `../../../shared/erp-connectors.md` that answer. Name the M3 data the plugin
+ cannot get from it (standard cost, quote history), once, here.
+- **Infor M3 is not Infor CloudSuite Industrial or Infor LN.** "Infor" alone
+ is asked which one. Only M3 is supported; the others are named systems.
+- **Not live** — quote its row in the setup-steps table word for word.
+- **Do not pull business data during this step.** This is a reachability and
+ shape check, not a data pull.
+
+**Anything else** — accept the name as given and say what happens next, nothing
+more:
+
+> *"No supported connector for Limble. I'll run your maintenance data on exports
+> for now and look at connector options at the end of setup."*
+
+No search, no setup steps, no mention of `custom-connector` here. Step 12 does
+that once, for every system at the same time.
+
+Record each answer in the profile's `### Systems` section: the name, and one of
+`live (supported)`, `live (custom)`, `file`, `none`.
+
+**Never connect anything on the user's behalf, and never take a credential in
+conversation.** Credentials go into connector settings. Where a connector needs
+an admin action the plant person cannot perform, say exactly what to ask for and
+who to ask.
+
+---
+
+## 2 — Documents
+
+See `document-intake.md`. The exact list, the skip tags for what a live
+connector covers, classification before deep reading, and the guardrails on
+what a mined value may and may not do.
+
+---
+
+## 3 — Export folder and dropped files
+
+The plugin's data foundation is not "connect to the MES." It is a folder where
+the plant's existing scheduled exports land, on a predictable path and cadence.
+
+1. **Ask where the exports land.** "Your MES and inspection reports get dropped
+ somewhere on SharePoint or OneDrive on a schedule. Where do they land?"
+2. **List what is actually there.**
+3. **Infer what each file is from its headers, then have the user confirm each
+ one.** Never accept the inference alone. A file identified wrong is worse than
+ a file not identified, because it will be joined.
+4. **Record the refresh cadence and coverage window per file.**
+
+**A file dragged into the conversation is a valid first-run source.** Confirm it
+the same way, one at a time, and record its cadence as **manual, not
+scheduled**. Then say what that means in one line: *"That works today. The
+morning pulse runs on its own overnight, so it needs this file landing on a
+schedule or a live connector — here's the export spec for IT."*
+
+### When the exports do not exist yet
+
+Common, and not a dead end. Produce an export request specification the plant's
+IT can implement without a follow-up call: exact fields with types and units,
+file format and encoding, naming convention, landing path, cadence, the window
+each file covers, and what to do about late or corrected records.
+
+IT is far more willing to schedule a report than to issue credentials, so this is
+frequently the fastest path to data in the whole build. It is also the path from
+a manual, dragged-in file to a scheduled one.
+
+### The maintenance export, specified
+
+Where the plant's CMMS has no live connector, this is the spec to hand IT. It is
+what `breakdown-diagnosis`, `daily-production-report` and `data-consolidate`
+read in place of a CMMS connector.
+
+| Field | Type | Unit / format | Required | Notes |
+|---|---|---|---|---|
+| `work_order_id` | text | — | yes | The CMMS's own ID, unchanged |
+| `asset_id` | text | — | yes | The same asset ID the MES downtime export uses; if the systems differ, both columns |
+| `asset_name` | text | — | yes | Plant's name for the machine |
+| `type` | text | `corrective` / `preventive` / `inspection` | yes | Map the CMMS's own types; never leave blank |
+| `status` | text | `open` / `in_progress` / `closed` | yes | |
+| `opened_at` | timestamp | ISO 8601 **with offset** (`2026-09-08T06:12:00-04:00`) | yes | Naive timestamps break cross-system correlation |
+| `closed_at` | timestamp | ISO 8601 with offset | when closed | Blank, never zero, while open |
+| `failure_mode` | text | — | no | The CMMS's failure code or category |
+| `close_out_note` | text | — | no | Free text, verbatim; `breakdown-diagnosis` mines it |
+| `parts_used` | text | `part_no:qty;…` | no | |
+| `labor_hours` | number | hours, decimal | no | |
+| `pm_plan_id` | text | — | no | Which PM plan, for preventive work |
+
+- **Format:** CSV, UTF-8, header row, comma-delimited, quoted text fields.
+- **Naming:** `cmms_maintenance_<YYYY-MM-DD>.csv`, dated the day of export.
+- **Landing path:** the plant's export folder, beside the MES files.
+- **Cadence:** nightly, landing by 02:00 local, or whatever the MES files use.
+- **Window:** a rolling 90 days of `opened_at`, so a work order reopened or
+ closed late is picked up on the next export.
+- **Late or corrected records:** re-exported in full inside the window; the
+ newest file wins on `work_order_id`.
+- **Asset register:** a second file, `cmms_assets_<YYYY-MM-DD>.csv` — `asset_id`,
+ `asset_name`, `work_center`, `cell`, `make`, `model`, `install_date` — weekly
+ is enough.
+
+---
+
+## 4 — Time configuration
+
+See `time-config.md`. Per-source zones, shift pattern, production-day boundary,
+cross-midnight attribution, planned-production-time definition, then the offset
+self-check.
+
+---
+
+## 5 — Vocabulary and report depth
+
+Short, and it changes every output the plant ever reads.
+
+> *"A couple of quick ones so my reports sound like your plant. Do you call it a
+> job, a work order, or a traveler? And is it a cell, a line, or a work center?"*
+
+Capture the plant's word for each of the six join keys and for their
+organizational units. Canonical names are in
+`../../data-consolidate/reference/join-keys.md`; the plant's words are what gets
+displayed.
+
+Where the plant's word collides with a build term, record both. **"Work order" is
+the one that always collides**, because maintenance systems call repair tickets
+work orders too.
+
+**Report depth**, one optional question:
+
+> *"When I write up an NCR or an 8D, do you want the summary first with the
+> detail behind it, or the full detail straight away?"*
+
+Recorded as `summary-first` or `full`. Deferred means `full`.
+
+---
+
+## 6 — Sites
+
+> *"Is this one plant, or several?"*
+
+If several: get the names, and ask which is the default for a run that does not
+say. Then ask groups 4, 5 and 7 per site, offering inheritance rather than
+repeating the whole interview.
+
+> *"Brantford — same vocabulary and capability as Fairview, or different? I only
+> need the differences."*
+
+---
+
+## 7 — Capability profile and machining data
+
+Feeds `customer-inquiry-intake`'s manufacturability check and bid/no-bid
+recommendation. Ask as what the plant can and cannot build, not as a spec sheet.
+
+- **Materials** routinely run, and any explicitly not run
+- **Processes** available in-house, and what goes outside
+- **Size envelope** — the largest thing that fits the machines
+- **Tolerance capability** — the tightest tolerance demonstrated, by process. Ask
+ for demonstrated, not aspirational; this number is the basis for declining work
+- **Certifications held**, with expiry dates where relevant
+
+Missing this group means bid/no-bid degrades to a constraint-free recommendation
+and must say so. That is a real loss, so it is worth the five minutes.
+
+### Machining data
+
+Feeds `quote-build`'s hours ladder when a part has no current routing. Where a
+routing export or asset register came in at Step 2 or 3, most of this is
+*confirm or correct*.
+
+> *"For quoting from drawings, I need a few shop-floor numbers. What kinds of
+> machines do you have — saws, 3-axis mills, lathes — and which work centers
+> and cells are they? Roughly how long is a typical setup on each, and how long
+> does a tool change take?"*
+
+- **Machine classes** — each class, its work centers and cell, setup hours and
+ tool-change minutes. **Ask whether each figure was measured or is a best
+ guess, and record `measured` or `assumed`.** An assumed figure is still
+ used; it is named whenever it drives a variance.
+- **Cutting data** — per material and tool class, surface speed (SFM) and chip
+ load (inch per tooth). Or the name of the plant's Fusion tool library, if
+ that is where they keep it. *"If you don't keep cutting data, that's fine —
+ hours from a drawing will be labelled as library defaults until you do."*
+ An estimator's ballpark is recorded as `assumed`, never as plant data.
+- **Variance-flag threshold** — *"How far apart can two estimates of the same
+ operation be before you want it flagged?"* Deferred means the 15% default,
+ labelled as not plant-set.
+- **Stale interval** — *"How old can a cost or an actual be before you'd stop
+ trusting it?"* In days.
+
+Fields and format: `config-profile.md`, *Machining data*.
+
+---
+
+## 8 — Standards, clauses and approved suppliers
+
+- **Which standards the plant is certified to** — ISO 9001, AS9100, IATF 16949,
+ with revision
+- **Standard quality clauses** imposed on suppliers — material certs, first
+ article inspection, PPAP submission level, right-of-access for audits
+- **Standard commercial terms** — payment, freight, packaging, liability, tooling
+ ownership
+
+- **Approved suppliers, by commodity** — bar stock, castings, black oxide,
+ heat treat. Where the ERP (NetSuite or Infor M3) is live, read the vendor list and ask only which
+ are approved for what; the ERP holds vendors, not approvals.
+
+Ask for the plant's existing standard clause list and approved supplier list as
+documents rather than reconstructing them in conversation. They exist; somebody
+in purchasing has them.
+
+---
+
+## 9 — Templates
+
+> *"Send me one real example of each and I'll work out the shape from it — no need
+> to describe them."*
+
+Five documents, each plant-specific and often customer-program-specific:
+
+| Template | Consumed by |
+|---|---|
+| NCR form | `ncr-writeup` |
+| 8D format | `root-cause-capa` |
+| Quote layout | `quote-build` |
+| Supplier RFQ package | `supplier-quote-request` |
+| Trade study memo | `trade-study-report` |
+
+**Derive the structure from a real example, never from a generic version.** A
+customer-required 8D has a contractual shape, and a plausible-looking substitute
+is worse than an admitted gap.
+
+Collect the templates whenever the user has them to hand, and let them defer
+freely — a plant that hasn't run a trade study yet has no reason to produce
+a trade study memo template on day one. Say that honestly rather than
+implying urgency.
+
+---
+
+## 10 — Commercial rates
+
+Labor rate, burden rate and margin rules are commercially sensitive; downtime
+cost per hour is derived from them and inherits the same handling. Capture
+the actual values — this group is asked for real, not as a pointer to who
+holds them. The storage rule is `../../../shared/secret-config.md`.
+
+Check the four `MFG_*` variables by name first, without printing them. Any
+that is set is recorded as *set in environment* and not asked. Ask for the
+rest:
+
+> *"Last one — and this one's sensitive. Do you have your labour rate and
+> burden rate to hand? I'll save them in the plant profile, so quotes and the
+> morning report can use them without asking again. Anyone at the plant who
+> can see this plugin's memory can read that profile, and the numbers never
+> go on a customer quote. If you'd rather keep them out of the profile
+> entirely, your IT team can set them as environment variables instead."*
+
+Then margin, in plain words — never ask anyone to write JSON:
+
+> *"What margin do you usually quote at? And is there any customer, or any
+> kind of job — prototypes, rush work — where it's different?"*
+
+Record the answer as a `default` plus `by_customer` and `by_job_type`
+overrides, in the shape of `MFG_MARGIN_RULES`. A rule that does not fit that
+shape ("depends on the job") is recorded as said and goes on the gaps list.
+
+Then downtime:
+
+> *"And a figure for what an hour of downtime costs you — that's the one that
+> makes the morning report price a stoppage in dollars rather than minutes."*
+
+Four values, not three. **Downtime cost per hour is asked, never derived.**
+Deriving it from labor and burden understates it — it omits lost contribution
+and the cost of the missed commitment — and the plant's own figure is the one
+they will defend in a production meeting. If they don't have one, that is a
+placeholder and a gaps-list row like any other.
+
+**Ask who is giving the rates** if they haven't said: *"And who should I put
+down as the source for these?"* Every confirmed rate carries that name and
+the date. Never infer the name.
+
+**Show the values once, for a check.** The approval draft carries a section
+headed *Commercial rates — internal, check these before you say yes*, with
+each rate's value. That section is the only place in the conversation the
+values are restated; the question asking for the yes, the confirmation after
+the write and everything else name the rates without their values. Written
+only on an explicit yes, as **confirmed**, with the name and the date.
+
+Sensitivity here is about **storage and audience, not secrecy from every
+consumer.** These values are usable and displayable in internal artifacts
+(`quote-build`'s cost-basis sheet, priced downtime in the morning report) —
+never in a customer-facing artifact, the readable setup summary, the config
+profile page, the gaps list, sample data, or logs. After the write, confirm by
+name ("labor rate is confirmed in the plant profile"), not by value.
+
+**Credentials are never taken this way.** If someone pastes a token,
+password or API key in the middle of this group, it is refused and never
+repeated, per `../../../shared/secret-config.md`.
+
+**Scrap costing basis is not in this group, and isn't asked as a question
+here.** It's internal-only but not confidential in the same way (it
+already sits in the ERP), so at this point in the interview — not Step
+1's reachability check, which never pulls business data — read it
+directly from the NetSuite connector if it's live: "standard cost from
+NetSuite" is a method, not a rate, and the connector is the source of
+truth for which method the plant actually uses. Infor M3 does not give
+standard cost to this plugin (`../../../shared/erp-connectors.md`), so with M3
+it is asked, like any other unconnected ERP. Where NetSuite isn't
+connected, ask for it here instead, as a plain (non-sensitive) config
+value, and record which source supplied it.
+
+Expect "I'd have to ask" throughout this group. That is a complete answer —
+record a marked placeholder with its assumption and put it on the gaps
+list, naming the rate, never its value. When the real value arrives later
+("update our labour rate"), it becomes confirmed and drops off the gaps list.
diff --git a/plugins/claude-for-manufacturing/skills/onboarding/reference/time-config.md b/plugins/claude-for-manufacturing/skills/onboarding/reference/time-config.md
new file mode 100644
index 00000000..e9aea67b
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/onboarding/reference/time-config.md
@@ -0,0 +1,137 @@
+# The time interview and the offset self-check
+
+**Cross-system timestamp alignment and shift-boundary definition are the highest
+-risk correctness issues in this build.** This is the only place they get
+established, which is why this file exists rather than three paragraphs in the
+skill body.
+
+Everything here lands in the `## Plant context` source clock table and the site
+blocks, per `config-profile.md`.
+
+---
+
+## Why it is the highest risk
+
+A misaligned timestamp is a hole that looks like a value. Nothing errors. The
+data is present, well-formed and wrong by an hour, and every downstream
+correlation inherits the error while looking perfectly reasonable.
+
+Two concrete consequences already written into the plugin:
+
+- **`root-cause-capa`** aligns sensor, inspection, production and maintenance
+ data onto one timeline around an event. If the clocks are off, it produces a
+ spurious correlation, presents it confidently, and closes an investigation on
+ the wrong cause.
+- **`daily-production-report`** computes availability against planned production
+ time. If the shift boundary is wrong, every OEE figure is wrong, and OEE is the
+ number everyone in operations knows by heart — so a wrong one destroys trust in
+ the whole report.
+
+---
+
+## Part 1 — Per-source clocks
+
+Ask this **per data source**, not once for the plant. Different systems record
+time differently and a plant person will not have thought about it, so ask
+concretely rather than abstractly.
+
+For each source in the export folder and each live connector:
+
+1. **What timezone are this system's timestamps in?** Offer the plant's local
+ zone as the likely answer, but do not assume it. Historians and cloud systems
+ are frequently UTC.
+2. **Does the timestamp carry its zone, or is it bare?** A bare local time is
+ "naive" and cannot be safely compared to anything until the zone is declared.
+ The practical test: open one file and look at whether the timestamp has an
+ offset or a zone suffix on it.
+
+Record both per source. A naive source with a declared zone is workable; a naive
+source with an undeclared zone is a blocking gap.
+
+**Do not infer a zone from a system's default setting.** That is the zone the
+account was created in, not necessarily where the data was recorded.
+
+---
+
+## Part 2 — Shift and day definition
+
+Four questions, per site. These are the ones a supervisor answers instantly and
+an engineer guesses wrong.
+
+1. **What is the shift pattern?** Two 8s, three 8s, two 12s, 4-on-4-off, or
+ something else. Get the actual clock start times, not just the count.
+2. **When does the production day start?** Often the start of first shift, not
+ midnight. This is the single most consequential answer here, because it
+ decides which day every number belongs to.
+3. **A shift that crosses midnight — which day does it belong to?** The day it
+ started, or the day it ended. There is no universal convention and both are in
+ use. Getting it wrong moves a whole shift of output to the wrong day, which
+ makes the day look bad and the next day look good.
+4. **What counts as planned production time?** Scheduled shift hours, minus what
+ — planned maintenance windows, breaks, scheduled changeovers? This is the
+ denominator of OEE availability, so its definition decides whether 62% is a
+ maintenance problem or a definitional artifact.
+
+Where the plant runs more than one site, ask per site. Do not carry one site's
+answers to another silently; `config-profile.md` explains the inheritance rule.
+
+---
+
+## Part 3 — The offset self-check
+
+**This is the point of the whole interview.** A declared configuration is a
+claim. This step tests it against the data.
+
+The procedure:
+
+1. **Find one event recorded in two systems.** A production work order with a
+ completion timestamp in the ERP and in the MES export. A downtime event in
+ both the maintenance record and the historian window. A shipment in the ERP and
+ the planning export.
+2. **Convert both timestamps into a single zone** using the declarations from
+ Part 1.
+3. **Compare them.** They should agree to within the systems' own recording
+ granularity.
+4. **Report the observed skew**, whether or not it is zero. A zero result is a
+ confirmed configuration, which is worth saying out loud.
+
+### Reading the result
+
+| Observed | What it means | What to do |
+|---|---|---|
+| Zero, or within recording granularity | The declared config is consistent with the data | Record it as checked, with the date |
+| A whole-hour offset | A timezone declaration is wrong, or a naive source was assigned the wrong zone | Re-ask Part 1 for the source in question |
+| A whole-hour offset that matches a DST transition | A source is recording standard time year-round, or converting inconsistently | Record the skew and flag it; this one recurs twice a year |
+| Minutes, not hours | Genuine clock drift on a machine or server | Report it to the plant's IT. This is a real finding |
+| Cannot be tested — no shared event | The config is declared but unverified | Record as unverified and put it on the gaps list |
+
+### When the user insists the config is right
+
+**Report the skew; do not override it.** The observed data is evidence and the
+declaration is a claim. A real clock drift is worth surfacing to their IT, and
+overriding the measurement to match the assertion throws away the only signal
+there is.
+
+Say it plainly and without argument:
+
+> *"Your MES export reads one hour ahead of NetSuite on the same work order
+> completion. I've recorded both declarations as you gave them and flagged the
+> skew, so anything that correlates these two sources will say the alignment is
+> unverified. Worth having IT check the MES server clock."*
+
+---
+
+## What blocks and what defers
+
+Consistent with the skill's rule that setup never blocks:
+
+- **Deferrable:** an untested offset, a missing planned-production-time
+ definition, a second site's shift pattern. All go on the gaps list with the
+ affected skills named.
+- **Effectively blocking downstream, not here:** a naive source with no declared
+ zone. Setup completes, but per `../../../shared/absent-is-not-zero.md` any skill
+ asked to correlate that source refuses and reports the alignment gap instead of
+ producing a correlation nobody can trust.
+
+The distinction matters. Onboarding does not stop. The skill that would produce a
+wrong answer does.
diff --git a/plugins/claude-for-manufacturing/skills/quote-build/SKILL.md b/plugins/claude-for-manufacturing/skills/quote-build/SKILL.md
new file mode 100644
index 00000000..206cd622
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/quote-build/SKILL.md
@@ -0,0 +1,490 @@
+---
+name: quote-build
+description: "Produces the make-to-order quote from the intake form, comparable prior jobs and cost history, with every number traced to where it came from — material at the price actually paid on a named purchase order, machine hours per operation from a labelled ladder (current routing, closed-job actuals, the confirmed design, first principles) with setup and run kept apart, setup re-amortized at each quantity break, and margin on its own line. Checks the promised date against real shop load before committing to it. Revises in place when a customer counters, preserving what changed and why. Use when someone says \"build the quote,\" \"price this job,\" \"what should we charge,\" \"quote this RFQ,\" or \"the customer came back on price.\""
+compatibility: "Requires none. Reads NetSuite or Infor M3 (or any ERP mapped into the dataset) for standard cost, actual cost on closed work orders and purchase prices, Microsoft 365 for prior quotes and templates, a planning export for shop load, and Autodesk Fusion for CAM-derived hours where connected. Runs on the intake form and pasted cost figures with no connector. Reads rates from an MFG_* variable or the plant profile, never asking each run. The quote uses the plant's own template."
+---
+
+# Quote Build
+
+Pricing a make-to-order job means building up a cost and then applying
+commercial judgment. Every job is priced fresh, which is why quoting is skilled,
+slow, expert work — and why the estimator is usually the bottleneck.
+
+**The cost basis is shown, always.** A quote that says *$14,720* is useless. One
+that says *$14,720, of which $6,100 is material at the price we paid on PO-8841
+in June, plus 8% scrap* is defensible.
+
+**Quick start**
+
+```
+→ Load the intake form. Lines with no quantity or no material are skipped; quote the rest and list what's blocked
+→ Find comparables; show what made each one comparable AND how this job differs
+→ Flag capability BEFORE pricing. Then hours per op from the ladder: routing → actuals → confirmed design → first principles
+→ Setup and run separate at every rung. A superseded routing is shown, never priced. probable_standard never outranks rung 3
+→ Build up the cost: material, labor, machine, setup, outside processing, tooling
+→ Resolve rates: MFG_* variable, then the plant profile. Never asked in the run, never invented
+→ Re-amortize setup at every quantity break
+→ Margin on its own line. Never buried
+→ Check the promised date against real shop load. Never quote a date blind
+→ Assemble the customer quote AND the internal cost-basis sheet. No hours, ranges, rates, paths or basis labels in the customer's
+→ On a counter: revise in place with a change record. Never a second quote, never reopen CAD
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| The intake form | `customer-inquiry-intake` | `../../shared/contracts/intake-form.md` |
+| Consolidated dataset, including `routings` and `operation_actuals` (v4) | `data-consolidate` | `../../shared/contracts/consolidated-dataset.md` |
+| Geometry estimate, per line | `rfq-to-quote` step 7, or typed by the estimator | `../../shared/contracts/geometry-estimate.md` |
+| Machine classes, cutting data, variance threshold | `### Machining data` in the `## Plant context` block | Config |
+| Standard cost and item master | The ERP (NetSuite or Infor M3), each cost read from the field the profile's cost map names (`../onboarding/reference/erp-scope.md`); a field equal to the sell price is never a cost. Infor M3 gives no standard cost: last purchase price first, per `../../shared/erp-connectors.md` | Connector |
+| Actual cost on prior jobs | `production_work_orders` actual-cost columns in the dataset (v6): NetSuite closed work orders, Infor M3 work order operations, or any ERP `custom-connector` mapped | Dataset |
+| Recent material purchase prices | ERP purchase orders | Connector |
+| Awarded supplier bid for an outside process, with its selection record | `supplier-quote-request`, when this quote started the sourcing event | `../../shared/contracts/supplier-bid.md` |
+| Prior quotes for this customer or part | M365 documents, NetSuite. Infor M3: documents only | Documents and connector |
+| Labor, burden and margin rates | `MFG_*` variable, else the plant profile — see below | Config |
+| Shop schedule and load | Planning export to the M365 folder | CSV/XLSX |
+
+**Rates are resolved, not asked for each run**, in the order
+`../../shared/secret-config.md`, *Resolving a rate*, sets, and no other:
+
+1. `MFG_LABOR_RATE`, `MFG_BURDEN_RATE`, `MFG_MARGIN_RULES`, checked by name,
+ never printed. These win; a stored value for the same rate is **never
+ printed anywhere**, only named as also held.
+2. A **confirmed** rate in the `## Plant rates` file at `rates_path` (an older
+ profile: its `### Commercial rates`). Price on it with no label.
+3. A **placeholder** in the same place. Price on it and label it, below.
+4. Nothing. **Block the lines it feeds**, named; the rest is still produced.
+
+Shown on the internal cost-basis sheet, never on the customer-facing quote.
+
+**A rate typed into this run is not used**: say it is not on file, do not
+repeat the number, and offer `onboarding`'s "update our labour rate", which
+saves it with a name and date for every quote after this one.
+
+---
+
+## Workflow
+
+### Step 1 — Load the intake form
+
+**Refuse to proceed on line items with no quantity or no material.** Quote the
+rest and list what is blocked and why.
+
+A 40-line RFQ with one underspecified item produces 39 prices and one question,
+not silence.
+
+**Read the commercial terms** — payment, freight, packaging, liability. Where
+the intake form states one, carry it into the quote as given. Where one is
+null, quote against the plant's standard for that term, name the assumption on
+the exclusions list, and keep the missing-register row — do not fill it in
+silently. Where `customer-inquiry-intake` flagged a stated term as clashing
+with the plant's standard, carry that flag onto the exclusions list too; it
+does not resolve itself by arriving here.
+
+**Block on missing provenance.** Where `field_sources` is absent from the
+intake form, block — without provenance the estimator cannot verify a number
+against the package, and a quote built on an unsourced field is a quote no
+one can defend.
+
+**Where `quantities` has only one entry but the customer's ambiguous register
+shows breaks were requested**, quote what is there and state plainly that the
+breaks were not captured — never invent the missing quantity points.
+
+**Where `ambiguous_register` carries an entry on a field the quote depends
+on**, quote against one value, name which, and state the other explicitly
+rather than silently picking one — the same discipline the intake form itself
+applies to a customer's conflicting statements.
+
+**Where `recommendation` is `no_bid`**, it is a recommendation, not a
+decision. Proceed only if the estimator says to, and say so in the quote's
+assumptions when you do.
+
+**Check `bid_decision_state`, and each line's `line_bid_decision`, never context.**
+`declined` blocks the inquiry, or that line, listed as not quoted by the
+estimator's decision; reopening is a new decision. `draft`, or a set
+`bid_decision_reset`, means no ruling covers it: quote only if told to in the
+run, and record on the quote that it proceeded on an unconfirmed recommendation.
+
+**`inquiry_state` is a different axis, and reading it as a decision is the
+error to avoid.** `superseded` blocks — a later revision exists, quote that one.
+`stale` does **not** block and never means declined: it means the customer went
+quiet on open questions. Quote with exclusions naming those questions, or do not
+quote — but never treat the silence as a no.
+
+**Where `recommendation_provisional` is true**, answers were still outstanding
+when this was scored. Quote if the estimator says to, and carry the outstanding
+questions onto the assumptions list — they are precisely what the price rests
+on. Where `hard_disqualifier_stopped` is true, the plant cannot build this as
+specified: quote only on an explicit override, with the disqualifying constraint
+on the exclusions list.
+
+**Read the geometry estimate's `approval.status` the same way.** `confirmed`
+means the estimator passed Gate 3 on this model, tolerance reading and
+operation list. **`draft` is unconfirmed: no hours derived from it reach a
+quote** unless the estimator says so in this run — then the internal sheet
+records who said so and that the model was unconfirmed. A
+`drawing_revision_priced_to` that differs from the intake line's `revision`
+blocks: that estimate is another part.
+
+### Step 2 — Find comparables
+
+Prior jobs for the same part number first, then similar parts by material,
+process and size.
+
+**Show what made each one comparable and how the new job differs.** Same part,
+half the quantity, different finish, eighteen months of material inflation — the
+estimator needs those differences to weigh the comparable at all.
+
+Where no comparable exists, say so clearly and **do not produce a confident
+number off nothing.**
+
+**Count the history in code.** How many orders, how many for this customer,
+how many closed work orders, across what dates — each is a filter run over the
+data, and each goes in the figures block (`../../shared/computed-figures.md`)
+with that filter. "Consistent across five orders" written from memory misses
+the sixth, and the one missed tends to be the customer's own.
+
+### Step 3 — Flag capability, then derive the hours
+
+**Capability flags come before any price.** Carry the intake form's
+`constraint_violations`, and check every tolerance on the geometry estimate
+against demonstrated capability in the Plant context: **a tolerance tighter
+than the plant has demonstrated on that process is flagged by name, value and
+capability**, on the internal sheet and, as a plain statement of what is
+quoted, in the assumptions. Pricing it first and flagging it after is how a
+plant commits to a tolerance it has never held.
+
+**Then hours per operation, from the ladder.** Read `reference/hours-ladder.md`
+before deriving any hour. Per operation, best available first:
+
+1. **A routing for this part and revision**, cited. A routing for another
+ revision is superseded — shown as such, never priced from.
+2. **Closed-job actuals** not flagged `probable_standard`.
+3. **Geometry-derived** from the confirmed estimate: the CAM path where Fusion
+ and plant cutting data exist, the feature path always.
+4. **First principles**, naming what would firm it up.
+
+**`probable_standard` actuals never outrank rung 3.** **Library feeds
+(`fusion_default`) are rung 4, labelled "library defaults, not plant data."**
+Setup and run are carried separately at every rung. Where two rungs exist the
+variance is computed in code and flagged above the Plant context threshold —
+or 15%, printed word for word as *"default threshold, not plant-set"* — with its drivers
+named. Every hour, range and variance goes to the figures block.
+
+### Step 4 — Build up the cost
+
+Material with its scrap allowance, labor, machine and burden, setup, outside
+processing, tooling.
+
+**Each line cites its source** — standard cost, an actual purchase price with
+its PO and date, or the actual cost from a specific prior work order. Labor,
+machine and setup use the hours from Step 3, rung by rung, never a single
+hours rule for the whole job. Read `reference/cost-buildup.md`.
+
+Where a required rate is not supplied, build to that point and **name exactly
+which rate is missing and which lines it blocks.** Never substitute a plausible
+one.
+
+**No job-quantity total and no unit price for this job may appear while a
+required rate is unset — not from standard cost, not from price history, not
+as a ballpark.** Every route to a number is closed, including the ones that
+look like something else:
+
+- *Standard cost × quantity* is a price by another name. Standard cost may be
+ cited as a material basis per unit, labelled standard; it is never extended
+ by the job quantity into a total while labor or burden is blocked.
+- *A prior sell price × quantity* is a price too. Prior sales may be listed as
+ history — order, date, quantity, price, one line each — and are never
+ multiplied by the requested quantity, never headed "unit price," never
+ offered as a guide to this job.
+- *"Just a ballpark"* and *"use a typical shop rate"* get the same answer.
+ Decline the typical rate without naming one, and do not then produce the
+ ballpark some other way.
+
+**A placeholder is a rate, and prices the job.** Where the `## Plant context`
+block carries a rate as a marked placeholder with its assumption — recorded by
+the plant at onboarding, not invented here — build on it. Label every line it
+touches, and the cost sheet as a whole, **"placeholder rate — not confirmed"**,
+and put the placeholder on the assumptions list by name. The gaps list names it,
+never its value. This state, "quote-build is
+running on a placeholder," is expected. What is still refused is any
+rate the model supplies itself, from a benchmark or a lookup.
+
+**A confirmed rate prices the same way, without the label.** A rate the
+rates file records as confirmed — given by a named person on a
+date and approved at onboarding — is the plant's number, as much as one set in
+`MFG_*`. Cite it on the internal sheet as *plant profile, confirmed by <name>
+on <date>*, and leave it off the assumptions and gaps lists.
+
+**Still produce everything the rates do not touch:** material at the price
+actually paid on a named PO with its date; the setup amortization structure at
+each quantity, with the dollar values blocked; outside processing and tooling
+where sourced; and the date check against shop load. Name each missing rate
+and both ways to set it — *"update our labour rate"* to record it on the
+plant's rates page, or `MFG_LABOR_RATE` / `MFG_BURDEN_RATE` in the environment — say which
+lines each blocks, and say the quote completes as soon as they are set.
+
+### Step 5 — Apply quantity breaks
+
+**Recompute setup amortization at each quantity the customer asked for.** Setup
+does not scale — it is the same cost across more units, and that is the entire
+reason unit price drops with volume.
+
+Show the setup contribution per unit at each break so the spread is explicable.
+
+**Setup and run stay separate at every break, at every rung.** Where a source
+gives only a lumped total, the split is unknown: say so, and **never
+re-amortize it** — use the highest rung that carries a split for the break
+arithmetic.
+
+### Step 6 — Apply margin
+
+Per the configured rules, **shown as its own line and never buried.**
+An estimator negotiating needs to see exactly how much room they have.
+
+### Step 7 — Check the promised date against shop load
+
+Read the planning export and answer whether the requested date is achievable
+given what is already committed, plus material and outside-processing lead time.
+**The work content is setup plus run hours by work center from each
+operation's winning rung, and the check names that basis.**
+
+**If it cannot be met, say so and give the earliest date that can.** Quoting a
+date the shop cannot hit is how a plant loses a customer twice.
+
+Without a planning export, the quote carries a stated lead time with an explicit
+**"not checked against shop load"** caveat — never a silent omission. Read
+`reference/date-and-load.md`.
+
+### Step 8 — Assemble both documents
+
+The **customer-facing quote** in the plant's template, and the **internal
+cost-basis sheet** the estimator keeps and defends.
+
+**Emit the customer quote between delimiters, and keep everything internal
+outside them:**
+
+```
+=== CUSTOMER QUOTE — SENDABLE ===
+…the quote, and only the quote…
+=== END ===
+```
+
+The cost-basis sheet is its own delimited document, so both are explicit and
+neither can be mistaken for the other:
+
+```
+=== INTERNAL COST SHEET — NOT FOR CUSTOMER ===
+…the buildup, every source, each rate against its source, the
+hours per operation with rung, path, cutting data basis, setup and run,
+range, variance and drivers, the comparables, the margin line, the
+figures block…
+=== END ===
+```
+
+Notes to the estimator that belong to neither document go outside both
+blocks. Narrative cost prose with no delimiter is not a cost sheet. **An assumption that
+reveals pricing policy is internal**: "no customer was named, so the default
+margin rule applies; a different rule is configured for another customer" is
+useful to the estimator and must never sit inside the quote. On the internal
+sheet, show each rate's value against its source — `MFG_LABOR_RATE`, *plant
+profile, confirmed by <name> on <date>*, or *plant profile, placeholder* —
+that is what makes the basis defensible.
+
+**The customer quote states what was quoted, not how it was estimated.** Its
+assumptions name the **drawing revision priced to** and the **tolerances as
+read** — *"priced to PN-4471-B Rev 2; unspecified tolerances ±0.005 in per the
+drawing's general note"* — and any capability flag as a statement of scope.
+
+**Then read the block alone, and reject it if it holds** any hours figure —
+setup, run, cycle or machine time, per piece or per job — any low, expected or
+high range, any rung, path or source of an hour (routing, actuals, CAM, feature
+path, geometry estimate, first principles), any cutting-data basis label
+(`plant_library`, `estimator_entered`, `fusion_default`, library defaults), any
+variance, `probable_standard`, or anything from `cost_down_proposals`;
+any rate value —
+from an `MFG_*` variable or the plant profile, or a figure that is one times
+something —
+the word "margin" **in any form — "margin applied," "standard margin," "at our
+usual margin," a margin percentage, or a line item called margin** — any
+description of which pricing rule was used, or any customer's name but the
+addressee's. The customer sees prices; how they were arrived at is the
+internal sheet's business. A rejected block is rewritten before anything is
+sent, not annotated. The full list is
+`../../shared/secret-config.md`, *The outbound document check*.
+
+### Step 9 — Handle the negotiation loop
+
+When a customer counters, **revise the existing quote in place and preserve a
+change record** of what moved and why.
+
+A counter is not a new quote. Treating it as one is how a plant ends up with
+four versions in circulation and no record of what was conceded. Re-derive the
+affected lines rather than patching the total, and where a price dropped with no
+scope change, **say that margin moved.** Re-derive from the stored operation
+record — **a price counter never reopens CAD.** A new drawing revision is not a
+counter: it goes back to `rfq-to-quote` step 7. Read `reference/revisions.md`.
+
+---
+
+## Approval gates
+
+**Nothing reaches a customer without the estimator releasing it.** This is
+Chain 1's **fourth** gate, at step 11. Gate 1 is the estimator sending the
+open questions at step 4; Gate 2 is confirming the bid/no-bid at step 5; Gate 3
+is confirming the design, tolerance reading and operation list at step 8 — no
+geometry-derived hour is priced without it or a recorded override. The quote
+is drafted, shown with its cost basis, and sent by a person.
+
+**Every revision goes through the same gate.** A second version of an approved
+quote is not pre-approved.
+
+**Rates are resolved per `../../shared/secret-config.md` and shown only where
+the audience rule allows.** Nothing is written back to the ERP; the quote is a document the
+estimator files and sends. The margin line appears on the internal
+cost-basis sheet, never on the customer-facing quote.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The customer-facing quote** — line items, prices, quantity breaks, lead time,
+validity period, terms (payment, freight, packaging, liability — as the
+customer stated them, or the plant's standard where one was never stated), and
+the assumptions and exclusions list.
+
+Per `../../shared/artifact-style.md`, a quote is a controlled document and uses
+the plant's own template captured during `onboarding`, **never the house style.**
+
+**The internal cost-basis sheet** — the full buildup with every source cited,
+the comparables used and how they differ, the margin applied, and every
+assumption made. The estimator hands this to their manager and defends the price
+without re-deriving it. **It carries the figures block** — every count of
+orders, lines and comparables, and every extended figure, with the filter or
+arithmetic behind it. Internal only; it never appears in the customer quote.
+
+**The hours-basis table, on the internal sheet** — per operation: rung, path,
+cutting-data basis, setup and run with their range, every other rung with its
+variance, the variance drivers, and the toolpath check where the CAM path ran.
+Any `cost_down_proposals` from the geometry estimate sit here, internal only.
+
+**The operation record** — kept with the quote, so a counter re-prices without
+reopening anything and the estimate can one day be compared with the job's
+actuals. Its fields are in `reference/hours-ladder.md`.
+
+**The assumptions and exclusions list** — explicit, including any commercial
+term quoted against the plant's standard because the customer never stated one,
+or flagged because a stated one clashed with the plant's. This is what protects
+the plant when the customer's expectations diverge later, and it is the section
+everyone skips.
+
+**Revision history** — when revising, with what changed and why.
+
+**The Sales command-center page** — Chain 1's closing step. Commercial
+performance for the period, carrying the intake record and the quote by
+reference so the page reads from what was actually sent rather than a separate
+summary of it. Produced as an artifact you place; nothing is written to a
+system. The customer-facing version carries no margin line. Read
+`../../shared/command-center.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **No comparable exists** — a genuinely new part. Say so; do not produce a
+ confident number off nothing.
+- **Material price is volatile** — cite the price as of its date and add a
+ validity caveat to the quote.
+- **The requested date is impossible** — never quietly quote a date the shop
+ cannot hit.
+- **A quantity far outside anything the plant has run** — flag the extrapolation
+ explicitly. A price at 50,000 derived from experience at 500 is not a quote.
+- **Currency or unit mismatches between the RFQ and our cost data** — surface
+ them rather than converting silently.
+- **A required rate was not supplied** — name which one and which lines it
+ blocks. Never invent it, and produce no total and no unit price for the job
+ by any other route — see Step 4.
+- **The cost history is stale** — cite each figure as of the date its work order
+ closed. A comparable priced in a different material market is still useful,
+ but only if its age is visible.
+- **A spec on the intake form has no source reference** — block that spec. An
+ unsourced tolerance is an inference, and inferences get priced and then
+ committed to contractually.
+- **A commercial term (payment, freight, packaging, liability) was never
+ stated** — quote against the plant's standard for that term and name the
+ assumption on the exclusions list. Never fill it in silently.
+- **The only routing is for an earlier revision** — superseded. Show it as
+ such; derive from the next rung. Never price the new revision on it.
+- **Actuals agree to within 1%** — `probable_standard`. Shown, never above a
+ geometry-derived estimate.
+- **The geometry estimate is still `draft`** — no hours from it reach a quote
+ without the estimator's say-so in the run, recorded on the internal sheet.
+- **A Plant context value is tagged `assumed`** — use it, label it, and name it
+ as a variance driver where it explains more of a gap than the threshold.
+
+---
+
+## Degradation
+
+Runs on the intake form plus pasted cost figures with no connector at all.
+
+| Not available | What happens |
+|---|---|
+| The ERP (NetSuite or Infor M3) | No standard cost, actual cost or purchase-price history. Ask for material prices and rates directly, and label the whole buildup as supplied rather than sourced |
+| Closed-work-order cost | Build up from standard cost, labelled **"standard cost (3rd preference, no actual-cost comparable)"** — standard cost does not say whether the last job made money |
+| The intake form | Treat the request as a minimal intake: part and quantity as the user stated them, every other field null and on the missing register. Build from the best basis available and label it. A recorded placeholder rate counts as a set rate |
+| Purchase-order history | Price material from a current supplier quote or a supplied figure, with its date |
+| Planning export | Quote a stated lead time with the explicit "not checked against shop load" caveat |
+| Prior quotes | No precedent for this customer. State it rather than reading absence as a new relationship |
+| The plant's quote template | Use a neutral quote structure covering every section above, and flag that the controlled template was unavailable |
+| Routings and actuals | The ladder starts at rung 3, or rung 4 where there is no confirmed geometry estimate. Name both tabs missing |
+| Geometry estimate | No rung 3 for that line. Say the design step did not run and why; the ladder runs on what exists |
+| A drawing (path A, text specs only) | **A ROM, never a firm quote**: ROM on the internal sheet, a budgetary estimate on the customer document, nothing about method. An override does not make it firm. `reference/hours-ladder.md`, *Path A* |
+| Fusion, or its Manufacturing workspace | Feature path only, and the internal sheet says so. No toolpath check is claimed |
+| Plant cutting data | The CAM path runs on library feeds, labelled `fusion_default`, rung 4. The feature path cannot time a cut; that op is rung 4 |
+| Machining data in the Plant context | No plant setup or tool-change values, no cell map, and a variance threshold of 15% printed as "default threshold, not plant-set" |
+
+---
+
+## Chain position
+
+**Chain 1, RFQ to quote** — the final step, depending on `customer-inquiry-intake`
+and `data-consolidate` as two independent inputs, not a pipe from one through
+the other.
+
+Both this step and the intake's bid/no-bid depend on cost history. **If the ERP
+is not connected, both degrade to document-based comparables and the chain says
+so** rather than quietly producing weaker output.
+
+**Metric.** Quote turnaround; hit rate; the unbid book.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/hours-ladder.md` | Step 3 — always, before any hour: the ladder, setup and run, ranges, variance, the CAM and feature paths, the per-op sheet columns and the operation record |
+| `reference/cost-buildup.md` | Steps 2 to 6 — the seven lines, their sources, comparables, and quantity breaks |
+| `reference/date-and-load.md` | Step 7 — the load check, its scope boundary, and the caveat when it cannot run |
+| `reference/revisions.md` | Step 9 — the change record, re-deriving from the operation record, and why a new drawing revision is not a counter |
+| `../../shared/contracts/geometry-estimate.md` | Steps 1 and 3 — the geometry estimate, its approval state and what blocks it |
+| `../../shared/computed-figures.md` | Steps 2 and 7 — the figures block every stated count is quoted from |
+| `../../shared/contracts/intake-form.md` | Step 1 — the intake shape, a line with no quantity or no material, the missing behavior for a null commercial term, an ambiguous register entry, uncaptured quantity breaks, a `no_bid` recommendation, the `bid_decision_state` gate, and absent `field_sources` |
diff --git a/plugins/claude-for-manufacturing/skills/quote-build/reference/cost-buildup.md b/plugins/claude-for-manufacturing/skills/quote-build/reference/cost-buildup.md
new file mode 100644
index 00000000..422548f1
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/quote-build/reference/cost-buildup.md
@@ -0,0 +1,192 @@
+# The cost buildup
+
+**"Cost basis shown" is the whole point of this skill.**
+
+An estimator will not trust — and cannot defend to a customer — a number with no
+derivation. A quote that says *$14,720* is useless. One that says *$14,720, of
+which $6,100 is material at the price we paid on PO-8841 in June, plus 8% scrap
+allowance* is usable, defensible, and can be handed to a manager without
+re-deriving it.
+
+So every line carries **its source and its assumption.**
+
+---
+
+## The seven lines
+
+### Material
+
+Quantity × price, **plus a scrap allowance** — you buy more than the finished
+part needs, because some is cut away or ruined.
+
+Cite the price to one of three things, in order of preference:
+
+1. **An actual purchase price with its PO number and date.** The best basis
+ available, and the only one that reflects what this plant actually pays.
+2. **A current supplier quote**, with its validity period.
+3. **Standard cost**, clearly labelled as standard, and labelled with its
+ place in this list: **"standard cost (3rd preference, no actual-cost
+ comparable)"**, with the reminder that standard cost does not say whether
+ the last job of this kind made money.
+
+**No intake form is not a reason to build nothing.** "Price 250 of PN-4402-A"
+in conversation is a minimal intake: part and quantity stated by the user,
+everything else null and on the missing register. Build from the highest
+preference available, which with standard cost only is the third, and label
+it as such. A buildup with a labelled weaker basis is what the estimator
+asked for; stopping on the missing form hands back nothing.
+
+**Always state the date of the price used.** Material markets move, and a
+quote built on a price as of eight months ago is a different number from one
+built last week. Where the price is volatile, say so and add a validity caveat
+to the quote.
+
+### Labor
+
+For each operation: **setup hours plus run hours at this quantity**, × the
+labor rate.
+
+The hours come from the ladder in `hours-ladder.md`, one rung per operation,
+never a single rule for the whole job: a current-revision routing, cited; else
+recorded closed-job actuals; else hours derived from the confirmed geometry
+estimate; else first principles, naming what would firm them up. The rung, the
+path and the cutting-data basis go on the internal sheet beside the line.
+
+A routing for a superseded revision is not an estimate of anything. It is
+shown as superseded and never priced from.
+
+### Machine and burden
+
+Machine time × a rate covering the machine's cost of ownership. Same rule: the
+rate cites its source, and the time cites its rung — the same setup and run
+hours the labor line used, never a second estimate of them.
+
+### Setup
+
+**The one-time cost of preparing a machine for the job, amortized across the
+quantity.**
+
+This is the single most important line for understanding a make-to-order quote,
+because it is why unit price drops sharply with volume and why quantity breaks
+exist at all. Show setup as a total *and* as its per-unit contribution at each
+quantity — those two numbers together explain the entire shape of the price
+curve to a customer who asks.
+
+**Setup and run are carried separately at every rung.** A source that only gives
+a lumped total has an unknown split: say so, and never re-amortize it across a
+different quantity — use the highest rung that carries a split for the break
+arithmetic, and show the lumped figure beside it at the quantity it came from.
+
+### Outside processing
+
+Heat treat, plating, coating done by a vendor. Cite the vendor price and its
+date, and note the lead time it adds — outside processing is frequently the
+constraint on the promised date rather than the machining.
+
+**Where `supplier-quote-request` ran a sourcing event for this line and the
+buyer recorded a decision**, the line is *sourced*: price it from the awarded
+break in the selection record (`../../../shared/contracts/supplier-bid.md`)
+and cite supplier, `bid_ref`, bid date, `decided_by` and `decided_at` on the
+internal sheet. Its production lead time goes into the date check. A quantity
+no awarded break covers is named, never interpolated; an MOQ above the quote
+quantity or an expired validity is flagged on the line. A bid with no
+selection record is cited as *a supplier quote, not awarded*. The supplier's
+name and price stay off the customer quote.
+
+### Tooling
+
+Fixtures or dies. Often charged separately as NRE — non-recurring engineering —
+rather than amortized.
+
+**Whether tooling is amortized or charged separately changes the comparison
+entirely**, so state which, and state who owns the tooling at the end.
+
+### Margin
+
+Applied on top, per the configured rules, **and always shown as its own line.**
+
+**Never bury margin inside another line.** An estimator negotiating with a
+customer needs to know exactly how much room they have, and a margin folded into
+the material line is invisible to them and to their manager.
+
+---
+
+## Rates are resolved, not asked for each run
+
+Labor, burden and margin rates are commercially sensitive, but `onboarding`
+captures the actual values, not a pointer to who holds them. This skill
+resolves each one in the order `../../../shared/secret-config.md`, *Resolving
+a rate*, sets: the `MFG_*` variable if it is set, then a confirmed rate in the
+plant profile, then a placeholder there, then nothing — and nothing blocks
+the line.
+
+Sensitivity here is about storage and audience, not secrecy from this
+skill: the burden rate is multiplied by hours and shown on the internal
+cost-basis sheet, because that's the whole point of a cost basis the
+estimator can defend. It never appears on the customer-facing quote, and
+it's never restated back conversationally unprompted — confirmed by name,
+not value, if it needs mentioning at all.
+
+Where a rate is a **marked placeholder** — recorded at onboarding with its
+assumption because the person answering did not know — price on it, and label
+every line it touches and the sheet "placeholder rate — not confirmed". The
+plant supplied it and has seen it; it is their number until the real one
+arrives.
+
+Where a rate genuinely isn't on file at all (no variable, nothing confirmed and
+no placeholder in the profile), **do not substitute a plausible one.**
+Produce the buildup to the point the rate is needed and say exactly which
+rate is missing and which lines it blocks. A quote built on an invented
+burden rate is wrong in a way nobody will catch until the job runs.
+
+**While a required rate is unset, no job-quantity total and no unit price for
+this job appears — not from standard cost, not from price history.** Standard
+cost times the quantity, and last year's sell price times the quantity, are
+both a price arrived at by a side door, and once either is on the page it is
+the number that gets quoted. Prior sales are listed as history, one order per
+line, and are never extended by the requested quantity or headed "unit price."
+A request for "just a ballpark" is declined the same way.
+
+---
+
+## Quantity breaks
+
+**Recompute setup amortization at each quantity the customer asked for.** This
+is the most common arithmetic error in hand-built quotes and the easiest to get
+right mechanically.
+
+Material scales roughly linearly. Labor scales with quantity but often improves
+with a learning curve. **Setup does not scale at all** — it is the same cost
+divided by more units.
+
+Show the per-unit price at each break with the setup contribution visible, so
+the customer can see why 1,000 is cheaper per piece than 100 and the estimator
+can defend the spread.
+
+Where the customer asked for a quantity **far outside anything the plant has
+run**, flag the extrapolation explicitly. A price at 50,000 derived from
+experience at 500 is an extrapolation, not a quote, and saying so protects
+everyone.
+
+---
+
+## Comparables
+
+The fastest sanity check an estimator has: *we made something like this last
+year for $X.*
+
+Search in order: **the same part number**, then similar parts by material,
+process and size.
+
+For each comparable, show **what made it comparable and how the new job
+differs.** A comparable presented without its differences is misleading —
+same part, half the quantity, different finish, and a material market eighteen
+months older is not the same job, and the estimator needs those four facts to
+weigh it.
+
+**Where no comparable exists — a genuinely new part — say so clearly and do not
+produce a confident number off nothing.** That is what the ladder is for: hours
+from the confirmed geometry estimate where there is one (rung 3), and first
+principles only where there is nothing better (rung 4). Either way each
+operation is labelled with its rung and names what would firm it up, and the
+setup and run split is kept.
diff --git a/plugins/claude-for-manufacturing/skills/quote-build/reference/date-and-load.md b/plugins/claude-for-manufacturing/skills/quote-build/reference/date-and-load.md
new file mode 100644
index 00000000..20552866
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/quote-build/reference/date-and-load.md
@@ -0,0 +1,92 @@
+# Checking the promised date against the shop
+
+**Quoting a date the shop cannot hit is how a plant loses a customer twice** —
+once when the job is late, and again when they remember it during the next RFQ.
+
+A price that is right and a date that is wrong is a bad quote. The date is
+frequently the thing the customer actually cares about.
+
+---
+
+## What the check does
+
+Read the planning or schedule export and answer one question: **given what is
+already committed, can this job be delivered by the requested date?**
+
+Work through, in order:
+
+1. **The work content this job adds** — setup plus run hours by work centre,
+ from each operation's winning rung on the ladder (`hours-ladder.md`), with
+ that basis named: *"Cell B: 31.4 h, rung 2, closed-job actuals"*. A load
+ check built on first-principles hours says so. Work centres come from the
+ routing, or from the machine class to work centre map in the Plant context
+ for a geometry-derived operation.
+2. **What is already loaded** on those work centres between now and the
+ requested date.
+3. **Material lead time**, which frequently dominates. A four-week steel lead
+ time makes a three-week delivery impossible regardless of what the machines
+ are doing.
+4. **Outside processing lead time**, which is easy to forget and often the real
+ constraint — black oxide at five working days a lot is a week the machines
+ cannot recover.
+5. **Whether the requested date survives all four.**
+
+---
+
+## What to report
+
+**If the date can be met**, say so and say what it depends on — usually material
+arriving and the current load holding.
+
+**If it cannot, say so, and give the earliest date that can.** A quote that
+silently promises an impossible date is the failure this step exists to prevent;
+one that offers a realistic alternative is a commercial conversation the
+estimator can actually have.
+
+> *"The requested 3 November is not achievable. Cell B is loaded to 92% through
+> late October on committed work, and the 6061-T6 is on a four-week lead time
+> against an order that has not been placed. The earliest defensible date is 21
+> November, assuming material is ordered this week. If 3 November is firm, the
+> conversation is about what gets displaced — worth flagging to scheduling
+> before this goes out."*
+
+**Name what was checked and what was not.** A load check that looked at machine
+hours but could not see labour availability should say so. That is the
+difference between a caveat the estimator can weigh and a promise they cannot.
+
+---
+
+## This is not finite-capacity scheduling
+
+The same boundary `daily-production-report` holds for reschedule proposals
+applies here, for the same reason.
+
+**Producing an optimal shop schedule is a constraint-optimisation problem, and a
+language model asked to do it will return a plausible-looking answer that
+quietly violates constraints** — which is worse than returning nothing, because
+it looks authoritative.
+
+What is in scope is a **load check with its reasoning shown**: here is the work
+this adds, here is what is already committed on those work centres, here is
+where it does not fit. Not a re-optimised shop calendar.
+
+---
+
+## Degradation — and it must not be silent
+
+**Without a planning or schedule export**, the quote carries a stated lead time
+with an explicit caveat:
+
+> *"Lead time quoted at 8 weeks from receipt of order, based on the routing and
+> normal material lead time. **This has not been checked against current shop
+> load** — no schedule export was available. Confirm with scheduling before
+> release."*
+
+**Never a silent omission.** A quote with no date caveat reads as a date that
+was checked, and that is precisely the wrong impression to leave with an
+estimator about to commit to a customer.
+
+Where the export exists but is stale, state the load **as of** its last refresh
+rather than as current. A load picture from three weeks ago has missed
+everything booked since, and per `../../../shared/absent-is-not-zero.md` a stale
+figure presented as current is the worst available outcome.
diff --git a/plugins/claude-for-manufacturing/skills/quote-build/reference/hours-ladder.md b/plugins/claude-for-manufacturing/skills/quote-build/reference/hours-ladder.md
new file mode 100644
index 00000000..b222fe29
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/quote-build/reference/hours-ladder.md
@@ -0,0 +1,242 @@
+# The hours step and the ladder
+
+**Every machine hour on the internal sheet says where it came from.** An
+estimator handed "op 20: 9.5 min/pc" cannot tell a number read off a current
+routing from one Fusion produced with library feeds, and those two numbers
+deserve very different amounts of trust. So each operation carries its rung,
+its path, its cutting-data basis, its setup and run separately, a range, and
+the variance against every other source that exists.
+
+None of it reaches the customer. The customer quote carries prices; this file
+is the internal sheet's business.
+
+---
+
+## What the hours step reads
+
+| Input | From | When it is absent |
+|---|---|---|
+| Routings | `routings` tab, consolidated dataset v4, or a routing file | No rung 1. Say so per part |
+| Operation actuals | `operation_actuals` tab, dataset v4, or an actuals file | No rung 2. Say so per part |
+| Geometry estimate | `../../../shared/contracts/geometry-estimate.md`, from `rfq-to-quote` step 7 or typed by the estimator | No rung 3. The internal sheet says the design step did not run and why |
+| Machine classes | `Machine classes` table under `### Machining data` in the `## Plant context` block: Machine class, Work centers, Cell, Setup hours, Tool change min, Basis | Setup at rung 3 cannot be taken from the plant. Name it; the estimator supplies it or the op falls to rung 4 |
+| Cutting data | `Cutting data` table in the same section (Material, Tool class, SFM, Chip load ipt, Basis), or a line `Fusion tool library: <name>` | The CAM path runs on library feeds and every op is `fusion_default`, rung 4. The feature path cannot compute a cut time |
+| Variance flag threshold | `Variance flag threshold: <percent>` in the same section | Use 15%, and print it as **"15% — default threshold, not plant-set"** wherever a flag depends on it |
+
+A value tagged `Basis: assumed` in either table is used and labelled assumed on
+every op it touches. It is the plant's number, recorded as a guess.
+
+---
+
+## The ladder, per operation
+
+Best available first. **The highest rung that exists for an operation is its
+basis; every other rung that exists is shown beside it as a cross-check.**
+
+| Rung | What qualifies | What does not |
+|---|---|---|
+| **1 — Routing** | A routing for this part **and the revision being quoted**, cited by file and row or record. A routing that records no revision is usable, labelled *"routing revision not recorded — confirm it is current for Rev X"* | A routing for another revision. It is **superseded**: shown on the internal sheet as *"Rev 1 routing — superseded, not used"*, never priced from, at any rung |
+| **2 — Closed-job actuals** | Actual setup and run hours from closed production work orders for this part and operation, `actuals_confidence: recorded`. Each work order named, the count from the figures block | Actuals flagged `probable_standard`. See below |
+| **3 — Geometry-derived** | Hours derived from a geometry estimate whose `approval.status` is `confirmed` — or `draft` with the estimator's explicit say-so in this run, recorded — by the CAM path or the feature path, with `cutting_data_basis` of `plant_library` or `estimator_entered` | Anything on `fusion_default` cutting data. Anything from an unconfirmed model with no say-so |
+| **4 — First principles** | Everything else: library feeds, a similar part's routing, the estimator's judgement, a feature path with no cutting data. **Always names what would firm it up** — *"a current routing, or plant SFM for 4140 with a 0.5 in carbide end mill"* | Never presented as anything firmer than it is |
+
+### `probable_standard` actuals never outrank rung 3
+
+Actuals the backflush check flagged may be the routing standard posted under a
+work order number. They are shown, with their `confidence_reason`, and ranked
+**below a geometry-derived estimate and above first principles.** Where the
+standard they echo belongs to a superseded routing, they echo a superseded
+standard: say that, too.
+
+### Actuals from an earlier revision
+
+Actuals carry the revision the job ran to where the source records it. Where a
+drawing revision changed something this operation cuts or holds — the revision
+history names it — those actuals are a cross-check for that operation, not its
+basis. Operations the change did not touch keep them at rung 2, labelled with
+the revision they ran at.
+
+### Units
+
+Setup in hours, run as minutes per piece. Where a source declares its unit,
+converting minutes and hours is exact and is shown once (*"routing 7.00 min/pc
+= 0.117 h/pc"*). **Where a source's unit is undeclared, that source is not used
+for that operation** until the plant says what the unit is. The dataset's
+`time_unit_flag` is carried onto the sheet.
+
+---
+
+## Setup and run, separately, at every rung
+
+Setup is a cost per job; run is a cost per piece. Each rung supplies both, or
+says it cannot.
+
+**A source that gives only a lumped total has an unknown split.** State it, and
+**never re-amortize it**: a total of 25 hours for 200 pieces is not 0.125 h/pc
+at a quantity of 50, because nobody knows how much of the 25 was setup. For the
+quantity-break arithmetic, use the highest rung that does carry a split, and
+show the lumped figure beside it at the quantity it came from.
+
+---
+
+## The range, and where each bound comes from
+
+Low, expected and high, setup and run, **on the internal sheet only.** Each
+bound names what produced it:
+
+- Rung 1: the routing standard is expected. Low and high come from recorded
+ actuals for the same operation where they exist; otherwise the range is a
+ single point, printed as *"no spread available"*.
+- Rung 2: median of the recorded work orders is expected; the lowest and
+ highest are low and high.
+- Rung 3: the CAM path and the feature path bound each other where both ran;
+ otherwise the cutting data's own spread where the table gives one; otherwise
+ a single point.
+- Rung 4: the range the stated assumptions produce, each assumption named.
+
+**A range never comes from a percentage band nobody measured.** "±15%" with no
+source is an invented number with a plus-minus sign.
+
+---
+
+## Variance
+
+Where two or more rungs exist for an operation, compute in code, for setup and
+for run separately: (other − basis) ÷ basis. Put each in the figures block.
+
+**Flag any variance above the threshold** — the Plant context's `Variance flag
+threshold`, or 15% labelled *"default threshold, not plant-set"*.
+
+**Every flagged variance names its drivers.** What differs between the two
+numbers: a tool-change allowance, a feed at nominal diameter, a finish pass one
+source has and the other lacks, a revision change, a backflushed standard.
+
+**An assumed plant value that accounts for more of a gap than the threshold is
+named as a driver**, with its `Basis: assumed` tag. A 0.5 min tool change
+across fourteen tool changes is seven minutes a piece, and if the measured
+value is 0.15 min, that assumption is most of a 36% gap. The estimator needs to
+see that the plant's own default, not the cutting, is the variance.
+
+---
+
+## The CAM path
+
+Runs when Fusion is connected with its Manufacturing workspace, a confirmed
+geometry estimate has a `document_ref`, and cutting data exists in the Plant
+context or as a named Fusion tool library. The connector calls and the
+behaviors that break them are in
+`../../design-space-explore/reference/cad-adapter.md` — read it before the
+first call.
+
+1. **Integrity check first** (rule 7.5). List bodies and sketches. Anything not
+ in the geometry estimate's `bodies_after` / `sketches_after` fails the step.
+ Repeat after the CAM step.
+2. **One setup per `setups` row**, stock and stock-to-leave set explicitly
+ (rule 7.6). Create operations in `op_seq` order — they cannot be reordered.
+3. **Cutting data from the plant**, per op: `cutting_data_basis` is
+ `plant_library` (the Plant context table, or the named Fusion tool library),
+ `estimator_entered` (typed in this run by the estimator, recorded), or
+ `fusion_default`. **`fusion_default` demotes the op to rung 4, labelled
+ "library defaults, not plant data"** (rule 7.1). Set the tool first, feeds
+ last, and read them back.
+4. **Chamfers and small features** use the effective cutting diameter or the
+ plant's fixed feed, never the tool's nominal diameter (rule 7.7).
+5. **Generate, then poll** `isGenerating` / `hasToolpath`. Clear an existing
+ toolpath before regenerating.
+6. **Verify each toolpath by geometry** (rule 7.4). Read the toolpath points
+ and check them against the op's intent — outside the boss, inside the
+ pocket, within the hole. `isToolpathValid` is necessary, not sufficient: a
+ valid toolpath has cut the wrong region before. Record per op: points read,
+ points inside the intended region, pass or fail. A failed op is not timed.
+7. **Read machining time per op.** Add tool changes yourself: the Plant
+ context's `Tool change min` × the op's tool-change count (rule 7.2).
+ `getMachiningTime` ignores the tool-change time it is given.
+8. **Rough-only times are labelled rough-only** (rule 7.6). A finish pass the
+ CAM setup does not cut is added by the feature path and labelled as such.
+
+Without Fusion Manufacturing: the feature path only, and the sheet says so.
+
+## The feature path
+
+Runs always where a confirmed geometry estimate exists, Fusion or not. Per
+operation, from its `features` rows:
+
+1. **Setup hours** from the operation's machine class in the `Machine classes`
+ table, with its basis tag.
+2. **Cut time per feature** from the cutting data for the material and tool
+ class: spindle speed = SFM × 3.82 ÷ tool diameter; feed = speed × chip load ×
+ flutes; time = cut length ÷ feed. Tool diameter, flutes, stepover and depth
+ of cut are **assumptions, named on the op** — the estimator confirmed the
+ operation list at Gate 3, not the tooling. Chamfers per rule 7.7.
+3. **Tool changes** = count × `Tool change min`, labelled with its basis.
+4. **Outside processes** carry no machine time. Their lead time — *"black
+ oxide, 5 working days per lot"* — goes to the date check.
+
+No cutting data for the material: the feature path cannot compute a cut time.
+That op's run falls to rung 4 unless the estimator enters cutting data, which
+makes it `estimator_entered`.
+
+**No row for a tool class — a reamer, a chamfer mill — is not licence to supply
+one.** Time that element on the nearest row the table does have, say which row
+and that it is a stand-in, and mark the element rung 4. Never a handbook SFM,
+never a "typical" feed: that is a rate the model invented, with a unit.
+
+---
+
+## The internal sheet, per operation
+
+One row per operation, inside the internal cost sheet's delimiters:
+
+| Column | Holds |
+|---|---|
+| Op | `op_seq` and description |
+| Work center / cell | From the routing, or the machine class map |
+| Rung | 1–4, and *why not higher* where a higher rung was refused (superseded, `probable_standard`, unconfirmed model) |
+| Path | Routing, actuals, CAM path, feature path, first principles |
+| Cutting data basis | `plant_library`, `estimator_entered`, `fusion_default`, or n/a |
+| Setup h | Low / expected / high, each bound's source |
+| Run min/pc | Low / expected / high, each bound's source |
+| Other rungs | Each with its setup and run, and the variance against the basis |
+| Variance drivers | Named, assumed plant values tagged |
+| Toolpath check | CAM path only: result per op, or *"not run — feature path"* |
+
+## The operation record
+
+Kept with the quote, because revisions re-derive from it and because one day
+someone will ask how good these estimates were. Per operation: part, revision
+priced to, `op_seq`, work center, machine class, rung, path, cutting data basis,
+setup and run (low, expected, high, with units), the quantity breaks they were
+priced at, every source cited, the geometry estimate's `document_ref` and
+approval state, and the date derived. **That is enough to compare against the
+actuals when the job closes, by part, revision and operation.** The comparison
+itself is not built yet.
+
+A price counter re-derives from this record. It never reopens CAD.
+
+---
+
+## Path A — a ROM, never a firm quote
+
+A line is path A when the intake form line's `geometry_path` is `A`, or its
+geometry estimate's `geometry_path` is `A` or its `origin` is
+`built_from_text`: text specifications and no drawing. Every dimension was
+read from text, and no tolerance came from a drawing. **The price is a rough
+order of magnitude, and the quote says so on both documents, in different
+words.**
+
+- **Internal sheet.** The first line inside its delimiters reads *"ROM —
+ rough order of magnitude. Path A: text specs, no drawing. Not a firm quote
+ and not releasable as one."* The ladder runs as usual, and every hour is
+ labelled as it would be.
+- **Customer document.** It stays inside `=== CUSTOMER QUOTE — SENDABLE ===`
+ but is titled **Budgetary estimate**, not quotation, and its assumptions
+ carry one sentence in customer terms: *"This is a budgetary estimate based on
+ the written specifications you provided, for planning only. It is not an
+ offer; we will send a firm quotation on receipt of a released drawing."*
+ **Nothing about how it was estimated**: not "ROM", not "rough order of
+ magnitude", not text specs, path, model, hours or basis. The outbound check
+ rejects them in this block like any other basis label.
+- **At Gate 4** the estimator may release it as a budgetary estimate. **No
+ release, override or Gate 3 yes turns it into a firm quote.** Asked to, say
+ so in one line: a firm quote needs a drawing, and the drawing goes back to
+ `rfq-to-quote` step 7 as path C2.
diff --git a/plugins/claude-for-manufacturing/skills/quote-build/reference/revisions.md b/plugins/claude-for-manufacturing/skills/quote-build/reference/revisions.md
new file mode 100644
index 00000000..740c84a5
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/quote-build/reference/revisions.md
@@ -0,0 +1,101 @@
+# The negotiation loop
+
+**Most of an estimator's time goes into revisions, not first drafts.** That is
+why this is core behaviour rather than a follow-up feature.
+
+---
+
+## A counter is not a new quote
+
+When a customer comes back — "can you do better at 1,000?", "we need it two
+weeks earlier", "drop the anodize" — **revise the existing quote in place and
+preserve a change record.**
+
+Treating a counter as a fresh quote is how a plant ends up with four versions in
+circulation, no record of what was conceded, and two people quoting the same job
+to the same customer at different prices. It happens constantly, and it is
+entirely a bookkeeping failure.
+
+---
+
+## What the change record holds
+
+Per revision:
+
+| | |
+|---|---|
+| Revision number and date | Sequential, on one quote, not a new reference |
+| What the customer asked for | In their words |
+| What changed in the quote | Line by line, old value to new value |
+| **Why it changed** | The reason, not just the delta |
+| What did not change, and was asked about | The concessions that were declined |
+
+**That "why" column is the one that matters.** Six months later somebody needs
+to know whether the price dropped because the quantity went up, because a
+material price was re-checked and had fallen, or because somebody gave away four
+points of margin to win the job. Those are three completely different facts and
+only one of them is repeatable.
+
+**Record what was declined, too.** A customer who asked for 60-day terms and did
+not get them will ask again on the next order, and the estimator should walk in
+knowing that.
+
+---
+
+## Re-derive, do not patch
+
+When a parameter changes, **re-run the affected buildup lines rather than
+adjusting the total.**
+
+A quantity change means setup re-amortizes across the new quantity. A material
+change means a new price at a new date, a new scrap allowance, and possibly a
+new routing. Patching a total by hand loses that and produces a quote whose
+cost-basis sheet no longer reconciles with its own front page — which is exactly
+the document the estimator was going to defend to their manager.
+
+Re-derive, then show the diff against the prior revision.
+
+**Re-derive from the stored operation record** (`hours-ladder.md`, *The
+operation record*): the rung, path, setup and run per operation as priced. A
+quantity change re-amortizes setup from it; a price counter re-prices from it.
+**A price counter never reopens CAD** and never re-runs the hours step —
+nothing about the part changed.
+
+**A drawing revision is not a counter.** A new revision can change what every
+operation cuts, so it goes back to `rfq-to-quote` step 7 for a new geometry
+estimate and a new Gate 3, and the hours are derived again. Pricing a new
+revision on the old revision's hours is the same mistake as pricing it on a
+superseded routing.
+
+---
+
+## Margin concessions are shown, never absorbed
+
+If the revision is a price drop with no change in scope, then **margin moved**,
+and the change record says so explicitly with the before and after.
+
+The temptation is to present a lower price as though something in the cost
+changed. It did not. An estimator needs to see the margin line move so they know
+how much room is left before the next round, and a manager needs to see it to
+know what the job is actually worth.
+
+---
+
+## Watch for scope creeping in with the counter
+
+Customers frequently bundle a scope change into what sounds like a price
+negotiation. *"Can you do $3.80? And we'd need the first article two weeks
+earlier."*
+
+**Separate those.** Price the scope change as a scope change, show it as its own
+line in the revision, and let the estimator decide whether it is a concession or
+a new requirement. A scope change absorbed silently into a price negotiation is
+how margin disappears without anyone being able to point at where.
+
+---
+
+## Every revision goes through the gate
+
+A revision is a customer-facing document like any other. It is drafted, shown
+with its diff, and **released by the estimator.** Nothing goes out because it is
+the second version of something already approved.
diff --git a/plugins/claude-for-manufacturing/skills/rfq-to-quote/SKILL.md b/plugins/claude-for-manufacturing/skills/rfq-to-quote/SKILL.md
new file mode 100644
index 00000000..d9f9a751
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/rfq-to-quote/SKILL.md
@@ -0,0 +1,330 @@
+---
+name: rfq-to-quote
+description: "Runs the whole RFQ-to-quote chain end to end: reads the inquiry and its drawings, checks it against what the plant can build, drafts the questions back, returns a provisional bid/no-bid, pulls cost history, routings and closed-job actuals, builds an internal estimating model in Fusion where connected (from the drawing, a prior part's model saved as new, text specs as a ROM only, or a STEP file), derives machine hours per operation with each hour's basis labelled, and drafts the quote with its cost basis shown. Four approval gates, and the chain pauses for days while the customer answers. Use when someone says \"run the RFQ chain,\" \"take this RFQ all the way to a quote,\" \"quote this end to end,\" \"quote this from the drawing,\" or names an inquiry and asks for the full workflow."
+compatibility: "Requires none. Chains customer-inquiry-intake, data-consolidate and quote-build, and runs the design step itself. Reads Microsoft 365 and NetSuite or Infor M3 where connected, and Autodesk Fusion (desktop, open) for the design step and CAM hours; runs on a pasted RFQ and file exports with no connector, with every missing piece labelled. Nothing reaches a customer without the estimator releasing it. Resumable: answers arriving days later re-enter the chain rather than starting a new one."
+---
+
+# RFQ to Quote
+
+Chain 1. `customer-inquiry-intake` → `data-consolidate` → design step →
+`quote-build`.
+
+**This chain does not run in one sitting**, and building it as though it does
+is the main way it goes wrong. Steps 1 to 5 happen when the RFQ lands. Then it
+pauses while the customer answers, often for days, which is usually the longest
+single stretch in quote turnaround. Treat the inquiry as resumable state.
+
+**Every member step runs through its member skill — load its SKILL.md before
+the step, and produce what it produces.** Steps 1 to 5 are
+`customer-inquiry-intake`; step 6 is `data-consolidate`, backflush check
+included; steps 9 to 11 are `quote-build` with its
+`../quote-build/reference/hours-ladder.md`, ending in its two delimited documents. A chain
+that prices from memory of its members drops exactly the rules that make the
+price defensible: the ladder, the default variance threshold, the outbound
+check.
+
+**Quick start**
+
+```
+→ Steps 1-5 on arrival. Then STOP and wait for the customer
+→ Step 3 can short-circuit: a hard disqualifier ends the sequence before we ask anything
+→ Step 5 never waits. Provisional score on what is known
+→ Answers re-enter at step 2, NOT step 5. The gaps register shrinks and step 5 re-scores
+→ No answer? Stale. Never cancelled, never declined
+→ Step 6 BEFORE step 7: a current-revision routing makes the design a cross-check, not the basis
+→ Step 7 builds an internal model per path: C2 drawing, B prior model saved as new, A text (ROM only), C1 STEP (unverified)
+→ Integrity check before and after every CAD step. The prior model is never overwritten
+→ Fusion missing? Hand-entered features or no design step. Labelled, never a stop
+→ Four gates: send questions, confirm bid/no-bid, confirm the design, release the quote
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| The RFQ and its drawings | M365 mail and attachments, a folder, or pasted | PDF, XLSX, DOCX, image, email body, STEP |
+| Customer answers, when they arrive | Conversation, or a forwarded reply | Text |
+| Routings and closed-job operation actuals | Through `data-consolidate` | Dataset v4 |
+| Machining data | `### Machining data` in the `## Plant context` block | Config |
+| Fusion, for the design step | The desktop app, with the connector | Live CAD connection |
+| Everything else | Whatever the three member skills read | See each skill |
+
+---
+
+## The twelve steps
+
+**1. The RFQ arrives**, in whatever format the customer sent it. Hand it to
+`customer-inquiry-intake`. A multi-attachment package is one inquiry.
+
+**2. Extract into the intake form**, with missing and ambiguous flagged
+separately, every tolerance carrying how it was read, and **each line's
+`geometry_path` classified** — `C2` drawing, `C1` STEP, `B` prior part, `A`
+text only, `none`. This is also where a customer's later answer re-enters.
+
+**3. Check against the plant's constraints.** A **hard disqualifier stops the
+sequence here** with a no-bid recommendation and its specific reason, before
+the plant engages the customer at all. There is no point asking five questions
+about a part the plant cannot make.
+
+Two limits, both load-bearing. It stops the *sequence*, not the inquiry: the
+estimator can override and proceed, and the inquiry stays open. And only
+violations determinable from **stated facts** qualify. Anything resting on a
+missing field is a scoring input for step 5, not a stop.
+
+**4. Draft the open questions** back to the customer, as sendable email text —
+including a drawing with no revision and any change the customer says is
+pending. **Gate 1** — the estimator sends them. Nothing goes to a customer
+from here. When they say they have, record `questions_sent_at` and `_by`: the
+stale clock starts there.
+
+**5. Return the provisional bid/no-bid**, with its reasoning and the specific
+unanswered questions that would change it, **per line as well as overall**: an
+RFQ whose lines deserve different answers is `partial`, with each line's
+`line_recommendation`. **Gate 2** — the estimator confirms or declines, per line
+where the lines differ, and `bid_decision_basis` records what they ruled on.
+
+**Step 5 never waits.** Most RFQs arrive with at least one gap, so a
+recommendation that blocked on answers would stall the chain on nearly all of
+them. It sits after the questions rather than at the front because a sound call
+often needs those questions already in flight, but it is still ahead of every
+costing step.
+
+**Then the chain stops.** While any drafted question is unanswered, the first
+pass ends here, and says so in these terms: *"Paused after step 5, at Gate 1 and
+Gate 2 — the questions are drafted for you to send, and the bid/no-bid is
+provisional until you confirm it. Steps 6 to 11 run when the customer answers,
+or when you tell me to quote with those questions as exclusions."* **No
+customer-facing quote — no price, no lead time, no terms — is drafted in the
+same pass as the questions it depends on**, even when the request was "take
+this all the way to a quote." A quote built on an open question prices a guess,
+and once it exists it gets sent. The estimator may still choose to quote on
+exclusions; that is their call at Gate 2, made after seeing the questions, not
+a default.
+
+**A pause is saved, so a new session can resume it.** Save the intake form on
+the Open work page as the contract names it, with `open_questions` word for
+word as sent, set `paused_at_step` and `waiting_on`, and write the inquiry's line to the page's `## Open inquiries`
+block, per `../../shared/contracts/intake-form.md` and
+`../../shared/replies.md`. Name the page and the file on it. On resume, bring
+in the page, read the line, open the form from it, and continue at
+`paused_at_step`; never start the inquiry over.
+
+**6. Pull cost history, comparables, routings and operation actuals** via
+`data-consolidate` and the ERP, with the backflush check — load
+`../data-consolidate/SKILL.md`; actuals agreeing within 1% are
+`probable_standard`, all of them, not the one that happens to equal the
+routing. **This runs before
+the design step on purpose:** where a current-revision routing or trustworthy
+actuals exist, the model is a cross-check, not the basis.
+
+**7. The design step.** Per line, by path, build the internal estimating model
+in a new Fusion document, every feature citing its source, with the
+document-integrity check before and after: **C2** from the drawing; **B** by
+opening a different prior part's model, applying the drawing's changes and
+saving as a new document, the prior model never overwritten, falling back to
+C2 when it is unavailable; **A** from text specs, every dimension `from_text`,
+**a ROM only, never a firm quote**; **C1** by importing the STEP and reading
+it, nothing generated, **the import unverified**. Emit the
+**geometry estimate**, `approval.status: draft`, per
+`../../shared/contracts/geometry-estimate.md`. **Skipped for a line with a
+current-revision routing** unless the estimator asks for a cross-check. Read
+`reference/design-step.md` before the first CAD call.
+
+**8. Gate 3 — the estimator confirms the design.** The model, the tolerance
+reading, the datum assumptions (every `inferred` datum, by name), the operation
+list, and the open questions the model raised. A line priced from a current
+routing still passes Gate 3 on the routing's operation list and the tolerance
+reading. **No geometry-derived hour is computed for the quote until this yes,
+or an override the estimator gives and the record keeps.**
+
+**9. The hours step**, through `quote-build` — load `../quote-build/SKILL.md`
+and `../quote-build/reference/hours-ladder.md` first: the CAM path where Fusion
+Manufacturing and plant cutting data exist, the feature path always — setup
+hours and run minutes per operation, low, expected and high, each labelled with
+its basis, each toolpath verified by geometry.
+
+**10. The ladder per operation**, through `quote-build`: routing, then
+recorded actuals, then geometry-derived, then first principles; variance where
+two exist; setup and run apart; capability flags; the load check by work center.
+
+**11. The customer quote and the internal sheet**, as `quote-build` emits them:
+`=== CUSTOMER QUOTE — SENDABLE ===` and `=== INTERNAL COST SHEET — NOT FOR
+CUSTOMER ===`, each closed with `=== END ===`, the outbound check run on the
+first. **Gate 4** — the estimator reviews and releases.
+
+**12. When something comes back.** See *Resuming*, below.
+
+---
+
+## Approval gates
+
+**Four, and the count matters** — a reader who thinks there are three has lost
+the one that stops an unconfirmed model pricing a job, and a reader who thinks
+there are two has lost the one that stops mail reaching a customer.
+
+| Gate | Where | What it protects |
+|---|---|---|
+| 1 | Step 4 | The estimator sends the questions. No mail leaves on anyone's behalf |
+| 2 | Step 5 | The estimator confirms bid/no-bid. This is what makes the chain valuable rather than merely fast |
+| 3 | Step 8 | The estimator confirms the model, the tolerance reading, the datum assumptions and the operation list. Hours are derived from what was confirmed, not from what was generated |
+| 4 | Step 11 | The estimator releases the quote |
+
+Nothing reaches a customer without human release. The generated model never
+reaches a customer at all.
+
+**Asked where sign-off is needed, answer with this table** — each gate, its
+step, and what the estimator does there. "All four gates are still with the
+estimator" is true and tells them nothing. And whenever the chain stops, it
+names the gate and the step it stopped at. What a yes at a gate does and does
+not cover — including that a Gate 3 yes does not carry to a later drawing
+revision — is `../../shared/approval-gates.md`.
+
+---
+
+## Resuming
+
+### When the answers come back
+
+**An answer is new source material.** It re-enters at **step 2**, not step 5 —
+it is extracted like anything else with its own source reference, the gaps
+register shrinks, and step 5 re-scores on the fuller picture.
+
+It **revises the existing inquiry**. It never opens a new one. When the
+inquiry came from the Open work page, **the reply's first line says so**:
+*"Picking up EH-RFQ-0912 from your Open work page, paused at step 5."* Match
+each answer to its question by the numbers in the saved `open_questions`.
+
+**Where an answer flips the recommendation, say so and say why.** A
+recommendation that silently reverses between two readings is worse than either
+version of it. **And an earlier Gate 2 yes lapses**: it covered the
+recommendation as shown in `bid_decision_basis`, not the new one. Return the
+decision (and the changed line's) to `draft`, set `bid_decision_reset` to what
+changed, and ask Gate 2 again naming the change. Never quote a line on a yes
+given before it flipped.
+
+### When a revised drawing arrives
+
+**A new drawing revision re-runs step 7** for the lines it touches: a new
+model, a new geometry estimate, a new Gate 3. The previous Gate 3 yes covered
+the previous revision and nothing else. Hours and price follow from the new
+confirmation.
+
+### When the customer counters on price
+
+**A price counter does not re-run step 7 and never reopens CAD.** Nothing about
+the part changed. `quote-build` re-derives from the stored operation record,
+and the revision goes through Gate 4 like any other.
+
+### When they never come back
+
+After the interval (`MFG_RFQ_STALE_DAYS`, the profile, or 5 business days by
+default, per `customer-inquiry-intake`) the inquiry surfaces as **stale**, carrying its
+provisional recommendation and its still-open questions, so the estimator
+quotes it with exclusions or drops it deliberately.
+
+**A declined inquiry is never surfaced as stale**: it has been decided.
+
+**Stale is a visibility change, never a status change.** Nothing here cancels,
+declines, closes or no-bids an inquiry because a customer went quiet. Letting
+it go quiet is how an RFQ joins the unbid book, which is one of this chain's
+own metrics.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+Everything the member skills produce, in order: the intake form, the open
+questions as sendable text, the provisional recommendation with what would
+change it, the **geometry estimate** per line (or the reason there is none),
+the customer-facing quote, the internal cost-basis sheet with its **hours-basis
+table** — rung, path, cutting-data basis, setup and run, range, variance and
+drivers per operation — and the assumptions and exclusions list.
+
+**The Sales command-center page** — commercial performance for the period,
+carrying the intake record and the quote by reference. An artifact you place;
+nothing is written to a system. Read `../../shared/command-center.md`.
+
+---
+
+## Edge cases and failure modes
+
+- **A hard disqualifier fires at step 3** — the chain stops before step 4. The
+ inquiry stays open and the estimator may override.
+- **The estimator declines at Gate 2** — `quote-build` blocks. Reopening is a
+ new decision, not a quote.
+- **The estimator declines the model at Gate 3** — no geometry-derived hours.
+ Correct the model and re-confirm, or price from the rungs that remain.
+- **A revised RFQ arrives mid-chain** — it supersedes, and the chain resumes
+ against the revision rather than running twice.
+- **The customer answers only some questions** — re-score on what arrived, and
+ keep the rest open. Partial is normal.
+- **The only routing is for an earlier revision** — superseded. Step 7 runs as
+ though there were no routing, and the old routing is shown, never priced.
+- **Foreign geometry appears in the Fusion document** — the step fails. Ask
+ the user to restart Fusion. Never build on top of it.
+- **Asked to update the prior part's model in place (path B)** — decline in
+ one line. The adapted model is always a new document.
+- **Asked to send a path A line as a firm quote** — decline. A firm quote
+ needs a drawing, and the drawing re-runs step 7.
+- **The model suggests a cheaper way to make the part** — it goes in
+ `cost_down_proposals`, on the internal sheet. Never to the customer.
+
+---
+
+## Degradation
+
+| Not available | What happens |
+|---|---|
+| The ERP (NetSuite or Infor M3) | **Steps 5 and 6 both degrade** to document-based comparables, and the chain says so rather than quietly producing weaker output |
+| The capability profile | Step 3 cannot run its constraint check. Say so; do not report a clean check that never happened |
+| M365 | Accept the RFQ pasted or uploaded. The chain is otherwise unchanged |
+| Fusion | **The chain still completes.** Step 7 offers a hand-entered feature list — prefilled from the drawing as read, every row cited, `origin: hand_entered` — for the estimator to confirm at Gate 3. Without it, step 7 is skipped and the ladder starts at whatever rung exists, down to first principles, labelled. Say "Fusion not connected — no model built" on the internal sheet |
+| Fusion Manufacturing (CAM) | Feature path only, and the label says so |
+| Plant cutting data | The CAM path runs on library feeds, labelled `fusion_default`, rung 4 |
+| Routings and actuals | Tabs named missing. The ladder starts at rung 3 |
+| A prior part model (path B) | **Falls back to C2**, built from the drawing in a new document, and says so with the reason. The prior model is never written to |
+| CAD, on a STEP file with no drawing (path C1) | **"C1: STEP read without CAD (unverified)"** — the STEP read as a text file, every value cited and labelled unverified. Else a hand-entered feature list, else skip step 7, labelled |
+| A drawing (path A, text specs only) | Built from the text, every dimension `from_text`. **A ROM, never a firm quote** — budgetary on the customer document, and nothing about how it was estimated |
+| Foreign geometry in the document | Step 7 fails for that line. The user restarts Fusion |
+
+---
+
+## Chain position
+
+**This is Chain 1 itself.** Members: `customer-inquiry-intake`,
+`data-consolidate`, `quote-build`, with the design step run here.
+
+**Metric.** Quote turnaround, owned jointly by `customer-inquiry-intake` and
+`quote-build`. Hit rate and the unbid book, owned by `quote-build`.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `../customer-inquiry-intake/SKILL.md` | Steps 1 to 5 and 2-on-return |
+| `../data-consolidate/SKILL.md` | Step 6 — routings, actuals and the backflush check |
+| `reference/design-step.md` | Steps 7 and 8 — the paths, the build, the integrity check and Gate 3 |
+| `../design-space-explore/reference/cad-adapter.md` | Step 7, before the first Fusion call — the create-from-scratch, save-as-new and STEP import calls, and the connector behaviors that break them |
+| `../design-space-explore/reference/adapt-prior-model.md` | Step 7, path B — open the prior model, apply, save as new, never overwrite |
+| `../quote-build/SKILL.md` | Steps 9 to 11 |
+| `../../shared/contracts/intake-form.md` | The handoff, including `geometry_path`, `bid_decision_state` and `inquiry_state` |
+| `../../shared/contracts/geometry-estimate.md` | Step 7's output and what Gate 3 moves |
+| `../../shared/command-center.md` | The Sales page, and why it is never a write |
+| `../../shared/approval-gates.md` | At every gate — what a yes covers, and how to say where the chain stopped |
diff --git a/plugins/claude-for-manufacturing/skills/rfq-to-quote/reference/design-step.md b/plugins/claude-for-manufacturing/skills/rfq-to-quote/reference/design-step.md
new file mode 100644
index 00000000..8b59c836
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/rfq-to-quote/reference/design-step.md
@@ -0,0 +1,285 @@
+# The design step and Gate 3
+
+**Step 7 builds an internal model of the customer's part so the plant can
+estimate how long it takes to make.** It is an estimating aid. It is not the
+customer's design, it is never sent, and it never changes the customer's
+drawing.
+
+The output is one geometry estimate per line, per
+`../../../shared/contracts/geometry-estimate.md`, always emitted as `draft`.
+Gate 3 is where an estimator turns it into something hours can be derived from.
+
+---
+
+## Before anything: does this line need a model?
+
+Step 6 has already run. Per line:
+
+- **A current-revision routing exists** — skip step 7. The routing is the
+ basis. Build the model only if the estimator asks for a cross-check, and say
+ which it is.
+- **The only routing is for another revision** — superseded. Treat the line as
+ having no routing. Name the superseded routing so nobody prices from it.
+- **No routing** — step 7 runs.
+
+Recorded actuals do not skip step 7. They are rung 2; the model is the
+cross-check that tells the estimator whether they are believable, and
+`probable_standard` actuals are not believable enough to skip it.
+
+## Path classification (R1)
+
+Read `geometry_path` from the intake form line. Where the form has no
+`geometry_path`, classify from `source_documents` and say so. Then, where
+the step finds something intake could not see, reclassify and record why —
+the estimator naming a different part's model on file as the starting point
+makes a C2 line a B line. An earlier revision of the same part never does.
+
+| Path | What step 7 does | Section |
+|---|---|---|
+| `C2` drawing | **Builds the model from the drawing** in a new document. The normal case | *Building the model — path C2* |
+| `B` drawing + a different prior part's model | **Opens the prior model, applies the drawing's changes, saves as a new document.** The prior model is never overwritten. Falls back to C2 when the prior model is unavailable or the changes are not its parameters | *Path B* |
+| `A` text only | **Builds from the text** with the same calls as C2. Every dimension `from_text`. **ROM only, never a firm quote** | *Path A* |
+| `C1` STEP, no drawing | **Imports the STEP and reads it.** Nothing generated. STEP import through the connector is **unverified** | *Path C1* |
+| `none` repeat part | Nothing to build. Priced from its routing or actuals, or a question back | |
+
+**Name the path that actually ran.** A path B line built from the drawing
+because the prior model was not there is reported as C2 with the reason, never
+as path B: calling it B would tell the estimator a prior part's proven geometry
+was reused when it was not.
+
+**Rules for every path.** The model is an internal estimating aid and never
+goes to a customer. Tolerances are read, never inferred: a general-note
+tolerance applied to a feature cites the note, and a tolerance nobody stated
+goes on `unreadables`. A datum assigned from the dimension scheme is
+`inferred` and shown at Gate 3. Every path passes the integrity check before
+and after its CAD step, and every path stops at Gate 3.
+
+---
+
+## Building the model — path C2
+
+Read `../../design-space-explore/reference/cad-adapter.md` first: the
+create-from-scratch calls, and the connector behaviors that lose calls or plant
+foreign geometry. The rules that matter most:
+
+- Every script defines `run(context)` and prints what it needs back.
+- Inspection calls are `readOnly: true`.
+- Each call under about 25 seconds.
+- Design workspace active on every call.
+- Fusion open with the document active; there is no file-only path.
+
+Then:
+
+1. **Create a new document**, named for the inquiry, line, part and revision —
+ even when the open document is empty. The open document is the user's.
+ Never a customer file, never an existing model.
+2. **Integrity check, before.** List bodies and sketches, read-only. A fresh
+ document lists none. Anything there means the add-in is replaying an earlier
+ script: stop and ask the user to restart Fusion.
+3. **Stock.** Material, form and size as the drawing or its material spec
+ states. Fit check: part envelope plus the cleanup allowance against the
+ stock, with the allowance's source. A part that fits only without cleanup is
+ flagged.
+4. **Datums.** A datum whose feature the drawing identifies is `stated`. A
+ datum the drawing references in a feature control frame without identifying
+ its feature is assigned from the dimension scheme and marked `inferred`.
+ Every inferred datum is a question for Gate 3.
+5. **Features**, prismatic first: sketch, extrude, hole or cut, fillet,
+ chamfer. Each feature row carries its dimension, its tolerance **as read**,
+ its `reading_basis`, and its view and zone. A general-note tolerance applied
+ to a feature cites the note — that is reading. **A tolerance the drawing does
+ not give and no note covers is not invented**: the feature goes on
+ `unreadables`.
+6. **Read back** bodies, bounding box and volume, and check them against a
+ hand calculation from the drawing's dimensions. Record both in
+ `model_checks`.
+7. **Integrity check, after.** Every new body and sketch is one this step
+ created, by name. **Anything else is foreign geometry: the step fails** for
+ this line. Record both lists. Tell the user to restart Fusion.
+8. **Setups and operations** — the plant's proposed way to make it, by machine
+ class from the Plant context: which faces each setup reaches, the fixture
+ note, which features each operation cuts, outside processes as their own
+ operations. Every assumption on the operation it belongs to.
+9. **Questions** for the estimator: every inferred datum, every assumption
+ that changes the operation list, every tolerance tighter than the plant has
+ demonstrated on that process.
+10. **Cost-down ideas** go in `cost_down_proposals` — internal, never to the
+ customer.
+
+Emit the geometry estimate with `approval.status: draft`. **The skill never
+marks it confirmed.**
+
+## Path B — adapt a prior part's model
+
+A drawing for this line, plus a **different** part whose model on file is
+named as the starting point: *"same as our PN-4402-A housing, 10 mm longer."*
+A new revision of a part the plant has already made is not path B; it is C2.
+
+Run `../../design-space-explore/reference/adapt-prior-model.md`, the same
+mechanism `design-space-explore` uses for its variants:
+
+1. **The user opens the prior model in Fusion.** Read it, read-only: name,
+ reference, version, parameters, bodies, sketches, unsaved changes.
+2. **Compare it with the drawing.** List every difference as *parameter: prior
+ value → drawing value, view and zone*. A difference no driving parameter
+ controls means path B does not fit: fall back to C2.
+3. **Save as a new document** named `<inquiry>_L<line>_<part>_R<rev>`, and
+ confirm it is the active document before the first write.
+4. Integrity check before (the copy lists exactly what the prior model held),
+ apply the parameters, verify the regeneration, read back, integrity check
+ after.
+5. **Confirm the prior model's version did not move.**
+6. Steps 3 and 4 and 8 to 10 of the C2 build — stock, datums, setups and
+ operations, questions, cost-down ideas — exactly as for C2. **Every feature
+ and tolerance on the estimate is read from the customer's drawing** and
+ cites its view and zone. Nothing is carried over from the prior part's
+ drawing.
+
+Emit `origin: adapted_from_prior`, `base_model_ref` the prior model and its
+version, `document_ref` the new document.
+
+**The prior model is never overwritten**, edited in place, or saved. Asked to
+"just update the old model", decline in one line and save as new.
+
+**When the prior model is not available, the line falls back to C2** — not
+on file, not found, the user cannot open it, unsaved changes in it, a change
+that is not its parameter, a failed regeneration, a read-back that does not
+match the drawing. Say it in one line, in these words, naming both paths so
+the estimator sees which one ran: *"Path B: PN-4402-A model not on file; built
+from the drawing as C2."* Emit the estimate as `geometry_path: C2`,
+`origin: built_from_drawing`, `base_model_ref: null`, with the fallback and its
+reason as the first entry in `questions_for_estimator`.
+
+The open, save-as-new and untouched-check calls have not been run through the
+connector. Say so at Gate 3 when path B ran.
+
+## Path A — build from text specs, ROM only
+
+Written specifications and no drawing: *"a 4140 bracket, 2 x 1.25 x 0.75 in,
+one 0.500 in through-bore."* Same build as C2, with the text in place of the
+drawing:
+
+- **Every dimension and tolerance is `reading_basis: from_text`**, and its
+ `source_ref` is the file and the line or paragraph of the text it came from.
+- **A dimension the text does not give is not invented.** It goes on
+ `unreadables` and becomes a question to the customer. A feature that cannot
+ be built without it is not built.
+- **A tolerance the text does not give is not invented either**, and the
+ plant's usual tolerance is not applied: there is no drawing, so there is no
+ general note to apply. Null, on `unreadables`.
+- Datums are almost never stated in text. Any datum the build needs is
+ `inferred`, and shown at Gate 3.
+- Emit `origin: built_from_text`, `drawing_revision_priced_to: null`.
+
+**A path A line is a ROM — rough order of magnitude — and never a firm
+quote.** Say so at Gate 3 and in the hand-off to `quote-build`, which labels
+it ROM on the internal sheet and calls it a budgetary estimate on the customer
+document, per `../../quote-build/reference/hours-ladder.md`, *Path A*. A Gate 3
+yes does not make it firm, and neither does an override. A firm quote needs a
+drawing, and the drawing re-runs step 7 as C2.
+
+Without Fusion: the hand-entered feature list, prefilled from the text, every
+row `from_text`, `origin: hand_entered`. Still a ROM.
+
+## Path C1 — import a STEP file and read it
+
+A STEP or other 3D file and no drawing. **Nothing is generated**: no sketch,
+no extrude, no change to the customer's geometry.
+
+**STEP import through the connector is unverified.** It has never been run in
+this repo. Say so on the line, every time.
+
+With Fusion: import the STEP into a new document named like any estimating
+model, integrity check before and after, then read bodies, bounding box,
+volume and faces read-only. Holes, pockets and faces are recognised from the
+faces; each is a reading to confirm at Gate 3, with its `source_ref` naming the
+file and the body or face. Then stock, datums (every one `inferred`: a STEP
+file identifies none), setups, operations and questions as for C2. Emit
+`origin: customer_step`, `cad_backend: fusion`.
+
+**A STEP file carries no tolerances this path reads.** Every feature's
+`tolerance` is null and its `reading_basis` is `unreadable_flagged`, with the
+gap on `unreadables`: *"no tolerance in the STEP file; ask the customer for
+the drawing or a tolerance spec."* Tolerances are never taken from the model's
+nominal geometry or from what is typical. That question goes back to the
+customer through intake.
+
+**When the import fails or Fusion is not connected**, in this order:
+
+1. **"C1: STEP read without CAD (unverified)."** A STEP file is text. Read it
+ as a file: the product name, the units, and where the file gives them, the
+ overall extents and the cylindrical faces' radii. Each value cites the file
+ and the entity number. Label every row unverified, `origin: customer_step`,
+ `cad_backend: none`, `document_integrity: not_applicable`. Where the text
+ does not yield a value, it is not estimated.
+2. **Else a hand-entered feature list**: the estimator reads the STEP in
+ whatever viewer they have and enters the features into the geometry
+ estimate by hand, `origin: hand_entered`.
+3. Else skip step 7, labelled.
+
+A C1 line that also has a drawing is C2: the drawing is the geometry.
+
+## When Fusion is not there
+
+The chain completes; step 7 changes shape, and says so in one line on the
+internal sheet: *"Fusion not connected — no model built."*
+
+- **Offer a hand-entered feature list.** Prefill it from the drawing (path C2
+ or B) or the text (path A) as intake read it — every feature with its view, zone and reading basis —
+ with `origin: hand_entered`, `cad_backend: none`, `document_integrity:
+ not_applicable`. It goes to Gate 3 exactly like a model, and once confirmed
+ the feature path derives hours from it.
+- **Or skip step 7.** No geometry estimate. The ladder starts at whatever rung
+ exists — recorded actuals, else first principles — labelled.
+
+Either way the chain does not stop at step 7 for want of Fusion. It still stops
+at Gate 3.
+
+---
+
+## Gate 3 — what the estimator is shown
+
+**Stop here, and say so:** *"Paused at Gate 3, step 8. The model for line 1 is
+built and drafted below. Confirm or correct it; hours are derived from what you
+confirm."*
+
+Show, per line:
+
+- The path that ran, and the model's document reference, or that the
+ features were hand-entered, or that no model was built and why
+- Path B: the prior model and its version, each parameter *from → to* with
+ its drawing view and zone, and that the prior model's version did not move.
+ Or the fallback to C2 and its reason
+- Path A: that every dimension is `from_text`, and **that the line is a ROM
+ only**
+- Path C1: that the STEP import is unverified, and every feature as a
+ reading to confirm
+- The drawing revision every feature was read from
+- **Every modelled feature with its dimension and its source** — the view
+ and zone it was read from, or the general note applied to it. A feature
+ list with no sources asks the estimator to re-read the drawing to check it
+- **The read-back against the hand calculation**, both numbers shown —
+ *"volume 1.6858 in³ (model) against 1.6858 in³ (hand calc from the
+ drawing)"* — never only "matches"
+- **The tolerances as read**, each with its reading basis and source
+- **The datums**, stated and inferred, inferred ones by name
+- The stock and its fit check, with any flag
+- **The operation list**, setup by setup, with its assumptions
+- The integrity result
+- `questions_for_estimator`
+
+A line with a current-revision routing is shown its routing's operation list
+and the tolerance reading instead. It still passes Gate 3.
+
+**A yes covers what was shown** — this model, these tolerances as read, these
+datums, this operation list. It does not cover a later drawing revision, it
+does not approve any hour (hours come after), and it does not approve a
+cost-down idea. A correction is recorded in `approval.note` and the estimate is
+re-emitted `confirmed` with who and when.
+
+**The turn that shows the model does not also confirm it.** A request made
+before the model was on screen — "build it and go straight to the price" — is
+not a Gate 3 yes; it is generic continuation. **An override is different, and
+explicit**: the estimator says to quote on the unconfirmed model. Then the
+quote proceeds, the override is recorded on the internal sheet with who gave
+it, and every hour it produced is labelled as resting on an unconfirmed model.
diff --git a/plugins/claude-for-manufacturing/skills/root-cause-capa/SKILL.md b/plugins/claude-for-manufacturing/skills/root-cause-capa/SKILL.md
new file mode 100644
index 00000000..d78bd42e
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/root-cause-capa/SKILL.md
@@ -0,0 +1,405 @@
+---
+name: root-cause-capa
+description: "Reads sensor history, inspection measurements, maintenance records and prior tickets onto one verified timeline, runs the pattern checks in code rather than by eye — SPC drift, clustering by lot, shift, operator, machine and tool change, correlation with a maintenance event — then proposes ranked candidate causal chains, each with the evidence for it, the evidence against it, and the test that would confirm or kill it. Drafts the 8D. Where the leading candidate points at purchased material, raises the supplier-caused flag that starts a sourcing action. Use when someone says \"why did this happen,\" \"root cause,\" \"write the 8D,\" \"investigate this nonconformance,\" \"CAPA,\" or \"the customer wants a corrective action report.\""
+compatibility: "Requires none. Reads the consolidated dataset, historian and inspection exports from Microsoft 365, the ERP (Oracle NetSuite or Infor M3) for lots and material receipts, and maintenance history via data-consolidate. Runs on exports alone with no connector. Never correlates across sources whose clocks it could not align. Never produces a single unqualified verdict."
+---
+
+# Root Cause and CAPA
+
+The step between "we found a bad part" and "we fixed the reason." It is slow,
+expert work, and the reason it is slow is that the evidence sits in four systems
+that nobody looks at together.
+
+**Two rules govern everything below, and they are the whole character of the
+skill:**
+
+**Compute, do not eyeball.** Control limits, run rules and group comparisons are
+calculated in code and the skill interprets the computed result. A claim that a
+process "was drifting," asserted from looking at a data file, is the first thing
+a quality manager will test and the fastest way to lose the room.
+
+**Rank, do not conclude.** The output is candidate causal chains with supporting
+*and contradicting* evidence. A confident wrong root cause is worse than a
+ranked list, because it closes the investigation and the fix fails.
+
+**Quick start**
+
+```
+→ Assemble the evidence window; VERIFY time alignment first
+→ Misaligned? Refuse to correlate. Say which conclusions still survive
+→ Run the computed checks: SPC drift, clustering, maintenance correlation, recurrence
+→ Build candidate chains, each link carrying its own evidence for and against
+→ Rank by evidential strength; name what would confirm and what would kill each
+→ Draft the 8D: D1-D5 and D7 populated, D6 and D8 left as placeholders
+→ Material implicated? Raise the supplier-caused flag for Chain 5
+→ Customer pack: redact as a reviewable diff, approved before anything leaves
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| The NCR | `ncr-writeup` | `../../shared/contracts/ncr.md` |
+| Sensor and process history for the window | Historian export to M365 | CSV |
+| Inspection measurements across the run | Quality system export to M365 | CSV/XLSX |
+| Prior NCRs and CAPAs | M365 quality library | Documents |
+| Maintenance history on the asset | CMMS, via `data-consolidate`'s consolidated dataset | Structured — connector-sourced when a CMMS connector is live, export-sourced otherwise |
+| Work order, lot, material receipts | The ERP. Infor M3 receipts carry no lot (`../../shared/erp-connectors.md`): the lot-to-receipt link is asked, and unverified until confirmed | Connector |
+| Supplier and PO for the material lot | The ERP | Connector |
+| Process documents and work instructions | M365 | Documents |
+| Source clocks, shift boundary, skew self-check | `## Plant context` | Config |
+
+**Two of these are read raw rather than from the consolidated dataset, and
+that is deliberate.** The historian export because no workbook tab carries a
+high-frequency sensor trace, and the inspection export because a computed
+control chart needs the measurement as the gage wrote it, not as the ladder
+normalized it. On identity — which lot, which work order — the dataset still
+wins. Read *What this dataset is authoritative for* in
+`../../shared/contracts/consolidated-dataset.md`.
+
+**An NCR with no cited requirement blocks the 8D, the customer pack and the
+diff**, with a pointer back to `ncr-writeup`. Nonconformance is always against
+a requirement. The investigation itself proceeds as a draft, per Step 5: ranked
+candidates and an evidence appendix, labelled draft and blocked from the 8D.
+
+**Carry the NCR's open questions forward, never close them by omission.** A
+scope with `qty_suspect_is_minimum` is printed *at least N* in D2 and in the
+customer pack; an `escape_possible` NCR keeps its shipment check open in D3; a
+null `qty_found` stays null with its reason.
+
+---
+
+## Workflow
+
+### Step 1 — Assemble the evidence window, and verify the clocks
+
+Align sensor, inspection, production and maintenance data onto one zone-aware
+timeline around the event.
+
+**This is most of the work and the highest-risk step in the skill.** Different
+systems record time differently, some in plant local and some in UTC, some
+zone-naive. Read the per-source clocks and the measured skew from the
+`## Plant context` block rather than assuming, then confirm against an event
+visible in two sources.
+
+**Where alignment cannot be verified, refuse to correlate** and say which
+conclusions survive anyway — lot clustering, for instance, does not depend on
+the clocks. Read `reference/time-alignment.md`.
+
+**A join is a join only when the data carries it.** A work order is on the
+timeline as a *data join* when a record ties it to the lot, the part or the
+event — a lot number on its row, a receipt against it. A work order the NCR's
+free text names, with no such record, is on the timeline **labelled "per NCR
+text, not a data join"**, and every conclusion resting on it says so. Calling
+three work orders a clean traceability join when the data ties the heat to
+one of them widens the suspect scope on an assertion, and the scope is the
+number a customer gets told.
+
+### Step 2 — Run the pattern checks, computed
+
+- **SPC drift** on the relevant characteristic across this run and the ones
+ before it, against computed control limits and run rules
+- **Clustering** by material lot, shift, operator, machine and tool change —
+ each reported against its base rate
+- **Correlation with a maintenance event**, gated on step 1 verifying
+- **Recurrence**, carried forward from the NCR's search at creation
+
+Report checks that came back clean, and separately report checks that **could
+not run**. Those are different states. Read `reference/pattern-checks.md`.
+
+**Print every figure from the computation, including the comparisons.** The
+control limits, the measured value, and *how many times over the limit it is*
+all come out of the same code and go into the figures block
+(`../../shared/computed-figures.md`). Computing a limit in code and then
+dividing by it from memory is how a correct chart gets a wrong sentence written
+under it. The prose quotes the block.
+
+**The SPC rows are required whenever measurements exist, whatever they show.**
+Five rows in the figures block, every run: **centreline, UCL, LCL, the basis**
+(which chart, how many points, which runs), and **the run rule checked** with
+its result. They are printed when the process was in control, when the run
+rule found nothing, and when the finding is thin — "computed, no drift found"
+is a result, and a chart nobody can see is the claim a quality manager tests
+first. The only run that omits them is one with no measured characteristic,
+and that run says so under *checks that could not run*.
+
+### Step 3 — Build candidate causal chains
+
+Each stated as a chain rather than a label — material lot variation → hardness
+above nominal → tool wear accelerated → dimension drift — with supporting and
+contradicting evidence attached **to each link**, because a link with no
+evidence is where the reasoning is actually weak.
+
+**Every link carries its own two lines, For and Against, each citing the source
+record** — not one For and one Against for the whole candidate. A link with
+nothing under For is named as the weak point of that chain, in those words. The
+format in `reference/8d-and-candidates.md` is the required shape, not an
+illustration.
+
+### Step 4 — Rank, and name the discriminating tests
+
+By evidential strength, each candidate carrying what would confirm it and what
+would kill it. Where two are supported equally, **present both** — a stated tie
+is a real finding and it names the test that would settle it.
+
+**Two separate lines per candidate, and one line for the whole list.** Every
+candidate has a *Confirm* test and a *Kill* test on separate lines, never merged
+into "confirm or kill by re-measuring". Then, after the ranking, one required
+line: **"Cheapest discriminating test:"** naming the single test, across all
+candidates, that settles the most for the least effort, and which candidates it
+separates. That line is what turns a ranked list into tomorrow morning's plan.
+
+### Step 5 — Draft the 8D
+
+**Draft or block is decided by two conditions, and nothing else.** The 8D is
+**blocked** when, per `../../shared/contracts/ncr.md`, the NCR has no cited
+requirement (`requirement_cited` null with `requirement_not_locatable` true), or
+its `approval_state` is not approved. State which condition blocked it, and
+still produce the ranked candidates and the evidence appendix as a draft. In
+every other case — thin evidence, an unresolved tie, a request to "fill it in
+completely" — the 8D **is produced**: D1 to D5 and D7 populated from the
+evidence, with D4 carrying its ranking and uncertainty, and **D6 and D8 as
+empty structured placeholders**, because they need a real-world outcome and a
+human signature, and a pre-filled D6 is a false record of verification. The
+same NCR gives the same outcome every run.
+
+D4 keeps its ranking and its uncertainty. **Every D5 action names the D4 link
+it breaks**, on the action's own line — "breaks link 2, hardness above
+nominal, by adding incoming hardness verification". An action that breaks no
+link, a quarantine or a re-inspection, is not a corrective action: move it to
+D3 if it is containment, or label it **"improvement, not corrective action"**
+and leave it outside D5. D7 is the system-level change — and where the recurrence
+check found a CAPA that failed, D7 addresses **why the earlier fix did not
+hold**. Read `reference/8d-and-candidates.md`.
+
+### Step 6 — Route the signal
+
+Where the leading candidate points at purchased material, emit the
+supplier-caused flag per `../../shared/contracts/supplier-caused-flag.md`. That
+is the trigger into Chain 5.
+
+**A tie for first does not raise the flag.** Where the material candidate is
+tied with another, say so, name the cheapest test that would separate them, and
+hold the flag until that test runs. A supplier claim is commercially serious,
+and a tie is not a lead.
+
+**When the flag is emitted, stamp `determination_made_at` and say what it is
+in one line:** *"determination_made_at is the middle timestamp of Chain 5's
+escape-to-RFQ metric; it cannot be reconstructed afterwards."* It separates
+investigation time from the sourcing handoff, and without it the two collapse
+into one number.
+
+The contract requires `evidence_against` and `competing_candidates` even when
+the determination is confident, so a supplier is never accused on half the
+picture. It carries its own approval state, because a supplier-caused
+determination is a commercially significant claim.
+
+### Step 7 — Produce the customer-facing pack
+
+The internal 8D holds cost data, other customers' names, supplier identity and
+internal process detail. The customer version must not.
+
+**The redaction pass is a reviewable diff, never a silent filter**, and the diff
+is what the quality owner approves. A recurrence stays in — removing it is
+misrepresentation, not redaction. **Every removal request is recorded in the
+diff, including the ones refused**: who asked, what they asked to remove, and
+the refusal with its reason. Where the pack is still blocked and no diff exists
+yet, emit a **"Pending redaction log"** now with the same entry, so the
+request and the refusal are on the record before the diff is built. Read
+`reference/redaction.md`.
+
+### Step 8 — Update the register row, and the Quality Register
+
+`ncr-writeup` wrote this NCR's row in the Quality Register. This step adds
+what only the investigation knows, per
+`../../shared/contracts/quality-register-record.md`: the 8D step reached, the
+leading cause **labelled as a candidate**, the supplier-caused flag, and the
+effectiveness-check date once one is committed. Per
+`../../shared/live-dashboard.md`, which names every tool call:
+
+1. **Find the register** — the `## Dashboards` line on the Open work page, then the exact
+ title *"<Site>: Quality Register"*.
+2. **Read the row keyed `<site>_<ncr_ref>` and carry forward every field this
+ skill does not own.** The escape clock, containment and recurrence belong
+ to `ncr-writeup`; blanking them on a rewrite is how a register loses the
+ one deadline that matters. No row yet (the NCR was written elsewhere):
+ create it from the NCR this skill was handed.
+3. `set` the row, `list` the collection, rebuild the register in code and
+ publish it.
+4. **Report it** with the dashboard line and the sensitivity line, or the
+ fallback and *"The Quality Register was not updated: [reason]."*
+
+**The row carries references, never content.** The NCR and the 8D appear as
+their identifiers and a one-line summary. Nothing from the internal 8D's cost
+data, and nothing from the redacted customer pack, goes into the register.
+**The supplier signal stays on the Supply Chain page**; the register carries
+only the flag.
+
+---
+
+## Approval gates
+
+**The source NCR's own `approval_state` gates anything customer-facing.** Per
+`../../shared/contracts/ncr.md`, if the NCR isn't `approved`, block the 8D,
+the customer-facing pack, and the redaction diff — the investigation itself
+may still proceed as a draft, since evidence-gathering doesn't need to wait
+on the NCR's sign-off, but nothing built on an unapproved finding goes
+further than that.
+
+**A supplier-caused determination needs a human owner.** It says a vendor caused
+a defect and it starts a search for an alternate source. The flag carries
+`approval_state`, and `supplier-quote-request` blocks on anything not approved.
+
+**Nothing customer-facing leaves without review of the redaction diff.** This is
+Chain 2's closing gate. The pack is drafted and handed to a person; it is never
+sent.
+
+The investigation itself writes nothing back to any system of record. The 8D is
+a document the quality owner files.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**Report depth follows the plant's preference.** The `## Plant context`
+block's **Report depth** line is `summary-first` or `full` (absent means
+`full`). Summary-first puts a short summary — what was found, what it
+affects, what happens next — above the full document; it moves nothing out and
+drops nothing. Every required field is still in the document below it.
+
+**Ranked candidate root causes** — each a chain, with For and Against per link
+citing the source, a separate Confirm test and Kill test, and after the list
+the one **cheapest discriminating test**.
+
+**The drafted 8D** in the plant's or the customer's controlled template captured
+during `onboarding`. Per `../../shared/artifact-style.md`, a controlled document
+is never house-styled.
+
+**Evidence appendix** — the aligned timeline with its verified skew and residual
+uncertainty, the computed SPC view, the lot analysis, the checks that came back
+clean, the checks that could not run, and every source file cited.
+
+**The figures block** — required, and part of the appendix. Every limit, mean,
+ratio, count and cluster share stated anywhere in the output, with the
+computation it came from. A claim that something is absent — no prior NCR, no
+maintenance event in the window — carries the query that returned nothing. Per
+`../../shared/computed-figures.md`. It stays on the internal side of the
+redaction diff.
+
+**Supplier-caused flag** — when applicable.
+
+**Customer-facing redacted pack, plus the diff** — when requested. The diff,
+or the pending redaction log while the pack is blocked, records every removal
+request and every refusal.
+
+**The register row** — per `../../shared/contracts/quality-register-record.md`,
+with its key `<site>_<ncr_ref>` and the 8D fields, in the reply's summary table
+on every run, stored or not.
+
+**The Quality command-center page: the Quality Register** — open corrective
+actions, carrying the NCR and the 8D by reference, updated in place per
+`../../shared/live-dashboard.md`. Nothing is written to a system of record.
+**It is reported as updated only when the publish returned a URL in this
+run**; otherwise the page is offered in the conversation with *"The Quality
+Register was not updated: [reason]."* Never "shared." Read
+`../../shared/command-center.md`. This closes Chain 2, and is one of the two
+pages Chain 5 produces from one run (the other, Supply Chain, is
+`supplier-quote-request`'s).
+
+---
+
+## Edge cases and failure modes
+
+- **The sensor export does not cover the event window** — say so. **Do not reason
+ from adjacent data as if it were the event.**
+- **Timestamps misaligned across systems** — detect and refuse to correlate. The
+ highest-risk failure mode here, and a spurious correlation stated confidently
+ is worse than no answer.
+- **Evidence supports two candidates equally** — present both. Do not break the
+ tie artificially.
+- **No prior history exists** — say so. **Absence of recurrence is not evidence of
+ a one-off**, and `no_searchable_history` is never read as a first occurrence.
+- **The NCR's cited requirement is missing** — block, with a pointer back to
+ `ncr-writeup`.
+- **The finding is subjective** — no measured characteristic, so the SPC check
+ cannot run. Skip it and say why rather than substituting an impression.
+- **Clustering on small numbers** — three failures split two-to-one is not a
+ pattern. Say that plainly.
+- **Clustering by operator** — name the pattern, not the person. An investigation
+ that terminates on an individual has usually stopped one question early.
+
+---
+
+## Degradation
+
+Runs on exports alone. Sensor and inspection data reach the plugin as scheduled
+files in every plant; that is the designed path.
+
+| Not available | What happens |
+|---|---|
+| Historian export | No sensor evidence. Very common — most assets are not instrumented. Proceed on inspection, production and maintenance evidence and say sensor data was unavailable |
+| Inspection measurements | No SPC drift check. Reason from the condition as described |
+| The ERP (NetSuite or Infor M3) | Lot and material-receipt evidence is unavailable, so a supplier-caused determination usually cannot be reached. Say that rather than reaching it on weaker grounds |
+| Quality document library | No recurrence check. Reported as `no_searchable_history`, never as a first occurrence |
+| The plant's 8D template | Use the standard eight-discipline structure and flag that the controlled template was not available |
+| A verified clock alignment | Correlation is refused. Non-time-dependent analysis still runs and the output says which is which |
+| The `Artifact` or `ArtifactData` tools | The investigation and the 8D are unaffected. The Quality page is offered in the conversation, showing this NCR only, with "The Quality Register was not updated" |
+
+**If Limble isn't included, or no CMMS connector is live** — minor here. Maintenance history arrives in the
+same scheduled export as everything else, through `data-consolidate`, and the
+maintenance-correlation check runs on it unchanged. What changes is freshness:
+name maintenance explicitly as an export-sourced input in the evidence appendix
+rather than letting it read as live, since a repair logged after the last export
+will not be on the timeline at all.
+
+---
+
+## Chain position
+
+**Chain 2, inspection to CAPA** — step 2, from `ncr-writeup`. The chain closes on
+the 8D and its redacted customer pack.
+
+**Chain 5, supplier escape to alternate source** — step 2, emitting the flag that
+triggers `supplier-quote-request`.
+
+**Metric.** CAPA closure time; first-pass yield.
+
+**This skill's investigation time sits inside Chain 5's first segment.** That
+chain measures escape detected → supplier-caused determination → RFQ issued, and
+the middle timestamp is this skill's to stamp: **record when the supplier-caused
+determination is made**, at the moment the flag is raised for approval.
+
+That middle stamp is easy to omit and impossible to reconstruct afterwards, and
+without it the investigation time and the sourcing handoff collapse into one
+undifferentiated number — which would hide the half the plugin actually moves.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/time-alignment.md` | Step 1 — always. The highest-risk step |
+| `reference/pattern-checks.md` | Step 2 — the four computed checks and how to report them |
+| `../../shared/computed-figures.md` | Step 2 and on emit — the figures block every stated number is quoted from |
+| `reference/8d-and-candidates.md` | Steps 3 to 5 — causal chains, ranking, and the eight disciplines |
+| `reference/redaction.md` | Step 7 — what comes out, what must stay, and the diff |
+| `../../shared/contracts/ncr.md` | On load — what `ncr-writeup` hands over and when to block |
+| `../../shared/contracts/supplier-caused-flag.md` | Step 6 — the Chain 5 trigger |
+| `../../shared/live-dashboard.md` | Step 8 — finding and updating the Quality Register, and the fallback |
+| `../../shared/contracts/quality-register-record.md` | Step 8 — the fields this skill owns, and the ones it carries forward |
diff --git a/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/8d-and-candidates.md b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/8d-and-candidates.md
new file mode 100644
index 00000000..5aa515f6
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/8d-and-candidates.md
@@ -0,0 +1,124 @@
+# Candidate causal chains, and the 8D
+
+---
+
+## Part 1 — Ranked candidates, never a verdict
+
+**A confident wrong root cause is worse than a ranked list, because it closes
+the investigation.** Everyone stops looking, a corrective action gets
+implemented against the wrong mechanism, it fails, and the next occurrence is a
+recurrence after a closed CAPA — the most serious finding in the vocabulary.
+
+So the output is always **ranked candidates with supporting and contradicting
+evidence**, never one unqualified answer.
+
+### State each candidate as a chain
+
+Not a label. A chain of steps, each one carrying its own evidence:
+
+> **Candidate 1 — material hardness above nominal**
+> `LOT-77219 hardness 232 HB against 187–217 HB required` → `tool wear
+> accelerated across the run` → `true position drifted out at OP30`
+>
+> **For:** material cert on the lot reports 232 HB (cert-77219.pdf p2). All 14
+> out-of-tolerance parts trace to LOT-77219, none to LOT-77188 run on the same
+> cell that week.
+> **Against:** spindle load rose across the run on both lots, which a
+> material-only cause does not explain.
+> **What would confirm it:** hardness-test three retained parts from each lot.
+> **What would kill it:** LOT-77188 parts showing the same drift on re-measure.
+
+Chains matter because they are testable at each link, and because a link with no
+evidence behind it is where the reasoning is actually weak. A one-word cause
+hides that; a chain exposes it.
+
+### Rank by evidential strength, and say what would settle it
+
+Every candidate carries **the test that would confirm it and the test that would
+kill it.** That is what turns a ranked list into a plan — the quality engineer
+picks the cheapest discriminating test rather than working the list top-down.
+
+**Where two candidates are supported equally, present both.** Do not break the
+tie artificially to produce a cleaner-looking answer. A stated tie is a real
+finding: it says the evidence on hand cannot separate them, and it names the
+test that would.
+
+### Symptom versus root cause
+
+Keep pushing until the answer is something a system-level change could prevent.
+
+| Symptom | Root cause underneath it |
+|---|---|
+| The operator misread the print | Two revisions were in circulation and the shop copy was uncontrolled |
+| The tool was worn | The tool-change interval was set for a different material |
+| The gage read wrong | Calibration lapsed and nothing flagged it |
+
+The left column tells you who to talk to. The right column tells you what to
+change so it cannot happen again — which is what D7 needs.
+
+---
+
+## Part 2 — The 8D
+
+Eight disciplines. Many customers, especially in automotive and aerospace,
+contractually require this format, which is precisely why it is a good drafting
+target: **it is a fixed shape.**
+
+| | Discipline | Drafted from |
+|---|---|---|
+| D1 | Team | Names from the NCR — who found it, who owns quality — as a proposed team the owner edits |
+| D2 | Problem description | The NCR: quantified what, where, when, how many, against which requirement |
+| D3 | Interim containment | The NCR's containment plan, by location, with what has already been done |
+| D4 | Root cause | The leading candidate **with its ranking and contradicting evidence intact** |
+| D5 | Chosen corrective actions | Actions that address D4 specifically, each traceable to the link in the chain it breaks |
+| D6 | Implement and verify | **Structured placeholder.** Needs a real-world outcome |
+| D7 | Prevent recurrence | The system-level change so the class of problem cannot return |
+| D8 | Close and recognize | **Structured placeholder.** Needs human sign-off |
+
+### D6 and D8 stay empty on purpose
+
+They require things that have not happened yet: proof that the action worked,
+and a person signing their name. **Leave them as structured placeholders with
+the fields laid out** — never pre-filled, never with plausible text a reviewer
+might skim past and accept.
+
+An 8D with a drafted D6 is a false record of verification, and in an audit it is
+much worse than an incomplete one.
+
+### D4 keeps its uncertainty
+
+The temptation is to flatten the ranked candidates into a single confident D4
+because that is what the form looks like it wants. Resist it.
+
+Where the leading candidate is not clearly ahead, D4 says so and names the test
+that would settle it. A customer reading an honest D4 with a stated confidence
+and a verification plan is being told the truth about where the investigation
+stands. That is what the discipline is for.
+
+### D5 traces to D4, link by link
+
+Each corrective action names **which link in the causal chain it breaks.** An
+action that does not attach to a link is not a corrective action, it is an
+improvement — worth doing, but it belongs somewhere else, and mixing the two is
+how a CAPA closes without fixing anything.
+
+### D7 is where recurrence gets prevented
+
+D5 fixes this problem. D7 stops the class of problem. Incoming hardness
+verification on that material, a controlled-print process, a calibration alarm
+that actually fires — the change that means the mechanism cannot reach a part
+again.
+
+Where the recurrence check found a prior CAPA that failed, **D7 must address why
+the earlier fix did not hold**, not simply restate it. Proposing the same action
+that already failed once is the single most predictable way for this document to
+be rejected.
+
+---
+
+## The template
+
+The 8D goes to a customer against a contractual format. Use the plant's or the
+customer's own template captured during `onboarding`, and per
+`../../../shared/artifact-style.md`, **never restyle a controlled document into
+the house look.** Styling it would make it wrong, not nicer.
diff --git a/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/pattern-checks.md b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/pattern-checks.md
new file mode 100644
index 00000000..99ecf77a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/pattern-checks.md
@@ -0,0 +1,114 @@
+# The pattern checks — computed, never eyeballed
+
+**Every check on this page is calculated in code, and the skill interprets the
+computed result.**
+
+This is not a stylistic preference. A statement that a process "was drifting,"
+asserted from having looked at a data file, is exactly the claim a quality
+manager will test first, and it is the fastest available way to lose their
+trust. They have a control chart. If yours disagrees with theirs and you cannot
+show the arithmetic, you are finished in that room.
+
+So: compute the control limits, compute the group comparisons, run the run
+rules, and then say in plain language what came out.
+
+---
+
+## 1. SPC drift on the relevant characteristic
+
+Plot the measured characteristic across the run and the runs preceding it,
+against computed control limits.
+
+**The point of SPC is to catch the process that is fully in spec and clearly
+heading out.** A run where every part passed but the last forty measurements sat
+above the centreline and trending is a different finding from a single bad part,
+and no individual inspection would ever flag it.
+
+Apply the standard run rules rather than only checking for out-of-limit points:
+a run of consecutive points on one side of the centre, a sustained trend, points
+beyond two sigma. Say which rule triggered.
+
+**Print the chart's numbers, every time.** Centreline, UCL, LCL, the basis
+(individuals or X-bar, n points, which runs), and the run rule with its result
+are five required rows in the figures block. They are printed when nothing
+drifted: "UCL 0.00207, no point beyond, no run rule fired" is the evidence that
+the check ran. A response that says "drift was checked" and shows no limit has
+not shown its work.
+
+**Control limits are not specification limits.** Confusing the two is the most
+common error in this area, and it goes both ways: a process can be inside spec
+and out of control, or in control and producing scrap. Report against both and
+label which is which.
+
+Needs measured values. Where the NCR carries `is_subjective: true` or no
+measurements, **skip this check and say why** rather than substituting a
+qualitative impression for it.
+
+---
+
+## 2. Clustering
+
+Do the failures group by something? Compute the comparison; do not eyeball a
+table.
+
+| Group by | What it would point at |
+|---|---|
+| Material lot | The supplier. This is the signal that routes into Chain 5 |
+| Shift | Training, staffing, a handover, or an environmental swing overnight |
+| Operator | Training or a work-instruction gap. Handle with care — see below |
+| Machine or cell | Equipment condition, tooling, or a setup |
+| Position relative to a tool change | Tool wear, which usually also shows as a trend rather than a cluster |
+
+**State the base rate alongside the cluster.** Eleven of fourteen failures on
+night shift means nothing if night shift ran eighty percent of the parts. This
+is the single most common way a clustering claim turns out to be nothing, and
+computing it takes one extra division.
+
+**Report small numbers as small numbers.** Three failures split two-to-one
+across shifts is not a pattern, and saying so plainly is more useful than
+dressing it up.
+
+**On operator clustering specifically:** name the pattern, not the person's
+competence. "The operator misread the print" is a symptom. "Two revisions of the
+print were in circulation and the shop copy was not controlled" is a root cause,
+and it is the same evidence read properly. An investigation that terminates on a
+named individual has almost always stopped one question early.
+
+---
+
+## 3. Correlation with a maintenance event
+
+Was the machine serviced, adjusted or repaired shortly before the failures
+began? A repair is a change, and a change is a candidate cause — including
+because it may have been done wrong.
+
+This check depends on aligned timestamps, so it is gated on
+`time-alignment.md` verifying. Where alignment fails, this check does not run
+and the output says so.
+
+---
+
+## 4. Recurrence
+
+The NCR already carries a recurrence finding from its history search at
+creation. Read it forward rather than re-deriving it, and weight it heavily.
+
+`recurrence_prior_capa_failed` is the highest-signal input available here. It
+says a previous investigation reached a conclusion, somebody implemented a fix,
+and the problem came back anyway — which means either the earlier root cause was
+wrong, or the corrective action never really happened. Both are worth stating,
+and the earlier 8D is worth reading before proposing a new one.
+
+Where recurrence is `no_searchable_history`, that is **not** a first occurrence
+and must never be written as one.
+
+---
+
+## Reporting what did not trigger
+
+A check that ran and found nothing is evidence, and it belongs in the appendix.
+
+"Failures did not cluster by shift or by operator" is what makes the lot
+clustering meaningful. Report the checks that came back clean alongside the ones
+that did not, and report separately any check that **could not run** — those are
+three different states and collapsing them misleads.
diff --git a/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/redaction.md b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/redaction.md
new file mode 100644
index 00000000..e3389713
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/redaction.md
@@ -0,0 +1,96 @@
+# The customer-facing pack, and the redaction pass
+
+The internal 8D and the version that goes to a customer are different documents,
+and the difference has to be **visible and approved**, never applied quietly.
+
+---
+
+## What the internal 8D contains that must not leave
+
+| Category | Examples |
+|---|---|
+| Cost | Scrap value, rework hours, internal rates, the financial impact of the escape |
+| Other customers | Any other customer's name, part, program or order appearing in the evidence |
+| Internal process detail | Machine capability, cycle times, yields, supplier pricing and terms |
+| Supplier identity | Often commercially sensitive, and sometimes contractually protected |
+| Personnel | Operator and technician names. See below |
+| Other findings | Unrelated NCRs that surfaced during the history search |
+
+**Personnel names come out by default.** A customer needs to know a
+work-instruction gap existed and has been closed. They do not need the name of
+the person on shift, and once it is in a document that leaves the building
+nobody controls where it goes.
+
+---
+
+## What must survive
+
+Redaction is not summarisation, and the temptation to sand off anything
+uncomfortable produces a document that says nothing and satisfies no one.
+
+The customer keeps: the requirement that was violated, the condition found with
+its measurements, the affected quantity and the containment across the locations
+that touch them, the root cause with its confidence, the corrective and
+preventive actions, and the dates.
+
+**A recurrence stays in.** If this has happened before and the previous fix did
+not hold, the customer is entitled to know. Removing it is not redaction, it is
+misrepresentation, and it is the thing that ends a supplier relationship when it
+comes out later — as it does.
+
+---
+
+## The diff is the deliverable
+
+**Produce the redaction as a reviewable diff, not a filtered output.**
+
+**The diff also records what was asked for and refused.** "Take the bit about
+it having happened before out of the customer version" is a removal request; it
+is refused, the recurrence stays in, and the diff carries the entry: requested
+by, what, refused, why. A refusal that lives only in the chat is invisible to
+the quality owner who approves the diff and to the auditor who reads it later.
+Where the pack is still blocked and there is no diff yet, emit a "Pending
+redaction log" with the same entry now.
+
+The quality owner approves the diff, not the redacted document. The reason is
+specific: reading a clean customer version tells you nothing about what was
+taken out, and the risk in this operation runs in both directions — something
+sensitive left in, or something the customer needed removed.
+
+Show, side by side, every change with its reason:
+
+| Location | Internal | Customer version | Why |
+|---|---|---|---|
+| D2 | "480 parts, $18,400 at standard cost" | "480 parts" | Cost |
+| D4 evidence | "LOT-77219 from Example Steel" | "the implicated material lot" | Supplier identity |
+| D4 evidence | "same cell that ran 4402 for Example Medical" | "the same cell" | Another customer |
+| D3 | "Held at cell B by R. Nunes" | "Held at the cell" | Personnel |
+| D5 | unchanged | unchanged | — |
+
+**Never a silent filter.** A redaction that happens invisibly is one nobody has
+checked, and this document is going to a customer under a contractual format.
+
+---
+
+## Two things the pass must not do
+
+**Do not soften the finding.** Redaction removes information the customer should
+not have. It does not turn "the process was out of control from 08:20" into "a
+process variation was observed." The second sentence is a different claim and it
+is not true.
+
+**Do not redact into incoherence.** If removing the supplier's identity leaves
+D4 unreadable, that is a decision for the quality owner — say so in the diff and
+let them make it. Sometimes the right answer is that the customer is told a
+material supplier is implicated without being told which, and sometimes the
+contract requires the name. That is their call, not the skill's.
+
+---
+
+## The gate
+
+Nothing customer-facing leaves without the quality owner reviewing the diff and
+approving it. This is Chain 2's closing approval gate.
+
+The redacted pack is a draft, produced in the customer's controlled template,
+handed to a person. It is not sent.
diff --git a/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/time-alignment.md b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/time-alignment.md
new file mode 100644
index 00000000..f375a53a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/root-cause-capa/reference/time-alignment.md
@@ -0,0 +1,105 @@
+# Time alignment — the highest-risk failure mode in the skill
+
+Getting the timeline right is most of the work in a root cause investigation,
+and getting it wrong produces a **spurious correlation stated confidently**,
+which is worse than producing nothing.
+
+This is the highest-risk correctness issue in the whole plugin, alongside
+shift boundaries. Treat it that way.
+
+---
+
+## Why it goes wrong
+
+Four systems recording the same event will disagree about when it happened:
+
+| Source | How it usually records time |
+|---|---|
+| The historian | Often UTC, often zone-naive, sampled at high frequency |
+| The MES | Usually local plant time, attributed to a shift rather than a clock |
+| The ERP | Local, but posted at transaction time rather than event time |
+| The maintenance system | Whenever the technician got round to entering it, which may be hours later or the next morning |
+
+None of them is wrong. They are answering different questions. But laid on one
+timeline without reconciliation, a bearing that failed at 14:10 sits next to a
+tolerance excursion at 18:10 and the four-hour gap disappears into a confident
+sentence about causation.
+
+**A one-hour daylight-saving offset is the classic version of this**, and it is
+invisible for exactly half the year.
+
+---
+
+## What `onboarding` already established
+
+Read from the `## Plant context` block rather than asking again:
+
+- **Per-source timezone**, and whether that source's timestamps are zone-aware
+ or naive
+- **The production-day boundary** and the cross-midnight attribution rule
+- **The observed clock skew** from the offset self-check — `onboarding`
+ cross-correlates a single event recorded in two systems and reports the
+ measured difference
+
+That last one is the useful one. A declared configuration is what somebody
+believes; the self-check result is what the clocks actually did.
+
+---
+
+## Verify, then correlate
+
+**Verify alignment before running any pattern check**, and report the result as
+part of the evidence appendix rather than as an assumption:
+
+1. Convert every source onto one zone-aware timeline. Name the zone in the
+ output.
+2. Apply the known per-source offset from the self-check.
+3. Find at least one event visible in two sources and confirm they now agree.
+ A production stop appearing in both the MES export and the historian is the
+ usual anchor.
+4. State the residual uncertainty. "Aligned to within about two minutes" is a
+ useful statement. "Aligned" on its own is not.
+
+---
+
+## Misalignment blocks correlation
+
+**When alignment cannot be verified, refuse to correlate.** Do not fall back to
+approximate matching and do not soften it with a hedge.
+
+Report what is known, which is often still a great deal:
+
+> *"I can't correlate the spindle-load trace to the inspection results. The
+> historian export carries naive timestamps and this plant's context block
+> records a 47-minute skew between the historian and the MES that has not been
+> re-checked since the export path changed in July. A 47-minute error is larger
+> than the window I'd be reasoning inside, so any correlation I drew would be
+> unsafe.*
+>
+> *What I can still tell you: the lot clustering holds regardless of timing —
+> all 14 failures trace to LOT-77219 and none to LOT-77188. That analysis does
+> not depend on the clocks."*
+
+That answer is more useful than a correlation, because it says which conclusions
+survive and which do not.
+
+---
+
+## Shift boundaries are part of this
+
+A cross-midnight shift belongs to one production day, and which one is a
+per-plant rule captured during `onboarding`.
+
+Get it wrong and clustering by shift silently inverts: night-shift events land
+on the wrong day, and the pattern check reports a difference between shifts that
+is really a difference in bookkeeping. **State the boundary rule in the evidence
+appendix**, so the quality manager can check it against what they know.
+
+---
+
+## An observed skew is itself a finding
+
+If the alignment check turns up a drift nobody knew about, that is worth
+reporting to their IT independently of this investigation. A historian running
+several minutes off has been quietly corrupting every correlation anyone has
+drawn from it, including the ones drawn by hand in spreadsheets.
diff --git a/plugins/claude-for-manufacturing/skills/supplier-escape-to-alternate-source/SKILL.md b/plugins/claude-for-manufacturing/skills/supplier-escape-to-alternate-source/SKILL.md
new file mode 100644
index 00000000..51ec7362
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-escape-to-alternate-source/SKILL.md
@@ -0,0 +1,205 @@
+---
+name: supplier-escape-to-alternate-source
+description: "Runs the cross-area chain from a nonconformance traced to purchased material through to an alternate-source RFQ: writes the NCR and its containment, establishes root cause against the supplier rather than the process, records the corrective action, then builds the sourcing package with a response format that makes the returned bids comparable. Use when someone says \"run the supplier escape chain,\" \"a supplier caused this, find us an alternate,\" \"supplier escape to alternate source,\" or asks to source around a supplier who caused a defect."
+compatibility: "Requires none. Chains ncr-writeup, root-cause-capa and supplier-quote-request. Reads Microsoft 365 and the ERP (Oracle NetSuite or Infor M3) where connected; runs on pasted findings, uploaded drawings and file exports with no connector. A supplier-caused determination needs a human owner before it acts, and nothing reaches a supplier without release."
+---
+
+# Supplier-Caused Escape to Alternate Source
+
+Chain 5. `ncr-writeup` → `root-cause-capa` → `supplier-quote-request`.
+
+**The plugin's cross-area proof point.** A quality finding automatically
+starting a sourcing action essentially never happens today, because quality and
+purchasing live in different systems and different departments. That handoff is
+the whole point of this chain.
+
+If a part has exactly one qualified supplier and that supplier has a quality
+problem, production stops. Sourcing an alternate is insurance, and the value is
+in starting early: qualifying one takes weeks to months and nothing here
+shortens that.
+
+**Quick start**
+
+```
+→ A nonconformance traced to purchased material starts it
+→ Root cause established against the SUPPLIER, not the process
+→ Gate 1: a supplier-caused determination is a commercial claim. It needs an owner
+→ Corrective action recorded
+→ Build the alternate-source RFQ. Response format forces comparable bids
+→ Gate 2: nothing outbound without release
+→ THREE timestamps, not two. The middle one cannot be reconstructed later
+```
+
+---
+
+## Inputs
+
+| Input | Source | Form |
+|---|---|---|
+| The nonconformance | Inspector notes, an inspection export, a customer complaint | Conversation, M365, pasted |
+| Drawing and specification | M365 document library | PDF |
+| Everything else | Whatever the three member skills read | See each skill |
+
+---
+
+## The four steps
+
+**1. A nonconformance traced to purchased material starts it.** `ncr-writeup`
+writes it against its requirement, scopes the suspect quantity, and places every
+part across the five containment locations. Where containment finds parts at or
+past a customer, the escape notification drafts automatically against its
+contractual clock.
+
+**2. Root cause is established against the supplier rather than the process**,
+through `root-cause-capa`. Lot clustering is the signal that points here: do
+the failures group by material lot rather than by shift, operator or machine?
+
+**Gate 1** — a supplier-caused determination is a commercially significant
+claim. It says a named vendor caused a defect and it starts a search for an
+alternate source. It needs a human owner.
+
+**3. Corrective action is recorded** — the 8D, with D7 addressing the
+system-level change.
+
+**4. Build the RFQ package for an alternate source** through
+`supplier-quote-request`: the drawing and specification at the verified current
+revision, the demand picture, the quality clauses, the commercial terms, and a
+**response schedule that forces comparable bids**.
+
+**Gate 2** — nothing goes outbound until a person releases it.
+
+**The chain ends at release; the sourcing event does not.** After it,
+`supplier-quote-request` carries the event on: one email draft per supplier
+for the buyer to send, response tracking and chases, the returned bids read
+into one shape and compared, and a recommendation. The buyer decides, and the
+skill records who and when. Nothing there is a third gate of this chain.
+
+---
+
+## Approval gates
+
+| Gate | Where | What it protects |
+|---|---|---|
+| 1 | After step 2 | The supplier-caused determination has a named human owner before it acts |
+| 2 | Before step 4 sends | Nothing reaches a supplier unreleased |
+
+The flag carries its own `approval_state`, and `supplier-quote-request`
+**checks the gate** rather than assuming the flag's existence implies it. An
+unapproved flag is reported as a finding that needs an owner, not acted on.
+
+---
+
+## Three timestamps, not two
+
+The chain's headline metric is **time from escape to alternate-source RFQ
+issued**, and it cannot be owned by one skill: root cause analysis sits in the
+middle of that window and can take days or weeks. So it is measured in two
+segments, which needs three stamps.
+
+| Stamp | Written by | On |
+|---|---|---|
+| `escape_detected_at` | `ncr-writeup`, when containment first places parts at or past a customer | `ncr.md` |
+| `determination_made_at` | `root-cause-capa`, when the flag is raised | `supplier-caused-flag.md` |
+| `rfq_issued_at` | `supplier-quote-request`, when the package goes out | Its own sourcing record |
+
+**The middle one is the one that gets dropped, and the only one that cannot be
+reconstructed afterwards.** The chain's output says so beside the stamp, every
+run: *"determination_made_at — the middle of the three; this cannot be
+reconstructed afterwards."* A stamp with no such line is the one a later
+reader assumes could be backfilled. Without it the two segments collapse into a single
+number, and the second segment — the dead time this chain actually eliminates —
+disappears behind an investigation that legitimately takes weeks.
+
+Keeping it segmented is what makes the improvement legible. Cutting the handoff
+from two weeks to two days shows up even while the investigation still takes a
+week. One blended figure would hide which half moved.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+Two pages from one run, with different audiences:
+
+**Quality** takes the corrective action record — the NCR, the containment plan,
+the 8D. **Supply Chain** takes the supplier signal and the sourcing package —
+the RFQ, the missing-items list, the candidate suppliers with any single-source
+risk flagged. They are separate artifacts, not one page with two sections. Read
+`../../shared/command-center.md`.
+
+**The Quality side is the Quality Register.** The NCR and 8D steps of this chain
+are `ncr-writeup` and `root-cause-capa`, and each writes its row and updates the
+site's register dashboard per `../../shared/live-dashboard.md` — including the
+supplier-caused flag. This chain adds no third write. The Supply Chain page
+stays a page offered in the conversation, never part of the register.
+
+Plus the escape notification draft where parts reached a customer, and the
+cover email per supplier.
+
+---
+
+## Edge cases and failure modes
+
+- **The drawing revision in the library disagrees with the ERP** — **hard
+ stop** at step 4. Sending the wrong revision is the classic expensive error
+ this exists to prevent.
+- **ITAR or export-controlled data** — blocking gate before assembly, not
+ before sending.
+- **Only one qualified supplier exists** — flag it loudly. That is the finding,
+ and it is usually more urgent than the package it appeared in.
+- **The flag arrives unapproved** — block. Report it as needing an owner.
+- **Evidence points at the supplier but the leading candidate is something
+ else** — the flag carries `is_leading_candidate` and `competing_candidates`
+ for exactly this. Proceed as an exploratory search and label it as one.
+
+---
+
+## Degradation
+
+| Not available | What happens |
+|---|---|
+| The standard quality clause set | List the clauses found on the current part record and flag the set as **unverified** |
+| No drawing exists (a commodity or catalog item) | Switch to a specification-based request rather than blocking |
+| The ERP (NetSuite or Infor M3) | Demand picture and vendor list come from documents or are asked for, and the package says which |
+| The quality document library | Recurrence reports "no searchable history available" rather than silence |
+
+**Check the freshness of the usage and demand exports before quoting a volume
+to a supplier.** A stale export understates demand, and a supplier priced
+against the wrong annual volume returns a bid nobody can use. State the window
+each figure came from.
+
+---
+
+## Chain position
+
+**This is Chain 5 itself.** Members: `ncr-writeup`, `root-cause-capa`,
+`supplier-quote-request`.
+
+**Metric.** Escape response time, owned by `ncr-writeup`. Time from escape to
+alternate-source RFQ issued, owned in two segments: detection and investigation
+by `ncr-writeup` and `root-cause-capa`, the sourcing handoff by
+`supplier-quote-request`.
+
+**What this chain does not move: requalification lead time.** Qualifying an
+alternate takes as long as sample parts, first article inspection and PPAP
+take. What it compresses is the dead time before anyone starts.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `../ncr-writeup/SKILL.md` | Step 1, and the escape clock |
+| `../root-cause-capa/SKILL.md` | Steps 2 and 3 |
+| `../supplier-quote-request/SKILL.md` | Step 4, and both hard stops |
+| `../../shared/contracts/supplier-caused-flag.md` | The only cross-area handoff in the plugin |
+| `../../shared/command-center.md` | The two pages, and why neither is a write |
diff --git a/plugins/claude-for-manufacturing/skills/supplier-quote-request/SKILL.md b/plugins/claude-for-manufacturing/skills/supplier-quote-request/SKILL.md
new file mode 100644
index 00000000..361671bc
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-quote-request/SKILL.md
@@ -0,0 +1,412 @@
+---
+name: supplier-quote-request
+description: "Builds the RFQ package that goes out to suppliers — drawing and specification at the verified current revision, the demand picture, the quality clause list, commercial terms, and a mandated response format that makes the returned bids comparable by construction. Lists everything missing. Hard stops on a revision mismatch or restricted technical data. Then runs the supplier loop: candidates from the approved supplier list with unapproved and single-source flagged, one email draft per supplier for the buyer to send, response tracking with chase drafts, returned bids read into one shape with every missing field listed, a comparison per quantity break computed in code, and a recommendation. The buyer decides; the skill records who and when. Use when someone says \"source this part,\" \"send an RFQ to suppliers,\" \"we need an alternate supplier,\" \"get quotes on this,\" \"who else can make this?\", \"chase the suppliers,\" \"compare these bids,\" or \"we're going with this supplier.\""
+compatibility: "Requires none. Reads the ERP (Oracle NetSuite or Infor M3) for the item master, usage history, vendor records and purchase-order history, and Microsoft 365 for drawings, specifications, templates and supplier replies. Runs on an uploaded drawing, pasted quantities and pasted bids with no connector. Nothing goes to a supplier, and nothing is awarded or ordered, except by the buyer."
+---
+
+# Supplier Quote Request
+
+The RFQ pointed the other way: instead of a customer asking us to quote, we are
+asking suppliers to quote us.
+
+**The quality of the package determines the quality of the bids.** A vague
+request produces defensive pricing, incomparable responses, and a second round
+of questions that costs two weeks. Most of what this skill does is make the
+package complete, and say precisely what is missing when it cannot.
+
+**Then it carries the event to a decision.** The skill drafts, tracks,
+computes and recommends. **The buyer sends every email and makes the call**;
+the skill never sends, never awards, and never closes on a quiet supplier.
+
+**Quick start**
+
+```
+→ Take the trigger: an approved supplier-caused flag, or a direct request
+→ HARD STOP: drawing revision vs ERP item master. Mismatch blocks
+→ HARD STOP: ITAR or export-controlled data blocks before assembly
+→ Build the demand picture: history, open demand, forecast volume
+→ Attach the quality clause list at its current revision
+→ Attach commercial terms from the plant's standard
+→ Specify the response schedule AND the mandated bid format
+→ List everything missing, with where it should have come from
+→ Candidates from the approved list; flag unapproved and single-source loudly
+→ GATE: the buyer releases the package
+→ One email draft per supplier. GATE: the buyer sends. Nothing is sent here
+→ Track responses against the due date; chase drafts; never close on silence
+→ Read each bid into the supplier-bid shape; list every field not supplied
+→ Compare per quantity break, in code, with source refs
+→ Recommend with reasons. The buyer decides; record who and when
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| Trigger — a supplier-caused nonconformance | `root-cause-capa` | `../../shared/contracts/supplier-caused-flag.md` |
+| Part number, revision, current spec | ERP item master (NetSuite or Infor M3, `../../shared/erp-connectors.md`), M365 drawing library | Connector and documents |
+| Drawing and specification files | M365 SharePoint library | PDF |
+| Quantities and forecast volume | ERP historical usage and open demand | Connector |
+| Current and alternate supplier list | ERP vendor records | Connector |
+| Current price and terms | ERP purchase-order history | Connector |
+| Standard quality clauses and terms | `## Plant context`, captured during `onboarding` | Config and M365 template |
+| Approved suppliers by commodity | `### Approved suppliers` in `## Plant context` | Config |
+| Trigger — an outside process or bought-in item on a quote | `quote-build` or `rfq-to-quote`, or the estimator | Inquiry ref, line, operation |
+| Sourcing event state | The `## Sourcing events` block on the Open work page, or a table the buyer pastes | Open work page |
+| Returned bids | Supplier emails (M365, read-only), PDFs, spreadsheets, pasted text | Documents |
+
+**Blocks on an unapproved flag.** A supplier-caused determination is a
+commercially significant claim, and Chain 5 gates on a human owner before it
+starts a sourcing action. An unapproved flag is reported as a finding that needs
+an owner, not acted on.
+
+**Blocks on a flag with no `part_revision`.** The revision check below cannot
+clear without one.
+
+---
+
+## Workflow
+
+### Step 1 — Take the trigger
+
+Either the approved supplier-caused flag from Chain 5, or a direct request to
+source a part. Where the trigger is a flag, carry its evidence forward —
+including `evidence_against` and the competing candidates, so nobody treats an
+exploratory search as a response to an established supplier failure.
+
+### Step 2 — Assemble the technical package, and verify the revision
+
+Pull the drawing and specification, and **verify the revision against the ERP
+item master.**
+
+**A revision mismatch is a hard stop, not a warning.** Read
+`reference/hard-stops.md`. Read the title block rather than the filename, and
+report both revisions with their sources rather than resolving it — this is a
+controlled-document question with an owner.
+
+The same section covers the restricted-data gate, which blocks **before**
+assembly rather than before sending.
+
+### Step 3 — Build the demand picture, and state the delivery requirements
+
+Historical usage over a stated window, open demand, and forecast volume clearly
+labelled as a forecast. Suppliers price 100 a year very differently from 10,000
+a year.
+
+**Never inflate a forecast to get a better price.** Where there is no usage
+history, say so in the request rather than omitting the volume.
+
+**Total the usage in code.** Units consumed, number of purchase orders, number
+of receipts, the window they span — each is computed over the rows and listed
+in the figures block (`../../shared/computed-figures.md`) with its filter and
+its as-of date. A supplier prices against this number; it is not one to retype.
+**The demand picture is three labelled figures, each with its window and
+as-of date, or an explicit absence:**
+
+| Figure | Example | If absent |
+|---|---|---|
+| Historical usage | *1,200 lb over 2026-07-20 to 2026-08-28, as of the 2026-08-31 export* | *no purchase or receipt for this material in the window searched, 2026-06-01 to 2026-08-31* |
+| Open demand | *2 open work orders, 440 pieces, due 2026-09-14, as of the 2026-08-31 export* | *no open work orders or sales orders for this part in the export* |
+| Forecast | *EAU 5,000, labelled forecast, from the customer's RFQ* | *no forecast supplied* |
+
+A package that states only the absence of usage has no demand picture; a
+supplier cannot price against a missing row.
+
+**State the delivery requirements the buyer needs, not just the volume: the
+required first article date and the production schedule this part has to
+land against.** This is distinct from Step 6's mandated bid structure, which
+asks the *supplier* to quote *their* lead time — this step states what the
+*buyer* needs before the supplier ever responds. Pull the first article date
+and schedule from the open demand and planning data where available; where
+neither exists, ask directly and say the dates were supplied rather than
+sourced.
+
+### Step 4 — Attach the quality clause list at current revision
+
+Certifications, material certs, first article inspection, PPAP submission level,
+certificate of conformance, right of access, change notification, retention and
+lot traceability.
+
+**Revision matters as much here as on the drawing.** Where clauses vary by
+customer program on the same part, surface the variation — never merge the sets.
+Read `reference/quality-clauses.md`.
+
+### Step 5 — Attach commercial terms
+
+From the plant's configured standard: payment, freight, packaging, liability,
+tooling ownership.
+
+### Step 6 — Specify the response schedule and format
+
+A response due date, and a **mandated bid structure**: unit price at each
+quantity separately, tooling priced separately, tooling ownership, lead time
+split into first article and production, minimum order quantity, currency,
+validity period, and exclusions listed rather than implied.
+
+**This is the highest-leverage line in the whole package.** Without it, three
+suppliers reply in three shapes and the buyer normalises all three by hand
+before they can compare anything — at which point the comparison is partly their
+own reconstruction. Read `reference/bid-comparability.md`.
+
+### Step 7 — List what is missing
+
+Every element of a complete package that could not be located: what it is, why
+it matters, and where it should have come from.
+
+**This is the skill's most-used output.** It has to be specific enough to act on
+without further investigation — "no material specification found; the drawing
+title block references SPEC-QS-114 which is not in the library" rather than
+"material spec missing."
+
+### Step 8 — Identify candidate suppliers
+
+From the `### Approved suppliers` table in `## Plant context`, matched on the
+commodity with the match stated, plus ERP vendors that fit it, plus the
+incumbent for comparison, each with its requalification path. **A vendor not
+on the approved table is listed as *not confirmed approved*.** Read
+`reference/supplier-loop.md`.
+
+**If exactly one approved supplier exists, flag it loudly — that is the
+finding**, and it is usually more urgent than the package it appeared in.
+
+**The buyer then releases the package.** Steps 9 to 13 follow, often across
+several conversations.
+
+### Step 9 — Draft one email per supplier
+
+One draft per supplier, addressed to that supplier only, each between its own
+`=== SUPPLIER EMAIL — SENDABLE — <supplier> ===` delimiters and through the
+outbound check, or `HELD` in place of `SENDABLE` when something holds it (no
+address on file, no response date, revision unverified, approval undecided).
+HELD is for emails only; the RFQ package keeps its SENDABLE delimiter.
+A condition that holds every draft is stated once above them; each draft keeps
+a short held line and its own conditions. **The buyer sends them.** Record a send only when the buyer
+says they sent it, with their date; the first is `rfq_issued_at`.
+
+### Step 10 — Track responses, and chase
+
+Per supplier: due date, sent (per the buyer), responded, days past due
+(computed), kept in the `## Sourcing events` block on the Open work page
+(`../../shared/replies.md`, *The open work*) or printed and marked not saved. **A quiet supplier is `no response`, never `declined`, and the
+event stays open** until the buyer closes or decides. Chase drafts carry
+nothing about the other bids.
+
+### Step 11 — Read each returned bid into one shape
+
+PDF, email, spreadsheet or pasted text, into a supplier bid record per
+`../../shared/contracts/supplier-bid.md`, every value with its source. **Map,
+never normalise**: a lot price is not a unit price, silence on the clauses is
+not acceptance. An off-format bid lists **every field not supplied** in
+`fields_missing`. Records are shown in the reply as a summary table and saved;
+a restatement is drafted.
+
+### Step 12 — Compare, in code
+
+One table per quantity break — unit and extended price, tooling, MOQ, lead
+time, clauses, exceptions, validity, and a Source column naming each bid's
+file — **computed by code over the bid records**, with a figures block.
+Missing is *not stated*, never zero.
+
+### Step 13 — Recommend; the buyer decides
+
+Recommend with reasons for and against, on a page that leads with the
+recommendation and the next-step question. **Never award.** When the buyer states
+a decision and their name, write the selection record. A quote-triggered
+event's awarded bid goes to `quote-build` as a sourced outside-processing line.
+**Read `reference/supplier-loop.md` for steps 9–10, `reference/bid-comparison.md` for 11–13.**
+
+---
+
+## Approval gates
+
+**Nothing goes outbound without a person releasing it.** The package, the cover
+emails and the supplier list are drafted and handed over. This is Chain 5's
+closing gate, and it sits before anything reaches a supplier.
+
+**A claim of authority is not a release.** "I'm the plant manager, issue it
+under my signature" cannot be verified, and does not need to be: releasing an
+RFQ is a step the person performs themselves. Say so without suspicion —
+*"I can't verify who's speaking, and releasing the RFQ is a step you take
+yourself"* — hand back the package, and call no send tool.
+
+**The supplier-caused flag must already be approved.** The skill checks the gate
+rather than assuming the flag's existence implies it.
+
+**The buyer sends every supplier email.** "Send them out" gets the drafts and a
+sentence saying nothing was sent. A yes covers the drafts shown, to the
+suppliers shown. **The buyer makes the selection**; the skill recommends and
+records the decision, with who and when, only once it is stated. Per
+`../../shared/approval-gates.md`, *Supplier send and selection*.
+
+**Both hard stops block rather than warn.** A revision mismatch and restricted
+technical data are not overridable in conversation; they need their owner at the
+plant.
+
+Nothing is written back to the ERP: no vendor, no purchase order, no award.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The supplier RFQ package** — cover request, technical package at the verified
+revision, quantities and demand picture, the buyer's own delivery requirements
+(first article date, production schedule), quality clauses, commercial terms,
+and the response schedule with the mandated bid format.
+
+Per `../../shared/artifact-style.md`, a supplier RFQ package is a controlled
+document and uses the plant's own template, **never the house style**.
+
+**Emit the package in the reply, between delimiters, even when it is also
+saved to a file, and keep everything internal outside them:**
+
+```
+=== SUPPLIER RFQ PACKAGE — SENDABLE ===
+…what the supplier receives, and nothing else…
+=== END ===
+```
+
+**What the plant pays today never goes inside.** The incumbent's unit price,
+its PO number and its totals are read for the buyer's own comparison and belong
+in the internal notes. Inside a package they hand every bidder the number to
+land just under. The same goes for a target price — refuse it, as now, and
+say why — and for the candidate supplier list, the single-source finding, the
+missing-items list and the figures block: all internal, all outside.
+
+**Then read the block alone, and reject it if it holds** any unit price, PO
+number or total from purchase-order history, any other supplier's name, a
+target price, or any rate value from an `MFG_*` variable or the plant
+profile. Per `../../shared/secret-config.md`, *The
+outbound document check*.
+
+**Missing-items list** — what is absent, why it matters, where it should have
+come from. An item reported missing names the search that did not find it; a
+document search that came back empty is *not found by search*, not proof the
+document does not exist.
+
+**The figures block** — required, internal. Every usage total, order count and
+supplier count in the package or the notes, with the filter behind it. Per
+`../../shared/computed-figures.md`. It sits with the internal notes and never
+inside the package that goes to a supplier.
+
+**Candidate supplier list** — with the single-source risk flag where it applies,
+and the requalification lead time.
+
+**Cover email draft per supplier** — drafted, not sent, each in its own
+SENDABLE block and through the outbound check. Chase and restatement drafts the
+same way.
+
+**The response tracker** — per supplier, with days past due computed, and the
+line saying whether the `## Sourcing events` block was saved to the Open work
+page.
+
+**Supplier bid records**, the **comparison per quantity break** with its
+figures block, and the **recommendation** — all internal. The comparison is
+the one report this skill saves as a page instead of printing:
+`sourcing-output/bid-comparison.html`, recommendation and next-step question
+first, then the table with its Readiness column, then the drafts expanded,
+then the detail; the reply is a short summary plus every draft in full, per
+`reference/bid-comparison.md`. With no way to write a file, print the
+whole comparison in the reply. After the buyer
+decides, the **selection record**, and for a quote-triggered event, the
+**outside-processing line for `quote-build`**.
+
+**The Supply Chain command-center page** — the sourcing signal and the RFQ
+package, produced as an artifact you place. Nothing is written to a system.
+Read `../../shared/command-center.md`. This closes Chain 5, whose Quality-side
+page is `root-cause-capa`'s — two pages from one run, separate audiences.
+
+---
+
+## Edge cases and failure modes
+
+- **Drawing revision in the library does not match the ERP** — hard stop. The
+ failure mode this skill exists to prevent.
+- **No drawing exists** — a commodity or catalogue item. Switch to a
+ specification-based request rather than blocking.
+- **Only one qualified supplier** — flag loudly. That is the finding.
+- **Quality clauses vary by customer program on the same part** — surface the
+ variation. Merging fails in both directions.
+- **ITAR or export-controlled data in scope** — blocking gate, before assembly.
+ Do not assess supplier eligibility; route it to its owner.
+- **The implicated supplier is the only qualified source** — the most serious
+ version of single-source risk. Say so first, before the package.
+- **Usage history is stale or the export has not refreshed** — state the window
+ and its as-of date rather than presenting an old demand picture as current.
+- **A supplier misses the due date** — `no response`, days past due, a chase
+ draft. The event stays open; the comparison says the bid is missing.
+- **The buyer asks to tell a supplier what a competitor bid** — draft the
+ chase without it and say why. Same leak as the incumbent's price.
+- **Bids in two currencies** — no conversion, not ranked against each other.
+- **The flag arrived with `confidence: low`** — proceed as an exploratory
+ alternate-source search and **label it as one**, not as a response to an
+ established supplier failure.
+
+---
+
+## Degradation
+
+Runs on an uploaded drawing and pasted quantities with no connector.
+
+| Not available | What happens |
+|---|---|
+| The ERP (NetSuite or Infor M3) | No item-master revision to check against, so the revision comparison **cannot clear** — report it as unverified and treat the package as blocked until someone confirms the revision. Ask for usage volumes directly. **Candidates come from the Plant context approved table only**, by ID, with names asked for where missing |
+| The approved supplier table | Candidates from ERP vendors only, **every one flagged not confirmed approved**. Neither source: suppliers the buyer names, labelled the same |
+| M365 document library | Ask for the drawing and specification as uploads. Everything downstream is unchanged |
+| M365 mail | Drafts are handed back, as always; nothing is sent either way. Bids are pasted or uploaded, and no reply is looked for |
+| Memory | The tracker is printed each run and not stored; say so, and ask for it pasted back next time |
+| The standard clause set from `onboarding` | List the clauses found on the current part record and **flag the whole set as unverified.** Do not assemble a plausible list from what plants usually require |
+| Purchase-order history | No current price for comparison. Say so rather than sourcing blind to what is being paid today |
+| The plant's RFQ template | Use a neutral package structure covering every section above, and flag that the controlled template was unavailable |
+
+---
+
+## Chain position
+
+**Chain 5, supplier-caused escape to alternate source** — the final step,
+triggered by `root-cause-capa`: a quality finding starting a sourcing action,
+the cross-area handoff that essentially never happens today. **Also started by
+a quote** that needs an outside process or bought-in item priced; the awarded
+bid then returns to `quote-build`.
+
+**Metric.** Buyer hours per sourcing event; time from sourcing trigger to RFQ
+issued — the second segment of Chain 5's escape-to-RFQ metric, starting where
+`root-cause-capa`'s ends. **Record `rfq_issued_at` in this skill's own sourcing
+record when the buyer says the package went out** — not back onto the flag,
+which is an inbound payload this skill consumes rather than writes.
+
+Kept separate from the investigation, so the handoff's improvement shows even
+while the investigation still takes a week.
+
+**Not claimed: requalification lead time.** Samples, first article and PPAP
+take what they take.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/hard-stops.md` | Step 2 — the revision check and the restricted-data gate |
+| `reference/bid-comparability.md` | Steps 3 and 6 — the demand picture and the mandated response format |
+| `reference/quality-clauses.md` | Steps 4 and 8 — the clause list, program variation, and supplier candidates |
+| `../../shared/contracts/supplier-caused-flag.md` | Step 1 — what to check before acting on the trigger |
+| `../../shared/secret-config.md` | On emit — the outbound document check on the delimited package |
+| `../../shared/approval-gates.md` | At the release gate — why an authority claim is not a release |
+| `../../shared/computed-figures.md` | Steps 3 and 12, and on emit — the figures block, and how to state an absence |
+| `reference/supplier-loop.md` | Steps 8 to 10 — candidates, one draft per supplier, the send gate, tracking and chasing |
+| `reference/bid-comparison.md` | Steps 11 to 13 — ingest, off-format bids, the comparison, the recommendation and the selection record |
+| `../../shared/contracts/supplier-bid.md` | Steps 11 to 13 — the bid and selection record shapes, and what `quote-build` reads |
diff --git a/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparability.md b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparability.md
new file mode 100644
index 00000000..6adafab8
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparability.md
@@ -0,0 +1,108 @@
+# The response specification — making bids comparable by construction
+
+**The highest-leverage line in the whole package**, and the one most often left
+out.
+
+---
+
+## The problem it solves
+
+Three suppliers reply to the same request in three shapes:
+
+| Supplier | What they sent |
+|---|---|
+| A | $4.10 per piece, tooling included, 6 weeks |
+| B | $3,180 per lot of 1,000, tooling quoted separately at $8,500, "8–10 weeks ARO" |
+| C | $3.85/pc at 1,000 and $3.40 at 5,000, tooling amortized over the first order, freight collect |
+
+Nobody can compare those. The buyer spends an afternoon normalising all three
+onto one basis, guesses at the pieces that were not stated, and the comparison
+they end up with is partly their own reconstruction rather than what the
+suppliers actually offered.
+
+**Specifying the response format up front is what makes the later comparison
+honest**, rather than a normalisation exercise performed after the fact by
+somebody with an opinion about who should win.
+
+---
+
+## What to mandate
+
+### The bid structure
+
+- **Unit price at each stated quantity, separately.** Not an average, not a
+ blended rate. One line per quantity break asked for.
+- **Tooling and NRE priced separately**, never folded into the piece price. A
+ supplier who buries $8,500 of tooling in the unit price at 1,000 looks
+ expensive at 1,000 and cheap at 10,000, and the buyer cannot see why.
+- **Tooling ownership stated.** Who owns it at the end matters as much as the
+ price, and it decides whether a second source is even possible later.
+- **Lead time, split into first article and production**, and stated from a
+ named event — receipt of order, receipt of tooling approval — rather than "8
+ weeks."
+- **Minimum order quantity**, which frequently turns out to exceed the quantity
+ quoted.
+- **Currency**, explicitly.
+- **Price validity period.**
+- **Any exclusions or assumptions**, listed rather than implied. This is where
+ the surprises live.
+
+### The commercial basis
+
+State the terms the bid must assume rather than letting each supplier assume
+their own: **Incoterms or freight basis, packaging, payment terms.** Otherwise
+one bid is delivered and another is ex-works, and the difference is invisible
+until the invoice.
+
+### The response schedule
+
+- A **due date** for the response
+- **Who to send it to**, and how
+- A **named contact** for technical questions, with the note that answers given
+ to one bidder will be shared with all — which is both fair and the thing that
+ stops a scope drift nobody sees
+
+---
+
+## Say what happens to a non-conforming bid
+
+A required format that carries no consequence is a suggestion.
+
+State plainly that a bid returned in a different shape will be sent back for
+restatement rather than normalised on the buyer's side. Most suppliers comply
+immediately, because the request is reasonable and the alternative costs them
+time too.
+
+---
+
+## Where the quantities come from
+
+The demand picture is what makes the bid meaningful, and it is worth being
+accurate rather than optimistic.
+
+- **Historical usage**, over a stated window, from the ERP
+- **Open demand** currently on the books
+- **Forecast or estimated annual usage**, clearly labelled as a forecast
+
+**Suppliers price 100 a year very differently from 10,000 a year.** A quantity
+quoted without a volume context gets priced defensively, and the plant pays for
+that pessimism on every part.
+
+**Never inflate the forecast to get a better price.** It produces a price the
+supplier cannot hold, and the renegotiation arrives at the worst possible moment
+— usually once the alternate source has already been qualified and the leverage
+has moved.
+
+Where usage history is unavailable or the part is new, **say so in the request**
+rather than omitting the volume. "New part, no usage history, initial order 500,
+annual volume not yet established" is a statement a supplier can price against.
+Silence is not, and they will assume the worst.
+
+---
+
+## When the bids come back
+
+Each returned bid is read into `../../../shared/contracts/supplier-bid.md`,
+which mirrors the bid structure above field for field. A field the supplier did
+not supply is listed in `fields_missing`, and the restatement request names it.
+Read `bid-comparison.md`.
diff --git a/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparison.md b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparison.md
new file mode 100644
index 00000000..e1445a1d
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/bid-comparison.md
@@ -0,0 +1,214 @@
+# Bids — ingest, compare, recommend, record the decision
+
+Steps 11 to 13. The returned bids go into one shape, the comparison is
+computed from that shape, and the buyer decides. The shape is
+`../../../shared/contracts/supplier-bid.md`; the format the package asked for
+is `bid-comparability.md`.
+
+---
+
+## Step 11 — Ingest each bid
+
+Bids arrive as a PDF, an email, a spreadsheet, or pasted text. Read each into a
+supplier bid record, **one per response**, every value with its `source_ref`.
+
+**Map, never normalise.** The record holds what the supplier stated:
+
+- **A lot price is not a unit price.** *"$410 for 200"* goes in `as_quoted`
+ and `unit_price` stays null. Dividing it is the buyer's afternoon of
+ normalising that the mandated format exists to remove.
+- **Tooling folded into the piece price** is `tooling_in_unit_price: true`,
+ not a tooling price of zero.
+- **"About a week"** is not a lead time from a named event. Keep the words,
+ leave the split fields null.
+- **Silence on the quality clauses** is `not_stated`, never accepted.
+- **No currency stated** is null, never assumed.
+- **A break the package asked for and the supplier did not price** stays on the
+ record with nulls. It is the gap a buyer most needs to see.
+
+### Off-format bids
+
+A bid is `off_format` when any mandated field is missing or in another shape.
+**List every field not supplied in `fields_missing`, by name**, by checking
+each mandated field in turn — unit price at each break, currency, lead time
+first article and production from a named event, tooling price or a statement
+that none is needed, tooling ownership, MOQ, validity, quality clause
+acceptance — not by noticing what stands out.
+
+Then draft a restatement request for the buyer to send, per
+`bid-comparability.md`, *Say what happens to a non-conforming bid*: it names
+the missing fields and asks for the bid in the package's format. It goes
+between `=== SUPPLIER EMAIL — SENDABLE — <supplier> ===` (or `HELD`, per
+`supplier-loop.md`) and `=== END ===`, and the outbound check there applies — **nothing about other bids**.
+A restated bid gets a new `bid_ref` that `supersedes` the old one.
+
+A bid that claims to be from a supplier not on the candidate list is ingested,
+marked `not_confirmed_approved`, and flagged.
+
+**Show every record in the reply** as the summary table in
+`../../../shared/replies.md` — supplier, source file, the break prices as
+quoted, `fields_missing` by that name — and save the full record. The buyer
+reads the reply, and a record that exists only in a file nobody opened has not
+been shown; a raw YAML block is shown but not read.
+
+---
+
+## Step 12 — Compare, in code
+
+**Every figure in the comparison is computed by code over the bid records**
+and printed from the result, with a figures block per
+`../../../shared/computed-figures.md`. No price is retyped from a PDF into the
+table.
+
+### One table per quantity break
+
+| Supplier | Approval | Unit price | Extended (unit × qty) | Tooling | MOQ | Lead time FA / production | Clauses | Exceptions | Validity | Readiness | Source |
+|---|---|---|---|---|---|---|---|---|---|---|---|
+
+- **Readiness** is the derived status from step 13, *ready for buyer review*
+ or *provisional* with what is open, in the same table.
+ There is no second full table repeating approval, readiness or open
+ requirements; the per-prerequisite evidence sits in the detail below,
+ collapsible, never removed.
+
+- **Extended** is unit price × break quantity, computed. A bid with no unit
+ price at that break reads *not quoted per unit*, with `as_quoted` beside it;
+ where a lot price is shown divided, it is labelled *derived from a lot price,
+ not quoted* and is not ranked.
+- **First-order total** — extended plus one-time tooling — gets its own column
+ where any bid carries tooling, labelled *includes one-time tooling*. A bid
+ that is cheaper per piece and dearer once its tooling is counted is the
+ finding the separate tooling line exists to show.
+- **MOQ above the break quantity** is flagged on that row: the price does not
+ buy that quantity.
+- **A Source column on every table, naming each bid's file and page, sheet or
+ email** — `bid_example-finishing_2026-10-22.txt`, not "the bid files". It is not
+ optional: a figure a buyer cannot trace back is one they will re-key.
+- **Different or unstated currencies are not ranked against each other.** No
+ conversion; each stays as stated.
+- **Absent is not zero.** A missing tooling price is *not stated*, not $0. A
+ missing lead time is not the fastest.
+
+Below the tables: who has not responded, with days past due (from
+`supplier-loop.md`), and every off-format bid with its `fields_missing`.
+
+The comparison is internal. It never goes inside any SENDABLE block.
+
+---
+
+## Step 13 — Recommend, then record the buyer's decision
+
+### Recommend, never award
+
+Recommend one bid per break, or one overall, **with the reasons and what argues
+against it**: price at each break, first-order total, lead time against the
+buyer's first article date from step 3, clause exceptions, approval status, and
+single-source exposure. A `not_confirmed_approved` supplier may be
+recommended only with its requalification named as a condition. A comparison
+missing a supplier says so beside the recommendation.
+
+**Ready for buyer review is derived, never a checklist item of its own.** Four
+prerequisites are judged separately for each bid, each with its evidence:
+
+1. **Cost comparable**: priced per unit at the break, currency stated, tooling
+ and MOQ known or flagged.
+2. **Supplier approved** for this process, or its requalification named.
+3. **Delivery evidenced**: a lead time that meets the first article date.
+4. **Technical and quality terms accepted**: every mandated clause and the
+ spec accepted as written. A clause the bid is silent on is *not stated*,
+ neither accepted nor refused; a clause the bid takes exception to is open
+ until the buyer accepts the exception. Either keeps the bid provisional.
+
+A bid is *ready for buyer review* only when all four hold; otherwise it is
+*provisional*, with what is open named (*"Valley: provisional, change
+notification clause not stated"*). The buyer's approval is a fifth thing,
+recorded only when given, and never counted as a prerequisite for itself.
+
+**The recommendation is not a decision.** The reply ends with the next-step
+question below, which hands it back to the buyer. "Pursue Example Finishing" is a
+next step, not a selection: a selection is recorded only when the buyer says
+they are going with a bid, with their name. Never write *awarded*, *selected*, *chosen* or *placed* about a bid
+the buyer has not chosen, and never draft an award notice before they have.
+
+### The comparison page leads with the recommendation
+
+The comparison is saved as `sourcing-output/bid-comparison.html` (house style,
+internal), one file saved over the last run's, with the event reference in its
+title, and the reply names that path. In order:
+
+1. **The provisional recommendation**: the bid, the reason, the main tradeoff,
+ and every requirement still open before an award.
+2. **The next step, as a question**: *"Pursue <supplier>, look into the
+ alternatives, or ask the suppliers to clarify?"* Choosing one is a
+ preference about what to do next, never a selection or an award.
+3. **The comparison table per quantity break**, with its Readiness column.
+4. **Draft supplier emails, not sent**: expanded, one card per supplier with
+ the supplier, the recipient or `[recipient: not on file]`, the subject and
+ the full body, and its HELD or SENDABLE status per `supplier-loop.md`.
+ Never inside a collapsed section.
+5. **Detail, collapsible but never removed**: the per-prerequisite readiness
+ evidence, the figures block and calculations, the bid records summary, and
+ the sources.
+
+The reply is the short summary in `../../../shared/replies.md`, with the
+recommendation, the tradeoff, the open requirements and the next-step
+question in prose, **no tables** (the table is on the page), **plus every
+draft in full between its delimiters**: a draft is
+something the buyer sends, so it is always in the reply. A question about the
+bids ("walk me through Example Plating at 200") is answered in the reply in full. With
+no way to write a file, print the whole comparison in the reply in this order.
+
+**Looking is not choosing.** Viewing an option, switching a quantity break on
+a page, or saying which option to discuss next sends nothing, places nothing,
+and records no selection. Clarification drafts stay unsent and sit below the
+comparison and recommendation. A revised comparison keeps the earlier one
+recoverable; it never overwrites a recorded decision.
+
+### Record the decision
+
+**A decision is recorded only when the buyer states it**, after the comparison
+was on screen, naming a supplier on it: *"Go with Example Finishing at both breaks."*
+Per `../../../shared/approval-gates.md`, *Supplier send and selection*.
+
+- **Generic continuation is not a decision.** "Go ahead," "do what you think,"
+ "pick the cheapest" — the last before any comparison was shown — get the
+ comparison and the question.
+- **Ask for a name** when none was given. `decided_by` is the name the buyer
+ gives, as given; it is not verified and does not need to be.
+- **A decision against the recommendation is recorded without argument**, with
+ `follows_recommendation: false` and the buyer's reason if they gave one.
+- **Write the selection record** per the contract: who, when, which bids were
+ on screen, which suppliers had not responded — and **show it in the reply**
+ as a short summary table, with `decided_by` and `decided_at` by those names,
+ as well as saving the full record. `decided_at` is the current time with its zone; when the buyer
+ has given a date the session clock disagrees with, use their date and say the
+ time of day is not known.
+
+Then say what it is and is not: *"Recorded: Example Finishing, decided by Dana
+Whitfield, 27 Oct 10:05. No purchase order has been raised and nothing has gone
+to any supplier."* Update the `## Sourcing events` block on the Open work page: status
+`decided`. Save the selection record there as `sourcing/<event-id>/decision.txt`.
+Award and regret notes are drafts on request, one per supplier, each through
+the outbound check; a regret note never carries the winning price or name.
+
+### When a quote started it
+
+**When the event was triggered by a quote** (`triggered_by.kind: quote`), the
+awarded bid flows to `quote-build` as a **sourced outside-processing line**.
+Emit it beside the selection record, in the shape the cost buildup reads:
+
+```
+Outside processing — EH-RFQ-0912 line 1, black oxide
+ Supplier: Example Finishing (VEND-5120), approved, single source
+ Unit price: 3.10 USD at 50; 2.20 USD at 200 — bid SRC-2026-10-14-PN-4471-B-BO/VEND-5120/1, received 2026-10-22
+ Tooling: none stated as required · Lead time: 5 working days from receipt of parts
+ Valid until: 2026-12-21 · Awarded by Dana Whitfield, 2026-10-27
+```
+
+`quote-build` cites it on the internal sheet and puts its lead time into the
+date check. **The supplier's name and price stay internal**; the customer quote
+carries the finished-part price only.
+
+A bid with no selection record is not a sourced line. If the estimator wants
+it used before the buyer decides, it is cited as *a supplier quote, not
+awarded*.
diff --git a/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/hard-stops.md b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/hard-stops.md
new file mode 100644
index 00000000..9b763f6a
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/hard-stops.md
@@ -0,0 +1,96 @@
+# The two hard stops
+
+Most of this skill assembles a package and reports what is missing. Two
+conditions are different: they **block**, and no amount of user insistence
+converts them into a warning.
+
+---
+
+## 1. Revision mismatch
+
+**The revision in the document library must match the revision on the ERP item
+master. When they disagree, stop.**
+
+This is not a data-quality nicety. **Sending a supplier the wrong revision is
+the classic and expensive error this skill exists to prevent**, and it is
+expensive in a specific way: nothing goes wrong for months. The supplier quotes
+the drawing you sent, wins the business, tools up, and ships parts that are
+correct against the print in their hand and wrong against the one in yours. You
+find out at first article if you are lucky, and at the customer if you are not.
+
+### What to check
+
+| Check | Where |
+|---|---|
+| Revision on the drawing file itself | The title block, not the filename. Filenames lie |
+| Revision recorded in the document library | M365 metadata or the library's own record |
+| Revision on the ERP item master | Where the profile's `### ERP scope` says revision lives: a named field, the item-ID suffix with its pattern, or not in the ERP. **Never inferred**: with no setting, say the ERP's revision location is not set and that the check could not use the ERP |
+| Revision the current demand was ordered against | Open purchase orders and sales orders |
+
+**Read the title block, not the filename.** `4471-B-RevC-final-v2.pdf` tells you
+what somebody typed. The title block tells you what the drawing is.
+
+### What to report
+
+Name both revisions, both sources, and both dates. Do not resolve it — this is
+a controlled-document question with an owner, and that owner is not the skill.
+
+> *"Stopping before assembling the package. The document library holds
+> 4471-B at Rev C, dated 2026-06-11. The NetSuite item master records Rev B, and
+> the open demand on PO-8841 was placed against Rev B. Those cannot both be
+> current. Either the item master was not updated when C released, or C was
+> released and never flowed to purchasing.*
+>
+> *That distinction matters to the quote, because the two revisions differ. I
+> need document control to confirm which revision this sourcing action is
+> against before anything goes to a supplier."*
+
+### The one thing not to do
+
+Do not send both revisions and let the supplier work it out. It looks helpful. It
+produces bids that are not comparable, and it tells the supplier that your
+configuration control is unreliable, which is a bad thing for them to know while
+they are pricing you.
+
+---
+
+## 2. Restricted data
+
+**ITAR, EAR, export-controlled, or otherwise restricted technical data must not
+be assembled into an outbound package without an explicit gate.** This is
+blocking, and it blocks before assembly rather than before sending.
+
+The reason for the ordering: once restricted geometry is collated into a package
+that is one click from an email, the control has already been weakened. Stop at
+the point of gathering.
+
+### How it shows up
+
+- An ITAR or EAR marking in the drawing title block or border
+- A distribution statement, or "export controlled" in a document header
+- A customer program known to be defence, space or controlled — captured in
+ `## Plant context` during `onboarding`
+- A supplier who is not on the plant's cleared list for that program
+
+### What to do
+
+Report it as blocking, name what was found and where, and state the specific
+question that needs answering — usually whether the candidate supplier holds the
+required registration and whether an export authorization covers the disclosure.
+
+**Do not assess eligibility.** Whether a given supplier may receive controlled
+technical data is a compliance determination with a named owner at the plant. The
+skill's job is to notice, stop, and route it there.
+
+---
+
+## Why these two and not the rest
+
+Everything else this skill finds goes on the missing-items list and the user
+decides. These two are different because **both produce a harm that lands
+somewhere other than where the mistake was made** — with a supplier who built to
+the wrong print, or with a compliance exposure the plant carries.
+
+A missing lead-time requirement produces a worse bid, and that is visible
+immediately. These two are not visible until much later, which is exactly why
+they are gates rather than warnings.
diff --git a/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/quality-clauses.md b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/quality-clauses.md
new file mode 100644
index 00000000..d90857ab
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/quality-clauses.md
@@ -0,0 +1,91 @@
+# Quality clauses, and the suppliers who can meet them
+
+---
+
+## The clause list
+
+The requirements a supplier must meet to be allowed to ship this part. They are
+part of the price — a supplier quoting without them is quoting a different job —
+so they belong in the request rather than in the purchase order afterwards.
+
+| Clause | What it obliges the supplier to do |
+|---|---|
+| Certification | Hold a current registration to the applicable standard — ISO 9001 general, AS9100 aerospace, IATF 16949 automotive |
+| Material certification | Supply mill certs traceable to the heat or lot |
+| First article inspection | Submit a full dimensional report on the first production part before running the balance |
+| PPAP submission | The automotive production-part approval package, at a stated submission level. **The level changes the cost materially** |
+| Certificate of conformance | Ship with a signed statement of conformance per lot |
+| Right of access | Permit audits by us, our customer, and the regulator |
+| Change notification | Notify before changing process, sub-tier supplier, or location |
+| Record retention | Hold records for a stated period |
+| Lot traceability | Maintain lot identity through their process, which is what makes ours possible |
+
+**PPAP level is not a detail.** Level 1 is a warrant; level 3 is a full package
+with dimensional results, material and performance test results, process flow,
+PFMEA and control plan. Quoting the wrong level is a real and unpleasant cost
+surprise, and it is one of the more common ones.
+
+---
+
+## Revision matters as much here as on the drawing
+
+**Quote against the clause list at its current revision.** A superseded clause
+list produces bids that are not valid, in exactly the way a superseded drawing
+does — and it is far less likely that anyone notices, because nobody reads the
+clause list twice.
+
+Where the clause set captured during `onboarding` is unavailable, **list the
+clauses found on the current part record and flag the whole set as unverified.**
+Do not assemble a plausible standard list from what plants usually require. A
+confidently wrong clause list is worse than an admitted gap, because the buyer
+will not re-check it.
+
+---
+
+## Clauses vary by customer program — surface it, never merge it
+
+The same part number can carry different requirements depending on which
+customer's program it is being built for. One customer flows down AS9100 plus a
+level-3 PPAP; another takes the same part under ISO 9001 with a certificate of
+conformance.
+
+**Surface the variation and let the buyer decide.** Do not merge the sets.
+
+Merging fails in both directions and both are bad: take the union and you have
+quoted the most expensive requirements onto every unit, so the price is wrong
+and the plant loses money quietly forever. Take the intersection and you have
+sourced parts that cannot legally ship to the stricter customer, which is a
+nonconformance you have manufactured on purpose.
+
+---
+
+## Candidate suppliers
+
+Existing qualified suppliers for this commodity, from the ERP vendor
+records, plus the current supplier for comparison.
+
+Where the trigger was a supplier-caused flag, the implicated supplier stays on
+the list, clearly marked. The buyer needs to see the incumbent's price next to
+the alternates, and sometimes the answer is a corrective action with the
+incumbent rather than a switch.
+
+### Single-source risk is the finding
+
+**If exactly one qualified supplier exists, flag it loudly.** That is usually
+more important than the sourcing package it appeared in.
+
+A part with one qualified supplier means a quality problem at that supplier
+stops production, with no path around it. Sourcing an alternate is insurance,
+and the moment you discover you need it is the moment it is too late to get it —
+which is precisely why Chain 5 exists.
+
+### Requalification lead time is why starting early is the value
+
+An alternate supplier cannot simply start shipping. They have to be qualified:
+sample parts, first article inspection, often a full PPAP, sometimes a site
+audit. **Weeks to months.**
+
+State the expected requalification path with the candidate list, so nobody reads
+an alternate source as available next month. The whole argument for starting a
+sourcing action off the back of a quality finding is that the clock is long and
+it has just started.
diff --git a/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/supplier-loop.md b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/supplier-loop.md
new file mode 100644
index 00000000..c7cb3445
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/supplier-quote-request/reference/supplier-loop.md
@@ -0,0 +1,212 @@
+# The supplier loop — candidates, drafts, and tracking the responses
+
+Steps 8 to 10. What happens between a released package and a pile of bids:
+who gets asked, what each of them is sent, and who has not answered.
+
+**The buyer sends every email and makes every decision.** This skill drafts,
+tracks and compares. It never sends, never awards, and never decides that a
+supplier who went quiet has dropped out.
+
+---
+
+## Step 8 — The candidate list
+
+### Where candidates come from
+
+1. **The `### Approved suppliers` table in `## Plant context`**, captured at
+ `onboarding` (format in `../../onboarding/reference/config-profile.md`,
+ *Approved suppliers*): Commodity | Approved | Notes. Find the commodity
+ this part or process belongs to, and say which row you matched and why —
+ *"black oxide, matched on the drawing note 'black oxide per MIL-DTL-13924'"*.
+ Where two rows could match, ask which one; do not pick.
+2. **ERP vendor records** (NetSuite or Infor M3, or the vendor export), for names, contacts and
+ any vendor whose category fits the commodity. **A vendor found here and not
+ on the approved table is listed as *not confirmed approved*.** The ERP
+ holds vendors, not which are approved for what.
+3. **The incumbent**, for comparison: the supplier on the current purchase
+ orders. Where the trigger is a supplier-caused flag, the implicated supplier
+ is the incumbent; whether to invite them back is the buyer's call, and the
+ list says so rather than deciding.
+
+### The columns
+
+| Supplier | ID | Approval status | Basis | Requalification |
+|---|---|---|---|---|
+| Example Finishing | VEND-5120 | **approved, single source** | Plant context, *Black oxide* row, marked single source | none |
+| Example Plating | VEND-5133 | **not confirmed approved** | NetSuite vendor, category finishing; not on the approved table | first article and a process audit before production |
+| Example Metalworks | VEND-5141 | **not confirmed approved** | Same | Same |
+
+**An approved ID that is not in the vendor records** is listed as *approved in
+Plant context, not found in vendor records* — a name or a contact may be
+missing, and the buyer needs to know before drafting to it.
+
+### Single source
+
+A commodity is single source when its row is marked so, **or when it has
+exactly one approved supplier.** Flag it loudly, first, and count it in code
+from the table rather than reading the note alone. The most serious version:
+the only approved source is the implicated supplier. Say that before the
+package.
+
+Every count on this list — approved, not confirmed approved, single-source
+commodities — goes in the figures block with the table and filter it came
+from.
+
+---
+
+## Step 9 — One draft per supplier
+
+**One email per supplier, addressed to that supplier only.** Never one email
+with every bidder in To or CC: that hands each of them the competition's names.
+The package rides along as the attachment the buyer adds; the email names it
+by title and revision.
+
+Each draft carries: the addressee, the subject with the event reference, the
+package title and drawing revision, the response due date, who to send the bid
+to, the technical contact, and the line that the bid must follow the mandated
+format in the package.
+
+**Emit each draft in the reply, between its own delimiters** — a copy saved
+to a file does not replace it:
+
+```
+=== SUPPLIER EMAIL — SENDABLE — VEND-5133 Example Plating ===
+…
+=== END ===
+```
+
+**Then read each block alone and reject it if it holds** any other supplier's
+name, any unit price, PO number or total from purchase-order history, a target
+price, any rate from an `MFG_*` variable or the plant profile, or anything
+about other bids. Per `../../../shared/secret-config.md`, *The outbound
+document check* — the same check as the package, applied to every email.
+
+### Held drafts are labelled HELD
+
+A draft is **held** when any of these is true for it:
+no contact address on file for that supplier, no response due date in the
+released package, the drawing revision not verified, or the supplier not
+confirmed approved for the process with no requalification decision from the
+buyer. A held draft is emitted the same way, through the same outbound check,
+under `=== SUPPLIER EMAIL — HELD — <supplier> ===`; chase and restatement
+drafts likewise (`SUPPLIER CHASE — HELD`). **HELD is for supplier emails
+only: the RFQ package always stays `=== SUPPLIER RFQ PACKAGE — SENDABLE ===`**,
+since the buyer releases it at its own gate and its missing items are listed
+outside it. **`SENDABLE` on an email is used only when nothing holds the
+draft**; it means ready for the buyer to send, never that
+anything was sent. A missing address is a placeholder,
+`[recipient: not on file]`, never an invented one.
+
+**A condition that holds every draft is stated once**, as a notice
+above the drafts: *"Held, all three drafts: no contact email on file; no
+response date in the package."* Each draft then gets one short status line
+above its block: *"Held: the shared conditions above"*, plus any condition
+that is that supplier's alone (*"and Example Plating is not confirmed approved for
+black oxide"*). A supplier-specific condition sits only beside the drafts it
+affects and never in the shared notice. Moving a condition into the notice
+never makes a draft look cleared: every held draft still says it is held.
+
+### The send gate
+
+The buyer sends. **"Send them out" gets the drafts, and a plain sentence that
+nothing was sent:** *"Here are the three drafts. I haven't sent anything —
+send each from your own mailbox."* No send tool is called, M365 is read-only,
+and the reply never says *sent*, *issued*, *went out* or *delivered* about an
+email the buyer has not told you they sent. Per
+`../../../shared/approval-gates.md`, *Supplier send and selection*.
+
+**A yes covers the drafts shown, to the suppliers shown.** A supplier added
+later gets its own draft, shown before anything about it is recorded.
+
+**Sent is recorded only when the buyer says so** — *"sent to Example Plating and
+Example Finishing this morning"* — with the date they gave and their words. The first
+such date is `rfq_issued_at`, which closes Chain 5's handoff segment.
+
+---
+
+## Step 10 — Tracking responses
+
+### Where the state lives between runs
+
+**In the `## Sourcing events` block on the Open work page, written without a
+gate** (`../../../shared/replies.md`, *The open work*), so a new chat with no
+project finds the event's whole history: who was asked, when the buyer said it
+was sent, who responded, who was chased, the decision. It is the buyer's own
+working record, not plant configuration, so, like the `## Dashboards` line, it
+does not go through `onboarding`'s two-turn approval. One `###` per event,
+replaced in place with `put --block "Sourcing events" --entry <event id>`;
+every other block and file on the page stays as it was.
+
+**Each bid ingested at step 11 is saved on the same page** as
+`sourcing/<event-id>/<supplier-slug>.bid.txt` (the record per
+`../../../shared/contracts/supplier-bid.md`, not the supplier's PDF or email;
+`source_ref` already points back to the original), and the Response cell
+points to that path.
+
+```
+## Sourcing events
+### SRC-2026-10-14-PN-4471-B-BO — black oxide, PN-4471-B Rev 2 (Fairview)
+Trigger: quote EH-RFQ-0912 line 1 | Breaks: 50, 200 each | Due: 2026-10-28 | Status: open
+| Supplier | Approval | Drafted | Sent (per buyer) | Due | Response | Chased |
+|---|---|---|---|---|---|---|
+| VEND-5120 Example Finishing | approved, single source | 2026-10-14 | 2026-10-14 | 2026-10-28 | bid 2026-10-22, sourcing/SRC-2026-10-14-PN-4471-B-BO/example-finishing.bid.txt | - |
+| VEND-5141 Example Metalworks | not confirmed approved | 2026-10-14 | 2026-10-14 | 2026-10-28 | none | - |
+```
+
+**Every run also prints the table in its output**, saved or not. **If the page
+cannot be written this session, say so in one line**: *"Not saved: your Open
+work page couldn't be written ([reason]). Paste this table back next time and
+I'll pick up from it."* Never say the event is being tracked. With no stored block and no pasted table, ask which
+suppliers were sent what and when; never reconstruct a send history.
+
+### Statuses
+
+| Status | Means |
+|---|---|
+| `drafted` | A draft was shown. Not sent, as far as this skill knows |
+| `sent` | The buyer said they sent it, on the date they gave |
+| `responded` | A bid is ingested (step 11), with its source |
+| `declined` | The supplier said, in writing, that they will not bid. Cite it |
+| `no response` | Past the due date with nothing received. **Not declined** |
+| `extended` | The buyer gave this supplier a new due date. Record both dates |
+
+**Days past due are computed in code** from today's date and the due date, and
+go in the figures block. A supplier never moves to `declined` because they went
+quiet, and nothing is inferred from a search that found no reply: with M365
+connected, the inbox may be searched read-only for the event reference, and a
+miss is *no reply found by search*.
+
+### Never close on silence
+
+**The event stays open until the buyer closes it or records a decision.** A
+quiet supplier does not end it, a due date passing does not end it, and most of
+the bids arriving does not end it. The run says how many responded out of how
+many sent, computed, and names who has not.
+
+The comparison may run on the bids in hand. When a supplier has not responded,
+it says so on the comparison — *"2 of 3 bids; Example Metalworks has not responded, 6 days
+past the 28 Oct due date"* — and the decision stays the buyer's, including
+whether to wait.
+
+### Chase drafts
+
+For each supplier past due, draft a chase, for the buyer to send:
+
+```
+=== SUPPLIER CHASE — SENDABLE — VEND-5141 Example Metalworks ===
+…
+=== END ===
+```
+
+It restates the event reference, the package, the original due date and a new
+date the buyer chooses (ask, or leave it as a blank for them to fill). **It says
+nothing about the other bids — not even that there are any: no other
+supplier's name, no price, no count of bids received, no "you are the last to
+respond", no "we will decide with the bids we have", no "this is
+competitive".** The deadline and the package are the only pressure in it. A buyer who asks to tell the
+supplier where a competitor landed gets the draft without it, and one sentence
+why — a competitor's price in a chase is the incumbent's-price leak in another
+envelope. The same outbound check runs on every chase block.
+
+Record the chase as drafted. Record it as chased only when the buyer says they
+sent it.
diff --git a/plugins/claude-for-manufacturing/skills/trade-study-report/SKILL.md b/plugins/claude-for-manufacturing/skills/trade-study-report/SKILL.md
new file mode 100644
index 00000000..4b490d9f
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/trade-study-report/SKILL.md
@@ -0,0 +1,236 @@
+---
+name: trade-study-report
+description: "Turns a filled-in trade study matrix and its analysis results into a scored comparison and a decision memo, with every score cited to its source. Runs the sensitivity analysis every time — where the winner flips, which criterion the decision actually rests on, whether an option never wins under any plausible weighting — because a recommendation with no sensitivity check is a spreadsheet, not a decision. Disqualifies options that violate a hard constraint rather than scoring them low. Consumes design-space-explore's variant manifest when one exists, or a matrix filled in by hand when it doesn't. Use when someone says \"compare these options,\" \"write the trade study,\" \"which design should we pick,\" \"score these against the requirements,\" or \"how sensitive is this decision to the weighting.\""
+compatibility: "Requires none. Reads a trade study matrix and analysis results from Microsoft 365 documents, a variant manifest from design-space-explore when one exists, and the ERP (Oracle NetSuite or Infor M3) for cost when connected. Runs entirely from a filled-in matrix and pasted figures, with no connector and no CAD backend."
+---
+
+# Trade Study Report
+
+A trade study is the formal way an engineering team chooses between design
+options: criteria that matter, weights on how much, options scored against
+each one, a weighted total that ranks them, and a memo that defends the pick
+in review.
+
+**The analysis is the expert work; the memo is assembly.** An engineer runs
+the simulations, then loses a day or more turning results into a document —
+assembling scores, writing up the reasoning, formatting a table, defending
+it the first time someone asks "what if cost mattered more?" This skill does
+the assembly.
+
+**It does not run analysis.** It reads scores that already exist — from
+`design-space-explore`'s variant manifest, from a simulation report, from
+engineering judgment stated plainly as judgment — and turns them into a
+ranked, defensible comparison.
+
+**Quick start**
+
+```
+→ Load the matrix: criteria, weights, options, scores. Weights sum to 100?
+→ Every option scored against every criterion? Report the gap, never impute
+→ Compute weighted totals and rank
+→ Run the sensitivity analysis. Always — never optional
+→ Check constraint compliance separately. A violation disqualifies, never
+ just lowers a score
+→ Write the memo: recommendation, reasoning, what was ruled out, risks
+→ Produce the scored comparison table, reviewable
+```
+
+---
+
+## Inputs
+
+**First, find the plant setup:** from the task's own folder (never `cd` into the plugin), run
+`python3 -I <this skill's folder>/../../shared/scripts/plant_setup.py find`, do its `setup_page_first` step, then read the profile at
+`profile_path` and any rate at `rates_path`, per `../../shared/replies.md`.
+
+| Input | Source | Form |
+|---|---|---|
+| Trade study matrix — criteria, weights, options | M365 (Excel/Word), or defined in conversation | XLSX / DOCX / conversation |
+| Analysis results per option | M365 (simulation reports, test data, spreadsheets) | Documents / CSV |
+| Variant manifest | `design-space-explore` output | `../../shared/contracts/variant-manifest.md` |
+| Requirements and constraints | M365 requirements document | Documents |
+| The plant's trade study memo template | `## Plant context`, captured during `onboarding` | Template |
+| Prior trade studies | M365 | Documents — for format and precedent |
+| Cost data per option | ERP cost: NetSuite standard cost, or Infor M3 last purchase price (`../../shared/erp-connectors.md`); or estimates | Connector / documents |
+
+---
+
+## Workflow
+
+### Step 1 — Load the matrix
+
+Criteria, weights, options, scores. **Validate that weights sum to 100**,
+and that every option is scored against every criterion.
+
+**Report gaps rather than imputing a score.** An unscored cell is a
+finding, not a zero — filling it in with a guess is exactly the failure
+this step exists to prevent. Read `reference/matrix-and-scoring.md`.
+
+**When the options come from a `design-space-explore` manifest, three
+manifest-level signals surface here, before any scoring happens** — per
+`../../shared/contracts/variant-manifest.md`:
+
+- A variant with `status: regeneration_failed` or `status: skipped` is
+ listed as an unevaluated option, excluded from the ranking, and stated
+ as excluded — never scored, never silently dropped from the list.
+- A non-empty `requested_not_driving` means part of the requested design
+ space was never explored. Say so.
+- `variant_count_confirmed: false` means the variant set itself was never
+ confirmed with the engineer before generation. Note that in the report.
+
+### Step 2 — Ingest analysis results
+
+Map each result to its criterion and option, **citing the source document
+for every score.**
+
+Where the source is `design-space-explore`'s variant manifest, read scores
+from each variant's `properties` and `analysis_results` — never re-derive a
+number the manifest already computed, and never re-run an analysis this
+skill doesn't perform.
+
+### Step 3 — Compute weighted totals and rank
+
+Score × weight, summed, per option.
+
+**Criterion direction must be explicit and verified before this step
+runs.** Some criteria are lower-is-better — mass, cost — and some are
+higher-is-better. Getting one backward silently inverts the result, and
+nothing about the arithmetic will look wrong when it happens. Read
+`reference/matrix-and-scoring.md`.
+
+### Step 4 — Run the sensitivity analysis
+
+**Always. Never optional.** Vary the weights across a plausible range and
+report where the winner flips, which criterion the decision actually rests
+on, and which options win under which weighting regimes.
+
+**This is the most valuable part of the skill and the part most often
+skipped.** Weights are subjective — somebody decided cost was 30% and
+weight was 25% — and a recommendation with no sensitivity check hides
+exactly how much that decision mattered. Read
+`reference/sensitivity-analysis.md`.
+
+### Step 5 — Check constraint compliance, separately from scoring
+
+An option that violates a hard requirement is **disqualified, not
+low-scoring.** These are different things, mixing them is a common error,
+and this skill keeps them apart throughout — a disqualified option never
+appears in the ranked comparison, only in its own list with the violated
+requirement named.
+
+### Step 6 — Write the decision memo
+
+Recommendation, reasoning, the sensitivity finding, what was ruled out and
+why, and the residual risks in the recommended option. Read
+`reference/decision-memo.md`.
+
+**In the plant's own memo template where one was captured at `onboarding`.**
+A trade study goes into the design record and gets defended in a review, so it
+has to arrive in the shape that record expects. Fall back to prior trade
+studies for format, then to a neutral structure — and name which was used, so
+nobody mistakes the house shape for their own.
+
+### Step 7 — Produce the scored comparison table
+
+In a reviewable format, per Output below.
+
+---
+
+## Approval gates
+
+**This skill recommends; it does not decide.** The memo is a draft an
+engineer reviews, signs, and defends in the design review — nothing here
+commits the plant to a design choice, the same way `customer-inquiry-intake`
+recommends a bid and `root-cause-capa` ranks candidate causes without
+concluding.
+
+Nothing is written back to any system of record.
+
+---
+
+## Output
+
+**Every document this skill produces is printed in the reply, in full.**
+Saving a copy to a file as well is fine, as Word or Excel per `../../shared/replies.md`, never `.txt`; a file *instead of* the reply is not.
+The person reads the reply, and every delimited block and outbound check lives
+in it — a document only on disk has been neither seen nor checked.
+**A record handed to another skill is saved and summarised, never pasted as
+raw YAML**; memory blocks are written where the plant's memory lives; and the
+name on an approval is asked, never taken from the account. All three per
+`../../shared/replies.md`.
+
+**The scored comparison table** — options × criteria, weighted, ranked,
+with every score cited to its source. **Each cell shows its contribution**
+(normalized score × weight) beside the raw score, so a reader can see where a
+total came from without a calculator, and **the table carries an explicit
+rank column** rather than leaving the order to be inferred from the totals.
+
+**The sensitivity analysis** — flip points, the most decision-sensitive
+criterion, and the regime-by-regime winners.
+
+**The decision memo** — recommendation, reasoning, the sensitivity finding,
+ruled-out options with their cause, and the residual risks in the
+recommended option.
+
+**The constraint compliance summary** — disqualified options listed
+separately from the ranked ones, each with the requirement it violated.
+
+**The memo is a controlled document**: it follows the plant's own trade study
+template, per `../../shared/artifact-style.md`, and is never restyled. Where
+no template is on file, use a plain neutral format and say the template is
+missing. Only a separate internal comparison view, which the team refers back
+to in review, uses the house artifact style.
+
+---
+
+## Edge cases and failure modes
+
+- **Weights don't sum to 100** — report it. Do not normalize silently.
+- **An option is unscored on a criterion** — report the gap. Never impute a
+ score.
+- **Two options are within noise of each other** — say so explicitly rather
+ than presenting a false winner.
+- **Scores are on inconsistent scales** — 1–5 against 1–10 against raw
+ units. Normalize, and show the normalization.
+- **Some criteria are lower-is-better, some higher-is-better** — direction
+ must be explicit per criterion. Getting it wrong silently inverts the
+ result.
+- **No analysis results yet, only the matrix** — produce the scored
+ comparison and clearly mark it as judgment-based, not analysis-based.
+
+---
+
+## Degradation
+
+Runs entirely from a filled-in matrix and pasted figures, with no
+connector and no CAD backend at all.
+
+| Not available | What happens |
+|---|---|
+| A variant manifest from `design-space-explore` | The matrix and its options come from a document or conversation instead. A hand-authored manifest with `cad_backend: none` is a valid, complete input, not a fallback — per `../../shared/contracts/variant-manifest.md` |
+| Analysis results, on every option | The comparison runs on judgment alone and **says so, throughout** — every score reads as judgment-based, never presented as analysis-based |
+| Analysis results, on some options | Score what is analyzed, report the gap per unanalyzed option, and **never impute a score** to fill it in |
+| ERP cost | Price from a supplied estimate or a document, with its source, rather than leaving cost unscored |
+| The plant's memo template | Fall back to prior trade studies for format; failing that, a neutral memo structure — and **say which**, because `onboarding`'s gaps list promises exactly this degradation |
+| Prior trade studies | Use a neutral memo structure and say the plant's own format was not available |
+
+---
+
+## Chain position
+
+**Not part of a named chain.** Consumes from `design-space-explore`
+directly — the same producer-consumer relationship `breakdown-diagnosis`
+has with `daily-production-report` in Chain 4.
+
+**Metric.** Design decisions per quarter; design cycle time.
+
+---
+
+## Reference files
+
+| File | Load when |
+|---|---|
+| `reference/matrix-and-scoring.md` | Steps 1 to 3 — validating the matrix, citing scores, normalization, criterion direction |
+| `reference/sensitivity-analysis.md` | Step 4 — always, before ranking is presented as final |
+| `reference/decision-memo.md` | Steps 5 to 7 — constraint compliance, the memo, the comparison table |
+| `../../shared/contracts/variant-manifest.md` | Step 2 — reading scores from a generated or hand-authored manifest |
diff --git a/plugins/claude-for-manufacturing/skills/trade-study-report/reference/decision-memo.md b/plugins/claude-for-manufacturing/skills/trade-study-report/reference/decision-memo.md
new file mode 100644
index 00000000..bfea5406
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/trade-study-report/reference/decision-memo.md
@@ -0,0 +1,94 @@
+# Constraint compliance, the memo, and the comparison table
+
+---
+
+## Disqualified, not low-scoring
+
+An option that violates a hard requirement — exceeds the envelope, misses
+a mandatory certification, fails a pass/fail load case — is **disqualified,
+not low-scoring.**
+
+Mixing the two is a common error and it fails in a specific, dangerous
+way: a disqualified option folded into the scored ranking can still win on
+weighted total if it scores well enough on everything else, and a reviewer
+skimming the ranking sees a winner rather than a design that legally
+cannot ship.
+
+**Keep the two lists separate throughout:**
+
+- The **ranked comparison** — only options that meet every hard
+ requirement.
+- The **constraint compliance summary** — every disqualified option, with
+ the specific requirement it violated, named plainly. Not folded into the
+ bottom of the ranking as a low score.
+
+> *"Option D is excluded from the ranking: it exceeds the 400mm envelope
+> constraint at 412mm. This is disqualifying, not a scoring penalty — see
+> the constraint compliance summary."*
+
+---
+
+## What the memo contains
+
+The memo is the document that gets read in the review and defended
+afterward. It carries:
+
+| Section | Content |
+|---|---|
+| Recommendation | The option, stated plainly, in the first line |
+| Reasoning | Why — grounded in the scored comparison, not restated from scratch |
+| Sensitivity finding | Stable, or fragile and at what weighting it flips — always present, per `sensitivity-analysis.md` |
+| Ruled-out options | Each one, with its specific cause — disqualified, or never won under any plausible weighting |
+| Residual risks | What the recommended option still carries, even after winning |
+
+### Residual risks are not optional
+
+**Every design has open risk, including the winner.** A memo that
+recommends an option and lists no risks reads as though the analysis
+found none, which is a stronger claim than any real trade study supports.
+Name what's still unresolved — an untested load case, a supplier not yet
+qualified for the material, a tolerance close to demonstrated capability —
+even when none of it changes the recommendation.
+
+---
+
+## Ruled-out options get their cause, not just their absence
+
+A reviewer scanning the memo should be able to tell **why** each
+non-winning option isn't the pick, without re-deriving it from the table:
+
+- Disqualified — name the constraint.
+- Never won under any plausible weighting — say so, per the sensitivity
+ analysis.
+- Won under some weightings but not the stated one — name where it does
+ win, so a reviewer who weights things differently can see it wasn't
+ ignored.
+
+An option that simply disappears from the memo with no stated reason
+invites the review to re-litigate a question this skill already answered.
+
+---
+
+## The comparison table, in a reviewable format
+
+Options as rows, criteria as columns, each cell showing the raw score, the
+normalized score, and — for the winning combination of weights — the
+contribution to the total. The weighted total per option, ranked. Every
+score's source cited per `matrix-and-scoring.md`.
+
+The memo follows the plant's trade study template, a controlled document
+per `../../../shared/artifact-style.md`; with none on file, a plain neutral
+format, and the missing template named. **A separate internal comparison
+view may use the house artifact style**; the memo itself never does. The
+header counts the scores by basis: *"14 analysis, 5 estimate, 6 judgment."*
+
+---
+
+## The bar the memo has to clear
+
+**It should read like something an engineer would put their name on.**
+Not a summary of the arithmetic — a document that states a recommendation,
+defends it with the evidence and the sensitivity finding, names what
+didn't make it and why, and is honest about what's still unresolved. If it
+reads like a printout of the scoring table with a sentence bolted on top,
+it has not done the job this skill exists to do.
diff --git a/plugins/claude-for-manufacturing/skills/trade-study-report/reference/matrix-and-scoring.md b/plugins/claude-for-manufacturing/skills/trade-study-report/reference/matrix-and-scoring.md
new file mode 100644
index 00000000..393edcfa
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/trade-study-report/reference/matrix-and-scoring.md
@@ -0,0 +1,102 @@
+# Loading the matrix, and scoring it honestly
+
+---
+
+## The matrix
+
+Four parts, and the whole skill is built around them:
+
+| Part | What it is |
+|---|---|
+| Criteria | What matters — cost, mass, manufacturability, lead time, stiffness, thermal performance, serviceability |
+| Weights | How much each criterion matters, usually percentages summing to 100 |
+| Options | The candidate designs — often the variants from `design-space-explore` |
+| Scores | Each option rated against each criterion |
+
+---
+
+## Validate before computing anything
+
+**Weights must sum to 100.** Where they don't, **report it and stop — do
+not normalize silently.** A matrix with weights totaling 94 or 108 is
+either a typo or an intentional statement that something was left out, and
+silently rescaling to 100 picks an answer to a question nobody asked. Show
+the total and ask.
+
+**Every option must be scored against every criterion.** Where a cell is
+empty, that is a gap, not a zero. **Report which option, which criterion,
+and never impute a value to fill it in** — a filled-in guess is
+indistinguishable from a real score once it's in the table, and it will be
+weighted and ranked exactly like one.
+
+---
+
+## Cite every score to its source
+
+A score with no citation is an assertion. For each cell:
+
+- **From `design-space-explore`'s variant manifest** — cite the variant ID
+ and which `properties` or `analysis_results` field it came from.
+- **From a simulation report or test data** — cite the document and the
+ specific result within it, the same discipline every other skill in this
+ plugin applies to a derived number.
+- **From engineering judgment** — say so explicitly. A judgment-based score
+ is legitimate input, and it stops being legitimate the moment it's
+ presented as though it came from analysis.
+
+---
+
+## Normalize inconsistent scales, and show the work
+
+Scores rarely arrive on one scale. One criterion might be rated 1–5 by an
+engineer, another measured in raw units from a simulation, a third scored
+1–10 by a different reviewer on a prior study.
+
+**Normalize onto one comparable scale before weighting, and show the
+normalization** — the raw value, the scale it came from, and the
+normalized value side by side. A reviewer checking the math needs to see
+both, or the weighted total is unverifiable even when it's correct.
+
+**The default method for a measured criterion is ratio normalization**:
+lower-is-better scores `best ÷ value`, higher-is-better scores
+`value ÷ best`, so proportions survive. Name the method on the table. **Do not
+use min-max with fewer than about four options**: it turns any difference,
+however small, into 0 against 1, and can flip the ranking on the same data.
+Use another method only where the user asks, and say which.
+
+**Every score carries its basis**, one of three, shown per cell and counted in
+the memo header:
+
+| Basis | What it is | Example |
+|---|---|---|
+| `analysis` | A result from simulation, test or the manifest's `analysis_results` | FEA deflection 0.12 mm |
+| `estimate` | Computed from model values by a stated formula, with its inputs | Stiffness scaled as t³ from `wall_thickness` |
+| `judgment` | A person's rating | Machinability 3 of 5, J. Okafor |
+
+An estimate is neither analysis nor opinion. Label it `estimate`, print the
+formula and inputs beside it, and never let it be read as either.
+
+---
+
+## Criterion direction — get this wrong and everything downstream is wrong
+
+Every criterion is either:
+
+- **Lower is better** — mass, cost, lead time, defect rate
+- **Higher is better** — stiffness, first-pass yield, demonstrated margin
+
+**State the direction explicitly, per criterion, before computing a single
+weighted total.** This is not a formality. A cost criterion scored so that
+a *higher* number wins produces a table that looks completely normal —
+every cell is populated, every total computes, the ranking is internally
+consistent — and it recommends the most expensive option with full
+confidence. Nothing about the arithmetic signals the error; only checking
+the stated direction against what was actually computed catches it.
+
+> *"Mass: lower is better, so a 0.351 kg variant scores higher than a
+> 0.418 kg one on this criterion. Confirmed against the matrix header
+> before computing totals."*
+
+Say it plainly for every criterion, even the obvious ones. The failure mode
+here is not confusion about which direction is correct — it's a scoring
+convention entered backward in a spreadsheet cell and never checked again.
diff --git a/plugins/claude-for-manufacturing/skills/trade-study-report/reference/sensitivity-analysis.md b/plugins/claude-for-manufacturing/skills/trade-study-report/reference/sensitivity-analysis.md
new file mode 100644
index 00000000..d5e235e5
--- /dev/null
+++ b/plugins/claude-for-manufacturing/skills/trade-study-report/reference/sensitivity-analysis.md
@@ -0,0 +1,90 @@
+# The sensitivity analysis — the most valuable part, and the most skipped
+
+**This runs every time. It is never optional**, regardless of how confident
+the ranking looks or how much time is left before the review.
+
+---
+
+## Why weights deserve suspicion
+
+A weighted total looks objective. It is arithmetic on numbers someone
+typed in, and one of the inputs — the weights — is a judgment call dressed
+up as a fact. Somebody in a room decided cost was 30% and weight was 25%,
+and a different reasonable person in the same room might have said 28 and
+27.
+
+**If the ranking only holds at exactly the weights as typed, it isn't a
+finding. It's an artifact of where the sliders happened to sit.** The
+sensitivity analysis is what tells the difference apart.
+
+---
+
+## What to compute
+
+Vary the weights across a plausible range — not the full space of every
+mathematically possible combination, but the range a reasonable reviewer
+would actually consider — and answer four questions:
+
+### 1. Does the winner change?
+
+Recompute the ranking at each weighting in the range. If the same option
+wins throughout, that is a strong, defensible recommendation and the memo
+should say so plainly.
+
+### 2. At what weighting does it flip?
+
+Where the winner does change, **name the specific weighting where it
+flips** — not "the ranking is sensitive to weighting" as a vague caveat,
+but the actual numbers.
+
+> *"Option A wins at the stated weighting — cost 30%, mass 25%. It also
+> wins everywhere cost stays above 27%. Below that, Option B takes it. The
+> two are separated by 0.03 on the weighted total at the stated weighting,
+> which is inside the flip zone, not clear of it."*
+
+That is a materially more useful statement than "Option A wins, 6.8 to
+6.5." The second number tells a reviewer nothing about how much to trust
+the first.
+
+### 3. Which criterion is the decision actually sensitive to?
+
+Some criteria can move a wide range without changing the outcome. One
+often decides everything. **Name it.** A decision that rests entirely on
+the cost weighting is a different conversation from one that rests on
+manufacturability, even if both currently point to the same option.
+
+### 4. Is there an option that never wins under any plausible weighting?
+
+**Say so.** An option that loses across the entire plausible range isn't a
+close alternative — it's not actually in contention, and the memo can
+recommend dropping it from further consideration rather than carrying it
+forward as a hedge.
+
+---
+
+## When two options are within noise
+
+Where the weighted totals sit closer together than the scores' own
+precision justifies — a 6.8 against a 6.7 built from inputs good to one
+decimal place — **say so explicitly rather than presenting a false
+winner.**
+
+> *"Options B and C separate by 0.1 on a scale where the individual scores
+> are only confident to about 0.3. That is not a distinguishable result.
+> The recommendation below is based on [stated reason beyond the score],
+> not on B's marginally higher total."*
+
+A ranked table with two rows that differ inside their own noise floor is
+technically ordered and practically meaningless, and presenting it as a
+clean win is worse than saying it's a toss-up.
+
+---
+
+## Report the finding even when it's boring
+
+A sensitivity analysis that comes back "stable across the whole plausible
+range, no flip found" is not a wasted step. It's the evidence that makes
+the recommendation strong, and it belongs in the memo with the same weight
+as a finding that the decision is fragile. **The absence of sensitivity is
+itself the finding**, and it's the one that lets a reviewer sign off
+without re-running the numbers themselves.